Files
no-copy-frontend/src/app/actions/auth.ts
T

74 lines
1.7 KiB
TypeScript
Raw Normal View History

2025-11-27 21:33:53 +07:00
'use server'
import { SignupFormSchema, FormState } from '@/app/lib/definitions'
import { createSession, deleteSession } from '@/app/lib/session'
import { redirect } from 'next/navigation'
export async function logout() {
await deleteSession()
}
export async function authorization(
state: string | undefined,
formData: FormData,
) {
try {
console.log(formData);
} catch (error) {
if (error) {
return 'Something went wrong.';
}
throw error;
}
}
export async function registration(
2025-11-28 12:38:14 +07:00
state: Record<string, string> | undefined,
2025-11-27 21:33:53 +07:00
formData: FormData,
) {
const validatedFields = SignupFormSchema.safeParse({
2025-11-28 12:38:14 +07:00
full_name: formData.get('full_name'),
2025-11-27 21:33:53 +07:00
email: formData.get('email'),
password: formData.get('password'),
2025-11-28 12:38:14 +07:00
confirm_password: formData.get('confirm_password'),
2025-11-27 21:33:53 +07:00
})
if (!validatedFields.success) {
2025-11-28 12:38:14 +07:00
const errors: Record<string, string> = {}
JSON.parse(validatedFields.error.message).forEach((obj: {
message: string,
path: string
}) => {
if (errors[obj.path[0]]) {
errors[obj.path[0]] = `${errors[obj.path[0]]} ${obj.message}`;
} else {
errors[obj.path[0]] = obj.message;
}
});
return errors;
2025-11-27 21:33:53 +07:00
}
try {
2025-11-28 12:38:14 +07:00
const { full_name, email, password } = validatedFields.data;
2025-11-27 21:33:53 +07:00
const response = await fetch('http://localhost:8080/api/auth/register', {
method: 'POST',
2025-11-28 12:38:14 +07:00
body: JSON.stringify({ fullName: full_name, email, password }),
2025-11-27 21:33:53 +07:00
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
}
});
let parsed = await response.json();
await createSession(parsed.token);
} catch (error) {
if (error) {
2025-11-28 12:38:14 +07:00
const errors: Record<string, string> = {}
errors['server'] = 'Something went wrong. from server'
return errors;
2025-11-27 21:33:53 +07:00
}
throw error;
}
redirect('/pages/dashboard');
}