From 595a9213c199f5bd0274c8dde382845f308e1567 Mon Sep 17 00:00:00 2001 From: Nicolai Ort Date: Fri, 18 Dec 2020 19:42:08 +0100 Subject: [PATCH] Added comments and formatting to the auth checker ref #6 --- src/authchecker.ts | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/src/authchecker.ts b/src/authchecker.ts index b17a803..44cfd36 100644 --- a/src/authchecker.ts +++ b/src/authchecker.ts @@ -7,7 +7,11 @@ import { IllegalJWTError, NoPermissionError, UserNonexistantOrRefreshtokenInvali import { JwtCreator, JwtUser } from './JwtCreator'; import { User } from './models/entities/User'; - +/** + * Handels authorisation verification via jwt's for all api endpoints using the @Authorized decorator. + * @param action Routing-Controllers action object that provides request and response objects among other stuff. + * @param permissions The permissions that the endpoint using @Authorized requires. + */ const authchecker = async (action: Action, permissions: string[] | string) => { let required_permissions = undefined; if (typeof permissions === "string") { @@ -16,18 +20,15 @@ const authchecker = async (action: Action, permissions: string[] | string) => { required_permissions = permissions } - let provided_token = "" + action.request.headers["authorization"]; - try { - provided_token = provided_token.replace("Bearer ", ""); - } - catch { } let jwtPayload = undefined try { + let provided_token = "" + action.request.headers["authorization"].replace("Bearer ", ""); jwtPayload = jwt.verify(provided_token, config.jwt_secret); jwtPayload = jwtPayload["userdetails"]; } catch (error) { jwtPayload = await refresh(action); } + const user = await getConnectionManager().get().getRepository(User).findOne({ id: jwtPayload["id"], refreshTokenCount: jwtPayload["refreshTokenCount"] }, { relations: ['permissions'] }) if (!user) { throw new UserNonexistantOrRefreshtokenInvalidError() } if (!jwtPayload["permissions"]) { throw new NoPermissionError(); } @@ -40,6 +41,10 @@ const authchecker = async (action: Action, permissions: string[] | string) => { return true; } +/** + * Handels soft-refreshing of access-tokens. + * @param action Routing-Controllers action object that provides request and response objects among other stuff. + */ const refresh = async (action: Action) => { let refresh_token = undefined; try {