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

basic RBAC system #5

Merged
merged 3 commits into from
Sep 14, 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
7 changes: 6 additions & 1 deletion api/src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,15 @@ import { ApiConfigModule } from '@api/modules/config/app-config.module';
import { APP_GUARD } from '@nestjs/core';
import { AuthModule } from '@api/modules/auth/auth.module';
import { JwtAuthGuard } from '@api/modules/auth/guards/jwt-auth.guard';
import { RolesGuard } from '@api/modules/auth/guards/roles.guard';

@Module({
imports: [ApiConfigModule, AuthModule],
controllers: [AppController],
providers: [AppService, { provide: APP_GUARD, useClass: JwtAuthGuard }],
providers: [
AppService,
{ provide: APP_GUARD, useClass: JwtAuthGuard },
{ provide: APP_GUARD, useClass: RolesGuard },
],
})
export class AppModule {}
11 changes: 11 additions & 0 deletions api/src/modules/auth/authorisation/roles.enum.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export enum ROLES {
ADMIN = 'admin',
PARTNER = 'partner',
GENERAL_USER = 'general_user',
}

export const ROLES_HIERARCHY = {
[ROLES.ADMIN]: [ROLES.PARTNER, ROLES.GENERAL_USER],
[ROLES.PARTNER]: [ROLES.GENERAL_USER],
[ROLES.GENERAL_USER]: [],
};
6 changes: 6 additions & 0 deletions api/src/modules/auth/decorators/roles.decorator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { SetMetadata } from '@nestjs/common';
import { ROLES } from '@api/modules/auth/authorisation/roles.enum';

export const ROLES_KEY = 'roles';
export const RequiredRoles = (...roles: ROLES[]) =>
SetMetadata(ROLES_KEY, roles);
33 changes: 33 additions & 0 deletions api/src/modules/auth/guards/roles.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import {
ROLES,
ROLES_HIERARCHY,
} from '@api/modules/auth/authorisation/roles.enum';
import { ROLES_KEY } from '@api/modules/auth/decorators/roles.decorator';

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

canActivate(context: ExecutionContext): boolean {
const requiredRoles: ROLES[] = this.reflector.getAllAndOverride<ROLES[]>(
ROLES_KEY,
[context.getHandler(), context.getClass()],
);
if (!requiredRoles) {
return true;
}
const { user } = context.switchToHttp().getRequest();

return this.hasRequiredRole(user.role, requiredRoles);
}

private hasRequiredRole(userRole: ROLES, requiredRoles: ROLES[]): boolean {
return requiredRoles.some(
(requiredRole) =>
userRole === requiredRole ||
ROLES_HIERARCHY[userRole]?.includes(requiredRole),
);
}
}
26 changes: 26 additions & 0 deletions api/src/modules/users/users.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { Controller, Get } from '@nestjs/common';
import { RequiredRoles } from '@api/modules/auth/decorators/roles.decorator';
import { ROLES } from '@api/modules/auth/authorisation/roles.enum';

@Controller('users')
export class UsersController {
// TODO: All of these endpoints are fake, only to test the role guard

@RequiredRoles(ROLES.ADMIN)
@Get('admin')
async createUserAsAdmin() {
return [ROLES.ADMIN];
}

@RequiredRoles(ROLES.PARTNER)
@Get('partner')
async createUserAsPartner() {
return [ROLES.PARTNER, ROLES.ADMIN];
}

@RequiredRoles(ROLES.GENERAL_USER)
@Get('user')
async createUserAsUser() {
return [ROLES.GENERAL_USER, ROLES.PARTNER, ROLES.ADMIN];
}
}
2 changes: 2 additions & 0 deletions api/src/modules/users/users.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@ import { Module } from '@nestjs/common';
import { UsersService } from './users.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import { User } from '@shared/entities/users/user.entity';
import { UsersController } from '@api/modules/users/users.controller';

@Module({
imports: [TypeOrmModule.forFeature([User])],
providers: [UsersService],
exports: [UsersService],
controllers: [UsersController],
})
export class UsersModule {}
File renamed without changes.
130 changes: 130 additions & 0 deletions api/test/auth/authorization.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
import { ROLES } from '@api/modules/auth/authorisation/roles.enum';
import { TestManager } from '../utils/test-manager';
import { User } from '@shared/entities/users/user.entity';

