Initial
This commit is contained in:
25
utilities/guard.ts
Normal file
25
utilities/guard.ts
Normal 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})
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user