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
@@ -7,6 +7,11 @@ LOG_LEVEL=log
|
||||
# Inactividad (minutos) tras la cual caduca la sesión web
|
||||
SESSION_TIMEOUT_MINUTES=30
|
||||
|
||||
# Base SQLite local (permisos de menú)
|
||||
SQLITE_PATH=./data/app.sqlite
|
||||
# Usuarios web (U_WEB_USER) con acceso total "*", garantizado al arrancar (separar con comas)
|
||||
ADMIN_WEB_USERS=
|
||||
|
||||
# --- SAP Business One Service Layer ---
|
||||
SAPB1_SL_URL=https://servidor-sap:50000/b1s/v1
|
||||
SAPB1_SL_COMPANYDB=
|
||||
|
||||
@@ -32,3 +32,25 @@ Guard global: todo `/api/*` exige `Authorization: Bearer <token>` salvo rutas `@
|
||||
```bash
|
||||
curl -s -H 'Content-Type: application/json' -d '{"username":"USUARIO","password":"CLAVE"}' localhost:3000/api/auth/login
|
||||
```
|
||||
|
||||
## Permisos de menú
|
||||
|
||||
Se guardan en SQLite (`SQLITE_PATH`, por defecto `./data/app.sqlite`, fuera del repo). Un usuario web (`U_WEB_USER`) tiene una lista de patrones de ruta:
|
||||
|
||||
| Patrón | Permite |
|
||||
|---|---|
|
||||
| `*` | Todo (administrador) |
|
||||
| `/ventas/*` | `/ventas` y todo lo que cuelga de `/ventas/` (no `/ventas-x`) |
|
||||
| `/ventas/ordenes` | Solo esa ruta |
|
||||
|
||||
| Endpoint | Quién | Descripción |
|
||||
|---|---|---|
|
||||
| `GET /api/user/menu` | Cualquier sesión | `{allowedPaths}` del usuario actual |
|
||||
| `GET /api/permissions`, `GET /api/permissions/:webUser` | Administrador | Consulta |
|
||||
| `PUT /api/permissions/:webUser` `{paths}` | Administrador | Reemplaza los permisos |
|
||||
| `DELETE /api/permissions/:webUser` | Administrador | Elimina los permisos |
|
||||
|
||||
- `ADMIN_WEB_USERS=george,ana` garantiza `*` a esos usuarios en cada arranque (nunca se queda el sistema sin acceso).
|
||||
- El sistema no deja quitar el acceso total al último administrador (409).
|
||||
- El esquema se sincroniza automáticamente (`synchronize`); pasar a migraciones cuando se estabilice por cliente.
|
||||
- Si `better-sqlite3` falla al instalar en una máquina nueva: `npm rebuild better-sqlite3`.
|
||||
@@ -26,8 +26,11 @@
|
||||
"@nestjs/config": "^12.0.1",
|
||||
"@nestjs/core": "^12.0.1",
|
||||
"@nestjs/platform-express": "^12.0.1",
|
||||
"@nestjs/typeorm": "^12.0.2",
|
||||
"better-sqlite3": "^12.11.1",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
"rxjs": "^7.8.1",
|
||||
"typeorm": "^1.1.2",
|
||||
"undici": "^6.20.1",
|
||||
"zod": "^4.6.7"
|
||||
},
|
||||
@@ -36,6 +39,7 @@
|
||||
"@nestjs/mau": "^0.2.6",
|
||||
"@nestjs/schematics": "^12.0.0",
|
||||
"@nestjs/testing": "^12.0.1",
|
||||
"@types/better-sqlite3": "^9.6.0",
|
||||
"@types/express": "^5.0.0",
|
||||
"@types/node": "^24.0.0",
|
||||
"@types/supertest": "^7.0.0",
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { AuthModule } from './auth/auth.module.js';
|
||||
import { AppConfigModule } from './config/config.module.js';
|
||||
import { DatabaseModule } from './database/database.module.js';
|
||||
import { HealthController } from './health/health.controller.js';
|
||||
import { PermissionsModule } from './permissions/permissions.module.js';
|
||||
import { SapModule } from './sap/sap.module.js';
|
||||
|
||||
@Module({
|
||||
imports: [AppConfigModule, SapModule, AuthModule],
|
||||
imports: [AppConfigModule, DatabaseModule, SapModule, AuthModule, PermissionsModule],
|
||||
controllers: [HealthController],
|
||||
})
|
||||
export class AppModule {}
|
||||
@@ -16,6 +16,12 @@ describe('validateEnv', () => {
|
||||
expect(env.SAPB1_SL_VERIFY_SSL).toBe(true);
|
||||
expect(env.SAPB1_SL_CA_FILE).toBeUndefined();
|
||||
expect(env.SAPB1_SL_MAX_CONCURRENCY).toBe(1);
|
||||
expect(env.SQLITE_PATH).toBe('./data/app.sqlite');
|
||||
expect(env.ADMIN_WEB_USERS).toEqual([]);
|
||||
});
|
||||
|
||||
it('separa ADMIN_WEB_USERS', () => {
|
||||
expect(validateEnv({ ...sap, ADMIN_WEB_USERS: 'george, ana ,' }).ADMIN_WEB_USERS).toEqual(['george', 'ana']);
|
||||
});
|
||||
|
||||
it('quita la barra final de la URL de SAP', () => {
|
||||
|
||||
@@ -19,6 +19,19 @@ export const envSchema = z
|
||||
.filter(Boolean),
|
||||
),
|
||||
LOG_LEVEL: z.enum(['error', 'warn', 'log', 'debug', 'verbose']).default('log'),
|
||||
// Base SQLite local (permisos de menú). `:memory:` para pruebas.
|
||||
SQLITE_PATH: z.string().min(1).default('./data/app.sqlite'),
|
||||
// Usuarios web (U_WEB_USER) que siempre tienen acceso total ("*"); se
|
||||
// garantiza al arrancar para no quedar fuera por un error de permisos.
|
||||
ADMIN_WEB_USERS: z
|
||||
.string()
|
||||
.default('')
|
||||
.transform((v) =>
|
||||
v
|
||||
.split(',')
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean),
|
||||
),
|
||||
// Inactividad tras la cual caduca la sesión web (deslizante).
|
||||
SESSION_TIMEOUT_MINUTES: z.coerce.number().int().positive().default(30),
|
||||
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import { mkdirSync } from 'node:fs';
|
||||
import { dirname, resolve } from 'node:path';
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { AppConfigService } from '../config/app-config.service.js';
|
||||
|
||||
/** Base SQLite local de la aplicación (hoy: permisos de menú). */
|
||||
@Module({
|
||||
imports: [
|
||||
TypeOrmModule.forRootAsync({
|
||||
inject: [AppConfigService],
|
||||
useFactory: (config: AppConfigService) => {
|
||||
const database = config.get('SQLITE_PATH');
|
||||
const inMemory = database === ':memory:';
|
||||
if (!inMemory) mkdirSync(dirname(resolve(database)), { recursive: true });
|
||||
return {
|
||||
type: 'better-sqlite3' as const,
|
||||
database,
|
||||
enableWAL: !inMemory,
|
||||
autoLoadEntities: true,
|
||||
// Una sola tabla pequeña: el esquema se sincroniza solo. Cuando el
|
||||
// esquema se estabilice por cliente, pasar a migraciones.
|
||||
synchronize: true,
|
||||
};
|
||||
},
|
||||
}),
|
||||
],
|
||||
})
|
||||
export class DatabaseModule {}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { type CanActivate, type ExecutionContext, ForbiddenException, Injectable } from '@nestjs/common';
|
||||
import type { AuthenticatedRequest } from '../auth/auth.types.js';
|
||||
import { PermissionsService } from './permissions.service.js';
|
||||
|
||||
/** Solo usuarios con acceso total ("*"). Se ejecuta después del guard de sesión global. */
|
||||
@Injectable()
|
||||
export class AdminGuard implements CanActivate {
|
||||
constructor(private readonly permissions: PermissionsService) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const req = context.switchToHttp().getRequest<AuthenticatedRequest>();
|
||||
if (!(await this.permissions.isAdmin(req.user.webUser))) {
|
||||
throw new ForbiddenException('Requiere permisos de administrador');
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { Column, Entity, PrimaryGeneratedColumn, Unique } from 'typeorm';
|
||||
|
||||
/** Un patrón de ruta permitido para un usuario web (`*`, `/ventas/*`, `/ventas/ordenes`). */
|
||||
@Entity('menu_permissions')
|
||||
@Unique(['webUser', 'pattern'])
|
||||
export class MenuPermission {
|
||||
@PrimaryGeneratedColumn()
|
||||
id: number;
|
||||
|
||||
@Column()
|
||||
webUser: string;
|
||||
|
||||
@Column()
|
||||
pattern: string;
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { Body, Controller, Delete, Get, HttpCode, Param, Put, Req, UseGuards } from '@nestjs/common';
|
||||
import { z } from 'zod';
|
||||
import type { AuthenticatedRequest } from '../auth/auth.types.js';
|
||||
import { ZodValidationPipe } from '../common/zod-validation.pipe.js';
|
||||
import { AdminGuard } from './admin.guard.js';
|
||||
import { PermissionsService } from './permissions.service.js';
|
||||
|
||||
// `*`, `/ventas/ordenes` o `/ventas/*`
|
||||
const pathPattern = z
|
||||
.string()
|
||||
.max(100)
|
||||
.regex(/^(\*|(\/[A-Za-z0-9_-]+)+(\/\*)?)$/, 'Patrón inválido: use "*", "/modulo/ruta" o "/modulo/*"');
|
||||
const setPathsSchema = z.object({ paths: z.array(pathPattern).max(200) });
|
||||
const webUserSchema = z.string().trim().min(1).max(100);
|
||||
type SetPathsDto = z.infer<typeof setPathsSchema>;
|
||||
|
||||
/** Menú permitido para el usuario de la sesión (lo consume el frontend). */
|
||||
@Controller('user')
|
||||
export class UserMenuController {
|
||||
constructor(private readonly permissions: PermissionsService) {}
|
||||
|
||||
@Get('menu')
|
||||
async menu(@Req() req: AuthenticatedRequest) {
|
||||
return { allowedPaths: await this.permissions.getPaths(req.user.webUser) };
|
||||
}
|
||||
}
|
||||
|
||||
/** Administración de permisos (solo acceso total). */
|
||||
@Controller('permissions')
|
||||
@UseGuards(AdminGuard)
|
||||
export class PermissionsController {
|
||||
constructor(private readonly permissions: PermissionsService) {}
|
||||
|
||||
@Get()
|
||||
list() {
|
||||
return this.permissions.listAll();
|
||||
}
|
||||
|
||||
@Get(':webUser')
|
||||
async get(@Param('webUser', new ZodValidationPipe(webUserSchema)) webUser: string) {
|
||||
return { webUser, paths: await this.permissions.getPaths(webUser) };
|
||||
}
|
||||
|
||||
@Put(':webUser')
|
||||
set(
|
||||
@Param('webUser', new ZodValidationPipe(webUserSchema)) webUser: string,
|
||||
@Body(new ZodValidationPipe(setPathsSchema)) body: SetPathsDto,
|
||||
) {
|
||||
return this.permissions.setPaths(webUser, body.paths);
|
||||
}
|
||||
|
||||
@Delete(':webUser')
|
||||
@HttpCode(204)
|
||||
remove(@Param('webUser', new ZodValidationPipe(webUserSchema)) webUser: string) {
|
||||
return this.permissions.remove(webUser);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { AdminGuard } from './admin.guard.js';
|
||||
import { MenuPermission } from './menu-permission.entity.js';
|
||||
import { PermissionsController, UserMenuController } from './permissions.controller.js';
|
||||
import { PermissionsService } from './permissions.service.js';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([MenuPermission])],
|
||||
controllers: [UserMenuController, PermissionsController],
|
||||
providers: [PermissionsService, AdminGuard],
|
||||
exports: [PermissionsService],
|
||||
})
|
||||
export class PermissionsModule {}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { ConflictException } from '@nestjs/common';
|
||||
import { DataSource } from 'typeorm';
|
||||
import type { AppConfigService } from '../config/app-config.service.js';
|
||||
import { MenuPermission } from './menu-permission.entity.js';
|
||||
import { PermissionsService } from './permissions.service.js';
|
||||
|
||||
describe('PermissionsService (SQLite en memoria)', () => {
|
||||
let ds: DataSource;
|
||||
let service: PermissionsService;
|
||||
|
||||
beforeEach(async () => {
|
||||
ds = new DataSource({ type: 'better-sqlite3', database: ':memory:', entities: [MenuPermission], synchronize: true });
|
||||
await ds.initialize();
|
||||
service = new PermissionsService(ds.getRepository(MenuPermission), { get: () => [] } as unknown as AppConfigService);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await ds.destroy();
|
||||
});
|
||||
|
||||
it('setPaths reemplaza y quita duplicados', async () => {
|
||||
await service.setPaths('luis', ['/ventas/*', '/compras/*']);
|
||||
await service.setPaths('luis', ['/inventario/*', '/inventario/*']);
|
||||
expect(await service.getPaths('luis')).toEqual(['/inventario/*']);
|
||||
});
|
||||
|
||||
it('listAll agrupa por usuario', async () => {
|
||||
await service.setPaths('b', ['/x']);
|
||||
await service.setPaths('a', ['/z', '/y']);
|
||||
expect(await service.listAll()).toEqual([
|
||||
{ webUser: 'a', paths: ['/y', '/z'] },
|
||||
{ webUser: 'b', paths: ['/x'] },
|
||||
]);
|
||||
});
|
||||
|
||||
it('ensureAdmins es idempotente y conserva otros permisos', async () => {
|
||||
await service.setPaths('ana', ['/ventas/*']);
|
||||
await service.ensureAdmins(['ana', 'ana', 'luis']);
|
||||
await service.ensureAdmins(['ana']);
|
||||
expect(await service.getPaths('ana')).toEqual(['*', '/ventas/*']);
|
||||
expect(await service.isAdmin('luis')).toBe(true);
|
||||
});
|
||||
|
||||
it('protege al último administrador (setPaths y remove)', async () => {
|
||||
await service.ensureAdmins(['ana']);
|
||||
await expect(service.setPaths('ana', ['/ventas/*'])).rejects.toBeInstanceOf(ConflictException);
|
||||
await expect(service.remove('ana')).rejects.toBeInstanceOf(ConflictException);
|
||||
expect(await service.getPaths('ana')).toEqual(['*']); // la transacción no dejó cambios
|
||||
|
||||
await service.ensureAdmins(['luis']);
|
||||
await service.remove('ana');
|
||||
expect(await service.getPaths('ana')).toEqual([]);
|
||||
});
|
||||
|
||||
it('no permite duplicar (usuario, patrón) a nivel de base de datos', async () => {
|
||||
const repo = ds.getRepository(MenuPermission);
|
||||
await repo.insert({ webUser: 'a', pattern: '/x' });
|
||||
await expect(repo.insert({ webUser: 'a', pattern: '/x' })).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,83 @@
|
||||
import { ConflictException, Injectable, Logger, OnApplicationBootstrap } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Not, Repository } from 'typeorm';
|
||||
import { AppConfigService } from '../config/app-config.service.js';
|
||||
import { MenuPermission } from './menu-permission.entity.js';
|
||||
|
||||
export const ALL_ACCESS = '*';
|
||||
|
||||
export interface UserPermissions {
|
||||
webUser: string;
|
||||
paths: string[];
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class PermissionsService implements OnApplicationBootstrap {
|
||||
private readonly logger = new Logger(PermissionsService.name);
|
||||
|
||||
constructor(
|
||||
@InjectRepository(MenuPermission) private readonly repo: Repository<MenuPermission>,
|
||||
private readonly config: AppConfigService,
|
||||
) {}
|
||||
|
||||
async onApplicationBootstrap() {
|
||||
await this.ensureAdmins(this.config.get('ADMIN_WEB_USERS'));
|
||||
}
|
||||
|
||||
async getPaths(webUser: string): Promise<string[]> {
|
||||
const rows = await this.repo.find({ where: { webUser }, order: { pattern: 'ASC' } });
|
||||
return rows.map((r) => r.pattern);
|
||||
}
|
||||
|
||||
async listAll(): Promise<UserPermissions[]> {
|
||||
const rows = await this.repo.find({ order: { webUser: 'ASC', pattern: 'ASC' } });
|
||||
const byUser = new Map<string, string[]>();
|
||||
for (const r of rows) byUser.set(r.webUser, [...(byUser.get(r.webUser) ?? []), r.pattern]);
|
||||
return [...byUser].map(([webUser, paths]) => ({ webUser, paths }));
|
||||
}
|
||||
|
||||
async isAdmin(webUser: string): Promise<boolean> {
|
||||
return this.repo.existsBy({ webUser, pattern: ALL_ACCESS });
|
||||
}
|
||||
|
||||
/** Reemplaza todos los permisos del usuario. */
|
||||
async setPaths(webUser: string, paths: string[]): Promise<UserPermissions> {
|
||||
const unique = [...new Set(paths)].sort();
|
||||
await this.repo.manager.transaction(async (manager) => {
|
||||
const repo = manager.getRepository(MenuPermission);
|
||||
if (!unique.includes(ALL_ACCESS)) await this.assertNotLastAdmin(repo, webUser);
|
||||
await repo.delete({ webUser });
|
||||
if (unique.length) await repo.insert(unique.map((pattern) => ({ webUser, pattern })));
|
||||
});
|
||||
this.logger.log(`Permisos de ${webUser} actualizados (${unique.length} patrones)`);
|
||||
return { webUser, paths: unique };
|
||||
}
|
||||
|
||||
async remove(webUser: string): Promise<void> {
|
||||
await this.repo.manager.transaction(async (manager) => {
|
||||
const repo = manager.getRepository(MenuPermission);
|
||||
await this.assertNotLastAdmin(repo, webUser);
|
||||
await repo.delete({ webUser });
|
||||
});
|
||||
this.logger.log(`Permisos de ${webUser} eliminados`);
|
||||
}
|
||||
|
||||
/** Garantiza el acceso total de los administradores configurados en el .env. */
|
||||
async ensureAdmins(webUsers: string[]): Promise<void> {
|
||||
for (const webUser of webUsers) {
|
||||
if (await this.isAdmin(webUser)) continue;
|
||||
await this.repo.insert({ webUser, pattern: ALL_ACCESS });
|
||||
this.logger.log(`Administrador "${webUser}" garantizado desde ADMIN_WEB_USERS`);
|
||||
}
|
||||
}
|
||||
|
||||
/** Evita dejar el sistema sin ningún usuario con acceso total. */
|
||||
private async assertNotLastAdmin(repo: Repository<MenuPermission>, webUser: string) {
|
||||
const isAdminNow = await repo.existsBy({ webUser, pattern: ALL_ACCESS });
|
||||
if (!isAdminNow) return;
|
||||
const others = await repo.countBy({ pattern: ALL_ACCESS, webUser: Not(webUser) });
|
||||
if (others === 0) {
|
||||
throw new ConflictException('No se puede quitar el acceso total al último administrador');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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