Skip to content

Commit

Permalink
update the authorization technique to check if user role matches ite …
Browse files Browse the repository at this point in the history
…priority (#488)

Co-authored-by: Olasunkanmi Oyinlola <olasunkanmioyinlola@Olasunkanmis-Mac-mini.local>
  • Loading branch information
olasunkanmi-SE and Olasunkanmi Oyinlola committed Feb 15, 2024
1 parent 7a0a799 commit e5c2e4d
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 8 deletions.
6 changes: 4 additions & 2 deletions backend/src/application/constants/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,15 @@ export const tokenExpiresIn = 3600000;
export enum Role {
ADMIN = 'ADMIN',
USER = 'USER',
GUEST = 'CLIENT',
CLIENT = 'CLIENT',
SUPERADMIN = 'SUPERADMIN',
}

export const RoleOrder: Record<Role, number> = {
[Role.GUEST]: 1,
[Role.CLIENT]: 1,
[Role.USER]: 2,
[Role.ADMIN]: 3,
[Role.SUPERADMIN]: 4,
};

export const ROLE_KEY = 'role';
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';
import { BaseDocument } from '../../../database';
import { ISingleClientData } from '../models/singleclient-model.interface';
import { SingleClientStatus } from '../../../../application/constants/constants';
import { Role, SingleClientStatus } from '../../../../application/constants/constants';

export type SingleClientDocument = SingleClientDataModel & Document;

Expand All @@ -29,7 +29,7 @@ export class SingleClientDataModel extends BaseDocument implements ISingleClient
@Prop({ type: String, required: true })
passwordHash: string;

@Prop({ type: String, default: 'admin' })
@Prop({ type: String, enum: Object.values(Role), default: Role.USER })
role: string;

@Prop({ type: Boolean, default: false })
Expand Down
13 changes: 9 additions & 4 deletions backend/src/shared/services/access_control.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,19 @@ export class AccessControlService implements IAccessControlService {
}

public isAuthorized({ currentRole, requiredRole }: IIsAuthorizedProps): boolean {
let authorized = false;
let isAuthorized = false;
for (const hierarchy of this.hierarchies) {
const priority = hierarchy.get(currentRole);
const requirePriority = hierarchy.get(requiredRole);
if (priority && requirePriority && priority >= requirePriority) {
authorized = true;
if (priority && requirePriority) {
if (priority >= requirePriority) {
isAuthorized = true;
}
if (priority === requirePriority) {
isAuthorized = true;
}
}
}
return authorized;
return isAuthorized;
}
}

0 comments on commit e5c2e4d

Please sign in to comment.