describe('Authorization', () => {
let testManager: TestManager;

beforeAll(async () => {
testManager = await TestManager.createTestManager();
});

afterEach(async () => {
await testManager.clearDatabase();
});

afterAll(async () => {
await testManager.close();
});

test('a user should have a default general user role when signing up', async () => {
await testManager
.request()
.post('/authentication/signup')
.send({ email: '[email protected]', password: '123456' });

const user = await testManager
.getDataSource()
.getRepository(User)
.findOne({ where: { email: '[email protected]' } });

expect(user.role).toEqual(ROLES.GENERAL_USER);
});

describe('ROLE TEST ENDPOINTS, REMOVE!', () => {
test('when role required is GENERAL_USER, all roles should have access', async () => {
const roles = [ROLES.GENERAL_USER, ROLES.PARTNER, ROLES.ADMIN];

for (const role of roles) {
const user = await testManager
.mocks()
.createUser({ role, email: `${role}@email.com` });
const { jwtToken } = await testManager.logUserIn(user);

const response = await testManager
.request()
.get('/users/user')
.set('Authorization', `Bearer ${jwtToken}`);

expect(response.status).toBe(200);
expect(response.body).toEqual(
expect.arrayContaining([
ROLES.GENERAL_USER,
ROLES.PARTNER,
ROLES.ADMIN,
]),
);
}
});

test('when role required is PARTNER, only PARTNER and ADMIN roles should have access', async () => {
const allowedRoles = [ROLES.PARTNER, ROLES.ADMIN];
const deniedRoles = [ROLES.GENERAL_USER];

for (const role of allowedRoles) {
const user = await testManager
.mocks()
.createUser({ role, email: `${role}@email.com` });
const { jwtToken } = await testManager.logUserIn(user);

const response = await testManager
.request()
.get('/users/partner')
.set('Authorization', `Bearer ${jwtToken}`);

expect(response.status).toBe(200);
expect(response.body).toEqual(
expect.arrayContaining([ROLES.PARTNER, ROLES.ADMIN]),
);
}

for (const role of deniedRoles) {
const user = await testManager
.mocks()
.createUser({ role, email: `${role}@email.com` });
const { jwtToken } = await testManager.logUserIn(user);

const response = await testManager
.request()
.get('/users/partner')
.set('Authorization', `Bearer ${jwtToken}`);

expect(response.status).toBe(403);
}
});

test('when role required is ADMIN, only ADMIN role should have access', async () => {
const allowedRoles = [ROLES.ADMIN];
const deniedRoles = [ROLES.GENERAL_USER, ROLES.PARTNER];

for (const role of allowedRoles) {
const user = await testManager
.mocks()
.createUser({ role, email: `${role}@email.com` });
const { jwtToken } = await testManager.logUserIn(user);

const response = await testManager
.request()
.get('/users/admin')
.set('Authorization', `Bearer ${jwtToken}`);

expect(response.status).toBe(200);
expect(response.body).toEqual([ROLES.ADMIN]);
}

for (const role of deniedRoles) {
const user = await testManager
.mocks()
.createUser({ role, email: `${role}@email.com` });
const { jwtToken } = await testManager.logUserIn(user);

const response = await testManager
.request()
.get('/users/admin')
.set('Authorization', `Bearer ${jwtToken}`);

expect(response.status).toBe(403);
}
});
});
});
2 changes: 1 addition & 1 deletion api/test/utils/test-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ export class TestManager {

mocks() {
return {
createUser: (additionalData: Partial<User>) =>
createUser: (additionalData?: Partial<User>) =>
createUser(this.getDataSource(), additionalData),
};
}
Expand Down
10 changes: 9 additions & 1 deletion shared/entities/users/user.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ import {
Column,
CreateDateColumn,
Entity,
OneToMany,
PrimaryGeneratedColumn,
} from "typeorm";
import { Exclude } from "class-transformer";
import { ROLES } from "@api/modules/auth/authorisation/roles.enum";

@Entity({ name: "users" })
export class User {
Expand All @@ -19,6 +19,14 @@ export class User {
@Exclude()
password: string;

@Column({
type: "enum",
default: ROLES.GENERAL_USER,
enum: ROLES,
enumName: "user_roles",
})
role: ROLES;

@CreateDateColumn({ name: "created_at" })
createdAt: Date;
}
Loading