perf: cache jwt secret as key

This commit is contained in:
Samuel
2023-03-17 17:47:43 +01:00
parent 5b6b97e86c
commit 810f5dd84c
3 changed files with 21 additions and 7 deletions
+13 -4
View File
@@ -18,8 +18,9 @@
import { checkToken, Config, Rights } from "@fosscord/util";
import * as Sentry from "@sentry/node";
import { NextFunction, Request, Response } from "express";
import { NextFunction, Request, Response, Router } from "express";
import { HTTPError } from "lambert-server";
import { createSecretKey, KeyObject } from "crypto";
export const NO_AUTHORIZATION_ROUTES = [
// Authentication routes
@@ -69,6 +70,16 @@ declare global {
}
}
let jwtPublicKey: KeyObject;
// Initialize the jwt secret as a key object so it does not need to be regenerated for each request.
export function initAuthentication(api: Router) {
jwtPublicKey = createSecretKey(
Buffer.from(Config.get().security.jwtSecret),
);
api.use(Authentication);
}
export async function Authentication(
req: Request,
res: Response,
@@ -90,11 +101,9 @@ export async function Authentication(
Sentry.setUser({ id: req.user_id });
try {
const { jwtSecret } = Config.get().security;
const { decoded, user } = await checkToken(
req.headers.authorization,
jwtSecret,
jwtPublicKey,
);
req.token = decoded;