83 lines
2.3 KiB
TypeScript
83 lines
2.3 KiB
TypeScript
import type { FormSubmitEvent } from '@nuxt/ui'
|
|
import { UserRole } from '~/.api-client'
|
|
import type { SignInSchema, SignUpSchema } from '~/types/schemas'
|
|
|
|
export const useUserStore = defineStore('User', () => {
|
|
const { createUser } = useUser()
|
|
const name = ref('')
|
|
const toast = useToast()
|
|
const { client } = useAuth()
|
|
|
|
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)
|
|
useToast().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: () => {
|
|
console.log('Successfully logged in!')
|
|
},
|
|
onError: (ctx) => {
|
|
console.log(ctx.error.message)
|
|
}
|
|
}
|
|
)
|
|
}
|
|
|
|
return { name, signUp, signIn }
|
|
})
|