Backend: RBAC faza 2 M1 - role gymowe z grantow zamiast kolumny roles (migracja: seed GYM_OWNER/GYM_TRAINER + backfill grantow i uzupelnienie Coaching.gymId; katalog 11 uprawnien gym z pinem gym:delegate tylko dla wlasciciela; resolver lib/gymPermissions i bramy per zasob w uslugach silowni, feedzie, obecnosciach i kontaktach; CRUD rol custom per silownia z kluczem serwerowym + PUT ról czlonka pod /admin/gyms; rekrutacja trenera wymaga wspolnej silowni (Coaching.gymId, 0 lub wiele = 400); DTO roles wyprowadzane z grantow - kolumna roles martwa do M4; wyszukiwanie admina po e-mailu wymaga pii:read; 15 unit testow resolvera, zestaw api 1009 green)

This commit is contained in:
tisachi
2026-11-26 00:37:17 +01:00
parent 61e28ff723
commit 654dbf97e0
45 changed files with 1648 additions and 426 deletions

View File

@@ -0,0 +1,136 @@
import { describe, expect, it, vi } from 'vitest';
import {
assertGymPermission,
canGym,
canInGym,
deriveMembershipRoles,
filterAssignableGymPermissions,
gymPermissionsFromGrants,
gymRoleKeyFor,
gymRoleKeys,
gymRoleLabel,
hasGymRoleKey,
isGymOwner,
} from '../../src/lib/gymPermissions.js';
import { GYM_PERMISSIONS, ROLE_KEYS } from '../../src/lib/permissions.js';
const grant = (key: string, permissions: string[]) => ({ role: { key, permissions } });
function prismaWithGrants(grants: ReturnType<typeof grant>[]) {
return {
userRoleGrant: { findMany: vi.fn().mockResolvedValue(grants) },
} as never;
}
describe('gymPermissionsFromGrants', () => {
it('merges permissions of all grants and drops unknown keys', () => {
const perms = gymPermissionsFromGrants([
grant(ROLE_KEYS.GYM_TRAINER, [GYM_PERMISSIONS.TRAINER_CLIENTS, 'users:read']),
grant('G_GYM_1234_RECEPCJA', [GYM_PERMISSIONS.GYM_CONTACT, GYM_PERMISSIONS.TRAINER_CLIENTS]),
]);
expect(perms).toEqual([GYM_PERMISSIONS.TRAINER_CLIENTS, GYM_PERMISSIONS.GYM_CONTACT]);
});
it('empty grants -> empty permissions', () => {
expect(gymPermissionsFromGrants([])).toEqual([]);
});
});
describe('canGym / gymRoleKeys / hasGymRoleKey', () => {
it('checks permission membership', () => {
expect(canGym([GYM_PERMISSIONS.GYM_STATS], GYM_PERMISSIONS.GYM_STATS)).toBe(true);
expect(canGym([GYM_PERMISSIONS.GYM_STATS], GYM_PERMISSIONS.GYM_DELETE)).toBe(false);
});
it('reads role keys from grants', () => {
const grants = [grant(ROLE_KEYS.GYM_OWNER, []), grant(ROLE_KEYS.GYM_TRAINER, [])];
expect(gymRoleKeys(grants)).toEqual([ROLE_KEYS.GYM_OWNER, ROLE_KEYS.GYM_TRAINER]);
expect(hasGymRoleKey(grants, ROLE_KEYS.GYM_TRAINER)).toBe(true);
expect(hasGymRoleKey(grants, 'OTHER')).toBe(false);
});
});
describe('deriveMembershipRoles', () => {
it('OWNER alone -> [OWNER] (legacy shape, no MEMBER)', () => {
expect(deriveMembershipRoles([ROLE_KEYS.GYM_OWNER], true)).toEqual(['OWNER']);
});
it('OWNER + TRAINER -> [OWNER, TRAINER]', () => {
expect(deriveMembershipRoles([ROLE_KEYS.GYM_OWNER, ROLE_KEYS.GYM_TRAINER], true)).toEqual([
'OWNER',
'TRAINER',
]);
});
it('TRAINER without owner -> [TRAINER, MEMBER]', () => {
expect(deriveMembershipRoles([ROLE_KEYS.GYM_TRAINER], true)).toEqual(['TRAINER', 'MEMBER']);
});
it('plain member -> [MEMBER]', () => {
expect(deriveMembershipRoles([], true)).toEqual(['MEMBER']);
});
it('not member, no grants -> []', () => {
expect(deriveMembershipRoles([], false)).toEqual([]);
});
});
describe('filterAssignableGymPermissions', () => {
it('keeps catalog keys and never allows gym:delegate', () => {
const out = filterAssignableGymPermissions([
GYM_PERMISSIONS.GYM_EDIT,
GYM_PERMISSIONS.GYM_DELEGATE,
'users:manage',
]);
expect(out).toEqual([GYM_PERMISSIONS.GYM_EDIT]);
});
});
describe('gymRoleKeyFor', () => {
it('builds ASCII slug with gym id suffix', () => {
const key = gymRoleKeyFor('Siłownia „Żółwik”', 'ckx1234abcd', 'Recepcja główna');
expect(key).toBe('G_SILOWNIA_ZOLWIK_abcd_RECEPCJA_GLOWNA');
expect(key.length).toBeLessThanOrEqual(40);
expect(key).toMatch(/^[A-Z0-9_]+$/i);
});
});
describe('gymRoleLabel', () => {
it('prefers custom name, falls back to key', () => {
expect(gymRoleLabel({ key: 'G_A_1_B', name: 'Recepcja' })).toBe('Recepcja');
expect(gymRoleLabel({ key: ROLE_KEYS.GYM_TRAINER, name: null })).toBe(ROLE_KEYS.GYM_TRAINER);
});
});
describe('isGymOwner / assertGymPermission / canInGym', () => {
const ownerGrants = [grant(ROLE_KEYS.GYM_OWNER, [GYM_PERMISSIONS.GYM_EDIT])];
it('isGymOwner true only with GYM_OWNER grant', async () => {
await expect(isGymOwner(prismaWithGrants(ownerGrants), 'u1', 'g1')).resolves.toBe(true);
await expect(
isGymOwner(prismaWithGrants([grant(ROLE_KEYS.GYM_TRAINER, [])]), 'u1', 'g1'),
).resolves.toBe(false);
});
it('assertGymPermission resolves via grants and admin override skips the query', async () => {
const prisma = prismaWithGrants([
grant('G_G_1_RECEPCJA', [GYM_PERMISSIONS.GYM_CONTACT]),
]);
await expect(
assertGymPermission(prisma, 'u1', 'g1', GYM_PERMISSIONS.GYM_CONTACT),
).resolves.toBeUndefined();
await expect(
assertGymPermission(prisma, 'u1', 'g1', GYM_PERMISSIONS.GYM_DELETE),
).rejects.toMatchObject({ status: 403 });
await expect(
assertGymPermission(prisma, 'u1', 'g1', GYM_PERMISSIONS.GYM_DELETE, true),
).resolves.toBeUndefined();
});
it('canInGym flag semantics', async () => {
const prisma = prismaWithGrants([grant(ROLE_KEYS.GYM_TRAINER, [GYM_PERMISSIONS.TRAINER_CLIENTS])]);
await expect(canInGym(prisma, 'u1', 'g1', GYM_PERMISSIONS.TRAINER_CLIENTS)).resolves.toBe(true);
await expect(canInGym(prisma, 'u1', 'g1', GYM_PERMISSIONS.GYM_STATS)).resolves.toBe(false);
await expect(canInGym(prisma, 'u1', 'g1', GYM_PERMISSIONS.GYM_STATS, true)).resolves.toBe(true);
});
});

