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
+38 -14
View File
@@ -1,28 +1,52 @@
import { SetMetadata, applyDecorators } from '@nestjs/common';
import { Request } from 'express';
import { CustomDecorator } from '@nestjs/common';
import { Permission } from './permissions.enum';
import { RequestUser } from './user.decorator';
export const PERMISSIONS_KEY = '__PERMISSIONS__';
export const MUST_BE_AUTHENTICATED_KEY = '__MUST_BE_AUTHENTICATED__';
export const CUSTOM_AUTHENTICATION_FUNCTION_KEY =
'__CUSTOM_AUTHENTICATION_FUNCTION__';
export const AUTH_FUNCTION_KEY = '__AUTH_FUNCTION__';
export type AuthenticationFunction = (req: Request, user: any) => boolean;
export function RequirePermissions(...permissions: Permission[]) {
return applyDecorators(
SetMetadata(PERMISSIONS_KEY, permissions),
SetMetadata(MUST_BE_AUTHENTICATED_KEY, true),
// implementation copied from SetMetadata, but tweaked to get existing values
// of the metadataKey and accumulate it with the new metadataValue
function SetMultipleMetadata(metadataKey, metadataValue): CustomDecorator {
const decoratorFactory = (target, key, descriptor) => {
// .start: tweak
// descriptor?.value = function decorator; target = class decorator
const accumulatedVal =
Reflect.getMetadata(metadataKey, descriptor?.value ?? target) ?? [];
accumulatedVal.push(metadataValue);
// .end: tweak
if (descriptor) {
Reflect.defineMetadata(metadataKey, accumulatedVal, descriptor.value);
return descriptor;
}
Reflect.defineMetadata(metadataKey, accumulatedVal, target);
return target;
};
decoratorFactory.KEY = metadataKey;
return decoratorFactory as any;
}
export function RequireAllPermissions(...permissions: Permission[]) {
return SetMultipleMetadata(AUTH_FUNCTION_KEY, (req, user: RequestUser) =>
permissions.every(({ seqid }) => user.permissions.includes(seqid)),
);
}
export function RequireSomePermission(...permissions: Permission[]) {
return SetMultipleMetadata(AUTH_FUNCTION_KEY, (req, user: RequestUser) =>
permissions.some(({ seqid }) => user.permissions.includes(seqid)),
);
}
export function AuthenticateCondition(func: AuthenticationFunction) {
return applyDecorators(
SetMetadata(CUSTOM_AUTHENTICATION_FUNCTION_KEY, func),
SetMetadata(MUST_BE_AUTHENTICATED_KEY, true),
);
return SetMultipleMetadata(AUTH_FUNCTION_KEY, func);
}
export function Authenticated() {
return SetMetadata(MUST_BE_AUTHENTICATED_KEY, true);
return SetMultipleMetadata(AUTH_FUNCTION_KEY, () => true);
}