- Introduced new columns `status`, `created_by`, and `updated_by` in the `users` table to track user status and ownership. - Updated the `employees` table to include a foreign key reference to the `users` table via `user_id`. - Created migration script `0012_users_primary.sql` to apply these changes to the database schema. - Enhanced the `EmployeesService` and `EmployeesRepository` to support user assignments and related data retrieval. - Updated DTOs and service methods to reflect the new user and employee relationships. - Added unit tests to validate the new functionality and ensure data integrity. - Modified existing controllers to accommodate the new fields and relationships in user and employee management.
295 lines
8.8 KiB
TypeScript
295 lines
8.8 KiB
TypeScript
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';
|
|
import { registerAndActivate } from './helpers/activate-user';
|
|
|
|
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 admin = await registerAndActivate(app, db, adminUsername, password);
|
|
adminAccessToken = admin.accessToken;
|
|
adminUserId = admin.userId;
|
|
const adminMe = await request(app.getHttpServer())
|
|
.get('/auth/me')
|
|
.set('Authorization', `Bearer ${adminAccessToken}`)
|
|
.expect(200);
|
|
expect(adminMe.body).toMatchObject({
|
|
privilege: null,
|
|
permissions: {},
|
|
});
|
|
|
|
const other = await registerAndActivate(app, db, otherUsername, password);
|
|
otherAccessToken = other.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);
|
|
});
|
|
});
|