110 lines
3.1 KiB
TypeScript
110 lines
3.1 KiB
TypeScript
import type { FormSubmitEvent } from '@nuxt/ui'
|
|
import { UserRole } from '~/.api-client'
|
|
import type { SignInSchema, SignUpSchema } from '~/types/schemas'
|
|
import type { RouteLocationRaw } from 'vue-router'
|
|
import { useAuthClient } from '~/composables/auth/useAuthClient'
|
|
import { useAuthState } from '~/composables/auth/useAuthState'
|
|
|
|
export function useAuthActions() {
|
|
const { client } = useAuthClient()
|
|
const { session, user } = useAuthState()
|
|
const { createUser } = useUser()
|
|
const toast = useToast()
|
|
|
|
async function signOut({ redirectTo }: { redirectTo?: RouteLocationRaw } = {}) {
|
|
const res = await client.signOut()
|
|
if (res.error) {
|
|
console.error('Error signing out:', res.error)
|
|
return res
|
|
}
|
|
session.value = null
|
|
user.value = null
|
|
if (redirectTo) {
|
|
await navigateTo(redirectTo, { external: true })
|
|
}
|
|
return res
|
|
}
|
|
|
|
async function signUp(payload: FormSubmitEvent<SignUpSchema>) {
|
|
await client.signUp.email(
|
|
{
|
|
email: payload.data.email,
|
|
password: payload.data.password,
|
|
name: payload.data.name
|
|
},
|
|
{
|
|
onRequest: () => {
|
|
console.log('Sending register request')
|
|
},
|
|
onResponse: () => {
|
|
console.log('Receiving register response')
|
|
},
|
|
onSuccess: async (ctx) => {
|
|
console.log('Successfully registered!')
|
|
|
|
// Create user in backend after successful Better Auth registration
|
|
try {
|
|
console.log('Creating user in backend...', ctx.data)
|
|
await createUser({
|
|
id: ctx.data.user.id,
|
|
name: ctx.data.user.name,
|
|
status: 'ACTIVE',
|
|
role: UserRole.Employee
|
|
})
|
|
console.log('User created in backend successfully')
|
|
} catch (error) {
|
|
console.error('Failed to create user in backend:', error)
|
|
toast.add({
|
|
title: 'Warning',
|
|
description: 'Account created but there was an issue with backend setup. Please contact support.',
|
|
color: 'warning'
|
|
})
|
|
}
|
|
|
|
await navigateTo('/')
|
|
},
|
|
onError: async (ctx) => {
|
|
console.log(ctx.error.message)
|
|
toast.add({
|
|
title: 'Fehler bei der Registrierung',
|
|
description: ctx.error.message,
|
|
color: 'error'
|
|
})
|
|
}
|
|
}
|
|
)
|
|
}
|
|
|
|
async function signIn(payload: FormSubmitEvent<SignInSchema>) {
|
|
await client.signIn.email(
|
|
{
|
|
email: payload.data.email,
|
|
password: payload.data.password
|
|
},
|
|
{
|
|
onRequest: () => {
|
|
console.log('Sending login request')
|
|
},
|
|
onSuccess: async () => {
|
|
console.log('Successfully logged in!')
|
|
await navigateTo('/')
|
|
},
|
|
onError: (ctx) => {
|
|
console.log(ctx.error.message)
|
|
toast.add({
|
|
title: 'Fehler bei der Anmeldung',
|
|
description: ctx.error.message,
|
|
color: 'error'
|
|
})
|
|
}
|
|
}
|
|
)
|
|
}
|
|
|
|
return {
|
|
signOut,
|
|
signUp,
|
|
signIn
|
|
}
|
|
}
|