feat(api): permisos de menú en SQLite con API de administración
- SQLite (better-sqlite3 + TypeORM, WAL) con tabla menu_permissions (usuario web, patrón de ruta); archivo fuera del repo. - GET /api/user/menu para el frontend; GET/PUT/DELETE /api/permissions solo para administradores (acceso "*"). - ADMIN_WEB_USERS garantiza el acceso total al arrancar; no se puede quitar el "*" al último administrador (409, dentro de una transacción). - Patrones validados (`*`, `/modulo/ruta`, `/modulo/*`). A diferencia del frontend anterior, `/inventario/*` ya no habilita `/inventario-x`. - Helper de e2e compartido (SAP simulado, SQLite en memoria). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
079cedbaed
commit
73fffee2f7
19 files changed
+1104
-55
No files matched your search
@@ -1,36 +1,12 @@
|
||||
import { Test } from '@nestjs/testing';
|
||||
import type { INestApplication } from '@nestjs/common';
|
||||
import request from 'supertest';
|
||||
|
||||
process.env.SAPB1_SL_URL ??= 'https://sap.invalid:50000/b1s/v1';
|
||||
process.env.SAPB1_SL_COMPANYDB ??= 'DB';
|
||||
process.env.SAPB1_SL_USER ??= 'u';
|
||||
process.env.SAPB1_SL_PASSWORD ??= 'p';
|
||||
|
||||
const EMPLOYEES = [
|
||||
{ EmployeeID: 7, FirstName: 'Ana', LastName: 'Pérez', Active: 'tYES', U_WEB_USER: 'ana', U_WEB_PASS: 'secreto' },
|
||||
];
|
||||
import { createTestApp, employee } from './support/create-test-app.js';
|
||||
|
||||
describe('Auth (e2e, SAP simulado)', () => {
|
||||
let app: INestApplication;
|
||||
|
||||
beforeEach(async () => {
|
||||
const { AppModule } = await import('../src/app.module.js');
|
||||
const { SapClientService } = await import('../src/sap/sap-client.service.js');
|
||||
const { SapSessionService } = await import('../src/sap/sap-session.service.js');
|
||||
const moduleRef = await Test.createTestingModule({ imports: [AppModule] })
|
||||
.overrideProvider(SapClientService)
|
||||
.useValue({
|
||||
get: async (_path: string, q: { $filter: string }) => ({
|
||||
data: { value: q.$filter === "U_WEB_USER eq 'ana'" ? EMPLOYEES : [] },
|
||||
}),
|
||||
})
|
||||
.overrideProvider(SapSessionService)
|
||||
.useValue({ getSession: async () => ({}), status: () => ({ connected: true }), onModuleDestroy: () => undefined })
|
||||
.compile();
|
||||
app = moduleRef.createNestApplication();
|
||||
app.setGlobalPrefix('api');
|
||||
await app.init();
|
||||
app = await createTestApp([employee('ana', 7)]);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
@@ -47,7 +23,7 @@ describe('Auth (e2e, SAP simulado)', () => {
|
||||
|
||||
it('flujo completo: login -> me -> ruta protegida -> logout -> 401', async () => {
|
||||
const res = await login('ana', 'secreto').expect(200);
|
||||
expect(res.body.user).toMatchObject({ webUser: 'ana', empId: 7, firstName: 'Ana' });
|
||||
expect(res.body.user).toMatchObject({ webUser: 'ana', empId: 7, firstName: 'ana' });
|
||||
expect(JSON.stringify(res.body)).not.toContain('secreto');
|
||||
const auth = { Authorization: `Bearer ${res.body.token}` };
|
||||
|
||||
|
||||
@@ -1,22 +1,12 @@
|
||||
import { Test } from '@nestjs/testing';
|
||||
import type { INestApplication } from '@nestjs/common';
|
||||
import request from 'supertest';
|
||||
|
||||
// Valores ficticios: este e2e no se conecta a SAP (el login es perezoso).
|
||||
process.env.SAPB1_SL_URL ??= 'https://sap.invalid:50000/b1s/v1';
|
||||
process.env.SAPB1_SL_COMPANYDB ??= 'DB';
|
||||
process.env.SAPB1_SL_USER ??= 'u';
|
||||
process.env.SAPB1_SL_PASSWORD ??= 'p';
|
||||
import { createTestApp } from './support/create-test-app.js';
|
||||
|
||||
describe('Health (e2e)', () => {
|
||||
let app: INestApplication;
|
||||
|
||||
beforeAll(async () => {
|
||||
const { AppModule } = await import('../src/app.module.js');
|
||||
const moduleRef = await Test.createTestingModule({ imports: [AppModule] }).compile();
|
||||
app = moduleRef.createNestApplication();
|
||||
app.setGlobalPrefix('api');
|
||||
await app.init();
|
||||
app = await createTestApp([]);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import type { INestApplication } from '@nestjs/common';
|
||||
import request from 'supertest';
|
||||
import { createTestApp, employee } from './support/create-test-app.js';
|
||||
|
||||
describe('Permisos de menú (e2e)', () => {
|
||||
let app: INestApplication;
|
||||
let admin: { Authorization: string };
|
||||
let luis: { Authorization: string };
|
||||
|
||||
const loginAs = async (username: string) => {
|
||||
const res = await request(app.getHttpServer()).post('/api/auth/login').send({ username, password: 'secreto' }).expect(200);
|
||||
return { Authorization: `Bearer ${res.body.token}` };
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
app = await createTestApp([employee('ana', 1), employee('luis', 2)], 'ana');
|
||||
admin = await loginAs('ana');
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('el administrador del .env obtiene "*" al arrancar', async () => {
|
||||
const res = await request(app.getHttpServer()).get('/api/user/menu').set(admin).expect(200);
|
||||
expect(res.body).toEqual({ allowedPaths: ['*'] });
|
||||
});
|
||||
|
||||
it('un usuario sin permisos recibe menú vacío', async () => {
|
||||
luis = await loginAs('luis');
|
||||
const res = await request(app.getHttpServer()).get('/api/user/menu').set(luis).expect(200);
|
||||
expect(res.body.allowedPaths).toEqual([]);
|
||||
});
|
||||
|
||||
it('el admin asigna permisos y el usuario los ve; un no-admin no puede administrar', async () => {
|
||||
await request(app.getHttpServer())
|
||||
.put('/api/permissions/luis')
|
||||
.set(admin)
|
||||
.send({ paths: ['/ventas/*', '/inventario/articulos', '/ventas/*'] })
|
||||
.expect(200)
|
||||
.expect({ webUser: 'luis', paths: ['/inventario/articulos', '/ventas/*'] });
|
||||
|
||||
luis = await loginAs('luis');
|
||||
const menu = await request(app.getHttpServer()).get('/api/user/menu').set(luis).expect(200);
|
||||
expect(menu.body.allowedPaths).toEqual(['/inventario/articulos', '/ventas/*']);
|
||||
|
||||
await request(app.getHttpServer()).get('/api/permissions').set(luis).expect(403);
|
||||
await request(app.getHttpServer()).put('/api/permissions/luis').set(luis).send({ paths: ['*'] }).expect(403);
|
||||
});
|
||||
|
||||
it('PUT reemplaza, GET lista y DELETE elimina', async () => {
|
||||
await request(app.getHttpServer()).put('/api/permissions/luis').set(admin).send({ paths: ['/ventas/*'] }).expect(200);
|
||||
await request(app.getHttpServer()).put('/api/permissions/luis').set(admin).send({ paths: ['/compras/*'] }).expect(200);
|
||||
|
||||
const list = await request(app.getHttpServer()).get('/api/permissions').set(admin).expect(200);
|
||||
expect(list.body).toEqual([
|
||||
{ webUser: 'ana', paths: ['*'] },
|
||||
{ webUser: 'luis', paths: ['/compras/*'] },
|
||||
]);
|
||||
|
||||
await request(app.getHttpServer()).delete('/api/permissions/luis').set(admin).expect(204);
|
||||
const one = await request(app.getHttpServer()).get('/api/permissions/luis').set(admin).expect(200);
|
||||
expect(one.body.paths).toEqual([]);
|
||||
});
|
||||
|
||||
it('rechaza patrones inválidos', async () => {
|
||||
for (const bad of ['ventas', '/ventas/', '/ventas/*/x', '/a b', '**', '']) {
|
||||
await request(app.getHttpServer()).put('/api/permissions/luis').set(admin).send({ paths: [bad] }).expect(400);
|
||||
}
|
||||
await request(app.getHttpServer()).put('/api/permissions/luis').set(admin).send({}).expect(400);
|
||||
});
|
||||
|
||||
it('no permite quitar el acceso total al último administrador', async () => {
|
||||
await request(app.getHttpServer()).put('/api/permissions/ana').set(admin).send({ paths: ['/ventas/*'] }).expect(409);
|
||||
await request(app.getHttpServer()).delete('/api/permissions/ana').set(admin).expect(409);
|
||||
|
||||
// con un segundo administrador, ana sí puede dejar de serlo
|
||||
await request(app.getHttpServer()).put('/api/permissions/luis').set(admin).send({ paths: ['*'] }).expect(200);
|
||||
await request(app.getHttpServer()).put('/api/permissions/ana').set(admin).send({ paths: ['/ventas/*'] }).expect(200);
|
||||
});
|
||||
|
||||
it('sin sesión no se accede al menú ni a la administración', async () => {
|
||||
await request(app.getHttpServer()).get('/api/user/menu').expect(401);
|
||||
await request(app.getHttpServer()).get('/api/permissions').expect(401);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
import { Test } from '@nestjs/testing';
|
||||
import type { INestApplication } from '@nestjs/common';
|
||||
|
||||
// Valores ficticios: los e2e no se conectan a SAP ni a un archivo SQLite.
|
||||
process.env.SAPB1_SL_URL ??= 'https://sap.invalid:50000/b1s/v1';
|
||||
process.env.SAPB1_SL_COMPANYDB ??= 'DB';
|
||||
process.env.SAPB1_SL_USER ??= 'u';
|
||||
process.env.SAPB1_SL_PASSWORD ??= 'p';
|
||||
process.env.SQLITE_PATH = ':memory:';
|
||||
|
||||
export interface FakeEmployee {
|
||||
EmployeeID: number;
|
||||
FirstName: string;
|
||||
LastName: string;
|
||||
Active: string;
|
||||
U_WEB_USER: string;
|
||||
U_WEB_PASS: string;
|
||||
}
|
||||
|
||||
export const employee = (webUser: string, id = 1, pass = 'secreto'): FakeEmployee => ({
|
||||
EmployeeID: id,
|
||||
FirstName: webUser,
|
||||
LastName: 'Test',
|
||||
Active: 'tYES',
|
||||
U_WEB_USER: webUser,
|
||||
U_WEB_PASS: pass,
|
||||
});
|
||||
|
||||
/** App completa con EmployeesInfo y la sesión SAP simulados. */
|
||||
export async function createTestApp(employees: FakeEmployee[], adminWebUsers = ''): Promise<INestApplication> {
|
||||
process.env.ADMIN_WEB_USERS = adminWebUsers;
|
||||
const { AppModule } = await import('../../src/app.module.js');
|
||||
const { SapClientService } = await import('../../src/sap/sap-client.service.js');
|
||||
const { SapSessionService } = await import('../../src/sap/sap-session.service.js');
|
||||
|
||||
const moduleRef = await Test.createTestingModule({ imports: [AppModule] })
|
||||
.overrideProvider(SapClientService)
|
||||
.useValue({
|
||||
get: async (_path: string, q: { $filter: string }) => ({
|
||||
data: { value: employees.filter((e) => q.$filter === `U_WEB_USER eq '${e.U_WEB_USER}'`) },
|
||||
}),
|
||||
})
|
||||
.overrideProvider(SapSessionService)
|
||||
.useValue({ getSession: async () => ({}), status: () => ({ connected: true }), onModuleDestroy: () => undefined })
|
||||
.compile();
|
||||
|
||||
const app = moduleRef.createNestApplication();
|
||||
app.setGlobalPrefix('api');
|
||||
await app.init();
|
||||
return app;
|
||||
}
|
||||
Reference in new issue
Block a user