|
| 1 | +'use server'; |
| 2 | + |
| 3 | +import { z } from 'zod'; |
| 4 | + |
| 5 | +import { createUser, getUser } from '@/lib/db/queries'; |
| 6 | + |
| 7 | +import { signIn } from './auth'; |
| 8 | + |
| 9 | +const authFormSchema = z.object({ |
| 10 | + email: z.string().email(), |
| 11 | + password: z.string().min(6), |
| 12 | +}); |
| 13 | + |
| 14 | +export interface LoginActionState { |
| 15 | + status: 'idle' | 'in_progress' | 'success' | 'failed' | 'invalid_data'; |
| 16 | +} |
| 17 | + |
| 18 | +export const login = async ( |
| 19 | + _: LoginActionState, |
| 20 | + formData: FormData, |
| 21 | +): Promise<LoginActionState> => { |
| 22 | + try { |
| 23 | + const validatedData = authFormSchema.parse({ |
| 24 | + email: formData.get('email'), |
| 25 | + password: formData.get('password'), |
| 26 | + }); |
| 27 | + |
| 28 | + await signIn('credentials', { |
| 29 | + email: validatedData.email, |
| 30 | + password: validatedData.password, |
| 31 | + redirect: false, |
| 32 | + }); |
| 33 | + |
| 34 | + return { status: 'success' }; |
| 35 | + } catch (error) { |
| 36 | + if (error instanceof z.ZodError) { |
| 37 | + return { status: 'invalid_data' }; |
| 38 | + } |
| 39 | + |
| 40 | + return { status: 'failed' }; |
| 41 | + } |
| 42 | +}; |
| 43 | + |
| 44 | +export interface RegisterActionState { |
| 45 | + status: |
| 46 | + | 'idle' |
| 47 | + | 'in_progress' |
| 48 | + | 'success' |
| 49 | + | 'failed' |
| 50 | + | 'user_exists' |
| 51 | + | 'invalid_data'; |
| 52 | +} |
| 53 | + |
| 54 | +export const register = async ( |
| 55 | + _: RegisterActionState, |
| 56 | + formData: FormData, |
| 57 | +): Promise<RegisterActionState> => { |
| 58 | + try { |
| 59 | + const validatedData = authFormSchema.parse({ |
| 60 | + email: formData.get('email'), |
| 61 | + password: formData.get('password'), |
| 62 | + }); |
| 63 | + |
| 64 | + const [user] = await getUser(validatedData.email); |
| 65 | + |
| 66 | + if (user) { |
| 67 | + return { status: 'user_exists' } as RegisterActionState; |
| 68 | + } |
| 69 | + await createUser(validatedData.email, validatedData.password); |
| 70 | + await signIn('credentials', { |
| 71 | + email: validatedData.email, |
| 72 | + password: validatedData.password, |
| 73 | + redirect: false, |
| 74 | + }); |
| 75 | + |
| 76 | + return { status: 'success' }; |
| 77 | + } catch (error) { |
| 78 | + if (error instanceof z.ZodError) { |
| 79 | + return { status: 'invalid_data' }; |
| 80 | + } |
| 81 | + |
| 82 | + return { status: 'failed' }; |
| 83 | + } |
| 84 | +}; |
0 commit comments