From dde23adef52f0ef37fd4eae31d559e111cf9221b Mon Sep 17 00:00:00 2001 From: Nabil Ould Hamou Date: Tue, 3 Dec 2024 19:20:00 +0100 Subject: [PATCH] added userId to locals --- src/hooks.server.ts | 1 + src/routes/+page.server.ts | 11 +++++++++-- src/routes/api/auth/login/+server.ts | 2 +- src/routes/chats/+page.server.ts | 1 + 4 files changed, 12 insertions(+), 3 deletions(-) diff --git a/src/hooks.server.ts b/src/hooks.server.ts index 38762b9..c4a435b 100644 --- a/src/hooks.server.ts +++ b/src/hooks.server.ts @@ -2,6 +2,7 @@ import type { Handle } from '@sveltejs/kit'; export const handle: Handle = async ({ event, resolve }) => { event.locals.token = await event.cookies.get('token'); + event.locals.userId = await event.cookies.get('UID'); return await resolve(event); }; \ No newline at end of file diff --git a/src/routes/+page.server.ts b/src/routes/+page.server.ts index 5f0c7a7..153ebff 100644 --- a/src/routes/+page.server.ts +++ b/src/routes/+page.server.ts @@ -9,7 +9,7 @@ export async function load({locals}) { } export const actions: Actions = { - login: async ({request, fetch, cookies}) => { + login: async ({request, fetch, cookies, locals}) => { const formData = await request.formData(); const response = await fetch('/api/auth/login', { @@ -27,7 +27,14 @@ export const actions: Actions = { maxAge: (60 * 60) * 30, }); - logger.debug("Successfully created a cookie for the user and proceeded with the login.") + cookies.set('UID', data.userId, { + path: '/', + httpOnly: true, + sameSite: 'strict', + maxAge: (60 * 60) * 30, + }); + + logger.debug("Successfully created a cookie for the user and proceeded with the login."); return redirect(302, "/chats"); } else { diff --git a/src/routes/api/auth/login/+server.ts b/src/routes/api/auth/login/+server.ts index 7b49e04..24f9211 100644 --- a/src/routes/api/auth/login/+server.ts +++ b/src/routes/api/auth/login/+server.ts @@ -30,7 +30,7 @@ export async function POST({request}) { // @ts-ignore const token = jwt.sign(user, process.env.JWT_SECRET, { expiresIn: "1h" }); logger.debug(`Generated a JWT token for user ${user.email}.`) - return json({token: token}); + return json({token: token, userId: user.id}); } else { return error(400, {message: "Email ou mot de passe invalide."}); diff --git a/src/routes/chats/+page.server.ts b/src/routes/chats/+page.server.ts index 19dc97b..491e754 100644 --- a/src/routes/chats/+page.server.ts +++ b/src/routes/chats/+page.server.ts @@ -1,4 +1,5 @@ export async function load({ fetch }) { + try { // Appel API ou récupération de données const res = await fetch('/api/channels', {