Backend: RBAC faza 2 M3 - endpointy ról gymowych dostępne dla delegata (gym:delegate z grantu ownera) zamiast tylko gyms:manage
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { Router } from 'express';
|
||||
import { Router, type Request } from 'express';
|
||||
import { z } from 'zod';
|
||||
import type { AppDeps } from '../deps.js';
|
||||
import { authenticate, requireAnyPermission, requirePermission } from '../middleware/auth.js';
|
||||
@@ -50,7 +50,7 @@ import {
|
||||
updateUser,
|
||||
} from '../services/admin.js';
|
||||
import { config } from '../config.js';
|
||||
import { notFound } from '../lib/errors.js';
|
||||
import { notFound, forbidden } from '../lib/errors.js';
|
||||
import {
|
||||
createFocusArea,
|
||||
deleteFocusArea,
|
||||
@@ -72,7 +72,8 @@ import {
|
||||
redactActivityLogResult,
|
||||
} from '../services/audit.js';
|
||||
import { asyncHandler } from '../lib/asyncHandler.js';
|
||||
import { PERMISSIONS, PERMISSION_KEYS } from '../lib/permissions.js';
|
||||
import { GYM_PERMISSIONS, PERMISSIONS, PERMISSION_KEYS } from '../lib/permissions.js';
|
||||
import { canGym, resolveGymPermissions } from '../lib/gymPermissions.js';
|
||||
import {
|
||||
assertNotStaffTarget,
|
||||
createGymRole,
|
||||
@@ -244,6 +245,19 @@ export function createAdminRoutes({ prisma }: AppDeps) {
|
||||
const guardStaffTarget = (userId: string, permissions: readonly string[]) =>
|
||||
assertNotStaffTarget(prisma, userId, permissions);
|
||||
|
||||
/**
|
||||
* Zarządzanie rolami w siłowni: nadzór platformowy (`gyms:manage`) albo
|
||||
* `gym:delegate` z grantów tej siłowni (RBAC faza 2 — właściciel zarządza
|
||||
* rolami członków przez te same endpointy co panel admina).
|
||||
*/
|
||||
const canManageRolesInGym = (gymParam = 'gymId') =>
|
||||
asyncHandler(async (req: Request, _res, next) => {
|
||||
if (req.user?.platformPermissions.includes(PERMISSIONS.GYMS_MANAGE)) return next();
|
||||
const perms = await resolveGymPermissions(prisma, req.user!.id, req.params[gymParam]);
|
||||
if (canGym(perms, GYM_PERMISSIONS.GYM_DELEGATE)) return next();
|
||||
return next(forbidden('Missing permission: gyms:manage or gym:delegate in this gym'));
|
||||
});
|
||||
|
||||
const listGymsQuerySchema = z.object({
|
||||
q: z.string().trim().max(200).optional(),
|
||||
kind: z.enum(['REAL', 'VIRTUAL']).optional(),
|
||||
@@ -448,7 +462,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
|
||||
* @openapi
|
||||
* /admin/gyms/{id}/members:
|
||||
* get:
|
||||
* summary: Members of one gym (gyms:manage). Query: q (imię/nazwisko/email), role (OWNER|TRAINER|MEMBER), limit (default 50, max 200), offset.
|
||||
* summary: Members of one gym (gyms:manage or gym:delegate in this gym). Query: q (imię/nazwisko/email), role (OWNER|TRAINER|MEMBER), limit (default 50, max 200), offset.
|
||||
* OWNER first, then by join date; each member carries roles, joinedAt, account status and `checkedInNow`.
|
||||
* tags: [Admin]
|
||||
* responses:
|
||||
@@ -457,7 +471,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
|
||||
*/
|
||||
router.get(
|
||||
'/gyms/:id/members',
|
||||
can(PERMISSIONS.GYMS_MANAGE),
|
||||
canManageRolesInGym('id'),
|
||||
validate(gymMembersQuerySchema, 'query'),
|
||||
asyncHandler(async (req, res) => {
|
||||
const q = req.query as z.infer<typeof gymMembersQuerySchema>;
|
||||
@@ -1533,14 +1547,14 @@ export function createAdminRoutes({ prisma }: AppDeps) {
|
||||
* @openapi
|
||||
* /admin/gyms/{gymId}/roles:
|
||||
* get:
|
||||
* summary: Role catalog for one gym (gyms:manage) — system gym roles + custom roles of that gym.
|
||||
* summary: Role catalog for one gym (gyms:manage or gym:delegate in this gym) — system gym roles + custom roles of that gym.
|
||||
* tags: [Admin]
|
||||
* responses:
|
||||
* 200: { description: OK, returns { roles: [{ id, key, name, permissions, isSystem, grantCount }] } }
|
||||
*/
|
||||
router.get(
|
||||
'/gyms/:gymId/roles',
|
||||
can(PERMISSIONS.GYMS_MANAGE),
|
||||
canManageRolesInGym(),
|
||||
asyncHandler(async (req, res) => {
|
||||
const result = await listGymRoles(prisma, req.params.gymId);
|
||||
res.json(result);
|
||||
@@ -1551,7 +1565,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
|
||||
* @openapi
|
||||
* /admin/gyms/{gymId}/roles:
|
||||
* post:
|
||||
* summary: Create a custom role for one gym (gyms:manage). Klucz generowany serwerowo;
|
||||
* summary: Create a custom role for one gym (gyms:manage or gym:delegate in this gym). Klucz generowany serwerowo;
|
||||
* klucze spoza katalogu gym i `gym:delegate` odrzucane.
|
||||
* tags: [Admin]
|
||||
* responses:
|
||||
@@ -1561,7 +1575,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
|
||||
*/
|
||||
router.post(
|
||||
'/gyms/:gymId/roles',
|
||||
can(PERMISSIONS.GYMS_MANAGE),
|
||||
canManageRolesInGym(),
|
||||
validate(gymRoleSchema),
|
||||
asyncHandler(async (req, res) => {
|
||||
const data = req.body as z.infer<typeof gymRoleSchema>;
|
||||
@@ -1585,7 +1599,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
|
||||
* @openapi
|
||||
* /admin/gyms/{gymId}/roles/{roleId}:
|
||||
* patch:
|
||||
* summary: Edit a custom gym role (gyms:manage). System roles: read-only.
|
||||
* summary: Edit a custom gym role (gyms:manage or gym:delegate in this gym). System roles: read-only.
|
||||
* tags: [Admin]
|
||||
* responses:
|
||||
* 200: { description: OK }
|
||||
@@ -1595,7 +1609,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
|
||||
*/
|
||||
router.patch(
|
||||
'/gyms/:gymId/roles/:roleId',
|
||||
can(PERMISSIONS.GYMS_MANAGE),
|
||||
canManageRolesInGym(),
|
||||
validate(gymRoleSchema.partial()),
|
||||
asyncHandler(async (req, res) => {
|
||||
const data = req.body as Partial<z.infer<typeof gymRoleSchema>>;
|
||||
@@ -1615,7 +1629,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
|
||||
* @openapi
|
||||
* /admin/gyms/{gymId}/roles/{roleId}:
|
||||
* delete:
|
||||
* summary: Delete a custom gym role (gyms:manage). System roles nieusuwalne; rola z grantami → 409.
|
||||
* summary: Delete a custom gym role (gyms:manage or gym:delegate in this gym). System roles nieusuwalne; rola z grantami → 409.
|
||||
* tags: [Admin]
|
||||
* responses:
|
||||
* 204: { description: Deleted }
|
||||
@@ -1625,7 +1639,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
|
||||
*/
|
||||
router.delete(
|
||||
'/gyms/:gymId/roles/:roleId',
|
||||
can(PERMISSIONS.GYMS_MANAGE),
|
||||
canManageRolesInGym(),
|
||||
asyncHandler(async (req, res) => {
|
||||
const result = await deleteGymRole(prisma, req.params.gymId, req.params.roleId);
|
||||
await logActivity(prisma, {
|
||||
@@ -1645,7 +1659,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
|
||||
* @openapi
|
||||
* /admin/gyms/{gymId}/members/{userId}/roles:
|
||||
* put:
|
||||
* summary: Replace the gym role grants of a member (gyms:manage). GYM_OWNER tylko z panelu admina;
|
||||
* summary: Replace the gym role grants of a member (gyms:manage or gym:delegate in this gym). GYM_OWNER tylko z panelu admina;
|
||||
* zmiana podbija tokenVersion.
|
||||
* tags: [Admin]
|
||||
* responses:
|
||||
@@ -1656,7 +1670,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
|
||||
*/
|
||||
router.put(
|
||||
'/gyms/:gymId/members/:userId/roles',
|
||||
can(PERMISSIONS.GYMS_MANAGE),
|
||||
canManageRolesInGym(),
|
||||
validate(memberGymRolesSchema),
|
||||
asyncHandler(async (req, res) => {
|
||||
const { roleKeys } = req.body as z.infer<typeof memberGymRolesSchema>;
|
||||
|
||||
@@ -2,7 +2,9 @@ import { describe, it, expect, beforeAll } from 'vitest';
|
||||
import { prisma } from '../../src/lib/prisma.js';
|
||||
import {
|
||||
buildApp,
|
||||
createMembership,
|
||||
createUser,
|
||||
createUserWithToken,
|
||||
grantGymRole,
|
||||
loginViaApi,
|
||||
rand,
|
||||
@@ -1225,3 +1227,95 @@ describe('admin: historia konta (GET /admin/users/:id/activity)', () => {
|
||||
expect(res.body.logs.every((l: { entityId: string }) => l.entityId === b.id)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('gym role endpoints dla delegata (GYM_OWNER bez ról platformowych)', () => {
|
||||
it('owner czyta katalog i członków, tworzy custom rolę i przypisuje granty; member 403; GYM_OWNER nienaruszalny', async () => {
|
||||
const app = buildApp();
|
||||
const suffix = rand();
|
||||
const gym = await prisma.gym.create({
|
||||
data: { name: `Delegat ${suffix}`, location: 'Kraków' },
|
||||
});
|
||||
const owner = await createUserWithToken();
|
||||
const member = await createUserWithToken();
|
||||
await createMembership(owner.user.id, gym.id, []);
|
||||
await grantGymRole(owner.user.id, gym.id, 'GYM_OWNER');
|
||||
await createMembership(member.user.id, gym.id, []);
|
||||
const ownerAuth = { Authorization: `Bearer ${owner.token}` };
|
||||
const memberAuth = { Authorization: `Bearer ${member.token}` };
|
||||
|
||||
// katalog ról siłowni: delegat 200, członek 403
|
||||
let res = await app.get(`/api/v1/admin/gyms/${gym.id}/roles`).set(ownerAuth);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.roles.map((r: { key: string }) => r.key)).toContain('GYM_OWNER');
|
||||
res = await app.get(`/api/v1/admin/gyms/${gym.id}/roles`).set(memberAuth);
|
||||
expect(res.status).toBe(403);
|
||||
|
||||
// lista członków z roleKeys: delegat 200
|
||||
res = await app.get(`/api/v1/admin/gyms/${gym.id}/members`).set(ownerAuth);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.members.map((m: { user: { id: string } }) => m.user.id)).toContain(
|
||||
member.user.id,
|
||||
);
|
||||
|
||||
// członek bez uprawnień nie nada sobie nic (przed jakąkolwiek zmianą jego tokenów)
|
||||
res = await app
|
||||
.put(`/api/v1/admin/gyms/${gym.id}/members/${member.user.id}/roles`)
|
||||
.set(memberAuth)
|
||||
.send({ roleKeys: ['GYM_TRAINER'] });
|
||||
expect(res.status).toBe(403);
|
||||
|
||||
// rola custom bez gym:delegate (przefiltrowany → puste uprawnienia → 400)
|
||||
res = await app
|
||||
.post(`/api/v1/admin/gyms/${gym.id}/roles`)
|
||||
.set(ownerAuth)
|
||||
.send({ name: 'Recepcja', permissions: ['gym:delegate'] });
|
||||
expect(res.status).toBe(400);
|
||||
|
||||
// utworzenie roli custom z katalogu gym
|
||||
res = await app
|
||||
.post(`/api/v1/admin/gyms/${gym.id}/roles`)
|
||||
.set(ownerAuth)
|
||||
.send({ name: `Recepcja ${suffix}`, permissions: ['gym:gallery'] });
|
||||
expect(res.status).toBe(201);
|
||||
const customKey: string = res.body.role.key;
|
||||
const customId: string = res.body.role.id;
|
||||
|
||||
// przydzielenie członkowi: custom + trener
|
||||
res = await app
|
||||
.put(`/api/v1/admin/gyms/${gym.id}/members/${member.user.id}/roles`)
|
||||
.set(ownerAuth)
|
||||
.send({ roleKeys: [customKey, 'GYM_TRAINER'] });
|
||||
expect(res.status).toBe(200);
|
||||
res = await app.get(`/api/v1/admin/gyms/${gym.id}/members`).set(ownerAuth);
|
||||
const row = res.body.members.find((m: { user: { id: string } }) => m.user.id === member.user.id);
|
||||
expect([...row.roleKeys].sort()).toEqual([...['GYM_TRAINER', customKey]].sort());
|
||||
|
||||
// delegat nie rusza grantów ownera ani nie nada GYM_OWNER
|
||||
res = await app
|
||||
.put(`/api/v1/admin/gyms/${gym.id}/members/${owner.user.id}/roles`)
|
||||
.set(ownerAuth)
|
||||
.send({ roleKeys: [] });
|
||||
expect(res.status).toBe(403);
|
||||
res = await app
|
||||
.put(`/api/v1/admin/gyms/${gym.id}/members/${member.user.id}/roles`)
|
||||
.set(ownerAuth)
|
||||
.send({ roleKeys: ['GYM_OWNER'] });
|
||||
expect(res.status).toBe(403);
|
||||
|
||||
// edycja/usunięcie własnej custom roli
|
||||
res = await app.delete(`/api/v1/admin/gyms/${gym.id}/roles/${customId}`).set(ownerAuth);
|
||||
expect(res.status).toBe(409);
|
||||
res = await app
|
||||
.post(`/api/v1/admin/gyms/${gym.id}/roles`)
|
||||
.set(ownerAuth)
|
||||
.send({ name: `Temp ${suffix}`, permissions: ['gym:equipment'] });
|
||||
const tempId: string = res.body.role.id;
|
||||
res = await app
|
||||
.patch(`/api/v1/admin/gyms/${gym.id}/roles/${tempId}`)
|
||||
.set(ownerAuth)
|
||||
.send({ name: `Temp2 ${suffix}` });
|
||||
expect(res.status).toBe(200);
|
||||
res = await app.delete(`/api/v1/admin/gyms/${gym.id}/roles/${tempId}`).set(ownerAuth);
|
||||
expect(res.status).toBe(204);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user