Skip to content

Commit

Permalink
Refactor hooks for better maintainability
Browse files Browse the repository at this point in the history
  • Loading branch information
nas-tabchiche committed Feb 15, 2024
1 parent 9c4140e commit 0209b58
Showing 1 changed file with 31 additions and 35 deletions.
66 changes: 31 additions & 35 deletions frontend/src/hooks.server.ts
Original file line number Diff line number Diff line change
@@ -1,39 +1,30 @@
import { BASE_API_URL } from '$lib/utils/constants';
import type { User } from '$lib/utils/types';
import { redirect, type Handle, type HandleFetch } from '@sveltejs/kit';
import { redirect, type Handle, type RequestEvent, type HandleFetch } from '@sveltejs/kit';

export const handle: Handle = async ({ event, resolve }) => {
const session = event.cookies.get('sessionid');

let csrfToken = event.cookies.get('csrftoken');
async function ensureCsrfToken(event: RequestEvent): Promise<string> {
let csrfToken = event.cookies.get('csrftoken') || '';
if (!csrfToken) {
csrfToken = await fetch(`${BASE_API_URL}/csrf/`, {
const response = await fetch(`${BASE_API_URL}/csrf/`, {
credentials: 'include',
headers: {
'content-type': 'application/json'
}
})
.then((res) => res.json())
.then((res) => res.csrfToken);
}
event.cookies.set('csrftoken', csrfToken!, {
httpOnly: false,
sameSite: 'lax',
path: '/',
secure: true
});

if (event.locals.user) {
// There is already a logged-in user. Load page as normal.
return await resolve(event);
headers: { 'content-type': 'application/json' }
});
const data = await response.json();
csrfToken = data.csrfToken;
event.cookies.set('csrftoken', csrfToken, {
httpOnly: false,
sameSite: 'lax',
path: '/',
secure: true
});
}
return csrfToken;
}

if (!session) {
// There is no session, so no logged-in user. Load page as normal.
return await resolve(event);
}
async function validateUserSession(event: RequestEvent): Promise<User | null> {
const session = event.cookies.get('sessionid');
if (!session) return null;

// Fetch the user corresponding to the session.
const res = await fetch(`${BASE_API_URL}/iam/current-user/`, {
credentials: 'include',
headers: {
Expand All @@ -43,18 +34,23 @@ export const handle: Handle = async ({ event, resolve }) => {
});

if (!res.ok) {
// The session is invalid. Delete the session cookie and redirect to the login page.
event.cookies.delete('sessionid', {
path: '/',
secure: true,
sameSite: 'lax'
path: '/'
});
redirect(302, `/login?next=${event.url.pathname}`);
}
return res.json();
}

// User exists, set `events.locals.user` and load page.
const response: User = (await res.json()) as User;
event.locals.user = response;
export const handle: Handle = async ({ event, resolve }) => {
await ensureCsrfToken(event);

if (event.locals.user) return await resolve(event);

const user = await validateUserSession(event);
if (user) {
event.locals.user = user;
}

return await resolve(event);
};
Expand Down

0 comments on commit 0209b58

Please sign in to comment.