add auth, logout

This commit is contained in:
smanylov
2025-11-28 15:28:15 +07:00
parent 5c1a60645f
commit c4ece25c61
6 changed files with 125 additions and 34 deletions
+57 -7
View File
@@ -1,25 +1,70 @@
'use server'
import { SignupFormSchema, FormState } from '@/app/lib/definitions'
import { createSession, deleteSession } from '@/app/lib/session'
import { SignupFormSchema, loginFormSchema } from '@/app/lib/definitions';
import { createSession, deleteSession, getSessionToken } from '@/app/lib/session';
import { redirect } from 'next/navigation'
export async function logout() {
await deleteSession()
const token = await getSessionToken();
try {
await fetch('http://localhost:8080/api/auth/logout', {
method: 'POST',
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization": `Bearer ${token}`,
}
});
} catch (error) {
throw error;
}
await deleteSession();
redirect('/login');
}
export async function authorization(
state: string | undefined,
formData: FormData,
) {
const validatedFields = loginFormSchema.safeParse({
email: formData.get('email'),
password: formData.get('password'),
})
if (!validatedFields.success) {
return 'error';
}
try {
console.log(formData);
const { email, password } = validatedFields.data;
const response = await fetch('http://localhost:8080/api/auth/login', {
method: 'POST',
body: JSON.stringify({
email: email,
password: password
}),
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
}
});
if (response.ok) {
let parsed = await response.json();
await createSession(parsed.token);
} else {
throw new Error('Something went wrong. from server');
}
} catch (error) {
if (error) {
return 'Something went wrong.';
return 'Something went wrong. from server';
}
throw error;
}
redirect('/pages/dashboard');
}
export async function registration(
@@ -59,8 +104,13 @@ export async function registration(
"Accept": "application/json"
}
});
let parsed = await response.json();
await createSession(parsed.token);
if (response.ok) {
let parsed = await response.json();
await createSession(parsed.token);
} else {
throw new Error('Something went wrong. from server');
}
} catch (error) {
if (error) {
const errors: Record<string, string> = {}