Add privilege management system with related migrations and guards
- Introduced a new `PrivilegesModule` to manage user privileges and access control. - Added `RequirePrivilege` decorator to enforce privilege checks on controller handlers. - Implemented `PrivilegesGuard` to handle authorization based on user privileges. - Created database migrations for `privileges`, `privilege_keys`, and `privilege_details` tables. - Updated user model to include `is_superadmin` field for enhanced access control. - Added unit tests for the new privileges functionality and guards to ensure correct behavior.
This commit is contained in:
@@ -0,0 +1,304 @@
|
||||
import { INestApplication } from '@nestjs/common';
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { eq } from 'drizzle-orm';
|
||||
import request from 'supertest';
|
||||
import { App } from 'supertest/types';
|
||||
import { AppModule } from '../src/app.module';
|
||||
import { configureApp } from '../src/common/configure-app';
|
||||
import { PRIVILEGE_ACTIONS } from '../src/modules/privileges/privilege-action';
|
||||
import { DRIZZLE, type DrizzleDB } from '../src/database/database.module';
|
||||
import {
|
||||
privilegeDetails,
|
||||
privilegeKeys,
|
||||
privileges,
|
||||
users,
|
||||
} from '../src/database/schema';
|
||||
|
||||
describe('Privileges (e2e)', () => {
|
||||
let app: INestApplication<App>;
|
||||
let db: DrizzleDB;
|
||||
|
||||
const password = 'password123';
|
||||
const adminUsername = `admin_${Date.now()}`;
|
||||
const otherUsername = `other_${Date.now()}`;
|
||||
|
||||
let adminAccessToken: string;
|
||||
let adminUserId: string;
|
||||
let otherAccessToken: string;
|
||||
let otherUserId: string;
|
||||
let adminPrivilegeId: string;
|
||||
|
||||
beforeAll(async () => {
|
||||
const moduleFixture: TestingModule = await Test.createTestingModule({
|
||||
imports: [AppModule],
|
||||
}).compile();
|
||||
|
||||
app = moduleFixture.createNestApplication();
|
||||
configureApp(app, {
|
||||
NODE_ENV: 'test',
|
||||
SWAGGER_ENABLED: 'false',
|
||||
});
|
||||
await app.init();
|
||||
db = app.get(DRIZZLE);
|
||||
|
||||
const adminReg = await request(app.getHttpServer())
|
||||
.post('/auth/register')
|
||||
.send({ username: adminUsername, password })
|
||||
.expect(201);
|
||||
adminAccessToken = (
|
||||
adminReg.body as { accessToken: string }
|
||||
).accessToken;
|
||||
|
||||
const adminMe = await request(app.getHttpServer())
|
||||
.get('/auth/me')
|
||||
.set('Authorization', `Bearer ${adminAccessToken}`)
|
||||
.expect(200);
|
||||
adminUserId = (adminMe.body as { id: string }).id;
|
||||
expect(adminMe.body).toMatchObject({
|
||||
privilege: null,
|
||||
permissions: {},
|
||||
});
|
||||
|
||||
const otherReg = await request(app.getHttpServer())
|
||||
.post('/auth/register')
|
||||
.send({ username: otherUsername, password })
|
||||
.expect(201);
|
||||
otherAccessToken = (
|
||||
otherReg.body as { accessToken: string }
|
||||
).accessToken;
|
||||
const otherMe = await request(app.getHttpServer())
|
||||
.get('/auth/me')
|
||||
.set('Authorization', `Bearer ${otherAccessToken}`)
|
||||
.expect(200);
|
||||
otherUserId = (otherMe.body as { id: string }).id;
|
||||
|
||||
const now = Date.now();
|
||||
const [priv] = await db
|
||||
.insert(privileges)
|
||||
.values({
|
||||
name: 'Administrator',
|
||||
code: `ADMIN_${now}`,
|
||||
status: 'active',
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
createdBy: adminUserId,
|
||||
updatedBy: adminUserId,
|
||||
})
|
||||
.returning();
|
||||
adminPrivilegeId = priv.id;
|
||||
|
||||
const keys = await db.select().from(privilegeKeys);
|
||||
expect(keys.length).toBeGreaterThanOrEqual(2);
|
||||
|
||||
const detailRows = keys.flatMap((key) =>
|
||||
PRIVILEGE_ACTIONS.map((action) => ({
|
||||
privilegeId: adminPrivilegeId,
|
||||
privilegeKeyId: key.id,
|
||||
action,
|
||||
value: true,
|
||||
})),
|
||||
);
|
||||
await db.insert(privilegeDetails).values(detailRows);
|
||||
|
||||
await db
|
||||
.update(users)
|
||||
.set({ privilegeId: adminPrivilegeId, updatedAt: Date.now() })
|
||||
.where(eq(users.id, adminUserId));
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('forbids privileges list without permission', async () => {
|
||||
await request(app.getHttpServer())
|
||||
.get('/privileges')
|
||||
.set('Authorization', `Bearer ${otherAccessToken}`)
|
||||
.expect(403);
|
||||
});
|
||||
|
||||
it('lists privilege keys for admin', async () => {
|
||||
const res = await request(app.getHttpServer())
|
||||
.get('/privilege-keys')
|
||||
.set('Authorization', `Bearer ${adminAccessToken}`)
|
||||
.expect(200);
|
||||
|
||||
expect(res.body.data).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ code: 'PRIVILEGES' }),
|
||||
expect.objectContaining({ code: 'USERS' }),
|
||||
]),
|
||||
);
|
||||
expect(res.body.meta).toMatchObject({
|
||||
totalItems: expect.any(Number),
|
||||
});
|
||||
});
|
||||
|
||||
it('CRUD privileges with details, status, and me permissions', async () => {
|
||||
const keysRes = await request(app.getHttpServer())
|
||||
.get('/privilege-keys?limit=50')
|
||||
.set('Authorization', `Bearer ${adminAccessToken}`)
|
||||
.expect(200);
|
||||
const privilegesKey = (
|
||||
keysRes.body.data as { id: string; code: string }[]
|
||||
).find((k) => k.code === 'PRIVILEGES');
|
||||
expect(privilegesKey).toBeDefined();
|
||||
|
||||
const created = await request(app.getHttpServer())
|
||||
.post('/privileges')
|
||||
.set('Authorization', `Bearer ${adminAccessToken}`)
|
||||
.send({
|
||||
name: 'Viewer',
|
||||
code: `VIEWER_${Date.now()}`,
|
||||
details: [
|
||||
{
|
||||
privilegeKeyId: privilegesKey!.id,
|
||||
action: 'view',
|
||||
value: true,
|
||||
},
|
||||
],
|
||||
})
|
||||
.expect(201);
|
||||
|
||||
expect(created.body).toMatchObject({
|
||||
name: 'Viewer',
|
||||
status: 'draft',
|
||||
createdBy: adminUserId,
|
||||
details: [
|
||||
expect.objectContaining({
|
||||
keyCode: 'PRIVILEGES',
|
||||
action: 'view',
|
||||
value: true,
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const id = created.body.id as string;
|
||||
|
||||
await request(app.getHttpServer())
|
||||
.get(`/privileges/${id}`)
|
||||
.set('Authorization', `Bearer ${adminAccessToken}`)
|
||||
.expect(200);
|
||||
|
||||
await request(app.getHttpServer())
|
||||
.patch(`/privileges/${id}`)
|
||||
.set('Authorization', `Bearer ${adminAccessToken}`)
|
||||
.send({ name: 'Viewer Updated' })
|
||||
.expect(200);
|
||||
|
||||
await request(app.getHttpServer())
|
||||
.patch(`/privileges/${id}`)
|
||||
.set('Authorization', `Bearer ${adminAccessToken}`)
|
||||
.send({ status: 'active' })
|
||||
.expect(400);
|
||||
|
||||
await request(app.getHttpServer())
|
||||
.patch(`/privileges/${id}/status`)
|
||||
.set('Authorization', `Bearer ${adminAccessToken}`)
|
||||
.send({ status: 'active' })
|
||||
.expect(200);
|
||||
|
||||
const list = await request(app.getHttpServer())
|
||||
.get('/privileges?search=Viewer')
|
||||
.set('Authorization', `Bearer ${adminAccessToken}`)
|
||||
.expect(200);
|
||||
expect(list.body.data.length).toBeGreaterThanOrEqual(1);
|
||||
expect(list.body.meta).toBeDefined();
|
||||
|
||||
const me = await request(app.getHttpServer())
|
||||
.get('/auth/me')
|
||||
.set('Authorization', `Bearer ${adminAccessToken}`)
|
||||
.expect(200);
|
||||
expect(me.body.privilege).toMatchObject({
|
||||
id: adminPrivilegeId,
|
||||
});
|
||||
expect(me.body.permissions.PRIVILEGES.view).toBe(true);
|
||||
|
||||
await request(app.getHttpServer())
|
||||
.patch(`/users/${otherUserId}/privilege`)
|
||||
.set('Authorization', `Bearer ${adminAccessToken}`)
|
||||
.send({ privilegeId: id })
|
||||
.expect(200);
|
||||
|
||||
await request(app.getHttpServer())
|
||||
.get('/privileges')
|
||||
.set('Authorization', `Bearer ${otherAccessToken}`)
|
||||
.expect(200);
|
||||
|
||||
await request(app.getHttpServer())
|
||||
.post('/privileges')
|
||||
.set('Authorization', `Bearer ${otherAccessToken}`)
|
||||
.send({ name: 'Nope', code: `NOPE_${Date.now()}` })
|
||||
.expect(403);
|
||||
|
||||
await request(app.getHttpServer())
|
||||
.patch(`/users/${otherUserId}/privilege`)
|
||||
.set('Authorization', `Bearer ${adminAccessToken}`)
|
||||
.send({ privilegeId: null })
|
||||
.expect(200);
|
||||
|
||||
await request(app.getHttpServer())
|
||||
.delete(`/privileges/${id}`)
|
||||
.set('Authorization', `Bearer ${adminAccessToken}`)
|
||||
.expect(204);
|
||||
});
|
||||
|
||||
it('imports privileges from CSV', async () => {
|
||||
const csv = `name,code,status\nImported Role,IMP_${Date.now()},draft\n`;
|
||||
const res = await request(app.getHttpServer())
|
||||
.post('/privileges/import')
|
||||
.set('Authorization', `Bearer ${adminAccessToken}`)
|
||||
.attach('file', Buffer.from(csv, 'utf8'), 'privileges.csv')
|
||||
.expect(201);
|
||||
|
||||
expect(res.body).toMatchObject({ imported: 1 });
|
||||
});
|
||||
|
||||
it('bulk status and bulk delete', async () => {
|
||||
const a = await request(app.getHttpServer())
|
||||
.post('/privileges')
|
||||
.set('Authorization', `Bearer ${adminAccessToken}`)
|
||||
.send({ name: 'Bulk A', code: `BA_${Date.now()}` })
|
||||
.expect(201);
|
||||
const b = await request(app.getHttpServer())
|
||||
.post('/privileges')
|
||||
.set('Authorization', `Bearer ${adminAccessToken}`)
|
||||
.send({ name: 'Bulk B', code: `BB_${Date.now()}` })
|
||||
.expect(201);
|
||||
|
||||
const ids = [a.body.id as string, b.body.id as string];
|
||||
|
||||
await request(app.getHttpServer())
|
||||
.post('/privileges/bulk-status')
|
||||
.set('Authorization', `Bearer ${adminAccessToken}`)
|
||||
.send({ ids, status: 'archived' })
|
||||
.expect(200);
|
||||
|
||||
await request(app.getHttpServer())
|
||||
.post('/privileges/bulk-delete')
|
||||
.set('Authorization', `Bearer ${adminAccessToken}`)
|
||||
.send({ ids })
|
||||
.expect(200);
|
||||
});
|
||||
|
||||
it('superadmin bypasses privilege checks without an assigned role', async () => {
|
||||
await db
|
||||
.update(users)
|
||||
.set({ isSuperadmin: true, updatedAt: Date.now() })
|
||||
.where(eq(users.id, otherUserId));
|
||||
|
||||
const me = await request(app.getHttpServer())
|
||||
.get('/auth/me')
|
||||
.set('Authorization', `Bearer ${otherAccessToken}`)
|
||||
.expect(200);
|
||||
expect(me.body).toMatchObject({
|
||||
isSuperadmin: true,
|
||||
privilege: null,
|
||||
});
|
||||
|
||||
await request(app.getHttpServer())
|
||||
.get('/privileges')
|
||||
.set('Authorization', `Bearer ${otherAccessToken}`)
|
||||
.expect(200);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user