Implement auth as source of truth on server and protect routes. Integrate with portal
This commit is contained in:
@@ -1,15 +1,16 @@
|
||||
import { env } from '$env/dynamic/private';
|
||||
import { redirect, type Handle } from '@sveltejs/kit';
|
||||
import { createHmac } from 'node:crypto';
|
||||
import { jwtVerify } from 'jose';
|
||||
|
||||
export const handle: Handle = async ({ event, resolve }) => {
|
||||
const cookieHash = event.cookies.get("session");
|
||||
const computedHash = createHmac("sha256", env.PORTAL_SECRET)
|
||||
.update("authenticated")
|
||||
.digest("hex");
|
||||
if (event.url.pathname !== "/login" && cookieHash !== computedHash)
|
||||
redirect(307, "/login");
|
||||
if (event.url.pathname !== "/login") {
|
||||
const token = event.cookies.get("auth");
|
||||
const secret = new TextEncoder().encode(env.AUTH_SECRET);
|
||||
const authenticated = token != null && await jwtVerify(token, secret)
|
||||
.then(() => true)
|
||||
.catch(() => false);
|
||||
if (!authenticated) redirect(307, "/login");
|
||||
}
|
||||
|
||||
const response = await resolve(event);
|
||||
return response;
|
||||
return await resolve(event);
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user