Files
2026-08-01 03:12:23 +02:00

291 lines
10 KiB
TypeScript

import { generateKeyPairSync } from 'crypto';
import request from 'supertest';
import nock from 'nock';
import jwt from 'jsonwebtoken';
process.env.KEYCLOAK_BASE_URL = 'http://keycloak.test';
process.env.KEYCLOAK_REALM = 'scouthub';
process.env.KEYCLOAK_MAGAZZINO_CLIENT_ID = 'test-client';
process.env.KEYCLOAK_MAGAZZINO_CLIENT_SECRET = 'test-secret';
process.env.DATABASE_URL = 'postgresql://user:pass@localhost:5432/scouthub_magazzino_test';
const tipoEventoFindMany = jest.fn();
const tipoEventoFindUnique = jest.fn();
const tipoEventoCreate = jest.fn();
const tipoEventoUpdate = jest.fn();
const tipoEventoDelete = jest.fn();
jest.mock('../../src/db/prisma', () => ({
prisma: {
tipoEvento: {
findMany: (...args: unknown[]) => tipoEventoFindMany(...args),
findUnique: (...args: unknown[]) => tipoEventoFindUnique(...args),
create: (...args: unknown[]) => tipoEventoCreate(...args),
update: (...args: unknown[]) => tipoEventoUpdate(...args),
delete: (...args: unknown[]) => tipoEventoDelete(...args),
},
},
}));
import { app } from '../../src/app';
const KEYCLOAK_HOST = 'http://keycloak.test';
const CERTS_PATH = '/realms/scouthub/protocol/openid-connect/certs';
const KID = 'test-kid';
const { publicKey, privateKey } = generateKeyPairSync('rsa', { modulusLength: 2048 });
const jwk = publicKey.export({ format: 'jwk' }) as Record<string, unknown>;
const privateKeyPem = privateKey.export({ type: 'pkcs1', format: 'pem' }) as string;
function signToken(payload: object): string {
return jwt.sign(payload, privateKeyPem, { algorithm: 'RS256', keyid: KID, expiresIn: '5m' });
}
function utenteToken(orgId = 'org-1'): string {
return signToken({
sub: 'user-1',
realm_access: { roles: ['censito'] },
organization: { 'gruppo-alfa': { id: orgId, roles: [] } },
});
}
function adminCatalogoToken(): string {
return signToken({
sub: 'admin-1',
realm_access: { roles: ['moderatore'] },
organization: { 'gruppo-omega': { id: 'org-9', roles: [] } },
});
}
beforeAll(() => {
nock(KEYCLOAK_HOST).persist().get(CERTS_PATH).reply(200, {
keys: [{ ...jwk, kid: KID, alg: 'RS256', use: 'sig' }],
});
});
afterAll(() => {
nock.cleanAll();
});
beforeEach(() => {
jest.clearAllMocks();
});
describe('GET /tipi-evento', () => {
test('è pubblico e restituisce solo i tipi evento confermati', async () => {
tipoEventoFindMany.mockResolvedValueOnce([{ id: 't-1', nome: 'Campo estivo', stato: 'confermata' }]);
const response = await request(app).get('/tipi-evento');
expect(response.status).toBe(200);
expect(response.body).toEqual([{ id: 't-1', nome: 'Campo estivo', stato: 'confermata' }]);
expect(tipoEventoFindMany).toHaveBeenCalledWith({
where: { stato: 'confermata' },
orderBy: { nome: 'asc' },
});
});
});
describe('GET /tipi-evento/moderazione', () => {
test('un utente normale non può accedere', async () => {
const response = await request(app)
.get('/tipi-evento/moderazione')
.set('Authorization', `Bearer ${utenteToken()}`);
expect(response.status).toBe(403);
expect(tipoEventoFindMany).not.toHaveBeenCalled();
});
test('un moderatore vede tutti i tipi evento, incluse le proposte', async () => {
tipoEventoFindMany.mockResolvedValueOnce([
{ id: 't-1', nome: 'Campo estivo', stato: 'confermata' },
{ id: 't-2', nome: 'Bivacco', stato: 'da_approvare' },
]);
const response = await request(app)
.get('/tipi-evento/moderazione')
.set('Authorization', `Bearer ${adminCatalogoToken()}`);
expect(response.status).toBe(200);
expect(response.body).toHaveLength(2);
});
test('risponde 401 senza token', async () => {
const response = await request(app).get('/tipi-evento/moderazione');
expect(response.status).toBe(401);
expect(tipoEventoFindMany).not.toHaveBeenCalled();
});
});
describe('POST /tipi-evento', () => {
test('un utente normale non può creare un tipo evento', async () => {
const response = await request(app)
.post('/tipi-evento')
.set('Authorization', `Bearer ${utenteToken()}`)
.send({ nome: 'Bivacco' });
expect(response.status).toBe(403);
expect(tipoEventoCreate).not.toHaveBeenCalled();
});
test('un moderatore crea un tipo evento già confermato', async () => {
tipoEventoCreate.mockResolvedValueOnce({ id: 't-2', nome: 'Bivacco', stato: 'confermata' });
const response = await request(app)
.post('/tipi-evento')
.set('Authorization', `Bearer ${adminCatalogoToken()}`)
.send({ nome: 'Bivacco' });
expect(response.status).toBe(201);
expect(tipoEventoCreate).toHaveBeenCalledWith({ data: { nome: 'Bivacco', stato: 'confermata' } });
});
test('risponde 401 senza token', async () => {
const response = await request(app).post('/tipi-evento').send({ nome: 'Bivacco' });
expect(response.status).toBe(401);
expect(tipoEventoCreate).not.toHaveBeenCalled();
});
});
describe('POST /tipi-evento/proposte', () => {
test("un utente autenticato con un'org propone un tipo evento, che nasce 'da_approvare'", async () => {
tipoEventoCreate.mockResolvedValueOnce({
id: 't-3',
nome: 'Uscita notturna',
stato: 'da_approvare',
creatoDaOrgId: 'org-1',
});
const response = await request(app)
.post('/tipi-evento/proposte')
.set('Authorization', `Bearer ${utenteToken('org-1')}`)
.send({ nome: 'Uscita notturna' });
expect(response.status).toBe(201);
expect(response.body).toMatchObject({ stato: 'da_approvare', creatoDaOrgId: 'org-1' });
expect(tipoEventoCreate).toHaveBeenCalledWith({
data: { nome: 'Uscita notturna', stato: 'da_approvare', creatoDaOrgId: 'org-1' },
});
});
test('risponde 401 senza token', async () => {
const response = await request(app).post('/tipi-evento/proposte').send({ nome: 'Uscita notturna' });
expect(response.status).toBe(401);
expect(tipoEventoCreate).not.toHaveBeenCalled();
});
});
describe('PUT /tipi-evento/:id', () => {
test('un utente normale non può modificare un tipo evento', async () => {
const response = await request(app)
.put('/tipi-evento/t-1')
.set('Authorization', `Bearer ${utenteToken()}`)
.send({ nome: 'Uscita di branco' });
expect(response.status).toBe(403);
expect(tipoEventoUpdate).not.toHaveBeenCalled();
});
test('un moderatore può modificare un tipo evento', async () => {
tipoEventoUpdate.mockResolvedValueOnce({ id: 't-1', nome: 'Uscita di branco' });
const response = await request(app)
.put('/tipi-evento/t-1')
.set('Authorization', `Bearer ${adminCatalogoToken()}`)
.send({ nome: 'Uscita di branco' });
expect(response.status).toBe(200);
expect(tipoEventoUpdate).toHaveBeenCalledWith({ where: { id: 't-1' }, data: { nome: 'Uscita di branco' } });
});
});
describe('DELETE /tipi-evento/:id', () => {
test('un utente normale non può eliminare un tipo evento', async () => {
const response = await request(app).delete('/tipi-evento/t-1').set('Authorization', `Bearer ${utenteToken()}`);
expect(response.status).toBe(403);
expect(tipoEventoDelete).not.toHaveBeenCalled();
});
test('un moderatore può eliminare un tipo evento', async () => {
tipoEventoDelete.mockResolvedValueOnce({ id: 't-1', nome: 'Sede' });
const response = await request(app).delete('/tipi-evento/t-1').set('Authorization', `Bearer ${adminCatalogoToken()}`);
expect(response.status).toBe(204);
expect(tipoEventoDelete).toHaveBeenCalledWith({ where: { id: 't-1' } });
});
test('risponde 401 senza token', async () => {
const response = await request(app).delete('/tipi-evento/t-1');
expect(response.status).toBe(401);
expect(tipoEventoDelete).not.toHaveBeenCalled();
});
});
describe('POST /tipi-evento/:id/approva', () => {
test('un moderatore può approvare un tipo evento proposto', async () => {
tipoEventoFindUnique.mockResolvedValueOnce({ id: 't-3', nome: 'Uscita notturna', stato: 'da_approvare' });
tipoEventoUpdate.mockResolvedValueOnce({ id: 't-3', nome: 'Uscita notturna', stato: 'confermata' });
const response = await request(app)
.post('/tipi-evento/t-3/approva')
.set('Authorization', `Bearer ${adminCatalogoToken()}`);
expect(response.status).toBe(200);
expect(response.body.stato).toBe('confermata');
expect(tipoEventoUpdate).toHaveBeenCalledWith({ where: { id: 't-3' }, data: { stato: 'confermata' } });
});
test('risponde 409 se il tipo evento è già confermato', async () => {
tipoEventoFindUnique.mockResolvedValueOnce({ id: 't-1', nome: 'Campo estivo', stato: 'confermata' });
const response = await request(app)
.post('/tipi-evento/t-1/approva')
.set('Authorization', `Bearer ${adminCatalogoToken()}`);
expect(response.status).toBe(409);
expect(tipoEventoUpdate).not.toHaveBeenCalled();
});
test('risponde 404 se il tipo evento non esiste', async () => {
tipoEventoFindUnique.mockResolvedValueOnce(null);
const response = await request(app)
.post('/tipi-evento/inesistente/approva')
.set('Authorization', `Bearer ${adminCatalogoToken()}`);
expect(response.status).toBe(404);
expect(tipoEventoUpdate).not.toHaveBeenCalled();
});
});
describe('POST /tipi-evento/:id/rifiuta', () => {
test('un moderatore può rifiutare un tipo evento proposto, che viene eliminato', async () => {
tipoEventoFindUnique.mockResolvedValueOnce({ id: 't-3', nome: 'Uscita notturna', stato: 'da_approvare' });
tipoEventoDelete.mockResolvedValueOnce({ id: 't-3' });
const response = await request(app)
.post('/tipi-evento/t-3/rifiuta')
.set('Authorization', `Bearer ${adminCatalogoToken()}`);
expect(response.status).toBe(204);
expect(tipoEventoDelete).toHaveBeenCalledWith({ where: { id: 't-3' } });
});
test('risponde 409 se il tipo evento è già confermato', async () => {
tipoEventoFindUnique.mockResolvedValueOnce({ id: 't-1', nome: 'Campo estivo', stato: 'confermata' });
const response = await request(app)
.post('/tipi-evento/t-1/rifiuta')
.set('Authorization', `Bearer ${adminCatalogoToken()}`);
expect(response.status).toBe(409);
expect(tipoEventoDelete).not.toHaveBeenCalled();
});
});