93 lines
2.3 KiB
TypeScript
93 lines
2.3 KiB
TypeScript
import { dev } from "$app/environment";
|
|
import { API_URL } from "$env/static/private";
|
|
|
|
import type { Actions, PageServerLoad } from "./$types";
|
|
|
|
import { redirect } from "@sveltejs/kit";
|
|
|
|
import { fail, setError, superValidate } from "sveltekit-superforms";
|
|
import { zod } from "sveltekit-superforms/adapters";
|
|
|
|
import { COOKIES } from "$lib/constants";
|
|
|
|
import { formConfirmationSchema, formSchema } from "./schema";
|
|
|
|
export const load: PageServerLoad = async ({ locals }) => {
|
|
if (locals.user) {
|
|
redirect(302, "/");
|
|
}
|
|
|
|
return {
|
|
title: 'Réinitialisation du mot de passe',
|
|
|
|
form: await superValidate(zod(formSchema)),
|
|
formConfirmation: await superValidate(zod(formConfirmationSchema))
|
|
}
|
|
};
|
|
|
|
export const actions: Actions = {
|
|
request: async ({ request, fetch }) => {
|
|
const form = await superValidate(request, zod(formSchema));
|
|
|
|
if (!form.valid) {
|
|
return fail(400, { form });
|
|
}
|
|
|
|
const res = await fetch(API_URL + '/user/fpw', {
|
|
method: 'POST',
|
|
body: JSON.stringify({
|
|
email: form.data.email
|
|
})
|
|
});
|
|
|
|
if (!res.ok) {
|
|
return setError(form, 'email', "Une erreur s'est produite ou l'email n'existe pas");
|
|
}
|
|
|
|
return {
|
|
form
|
|
}
|
|
},
|
|
confirmation: async ({ request, cookies, fetch, url: { searchParams } }) => {
|
|
const form = await superValidate(request, zod(formConfirmationSchema));
|
|
|
|
if (!form.valid) {
|
|
return fail(400, { form });
|
|
}
|
|
|
|
const res = await fetch(`${API_URL}/user/fpw`, {
|
|
method: 'POST',
|
|
body: JSON.stringify({
|
|
email: form.data.email,
|
|
password: form.data.password,
|
|
code: form.data.code
|
|
})
|
|
});
|
|
|
|
if (!res.ok) {
|
|
if (res.status === 400) {
|
|
return setError(form, 'code', "Le code de confirmation est incorrect");
|
|
}
|
|
|
|
return setError(form, 'code', "Une erreur est survenue, veuillez réessayer plus tard");
|
|
}
|
|
|
|
const token = res.headers.get('Authorization')?.split('Bearer ').pop();
|
|
|
|
if (!token) {
|
|
return setError(form, 'code', "Une erreur est survenue, veuillez réessayer plus tard");
|
|
}
|
|
|
|
cookies.set(COOKIES.SESSION, token, {
|
|
path: '/',
|
|
secure: !dev,
|
|
sameSite: 'strict'
|
|
});
|
|
|
|
const redirectTo = searchParams.get('redirectTo');
|
|
|
|
if (redirectTo) redirect(302, `/${redirectTo.slice(1)}`);
|
|
|
|
redirect(302, '/');
|
|
}
|
|
};
|