Minor tidy up

This commit is contained in:
jd
2026-02-13 22:12:02 +00:00
parent 387a9a36f3
commit eddba49893
5 changed files with 12 additions and 12 deletions

View File

@@ -1,6 +1,8 @@
import {BunRequest as Request} from 'bun';
import jwt from 'jsonwebtoken';
import {Claims} from "../orm/orm.ts";
import {ErrorResponse} from "./responseHelper";
import {UnauthorizedError} from "./errors";
import {Claims} from "../orm/claims";
export function guardRedirect(method: Function, redirectMethod: Function, guardedClaims: string[] | undefined = undefined) {
try {
@@ -10,18 +12,17 @@ export function guardRedirect(method: Function, redirectMethod: Function, guarde
}
}
export function guard(method: Function, guardedClaims: string[] | undefined = undefined):(r:Request)=>Promise<Response> {
export function guard(method: Function, guardedClaims: string[] | undefined = undefined): (r: Request) => Promise<Response> {
return async (request: Request): Promise<Response> => {
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;
console.log('Claims?', guardedClaims !== undefined, !userClaims.claims.some(x => guardedClaims?.includes(x)))
if (guardedClaims !== undefined && !userClaims.claims.some(x => guardedClaims.includes(x))) {
throw new Error('Unauthorized');
if (guardedClaims !== undefined && !userClaims.claims.some((x: string): boolean => guardedClaims.includes(x))) {
throw new UnauthorizedError('Unauthorized');
}
return method(await unwrap(request, userClaims));
} catch (e) {
return Response.json({message: 'Authentication failed.'}, {status: 401})
} catch (error: any) {
return new ErrorResponse(error as Error);
}
}
}
@@ -49,7 +50,7 @@ export async function unwrap(request: Request, claims: Claims | null = null) {
})
}
export function unwrapMethod(methodToUnwrap:((r:UnwrappedRequest)=>Response)|((r:UnwrappedRequest)=>Promise<Response>)):(r:Request)=>Promise<Response> {
export function unwrapMethod(methodToUnwrap: ((r: UnwrappedRequest) => Response) | ((r: UnwrappedRequest) => Promise<Response>)): (r: Request) => Promise<Response> {
return async (request: Request) => {
const unwrappedRequest = await unwrap(request);
return await methodToUnwrap(unwrappedRequest);