FEAT: refactor authentication and user decorators + unit tests

This commit is contained in:
Arthur Simas
2022-07-06 11:55:19 -03:00
parent 2c099ba491
commit 64d84f9148
7 changed files with 696 additions and 77 deletions
+20 -50
View File
@@ -11,13 +11,11 @@ import assert from 'assert';
import jwt from 'jsonwebtoken';
import { DadosferaLogger } from 'dadosfera-logs';
import { AuthClientService } from '../clients/auth/client.service';
import { Permission } from './permissions.enum';
import {
AuthenticationFunction,
PERMISSIONS_KEY,
CUSTOM_AUTHENTICATION_FUNCTION_KEY,
MUST_BE_AUTHENTICATED_KEY,
AUTH_FUNCTION_KEY,
} from './authentication.decorator';
import { RequestUser } from './user.decorator';
import ErrorBuilder from '../utils/ErrorBuilder';
import ErrorCodes from '../utils/errorCodes';
@@ -43,7 +41,7 @@ export class AuthenticationGuard
return this.loadDucJWKS();
}
async loadDucJWKS() {
private async loadDucJWKS() {
const { keys } = await this.authClient.getPublicKeys();
keys.forEach((key) => {
@@ -52,57 +50,38 @@ export class AuthenticationGuard
}
canActivate(ctx: ExecutionContext): boolean {
const requiredPermissions = this.reflector.getAllAndOverride<Permission[]>(
PERMISSIONS_KEY,
[ctx.getHandler(), ctx.getClass()],
);
const customAuthenticationFunction =
this.reflector.getAllAndOverride<AuthenticationFunction>(
CUSTOM_AUTHENTICATION_FUNCTION_KEY,
[ctx.getHandler(), ctx.getClass()],
);
const mustBeAuthenticated = this.reflector.getAllAndOverride<boolean>(
MUST_BE_AUTHENTICATED_KEY,
[ctx.getHandler(), ctx.getClass()],
);
const authFunctions = this.reflector.getAllAndMerge<
AuthenticationFunction[]
>(AUTH_FUNCTION_KEY, [ctx.getClass(), ctx.getHandler()]);
const mustBeAuthenticated = authFunctions.length > 0;
const request = ctx.switchToHttp().getRequest();
const accessToken = this.verifyToken(request, mustBeAuthenticated);
const accessToken = this.validateToken(request, mustBeAuthenticated);
if (!mustBeAuthenticated) {
// no need to be authenticated
return true;
}
if (!accessToken) {
// couldn't load valid token
if (!mustBeAuthenticated) {
// no need to be authenticated
return true;
}
throw new ErrorBuilder(ErrorCodes.AUTH.UNAUTHORIZED);
}
if (
typeof customAuthenticationFunction === 'function' &&
!customAuthenticationFunction(request, request.user)
) {
// custom authentication function forbidden this request
throw new ErrorBuilder(ErrorCodes.AUTH.FORBIDDEN);
}
if (
Array.isArray(requiredPermissions) &&
requiredPermissions.length > 0 &&
!this.matchPermissions(requiredPermissions, accessToken.permissions)
) {
// couldn't match permissions
// every authentication function must return true to authenticate
if (!authFunctions.every((func) => func(request, accessToken))) {
throw new ErrorBuilder(ErrorCodes.AUTH.FORBIDDEN);
}
return true;
}
private verifyToken(request, mustBeAuthenticated: boolean) {
private validateToken(
request,
mustBeAuthenticated: boolean,
): RequestUser | false {
const accessToken = request.get('Authorization');
let accessTokenPayload;
let accessTokenPayload: RequestUser;
// If the user isn't authenticated, an error will occurr anywhere here.
// Fancy error avoidance isn't performed by purpose, such as avoiding to access null values.
@@ -154,13 +133,4 @@ export class AuthenticationGuard
return accessTokenPayload;
}
private matchPermissions(
requiredPermissions: Permission[],
userPermissions: number[],
) {
return requiredPermissions.some((permission) =>
userPermissions.includes(permission.seqid),
);
}
}