This commit is contained in:
jd
2026-02-13 00:07:19 +00:00
commit eca7405974
11 changed files with 300 additions and 0 deletions

25
utilities/guard.ts Normal file
View File

@@ -0,0 +1,25 @@
import jwt from 'jsonwebtoken';
import {Claims} from "./orm";
export function guardRedirect(method: Function, redirectMethod: Function, guardedClaims: string[] | undefined = undefined) {
try {
return guard(method, guardedClaims);
} catch (e) {
return redirectMethod();
}
}
export function guard(method: Function, guardedClaims: string[] | undefined = undefined) {
return (request: Request): any => {
const authHeader: string | null = request.headers.get('Authorization')?.replace(/^Bearer /, '') as string ?? null;
try {
const userClaims: Claims = jwt.verify(authHeader as string, process.env.JWT_SECRET_KEY as string) as Claims;
if (guardedClaims !== undefined && !userClaims.claims.some(x => guardedClaims.includes(x))) {
throw new Error('Unauthorized');
}
return method(request, userClaims);
} catch (e) {
return Response.json({message: 'Authentication failed.'}, {status: 401})
}
}
}