View File

@@ -9,7 +9,27 @@ import {
import { PERMISSIONS } from '../../src/lib/permissions.js';
function mockPrisma() {
const tx = {
role: {
findMany: vi.fn().mockResolvedValue([
{ id: 'r-owner', key: 'GYM_OWNER' },
{ id: 'r-trainer', key: 'GYM_TRAINER' },
]),
},
userRoleGrant: {
findMany: vi.fn().mockResolvedValue([]),
create: vi.fn(),
delete: vi.fn(),
},
gymMembership: {
create: vi.fn(),
findUniqueOrThrow: vi.fn(),
},
user: { update: vi.fn() },
};
return {
$tx: tx,
$transaction: vi.fn(async (cb: (t: typeof tx) => unknown) => cb(tx)),
user: { findUnique: vi.fn(), count: vi.fn(), update: vi.fn(), delete: vi.fn() },
gym: { findUnique: vi.fn(), update: vi.fn(), delete: vi.fn() },
gymMembership: { findUnique: vi.fn(), create: vi.fn(), update: vi.fn(), delete: vi.fn() },
@@ -117,7 +137,7 @@ describe('updateMembership', () => {
});
});
it('sets the roles list of an existing membership', async () => {
it('replaces OWNER/TRAINER system grants and bumps tokenVersion', async () => {
const prisma = mockPrisma();
prisma.gymMembership.findUnique.mockResolvedValue({
id: 'm1',
@@ -125,18 +145,20 @@ describe('updateMembership', () => {
gymId: 'g1',
roles: ['MEMBER'],
});
prisma.gymMembership.update.mockResolvedValue({
prisma.$tx.gymMembership.findUniqueOrThrow.mockResolvedValue({
id: 'm1',
userId: 'u1',
gymId: 'g1',
roles: ['OWNER', 'TRAINER'],
});
const result = await updateMembership(prisma, 'u1', 'g1', ['OWNER', 'TRAINER']);
expect(result.membership).toMatchObject({ roles: ['OWNER', 'TRAINER'] });
expect(prisma.gymMembership.update).toHaveBeenCalledWith({
where: { userId_gymId: { userId: 'u1', gymId: 'g1' } },
data: { roles: ['OWNER', 'TRAINER'] },
expect(prisma.$tx.userRoleGrant.create).toHaveBeenCalledTimes(2);
expect(prisma.$tx.userRoleGrant.create).toHaveBeenCalledWith({
data: { userId: 'u1', roleId: 'r-owner', gymId: 'g1' },
});
expect(prisma.$tx.user.update).toHaveBeenCalledWith(
expect.objectContaining({ data: { tokenVersion: { increment: 1 } } }),
);
});
});