Files
nuxtfiber/app/composables/useLogin.ts
Beyhan Oğur 7b2b27a42c first commit
2026-04-26 22:18:17 +03:00

81 lines
2.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import Swal from 'sweetalert2'
import { loginSchema, getFirstZodError, getFieldErrors } from '~~/lib/validations/auth'
export function useLogin () {
const { signIn } = useAuth()
const router = useRouter()
const route = useRoute()
const email = ref('')
const password = ref('')
const turnstileToken = ref<string | null>(null)
const turnstileRef = ref<{ reset: () => void } | null>(null)
const fieldError = ref<Record<string, string>>({})
const loading = ref(false)
const callbackUrl = computed(() => (route.query.callbackUrl as string) || '/')
async function onSubmit () {
fieldError.value = {}
const parsed = loginSchema.safeParse({ email: email.value, password: password.value })
if (!parsed.success) {
fieldError.value = getFieldErrors(parsed.error)
await Swal.fire({ icon: 'error', title: 'Doğrulama hatası', text: getFirstZodError(parsed.error) })
return
}
if (!turnstileToken.value) {
await Swal.fire({ icon: 'warning', title: 'Güvenlik doğrulaması', text: 'Lütfen güvenlik kutusunu işaretleyin.' })
return
}
loading.value = true
try {
const result = await signIn('credentials', {
email: email.value,
password: password.value,
turnstile_token: turnstileToken.value,
callbackUrl: callbackUrl.value,
})
if (result?.error) {
const msg = result.error === 'CredentialsSignin' ? 'E-posta veya şifre hatalı.' : String(result.error)
await Swal.fire({ icon: 'error', title: 'Giriş başarısız', text: msg })
turnstileRef.value?.reset()
turnstileToken.value = null
return
}
await Swal.fire({ icon: 'success', title: 'Giriş başarılı', timer: 1500, showConfirmButton: false })
if (result?.url) await router.push(result.url)
} catch (e: unknown) {
const msg = e instanceof Error ? e.message : 'Giriş yapılamadı.'
await Swal.fire({ icon: 'error', title: 'Hata', text: msg })
turnstileRef.value?.reset()
turnstileToken.value = null
} finally {
loading.value = false
}
}
async function signInWith (provider: 'github' | 'google') {
loading.value = true
try {
await signIn(provider, { callbackUrl: callbackUrl.value })
} catch (e: unknown) {
const msg = e instanceof Error ? e.message : 'Giriş yapılamadı.'
await Swal.fire({ icon: 'error', title: 'Hata', text: msg })
} finally {
loading.value = false
}
}
return {
email,
password,
turnstileToken,
turnstileRef,
fieldError,
loading,
callbackUrl,
onSubmit,
signInWith,
}
}