|
| 1 | +"use server" |
| 2 | +import { getSessionLogin, postSignupUser } from '@/api/gateway'; |
| 3 | +// defines the server-sided login action. |
| 4 | +import { SignupFormSchema, LoginFormSchema, FormState, isError } from '@/api/structs'; |
| 5 | +import { createSession } from '@/app/actions/session'; |
| 6 | +import { cookies } from 'next/headers'; |
| 7 | +import { redirect } from 'next/navigation'; |
| 8 | + |
| 9 | +// credit - taken from Next.JS Auth tutorial |
| 10 | +export async function signup(state: FormState, formData: FormData) { |
| 11 | + // Validate form fields |
| 12 | + const validatedFields = SignupFormSchema.safeParse({ |
| 13 | + username: formData.get('username'), |
| 14 | + email: formData.get('email'), |
| 15 | + password: formData.get('password'), |
| 16 | + }); |
| 17 | + |
| 18 | + // If any form fields are invalid, return early |
| 19 | + if (!validatedFields.success) { |
| 20 | + return { |
| 21 | + errors: validatedFields.error.flatten().fieldErrors, |
| 22 | + } |
| 23 | + } |
| 24 | + |
| 25 | + const json = await postSignupUser(validatedFields.data); |
| 26 | + |
| 27 | + if (!isError(json)) { |
| 28 | + // TODO: handle OK |
| 29 | + redirect("/auth/login"); |
| 30 | + } else { |
| 31 | + // TODO: handle failure codes: 400, 409, 500. |
| 32 | + console.log(`${json.status}: ${json.error}`); |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +export async function login(state: FormState, formData: FormData) { |
| 37 | + // Validate form fields |
| 38 | + const validatedFields = LoginFormSchema.safeParse({ |
| 39 | + email: formData.get('email'), |
| 40 | + password: formData.get('password'), |
| 41 | + }); |
| 42 | + |
| 43 | + // If any form fields are invalid, return early |
| 44 | + if (!validatedFields.success) { |
| 45 | + return { |
| 46 | + errors: validatedFields.error.flatten().fieldErrors, |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + const json = await getSessionLogin(validatedFields.data); |
| 51 | + if (!isError(json)) { |
| 52 | + if (cookies().has('session')) { |
| 53 | + console.log(cookies().get('session')); |
| 54 | + console.log("Note a cookie already exists, overriding!"); |
| 55 | + } |
| 56 | + await createSession(json.data.accessToken); |
| 57 | + |
| 58 | + if (cookies().has('session')) { |
| 59 | + console.log(`New cookie: ${cookies().get('session')?.value}`); |
| 60 | + } |
| 61 | + } else { |
| 62 | + console.log(json.error); |
| 63 | + } |
| 64 | +} |
0 commit comments