Added auto database creation based on sql scripts and jwt key cache

This commit is contained in:
fedyna-k
2025-01-16 23:13:58 +01:00
parent 914875a3df
commit 46a417f411
8 changed files with 70 additions and 7 deletions
+24 -3
View File
@@ -1,6 +1,7 @@
import { FreshContext } from "$fresh/server.ts";
import { getCookies } from "$std/http/cookie.ts";
import { isJwtValid } from "@popov/jwt";
import { getJwtPayload, isJwtValid } from "@popov/jwt";
import { LoginJWT } from "$root/routes/login.tsx";
const PUBLIC_ROUTES = [
"/",
@@ -11,6 +12,8 @@ const PUBLIC_ROUTES = [
"/contact",
];
const jwtKeyCache: Record<string, string> = {};
export interface State {
isAuthenticated: boolean;
}
@@ -19,15 +22,33 @@ function isRoutePublic(route: string) {
return PUBLIC_ROUTES.includes(route) || route.match(/\..+$/);
}
export function getKey(user: string): string {
if (!jwtKeyCache[user]) {
const keyBuffer = new Uint8Array(32);
crypto.getRandomValues(keyBuffer);
jwtKeyCache[user] = new TextDecoder().decode(keyBuffer);
}
return jwtKeyCache[user];
}
export const handler = [
async function checkAuthentication(
request: Request,
context: FreshContext<State>,
) {
const cookies = getCookies(request.headers);
if (!cookies["sessionToken"]) {
context.state.isAuthenticated = false;
return await context.next();
}
const content = getJwtPayload(cookies["sessionToken"]) as LoginJWT;
const key = getKey(content.user.uid as string);
context.state.isAuthenticated = await isJwtValid(
cookies["sessionToken"] ?? "",
"NEED TO CHANGE THIS KEY FURTHER IN DEV",
cookies["sessionToken"],
key,
);
return await context.next();
+10 -1
View File
@@ -7,6 +7,7 @@ import {
} from "@melvdouc/xml-parser";
import { createJwt } from "@popov/jwt";
import { setCookie } from "$std/http/cookie.ts";
import { getKey } from "$root/routes/_middleware.ts";
const SERVICE = "https://localhost/login";
const CAS = "https://ident.univ-amu.fr/cas";
@@ -23,6 +24,14 @@ interface CasResponse extends RegularTagNode {
children: [TextNode, CasGroupNode];
}
export interface LoginJWT {
iss: "PolyMPR";
iat: number;
exp: number;
aud: "PolyMPR";
user: Record<string, string | string[]>;
}
function getTag(tag: CasTagNode): [string, string] {
return [
tag.tagName.replace("cas:", ""),
@@ -55,7 +64,7 @@ function createUserJWT(casResponse: CasResponse): Promise<string> {
user: fullUserInfos,
};
const key = "NEED TO CHANGE THIS KEY FURTHER IN DEV";
const key = getKey(fullUserInfos.uid as string);
return createJwt(payload, key);
}