Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BE: Permissions Interface in vehicles #1535

Merged
merged 1 commit into from
Aug 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion vehicles/src/common/decorator/roles.decorator.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import { SetMetadata } from '@nestjs/common';
import { Role } from '../enum/roles.enum';
import { IRole } from '../interface/role.interface';
import { IPermissions } from '../interface/permissions.interface';

export const ROLES_KEY = 'roles';
export const Roles = (...roles: Role[] | IRole[]) =>
// Todo: Change IPermissions array to a single object when removing
// roles.
export const Roles = (...roles: Role[] | IRole[] | IPermissions[]) =>
SetMetadata(ROLES_KEY, roles);
8 changes: 4 additions & 4 deletions vehicles/src/common/guard/roles.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,16 @@ import { IUserJWT } from '../interface/user-jwt.interface';
import { matchRoles } from '../helper/auth.helper';
import { IRole } from '../interface/role.interface';
import { IDP } from '../enum/idp.enum';
import { IPermissions } from '../interface/permissions.interface';

@Injectable()
export class RolesGuard implements CanActivate {
constructor(private reflector: Reflector) {}

canActivate(context: ExecutionContext): boolean {
const roles = this.reflector.getAllAndOverride<Role[] | IRole[]>('roles', [
context.getHandler(),
context.getClass(),
]);
const roles = this.reflector.getAllAndOverride<
Role[] | IRole[] | IPermissions[]
>('roles', [context.getHandler(), context.getClass()]);
// Guard is invoked regardless of the decorator being actively called
if (!roles) {
return true;
Expand Down
60 changes: 53 additions & 7 deletions vehicles/src/common/helper/auth.helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
IDIRUserAuthGroup,
} from '../enum/user-auth-group.enum';
import { IRole } from '../interface/role.interface';
import { IPermissions } from '../interface/permissions.interface';

/**
* Determines the directory type based on the identity provider of the user.
Expand Down Expand Up @@ -39,10 +40,26 @@ export const getDirectory = (user: IUserJWT) => {
* @param {Role[] | IRole[]} obj - The object to be checked.
* @returns {obj is Role[]} True if obj is an array of Role, false otherwise.
*/
function isRoleArray(obj: Role[] | IRole[]): obj is Role[] {
function isRoleArray(obj: Role[] | IRole[] | IPermissions[]): obj is Role[] {
return Array.isArray(obj) && obj.every((item) => typeof item === 'string');
}

/**
* Type guard to check if an input object has the structure of an IPermissions.
*
* @param {IRole | Role[]} permissions - The object to be checked.
* @returns {permissions is IPermissions} True if the object matches the IPermissions structure, false otherwise.
*/
const isIPermissions = (
permissions: IRole | Role[] | IPermissions,
): permissions is IPermissions => {
const { allowedBCeIDRoles, allowedIdirRoles, claims } =
permissions as IPermissions;
return (
Boolean(allowedBCeIDRoles) || Boolean(allowedIdirRoles) || Boolean(claims)
);
};

/**
* Evaluates if a user has at least one of the specified roles, belongs to the specified user authorization group, or meets complex role criteria.
*
Expand All @@ -55,16 +72,41 @@ function isRoleArray(obj: Role[] | IRole[]): obj is Role[] {
* If any role object's criteria are met (considering 'userAuthGroup' if defined), it returns true.
* Throws an error if both 'allOf' and 'oneOf' are defined in a role object.
*
* @param {Role[] | IRole[]} roles - An array of roles or role requirement objects to be matched against the user's roles.
* @param {Role[] | IRole[] | IPermissions} roles - An array of roles or role requirement objects to be matched against the user's roles.
* @param {Role[]} userRoles - An array of roles assigned to the user.
* @param {UserAuthGroup} userAuthGroup - Optional. The user authorization group to which the user belongs.
* @param {UserAuthGroup} userAuthGroup - The user authorization group to which the user belongs.
* @returns {boolean} Returns true if the user meets any of the defined role criteria or belongs to the specified user authorization group; false otherwise.
*/
export const matchRoles = (
roles: Role[] | IRole[],
roles: Role[] | IRole[] | IPermissions[],
userRoles: Role[],
userAuthGroup?: UserAuthGroup,
userAuthGroup: UserAuthGroup,
) => {
if (isIPermissions(roles[0] as IPermissions)) {
const { allowedIdirRoles, allowedBCeIDRoles, claims } =
roles[0] as IPermissions;
// If only claims is specified, return the value of that.
if (claims && !allowedBCeIDRoles && !allowedIdirRoles) {
return claims.some((role) => userRoles.includes(role));
}
let isAllowed: boolean;
const isIdir = userAuthGroup in IDIRUserAuthGroup;
if (isIdir) {
isAllowed = allowedIdirRoles?.includes(
userAuthGroup as IDIRUserAuthGroup,
);
} else {
isAllowed = allowedBCeIDRoles?.includes(
userAuthGroup as ClientUserAuthGroup,
);
}
// If claims is specified alongside the allowed roles, include
// its value in the output.
if (claims) {
isAllowed = isAllowed && claims.some((role) => userRoles.includes(role));
}
return isAllowed;
}
if (isRoleArray(roles)) {
// Scenario: roles is a simple list of Role objects.
// This block checks if any of the roles assigned to the user (userRoles)
Expand All @@ -81,7 +123,7 @@ export const matchRoles = (
// 2. oneOf - at least one of the roles listed must be included in userRoles.
// It returns true if either condition is met for any role object, indicating the user meets the role requirements.
// An error is thrown if 'allOf' and 'oneOf' are both defined, as it's considered an invalid configuration.
return roles.some((roleObject) => {
return (roles as IRole[]).some((roleObject) => {
if (roleObject.allOf?.length && roleObject.oneOf?.length) {
throw new InternalServerErrorException(
'Cannot define both allOf and oneOf at the same time!',
Expand Down Expand Up @@ -185,7 +227,11 @@ export const validateUserCompanyAndRoleContext = (
userCompanies: number[],
currentUser: IUserJWT,
) => {
const rolesExists = matchRoles(roles, currentUser.roles);
const rolesExists = matchRoles(
roles,
currentUser.roles,
currentUser.orbcUserAuthGroup,
);
if (!rolesExists && userGUID) {
throw new ForbiddenException();
}
Expand Down
34 changes: 34 additions & 0 deletions vehicles/src/common/interface/permissions.interface.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { Role } from '../enum/roles.enum';
import {
ClientUserAuthGroup,
IDIRUserAuthGroup,
} from '../enum/user-auth-group.enum';

/**
* The permission configuration for endpoints.
*/
export interface IPermissions {
/**
* The idir auth roles that are allowed to see the component.
*
* If the user has one of the specified auth groups,
* the component will render.
*/
allowedIdirRoles?: readonly IDIRUserAuthGroup[];

/**
* The bceid auth roles that are allowed to see the component.
*
* If the user has one of the specified auth groups,
* the component will render.
*/
allowedBCeIDRoles?: readonly ClientUserAuthGroup[];

/**
* The collection of individual security claims that may be used
* for additional consideration.
*
* If provided, the claim will be additionally checked on.
*/
claims?: readonly Role[];
}
Loading