@@ -195,9 +240,11 @@ export default function Layout() {
user?.nickname ||
user?.email ||
'?';
+ const platformRoleNames = (user?.platformRoles ?? []).map((k) => t(`roles:names.${k}`, k));
const roles = [
- user?.isAdmin ? t('nav.roleAdmin') : null,
- isTrainer ? t('nav.roleTrainer') : t('nav.roleMember'),
+ ...platformRoleNames,
+ // bez ról platformowych widać kontekst siłowni; z rolami nie dodajemy "Ćwiczącego"
+ isTrainer ? t('nav.roleTrainer') : platformRoleNames.length ? null : t('nav.roleMember'),
]
.filter(Boolean)
.join(' · ');
diff --git a/admin/src/components/LogTable.tsx b/admin/src/components/LogTable.tsx
index 948e5b9..c804c7e 100644
--- a/admin/src/components/LogTable.tsx
+++ b/admin/src/components/LogTable.tsx
@@ -1,7 +1,7 @@
import type { ActivityLog } from '../api/types';
import { Badge, type BadgeColor } from './ui';
import i18n from '../i18n';
-import { fmtDate, fmtDateTime, fmtTime, maskEmail } from '../lib/format';
+import { fmtDate, fmtDateTime, fmtTime } from '../lib/format';
const t = (key: string, options?: Record
): string =>
String(i18n.t(`logs:${key}`, options as never));
@@ -27,7 +27,8 @@ export function formatLogDate(iso: string) {
export function actorName(log: ActivityLog) {
const { firstName, lastName, email } = log.actor;
- return [firstName, lastName].filter(Boolean).join(' ') || maskEmail(email);
+ // e-mail w actorze jest już zredagowany po stronie serwera (bez pii:read zamaskowany)
+ return [firstName, lastName].filter(Boolean).join(' ') || email;
}
/** Nazwa obiektu z szczegółów wpisu (tytuł planu, nazwa siłowni, nazwa obwodu). */
@@ -52,7 +53,6 @@ const HIDDEN_DETAIL_KEYS = new Set([
]);
function formatDetailValue(log: ActivityLog, key: string, value: unknown): string {
- if (key === 'email' && typeof value === 'string') return maskEmail(value);
if (Array.isArray(value)) return value.map((v) => String(v)).join(', ');
if (value && typeof value === 'object') {
return Object.entries(value)
@@ -123,7 +123,7 @@ export function LogTable({ logs }: { logs: ActivityLog[] }) {
{actorName(log)}
- {maskEmail(log.actor.email)}
+ {log.actor.email}
{log.actor.id}
diff --git a/admin/src/components/UserPicker.tsx b/admin/src/components/UserPicker.tsx
index a3f3f08..67a11a9 100644
--- a/admin/src/components/UserPicker.tsx
+++ b/admin/src/components/UserPicker.tsx
@@ -2,10 +2,9 @@ import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Search, X } from 'lucide-react';
import type { User } from '../api/types';
-import { maskEmail } from '../lib/format';
export function userLabel(u: User): string {
- return [u.firstName, u.lastName].filter(Boolean).join(' ') || maskEmail(u.email);
+ return [u.firstName, u.lastName].filter(Boolean).join(' ') || u.email;
}
/** Przeszukiwalny wybór użytkownika (listę pobiera strona) — wzór: GymPicker z członkostw. */
@@ -103,7 +102,7 @@ export function UserPicker({
>
{userLabel(u)}
{u.firstName && (
- {maskEmail(u.email)}
+ {u.email}
)}
))
diff --git a/admin/src/i18n/index.ts b/admin/src/i18n/index.ts
index 9373756..7ccb3ae 100644
--- a/admin/src/i18n/index.ts
+++ b/admin/src/i18n/index.ts
@@ -16,6 +16,7 @@ import plCatalog from './locales/pl/catalog.json';
import plLogs from './locales/pl/logs.json';
import plVerifications from './locales/pl/verifications.json';
import plAnnouncements from './locales/pl/announcements.json';
+import plRoles from './locales/pl/roles.json';
import enCommon from './locales/en/common.json';
import enAuth from './locales/en/auth.json';
import enErrors from './locales/en/errors.json';
@@ -26,6 +27,7 @@ import enCatalog from './locales/en/catalog.json';
import enLogs from './locales/en/logs.json';
import enVerifications from './locales/en/verifications.json';
import enAnnouncements from './locales/en/announcements.json';
+import enRoles from './locales/en/roles.json';
export const NAMESPACES = [
'common',
@@ -38,6 +40,7 @@ export const NAMESPACES = [
'logs',
'verifications',
'announcements',
+ 'roles',
] as const;
export type Namespace = (typeof NAMESPACES)[number];
@@ -53,6 +56,7 @@ const resources = {
logs: plLogs,
verifications: plVerifications,
announcements: plAnnouncements,
+ roles: plRoles,
},
en: {
common: enCommon,
@@ -65,6 +69,7 @@ const resources = {
logs: enLogs,
verifications: enVerifications,
announcements: enAnnouncements,
+ roles: enRoles,
},
} as const;
diff --git a/admin/src/i18n/locales/en/auth.json b/admin/src/i18n/locales/en/auth.json
index 9d0b5e1..93a11c1 100644
--- a/admin/src/i18n/locales/en/auth.json
+++ b/admin/src/i18n/locales/en/auth.json
@@ -4,7 +4,7 @@
"rememberMe": "Remember me",
"login": "Log in",
"loginError": "Login error",
- "notAdmin": "Access restricted to administrators",
+ "notStaff": "This account has no access to the admin panel.",
"loginLoading": "Logging in…",
"invalidCredentials": "Invalid email or password.",
"sessionExpired": "Session expired — log in again.",
diff --git a/admin/src/i18n/locales/en/common.json b/admin/src/i18n/locales/en/common.json
index 0421250..e9486f3 100644
--- a/admin/src/i18n/locales/en/common.json
+++ b/admin/src/i18n/locales/en/common.json
@@ -32,6 +32,7 @@
"focusAreas": "Focus areas",
"logs": "Logs",
"verifications": "Verifications",
+ "roles": "Roles",
"management": "Management",
"dictionaries": "Dictionaries",
"system": "System",
@@ -40,7 +41,6 @@
"mainNav": "Main navigation",
"expandMenu": "Expand menu",
"collapseMenu": "Collapse menu",
- "roleAdmin": "Admin",
"roleTrainer": "Trainer",
"roleMember": "Member",
"buildInfo": "build {{sha}} · {{time}}",
diff --git a/admin/src/i18n/locales/en/errors.json b/admin/src/i18n/locales/en/errors.json
index cb904d8..fdf6012 100644
--- a/admin/src/i18n/locales/en/errors.json
+++ b/admin/src/i18n/locales/en/errors.json
@@ -12,6 +12,9 @@
"ACCOUNT_SUSPENDED": "Account suspended.",
"ACCOUNT_SUSPENDED_until": "Account suspended until {{date}}.",
"ACCOUNT_BANNED": "Account blocked by an administrator.",
+ "STAFF_MUTATION_FORBIDDEN": "Only someone with the roles:manage permission can modify accounts holding a platform role.",
+ "LAST_ROLES_MANAGER": "This is the last account with roles:manage — it cannot be taken away.",
+ "PII_FORBIDDEN": "Missing pii:read permission — personal data is unavailable.",
"reasonSuffix": " Reason: {{reason}}",
"loginFailed": "Login failed",
"saveFailed": "Failed to save",
diff --git a/admin/src/i18n/locales/en/logs.json b/admin/src/i18n/locales/en/logs.json
index e0512ac..5b02629 100644
--- a/admin/src/i18n/locales/en/logs.json
+++ b/admin/src/i18n/locales/en/logs.json
@@ -24,7 +24,8 @@
"announcement": "Announcement",
"exercise": "Exercise",
"equipment": "Equipment",
- "focus_area": "Focus area"
+ "focus_area": "Focus area",
+ "role": "Platform role"
},
"details": {
"email": "e-mail",
@@ -64,7 +65,9 @@
"instanceId": "equipment instance",
"photoId": "photo",
"swappedWith": "swapped with",
- "type": "claim type"
+ "type": "claim type",
+ "key": "key",
+ "permissions": "permissions"
},
"actions": {
"user": {
@@ -75,6 +78,7 @@
"updated": "Account updated (admin)",
"status": { "changed": "Account status changed" },
"admin": { "changed": "Admin role changed" },
+ "roles": { "changed": "Platform roles changed" },
"password": { "changed": "Password changed" },
"deleted": "Account deleted"
},
@@ -182,6 +186,11 @@
"created": "Focus area created",
"updated": "Focus area updated",
"deleted": "Focus area deleted"
+ },
+ "role": {
+ "created": "Platform role created",
+ "updated": "Platform role updated",
+ "deleted": "Platform role deleted"
}
}
}
diff --git a/admin/src/i18n/locales/en/roles.json b/admin/src/i18n/locales/en/roles.json
new file mode 100644
index 0000000..16bf864
--- /dev/null
+++ b/admin/src/i18n/locales/en/roles.json
@@ -0,0 +1,37 @@
+{
+ "title": "Roles",
+ "intro": "Platform roles decide what is visible and allowed in the panel. Permission sets add up for people with multiple roles.",
+ "newRole": "New role",
+ "editRole": "Edit role",
+ "keyLabel": "Role key",
+ "systemBadge": "system",
+ "permsTitle": "Permissions",
+ "grantCount_one": "Assigned to {{count}} account",
+ "grantCount_few": "Assigned to {{count}} accounts",
+ "grantCount_many": "Assigned to {{count}} accounts",
+ "grantCount_other": "Assigned to {{count}} accounts",
+ "pinnedNote": "A system role always keeps roles:manage — without it the panel can be locked out for good.",
+ "deleteTitle": "Delete role?",
+ "deleteDesc": "Role “{{name}}” will be gone permanently. A role assigned to accounts cannot be removed.",
+ "deleteBlockedSystem": "System roles cannot be deleted.",
+ "deleteBlockedAssigned": "The role is assigned to accounts — unassign them first.",
+ "editAria": "Edit role {{name}}",
+ "removeAria": "Delete role {{name}}",
+ "emptyTitle": "No roles",
+ "emptyDesc": "Define the first platform role.",
+ "names": {
+ "ADMIN": "Administrator",
+ "MODERATOR": "Moderator"
+ },
+ "perms": {
+ "users_read": "View users",
+ "users_manage": "Manage accounts (edit, sanctions, passwords)",
+ "pii_read": "Personal data (full emails, phones, birth dates)",
+ "roles_manage": "Manage roles and permissions",
+ "catalog_manage": "Catalogs (exercises, equipment, focus areas)",
+ "gyms_manage": "Manage gyms",
+ "announcements_manage": "Announcements",
+ "verifications_view": "Review gym applications",
+ "logs_view": "Audit logs"
+ }
+}
diff --git a/admin/src/i18n/locales/en/users.json b/admin/src/i18n/locales/en/users.json
index 6228751..0a5b747 100644
--- a/admin/src/i18n/locales/en/users.json
+++ b/admin/src/i18n/locales/en/users.json
@@ -24,7 +24,7 @@
"ageWord": "age: {{age}}",
"statusSuspended": "Suspended",
"statusBanned": "Banned",
- "adminBadge": "Admin",
+ "staffLockedBadge": "Staff account — changes require roles:manage",
"gymsShort": "{{count}} gyms",
"noUsersTitle": "No users",
"noUsersDesc": "No users.",
@@ -69,7 +69,11 @@
"roleNoGym": "You cannot add someone to a gym without a role. Select a role for “{{name}}” or remove this row.",
"rolesNeedGym": "Roles ({{labels}}) require a selected gym. Choose a gym or clear the roles.",
"stepData": "Details",
- "stepRoles": "Roles",
+ "stepRoles": "Platform roles",
+ "gymRolesLabel": "Gym roles",
+ "platformRolesHint": "Tick roles; permissions add up. Changing roles logs that person out (re-login required).",
+ "noPlatformRoles": "No platform roles.",
+ "rolesNeedManageNote": "Changing platform roles requires the roles:manage permission.",
"firstName": "First name",
"lastName": "Last name",
"newPasswordOpt": "New password (optional)",
@@ -77,9 +81,6 @@
"repeatNewPassword": "Repeat new password",
"repeatPassword": "Repeat password",
"birthDate": "Date of birth",
- "adminPlatformTitle": "Platform administrator",
- "ariaShowAdmin": "Show admin permissions",
- "ariaHideAdmin": "Collapse admin permissions",
"noGymsYet": "No gyms yet",
"noGymsYetDesc": "Add the first gym and select a role — memberships are granted and changed in the wizard.",
"addFirstGym": "Add the first gym",
diff --git a/admin/src/i18n/locales/pl/auth.json b/admin/src/i18n/locales/pl/auth.json
index 5c5a742..c29bbab 100644
--- a/admin/src/i18n/locales/pl/auth.json
+++ b/admin/src/i18n/locales/pl/auth.json
@@ -4,7 +4,7 @@
"rememberMe": "Zapamiętaj mnie",
"login": "Zaloguj",
"loginError": "Błąd logowania",
- "notAdmin": "Dostęp tylko dla administratorów",
+ "notStaff": "To konto nie ma dostępu do panelu administracyjnego.",
"loginLoading": "Logowanie…",
"invalidCredentials": "Nieprawidłowy e-mail lub hasło.",
"sessionExpired": "Sesja wygasła — zaloguj się ponownie.",
diff --git a/admin/src/i18n/locales/pl/common.json b/admin/src/i18n/locales/pl/common.json
index ac6fcda..c6b3012 100644
--- a/admin/src/i18n/locales/pl/common.json
+++ b/admin/src/i18n/locales/pl/common.json
@@ -32,6 +32,7 @@
"focusAreas": "Obszary treningowe",
"logs": "Logi",
"verifications": "Weryfikacje",
+ "roles": "Role",
"management": "Zarządzanie",
"dictionaries": "Słowniki",
"system": "System",
@@ -40,7 +41,6 @@
"mainNav": "Nawigacja główna",
"expandMenu": "Rozwiń menu",
"collapseMenu": "Zwiń menu",
- "roleAdmin": "Admin",
"roleTrainer": "Trener",
"roleMember": "Ćwiczący",
"buildInfo": "wersja {{sha}} · {{time}}",
diff --git a/admin/src/i18n/locales/pl/errors.json b/admin/src/i18n/locales/pl/errors.json
index 6bffafe..d7bc94a 100644
--- a/admin/src/i18n/locales/pl/errors.json
+++ b/admin/src/i18n/locales/pl/errors.json
@@ -12,6 +12,9 @@
"ACCOUNT_SUSPENDED": "Konto zawieszone.",
"ACCOUNT_SUSPENDED_until": "Konto zawieszone do {{date}}.",
"ACCOUNT_BANNED": "Konto zablokowane przez administratora.",
+ "STAFF_MUTATION_FORBIDDEN": "Konta z rolą platformową może zmieniać tylko osoba z uprawnieniem roles:manage.",
+ "LAST_ROLES_MANAGER": "To ostatnia osoba z uprawnieniem roles:manage — nie można jej go odebrać.",
+ "PII_FORBIDDEN": "Brak uprawnienia pii:read — dane osobowe są niedostępne.",
"reasonSuffix": " Powód: {{reason}}",
"loginFailed": "Błąd logowania",
"saveFailed": "Błąd zapisu",
diff --git a/admin/src/i18n/locales/pl/logs.json b/admin/src/i18n/locales/pl/logs.json
index 16c90d0..cdb2401 100644
--- a/admin/src/i18n/locales/pl/logs.json
+++ b/admin/src/i18n/locales/pl/logs.json
@@ -24,7 +24,8 @@
"announcement": "Ogłoszenie",
"exercise": "Ćwiczenie",
"equipment": "Sprzęt",
- "focus_area": "Partia mięśniowa"
+ "focus_area": "Partia mięśniowa",
+ "role": "Rola platformowa"
},
"details": {
"email": "e-mail",
@@ -64,7 +65,9 @@
"instanceId": "instancja wyposażenia",
"photoId": "zdjęcie",
"swappedWith": "zamieniono z",
- "type": "rodzaj wniosku"
+ "type": "rodzaj wniosku",
+ "key": "klucz",
+ "permissions": "uprawnienia"
},
"actions": {
"user": {
@@ -75,6 +78,7 @@
"updated": "Konto zaktualizowane (admin)",
"status": { "changed": "Zmiana statusu konta" },
"admin": { "changed": "Zmiana roli administratora" },
+ "roles": { "changed": "Zmiana ról platformowych" },
"password": { "changed": "Zmiana hasła" },
"deleted": "Konto usunięte"
},
@@ -182,6 +186,11 @@
"created": "Partia utworzona",
"updated": "Partia zaktualizowana",
"deleted": "Partia usunięta"
+ },
+ "role": {
+ "created": "Rola platformowa utworzona",
+ "updated": "Rola platformowa zaktualizowana",
+ "deleted": "Rola platformowa usunięta"
}
}
}
diff --git a/admin/src/i18n/locales/pl/roles.json b/admin/src/i18n/locales/pl/roles.json
new file mode 100644
index 0000000..7dcb732
--- /dev/null
+++ b/admin/src/i18n/locales/pl/roles.json
@@ -0,0 +1,37 @@
+{
+ "title": "Role",
+ "intro": "Role platformowe decydują, co widać i wolno w panelu. Zestawy uprawnień sumują się dla osób z wieloma rolami.",
+ "newRole": "Nowa rola",
+ "editRole": "Edycja roli",
+ "keyLabel": "Klucz roli",
+ "systemBadge": "systemowa",
+ "permsTitle": "Uprawnienia",
+ "grantCount_one": "Przypisana do {{count}} konta",
+ "grantCount_few": "Przypisana do {{count}} kont",
+ "grantCount_many": "Przypisana do {{count}} kont",
+ "grantCount_other": "Przypisana do {{count}} konta",
+ "pinnedNote": "Rola systemowa zawsze zachowuje roles:manage — bez tego panel można zamknąć na zawsze.",
+ "deleteTitle": "Usunąć rolę?",
+ "deleteDesc": "Rola „{{name}}” zniknie na stałe. Nie da się usunąć roli przypisanej do kont.",
+ "deleteBlockedSystem": "Role systemowe są nieusuwalne.",
+ "deleteBlockedAssigned": "Rola jest przypisana do kont — najpierw je odznacz.",
+ "editAria": "Edytuj rolę {{name}}",
+ "removeAria": "Usuń rolę {{name}}",
+ "emptyTitle": "Brak ról",
+ "emptyDesc": "Zdefiniuj pierwszą rolę platformową.",
+ "names": {
+ "ADMIN": "Administrator",
+ "MODERATOR": "Moderator"
+ },
+ "perms": {
+ "users_read": "Podgląd użytkowników",
+ "users_manage": "Zarządzanie kontami (edycja, kary, hasła)",
+ "pii_read": "Dane osobowe (pełne e-maile, telefony, daty urodzeń)",
+ "roles_manage": "Zarządzanie rolami i uprawnieniami",
+ "catalog_manage": "Słowniki (ćwiczenia, urządzenia, partie)",
+ "gyms_manage": "Zarządzanie siłowniami",
+ "announcements_manage": "Ogłoszenia",
+ "verifications_view": "Weryfikacje wniosków o siłownie",
+ "logs_view": "Logi audytu"
+ }
+}
diff --git a/admin/src/i18n/locales/pl/users.json b/admin/src/i18n/locales/pl/users.json
index 87193ea..1b06492 100644
--- a/admin/src/i18n/locales/pl/users.json
+++ b/admin/src/i18n/locales/pl/users.json
@@ -24,7 +24,7 @@
"ageWord": "wiek: {{age}}",
"statusSuspended": "Zawieszone",
"statusBanned": "Zablokowane",
- "adminBadge": "Admin",
+ "staffLockedBadge": "Konto personelu — zmiana wymaga roles:manage",
"gymsShort": "{{count}} sił.",
"noUsersTitle": "Brak użytkowników",
"noUsersDesc": "Brak użytkowników.",
@@ -69,7 +69,11 @@
"roleNoGym": "Nie wolno dodać kogoś do siłowni bez roli. Zaznacz rolę dla „{{name}}” albo usuń ten wiersz.",
"rolesNeedGym": "Role ({{labels}}) wymagają wybranej siłowni. Wybierz siłownię albo odznacz role.",
"stepData": "Dane",
- "stepRoles": "Role",
+ "stepRoles": "Role platformowe",
+ "gymRolesLabel": "Role w siłowni",
+ "platformRolesHint": "Zaznacz role; uprawnienia sumują się. Zmiana ról wygasa sesje tej osoby (wymaga ponownego logowania).",
+ "noPlatformRoles": "Brak ról platformowych.",
+ "rolesNeedManageNote": "Zmiana ról platformowych wymaga uprawnienia roles:manage.",
"firstName": "Imię",
"lastName": "Nazwisko",
"newPasswordOpt": "Nowe hasło (opcjonalnie)",
@@ -77,9 +81,6 @@
"repeatNewPassword": "Powtórz nowe hasło",
"repeatPassword": "Powtórz hasło",
"birthDate": "Data urodzenia",
- "adminPlatformTitle": "Administrator platformy",
- "ariaShowAdmin": "Pokaż uprawnienia admina",
- "ariaHideAdmin": "Zwiń uprawnienia admina",
"noGymsYet": "Jeszcze bez siłowni",
"noGymsYetDesc": "Dodaj pierwszą siłownię i zaznacz rolę — członkostwa nadajesz w kreatorze albo w konsoli siłowni.",
"addFirstGym": "Dodaj pierwszą siłownię",
diff --git a/admin/src/lib/format.ts b/admin/src/lib/format.ts
index 4913831..e71ef2b 100644
--- a/admin/src/lib/format.ts
+++ b/admin/src/lib/format.ts
@@ -16,26 +16,9 @@ export function displayName(
}
/**
- * Maska adresu e-mail do wyświetlania w panelu admina: pierwsza i ostatnia litera
- * local part, pierwsza litera domeny i TLD — reszta jako gwiazdki (np. jan@fitos.pl → j*n@f****.pl).
+ * Maska e-maila mieszka po stronie API (lib/permissions.ts) — panel renderuje
+ * dokładnie to, co zwraca serwer (bez pii:read przychodzi już zamaskowany).
*/
-export function maskEmail(email: string | null | undefined): string {
- if (!email) return '—';
- const at = email.indexOf('@');
- if (at < 1) return '*';
- const local = email.slice(0, at);
- const localMask =
- local.length <= 2
- ? `${local.slice(0, 1)}${'*'.repeat(Math.max(local.length - 1, 1))}`
- : `${local.slice(0, 1)}${'*'.repeat(local.length - 2)}${local.slice(-1)}`;
- const domain = email.slice(at + 1);
- const dot = domain.indexOf('.');
- const firstLabel = dot < 0 ? domain : domain.slice(0, dot);
- const rest = dot < 0 ? '' : domain.slice(dot);
- const domainMask = `${firstLabel.slice(0, 1)}${'*'.repeat(Math.max(firstLabel.length - 1, 1))}${rest}`;
- return `${localMask}@${domainMask}`;
-}
-
export function fmtDate(iso: string | null | undefined): string {
if (!iso) return '—';
return new Date(iso).toLocaleDateString(currentTag(), {
diff --git a/admin/src/pages/Roles.tsx b/admin/src/pages/Roles.tsx
new file mode 100644
index 0000000..f765180
--- /dev/null
+++ b/admin/src/pages/Roles.tsx
@@ -0,0 +1,260 @@
+import { useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useMutation, useQueryClient } from '@tanstack/react-query';
+import { KeyRound, Pencil, Plus, ShieldCheck, Trash2 } from 'lucide-react';
+import { api } from '../api/client';
+import type { PlatformRole } from '../api/types';
+import {
+ Badge,
+ Button,
+ Card,
+ ConfirmDialog,
+ EmptyState,
+ ErrorText,
+ Field,
+ Input,
+ Loading,
+ Modal,
+ Muted,
+} from '../components/ui';
+import { useTopbar } from '../topbar';
+import { usePermissionCatalog, usePlatformRoles } from './users/user-queries';
+
+/** Klucz i18n uprawnienia: dwukropek zastąpiony podkreśleniem (separatory i18next). */
+function permKey(perm: string): string {
+ return `perms.${perm.replace(':', '_')}`;
+}
+
+/**
+ * Role platformowe (RBAC): lista ról z zestawami uprawnień, kreator roli
+ * własnej, edycja (rola systemowa: klucz stały, roles:manage przypięty)
+ * i usuwanie tylko ról bez przypisań.
+ */
+export default function Roles() {
+ const { t } = useTranslation('roles');
+ const qc = useQueryClient();
+ const { data, isLoading, error } = usePlatformRoles();
+ const { data: catalog } = usePermissionCatalog();
+ const roles = data?.roles ?? [];
+ const allPerms = catalog?.permissions ?? [];
+
+ const [formOpen, setFormOpen] = useState(false);
+ const [editing, setEditing] = useState(null);
+ const [key, setKey] = useState('');
+ const [perms, setPerms] = useState([]);
+ const [formError, setFormError] = useState(null);
+ const [deleting, setDeleting] = useState(null);
+
+ const invalidate = () => {
+ qc.invalidateQueries({ queryKey: ['admin-roles'] });
+ qc.invalidateQueries({ queryKey: ['admin-users'] });
+ };
+
+ const save = useMutation({
+ mutationFn: async () => {
+ if (editing) {
+ await api(`/admin/roles/${editing.id}`, {
+ method: 'PATCH',
+ body: { name: key.trim().toUpperCase(), permissions: perms },
+ });
+ } else {
+ await api('/admin/roles', {
+ method: 'POST',
+ body: { key: key.trim().toUpperCase(), permissions: perms },
+ });
+ }
+ },
+ onSuccess: () => {
+ invalidate();
+ setFormOpen(false);
+ setEditing(null);
+ setFormError(null);
+ },
+ onError: (e) => setFormError((e as Error).message),
+ });
+
+ const remove = useMutation({
+ mutationFn: (id: string) => api(`/admin/roles/${id}`, { method: 'DELETE' }),
+ onSuccess: () => {
+ invalidate();
+ setDeleting(null);
+ },
+ onError: (e) => {
+ setDeleting(null);
+ setFormError((e as Error).message);
+ },
+ });
+
+ function openCreate() {
+ setEditing(null);
+ setKey('');
+ setPerms([]);
+ setFormError(null);
+ setFormOpen(true);
+ }
+
+ function openEdit(role: PlatformRole) {
+ setEditing(role);
+ setKey(role.key);
+ setPerms(role.permissions);
+ setFormError(null);
+ setFormOpen(true);
+ }
+
+ const toggle = (perm: string) =>
+ setPerms((ps) => (ps.includes(perm) ? ps.filter((p) => p !== perm) : [...ps, perm]));
+
+ useTopbar({
+ title: t('title'),
+ actions: [{ label: t('newRole'), onClick: openCreate, icon: Plus }],
+ });
+
+ const pinned = editing?.isSystem && perms.includes('roles:manage');
+
+ return (
+ <>
+ {t('intro')}
+
+ {isLoading && }
+ {error && (
+
+ {t('common:errorPrefix')}
+ {(error as Error).message}
+
+ )}
+
+ {formError && !formOpen && (
+
+ {formError}
+
+ )}
+
+
+ {roles.map((r) => (
+
+
+
+
+
+ {t(`names.${r.key}`, { defaultValue: r.key })}
+
+ {r.isSystem && {t('systemBadge')}}
+
+ {r.key}
+
+ {r.permissions.map((p) => (
+
+ {t(permKey(p), { defaultValue: p })}
+
+ ))}
+
+
+
+
+
+
+
+
+ {t('grantCount', { count: r.grantCount })}
+
+
+ ))}
+
+
+ {!isLoading && !error && roles.length === 0 && (
+
+
+
+ )}
+
+ setFormOpen(false)}
+ title={editing ? t('editRole') : t('newRole')}
+ >
+
+
+ setKey(e.target.value.toUpperCase())}
+ placeholder="EX. SUPPORT"
+ className="font-mono"
+ />
+
+
+
+ {t('permsTitle')}
+
+
+ {allPerms.map((p) => (
+
+ ))}
+
+ {pinned && {t('pinnedNote')} }
+
+ {formError && {formError}}
+
+
+
+
+
+
+
+ setDeleting(null)}
+ onConfirm={() => deleting && remove.mutate(deleting.id)}
+ title={t('deleteTitle')}
+ description={t('deleteDesc', { name: deleting?.key })}
+ confirmLabel={t('common:remove')}
+ danger
+ busy={remove.isPending}
+ />
+ >
+ );
+}
diff --git a/admin/src/pages/Verifications.tsx b/admin/src/pages/Verifications.tsx
index 7a6ee09..cfbbd46 100644
--- a/admin/src/pages/Verifications.tsx
+++ b/admin/src/pages/Verifications.tsx
@@ -25,7 +25,7 @@ import {
import type { BadgeColor } from '../components/ui';
import { Avatar } from '../components/Avatar';
import { formatAvailability } from '../lib/availability';
-import { fmtDate, maskEmail } from '../lib/format';
+import { fmtDate } from '../lib/format';
import i18n from '../i18n';
import { useTopbar } from '../topbar';
@@ -48,7 +48,7 @@ function claimTypeLabel(claim: GymClaim) {
function applicantName(claim: GymClaim) {
const { firstName, lastName, email } = claim.user;
- return [firstName, lastName].filter(Boolean).join(' ') || maskEmail(email);
+ return [firstName, lastName].filter(Boolean).join(' ') || email;
}
/** Pobranie pliku przez `apiBlob` (Bearer + rotacja 401) → tymczasowy . */
@@ -285,7 +285,7 @@ export function VerificationDetail() {
{claim.companyName || '—'}
{claim.nip || '—'}
{claim.phone || '—'}
- {claim.email ? maskEmail(claim.email) : '—'}
+ {claim.email || '—'}
@@ -298,7 +298,7 @@ export function VerificationDetail() {
{applicantName(claim)}
- {maskEmail(claim.user.email)}
+ {claim.user.email}
{claim.user.phone != null && (
{claim.user.phone}
)}
diff --git a/admin/src/pages/gyms/GymDetail.tsx b/admin/src/pages/gyms/GymDetail.tsx
index 8fe7f1b..27a0a3e 100644
--- a/admin/src/pages/gyms/GymDetail.tsx
+++ b/admin/src/pages/gyms/GymDetail.tsx
@@ -33,7 +33,7 @@ import {
} from '../../components/ui';
import { AvailabilityEditor } from '../../components/AvailabilityEditor';
import { dayFull, formatDayRangeClock, normalizeAvailability } from '../../lib/availability';
-import { fmtDate, fmtDateTime, maskEmail } from '../../lib/format';
+import { fmtDate, fmtDateTime } from '../../lib/format';
import { GYM_ROLE_META, GYM_ROLE_ORDER } from '../../lib/roles';
import { useAdminUsers } from '../users/user-queries';
import { useGymAuditLogs, useGymMembers, useGymRelated } from '../../api/queries';
@@ -74,13 +74,13 @@ function memberLabel(m: AdminGymMemberItem): string {
return personName(m.user);
}
-/* Nazwa osoby; fallback na zamaskowany e-mail. */
+/* Nazwa osoby; fallback na e-mail (redagowany po stronie serwera). */
function personName(p: {
firstName?: string | null;
lastName?: string | null;
email: string;
}): string {
- return [p.firstName, p.lastName].filter(Boolean).join(' ') || maskEmail(p.email);
+ return [p.firstName, p.lastName].filter(Boolean).join(' ') || p.email;
}
/* Rola jako pigułki — te same etykiety co na członkostwach usera. */
@@ -132,7 +132,7 @@ function MembersTable({
>
{memberLabel(m)}
- {maskEmail(m.user.email)}
+ {m.user.email}
|
diff --git a/admin/src/pages/gyms/GymsList.tsx b/admin/src/pages/gyms/GymsList.tsx
index 502a2aa..3b2bbd9 100644
--- a/admin/src/pages/gyms/GymsList.tsx
+++ b/admin/src/pages/gyms/GymsList.tsx
@@ -8,10 +8,10 @@ import { Badge, Card, EmptyState, ErrorText, Loading, Select } from '../../compo
import { formatDayRangeClock, normalizeAvailability } from '../../lib/availability';
import { useListSearch } from '../../store/list-search';
import { useTopbar } from '../../topbar';
-import { fmtDate, maskEmail } from '../../lib/format';
+import { fmtDate } from '../../lib/format';
function ownerLabel(o: AdminGymListItem['owners'][number]): string {
- return [o.firstName, o.lastName].filter(Boolean).join(' ') || maskEmail(o.email);
+ return [o.firstName, o.lastName].filter(Boolean).join(' ') || o.email;
}
/* Wiersz listy — klik na całej szerokości prowadzi do konsoli siłowni w panelu admina;
diff --git a/admin/src/pages/users/UserDetail.tsx b/admin/src/pages/users/UserDetail.tsx
index 0af3b91..7285d28 100644
--- a/admin/src/pages/users/UserDetail.tsx
+++ b/admin/src/pages/users/UserDetail.tsx
@@ -28,7 +28,7 @@ import {
Loading,
StatCell,
} from '../../components/ui';
-import { fmtDate, fmtDateTime, displayName, maskEmail } from '../../lib/format';
+import { fmtDate, fmtDateTime, displayName } from '../../lib/format';
import {
detailsText,
actionLabel,
@@ -37,18 +37,19 @@ import {
actionColor,
} from '../../components/LogTable';
import { GYM_ROLE_META, GYM_ROLE_ORDER } from '../../lib/roles';
+import { cn } from '../../lib/utils';
import { UserRestrictionModal } from './UserRestrictionModal';
import { useAdminUser, useUserActivity, useUserClaims } from './user-queries';
import { useAuth } from '../../store/auth';
-/** Nazwa wyświetlana użytkownika (nick → imię+nazwisko → zamaskowany e-mail). */
+/** Nazwa wyświetlana użytkownika (nick → imię+nazwisko → e-mail; serwer już go maskuje bez pii:read). */
export function userDisplayName(u: {
nickname?: string | null;
firstName?: string | null;
lastName?: string | null;
email: string;
}): string {
- return displayName(u) === '—' ? maskEmail(u.email) : displayName(u);
+ return displayName(u) === '—' ? u.email : displayName(u);
}
/* Rola jako pigułki — te same etykiety co w konsoli siłowni. */
@@ -78,8 +79,12 @@ export default function UserDetail() {
const navigate = useNavigate();
const queryClient = useQueryClient();
const { user, isLoading, error } = useAdminUser(id);
- const { data: claimsData } = useUserClaims(id);
- const { data: activityData } = useUserActivity(id, 10);
+ const perms = me?.permissions ?? [];
+ const canRoles = perms.includes('roles:manage');
+ const canVerify = perms.includes('verifications:view');
+ const canLogs = perms.includes('logs:view');
+ const { data: claimsData } = useUserClaims(canVerify ? id : undefined);
+ const { data: activityData } = useUserActivity(canLogs ? id : undefined, 10);
const [confirmOpen, setConfirmOpen] = useState(false);
const [busy, setBusy] = useState(false);
const [removeError, setRemoveError] = useState('');
@@ -88,23 +93,28 @@ export default function UserDetail() {
null,
);
+ // Konto z rolą platformową (staff) wolno ruszać tylko posiadaczowi roles:manage.
+ const staffLocked = (user?.platformRoles?.length ?? 0) > 0 && !canRoles;
+
// Menu trzyma tylko akcje (edycja/logi/kary/usunięcie); resztą admin zarządza w treści.
useTopbar({
title: t('consoleTitle'),
back: '/users',
actions: user
- ? [
- { label: t('common:edit'), icon: Pencil, to: `/users/${user.id}/edit` },
- { label: t('logsAction'), icon: ScrollText, to: `/users/${user.id}/logs` },
- { label: t('suspend'), icon: Pause, onClick: () => setRestriction('SUSPENDED') },
- {
- label: t('ban'),
- icon: Ban,
- variant: 'danger',
- onClick: () => setRestriction('BANNED'),
- },
- { label: t('common:remove'), variant: 'danger', onClick: () => setConfirmOpen(true) },
- ]
+ ? staffLocked
+ ? [{ label: t('logsAction'), icon: ScrollText, to: `/users/${user.id}/logs` }]
+ : [
+ { label: t('common:edit'), icon: Pencil, to: `/users/${user.id}/edit` },
+ { label: t('logsAction'), icon: ScrollText, to: `/users/${user.id}/logs` },
+ { label: t('suspend'), icon: Pause, onClick: () => setRestriction('SUSPENDED') },
+ {
+ label: t('ban'),
+ icon: Ban,
+ variant: 'danger',
+ onClick: () => setRestriction('BANNED'),
+ },
+ { label: t('common:remove'), variant: 'danger', onClick: () => setConfirmOpen(true) },
+ ]
: [],
});
@@ -134,8 +144,8 @@ export default function UserDetail() {
const invalidateUsers = () => queryClient.invalidateQueries({ queryKey: ['admin-users'] });
const name = userDisplayName(user);
- // właściciel konta widzi swój e-mail w pełnej formie; dla innych — maska
- const emailShown = user.id === me?.id ? user.email : maskEmail(user.email);
+ // serwer redaguje e-mail wg uprawnień widza (bez pii:read przychodzi zamaskowany)
+ const emailShown = user.email;
const memberships = user.memberships ?? [];
const claims = claimsData?.claims ?? [];
const logs = activityData?.logs ?? [];
@@ -169,11 +179,22 @@ export default function UserDetail() {
{`${t('reasonPrefix')}${user.restrictionReason}`}
)}
{user.nickname && @{user.nickname}}
- {user.isAdmin && {t('adminBadge')}}
+ {user.platformRoles.map((r) => (
+
+ {t(`roles:names.${r}`, { defaultValue: r })}
+
+ ))}
+ {staffLocked && {t('staffLockedBadge')}}
{t('createdOn', { date: fmtDate(user.createdAt) })}
-
+
}
/>
- }
- />
+ {canVerify && (
+ }
+ />
+ )}
(
- setManage({ gymId: m.gymId, gymName: m.gym.name, roles: m.roles })
+ onClick={
+ staffLocked
+ ? undefined
+ : () =>
+ setManage({ gymId: m.gymId, gymName: m.gym.name, roles: m.roles })
}
- className="cursor-pointer border-b border-line/60 transition-colors last:border-b-0 hover:bg-line/20"
+ className={cn(
+ 'border-b border-line/60 transition-colors last:border-b-0',
+ !staffLocked && 'cursor-pointer hover:bg-line/20',
+ )}
>
|
{m.gym.name}
@@ -250,81 +279,85 @@ export default function UserDetail() {
{/* LOGI KONTA: ostatnie 10 + przejście do pełnej podstrony (jak logi w konsoli siłowni) */}
-
-
- {t('logsCardTitle')}
-
- {t('allLogs')}
-
-
- {logs.length === 0 ? (
- {t('noActivity')}
- ) : (
-
- {logs.map((log) => {
- const details = detailsText(log);
- return (
-
-
- {formatLogDate(log.createdAt)}
-
- {actionLabel(log.action)}
-
- {t('byActor', { actor: actorName(log) })}
-
- {details && {details}}
-
- );
- })}
+ {canLogs && (
+
+
+ {t('logsCardTitle')}
+
+ {t('allLogs')}
+
- )}
-
+ {logs.length === 0 ? (
+ {t('noActivity')}
+ ) : (
+
+ {logs.map((log) => {
+ const details = detailsText(log);
+ return (
+
+
+ {formatLogDate(log.createdAt)}
+
+ {actionLabel(log.action)}
+
+ {t('byActor', { actor: actorName(log) })}
+
+ {details && {details}}
+
+ );
+ })}
+
+ )}
+
+ )}
diff --git a/admin/src/pages/users/UserForm.tsx b/admin/src/pages/users/UserForm.tsx
index f0fbea8..ed755c7 100644
--- a/admin/src/pages/users/UserForm.tsx
+++ b/admin/src/pages/users/UserForm.tsx
@@ -1,12 +1,12 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
-import { Building2, Check, ChevronDown, ShieldCheck, Trash2, UserPlus } from 'lucide-react';
+import { Building2, Check, ShieldCheck, Trash2, UserPlus } from 'lucide-react';
import { api } from '../../api/client';
import { apiErrorMessage } from '../../lib/errors';
-import type { Gym, GymRole, User } from '../../api/types';
-import { ADMIN_ROLE_META, GYM_ROLE_META } from '../../lib/roles';
-import { todayStr, maskEmail } from '../../lib/format';
+import type { Gym, GymRole } from '../../api/types';
+import { GYM_ROLE_META } from '../../lib/roles';
+import { todayStr } from '../../lib/format';
import { GymPicker } from '../../components/GymPicker';
import { GymRolePicker } from '../../components/GymRolePicker';
import {
@@ -23,7 +23,7 @@ import {
Modal,
} from '../../components/ui';
import { useTopbar } from '../../topbar';
-import { useAdminUser, useUserGyms } from './user-queries';
+import { useAdminUser, usePlatformRoles, useUserGyms } from './user-queries';
import { useAuth } from '../../store/auth';
/** Wiersz członkostwa w formularzu: tymczasowy klucz + wybrana siłownia + role. */
@@ -38,24 +38,10 @@ interface MembershipRow {
let rowSeq = 0;
const nextKey = () => ++rowSeq;
-/** Wyjaśnienie roli administratora — rozwijane, żeby nie zaśmiecać formularza. */
-function AdminExplain({ open, items }: { open: boolean; items: string[] }) {
- if (!open) return null;
- return (
-
- {items.map((g) => (
- -
- •
- {g}
-
- ))}
-
- );
-}
-
/**
* Kreator tworzenia/edycji użytkownika — jedyne miejsce edycji danych i członkostw.
- * Tworzenie: dane + role + członkostwa (POST-y po utworzeniu konta).
+ * Tworzenie: dane + członkostwa (POST-y po utworzeniu konta); role platformowe
+ * nadaje się tylko z uprawnieniem roles:manage (PUT /users/:id/roles).
* Edycja: PATCH konta + porządkowanie członkostw (POST/PATCH/DELETE wg zmian);
* strona „Członkostwa w siłowniach" jest tylko do odczytu, a kary (zawieszenie/ban)
* nadaje się z menu kontekstowego strony użytkownika (UserRestrictionModal).
@@ -63,11 +49,14 @@ function AdminExplain({ open, items }: { open: boolean; items: string[] }) {
export default function UserForm() {
const { t } = useTranslation('users');
const me = useAuth((s) => s.user);
+ const canRoles = me?.permissions?.includes('roles:manage') ?? false;
+ const canPii = me?.permissions?.includes('pii:read') ?? false;
const { id } = useParams();
const isEdit = Boolean(id);
const navigate = useNavigate();
const { user, isLoading } = useAdminUser(id);
const { data: gymsData } = useUserGyms();
+ const { data: rolesData } = usePlatformRoles(canRoles);
const formRef = useRef(null);
const [busy, setBusy] = useState(false);
@@ -93,6 +82,7 @@ export default function UserForm() {
});
const gyms: Gym[] = gymsData?.gyms ?? [];
+ const platformRoles = rolesData?.roles ?? [];
const [form, setForm] = useState({
firstName: '',
@@ -101,9 +91,8 @@ export default function UserForm() {
password2: '',
email: '',
birthDate: '',
- isAdmin: false,
});
- const [adminExplain, setAdminExplain] = useState(false);
+ const [roleKeys, setRoleKeys] = useState([]);
// domyślnie zero wierszy — pierwszą siłownię dodaje admin (mile widziana w stanie pustym)
const [rows, setRows] = useState([]);
const [error, setError] = useState('');
@@ -125,9 +114,9 @@ export default function UserForm() {
password: '',
password2: '',
email: user.email,
- birthDate: user.birthDate ? user.birthDate.slice(0, 10) : '',
- isAdmin: user.isAdmin,
+ birthDate: canPii && user.birthDate ? user.birthDate.slice(0, 10) : '',
});
+ setRoleKeys(user.platformRoles ?? []);
setRows(
(user.memberships ?? []).map((m) => ({
key: nextKey(),
@@ -136,7 +125,7 @@ export default function UserForm() {
existing: true,
})),
);
- }, [user]);
+ }, [user, canPii]);
// siłownie niedostępne w pozostałych wierszach (bez duplikatów w jednym formularzu)
const gymsFor = (rowKey: number): Gym[] => {
@@ -199,19 +188,24 @@ export default function UserForm() {
if (!isEdit) {
let createdId = createdIdRef.current;
if (!createdId) {
- const data = await api<{ user: User }>('/admin/users', {
+ const data = await api<{ user: { id: string } }>('/admin/users', {
method: 'POST',
body: {
email: form.email.trim(),
password: form.password,
firstName: form.firstName || undefined,
lastName: form.lastName || undefined,
- birthDate: form.birthDate || undefined,
- isAdmin: form.isAdmin,
+ birthDate: (canPii && form.birthDate) || undefined,
},
});
createdId = data.user.id;
createdIdRef.current = createdId;
+ if (roleKeys.length > 0) {
+ await api(`/admin/users/${createdId}/roles`, {
+ method: 'PUT',
+ body: { roles: roleKeys },
+ });
+ }
}
for (const r of rows.filter((x) => x.gymId)) {
if (doneGymIdsRef.current.has(r.gymId)) continue;
@@ -226,16 +220,25 @@ export default function UserForm() {
}
// EDYCJA: PATCH konta (tożsamość/dostęp), potem porządkowanie członkostw.
- // E-mail w edycji jest ukryty (zna go tylko user) — PATCH przenosi niezmieniony adres.
+ // Bez pii:read e-mail przychodzi zamaskowany, a data urodzenia jako null —
+ // tych pól nie wysyłamy w ogóle (serwer i tak ich nie przyjmie).
const patchBody: Record = {
- email: form.email.trim(),
firstName: form.firstName || null,
lastName: form.lastName || null,
- birthDate: form.birthDate || null,
- isAdmin: form.isAdmin,
};
+ if (canPii) {
+ patchBody.email = form.email.trim();
+ patchBody.birthDate = form.birthDate || null;
+ }
if (form.password) patchBody.password = form.password;
await api(`/admin/users/${id}`, { method: 'PATCH', body: patchBody });
+ const originalRoles = user?.platformRoles ?? [];
+ const rolesChanged =
+ roleKeys.length !== originalRoles.length ||
+ roleKeys.some((k) => !originalRoles.includes(k));
+ if (rolesChanged) {
+ await api(`/admin/users/${id}/roles`, { method: 'PUT', body: { roles: roleKeys } });
+ }
for (const gid of removedGymIds) {
await api(`/admin/users/${id}/memberships/${gid}`, { method: 'DELETE' });
@@ -319,10 +322,10 @@ export default function UserForm() {
/>
- {isEdit && id !== me?.id ? (
- // cudzy e-mail: zamaskowany i tylko do odczytu (zna go tylko właściciel);
- // PATCH poniżej przenosi niezmieniony, pełny adres z formularza
-
+ {isEdit && !canPii ? (
+ // cudzy e-mail bez pii:read: serwer wysyła go zamaskowanego, tylko do odczytu;
+ // PATCH poniżej w ogóle go nie wysyła
+
) : (
)}
-
- setForm({ ...form, birthDate: e.target.value })}
- />
-
+ {canPii && (
+
+ setForm({ ...form, birthDate: e.target.value })}
+ />
+
+ )}
- {/* Krok 2 — role w panelu */}
+ {/* Krok 2 — role platformowe */}
@@ -352,49 +357,59 @@ export default function UserForm() {
{t('stepRoles')}
- {/* Rola administratora platformy */}
-
-
-
-
+ {canRoles ? (
+
+ {t('platformRolesHint')}
+
+ {platformRoles.map((r) => (
+
+ ))}
+
- t(`common:${k}`))}
- />
-
+ ) : (
+
+ {isEdit && (user?.platformRoles?.length ?? 0) > 0 ? (
+
+ {(user?.platformRoles ?? []).map((k) => (
+
+ {t(`roles:names.${k}`, { defaultValue: k })}
+
+ ))}
+
+ ) : (
+ {t('noPlatformRoles')}
+ )}
+ {t('rolesNeedManageNote')}
+
+ )}
{/* Krok 3 — członkostwa w siłowniach (edytor: tworzenie POST, edycja POST/PATCH/DELETE) */}
- {isEdit ? 4 : 3}
+ 3
{t('membershipsTitle')}
@@ -443,7 +458,7 @@ export default function UserForm() {
/>
-
+
updateRow(r.key, { roles })}
diff --git a/admin/src/pages/users/UsersList.tsx b/admin/src/pages/users/UsersList.tsx
index b105a75..195f277 100644
--- a/admin/src/pages/users/UsersList.tsx
+++ b/admin/src/pages/users/UsersList.tsx
@@ -9,13 +9,11 @@ import { Badge, Card, EmptyState, ErrorText, ListRow, Loading } from '../../comp
import { Avatar } from '../../components/Avatar';
import { useListSearch } from '../../store/list-search';
import { useTopbar } from '../../topbar';
-import { useAuth } from '../../store/auth';
-import { ageFromBirthDate, fmtDate, maskEmail } from '../../lib/format';
+import { ageFromBirthDate, fmtDate } from '../../lib/format';
import { userDisplayName } from './UserDetail';
export default function UsersList() {
const { t } = useTranslation('users');
- const me = useAuth((s) => s.user);
useTopbar({
title: t('common:nav.users'),
search: 'users',
@@ -67,7 +65,7 @@ export default function UsersList() {
}
meta={
<>
- {u.id === me?.id ? u.email : maskEmail(u.email)}
+ {u.email}
{ageFromBirthDate(u.birthDate) != null
? ` · ${t('ageWord', { age: ageFromBirthDate(u.birthDate) })}`
: ''}
@@ -82,7 +80,11 @@ export default function UsersList() {
{t('statusSuspended')}
)}
{u.status === 'BANNED' && {t('statusBanned')}}
- {u.isAdmin && {t('adminBadge')}}
+ {u.platformRoles.map((r) => (
+
+ {t(`roles:names.${r}`, { defaultValue: r })}
+
+ ))}
{t('gymsShort', { count: u.memberships?.length ?? 0 })}
diff --git a/admin/src/pages/users/user-queries.ts b/admin/src/pages/users/user-queries.ts
index d4ba025..695c708 100644
--- a/admin/src/pages/users/user-queries.ts
+++ b/admin/src/pages/users/user-queries.ts
@@ -1,6 +1,23 @@
import { useQuery } from '@tanstack/react-query';
import { api } from '../../api/client';
-import type { ActivityLogPage, Gym, GymClaim, User } from '../../api/types';
+import type { ActivityLogPage, Gym, GymClaim, PlatformRole, User } from '../../api/types';
+
+/** Katalog kluczy uprawnień (edytor ról, wymaga roles:manage). */
+export function usePermissionCatalog(enabled = true) {
+ return useQuery({
+ queryKey: ['admin-permissions'],
+ queryFn: () => api<{ permissions: string[] }>('/admin/permissions'),
+ enabled,
+ });
+}
+
+export function usePlatformRoles(enabled = true) {
+ return useQuery({
+ queryKey: ['admin-roles'],
+ queryFn: () => api<{ roles: PlatformRole[] }>('/admin/roles'),
+ enabled,
+ });
+}
/** Lista użytkowników admina — wspólne źródło danych dla podstron /users/:id/*. */
export function useAdminUsers() {
diff --git a/admin/src/store/auth.ts b/admin/src/store/auth.ts
index 3eebfb2..073e286 100644
--- a/admin/src/store/auth.ts
+++ b/admin/src/store/auth.ts
@@ -32,9 +32,9 @@ export const useAuth = create((set) => ({
setAccessToken(null);
throw err;
}
- if (!data.user.isAdmin) {
+ if (!data.user.permissions?.length) {
setAccessToken(null);
- throw new Error(i18n.t('auth:notAdmin'));
+ throw new Error(i18n.t('auth:notStaff'));
}
setAccessToken(data.accessToken);
set({ user: data.user });
@@ -64,10 +64,12 @@ export const useAuth = create((set) => ({
const data = await refreshRes.json();
setAccessToken(data.accessToken);
const me = await api<{ user: User }>('/me');
- if (me.user.isAdmin) {
+ if (me.user.permissions?.length) {
set({ user: me.user, ready: true });
return;
}
+ // sesja bez uprawnień panelu — nie wchodzimy (ciastko aplikacji użytkownika)
+ setAccessToken(null);
}
} catch {
// no session
diff --git a/admin/test/GymDetail.test.tsx b/admin/test/GymDetail.test.tsx
index 35d8f8b..ba0e2e1 100644
--- a/admin/test/GymDetail.test.tsx
+++ b/admin/test/GymDetail.test.tsx
@@ -67,7 +67,7 @@ const U1 = {
firstName: 'Jan',
lastName: 'Kowalski',
nickname: null,
- isAdmin: false,
+ platformRoles: [],
} as unknown as User;
const MEMBERS_PAGE_1 = {
@@ -268,11 +268,9 @@ describe('admin GymDetail (konsola)', () => {
expect(within(table).getByText('Anna Kowalska')).toBeInTheDocument();
const trainerRow = within(table).getByText('Jan Nowak').closest('tr');
expect(within(trainerRow as HTMLElement).getByText('Trener')).toBeInTheDocument();
- // członkowie: e-maile zamaskowane; pełne adresy nigdy w DOM
- expect(within(table).getByText('j*n@f****.pl')).toBeInTheDocument();
- expect(within(table).getByText('a**a@f****.pl')).toBeInTheDocument();
- expect(screen.queryByText('jan@fitos.pl')).not.toBeInTheDocument();
- expect(screen.queryByText('anna@fitos.pl')).not.toBeInTheDocument();
+ // członkowie: e-maile renderowane 1:1 z DTO (serwer maskuje bez pii:read)
+ expect(within(table).getByText('jan@fitos.pl')).toBeInTheDocument();
+ expect(within(table).getByText('anna@fitos.pl')).toBeInTheDocument();
expect(screen.queryByText('ola@fitos.pl')).not.toBeInTheDocument();
// brak przycisków w tabeli — akcje członka dopiero w menu z kliknięcia wiersza
expect(within(table).queryAllByRole('button')).toHaveLength(0);
diff --git a/admin/test/Login.test.tsx b/admin/test/Login.test.tsx
index 804c75b..1ead6f7 100644
--- a/admin/test/Login.test.tsx
+++ b/admin/test/Login.test.tsx
@@ -15,7 +15,8 @@ const ADMIN: User = {
birthDate: null,
heightCm: null,
phone: null,
- isAdmin: true,
+ platformRoles: ['ADMIN'],
+ permissions: ['users:read', 'users:manage', 'pii:read', 'roles:manage', 'logs:view'],
availability: null,
priorities: null,
exclusions: null,
@@ -29,7 +30,13 @@ const ADMIN: User = {
createdAt: '2026-08-22T10:00:00.000Z',
};
-const NON_ADMIN: User = { ...ADMIN, id: 'u2', email: 'jan@test.local', isAdmin: false };
+const NON_ADMIN: User = {
+ ...ADMIN,
+ id: 'u2',
+ email: 'jan@test.local',
+ platformRoles: [],
+ permissions: [],
+};
function jsonResponse(status: number, body: unknown) {
return new Response(JSON.stringify(body), {
@@ -83,7 +90,7 @@ describe('admin Login page', () => {
expect(useAuth.getState().user).toEqual(ADMIN);
});
- it('rejects a non-admin login with a dedicated error and stays on the page', async () => {
+ it('rejects a non-staff login with a dedicated error and stays on the page', async () => {
vi.stubGlobal(
'fetch',
vi.fn(async () => jsonResponse(200, { user: NON_ADMIN, accessToken: 'tok-1' })),
@@ -95,7 +102,9 @@ describe('admin Login page', () => {
await user.type(email, 'jan@test.local');
await user.type(password, 'Password123!');
await user.click(screen.getByRole('button', { name: 'Zaloguj' }));
- expect(await screen.findByText('Dostęp tylko dla administratorów')).toBeInTheDocument();
+ expect(
+ await screen.findByText('To konto nie ma dostępu do panelu administracyjnego.'),
+ ).toBeInTheDocument();
expect(screen.queryByText('HOME')).not.toBeInTheDocument();
expect(useAuth.getState().user).toBeNull();
});
diff --git a/admin/test/Logs.test.tsx b/admin/test/Logs.test.tsx
index 98f43d0..2704001 100644
--- a/admin/test/Logs.test.tsx
+++ b/admin/test/Logs.test.tsx
@@ -68,7 +68,7 @@ const USER1: User = {
birthDate: null,
heightCm: null,
phone: null,
- isAdmin: false,
+ platformRoles: [],
availability: null,
priorities: null,
exclusions: null,
@@ -139,11 +139,9 @@ describe('admin Logs page', () => {
expect(await screen.findByText('start: 2026-08-24')).toBeInTheDocument();
// ID aktora w kolumnie „Użytkownik"
expect(screen.getAllByText('user-1').length).toBeGreaterThan(0);
- // aktor: zamaskowany e-mail pod imieniem i nazwiskiem; pełny adres nigdy w DOM
- expect(screen.getByText('a**a@t***.local')).toBeInTheDocument();
- expect(screen.getAllByText('j*n@t***.local').length).toBeGreaterThan(0);
- expect(screen.queryByText('anna@test.local')).not.toBeInTheDocument();
- expect(screen.queryByText('jan@test.local')).not.toBeInTheDocument();
+ // aktor: e-mail renderowany 1:1 z DTO (redakcja PII jest po stronie serwera)
+ expect(screen.getByText('anna@test.local')).toBeInTheDocument();
+ expect(screen.getAllByText('jan@test.local').length).toBeGreaterThan(0);
// etykiety akcji
expect(screen.getAllByText('Plan aktywowany').length).toBeGreaterThan(0);
expect(screen.getAllByText('Sesja zakończona').length).toBeGreaterThan(0);
@@ -236,11 +234,9 @@ describe('admin Logs page', () => {
expect(screen.getByText('Anna')).toBeInTheDocument();
});
- it('maskuje e-maile w szczegółach logów (także wpisy historyczne)', () => {
+ it('renderuje e-maile w szczegółach logów 1:1 z DTO (redakcja po stronie serwera)', () => {
const lines = detailsLines(LOG_EMAIL_DETAIL);
- expect(lines).toContain('e-mail: n**y@t***.local');
- expect(lines.join(' ')).not.toContain('nowy@test.local');
- expect(lines.join(' ')).not.toContain('ada@test.local');
+ expect(lines).toContain('e-mail: nowy@test.local');
});
it('shows an error when the logs request fails', async () => {
diff --git a/admin/test/UserDetail.test.tsx b/admin/test/UserDetail.test.tsx
index d6b59a7..65291b6 100644
--- a/admin/test/UserDetail.test.tsx
+++ b/admin/test/UserDetail.test.tsx
@@ -4,6 +4,7 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import UserDetail from '../src/pages/users/UserDetail';
import { setAccessToken } from '../src/api/client';
+import { useAuth } from '../src/store/auth';
import type { Gym, User } from '../src/api/types';
const G1: Gym = {
@@ -26,7 +27,7 @@ const U1: User = {
birthDate: '1996-05-05T00:00:00.000Z',
heightCm: 180,
phone: null,
- isAdmin: true,
+ platformRoles: ['ADMIN'],
availability: null,
priorities: null,
exclusions: null,
@@ -41,6 +42,27 @@ const U1: User = {
memberships: [{ gymId: 'g1', roles: ['OWNER', 'TRAINER'], gym: G1 }],
};
+const ADMIN_SESSION: User = {
+ ...U1,
+ id: 'me-1',
+ email: 'ada@test.local',
+ firstName: 'Ada',
+ lastName: 'Admin',
+ nickname: null,
+ platformRoles: ['ADMIN'],
+ permissions: [
+ 'users:read',
+ 'users:manage',
+ 'pii:read',
+ 'roles:manage',
+ 'catalog:manage',
+ 'gyms:manage',
+ 'announcements:manage',
+ 'verifications:view',
+ 'logs:view',
+ ],
+};
+
function jsonResponse(status: number, body: unknown) {
return new Response(JSON.stringify(body), {
status,
@@ -86,10 +108,12 @@ function renderUserDetail() {
beforeEach(() => {
setAccessToken('admin-tok');
+ useAuth.setState({ user: ADMIN_SESSION, ready: true });
});
afterEach(() => {
vi.unstubAllGlobals();
+ useAuth.setState({ user: null, ready: false });
});
describe('admin UserDetail (konsola użytkownika)', () => {
@@ -151,11 +175,10 @@ describe('admin UserDetail (konsola użytkownika)', () => {
expect(await screen.findByRole('heading', { level: 2, name: 'jano' })).toBeInTheDocument();
expect(screen.getByRole('link', { name: 'Wróć' })).toHaveAttribute('href', '/users');
- // panel podsumowania: zamaskowany e-mail + nick + badge admina + pasek danych administracyjnych
- expect(screen.getByText('j*n@t***.local')).toBeInTheDocument();
- expect(screen.queryByText('jan@test.local')).not.toBeInTheDocument();
+ // panel podsumowania: e-mail 1:1 z DTO (serwer maskuje bez pii:read) + nick + badge roli
+ expect(screen.getByText('jan@test.local')).toBeInTheDocument();
expect(screen.getByText('@jano')).toBeInTheDocument();
- expect(screen.getByText('Admin')).toBeInTheDocument();
+ expect(screen.getByText('Administrator')).toBeInTheDocument();
expect(screen.getByText('Ostatnie logowanie')).toBeInTheDocument();
expect(screen.getByText('Członkostwa')).toBeInTheDocument();
expect(screen.getByText('Konto od')).toBeInTheDocument();
diff --git a/admin/test/UserForm.test.tsx b/admin/test/UserForm.test.tsx
index bd53fa2..841395a 100644
--- a/admin/test/UserForm.test.tsx
+++ b/admin/test/UserForm.test.tsx
@@ -5,8 +5,9 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import UserForm from '../src/pages/users/UserForm';
import { setAccessToken } from '../src/api/client';
+import { useAuth } from '../src/store/auth';
import { API_BASE } from '../src/config';
-import type { Gym, User } from '../src/api/types';
+import type { Gym, PlatformRole, User } from '../src/api/types';
const GYM_A: Gym = {
id: 'gym-a',
@@ -43,7 +44,7 @@ function emptyUser(over: Partial): User {
birthDate: null,
heightCm: null,
phone: null,
- isAdmin: false,
+ platformRoles: [],
availability: null,
priorities: null,
exclusions: null,
@@ -67,10 +68,34 @@ const EDITED: User = emptyUser({
firstName: 'Jan',
lastName: 'Kowalski',
birthDate: '1996-05-05T00:00:00.000Z',
- isAdmin: true,
+ platformRoles: ['ADMIN'],
memberships: [{ gymId: 'gym-a', roles: ['MEMBER'], gym: GYM_A }],
});
+const ROLE_ADMIN: PlatformRole = {
+ id: 'role-admin',
+ key: 'ADMIN',
+ permissions: ['users:read', 'users:manage', 'pii:read', 'roles:manage', 'logs:view'],
+ isSystem: true,
+ grantCount: 1,
+};
+
+const ADMIN_SESSION: User = {
+ ...emptyUser({ id: 'me-1', email: 'ada@test.local', firstName: 'Ada' }),
+ platformRoles: ['ADMIN'],
+ permissions: [
+ 'users:read',
+ 'users:manage',
+ 'pii:read',
+ 'roles:manage',
+ 'catalog:manage',
+ 'gyms:manage',
+ 'announcements:manage',
+ 'verifications:view',
+ 'logs:view',
+ ],
+};
+
function jsonResponse(status: number, body: unknown) {
return new Response(JSON.stringify(body), {
status,
@@ -124,10 +149,12 @@ function renderForm(path: string) {
beforeEach(() => {
setAccessToken('admin-tok');
+ useAuth.setState({ user: ADMIN_SESSION, ready: true });
});
afterEach(() => {
vi.unstubAllGlobals();
+ useAuth.setState({ user: null, ready: false });
});
/** Zapis via menu kontekstowe (topbar) nie istnieje w jednostkowym renderze —
@@ -160,10 +187,10 @@ describe('admin UserForm — kreator tworzenia', () => {
expect(
screen.getByText('Zwykły członek siłowni — trenuje i korzysta z planów.'),
).toBeInTheDocument();
- // uprawnienia administratora platformy — rozwijane
- await user.click(screen.getByRole('button', { name: /Pokaż uprawnienia admina/i }));
+ // wyjaśnienie przełącza się na rolę Właściciel (stały panel pod pigułkami)
+ await user.click(screen.getByRole('checkbox', { name: 'Właściciel — siłownia 1' }));
expect(
- screen.getByText('Zarządzanie wszystkimi użytkownikami i siłowniami'),
+ screen.getByText('Zarządza siłownią — to uprawnienie, nie samo członkostwo.'),
).toBeInTheDocument();
});
@@ -196,8 +223,9 @@ describe('admin UserForm — kreator tworzenia', () => {
expect(JSON.parse(post?.init?.body as string)).toMatchObject({
email: 'nowy3@test.local',
password: 'Password123!',
- isAdmin: false,
});
+ // bez platformy w formularzu — zero żądań PUT o role
+ expect(calls.some((c) => c.init?.method === 'PUT')).toBe(false);
const mem = calls.find(
(c) => c.init?.method === 'POST' && c.url.includes('/admin/users/u9/memberships'),
);
@@ -274,20 +302,22 @@ describe('admin UserForm — kreator tworzenia', () => {
});
describe('admin UserForm — kreator edycji', () => {
- it('wypełnia formularz danymi konta i członkostwami (edytor w wizardzie)', async () => {
+ it('wypełnia formularz danymi konta, rolami i członkostwami (edytor w wizardzie)', async () => {
mockRoutes([
{ match: '/admin/gyms', reply: () => ({ gyms: [GYM_A, GYM_B] }) },
+ { match: '/admin/roles', reply: () => ({ roles: [ROLE_ADMIN] }) },
{ match: '/admin/users', reply: () => ({ users: [EDITED] }) },
]);
const { container } = renderForm('/users/u1/edit');
// dane i członkostwo wczytane z użytkownika — krok 3 jest też w edycji
expect(await screen.findByDisplayValue('Jan')).toBeInTheDocument();
- // w edycji e-mail zamaskowany i tylko do odczytu (pełny adres zna tylko user)
- const emailInput = container.querySelector('input[type="email"]');
- expect(emailInput).toBeNull();
- const masked = container.querySelector('input[readonly]') as HTMLInputElement | null;
- expect(masked?.value).toBe('j*n@t***.local');
+ // z pii:read e-mail i data urodzenia są edytowalne (pełne wartości z DTO)
+ const emailInput = container.querySelector('input[type="email"]') as HTMLInputElement;
+ expect(emailInput.value).toBe('jan@test.local');
expect(screen.getByDisplayValue('1996-05-05')).toBeInTheDocument();
+ // rola platformowa z grantu jest zaznaczona
+ const adminCheck = screen.getByRole('checkbox', { name: /Administrator/ }) as HTMLInputElement;
+ expect(adminCheck.checked).toBe(true);
expect(await screen.findByText('Członkostwa w siłowniach')).toBeInTheDocument();
expect(screen.getByDisplayValue('Fit Factory')).toBeInTheDocument();
});
@@ -295,6 +325,7 @@ describe('admin UserForm — kreator edycji', () => {
it('zapis edycji bez zmian członkostw PATCHuje tylko konto', async () => {
const calls = mockRoutes([
{ match: '/admin/gyms', reply: () => ({ gyms: [GYM_A, GYM_B] }) },
+ { match: '/admin/roles', reply: () => ({ roles: [ROLE_ADMIN] }) },
{ method: 'PATCH', match: '/admin/users/u1', reply: () => ({ user: EDITED }) },
{ match: '/admin/users', reply: () => ({ users: [EDITED] }) },
]);
@@ -312,18 +343,21 @@ describe('admin UserForm — kreator edycji', () => {
const accountPatch = calls.find(
(c) => c.init?.method === 'PATCH' && c.url === `${API_BASE}/admin/users/u1`,
);
- // e-mail niewidoczny w formularzu, ale PATCH przenosi go bez zmian
+ // z pii:read pełny e-mail i data trafiają do PATCH; role platformowe bez zmian → brak PUT
expect(JSON.parse(accountPatch?.init?.body as string)).toMatchObject({
lastName: 'Nowak',
email: 'jan@test.local',
- isAdmin: true,
+ birthDate: '1996-05-05',
});
+ expect(JSON.parse(String(accountPatch?.init?.body))).not.toHaveProperty('isAdmin');
+ expect(calls.some((c) => c.init?.method === 'PUT')).toBe(false);
expect(calls.some((c) => c.url.includes('/memberships'))).toBe(false);
});
it('zapis edycji PATCHuje konto i zmianę roli członkostwa', async () => {
const calls = mockRoutes([
{ match: '/admin/gyms', reply: () => ({ gyms: [GYM_A, GYM_B] }) },
+ { match: '/admin/roles', reply: () => ({ roles: [ROLE_ADMIN] }) },
{ method: 'PATCH', match: '/memberships/gym-a', reply: () => ({ membership: {} }) },
{ method: 'PATCH', match: '/admin/users/u1', reply: () => ({ user: EDITED }) },
{ match: '/admin/users', reply: () => ({ users: [EDITED] }) },
@@ -340,16 +374,40 @@ describe('admin UserForm — kreator edycji', () => {
const accountPatch = calls.find(
(c) => c.init?.method === 'PATCH' && c.url === `${API_BASE}/admin/users/u1`,
);
- expect(JSON.parse(accountPatch?.init?.body as string)).toMatchObject({ isAdmin: true });
+ expect(JSON.parse(accountPatch?.init?.body as string)).not.toHaveProperty('isAdmin');
+ expect(calls.some((c) => c.init?.method === 'PUT')).toBe(false);
const memPatch = calls.find(
(c) => c.init?.method === 'PATCH' && c.url.includes('/memberships/gym-a'),
);
expect(JSON.parse(memPatch?.init?.body as string)).toEqual({ roles: ['MEMBER', 'OWNER'] });
});
+ it('zmiana ról platformowych w edycji wysyła PUT /users/:id/roles', async () => {
+ const calls = mockRoutes([
+ { match: '/admin/gyms', reply: () => ({ gyms: [GYM_A, GYM_B] }) },
+ { match: '/admin/roles', reply: () => ({ roles: [ROLE_ADMIN] }) },
+ { method: 'PUT', match: '/users/u1/roles', reply: () => ({ roles: [] }) },
+ { method: 'PATCH', match: '/admin/users/u1', reply: () => ({ user: EDITED }) },
+ { match: '/admin/users', reply: () => ({ users: [EDITED] }) },
+ ]);
+ const user = userEvent.setup();
+ renderForm('/users/u1/edit');
+ await screen.findByDisplayValue('Jan');
+
+ // odznacz Administratora (grant usunięty w formularzu)
+ await user.click(screen.getByRole('checkbox', { name: /Administrator/ }));
+ await submitForm();
+
+ expect(await screen.findByText('DETAIL-u1')).toBeInTheDocument();
+ const rolesPut = calls.find((c) => c.init?.method === 'PUT' && c.url.includes('/roles'));
+ expect(rolesPut).toBeDefined();
+ expect(JSON.parse(String(rolesPut?.init?.body))).toEqual({ roles: [] });
+ });
+
it('usunięcie wiersza członkostwa wysyła DELETE', async () => {
const calls = mockRoutes([
{ match: '/admin/gyms', reply: () => ({ gyms: [GYM_A, GYM_B] }) },
+ { match: '/admin/roles', reply: () => ({ roles: [ROLE_ADMIN] }) },
{ method: 'PATCH', match: '/admin/users/u1', reply: () => ({ user: EDITED }) },
{ method: 'DELETE', match: '/memberships/gym-a', reply: () => ({}) },
{ match: '/admin/users', reply: () => ({ users: [EDITED] }) },
diff --git a/admin/test/UserLogsPage.test.tsx b/admin/test/UserLogsPage.test.tsx
index fe34c49..5b6293a 100644
--- a/admin/test/UserLogsPage.test.tsx
+++ b/admin/test/UserLogsPage.test.tsx
@@ -18,7 +18,7 @@ const U1: User = {
birthDate: null,
heightCm: null,
phone: null,
- isAdmin: false,
+ platformRoles: [],
availability: null,
priorities: null,
exclusions: null,
diff --git a/admin/test/UserRestrictionModal.test.tsx b/admin/test/UserRestrictionModal.test.tsx
index a25af28..bc78b7f 100644
--- a/admin/test/UserRestrictionModal.test.tsx
+++ b/admin/test/UserRestrictionModal.test.tsx
@@ -16,7 +16,7 @@ const BASE_USER: User = {
birthDate: null,
heightCm: null,
phone: null,
- isAdmin: false,
+ platformRoles: [],
availability: null,
priorities: null,
exclusions: null,
diff --git a/admin/test/UsersList.test.tsx b/admin/test/UsersList.test.tsx
index 421881b..23f5dc4 100644
--- a/admin/test/UsersList.test.tsx
+++ b/admin/test/UsersList.test.tsx
@@ -15,7 +15,7 @@ const U1: User = {
birthDate: '1996-05-05T00:00:00.000Z',
heightCm: 180,
phone: null,
- isAdmin: false,
+ platformRoles: [],
availability: null,
priorities: null,
exclusions: null,
@@ -38,7 +38,7 @@ const U2: User = {
birthDate: null,
heightCm: null,
phone: null,
- isAdmin: true,
+ platformRoles: ['ADMIN'],
availability: null,
priorities: null,
exclusions: null,
@@ -96,24 +96,21 @@ describe('admin UsersList page', () => {
it('lists users fetched from the API', async () => {
mockFetchSequence(jsonResponse(200, { users: [U1, U2] }));
renderUsers();
- // meta z zamaskowanym e-mailem; pełny adres nigdy nie trafia do DOM
- expect(await screen.findByText('j*n@t***.local · wiek: 30')).toBeInTheDocument();
- expect(screen.getByText('a***n@t***.local')).toBeInTheDocument();
- expect(screen.queryByText('jan@test.local')).not.toBeInTheDocument();
- expect(screen.queryByText('admin@test.local')).not.toBeInTheDocument();
- // 'Admin' appears both as the user name link and as the admin badge
- expect(screen.getAllByText('Admin')).toHaveLength(2);
+ // serwer wysyła maskowane adresy tylko odbiorcom bez pii:read;
+ // tu DTO pochodzi z widoku ADMIN — pełne adresy trafiają do DOM
+ expect(await screen.findByText('jan@test.local · wiek: 30')).toBeInTheDocument();
+ expect(screen.getByText('admin@test.local')).toBeInTheDocument();
+ expect(screen.getByText('Administrator')).toBeInTheDocument();
});
it('filters users by the search box', async () => {
mockFetchSequence(jsonResponse(200, { users: [U1, U2] }));
renderUsers();
- await screen.findByText('j*n@t***.local · wiek: 30');
+ await screen.findByText('jan@test.local · wiek: 30');
// wyszukiwarka jest w menu kontekstowym (Layout) — filtr ustawiamy przez store
act(() => useListSearch.getState().setQuery('users', 'admin'));
- expect(screen.queryByText('j*n@t***.local · wiek: 30')).not.toBeInTheDocument();
- // wyszukiwarka dopasowuje po pełnym e-mailu (serwerowo po q), lecz UI pokazuje maskę
- expect(screen.getByText('a***n@t***.local')).toBeInTheDocument();
+ expect(screen.queryByText('jan@test.local · wiek: 30')).not.toBeInTheDocument();
+ expect(screen.getByText('admin@test.local')).toBeInTheDocument();
});
it('shows an error when the users request fails', async () => {
diff --git a/admin/test/auth-store.test.ts b/admin/test/auth-store.test.ts
index 54acd0c..b8fad16 100644
--- a/admin/test/auth-store.test.ts
+++ b/admin/test/auth-store.test.ts
@@ -11,7 +11,8 @@ const ADMIN: User = {
birthDate: null,
heightCm: null,
phone: null,
- isAdmin: true,
+ platformRoles: ['ADMIN'],
+ permissions: ['users:read', 'users:manage', 'pii:read', 'roles:manage', 'logs:view'],
availability: null,
priorities: null,
exclusions: null,
@@ -22,7 +23,13 @@ const ADMIN: User = {
createdAt: '2026-08-22T10:00:00.000Z',
};
-const NON_ADMIN: User = { ...ADMIN, id: 'u2', email: 'jan@test.local', isAdmin: false };
+const NON_ADMIN: User = {
+ ...ADMIN,
+ id: 'u2',
+ email: 'jan@test.local',
+ platformRoles: [],
+ permissions: [],
+};
function jsonResponse(status: number, body: unknown) {
return new Response(JSON.stringify(body), {
@@ -61,10 +68,10 @@ describe('admin auth store', () => {
expect(localStorage.getItem('fitos_admin_access')).toBe('tok-1');
});
- it('login rejects for non-admin users and clears the token', async () => {
+ it('login rejects for non-staff users and clears the token', async () => {
mockFetchSequence(jsonResponse(200, { user: NON_ADMIN, accessToken: 'tok-1' }));
await expect(useAuth.getState().login('jan@test.local', 'Password123!')).rejects.toThrow(
- 'Dostęp tylko dla administratorów',
+ 'To konto nie ma dostępu do panelu administracyjnego.',
);
expect(useAuth.getState().user).toBeNull();
expect(getAccessToken()).toBeNull();
diff --git a/admin/test/e2e/admin.spec.ts b/admin/test/e2e/admin.spec.ts
index 3a7c42a..99f7ea7 100644
--- a/admin/test/e2e/admin.spec.ts
+++ b/admin/test/e2e/admin.spec.ts
@@ -160,9 +160,8 @@ test('kliknięcie w użytkownika otwiera konsolę administracyjną', async ({ pa
// topbar = kategoria „Użytkownik”, nazwa dopiero w treści (h2) + „← Wróć”
await expect(page.getByRole('heading', { level: 1, name: 'Użytkownik' })).toBeVisible();
await expect(page.getByRole('heading', { level: 2, name: 'Jan Kowalski' })).toBeVisible();
- // panel podsumowania: zamaskowany e-mail + pasek danych administracyjnych (pełny adres zna tylko user)
- await expect(page.getByText('j*n@f****.pl')).toBeVisible();
- await expect(page.getByText('jan@fitos.pl')).toHaveCount(0);
+ // panel podsumowania: e-mail 1:1 z DTO (admin ma pii:read, więc pełny adres) + pasek danych
+ await expect(page.getByText('jan@fitos.pl')).toBeVisible();
await expect(page.getByText('Ostatnie logowanie')).toBeVisible();
await expect(page.getByText('Członkostwa', { exact: true })).toBeVisible();
await expect(page.getByText('Konto od')).toBeVisible();
@@ -182,19 +181,16 @@ test('kliknięcie w użytkownika otwiera konsolę administracyjną', async ({ pa
await expect(page.getByRole('button', { name: 'Dodawanie' })).not.toBeVisible();
});
-test('własne konto: właściciel widzi swój e-mail w pełni, cudzy pozostaje zamaskowany', async ({
- page,
-}) => {
+test('lista i profil: pełne adresy e-mail w widoku z pii:read', async ({ page }) => {
mockApi(page, { users: { users: [TEST_USER, TEST_ADMIN] } });
await loginAsAdmin(page);
await page.getByRole('link', { name: 'Użytkownicy' }).click();
- // wiersz własny (admin-test) = pełny adres, wiersz cudzy (user-1) = maska
+ // pełne adresy obu wierszy — maskowanie wykonuje serwer dla odbiorców bez pii:read
await expect(page.getByText('admin@fitos.pl')).toBeVisible();
- await expect(page.getByText('j*n@f****.pl')).toBeVisible();
+ await expect(page.getByText('jan@fitos.pl')).toBeVisible();
await page.getByRole('link', { name: 'Admin Test' }).click();
await expect(page).toHaveURL(/\/users\/admin-test$/);
await expect(page.getByText('admin@fitos.pl')).toBeVisible();
- await expect(page.getByText('a***n@f****.pl')).toHaveCount(0);
});
test('edycja członkostwa z karty w profilu — klik w wiersz otwiera menu, zapis wysyła PATCH', async ({
@@ -464,9 +460,8 @@ test('kreator edycji: zapis bez zmian członkostw wysyła tylko PATCH konta', as
await page.getByRole('button', { name: 'Edytuj' }).click();
await expect(page).toHaveURL(/\/users\/user-1\/edit$/);
await expect(page.getByRole('heading', { name: 'Edycja użytkownika' })).toBeVisible();
- // e-mail w edycji zamaskowany i tylko do odczytu (pełny adres zna tylko user)
- await expect(page.locator('input[readonly]')).toHaveValue('j*n@f****.pl');
- await expect(page.locator('input[type="email"]')).toHaveCount(0);
+ // e-mail w edycji edytowalny i pełny (admin ma pii:read — serwer wysyła pełny adres)
+ await expect(page.locator('input[type="email"]')).toHaveValue('jan@fitos.pl');
// pełny edytor: krok członkostw wczytany (skłon ról bez zmian = zero żądań członkostw)
await expect(page.getByRole('heading', { name: 'Członkostwa w siłowniach' })).toBeVisible();
await expect(page.getByRole('combobox', { name: 'Szukaj siłowni' })).toHaveValue('Fit Factory');
@@ -534,7 +529,9 @@ test('menu kontekstowe formularza „Nowy użytkownik” ma Zapisz, który wysy
);
await page.getByRole('button', { name: 'Zapisz' }).click();
const req = await postPromise;
- expect(req.postDataJSON()).toMatchObject({ email: 'nowy@fitos.pl', isAdmin: false });
+ const body = req.postDataJSON() as Record;
+ expect(body.email).toBe('nowy@fitos.pl');
+ expect(body).not.toHaveProperty('isAdmin');
await expect(page).toHaveURL(/\/users\/user-new$/);
});
diff --git a/admin/test/e2e/auth.spec.ts b/admin/test/e2e/auth.spec.ts
index 47336bf..01bd206 100644
--- a/admin/test/e2e/auth.spec.ts
+++ b/admin/test/e2e/auth.spec.ts
@@ -42,7 +42,7 @@ test('bez zaznaczenia zapamiętaj mnie e-mail nie jest zapisywany', async ({ pag
expect(stored).toBeNull();
});
-test('logowanie nie-admina zostaje odrzucone', async ({ page }) => {
+test('logowanie konta bez uprawnień panelu zostaje odrzucone', async ({ page }) => {
mockApi(page, {
loginBody: {
user: {
@@ -53,7 +53,8 @@ test('logowanie nie-admina zostaje odrzucone', async ({ page }) => {
birthDate: null,
heightCm: null,
phone: null,
- isAdmin: false,
+ platformRoles: [],
+ permissions: [],
availability: null,
priorities: null,
exclusions: null,
@@ -71,7 +72,7 @@ test('logowanie nie-admina zostaje odrzucone', async ({ page }) => {
await page.locator('input[type="password"]').fill('haslo123');
await page.getByRole('button', { name: 'Zaloguj' }).click();
await expect(page).toHaveURL(/\/login$/);
- await expect(page.getByText('Dostęp tylko dla administratorów')).toBeVisible();
+ await expect(page.getByText('To konto nie ma dostępu do panelu administracyjnego.')).toBeVisible();
});
test('nieudane logowanie administratora pokazuje komunikat o błędnych danych', async ({ page }) => {
diff --git a/admin/test/e2e/mock-api.ts b/admin/test/e2e/mock-api.ts
index 41064f8..2aa106f 100644
--- a/admin/test/e2e/mock-api.ts
+++ b/admin/test/e2e/mock-api.ts
@@ -16,7 +16,18 @@ export const TEST_ADMIN = {
birthDate: null,
heightCm: null,
phone: null,
- isAdmin: true,
+ platformRoles: ['ADMIN'],
+ permissions: [
+ 'users:read',
+ 'users:manage',
+ 'pii:read',
+ 'roles:manage',
+ 'catalog:manage',
+ 'gyms:manage',
+ 'announcements:manage',
+ 'verifications:view',
+ 'logs:view',
+ ],
availability: null,
priorities: null,
exclusions: null,
@@ -223,7 +234,7 @@ export const TEST_USER: User = {
birthDate: '1996-05-05T00:00:00.000Z',
heightCm: 180,
phone: '+48 500 100 200',
- isAdmin: false,
+ platformRoles: [],
availability: null,
priorities: null,
exclusions: null,
diff --git a/admin/test/e2e/roles.spec.ts b/admin/test/e2e/roles.spec.ts
new file mode 100644
index 0000000..154c492
--- /dev/null
+++ b/admin/test/e2e/roles.spec.ts
@@ -0,0 +1,121 @@
+import type { Page } from '@playwright/test';
+import { test, expect } from './fixtures';
+import { mockApi, TEST_ADMIN } from './mock-api';
+
+const MODERATOR = {
+ ...TEST_ADMIN,
+ id: 'mod-test',
+ email: 'mod@fitos.pl',
+ firstName: 'Marta',
+ lastName: 'Moderator',
+ platformRoles: ['MODERATOR'],
+ permissions: ['users:read', 'users:manage', 'catalog:manage', 'logs:view'],
+};
+
+const ADMIN_ROLES_BODY = {
+ roles: [
+ {
+ id: 'role-admin',
+ key: 'ADMIN',
+ permissions: ['users:read', 'users:manage', 'pii:read', 'roles:manage'],
+ isSystem: true,
+ grantCount: 2,
+ },
+ {
+ id: 'role-mod',
+ key: 'MODERATOR',
+ permissions: ['users:read', 'users:manage', 'catalog:manage', 'logs:view'],
+ isSystem: true,
+ grantCount: 1,
+ },
+ ],
+};
+
+function mockRolesRoutes(page: Page) {
+ page.route('**/api/v1/admin/roles*', (route) =>
+ route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify(ADMIN_ROLES_BODY),
+ }),
+ );
+ page.route('**/api/v1/admin/permissions', (route) =>
+ route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify({
+ permissions: [
+ 'users:read',
+ 'users:manage',
+ 'pii:read',
+ 'roles:manage',
+ 'catalog:manage',
+ 'gyms:manage',
+ 'announcements:manage',
+ 'verifications:view',
+ 'logs:view',
+ ],
+ }),
+ }),
+ );
+}
+
+async function login(page: Page) {
+ await page.goto('/login');
+ await page.locator('input[type="email"]').fill('admin@fitos.pl');
+ await page.locator('input[type="password"]').fill('haslo123');
+ await page.getByRole('button', { name: 'Zaloguj' }).click();
+}
+
+test('moderator ląduje na użytkownikach i nie widzi ról ani siłowni w nawigacji', async ({
+ page,
+}) => {
+ mockApi(page, { loginBody: { user: MODERATOR, accessToken: 'mod-token' } });
+ await login(page);
+ await expect(page).toHaveURL(/\/users$/);
+ await expect(page.getByRole('link', { name: 'Użytkownicy' })).toBeVisible();
+ await expect(page.getByRole('link', { name: 'Role' })).not.toBeVisible();
+ await expect(page.getByRole('link', { name: 'Siłownie' })).not.toBeVisible();
+});
+
+test('moderator nie wejdzie na /roles — strażnik przekierowuje na jego stronę startową', async ({
+ page,
+}) => {
+ mockApi(page, { loginBody: { user: MODERATOR, accessToken: 'mod-token' } });
+ await login(page);
+ await expect(page).toHaveURL(/\/users$/);
+ // pełne przeładowanie na /roles: init odświeża sesję — jako moderator (nadpisujemy trasy)
+ page.route('**/api/v1/auth/refresh', (route) =>
+ route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify({ accessToken: 'mod-token' }),
+ }),
+ );
+ page.route('**/api/v1/me', (route) =>
+ route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify({ user: MODERATOR, memberships: [] }),
+ }),
+ );
+ await page.goto('/roles');
+ await expect(page).toHaveURL(/\/users$/);
+ await expect(page.getByRole('heading', { name: 'Role' })).not.toBeVisible();
+});
+
+test('admin widzi role z nazwami, licznikami kont i badge systemowa', async ({ page }) => {
+ mockApi(page, { gyms: { gyms: [] } });
+ mockRolesRoutes(page);
+ await login(page);
+ await expect(page).toHaveURL(/\/gyms$/);
+ await page.getByRole('link', { name: 'Role' }).click();
+ await expect(page).toHaveURL(/\/roles$/);
+ await expect(page.getByRole('heading', { level: 1, name: 'Role' })).toBeVisible();
+ const main = page.getByRole('main');
+ await expect(main.getByText('Administrator', { exact: true })).toBeVisible();
+ await expect(main.getByText('Moderator', { exact: true })).toBeVisible();
+ await expect(main.getByText('Przypisana do 2 kont')).toBeVisible();
+ await expect(main.getByText('Przypisana do 1 konta')).toBeVisible();
+ await expect(main.getByText('systemowa', { exact: true })).toHaveCount(2);
+});
diff --git a/admin/test/e2e/verifications.spec.ts b/admin/test/e2e/verifications.spec.ts
index 9f1f62c..872d92e 100644
--- a/admin/test/e2e/verifications.spec.ts
+++ b/admin/test/e2e/verifications.spec.ts
@@ -38,10 +38,9 @@ test('szczegóły wniosku o nową realną: dane siłowni + wnioskodawca', async
// dane siłowni (typ nowa realna)
await expect(page.getByText('ul. Długa 5, Warszawa')).toBeVisible();
- // wnioskodawca — e-mail zamaskowany (pełny adres zna tylko user)
+ // wnioskodawca — e-mail renderowany 1:1 z DTO (redakcja PII po stronie serwera)
await expect(page.getByText('Anna Nowa')).toBeVisible();
- await expect(page.getByText('n**a@f****.pl').first()).toBeVisible();
- await expect(page.getByText('nowa@fitos.pl')).toHaveCount(0);
+ await expect(page.getByText('nowa@fitos.pl').first()).toBeVisible();
});
test('szczegóły wniosku o weryfikację: siłownia + dokument do pobrania', async ({ page }) => {
diff --git a/api/prisma/migrations/20261125201122_add_rbac_roles/migration.sql b/api/prisma/migrations/20261125201122_add_rbac_roles/migration.sql
new file mode 100644
index 0000000..620820f
--- /dev/null
+++ b/api/prisma/migrations/20261125201122_add_rbac_roles/migration.sql
@@ -0,0 +1,85 @@
+-- CreateTable
+CREATE TABLE "Role" (
+ "id" TEXT NOT NULL,
+ "key" TEXT NOT NULL,
+ "permissions" TEXT[],
+ "isSystem" BOOLEAN NOT NULL DEFAULT false,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL,
+
+ CONSTRAINT "Role_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateTable
+CREATE TABLE "UserRoleGrant" (
+ "id" TEXT NOT NULL,
+ "userId" TEXT NOT NULL,
+ "roleId" TEXT NOT NULL,
+ "gymId" TEXT,
+
+ CONSTRAINT "UserRoleGrant_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateIndex
+CREATE UNIQUE INDEX "Role_key_key" ON "Role"("key");
+
+-- CreateIndex
+CREATE INDEX "UserRoleGrant_userId_idx" ON "UserRoleGrant"("userId");
+
+-- CreateIndex
+CREATE INDEX "UserRoleGrant_roleId_idx" ON "UserRoleGrant"("roleId");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "UserRoleGrant_userId_roleId_gymId_key" ON "UserRoleGrant"("userId", "roleId", "gymId");
+
+-- AddForeignKey
+ALTER TABLE "UserRoleGrant" ADD CONSTRAINT "UserRoleGrant_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "UserRoleGrant" ADD CONSTRAINT "UserRoleGrant_roleId_fkey" FOREIGN KEY ("roleId") REFERENCES "Role"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "UserRoleGrant" ADD CONSTRAINT "UserRoleGrant_gymId_fkey" FOREIGN KEY ("gymId") REFERENCES "Gym"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- PartialUniqueIndex (platform grants): w PG NULL-e nie kolidują w zwykłym unique,
+-- więc grant platformowy (gymId IS NULL) potrzebuje osobnego indeksu częściowego.
+CREATE UNIQUE INDEX "UserRoleGrant_userId_roleId_platform_key" ON "UserRoleGrant"("userId", "roleId") WHERE "gymId" IS NULL;
+
+-- SeedSystemRoles: katalog uprawnień musi być zgodny z api/src/lib/permissions.ts
+INSERT INTO "Role" ("id", "key", "permissions", "isSystem", "createdAt", "updatedAt")
+VALUES
+ (
+ 'role_admin',
+ 'ADMIN',
+ ARRAY[
+ 'users:read',
+ 'users:manage',
+ 'pii:read',
+ 'roles:manage',
+ 'catalog:manage',
+ 'gyms:manage',
+ 'announcements:manage',
+ 'verifications:view',
+ 'logs:view'
+ ],
+ true,
+ now(),
+ now()
+ ),
+ (
+ 'role_moderator',
+ 'MODERATOR',
+ ARRAY['users:read', 'users:manage', 'catalog:manage', 'logs:view'],
+ true,
+ now(),
+ now()
+ )
+ON CONFLICT ("key") DO NOTHING;
+
+-- Backfill: dotychczasowi isAdmin dostają grant roli ADMIN (kolumna isAdmin zostaje do ręcznego czyszczenia)
+INSERT INTO "UserRoleGrant" ("id", "userId", "roleId", "gymId")
+SELECT gen_random_uuid()::text, u."id", r."id", NULL
+FROM "User" u
+JOIN "Role" r ON r."key" = 'ADMIN'
+WHERE u."isAdmin" = true
+ON CONFLICT DO NOTHING;
diff --git a/api/prisma/schema.prisma b/api/prisma/schema.prisma
index b1f8d0d..f25400e 100644
--- a/api/prisma/schema.prisma
+++ b/api/prisma/schema.prisma
@@ -173,6 +173,41 @@ model User {
gymConversations GymConversation[]
gymMessages GymMessage[] @relation("GymMessageSender")
gymConversationReads GymConversationRead[] @relation("GymConversationReader")
+ roleGrants UserRoleGrant[]
+}
+
+/// Rola RBAC: klucz + zestaw uprawnień (katalog w kodzie: lib/permissions.ts).
+/// `isSystem` = rola seedowana (ADMIN/MODERATOR): niedeletowalna, bez zmiany klucza.
+model Role {
+ id String @id @default(cuid())
+ key String @unique
+ permissions String[]
+ isSystem Boolean @default(false)
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+
+ grants UserRoleGrant[]
+}
+
+/// Grant roli użytkownikowi. `gymId = null` = rola platformowa (faza 1 — jedyna
+/// używana runtime'owo); grant z `gymId` projektowany w fazie 1, nieużywany do
+/// delegacji uprawnień (faza 2).
+/// Dla grantów platformowych dodatkowy częściowy unikalny indeks
+/// `(userId, roleId) WHERE gymId IS NULL` utworzony w migracji (w PG NULL-e
+/// nie kolidują w zwykłym @@unique).
+model UserRoleGrant {
+ id String @id @default(cuid())
+ userId String
+ roleId String
+ gymId String?
+
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
+ role Role @relation(fields: [roleId], references: [id], onDelete: Cascade)
+ gym Gym? @relation(fields: [gymId], references: [id], onDelete: Cascade)
+
+ @@unique([userId, roleId, gymId])
+ @@index([userId])
+ @@index([roleId])
}
/// Audit trail of user actions (app + trainer level). Best-effort writes,
@@ -382,6 +417,7 @@ model Gym {
announcements Announcement[]
presences GymPresence[]
conversations GymConversation[]
+ roleGrants UserRoleGrant[]
}
/// Zdjęcie w galerii siłowni REAL. `order` = kolejność; okładka = najmniejsze `order` (tie → najstarsze `createdAt`).
diff --git a/api/src/lib/permissions.ts b/api/src/lib/permissions.ts
new file mode 100644
index 0000000..f37b666
--- /dev/null
+++ b/api/src/lib/permissions.ts
@@ -0,0 +1,185 @@
+import type { PrismaClient } from '@prisma/client';
+
+/**
+ * Katalog uprawnień platformy (faza 1 RBAC). Źródło prawdy dla kluczy —
+ * role w bazie przechowują wyłącznie klucze stąd; nieznany klucz jest
+ * inertny (filtrowany przez `knownPermissions`).
+ */
+export const PERMISSIONS = {
+ USERS_READ: 'users:read',
+ USERS_MANAGE: 'users:manage',
+ PII_READ: 'pii:read',
+ ROLES_MANAGE: 'roles:manage',
+ CATALOG_MANAGE: 'catalog:manage',
+ GYMS_MANAGE: 'gyms:manage',
+ ANNOUNCEMENTS_MANAGE: 'announcements:manage',
+ VERIFICATIONS_VIEW: 'verifications:view',
+ LOGS_VIEW: 'logs:view',
+} as const;
+
+export type PermissionKey = (typeof PERMISSIONS)[keyof typeof PERMISSIONS];
+
+export const PERMISSION_KEYS = Object.values(PERMISSIONS) as PermissionKey[];
+
+export function isPermissionKey(value: string): value is PermissionKey {
+ return (PERMISSION_KEYS as string[]).includes(value);
+}
+
+/** Wycina klucze spoza katalogu (nieznane uprawnienia z bazy są inertne). */
+export function knownPermissions(values: readonly string[]): PermissionKey[] {
+ return values.filter(isPermissionKey);
+}
+
+/** Role seedowane w migracji + seedzie (ADMIN ⊇ MODERATOR przez pakiety kluczy). */
+export const DEFAULT_ROLES: ReadonlyArray<{
+ key: string;
+ permissions: PermissionKey[];
+ isSystem: true;
+}> = [
+ { key: 'ADMIN', permissions: [...PERMISSION_KEYS], isSystem: true },
+ {
+ key: 'MODERATOR',
+ permissions: [
+ PERMISSIONS.USERS_READ,
+ PERMISSIONS.USERS_MANAGE,
+ PERMISSIONS.CATALOG_MANAGE,
+ PERMISSIONS.LOGS_VIEW,
+ ],
+ isSystem: true,
+ },
+];
+
+export const ROLE_KEYS = {
+ ADMIN: 'ADMIN',
+ MODERATOR: 'MODERATOR',
+} as const;
+
+/** Include grantów platformowych (gymId IS NULL) — wspólny kształt dla zapytań. */
+export const PLATFORM_GRANTS_INCLUDE = {
+ where: { gymId: null },
+ include: { role: { select: { key: true, permissions: true } } },
+} as const;
+
+/** Kształt usera pobranego z `include: { roleGrants: PLATFORM_GRANTS_INCLUDE }`. */
+export interface WithPlatformGrants {
+ roleGrants?: ReadonlyArray<{ role: { key: string; permissions: string[] } }>;
+}
+
+export function platformRoleKeys(user: WithPlatformGrants): string[] {
+ return (user.roleGrants ?? []).map((g) => g.role.key);
+}
+
+/** Unia uprawnień (bez duplikatów) z unionu grantów roli użytkownika. */
+export function permissionsFromGrants(user: WithPlatformGrants): PermissionKey[] {
+ return [...new Set(knownPermissions((user.roleGrants ?? []).flatMap((g) => g.role.permissions)))];
+}
+
+export function hasPlatformRole(user: WithPlatformGrants, key: string): boolean {
+ return platformRoleKeys(user).includes(key);
+}
+
+/**
+ * Unia uprawnień z grantów platformowych użytkownika (gymId IS NULL).
+ * Poza Authenticate middleware — używana w flow logowania/`/me`, gdzie
+ * potrzebujemy świeżego stanu bez zależności od `req.user`.
+ */
+export async function resolvePlatformPermissions(
+ prisma: PrismaClient,
+ userId: string,
+): Promise {
+ const grants = await prisma.userRoleGrant.findMany({
+ where: { userId, gymId: null },
+ include: { role: { select: { permissions: true } } },
+ });
+ return [...new Set(knownPermissions(grants.flatMap((g) => g.role.permissions)))];
+}
+
+/**
+ * Maska adresu e-mail dla odbiorców bez `pii:read` (serwerowe źródło prawdy,
+ * klient renderuje dokładnie to, co dostał). Format identyczny z dawnym
+ * maskowaniem klienta panelu: `jan@fitos.pl → j*n@f****.pl`.
+ */
+export function maskEmail(email: string | null | undefined): string | null | undefined {
+ if (!email) return email;
+ const at = email.indexOf('@');
+ if (at < 1) return '*';
+ const local = email.slice(0, at);
+ const localMask =
+ local.length <= 2
+ ? `${local.slice(0, 1)}${'*'.repeat(Math.max(local.length - 1, 1))}`
+ : `${local.slice(0, 1)}${'*'.repeat(local.length - 2)}${local.slice(-1)}`;
+ const domain = email.slice(at + 1);
+ const dot = domain.indexOf('.');
+ const firstLabel = dot < 0 ? domain : domain.slice(0, dot);
+ const rest = dot < 0 ? '' : domain.slice(dot);
+ const domainMask = `${firstLabel.slice(0, 1)}${'*'.repeat(Math.max(firstLabel.length - 1, 1))}${rest}`;
+ return `${localMask}@${domainMask}`;
+}
+
+/**
+ * Redakcja PII w DTO per-user: bez `pii:read` e-mail maskowany, telefon i
+ * data urodzenia nigdy nie wysyłane (null, jeśli DTO ma takie pole).
+ * Admin (pii:read) bez zmian.
+ */
+export function redactUserDto(
+ dto: T,
+ permissions: readonly string[],
+): T {
+ if (permissions.includes(PERMISSIONS.PII_READ)) return dto;
+ const out = { ...dto } as Record;
+ out.email = dto.email ? maskEmail(dto.email) : dto.email;
+ if ('phone' in out) out.phone = null;
+ if ('birthDate' in out) out.birthDate = null;
+ return out as T;
+}
+
+/** Lista users/memberów/ownerów: redakcja każdego obiektu użytkownika w tablicy. */
+export function redactUserDtos(
+ dtos: readonly T[],
+ permissions: readonly string[],
+): T[] {
+ if (permissions.includes(PERMISSIONS.PII_READ)) return [...dtos];
+ return dtos.map((dto) => redactUserDto(dto, permissions));
+}
+
+/** Redakcja PII na obiekcie gniazdzonym (np. `member.user`). */
+export function redactUserDtosInPlace(
+ rows: T[],
+ permissions: readonly string[],
+): T[] {
+ if (permissions.includes(PERMISSIONS.PII_READ)) return rows;
+ for (const row of rows) {
+ if (row.user) row.user = redactUserDto(row.user, permissions) as T['user'];
+ }
+ return rows;
+}
+
+/** Redakcja `email` w zagnieżdżonym obiekcie użytkownika (pojedynczy). */
+export function redactUserRef(
+ ref: T,
+ permissions: readonly string[],
+): T {
+ if (!ref || permissions.includes(PERMISSIONS.PII_READ)) return ref;
+ return redactUserDto(ref, permissions) as T;
+}
+
+/** Redakcja pola `email` (dowolnej głębokości) w `details` logu audytowego. */
+function redactEmails(value: unknown): unknown {
+ if (Array.isArray(value)) return value.map(redactEmails);
+ if (value && typeof value === 'object') {
+ const out: Record = {};
+ for (const [k, v] of Object.entries(value as Record)) {
+ out[k] = k === 'email' && typeof v === 'string' ? maskEmail(v) : redactEmails(v);
+ }
+ return out;
+ }
+ return value;
+}
+
+export function redactLogDetails(
+ details: Record | null,
+ permissions: readonly string[],
+): Record | null {
+ if (!details || permissions.includes(PERMISSIONS.PII_READ)) return details;
+ return redactEmails(details) as Record;
+}
diff --git a/api/src/lib/publicUser.ts b/api/src/lib/publicUser.ts
index 88ef9df..6a0902c 100644
--- a/api/src/lib/publicUser.ts
+++ b/api/src/lib/publicUser.ts
@@ -1,6 +1,12 @@
import type { User } from '@prisma/client';
+import { platformRoleKeys, type WithPlatformGrants } from './permissions.js';
-export function publicUser(u: User) {
+/**
+ * DTO użytkownika. `platformRoles` = klucze ról platformowych z grantów;
+ * wymaga `include: { roleGrants: PLATFORM_GRANTS_INCLUDE }` przy pobraniu,
+ * bez tego zwraca [] (brak ról).
+ */
+export function publicUser(u: User & WithPlatformGrants) {
return {
id: u.id,
email: u.email,
@@ -11,7 +17,7 @@ export function publicUser(u: User) {
birthDate: u.birthDate ? u.birthDate.toISOString() : null,
heightCm: u.heightCm,
phone: u.phone,
- isAdmin: u.isAdmin,
+ platformRoles: platformRoleKeys(u),
availability: u.availability,
priorities: u.priorities,
exclusions: u.exclusions,
diff --git a/api/src/middleware/auth.ts b/api/src/middleware/auth.ts
index d4b2c7d..355d186 100644
--- a/api/src/middleware/auth.ts
+++ b/api/src/middleware/auth.ts
@@ -2,11 +2,26 @@ import type { NextFunction, Request, Response } from 'express';
import type { PrismaClient } from '@prisma/client';
import { verifyAccessToken } from '../lib/jwt.js';
import { AppError, forbidden, unauthorized } from '../lib/errors.js';
+import {
+ PLATFORM_GRANTS_INCLUDE,
+ permissionsFromGrants,
+ platformRoleKeys,
+ type PermissionKey,
+} from '../lib/permissions.js';
+
+export interface AuthenticatedUser {
+ id: string;
+ tokenVersion: number;
+ /** Klucze ról platformowych z grantów (gymId IS NULL). */
+ platformRoles: string[];
+ /** Unia uprawnień ról platformowych — katalog z lib/permissions.ts. */
+ platformPermissions: PermissionKey[];
+}
declare global {
namespace Express {
interface Request {
- user?: { id: string; isAdmin: boolean; tokenVersion: number };
+ user?: AuthenticatedUser;
}
}
}
@@ -17,9 +32,19 @@ export function authenticate(prisma: PrismaClient) {
const header = req.headers.authorization;
if (!header || !header.startsWith('Bearer ')) throw unauthorized('Missing access token');
const payload = verifyAccessToken(header.slice(7));
- const user = await prisma.user.findUnique({ where: { id: payload.sub } });
+ const user = await prisma.user.findUnique({
+ where: { id: payload.sub },
+ include: { roleGrants: PLATFORM_GRANTS_INCLUDE },
+ });
if (!user || user.tokenVersion !== payload.tv) throw unauthorized('Token revoked');
- req.user = { id: user.id, isAdmin: user.isAdmin, tokenVersion: user.tokenVersion };
+ // Role liczone przy każdym żądaniu — zmiana grantów (tokenVersion++)
+ // rozgłasza się natychmiast, bez zmian w tokenie.
+ req.user = {
+ id: user.id,
+ tokenVersion: user.tokenVersion,
+ platformRoles: platformRoleKeys(user),
+ platformPermissions: permissionsFromGrants(user),
+ };
next();
} catch (e) {
next(e instanceof AppError ? e : unauthorized('Invalid or expired token'));
@@ -27,9 +52,28 @@ export function authenticate(prisma: PrismaClient) {
};
}
-export function requireAdmin(req: Request, _res: Response, next: NextFunction) {
- if (!req.user?.isAdmin) return next(forbidden('Admin access required'));
- next();
+export function requirePermission(key: PermissionKey) {
+ return (req: Request, _res: Response, next: NextFunction) => {
+ if (!req.user?.platformPermissions.includes(key)) {
+ return next(forbidden(`Missing permission: ${key}`));
+ }
+ next();
+ };
+}
+
+/** Minimum jedno z uprawnień — dla tras odczytowych wspólnych różnym rolom (np. lista gymów dla pickera). */
+export function requireAnyPermission(keys: readonly PermissionKey[]) {
+ return (req: Request, _res: Response, next: NextFunction) => {
+ if (!keys.some((key) => req.user?.platformPermissions.includes(key))) {
+ return next(forbidden(`Missing permission: any of ${keys.join(', ')}`));
+ }
+ next();
+ };
+}
+
+/** Czy wywołujący ma uprawnienie (do obliczania flag per odpowedź, np. nadzór gymów). */
+export function callerHas(req: Request, key: PermissionKey): boolean {
+ return !!req.user?.platformPermissions.includes(key);
}
/** The user must hold the TRAINER role in at least one gym. */
diff --git a/api/src/routes/admin.ts b/api/src/routes/admin.ts
index b68d021..e284ec6 100644
--- a/api/src/routes/admin.ts
+++ b/api/src/routes/admin.ts
@@ -3,7 +3,7 @@ import path from 'node:path';
import { Router } from 'express';
import { z } from 'zod';
import type { AppDeps } from '../deps.js';
-import { authenticate, requireAdmin } from '../middleware/auth.js';
+import { authenticate, requireAnyPermission, requirePermission } from '../middleware/auth.js';
import { validate } from '../middleware/validate.js';
import {
availabilitySchema,
@@ -65,8 +65,29 @@ import {
listAnnouncementsForAdmin,
updateAnnouncementAsAdmin,
} from '../services/announcements.js';
-import { listActivityLogs, listGymAuditLogs, logActivity } from '../services/audit.js';
+import {
+ listActivityLogs,
+ listGymAuditLogs,
+ logActivity,
+ redactActivityLogResult,
+} from '../services/audit.js';
import { asyncHandler } from '../lib/asyncHandler.js';
+import { PERMISSIONS, PERMISSION_KEYS } from '../lib/permissions.js';
+import {
+ assertNotStaffTarget,
+ createRole,
+ deleteRole,
+ getUserPlatformRoles,
+ listRoles,
+ setUserPlatformRoles,
+ updateRole,
+} from '../services/roles.js';
+
+/** Brama uprawnień dołączana do poszczególnych rejestracji tras panelu. */
+const can = requirePermission;
+
+/** Brama „dowolnego z" — trasy odczytowe wspólne rolom (np. lista gymów dla pickera członkostw). */
+const canAny = requireAnyPermission;
const gymSchema = z.object({
name: z.string().min(1).max(200),
@@ -121,7 +142,6 @@ const createUserSchema = z.object({
firstName: z.string().min(1).max(100).optional(),
lastName: z.string().min(1).max(100).optional(),
birthDate: birthDateSchema,
- isAdmin: z.boolean().optional(),
});
const muscleArraySchema = z.array(z.string().min(1).max(50)).max(20);
@@ -138,7 +158,6 @@ const updateUserSchema = z
birthDate: birthDateSchema,
heightCm: z.number().positive().max(250).nullable().optional(),
phone: z.string().min(5).max(20).nullable().optional(),
- isAdmin: z.boolean().optional(),
password: z.string().min(8).optional(),
availability: availabilitySchema,
priorities: z.string().max(2000).nullable().optional(),
@@ -192,9 +211,33 @@ const removeMembershipSchema = z.object({
reason: z.string().trim().min(3).max(300).optional(),
});
+const createRoleSchema = z.object({
+ key: z.string().trim().min(2).max(40),
+ permissions: z.array(z.string().min(1).max(60)).max(50),
+});
+
+const updateRoleSchema = z.object({
+ name: z.string().trim().min(2).max(40).optional(),
+ permissions: z.array(z.string().min(1).max(60)).max(50).optional(),
+});
+
+const userRolesSchema = z.object({
+ roles: z.array(z.string().min(1).max(40)).max(20),
+});
+
export function createAdminRoutes({ prisma }: AppDeps) {
const router = Router();
- router.use(authenticate(prisma), requireAdmin);
+ // Uwierzytelnianie wspólne; autoryzacja per trasa przez can()
+ // (dawniej jeden requireAdmin na cały router).
+ router.use(authenticate(prisma));
+
+ /** Uprawnienia wywołującego — do redakcji PII w zwracanych DTO. */
+ const permsOf = (req: { user?: { platformPermissions: readonly string[] } }) =>
+ req.user!.platformPermissions;
+
+ /** Strażnik celu: mutacja konta z grantem platformowym wymaga roles:manage. */
+ const guardStaffTarget = (userId: string, permissions: readonly string[]) =>
+ assertNotStaffTarget(prisma, userId, permissions);
const listGymsQuerySchema = z.object({
q: z.string().trim().max(200).optional(),
@@ -205,18 +248,19 @@ export function createAdminRoutes({ prisma }: AppDeps) {
* @openapi
* /admin/gyms:
* get:
- * summary: List gyms (admin). Query: q (nazwa/adres/miasto/kod/właściciel), kind (REAL|VIRTUAL).
- * Each gym includes `owners` (members with OWNER role) and `_count.memberships`.
+ * summary: List gyms (gyms:manage lub users:manage — picker członkostw w formularzu usera). Query: q (nazwa/adres/miasto/kod/właściciel), kind (REAL|VIRTUAL).
+ * Each gym includes `owners` (members with OWNER role, PII redacted without pii:read) and `_count.memberships`.
* tags: [Admin]
* responses:
* 200: { description: OK }
*/
router.get(
'/gyms',
+ canAny([PERMISSIONS.GYMS_MANAGE, PERMISSIONS.USERS_MANAGE]),
validate(listGymsQuerySchema, 'query'),
asyncHandler(async (req, res) => {
const q = req.query as z.infer;
- const result = await listGyms(prisma, { q: q.q, kind: q.kind });
+ const result = await listGyms(prisma, { q: q.q, kind: q.kind }, permsOf(req));
res.json(result);
}),
);
@@ -225,13 +269,14 @@ export function createAdminRoutes({ prisma }: AppDeps) {
* @openapi
* /admin/gyms:
* post:
- * summary: Create gym (admin; ownerId becomes OWNER)
+ * summary: Create gym (gyms:manage; ownerId becomes OWNER)
* tags: [Admin]
* responses:
* 201: { description: Created }
*/
router.post(
'/gyms',
+ can(PERMISSIONS.GYMS_MANAGE),
validate(createGymSchema),
asyncHandler(async (req, res) => {
const data = req.body as z.infer;
@@ -253,7 +298,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
* @openapi
* /admin/gyms/{id}/owners:
* post:
- * summary: Grant the OWNER role to a user in a gym (admin)
+ * summary: Grant the OWNER role to a user in a gym (gyms:manage)
* tags: [Admin]
* responses:
* 200: { description: OK }
@@ -261,6 +306,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
*/
router.post(
'/gyms/:id/owners',
+ can(PERMISSIONS.GYMS_MANAGE),
validate(gymOwnerSchema),
asyncHandler(async (req, res) => {
const { userId } = req.body as z.infer;
@@ -280,7 +326,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
* @openapi
* /admin/gyms/{id}/owners/{userId}:
* delete:
- * summary: Revoke the OWNER role in a gym (admin; membership removed when no roles left)
+ * summary: Revoke the OWNER role in a gym (gyms:manage; membership removed when no roles left)
* tags: [Admin]
* responses:
* 204: { description: Revoked }
@@ -288,6 +334,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
*/
router.delete(
'/gyms/:id/owners/:userId',
+ can(PERMISSIONS.GYMS_MANAGE),
asyncHandler(async (req, res) => {
await removeGymOwner(prisma, req.params.id, req.params.userId);
await logActivity(prisma, {
@@ -305,13 +352,14 @@ export function createAdminRoutes({ prisma }: AppDeps) {
* @openapi
* /admin/gyms/{id}:
* patch:
- * summary: Update gym (admin)
+ * summary: Update gym (gyms:manage)
* tags: [Admin]
* responses:
* 200: { description: OK }
*/
router.patch(
'/gyms/:id',
+ can(PERMISSIONS.GYMS_MANAGE),
validate(updateGymSchema),
asyncHandler(async (req, res) => {
const data = req.body as z.infer;
@@ -331,13 +379,14 @@ export function createAdminRoutes({ prisma }: AppDeps) {
* @openapi
* /admin/gyms/{id}:
* delete:
- * summary: Delete gym (admin). Memberships are removed; user plans are kept.
+ * summary: Delete gym (gyms:manage). Memberships are removed; user plans are kept.
* tags: [Admin]
* responses:
* 204: { description: Deleted }
*/
router.delete(
'/gyms/:id',
+ can(PERMISSIONS.GYMS_MANAGE),
asyncHandler(async (req, res) => {
const result = await deleteGym(prisma, req.params.id);
await logActivity(prisma, {
@@ -360,7 +409,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
* @openapi
* /admin/gyms/{id}/logs:
* get:
- * summary: Audit log of one gym (admin) — gym.* entries, membership.* tied to this gym
+ * summary: Audit log of one gym (gyms:manage) — gym.* entries, membership.* tied to this gym
* (details.gymId) and this gym's claims/invitations. Query: limit (default 50, max 500), offset.
* tags: [Admin]
* responses:
@@ -369,6 +418,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
*/
router.get(
'/gyms/:id/logs',
+ can(PERMISSIONS.GYMS_MANAGE),
validate(gymLogsQuerySchema, 'query'),
asyncHandler(async (req, res) => {
const gym = await prisma.gym.findUnique({
@@ -378,7 +428,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
if (!gym) throw notFound('Gym not found');
const q = req.query as z.infer;
const result = await listGymAuditLogs(prisma, req.params.id, q.limit ?? 50, q.offset ?? 0);
- res.json(result);
+ res.json(redactActivityLogResult(result, permsOf(req)));
}),
);
@@ -393,7 +443,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
* @openapi
* /admin/gyms/{id}/members:
* get:
- * summary: Members of one gym (admin). Query: q (imię/nazwisko/email), role (OWNER|TRAINER|MEMBER), limit (default 50, max 200), offset.
+ * summary: Members of one gym (gyms:manage). 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:
@@ -402,10 +452,11 @@ export function createAdminRoutes({ prisma }: AppDeps) {
*/
router.get(
'/gyms/:id/members',
+ can(PERMISSIONS.GYMS_MANAGE),
validate(gymMembersQuerySchema, 'query'),
asyncHandler(async (req, res) => {
const q = req.query as z.infer;
- const result = await listGymMembers(prisma, req.params.id, q);
+ const result = await listGymMembers(prisma, req.params.id, q, permsOf(req));
res.json(result);
}),
);
@@ -414,7 +465,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
* @openapi
* /admin/gyms/{id}/related:
* get:
- * summary: Claims and invitations tied to one gym (admin), newest first.
+ * summary: Claims and invitations tied to one gym (gyms:manage), newest first.
* tags: [Admin]
* responses:
* 200: { description: OK, returns { claims, invitations } }
@@ -422,8 +473,9 @@ export function createAdminRoutes({ prisma }: AppDeps) {
*/
router.get(
'/gyms/:id/related',
+ can(PERMISSIONS.GYMS_MANAGE),
asyncHandler(async (req, res) => {
- const result = await listGymRelated(prisma, req.params.id);
+ const result = await listGymRelated(prisma, req.params.id, permsOf(req));
res.json(result);
}),
);
@@ -432,13 +484,14 @@ export function createAdminRoutes({ prisma }: AppDeps) {
* @openapi
* /admin/gyms/{id}/exceptions:
* get:
- * summary: List a gym's schedule exceptions (admin)
+ * summary: List a gym's schedule exceptions (gyms:manage)
* tags: [Admin]
* responses:
* 200: { description: OK }
*/
router.get(
'/gyms/:id/exceptions',
+ can(PERMISSIONS.GYMS_MANAGE),
asyncHandler(async (req, res) => {
const result = await listGymExceptions(prisma, req.params.id);
res.json(result);
@@ -449,7 +502,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
* @openapi
* /admin/gyms/{id}/exceptions:
* post:
- * summary: Add a one-off schedule exception (admin)
+ * summary: Add a one-off schedule exception (gyms:manage)
* tags: [Admin]
* responses:
* 201: { description: Created }
@@ -457,6 +510,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
*/
router.post(
'/gyms/:id/exceptions',
+ can(PERMISSIONS.GYMS_MANAGE),
validate(gymExceptionSchema),
asyncHandler(async (req, res) => {
const data = req.body as z.infer;
@@ -479,13 +533,14 @@ export function createAdminRoutes({ prisma }: AppDeps) {
* @openapi
* /admin/gyms/{id}/exceptions/{exceptionId}:
* delete:
- * summary: Remove a schedule exception (admin)
+ * summary: Remove a schedule exception (gyms:manage)
* tags: [Admin]
* responses:
* 204: { description: Removed }
*/
router.delete(
'/gyms/:id/exceptions/:exceptionId',
+ can(PERMISSIONS.GYMS_MANAGE),
asyncHandler(async (req, res) => {
const result = await deleteGymException(prisma, req.params.id, req.params.exceptionId);
await logActivity(prisma, {
@@ -514,7 +569,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
* @openapi
* /admin/gyms/{id}/equipment:
* post:
- * summary: Create an equipment instance in a gym (admin); repeats of a catalog type are new instances
+ * summary: Create an equipment instance in a gym (gyms:manage); repeats of a catalog type are new instances
* tags: [Admin]
* responses:
* 200: { description: OK, returns { gym, instance } }
@@ -523,6 +578,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
*/
router.post(
'/gyms/:id/equipment',
+ can(PERMISSIONS.GYMS_MANAGE),
validate(gymEquipmentSchema),
asyncHandler(async (req, res) => {
const { equipmentId, quantity, spec } = req.body as z.infer;
@@ -542,7 +598,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
* @openapi
* /admin/gyms/{id}/equipment/{instanceId}:
* patch:
- * summary: Change quantity and/or spec override of an equipment instance (admin); spec:null clears the override
+ * summary: Change quantity and/or spec override of an equipment instance (gyms:manage); spec:null clears the override
* tags: [Admin]
* responses:
* 200: { description: OK }
@@ -551,6 +607,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
*/
router.patch(
'/gyms/:id/equipment/:instanceId',
+ can(PERMISSIONS.GYMS_MANAGE),
validate(gymEquipmentInstanceSchema),
asyncHandler(async (req, res) => {
const body = req.body as z.infer;
@@ -576,7 +633,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
* @openapi
* /admin/gyms/{id}/equipment/{instanceId}:
* delete:
- * summary: Remove an equipment instance (and its photos) from a gym (admin)
+ * summary: Remove an equipment instance (and its photos) from a gym (gyms:manage)
* tags: [Admin]
* responses:
* 204: { description: Removed }
@@ -585,6 +642,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
*/
router.delete(
'/gyms/:id/equipment/:instanceId',
+ can(PERMISSIONS.GYMS_MANAGE),
asyncHandler(async (req, res) => {
const result = await removeGymEquipment(prisma, req.params.id, req.params.instanceId);
await logActivity(prisma, {
@@ -607,13 +665,14 @@ export function createAdminRoutes({ prisma }: AppDeps) {
* @openapi
* /admin/gyms/claims:
* get:
- * summary: List gym claims (admin, optional ?status=)
+ * summary: List gym claims (verifications:view, optional ?status=)
* tags: [Admin]
* responses:
* 200: { description: OK }
*/
router.get(
'/gyms/claims',
+ can(PERMISSIONS.VERIFICATIONS_VIEW),
validate(claimsQuerySchema, 'query'),
asyncHandler(async (req, res) => {
const q = req.query as z.infer;
@@ -626,7 +685,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
* @openapi
* /admin/gyms/claims/{id}:
* get:
- * summary: Gym claim detail (admin)
+ * summary: Gym claim detail (verifications:view)
* tags: [Admin]
* responses:
* 200: { description: OK }
@@ -634,6 +693,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
*/
router.get(
'/gyms/claims/:id',
+ can(PERMISSIONS.VERIFICATIONS_VIEW),
asyncHandler(async (req, res) => {
const result = await getGymClaim(prisma, req.params.id);
res.json(result);
@@ -644,7 +704,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
* @openapi
* /admin/gyms/claims/{id}/documents/{docId}:
* get:
- * summary: Download a claim document (admin)
+ * summary: Download a claim document (verifications:view)
* tags: [Admin]
* responses:
* 200: { description: File (attachment) }
@@ -652,6 +712,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
*/
router.get(
'/gyms/claims/:id/documents/:docId',
+ can(PERMISSIONS.VERIFICATIONS_VIEW),
asyncHandler(async (req, res) => {
const claim = await prisma.gymClaim.findUnique({
where: { id: req.params.id },
@@ -673,7 +734,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
* @openapi
* /admin/gyms/claims/{id}/approve:
* post:
- * summary: Approve a gym claim (admin) — virtual → REAL or creates a new REAL gym
+ * summary: Approve a gym claim (verifications:view) — virtual → REAL or creates a new REAL gym
* tags: [Admin]
* responses:
* 200: { description: Approved }
@@ -682,6 +743,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
*/
router.post(
'/gyms/claims/:id/approve',
+ can(PERMISSIONS.VERIFICATIONS_VIEW),
asyncHandler(async (req, res) => {
await approveGymClaim(prisma, req.user!.id, req.params.id);
await logActivity(prisma, {
@@ -702,7 +764,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
* @openapi
* /admin/gyms/claims/{id}/reject:
* post:
- * summary: Reject a gym claim with an optional reason (admin)
+ * summary: Reject a gym claim with an optional reason (verifications:view)
* tags: [Admin]
* responses:
* 200: { description: Rejected }
@@ -711,6 +773,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
*/
router.post(
'/gyms/claims/:id/reject',
+ can(PERMISSIONS.VERIFICATIONS_VIEW),
validate(rejectClaimSchema),
asyncHandler(async (req, res) => {
const { reason } = req.body as z.infer;
@@ -730,7 +793,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
* @openapi
* /admin/gyms/{id}:
* get:
- * summary: Get gym detail (admin)
+ * summary: Get gym detail (gyms:manage)
* tags: [Admin]
* responses:
* 200: { description: OK }
@@ -738,8 +801,9 @@ export function createAdminRoutes({ prisma }: AppDeps) {
*/
router.get(
'/gyms/:id',
+ can(PERMISSIONS.GYMS_MANAGE),
asyncHandler(async (req, res) => {
- const gym = await getGym(prisma, req.params.id);
+ const gym = await getGym(prisma, req.params.id, permsOf(req));
res.json(gym);
}),
);
@@ -748,16 +812,17 @@ export function createAdminRoutes({ prisma }: AppDeps) {
* @openapi
* /admin/users:
* get:
- * summary: List users (admin, optional ?search=)
+ * summary: List users (users:read, optional ?search=). Bez pii:read: e-mail maskowany, phone/birthDate null.
* tags: [Admin]
* responses:
* 200: { description: OK }
*/
router.get(
'/users',
+ can(PERMISSIONS.USERS_READ),
asyncHandler(async (req, res) => {
const search = req.query.search as string | undefined;
- const result = await listUsers(prisma, search);
+ const result = await listUsers(prisma, search, permsOf(req));
res.json(result);
}),
);
@@ -766,7 +831,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
* @openapi
* /admin/users:
* post:
- * summary: Create user (admin)
+ * summary: Create user (users:manage). Role platformowa nadawana osobno (PUT /admin/users/{id}/roles).
* tags: [Admin]
* responses:
* 201: { description: Created }
@@ -774,16 +839,18 @@ export function createAdminRoutes({ prisma }: AppDeps) {
*/
router.post(
'/users',
+ can(PERMISSIONS.USERS_MANAGE),
validate(createUserSchema),
asyncHandler(async (req, res) => {
const data = req.body as z.infer;
- const result = await createUser(prisma, data);
+ const result = await createUser(prisma, data, permsOf(req));
await logActivity(prisma, {
actorId: req.user!.id,
action: 'user.created',
entityType: 'user',
entityId: result.user.id,
- details: { email: result.user.email, isAdmin: result.user.isAdmin },
+ // log przechowuje surowy e-mail; redakcja następuje przy odczycie logów
+ details: { email: data.email.toLowerCase(), platformRoles: [] },
});
res.status(201).json(result);
}),
@@ -793,26 +860,32 @@ export function createAdminRoutes({ prisma }: AppDeps) {
* @openapi
* /admin/users/{id}:
* patch:
- * summary: Update user (admin). Role or status change increments token_version (JWT revocation).
+ * summary: Update user (users:manage). Mutacja konta z grantem platformowym wymaga roles:manage;
+ * pola PII (email/phone/birthDate) wymagają pii:read. Zmiana statusu incrementuje token_version (JWT revocation).
* Status SUSPENDED requires future suspensionUntil; BANNED requires restrictionReason.
* Login/refresh of a suspended (until active) or banned account returns 403 ACCOUNT_SUSPENDED / ACCOUNT_BANNED.
* tags: [Admin]
* responses:
* 200: { description: OK }
- * 403: { description: Attempt to remove the last admin role }
+ * 403: { description: 'STAFF_MUTATION_FORBIDDEN / PII_FORBIDDEN' }
* 404: { description: User not found }
* 409: { description: Email already registered }
*/
router.patch(
'/users/:id',
+ can(PERMISSIONS.USERS_MANAGE),
validate(updateUserSchema),
asyncHandler(async (req, res) => {
const data = req.body as z.infer;
- const result = await updateUser(prisma, req.params.id, data, req.user!.id);
- // Zmiany security logujemy osobno: kara (status) i rola (isAdmin).
+ const result = await updateUser(prisma, req.params.id, data, {
+ actorId: req.user!.id,
+ permissions: permsOf(req),
+ });
+ // Zmiany security logujemy osobno: kara (status). Rola platformowa — osobny
+ // strumień user.roles.changed (PUT /users/{id}/roles).
// W `user.updated` tylko NAZWY pól (jak profile.updated), nigdy wartości;
// `password` nie trafia do logów w ogóle.
- const { status, isAdmin, suspensionUntil, restrictionReason, ...rest } = data;
+ const { status, suspensionUntil, restrictionReason, ...rest } = data;
const fields = Object.keys(rest).filter((f) => f !== 'password');
if (fields.length > 0) {
await logActivity(prisma, {
@@ -836,15 +909,6 @@ export function createAdminRoutes({ prisma }: AppDeps) {
},
});
}
- if (isAdmin !== undefined) {
- await logActivity(prisma, {
- actorId: req.user!.id,
- action: 'user.admin.changed',
- entityType: 'user',
- entityId: req.params.id,
- details: { isAdmin },
- });
- }
res.json(result);
}),
);
@@ -853,16 +917,22 @@ export function createAdminRoutes({ prisma }: AppDeps) {
* @openapi
* /admin/users/{id}:
* delete:
- * summary: Delete user (admin). Plans/sessions are cascade-deleted.
+ * summary: Delete user (users:manage). Konto z grantem platformowym wymaga roles:manage;
+ * usunięcie ostatniego użytkownika z roles:manage → 403 (LAST_ROLES_MANAGER).
+ * Plans/sessions are cascade-deleted.
* tags: [Admin]
* responses:
* 204: { description: Deleted }
- * 403: { description: Own account or the last admin }
+ * 403: { description: Own account, staff target without roles:manage, or the last roles:manage holder }
*/
router.delete(
'/users/:id',
+ can(PERMISSIONS.USERS_MANAGE),
asyncHandler(async (req, res) => {
- const result = await deleteUser(prisma, req.params.id, req.user!.id);
+ const result = await deleteUser(prisma, req.params.id, {
+ actorId: req.user!.id,
+ permissions: permsOf(req),
+ });
await logActivity(prisma, {
actorId: req.user!.id,
action: 'user.deleted',
@@ -875,20 +945,72 @@ export function createAdminRoutes({ prisma }: AppDeps) {
}),
);
+ /**
+ * @openapi
+ * /admin/users/{id}/roles:
+ * get:
+ * summary: Platform role keys of one user (users:read)
+ * tags: [Admin]
+ * responses:
+ * 200: { description: OK, returns { roles: string[] } }
+ */
+ router.get(
+ '/users/:id/roles',
+ can(PERMISSIONS.USERS_READ),
+ asyncHandler(async (req, res) => {
+ const result = await getUserPlatformRoles(prisma, req.params.id);
+ res.json(result);
+ }),
+ );
+
+ /**
+ * @openapi
+ * /admin/users/{id}/roles:
+ * put:
+ * summary: Replace the set of platform roles of a user (roles:manage). Zdejmuje/odbiera
+ * roles:manage jako ostatniemu posiadaczowi → 403 (LAST_ROLES_MANAGER). Zmiana podbija token_version.
+ * tags: [Admin]
+ * responses:
+ * 200: { description: OK, returns { roles } }
+ * 400: { description: Unknown role key }
+ * 403: { description: LAST_ROLES_MANAGER }
+ * 404: { description: User not found }
+ */
+ router.put(
+ '/users/:id/roles',
+ can(PERMISSIONS.ROLES_MANAGE),
+ validate(userRolesSchema),
+ asyncHandler(async (req, res) => {
+ const { roles } = req.body as z.infer;
+ const result = await setUserPlatformRoles(prisma, req.params.id, roles);
+ await logActivity(prisma, {
+ actorId: req.user!.id,
+ action: 'user.roles.changed',
+ entityType: 'user',
+ entityId: req.params.id,
+ details: { roles },
+ });
+ res.json(result);
+ }),
+ );
+
/**
* @openapi
* /admin/users/{id}/memberships:
* post:
- * summary: Assign gym membership/role (admin)
+ * summary: Assign gym membership/role (users:manage; na koncie z grantem platformowym wymaga roles:manage)
* tags: [Admin]
* responses:
* 201: { description: Created }
+ * 403: { description: STAFF_MUTATION_FORBIDDEN }
* 409: { description: Membership already exists }
*/
router.post(
'/users/:id/memberships',
+ can(PERMISSIONS.USERS_MANAGE),
validate(membershipSchema),
asyncHandler(async (req, res) => {
+ await guardStaffTarget(req.params.id, permsOf(req));
const { gymId, roles } = req.body as z.infer;
const result = await addMembership(prisma, req.params.id, gymId, roles);
await logActivity(prisma, {
@@ -906,16 +1028,19 @@ export function createAdminRoutes({ prisma }: AppDeps) {
* @openapi
* /admin/users/{id}/memberships/{gymId}:
* patch:
- * summary: Change gym membership role (admin)
+ * summary: Change gym membership role (users:manage; na koncie z grantem platformowym wymaga roles:manage)
* tags: [Admin]
* responses:
* 200: { description: OK }
+ * 403: { description: STAFF_MUTATION_FORBIDDEN }
* 404: { description: Membership not found }
*/
router.patch(
'/users/:id/memberships/:gymId',
+ can(PERMISSIONS.USERS_MANAGE),
validate(updateMembershipSchema),
asyncHandler(async (req, res) => {
+ await guardStaffTarget(req.params.id, permsOf(req));
const { roles } = req.body as z.infer;
const result = await updateMembership(prisma, req.params.id, req.params.gymId, roles);
await logActivity(prisma, {
@@ -933,15 +1058,18 @@ export function createAdminRoutes({ prisma }: AppDeps) {
* @openapi
* /admin/users/{id}/memberships/{gymId}:
* delete:
- * summary: Remove gym membership (admin). Optional body: { reason } (audyt).
+ * summary: Remove gym membership (users:manage; na koncie z grantem platformowym wymaga roles:manage). Optional body: { reason } (audyt).
* tags: [Admin]
* responses:
* 204: { description: Deleted }
+ * 403: { description: STAFF_MUTATION_FORBIDDEN }
*/
router.delete(
'/users/:id/memberships/:gymId',
+ can(PERMISSIONS.USERS_MANAGE),
validate(removeMembershipSchema),
asyncHandler(async (req, res) => {
+ await guardStaffTarget(req.params.id, permsOf(req));
const { reason } = req.body as z.infer;
const result = await removeMembership(prisma, req.params.id, req.params.gymId);
await logActivity(prisma, {
@@ -964,7 +1092,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
* @openapi
* /admin/users/{id}/focus-chain:
* get:
- * summary: User's causal chain — priority/exclusion muscles linked to active plan exercises (admin)
+ * summary: User's causal chain — priority/exclusion muscles linked to active plan exercises (users:read)
* tags: [Admin]
* responses:
* 200: { description: OK }
@@ -972,6 +1100,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
*/
router.get(
'/users/:id/focus-chain',
+ can(PERMISSIONS.USERS_READ),
asyncHandler(async (req, res) => {
const result = await getFocusChain(prisma, req.params.id);
res.json(result);
@@ -982,7 +1111,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
* @openapi
* /admin/users/{id}/killstreak:
* get:
- * summary: User's killstreak (admin)
+ * summary: User's killstreak (users:read)
* tags: [Admin]
* responses:
* 200: { description: OK }
@@ -990,6 +1119,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
*/
router.get(
'/users/:id/killstreak',
+ can(PERMISSIONS.USERS_READ),
asyncHandler(async (req, res) => {
await ensureUser(prisma, req.params.id);
const killstreak = await getKillstreak(prisma, req.params.id);
@@ -1001,7 +1131,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
* @openapi
* /admin/users/{id}/body-parameters:
* get:
- * summary: User's body parameters over time (admin)
+ * summary: User's body parameters over time (users:read)
* tags: [Admin]
* responses:
* 200: { description: OK }
@@ -1009,6 +1139,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
*/
router.get(
'/users/:id/body-parameters',
+ can(PERMISSIONS.USERS_READ),
asyncHandler(async (req, res) => {
await ensureUser(prisma, req.params.id);
const result = await getBodyParameters(prisma, req.params.id);
@@ -1020,7 +1151,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
* @openapi
* /admin/users/{id}/body-parameters/weight:
* post:
- * summary: Add weight measurement for user (admin)
+ * summary: Add weight measurement for user (users:manage; na koncie z grantem platformowym wymaga roles:manage)
* tags: [Admin]
* responses:
* 201: { description: Created }
@@ -1028,9 +1159,11 @@ export function createAdminRoutes({ prisma }: AppDeps) {
*/
router.post(
'/users/:id/body-parameters/weight',
+ can(PERMISSIONS.USERS_MANAGE),
validate(weightSchema),
asyncHandler(async (req, res) => {
await ensureUser(prisma, req.params.id);
+ await guardStaffTarget(req.params.id, permsOf(req));
const data = req.body as z.infer;
const result = await addWeight(prisma, req.params.id, data);
await logActivity(prisma, {
@@ -1048,7 +1181,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
* @openapi
* /admin/users/{id}/body-parameters/weight/{measurementId}:
* delete:
- * summary: Delete a weight measurement of user (admin)
+ * summary: Delete a weight measurement of user (users:manage; na koncie z grantem platformowym wymaga roles:manage)
* tags: [Admin]
* responses:
* 204: { description: Deleted }
@@ -1056,8 +1189,10 @@ export function createAdminRoutes({ prisma }: AppDeps) {
*/
router.delete(
'/users/:id/body-parameters/weight/:measurementId',
+ can(PERMISSIONS.USERS_MANAGE),
asyncHandler(async (req, res) => {
await ensureUser(prisma, req.params.id);
+ await guardStaffTarget(req.params.id, permsOf(req));
const result = await deleteWeight(prisma, req.params.id, req.params.measurementId);
await logActivity(prisma, {
actorId: req.user!.id,
@@ -1074,7 +1209,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
* @openapi
* /admin/users/{id}/body-parameters/circumference:
* post:
- * summary: Add circumference measurement for user (admin)
+ * summary: Add circumference measurement for user (users:manage; na koncie z grantem platformowym wymaga roles:manage)
* tags: [Admin]
* responses:
* 201: { description: Created }
@@ -1082,9 +1217,11 @@ export function createAdminRoutes({ prisma }: AppDeps) {
*/
router.post(
'/users/:id/body-parameters/circumference',
+ can(PERMISSIONS.USERS_MANAGE),
validate(circumferenceSchema),
asyncHandler(async (req, res) => {
await ensureUser(prisma, req.params.id);
+ await guardStaffTarget(req.params.id, permsOf(req));
const data = req.body as z.infer;
const result = await addCircumference(prisma, req.params.id, data);
await logActivity(prisma, {
@@ -1107,7 +1244,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
* @openapi
* /admin/users/{id}/body-parameters/circumference/{measurementId}:
* delete:
- * summary: Delete a circumference measurement of user (admin)
+ * summary: Delete a circumference measurement of user (users:manage; na koncie z grantem platformowym wymaga roles:manage)
* tags: [Admin]
* responses:
* 204: { description: Deleted }
@@ -1115,8 +1252,10 @@ export function createAdminRoutes({ prisma }: AppDeps) {
*/
router.delete(
'/users/:id/body-parameters/circumference/:measurementId',
+ can(PERMISSIONS.USERS_MANAGE),
asyncHandler(async (req, res) => {
await ensureUser(prisma, req.params.id);
+ await guardStaffTarget(req.params.id, permsOf(req));
const result = await deleteCircumference(prisma, req.params.id, req.params.measurementId);
await logActivity(prisma, {
actorId: req.user!.id,
@@ -1139,7 +1278,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
* @openapi
* /admin/users/{id}/history:
* get:
- * summary: User's training history (admin). Query: month=YYYY-MM.
+ * summary: User's training history (users:read). Query: month=YYYY-MM.
* tags: [Admin]
* responses:
* 200: { description: OK }
@@ -1148,6 +1287,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
*/
router.get(
'/users/:id/history',
+ can(PERMISSIONS.USERS_READ),
validate(historyQuerySchema, 'query'),
asyncHandler(async (req, res) => {
await ensureUser(prisma, req.params.id);
@@ -1161,7 +1301,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
* @openapi
* /admin/users/{id}/exercise-progress:
* get:
- * summary: User's per-exercise progress — 1RM Epley + volume (admin)
+ * summary: User's per-exercise progress — 1RM Epley + volume (users:read)
* tags: [Admin]
* responses:
* 200: { description: OK }
@@ -1169,6 +1309,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
*/
router.get(
'/users/:id/exercise-progress',
+ can(PERMISSIONS.USERS_READ),
asyncHandler(async (req, res) => {
await ensureUser(prisma, req.params.id);
const result = await getExerciseProgress(prisma, req.params.id);
@@ -1186,8 +1327,8 @@ export function createAdminRoutes({ prisma }: AppDeps) {
* @openapi
* /admin/users/{id}/activity:
* get:
- * summary: Account history — audit stream scoped to the user (admin).
- * scope=onAccount (default): logi o bycie `user` z jego ID — logowania (IP), edycje (admin/self), kary (status/reason), rola admina, utworzenie/usunięcie.
+ * summary: Account history — audit stream scoped to the user (logs:view; bez pii:read e-maile maskowane).
+ * scope=onAccount (default): logi o bycie `user` z jego ID — logowania (IP), edycje (admin/self), kary (status/reason), role platformowe, utworzenie/usunięcie.
* scope=performed: akcje WYKONANE przez użytkownika (actorId). scope=all: unia obu strumieni.
* Query: scope, limit (default 50, max 500), offset (default 0).
* tags: [Admin]
@@ -1197,6 +1338,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
*/
router.get(
'/users/:id/activity',
+ can(PERMISSIONS.LOGS_VIEW),
validate(userActivityQuerySchema, 'query'),
asyncHandler(async (req, res) => {
await ensureUser(prisma, req.params.id);
@@ -1207,7 +1349,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
limit: q.limit ?? 50,
offset: q.offset ?? 0,
});
- res.json(result);
+ res.json(redactActivityLogResult(result, permsOf(req)));
}),
);
@@ -1230,7 +1372,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
* @openapi
* /admin/logs:
* get:
- * summary: Activity log — user actions from the app (admin).
+ * summary: Activity log — user actions from the app (logs:view; bez pii:read e-maile maskowane).
* Query: action, userId, from/to (YYYY-MM-DD), limit (default 100, max 500), offset (default 0).
* tags: [Admin]
* responses:
@@ -1238,6 +1380,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
*/
router.get(
'/logs',
+ can(PERMISSIONS.LOGS_VIEW),
validate(logsQuerySchema, 'query'),
asyncHandler(async (req, res) => {
const q = req.query as z.infer;
@@ -1249,10 +1392,133 @@ export function createAdminRoutes({ prisma }: AppDeps) {
limit: q.limit ?? 100,
offset: q.offset ?? 0,
});
+ res.json(redactActivityLogResult(result, permsOf(req)));
+ }),
+ );
+
+ /**
+ * @openapi
+ * /admin/permissions:
+ * get:
+ * summary: Permission key catalog (roles:manage) — for the role editor UI.
+ * tags: [Admin]
+ * responses:
+ * 200: { description: OK, returns { permissions: string[] } }
+ */
+ router.get(
+ '/permissions',
+ can(PERMISSIONS.ROLES_MANAGE),
+ asyncHandler(async (_req, res) => {
+ res.json({ permissions: PERMISSION_KEYS });
+ }),
+ );
+
+ /**
+ * @openapi
+ * /admin/roles:
+ * get:
+ * summary: List platform roles with permission sets and grant counts (roles:manage)
+ * tags: [Admin]
+ * responses:
+ * 200: { description: OK, returns { roles: [{ id, key, permissions, isSystem, grantCount }] } }
+ */
+ router.get(
+ '/roles',
+ can(PERMISSIONS.ROLES_MANAGE),
+ asyncHandler(async (_req, res) => {
+ const result = await listRoles(prisma);
res.json(result);
}),
);
+ /**
+ * @openapi
+ * /admin/roles:
+ * post:
+ * summary: Create a custom role (roles:manage). key: ^[A-Z][A-Z0-9_]{1,39}$; nieznane klucze uprawnień odrzucane.
+ * tags: [Admin]
+ * responses:
+ * 201: { description: Created }
+ * 400: { description: Invalid key }
+ * 409: { description: Role key already exists }
+ */
+ router.post(
+ '/roles',
+ can(PERMISSIONS.ROLES_MANAGE),
+ validate(createRoleSchema),
+ asyncHandler(async (req, res) => {
+ const data = req.body as z.infer;
+ const result = await createRole(prisma, data);
+ await logActivity(prisma, {
+ actorId: req.user!.id,
+ action: 'role.created',
+ entityType: 'role',
+ entityId: result.role.id,
+ details: { key: result.role.key, permissions: result.role.permissions },
+ });
+ res.status(201).json(result);
+ }),
+ );
+
+ /**
+ * @openapi
+ * /admin/roles/{id}:
+ * patch:
+ * summary: Rename and/or re-permission a role (roles:manage). System roles: klucz stały, roles:manage przypięty;
+ * usunięcie roles:manage grożące zerem posiadaczy → 403 (LAST_ROLES_MANAGER).
+ * tags: [Admin]
+ * responses:
+ * 200: { description: OK }
+ * 400: { description: Invalid key }
+ * 403: { description: System role rename / roles:manage removal / LAST_ROLES_MANAGER }
+ * 404: { description: Role not found }
+ */
+ router.patch(
+ '/roles/:id',
+ can(PERMISSIONS.ROLES_MANAGE),
+ validate(updateRoleSchema),
+ asyncHandler(async (req, res) => {
+ const data = req.body as z.infer;
+ const result = await updateRole(prisma, req.params.id, data);
+ await logActivity(prisma, {
+ actorId: req.user!.id,
+ action: 'role.updated',
+ entityType: 'role',
+ entityId: req.params.id,
+ details: { key: result.role.key, permissions: result.role.permissions },
+ });
+ res.json(result);
+ }),
+ );
+
+ /**
+ * @openapi
+ * /admin/roles/{id}:
+ * delete:
+ * summary: Delete a custom role (roles:manage). System roles nieusuwalne; rola z grantami → 409.
+ * tags: [Admin]
+ * responses:
+ * 204: { description: Deleted }
+ * 403: { description: Cannot delete a system role }
+ * 404: { description: Role not found }
+ * 409: { description: Role is still assigned to users }
+ */
+ router.delete(
+ '/roles/:id',
+ can(PERMISSIONS.ROLES_MANAGE),
+ asyncHandler(async (req, res) => {
+ const result = await deleteRole(prisma, req.params.id);
+ await logActivity(prisma, {
+ actorId: req.user!.id,
+ action: 'role.deleted',
+ entityType: 'role',
+ entityId: req.params.id,
+ details: { key: result.role.key },
+ });
+ res.status(204).end();
+ }),
+ );
+
const focusAreaSchema = z
.object({
name: z.string().min(1).max(100),
@@ -1284,13 +1550,14 @@ export function createAdminRoutes({ prisma }: AppDeps) {
* @openapi
* /admin/focus-areas:
* get:
- * summary: List focus areas with exercise usage counts (admin)
+ * summary: List focus areas with exercise usage counts (catalog:manage)
* tags: [Admin]
* responses:
* 200: { description: OK }
*/
router.get(
'/focus-areas',
+ can(PERMISSIONS.CATALOG_MANAGE),
asyncHandler(async (_req, res) => {
const result = await listFocusAreasWithUsage(prisma);
res.json(result);
@@ -1301,7 +1568,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
* @openapi
* /admin/focus-areas:
* post:
- * summary: Create a focus area (admin)
+ * summary: Create a focus area (catalog:manage)
* tags: [Admin]
* responses:
* 201: { description: Created }
@@ -1309,6 +1576,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
*/
router.post(
'/focus-areas',
+ can(PERMISSIONS.CATALOG_MANAGE),
validate(focusAreaSchema),
asyncHandler(async (req, res) => {
const data = req.body as z.infer;
@@ -1328,7 +1596,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
* @openapi
* /admin/focus-areas/{id}:
* patch:
- * summary: Update a focus area (admin)
+ * summary: Update a focus area (catalog:manage)
* tags: [Admin]
* responses:
* 200: { description: OK }
@@ -1336,6 +1604,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
*/
router.patch(
'/focus-areas/:id',
+ can(PERMISSIONS.CATALOG_MANAGE),
validate(focusAreaUpdateSchema),
asyncHandler(async (req, res) => {
const data = req.body as z.infer;
@@ -1355,7 +1624,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
* @openapi
* /admin/focus-areas/{id}:
* delete:
- * summary: Delete a focus area (admin)
+ * summary: Delete a focus area (catalog:manage)
* tags: [Admin]
* responses:
* 204: { description: Deleted }
@@ -1363,6 +1632,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
*/
router.delete(
'/focus-areas/:id',
+ can(PERMISSIONS.CATALOG_MANAGE),
asyncHandler(async (req, res) => {
const result = await deleteFocusArea(prisma, req.params.id);
await logActivity(prisma, {
@@ -1389,13 +1659,14 @@ export function createAdminRoutes({ prisma }: AppDeps) {
* @openapi
* /admin/announcements:
* get:
- * summary: List all announcements or those of one gym (?gymId=) (admin)
+ * summary: List all announcements or those of one gym (?gymId=) (announcements:manage)
* tags: [Admin]
* responses:
* 200: { description: OK }
*/
router.get(
'/announcements',
+ can(PERMISSIONS.ANNOUNCEMENTS_MANAGE),
asyncHandler(async (req, res) => {
const gymId = typeof req.query.gymId === 'string' ? req.query.gymId : null;
const result = await listAnnouncementsForAdmin(prisma, { gymId });
@@ -1407,7 +1678,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
* @openapi
* /admin/announcements:
* post:
- * summary: Create an announcement — global (gymId null) or for a gym (admin)
+ * summary: Create an announcement — global (gymId null) or for a gym (announcements:manage)
* tags: [Admin]
* responses:
* 201: { description: Created }
@@ -1415,6 +1686,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
*/
router.post(
'/announcements',
+ can(PERMISSIONS.ANNOUNCEMENTS_MANAGE),
validate(adminAnnouncementSchema),
asyncHandler(async (req, res) => {
const data = req.body as z.infer;
@@ -1434,7 +1706,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
* @openapi
* /admin/announcements/{id}:
* patch:
- * summary: Edit a manual announcement (admin)
+ * summary: Edit a manual announcement (announcements:manage)
* tags: [Admin]
* responses:
* 200: { description: OK }
@@ -1443,6 +1715,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
*/
router.patch(
'/announcements/:id',
+ can(PERMISSIONS.ANNOUNCEMENTS_MANAGE),
validate(announcementTextSchema),
asyncHandler(async (req, res) => {
const data = req.body as z.infer;
@@ -1462,7 +1735,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
* @openapi
* /admin/announcements/{id}:
* delete:
- * summary: Delete a manual announcement (admin)
+ * summary: Delete a manual announcement (announcements:manage)
* tags: [Admin]
* responses:
* 204: { description: Deleted }
@@ -1471,6 +1744,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
*/
router.delete(
'/announcements/:id',
+ can(PERMISSIONS.ANNOUNCEMENTS_MANAGE),
asyncHandler(async (req, res) => {
const result = await deleteAnnouncementAsAdmin(prisma, req.params.id);
await logActivity(prisma, {
diff --git a/api/src/routes/auth.ts b/api/src/routes/auth.ts
index 1847315..5c22089 100644
--- a/api/src/routes/auth.ts
+++ b/api/src/routes/auth.ts
@@ -104,7 +104,7 @@ export function createAuthRoutes({ prisma }: AppDeps) {
* summary: Login with email + password
* tags: [Auth]
* responses:
- * 200: { description: 'OK, returns user + access token; dla konta z isAdmin=true (login z aplikacji) wystawiamy tez ciastko fitos_admin_refresh — SSO panelu' }
+ * 200: { description: 'OK, returns user + access token; dla konta z min. 1 uprawnieniem platformowym (login z aplikacji) wystawiamy tez ciastko fitos_admin_refresh — SSO panelu' }
* 401: { description: 'INVALID_CREDENTIALS — zly e-mail albo haslo (ten sam kod dla obu przypadkow, bez enumeracji)' }
*/
router.post(
@@ -122,10 +122,11 @@ export function createAuthRoutes({ prisma }: AppDeps) {
details: { client: isAdminClient(req) ? 'admin' : 'app', ip: req.ip },
});
setRefreshCookie(res, result.refreshToken, isAdminClient(req));
- // Administrator logujacy sie przez aplikacje dostaje dodatkowo ciastko
- // panelu — link „Panel admina" otwiera admina juz zalogowanego (te same
- // ciastka po tej samej domenie; rotacja nie uniewaznia starych wartosci).
- if (!isAdminClient(req) && result.user.isAdmin) {
+ // Konto z uprawnieniami platformowymi logujace sie przez aplikacje dostaje
+ // dodatkowo ciastko panelu — link „Panel admina" otwiera admina juz
+ // zalogowanego (te same ciastka po tej samej domenie; rotacja nie
+ // uniewaznia starych wartosci).
+ if (!isAdminClient(req) && result.user.permissions.length > 0) {
setRefreshCookie(res, result.refreshToken, true);
}
res.json({ user: result.user, accessToken: result.accessToken });
diff --git a/api/src/routes/equipment.ts b/api/src/routes/equipment.ts
index 67ce368..74d94fb 100644
--- a/api/src/routes/equipment.ts
+++ b/api/src/routes/equipment.ts
@@ -1,7 +1,8 @@
import { Router } from 'express';
import { z } from 'zod';
import type { AppDeps } from '../deps.js';
-import { authenticate, requireAdmin } from '../middleware/auth.js';
+import { authenticate, requirePermission } from '../middleware/auth.js';
+import { PERMISSIONS } from '../lib/permissions.js';
import { validate } from '../middleware/validate.js';
import {
createEquipment,
@@ -45,7 +46,7 @@ const equipmentUpdateSchema = z.object({
export function createEquipmentRoutes({ prisma }: AppDeps) {
const router = Router();
- router.use(authenticate(prisma), requireAdmin);
+ router.use(authenticate(prisma), requirePermission(PERMISSIONS.CATALOG_MANAGE));
/**
* @openapi
diff --git a/api/src/routes/exercises.ts b/api/src/routes/exercises.ts
index ec5eef6..575a578 100644
--- a/api/src/routes/exercises.ts
+++ b/api/src/routes/exercises.ts
@@ -1,7 +1,8 @@
import { Router } from 'express';
import { z } from 'zod';
import type { AppDeps } from '../deps.js';
-import { authenticate, requireAdmin } from '../middleware/auth.js';
+import { authenticate, requirePermission } from '../middleware/auth.js';
+import { PERMISSIONS } from '../lib/permissions.js';
import { validate } from '../middleware/validate.js';
import {
createExercise,
@@ -54,7 +55,7 @@ const exerciseUpdateSchema = z.object({
export function createExerciseRoutes({ prisma }: AppDeps) {
const router = Router();
- router.use(authenticate(prisma), requireAdmin);
+ router.use(authenticate(prisma), requirePermission(PERMISSIONS.CATALOG_MANAGE));
/**
* @openapi
diff --git a/api/src/routes/gym-contact.ts b/api/src/routes/gym-contact.ts
index c875c08..3ae3947 100644
--- a/api/src/routes/gym-contact.ts
+++ b/api/src/routes/gym-contact.ts
@@ -1,7 +1,8 @@
import { Router } from 'express';
import { z } from 'zod';
import type { AppDeps } from '../deps.js';
-import { authenticate } from '../middleware/auth.js';
+import { authenticate, callerHas } from '../middleware/auth.js';
+import { PERMISSIONS } from '../lib/permissions.js';
import { validate } from '../middleware/validate.js';
import { asyncHandler } from '../lib/asyncHandler.js';
import {
@@ -40,7 +41,7 @@ export function createGymContactGymRoutes({ prisma }: AppDeps) {
const result = await getGymContactView(
prisma,
req.user!.id,
- req.user!.isAdmin,
+ callerHas(req, PERMISSIONS.GYMS_MANAGE),
req.params.gymId,
);
res.json(result);
@@ -99,7 +100,11 @@ export function createGymContactRoutes({ prisma }: AppDeps) {
router.get(
'/conversations',
asyncHandler(async (req, res) => {
- const result = await listOwnerInbox(prisma, req.user!.id, req.user!.isAdmin);
+ const result = await listOwnerInbox(
+ prisma,
+ req.user!.id,
+ callerHas(req, PERMISSIONS.GYMS_MANAGE),
+ );
res.json(result);
}),
);
@@ -121,7 +126,7 @@ export function createGymContactRoutes({ prisma }: AppDeps) {
const result = await getThread(
prisma,
req.user!.id,
- req.user!.isAdmin,
+ callerHas(req, PERMISSIONS.GYMS_MANAGE),
req.params.conversationId,
);
res.json(result);
@@ -156,7 +161,7 @@ export function createGymContactRoutes({ prisma }: AppDeps) {
const result = await replyToThread(
prisma,
req.user!.id,
- req.user!.isAdmin,
+ callerHas(req, PERMISSIONS.GYMS_MANAGE),
req.params.conversationId,
data.body,
);
diff --git a/api/src/routes/gyms.ts b/api/src/routes/gyms.ts
index cafc6d8..5645f3c 100644
--- a/api/src/routes/gyms.ts
+++ b/api/src/routes/gyms.ts
@@ -1,7 +1,8 @@
import { Router } from 'express';
import { z } from 'zod';
import type { AppDeps } from '../deps.js';
-import { authenticate } from '../middleware/auth.js';
+import { authenticate, callerHas } from '../middleware/auth.js';
+import { PERMISSIONS } from '../lib/permissions.js';
import { validate } from '../middleware/validate.js';
import {
createGym,
@@ -99,7 +100,12 @@ export function createGymRoutes(deps: AppDeps) {
validate(createGymSchema),
asyncHandler(async (req, res) => {
const data = req.body as z.infer;
- const result = await createGym(prisma, req.user!.id, data, req.user!.isAdmin);
+ const result = await createGym(
+ prisma,
+ req.user!.id,
+ data,
+ callerHas(req, PERMISSIONS.GYMS_MANAGE),
+ );
await logActivity(prisma, {
actorId: req.user!.id,
action: 'gym.created',
@@ -178,7 +184,7 @@ export function createGymRoutes(deps: AppDeps) {
const query = req.query as z.infer;
const result = await getEquipmentUsage(prisma, req.params.gymId, resolveRange(query), {
userId: req.user!.id,
- isAdmin: req.user!.isAdmin,
+ isAdmin: callerHas(req, PERMISSIONS.GYMS_MANAGE),
});
res.json(result);
}),
@@ -205,7 +211,7 @@ export function createGymRoutes(deps: AppDeps) {
const query = req.query as z.infer;
const result = await getGymPresenceTelemetry(prisma, req.params.gymId, resolveRange(query), {
userId: req.user!.id,
- isAdmin: req.user!.isAdmin,
+ isAdmin: callerHas(req, PERMISSIONS.GYMS_MANAGE),
});
res.json(result);
}),
@@ -233,7 +239,7 @@ export function createGymRoutes(deps: AppDeps) {
const query = req.query as z.infer;
const result = await getGymStatsOverview(prisma, req.params.gymId, resolveRange(query), {
userId: req.user!.id,
- isAdmin: req.user!.isAdmin,
+ isAdmin: callerHas(req, PERMISSIONS.GYMS_MANAGE),
});
res.json(result);
}),
@@ -260,7 +266,7 @@ export function createGymRoutes(deps: AppDeps) {
const { range } = req.query as z.infer;
const result = await getGymBoard(prisma, req.params.gymId, Number(range), {
userId: req.user!.id,
- isAdmin: req.user!.isAdmin,
+ isAdmin: callerHas(req, PERMISSIONS.GYMS_MANAGE),
});
res.json(result);
}),
@@ -317,7 +323,12 @@ export function createGymRoutes(deps: AppDeps) {
router.get(
'/:gymId',
asyncHandler(async (req, res) => {
- const result = await getGymPublic(prisma, req.user!.id, req.user!.isAdmin, req.params.gymId);
+ const result = await getGymPublic(
+ prisma,
+ req.user!.id,
+ callerHas(req, PERMISSIONS.GYMS_MANAGE),
+ req.params.gymId,
+ );
res.json(result);
}),
);
diff --git a/api/src/routes/gyms/equipmentPhotos.ts b/api/src/routes/gyms/equipmentPhotos.ts
index 85352bf..15f6cf3 100644
--- a/api/src/routes/gyms/equipmentPhotos.ts
+++ b/api/src/routes/gyms/equipmentPhotos.ts
@@ -12,6 +12,8 @@ import {
} from '../../lib/uploads.js';
import { badRequest, forbidden, notFound } from '../../lib/errors.js';
import { asyncHandler } from '../../lib/asyncHandler.js';
+import { callerHas } from '../../middleware/auth.js';
+import { PERMISSIONS } from '../../lib/permissions.js';
type Params = { gymId: string; equipmentInstanceId: string };
@@ -61,7 +63,7 @@ export function createEquipmentPhotoRoutes({ prisma }: AppDeps) {
const result = await addEquipmentPhotos(
prisma,
req.user!.id,
- req.user!.isAdmin,
+ callerHas(req, PERMISSIONS.GYMS_MANAGE),
gymId,
equipmentInstanceId,
files,
@@ -102,7 +104,7 @@ export function createEquipmentPhotoRoutes({ prisma }: AppDeps) {
const result = await deleteEquipmentPhoto(
prisma,
req.user!.id,
- req.user!.isAdmin,
+ callerHas(req, PERMISSIONS.GYMS_MANAGE),
gymId,
equipmentInstanceId,
photoId,
@@ -140,7 +142,7 @@ export function createEquipmentPhotoRoutes({ prisma }: AppDeps) {
if (!gym) throw notFound('Gym not found');
if (
gym.kind !== 'REAL' &&
- !(await canManageGym(prisma, gymId, req.user!.id, req.user!.isAdmin))
+ !(await canManageGym(prisma, gymId, req.user!.id, callerHas(req, PERMISSIONS.GYMS_MANAGE)))
)
throw forbidden('You do not have access to this gym');
const filePath = path.join(equipmentPhotoDir(gymId, equipmentInstanceId), photo.storedName);
diff --git a/api/src/routes/gyms/photos.ts b/api/src/routes/gyms/photos.ts
index c635bf3..2b3e1cb 100644
--- a/api/src/routes/gyms/photos.ts
+++ b/api/src/routes/gyms/photos.ts
@@ -17,6 +17,8 @@ import {
} from '../../lib/uploads.js';
import { badRequest, forbidden, notFound } from '../../lib/errors.js';
import { asyncHandler } from '../../lib/asyncHandler.js';
+import { callerHas } from '../../middleware/auth.js';
+import { PERMISSIONS } from '../../lib/permissions.js';
type GymParams = { gymId: string };
@@ -64,7 +66,13 @@ export function createGymPhotoRoutes({ prisma }: AppDeps) {
sizeBytes: f.size,
path: f.path,
}));
- const result = await addGymPhotos(prisma, req.user!.id, req.user!.isAdmin, gymId, files);
+ const result = await addGymPhotos(
+ prisma,
+ req.user!.id,
+ callerHas(req, PERMISSIONS.GYMS_MANAGE),
+ gymId,
+ files,
+ );
await logActivity(prisma, {
actorId: req.user!.id,
action: 'gym.photos.added',
@@ -97,7 +105,13 @@ export function createGymPhotoRoutes({ prisma }: AppDeps) {
'/:photoId',
asyncHandler(async (req, res) => {
const { gymId, photoId } = req.params as GymParams & { photoId: string };
- const result = await deleteGymPhoto(prisma, req.user!.id, req.user!.isAdmin, gymId, photoId);
+ const result = await deleteGymPhoto(
+ prisma,
+ req.user!.id,
+ callerHas(req, PERMISSIONS.GYMS_MANAGE),
+ gymId,
+ photoId,
+ );
await logActivity(prisma, {
actorId: req.user!.id,
action: 'gym.photo.deleted',
@@ -127,7 +141,7 @@ export function createGymPhotoRoutes({ prisma }: AppDeps) {
const result = await setGymPhotoCover(
prisma,
req.user!.id,
- req.user!.isAdmin,
+ callerHas(req, PERMISSIONS.GYMS_MANAGE),
gymId,
photoId,
);
@@ -163,7 +177,7 @@ export function createGymPhotoRoutes({ prisma }: AppDeps) {
if (!gym) throw notFound('Gym not found');
if (
gym.kind !== 'REAL' &&
- !(await canManageGym(prisma, gymId, req.user!.id, req.user!.isAdmin))
+ !(await canManageGym(prisma, gymId, req.user!.id, callerHas(req, PERMISSIONS.GYMS_MANAGE)))
)
throw forbidden('You do not have access to this gym');
const filePath = path.join(photoUploadDir(gymId), photo.storedName);
diff --git a/api/src/routes/presence.ts b/api/src/routes/presence.ts
index e35c4fd..d7c6928 100644
--- a/api/src/routes/presence.ts
+++ b/api/src/routes/presence.ts
@@ -1,7 +1,8 @@
import { Router } from 'express';
import { z } from 'zod';
import type { AppDeps } from '../deps.js';
-import { authenticate, requireAdmin } from '../middleware/auth.js';
+import { authenticate, requirePermission } from '../middleware/auth.js';
+import { PERMISSIONS } from '../lib/permissions.js';
import { validate } from '../middleware/validate.js';
import { asyncHandler } from '../lib/asyncHandler.js';
import {
@@ -142,7 +143,6 @@ export function createPresenceMeRoutes({ prisma }: AppDeps) {
*/
export function createPresenceAdminRoutes({ prisma }: AppDeps) {
const router = Router();
- router.use(authenticate(prisma), requireAdmin);
/**
* @openapi
@@ -159,6 +159,8 @@ export function createPresenceAdminRoutes({ prisma }: AppDeps) {
*/
router.get(
'/gyms/:gymId/equipment-usage',
+ authenticate(prisma),
+ requirePermission(PERMISSIONS.GYMS_MANAGE),
validate(rangeQuerySchema, 'query'),
asyncHandler(async (req, res) => {
const query = req.query as z.infer;
diff --git a/api/src/seed.ts b/api/src/seed.ts
index 8435786..f3c7407 100644
--- a/api/src/seed.ts
+++ b/api/src/seed.ts
@@ -258,9 +258,14 @@ async function seedFirstAdmin() {
console.warn('WARNING: using default admin password in non-production environment');
}
const passwordHash = await bcrypt.hash(password, 10);
- await prisma.user.create({
+ const admin = await prisma.user.create({
data: { email, passwordHash, isAdmin: true, firstName: 'Admin' },
});
+ // grant roli platformowej ADMIN (rola seedowana w migracji add_rbac_roles);
+ // kolumna isAdmin zostaje tylko do czasu ręcznego czyszczenia
+ const adminRole = await prisma.role.findUnique({ where: { key: 'ADMIN' } });
+ if (!adminRole) throw new Error('Role ADMIN missing — run prisma migrations before seed');
+ await prisma.userRoleGrant.create({ data: { userId: admin.id, roleId: adminRole.id } });
console.log(`Created first admin: ${email} (password from FITOS_FIRST_ADMIN_PASSWORD)`);
}
diff --git a/api/src/services/admin.ts b/api/src/services/admin.ts
index a99e9a2..5f73be7 100644
--- a/api/src/services/admin.ts
+++ b/api/src/services/admin.ts
@@ -3,7 +3,15 @@ import { Prisma, type GymRole, type PrismaClient } from '@prisma/client';
import { validateEquipmentSpec } from '../lib/equipmentSpec.js';
import { isPrismaNotFound } from '../lib/prisma.js';
import { publicUser } from '../lib/publicUser.js';
-import { badRequest, conflict, forbidden, notFound } from '../lib/errors.js';
+import {
+ PLATFORM_GRANTS_INCLUDE,
+ PERMISSIONS,
+ redactUserDto,
+ redactUserDtos,
+ redactUserRef,
+} from '../lib/permissions.js';
+import { AppError, badRequest, conflict, forbidden, notFound } from '../lib/errors.js';
+import { assertNotStaffTarget, assertTargetNotLastRolesManager } from './roles.js';
import {
removeEquipmentPhotoFiles,
removeGymClaimFiles,
@@ -52,7 +60,6 @@ export interface CreateUserInput {
firstName?: string;
lastName?: string;
birthDate?: string | null;
- isAdmin?: boolean;
}
export interface UpdateUserInput {
@@ -64,7 +71,6 @@ export interface UpdateUserInput {
birthDate?: string | null;
heightCm?: number | null;
phone?: string | null;
- isAdmin?: boolean;
password?: string;
availability?: Availability | null;
priorities?: string | null;
@@ -92,7 +98,11 @@ export interface ListGymsQuery {
kind?: 'REAL' | 'VIRTUAL';
}
-export async function listGyms(prisma: PrismaClient, query: ListGymsQuery = {}) {
+export async function listGyms(
+ prisma: PrismaClient,
+ query: ListGymsQuery = {},
+ permissions: readonly string[] = [],
+) {
const term = query.q?.trim();
const where: Prisma.GymWhereInput = {
...(query.kind ? { kind: query.kind } : {}),
@@ -137,12 +147,19 @@ export async function listGyms(prisma: PrismaClient, query: ListGymsQuery = {})
return {
gyms: gyms.map(({ memberships, ...g }) => ({
...g,
- owners: memberships.map((m) => m.user),
+ owners: redactUserDtos(
+ memberships.map((m) => m.user),
+ permissions,
+ ),
})),
};
}
-export async function getGym(prisma: PrismaClient, gymId: string) {
+export async function getGym(
+ prisma: PrismaClient,
+ gymId: string,
+ permissions: readonly string[] = [],
+) {
const gym = await prisma.gym.findUnique({
where: { id: gymId },
include: {
@@ -164,7 +181,10 @@ export async function getGym(prisma: PrismaClient, gymId: string) {
return {
...rest,
equipment: mapEquipmentPhotoDtos(gymId, equipment),
- owners: memberships.map((m) => m.user),
+ owners: redactUserDtos(
+ memberships.map((m) => m.user),
+ permissions,
+ ),
};
}
@@ -216,6 +236,7 @@ export async function listGymMembers(
prisma: PrismaClient,
gymId: string,
query: GymMembersQuery = {},
+ permissions: readonly string[] = [],
) {
const gym = await prisma.gym.findUnique({ where: { id: gymId }, select: { id: true } });
if (!gym) throw notFound('Gym not found');
@@ -259,14 +280,18 @@ export async function listGymMembers(
roles: m.roles,
joinedAt: m.createdAt.toISOString(),
checkedInNow: live.has(m.userId),
- user: m.user,
+ user: redactUserRef(m.user, permissions),
})),
total,
};
}
/** Wnioski i zaproszenia powiązane z jedną siłownią (admin), najnowsze pierwsze. */
-export async function listGymRelated(prisma: PrismaClient, gymId: string) {
+export async function listGymRelated(
+ prisma: PrismaClient,
+ gymId: string,
+ permissions: readonly string[] = [],
+) {
const gym = await prisma.gym.findUnique({ where: { id: gymId }, select: { id: true } });
if (!gym) throw notFound('Gym not found');
const [claims, invitations] = await Promise.all([
@@ -292,7 +317,7 @@ export async function listGymRelated(prisma: PrismaClient, gymId: string) {
id: c.id,
status: c.status,
createdAt: c.createdAt.toISOString(),
- user: c.user,
+ user: redactUserRef(c.user, permissions),
documentCount: c._count.documents,
})),
invitations: invitations.map((i) => ({
@@ -300,8 +325,8 @@ export async function listGymRelated(prisma: PrismaClient, gymId: string) {
status: i.status,
invitedAt: i.invitedAt.toISOString(),
expiresAt: i.expiresAt.toISOString(),
- user: i.user,
- invitedBy: i.invitedBy,
+ user: redactUserRef(i.user, permissions),
+ invitedBy: redactUserRef(i.invitedBy, permissions),
})),
};
}
@@ -474,25 +499,16 @@ export async function removeGymEquipment(prisma: PrismaClient, gymId: string, in
}
/**
- * Strażnik „ostatniego admina”: nie pozwala odebrać roli (lub usunąć konto)
- * jedynemu administratorowi — panel straciłby dostęp na stałe (brak UI do
- * odzyskiwania). Próba samodegradacji/self-deletion wpada w ten sam warunek,
- * gdy w systemie zostaje zero innych adminów.
+ * Strażnik „ostatniego roles:manage" (uogólnienie dawnego assertNotLastAdmin
+ * na granty ról) żyje w services/roles.ts; stąd korzystają deleteUser/
+ * updateUser oraz endpointy ról.
*/
-async function assertNotLastAdmin(prisma: PrismaClient, targetId: string, actorId?: string) {
- const otherAdmins = await prisma.user.count({
- where: { isAdmin: true, id: { not: targetId } },
- });
- if (otherAdmins === 0) {
- throw forbidden(
- actorId === targetId
- ? 'You cannot remove the last admin role from yourself'
- : 'Cannot remove the last admin role',
- );
- }
-}
-export async function listUsers(prisma: PrismaClient, search?: string) {
+export async function listUsers(
+ prisma: PrismaClient,
+ search?: string,
+ viewerPermissions: readonly string[] = [],
+) {
const term = search?.toLowerCase();
const users = await prisma.user.findMany({
where: term
@@ -504,18 +520,26 @@ export async function listUsers(prisma: PrismaClient, search?: string) {
],
}
: undefined,
- include: { memberships: { include: { gym: true } } },
+ include: {
+ memberships: { include: { gym: true } },
+ roleGrants: PLATFORM_GRANTS_INCLUDE,
+ },
orderBy: { createdAt: 'desc' },
});
return {
- users: users.map((u) => ({
- ...publicUser(u),
- memberships: u.memberships.map((m) => ({
- gymId: m.gymId,
- roles: m.roles,
- gym: m.gym,
- })),
- })),
+ users: users.map((u) =>
+ redactUserDto(
+ {
+ ...publicUser(u),
+ memberships: u.memberships.map((m) => ({
+ gymId: m.gymId,
+ roles: m.roles,
+ gym: m.gym,
+ })),
+ },
+ viewerPermissions,
+ ),
+ ),
};
}
@@ -526,7 +550,11 @@ function toPrismaBirthDate(value: string | null | undefined) {
return new Date(value);
}
-export async function createUser(prisma: PrismaClient, data: CreateUserInput) {
+export async function createUser(
+ prisma: PrismaClient,
+ data: CreateUserInput,
+ viewerPermissions: readonly string[] = [],
+) {
const existing = await prisma.user.findUnique({
where: { email: data.email.toLowerCase() },
});
@@ -539,20 +567,30 @@ export async function createUser(prisma: PrismaClient, data: CreateUserInput) {
firstName: data.firstName,
lastName: data.lastName,
birthDate: toPrismaBirthDate(data.birthDate),
- isAdmin: data.isAdmin ?? false,
},
+ include: { roleGrants: PLATFORM_GRANTS_INCLUDE },
});
- return { user: publicUser(user) };
+ return { user: redactUserDto(publicUser(user), viewerPermissions) };
}
export async function updateUser(
prisma: PrismaClient,
id: string,
data: UpdateUserInput,
- actorId?: string,
+ opts: { actorId?: string; permissions?: readonly string[] } = {},
) {
+ const viewerPermissions = opts.permissions ?? [];
const user = await prisma.user.findUnique({ where: { id } });
if (!user) throw notFound('User not found');
+ // anty-eskalacja: jakakolwiek mutacja konta z grantem platformowym wymaga roles:manage
+ await assertNotStaffTarget(prisma, id, viewerPermissions);
+ // bez pii:read pola PII są nieakceptowalne (nawet null — czyściec też jest zmianą)
+ if (
+ !viewerPermissions.includes(PERMISSIONS.PII_READ) &&
+ (data.email !== undefined || data.phone !== undefined || data.birthDate !== undefined)
+ ) {
+ throw new AppError(403, 'PII_FORBIDDEN', 'Missing permission: pii:read');
+ }
const email = data.email?.toLowerCase();
if (email && email !== user.email) {
const existing = await prisma.user.findUnique({ where: { email } });
@@ -563,11 +601,7 @@ export async function updateUser(
const phoneOwner = await prisma.user.findUnique({ where: { phone } });
if (phoneOwner) throw conflict('Phone already registered');
}
- const roleChanged = data.isAdmin !== undefined && data.isAdmin !== user.isAdmin;
const statusChanged = data.status !== undefined && data.status !== user.status;
- if (roleChanged && data.isAdmin === false) {
- await assertNotLastAdmin(prisma, id, actorId);
- }
const passwordHash = data.password ? await bcrypt.hash(data.password, 10) : undefined;
const muscles =
data.developMuscles !== undefined ||
@@ -586,6 +620,7 @@ export async function updateUser(
: {};
const updated = await prisma.user.update({
where: { id: user.id },
+ include: { roleGrants: PLATFORM_GRANTS_INCLUDE },
data: {
email,
firstName: data.firstName,
@@ -595,7 +630,6 @@ export async function updateUser(
birthDate: toPrismaBirthDate(data.birthDate),
heightCm: data.heightCm,
phone: data.phone,
- isAdmin: data.isAdmin,
passwordHash,
// kara czyści się przy przywróceniu; zmiana statusu wygłasza aktywne sesje
status: data.status,
@@ -610,26 +644,29 @@ export async function updateUser(
priorities: data.priorities,
exclusions: data.exclusions,
...muscles,
- ...(roleChanged || statusChanged ? { tokenVersion: { increment: 1 } } : {}),
+ ...(statusChanged ? { tokenVersion: { increment: 1 } } : {}),
},
});
- return { user: publicUser(updated) };
+ return { user: redactUserDto(publicUser(updated), viewerPermissions) };
}
-export async function deleteUser(prisma: PrismaClient, id: string, actorId?: string) {
- if (actorId && actorId === id) throw forbidden('You cannot delete your own account');
- const target = await prisma.user.findUnique({
- where: { id },
- select: { isAdmin: true, email: true },
- });
- if (target?.isAdmin) await assertNotLastAdmin(prisma, id, actorId);
+export async function deleteUser(
+ prisma: PrismaClient,
+ id: string,
+ opts: { actorId?: string; permissions?: readonly string[] } = {},
+) {
+ if (opts.actorId && opts.actorId === id) throw forbidden('You cannot delete your own account');
+ const target = await prisma.user.findUnique({ where: { id }, select: { email: true } });
+ if (!target) throw notFound('User not found');
+ await assertNotStaffTarget(prisma, id, opts.permissions ?? []);
+ await assertTargetNotLastRolesManager(prisma, id);
try {
await prisma.user.delete({ where: { id } });
} catch (e) {
if (isPrismaNotFound(e)) throw notFound('User not found');
throw e;
}
- return { email: target?.email ?? null };
+ return { email: target.email };
}
export async function addMembership(
diff --git a/api/src/services/audit.ts b/api/src/services/audit.ts
index e32f43d..f6ffaaa 100644
--- a/api/src/services/audit.ts
+++ b/api/src/services/audit.ts
@@ -1,5 +1,6 @@
import type { Prisma, PrismaClient } from '@prisma/client';
import { logger } from '../lib/logger.js';
+import { maskEmail, PERMISSIONS, redactLogDetails } from '../lib/permissions.js';
export interface ActivityLogInput {
actorId: string;
@@ -73,6 +74,26 @@ export interface ActivityLogEntry {
actor: ActivityLogActor;
}
+/**
+ * Redakcja PII w strumieniu logów dla odbiorców bez `pii:read`: e-mail aktora
+ * maskowany, pola `email` w `details` (user.created/user.deleted/logowanie)
+ * też. Admin bez zmian.
+ */
+export function redactActivityLogResult; total: number }>(
+ result: T,
+ permissions: readonly string[],
+): T {
+ if (permissions.includes(PERMISSIONS.PII_READ)) return result;
+ return {
+ ...result,
+ logs: result.logs.map((log) => ({
+ ...log,
+ actor: { ...log.actor, email: maskEmail(log.actor.email) as string },
+ details: redactLogDetails(log.details, permissions),
+ })),
+ };
+}
+
async function fetchActivityLogs(
prisma: PrismaClient,
where: Prisma.ActivityLogWhereInput,
@@ -91,7 +112,14 @@ async function fetchActivityLogs(
}),
prisma.activityLog.count({ where }),
]);
- return { logs, total };
+ // `details` jest zawsze zapisywany jako obiekt (logActivity) — zawężamy typ JSON.
+ return {
+ total,
+ logs: logs.map((log) => ({
+ ...log,
+ details: (log.details ?? null) as Record | null,
+ })),
+ };
}
function userScopeWhere(userId: string, scope: UserActivityScope): Prisma.ActivityLogWhereInput {
diff --git a/api/src/services/auth.ts b/api/src/services/auth.ts
index 7f93197..2dd1980 100644
--- a/api/src/services/auth.ts
+++ b/api/src/services/auth.ts
@@ -2,6 +2,11 @@ import bcrypt from 'bcryptjs';
import type { PrismaClient, User } from '@prisma/client';
import { signAccessToken, signRefreshToken, verifyRefreshToken } from '../lib/jwt.js';
import { publicUser } from '../lib/publicUser.js';
+import {
+ permissionsFromGrants,
+ PLATFORM_GRANTS_INCLUDE,
+ type PermissionKey,
+} from '../lib/permissions.js';
import { AppError, conflict, invalidCredentials, unauthorized } from '../lib/errors.js';
import { isPrismaUnique } from '../lib/prisma.js';
@@ -17,8 +22,10 @@ export interface LoginInput {
password: string;
}
+export type AuthUser = ReturnType & { permissions: PermissionKey[] };
+
export interface AuthResult {
- user: ReturnType;
+ user: AuthUser;
accessToken: string;
refreshToken: string;
}
@@ -32,6 +39,7 @@ export async function register(prisma: PrismaClient, input: RegisterInput): Prom
try {
user = await prisma.user.create({
data: { email, passwordHash, firstName: input.firstName, lastName: input.lastName },
+ include: { roleGrants: PLATFORM_GRANTS_INCLUDE },
});
} catch (e) {
// wyścig: findUnique puścił dwa żądania, baza wybija @@unique na email
@@ -39,7 +47,7 @@ export async function register(prisma: PrismaClient, input: RegisterInput): Prom
throw e;
}
return {
- user: publicUser(user),
+ user: { ...publicUser(user), permissions: permissionsFromGrants(user) },
accessToken: signAccessToken(user.id, user.tokenVersion),
refreshToken: signRefreshToken(user.id, user.tokenVersion),
};
@@ -72,7 +80,10 @@ async function assertUsable(prisma: PrismaClient, user: User): Promise {
const DUMMY_HASH = bcrypt.hashSync('placeholder-password-for-timing', 10);
export async function login(prisma: PrismaClient, input: LoginInput): Promise {
- const user = await prisma.user.findUnique({ where: { email: input.email.toLowerCase() } });
+ const user = await prisma.user.findUnique({
+ where: { email: input.email.toLowerCase() },
+ include: { roleGrants: PLATFORM_GRANTS_INCLUDE },
+ });
const ok = await bcrypt.compare(input.password, user?.passwordHash ?? DUMMY_HASH);
if (!user || !ok) throw invalidCredentials();
await assertUsable(prisma, user);
@@ -80,9 +91,10 @@ export async function login(prisma: PrismaClient, input: LoginInput): Promise [u.id, u]));
const result = new Map();
@@ -129,7 +136,7 @@ export async function authorInfos(
const author = byAuthor.get(a.authorId);
if (!author) continue;
const membership = memberships.find((m) => m.userId === a.authorId && m.gymId === a.gymId);
- const role: AnnouncementAuthorRole | null = author.isAdmin
+ const role: AnnouncementAuthorRole | null = author.roleGrants.length
? 'ADMIN'
: membership
? membership.roles.includes('OWNER')
@@ -163,7 +170,7 @@ async function authorInfo(
select: { roles: true },
})
: null;
- const role: AnnouncementAuthorRole | null = author.isAdmin
+ const role: AnnouncementAuthorRole | null = author.roleGrants.length
? 'ADMIN'
: membership
? membership.roles.includes('OWNER')
@@ -212,7 +219,9 @@ export async function getFeed(
take: limit,
include: {
gym: { select: { id: true, name: true } },
- author: { select: { id: true, firstName: true, lastName: true, isAdmin: true } },
+ author: {
+ select: { id: true, firstName: true, lastName: true, roleGrants: ADMIN_GRANT_SELECT },
+ },
},
}),
]);
@@ -323,7 +332,9 @@ export async function getAnnouncementDetail(prisma: PrismaClient, userId: string
where: { id },
include: {
gym: { select: { id: true, name: true } },
- author: { select: { id: true, firstName: true, lastName: true, isAdmin: true } },
+ author: {
+ select: { id: true, firstName: true, lastName: true, roleGrants: ADMIN_GRANT_SELECT },
+ },
},
});
if (!announcement) throw notFound('Announcement not found');
diff --git a/api/src/services/me.ts b/api/src/services/me.ts
index 332651a..59037aa 100644
--- a/api/src/services/me.ts
+++ b/api/src/services/me.ts
@@ -2,6 +2,7 @@ import bcrypt from 'bcryptjs';
import { Prisma } from '@prisma/client';
import type { PrismaClient } from '@prisma/client';
import { publicUser } from '../lib/publicUser.js';
+import { permissionsFromGrants, PLATFORM_GRANTS_INCLUDE } from '../lib/permissions.js';
import { AppError, conflict, notFound } from '../lib/errors.js';
import { isPrismaUnique } from '../lib/prisma.js';
import { latestWeightAtOrBefore } from './exerciseProgress.js';
@@ -94,11 +95,12 @@ export async function getProfile(prisma: PrismaClient, userId: string) {
},
orderBy: { gym: { name: 'asc' } },
},
+ roleGrants: PLATFORM_GRANTS_INCLUDE,
},
});
if (!user) throw notFound('User not found');
return {
- user: publicUser(user),
+ user: { ...publicUser(user), permissions: permissionsFromGrants(user) },
memberships: user.memberships.map((m) => ({
gymId: m.gymId,
roles: m.roles,
@@ -172,6 +174,7 @@ export async function updateProfile(
try {
const user = await prisma.user.update({
where: { id: userId },
+ include: { roleGrants: PLATFORM_GRANTS_INCLUDE },
data: {
...rest,
birthDate:
@@ -181,7 +184,7 @@ export async function updateProfile(
...muscles,
},
});
- return { user: publicUser(user) };
+ return { user: { ...publicUser(user), permissions: permissionsFromGrants(user) } };
} catch (e) {
// wyścig z pre-checkiem: inny użytkownik zdążył zapisać ten sam numer
if (isPrismaUnique(e)) throw conflict('Phone already registered');
diff --git a/api/src/services/roles.ts b/api/src/services/roles.ts
new file mode 100644
index 0000000..09eaba4
--- /dev/null
+++ b/api/src/services/roles.ts
@@ -0,0 +1,235 @@
+import { AppError, badRequest, conflict, forbidden, notFound } from '../lib/errors.js';
+import { isPrismaUnique } from '../lib/prisma.js';
+import { knownPermissions, PERMISSIONS } from '../lib/permissions.js';
+import { Prisma, type PrismaClient } from '@prisma/client';
+
+/** Klucz roli: stabilny identyfikator używany w danych, logach i tłumaczeniach. */
+const ROLE_KEY_RE = /^[A-Z][A-Z0-9_]{1,39}$/;
+
+export interface RoleDto {
+ id: string;
+ key: string;
+ permissions: string[];
+ isSystem: boolean;
+ /** Liczba aktywnych grantów platformowych tej roli. */
+ grantCount: number;
+}
+
+/**
+ * Kod błędu „ostatni użytkownik z roles:manage" — strażnik samoblokady panelu.
+ * Nie wolno wykonać żadnej operacji po której nikt nie mógłby już przywracać ról.
+ */
+function lastRolesManagerError(message: string) {
+ return new AppError(403, 'LAST_ROLES_MANAGER', message);
+}
+
+/** ID użytkowników trzymających roles:manage (grant platformowy). */
+async function rolesManagerUserIds(
+ prisma: PrismaClient,
+ excludeRoleId?: string,
+): Promise> {
+ const grants = await prisma.userRoleGrant.findMany({
+ where: {
+ gymId: null,
+ role: { permissions: { has: PERMISSIONS.ROLES_MANAGE } },
+ ...(excludeRoleId ? { roleId: { not: excludeRoleId } } : {}),
+ },
+ select: { userId: true },
+ });
+ return new Set(grants.map((g) => g.userId));
+}
+
+/** Strażnik celu: mutacja konta z grantem platformowym tylko dla `roles:manage`. */
+export async function assertNotStaffTarget(
+ prisma: PrismaClient,
+ userId: string,
+ permissions: readonly string[],
+) {
+ if (permissions.includes(PERMISSIONS.ROLES_MANAGE)) return;
+ const grant = await prisma.userRoleGrant.findFirst({
+ where: { userId, gymId: null },
+ select: { id: true },
+ });
+ if (grant) {
+ throw new AppError(
+ 403,
+ 'STAFF_MUTATION_FORBIDDEN',
+ 'Only users with roles:manage can modify staff accounts',
+ );
+ }
+}
+
+/** Strażnik usuwania konta: cel trzymający roles:manage nie może być ostatni. */
+export async function assertTargetNotLastRolesManager(prisma: PrismaClient, userId: string) {
+ const managers = await rolesManagerUserIds(prisma);
+ if (!managers.has(userId)) return;
+ managers.delete(userId);
+ if (managers.size === 0) {
+ throw lastRolesManagerError('Cannot remove the last user with roles:manage');
+ }
+}
+
+export async function listRoles(prisma: PrismaClient) {
+ const roles = await prisma.role.findMany({
+ orderBy: [{ isSystem: 'desc' }, { key: 'asc' }],
+ include: { _count: { select: { grants: { where: { gymId: null } } } } },
+ });
+ return {
+ roles: roles.map((r): RoleDto => ({
+ id: r.id,
+ key: r.key,
+ permissions: r.permissions,
+ isSystem: r.isSystem,
+ grantCount: r._count.grants,
+ })),
+ };
+}
+
+export async function createRole(
+ prisma: PrismaClient,
+ input: { key: string; permissions: string[] },
+) {
+ const key = input.key.trim().toUpperCase();
+ if (!ROLE_KEY_RE.test(key)) {
+ throw badRequest('Role key must match ^[A-Z][A-Z0-9_]{1,39}$');
+ }
+ const permissions = knownPermissions(input.permissions ?? []);
+ const existing = await prisma.role.findUnique({ where: { key } });
+ if (existing) throw conflict('Role key already exists');
+ try {
+ const role = await prisma.role.create({ data: { key, permissions } });
+ return {
+ role: { id: role.id, key: role.key, permissions: role.permissions, isSystem: role.isSystem },
+ };
+ } catch (e) {
+ // wyścig przy jednoczesnym tworzeniu tego samego klucza
+ if (isPrismaUnique(e)) throw conflict('Role key already exists');
+ throw e;
+ }
+}
+
+/**
+ * Edycja roli (nazwa = klucz + uprawnienia). Rola systemowa: klucz stały,
+ * `roles:manage` przypięty. Usunięcie `roles:manage` z roli zwykłej tylko,
+ * gdy pozostanie inny użytkownik z tym uprawnieniem.
+ */
+export async function updateRole(
+ prisma: PrismaClient,
+ id: string,
+ input: { name?: string; permissions?: string[] },
+) {
+ const role = await prisma.role.findUnique({ where: { id } });
+ if (!role) throw notFound('Role not found');
+ const data: Prisma.RoleUpdateInput = {};
+
+ if (input.name !== undefined) {
+ const key = input.name.trim().toUpperCase();
+ if (!ROLE_KEY_RE.test(key)) throw badRequest('Role key must match ^[A-Z][A-Z0-9_]{1,39}$');
+ if (role.isSystem) throw forbidden('System role key cannot be renamed');
+ if (key !== role.key) {
+ const taken = await prisma.role.findUnique({ where: { key } });
+ if (taken) throw conflict('Role key already exists');
+ data.key = key;
+ }
+ }
+
+ if (input.permissions !== undefined) {
+ const permissions = knownPermissions(input.permissions);
+ const hadRolesManage = role.permissions.includes(PERMISSIONS.ROLES_MANAGE);
+ const willHave = permissions.includes(PERMISSIONS.ROLES_MANAGE);
+ if (hadRolesManage && !willHave) {
+ if (role.isSystem) {
+ throw forbidden('roles:manage cannot be removed from a system role');
+ }
+ const remaining = await rolesManagerUserIds(prisma, role.id);
+ if (remaining.size === 0) {
+ throw lastRolesManagerError(
+ 'Removing roles:manage from this role would leave no role manager',
+ );
+ }
+ }
+ data.permissions = permissions;
+ }
+
+ try {
+ const updated = await prisma.role.update({ where: { id }, data });
+ return {
+ role: {
+ id: updated.id,
+ key: updated.key,
+ permissions: updated.permissions,
+ isSystem: updated.isSystem,
+ },
+ };
+ } catch (e) {
+ if (isPrismaUnique(e)) throw conflict('Role key already exists');
+ throw e;
+ }
+}
+
+/** Usuwanie tylko ról niesystemowych i bez grantów. */
+export async function deleteRole(prisma: PrismaClient, id: string) {
+ const role = await prisma.role.findUnique({
+ where: { id },
+ include: { _count: { select: { grants: true } } },
+ });
+ if (!role) throw notFound('Role not found');
+ if (role.isSystem) throw forbidden('Cannot delete a system role');
+ if (role._count.grants > 0) throw conflict('Role is still assigned to users');
+ await prisma.role.delete({ where: { id } });
+ return { role: { id: role.id, key: role.key } };
+}
+
+export async function getUserPlatformRoles(prisma: PrismaClient, userId: string) {
+ const grants = await prisma.userRoleGrant.findMany({
+ where: { userId, gymId: null },
+ include: { role: { select: { key: true } } },
+ });
+ return { roles: grants.map((g) => g.role.key) };
+}
+
+/**
+ * Wymiana zbioru grantów platformowych użytkownika (PUT). Strażnik
+ * samoblokady: jeśli cel traci roles:manage jako ostatni — 403.
+ * Zmiana podbija tokenVersion (sesje odświeżają uprawnienia).
+ */
+export async function setUserPlatformRoles(
+ prisma: PrismaClient,
+ userId: string,
+ roleKeys: string[],
+) {
+ const user = await prisma.user.findUnique({ where: { id: userId }, select: { id: true } });
+ if (!user) throw notFound('User not found');
+ const keys = [...new Set(roleKeys)];
+ let roles: Array<{ id: string; key: string; permissions: string[] }> = [];
+ if (keys.length > 0) {
+ roles = await prisma.role.findMany({
+ where: { key: { in: keys } },
+ select: { id: true, key: true, permissions: true },
+ });
+ if (roles.length !== keys.length) throw badRequest('Unknown role key');
+ }
+ const grants = await prisma.userRoleGrant.findMany({
+ where: { userId, gymId: null },
+ include: { role: { select: { key: true, permissions: true } } },
+ });
+ const currentKeys = new Set(grants.map((g) => g.role.key));
+ const changed = keys.length !== currentKeys.size || keys.some((k) => !currentKeys.has(k));
+ if (changed) {
+ const hadRolesManage = grants.some((g) =>
+ g.role.permissions.includes(PERMISSIONS.ROLES_MANAGE),
+ );
+ const willHave = roles.some((r) => r.permissions.includes(PERMISSIONS.ROLES_MANAGE));
+ if (hadRolesManage && !willHave) await assertTargetNotLastRolesManager(prisma, userId);
+ }
+ await prisma.$transaction(async (tx) => {
+ await tx.userRoleGrant.deleteMany({ where: { userId, gymId: null } });
+ if (roles.length > 0) {
+ await tx.userRoleGrant.createMany({ data: roles.map((r) => ({ userId, roleId: r.id })) });
+ }
+ if (changed) {
+ await tx.user.update({ where: { id: userId }, data: { tokenVersion: { increment: 1 } } });
+ }
+ });
+ return { roles: keys };
+}
diff --git a/api/src/swagger.ts b/api/src/swagger.ts
index e2427da..f891b92 100644
--- a/api/src/swagger.ts
+++ b/api/src/swagger.ts
@@ -4,7 +4,12 @@ export const openapi: Record = {
title: 'FitOS API',
version: '1.0.0',
description:
- 'FitOS — silnik planów treningowych. Autoryzacja: Bearer access token (15 min) + refresh token (httpOnly cookie).',
+ 'FitOS — silnik planów treningowych. Autoryzacja: Bearer access token (15 min) + refresh token (httpOnly cookie). ' +
+ 'RBAC (faza 1): endpointy panelu /admin/* wymagają uprawnień platformowych liczonych z ról (granty User→Role, gymId=NULL). ' +
+ 'Katalog uprawnień: users:read, users:manage, pii:read, roles:manage, catalog:manage, gyms:manage, announcements:manage, verifications:view, logs:view. ' +
+ 'Role ADMIN i MODERATOR są seedowane (isSystem). ' +
+ 'DTO użytkownika zwraca platformRoles (klucze ról; dawniej isAdmin); self payload (/auth/login, /me) zawiera dodatkowo permissions. ' +
+ 'Pola PII (email/phone/birthDate) są redagowane po stronie serwera, gdy odbiorca nie ma pii:read (email maskowany, reszta null).',
},
servers: [{ url: '/api/v1' }],
components: {
@@ -12,6 +17,24 @@ export const openapi: Record = {
bearerAuth: { type: 'http', scheme: 'bearer', bearerFormat: 'JWT' },
},
schemas: {
+ Role: {
+ type: 'object',
+ description:
+ 'Rola platformowa (RBAC); permissions = klucze z katalogu (nieznane klucze odrzucane)',
+ properties: {
+ id: { type: 'string' },
+ key: {
+ type: 'string',
+ description: 'Klucz roli, np. ADMIN, MODERATOR lub własny (^[A-Z][A-Z0-9_]{1,39}$)',
+ },
+ permissions: { type: 'array', items: { type: 'string' } },
+ isSystem: {
+ type: 'boolean',
+ description: 'true = seedowana: niedeletowalna, klucz stały, roles:manage przypięty',
+ },
+ grantCount: { type: 'integer', description: 'Liczba grantów platformowych roli' },
+ },
+ },
ExerciseReportSet: {
type: 'object',
description:
@@ -543,7 +566,10 @@ export const openapi: Record = {
security: [{ bearerAuth: [] }],
parameters: [{ name: 'gymId', in: 'path', required: true, schema: { type: 'string' } }],
responses: {
- 200: { description: 'OK, returns { gym, roles, isAdmin }' },
+ 200: {
+ description:
+ 'OK, returns { gym, roles, isAdmin } — isAdmin = nadzór platformowy nad siłowniami (uprawnienie gyms:manage)',
+ },
403: { description: 'Private VIRTUAL gym and the caller is not a manager' },
404: { description: 'Gym not found' },
},
@@ -2339,14 +2365,17 @@ export const openapi: Record = {
'/admin/users': {
get: {
tags: ['Admin'],
- summary: 'List users (admin, optional ?search=)',
+ summary: 'List users (permission users:read, optional ?search=)',
+ description:
+ 'Każdy user zawiera platformRoles (klucze ról platformowych). Bez pii:read: email maskowany (j*n@f****.pl), phone i birthDate null.',
security: [{ bearerAuth: [] }],
},
post: {
tags: ['Admin'],
- summary: 'Create user (admin)',
+ summary: 'Create user (permission users:manage)',
description:
- 'Writes an ActivityLog entry: user.created (details: email, isAdmin — never the password).',
+ 'Role platformowe nadawane osobno (PUT /admin/users/{id}/roles, wymaga roles:manage). ' +
+ 'Writes an ActivityLog entry: user.created (details: email, platformRoles — never the password).',
security: [{ bearerAuth: [] }],
requestBody: {
content: {
@@ -2360,7 +2389,6 @@ export const openapi: Record = {
firstName: { type: 'string' },
lastName: { type: 'string' },
birthDate: { type: 'string', format: 'date', nullable: true },
- isAdmin: { type: 'boolean' },
},
},
},
@@ -2372,23 +2400,172 @@ export const openapi: Record = {
patch: {
tags: ['Admin'],
summary:
- 'Update user (admin; role or status change revokes JWT via token_version). ' +
+ 'Update user (permission users:manage; status change revokes JWT via token_version). ' +
'Status: SUSPENDED requires future suspensionUntil, BANNED requires restrictionReason; ACTIVE clears both',
description:
+ 'Strażniki: cel z grantem platformowym wymaga roles:manage (403 STAFF_MUTATION_FORBIDDEN); ' +
+ 'pola PII (email/phone/birthDate) wymagają pii:read (403 PII_FORBIDDEN). ' +
'Writes ActivityLog entries by body content: user.updated (field names only), ' +
- 'user.status.changed (status/suspensionUntil/restrictionReason), user.admin.changed (isAdmin). Never logs the password.',
+ 'user.status.changed (status/suspensionUntil/restrictionReason). Never logs the password.',
security: [{ bearerAuth: [] }],
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
},
delete: {
tags: ['Admin'],
- summary: 'Delete user (admin; plans/sessions cascade-deleted)',
+ summary:
+ 'Delete user (permission users:manage; plans/sessions cascade-deleted). ' +
+ 'Konto z grantem platformowym wymaga roles:manage; usunięcie ostatniego użytkownika z roles:manage → 403 LAST_ROLES_MANAGER',
description:
'Writes an ActivityLog entry: user.deleted (details: email — the account is gone).',
security: [{ bearerAuth: [] }],
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
},
},
+ '/admin/users/{id}/roles': {
+ get: {
+ tags: ['Admin'],
+ summary: 'Platform role keys of a user (permission users:read)',
+ security: [{ bearerAuth: [] }],
+ parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
+ responses: {
+ 200: {
+ description: 'OK',
+ content: {
+ 'application/json': {
+ schema: {
+ type: 'object',
+ properties: { roles: { type: 'array', items: { type: 'string' } } },
+ },
+ },
+ },
+ },
+ },
+ },
+ put: {
+ tags: ['Admin'],
+ summary: 'Replace platform roles of a user (permission roles:manage)',
+ description:
+ 'Wymiana zbioru grantów platformowych. Zdejmowanie roles:manage ostatniemu posiadaczowi → 403 LAST_ROLES_MANAGER. ' +
+ 'Zmiana podbija token_version (sesje i uprawnienia odświeżone natychmiast). Writes ActivityLog: user.roles.changed.',
+ security: [{ bearerAuth: [] }],
+ parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
+ requestBody: {
+ content: {
+ 'application/json': {
+ schema: {
+ type: 'object',
+ required: ['roles'],
+ properties: {
+ roles: {
+ type: 'array',
+ items: { type: 'string' },
+ description: 'Klucze ról (nieznane → 400), np. ["ADMIN"] albo ["MODERATOR"]',
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ '/admin/permissions': {
+ get: {
+ tags: ['Admin'],
+ summary: 'Permission key catalog (permission roles:manage) — for the role editor UI',
+ security: [{ bearerAuth: [] }],
+ responses: {
+ 200: {
+ description: 'OK',
+ content: {
+ 'application/json': {
+ schema: {
+ type: 'object',
+ properties: { permissions: { type: 'array', items: { type: 'string' } } },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ '/admin/roles': {
+ get: {
+ tags: ['Admin'],
+ summary: 'List platform roles (permission roles:manage)',
+ security: [{ bearerAuth: [] }],
+ responses: {
+ 200: {
+ description: 'OK',
+ content: {
+ 'application/json': {
+ schema: {
+ type: 'object',
+ properties: {
+ roles: {
+ type: 'array',
+ items: { $ref: '#/components/schemas/Role' },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ post: {
+ tags: ['Admin'],
+ summary: 'Create a custom role (permission roles:manage)',
+ description:
+ 'key: ^[A-Z][A-Z0-9_]{1,39}$ (unique); klucze uprawnień spoza katalogu odrzucane. Writes ActivityLog: role.created.',
+ security: [{ bearerAuth: [] }],
+ requestBody: {
+ content: {
+ 'application/json': {
+ schema: {
+ type: 'object',
+ required: ['key', 'permissions'],
+ properties: {
+ key: { type: 'string' },
+ permissions: { type: 'array', items: { type: 'string' } },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ '/admin/roles/{id}': {
+ patch: {
+ tags: ['Admin'],
+ summary: 'Rename and/or re-permission a role (permission roles:manage)',
+ description:
+ 'Rola systemowa: klucz stały, roles:manage przypięty. Usunięcie roles:manage grożące zerem ' +
+ 'posiadaczy → 403 LAST_ROLES_MANAGER. Writes ActivityLog: role.updated.',
+ security: [{ bearerAuth: [] }],
+ parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
+ requestBody: {
+ content: {
+ 'application/json': {
+ schema: {
+ type: 'object',
+ properties: {
+ name: { type: 'string', description: 'Nowy klucz (tylko role własne)' },
+ permissions: { type: 'array', items: { type: 'string' } },
+ },
+ },
+ },
+ },
+ },
+ },
+ delete: {
+ tags: ['Admin'],
+ summary: 'Delete a custom role (permission roles:manage)',
+ description:
+ 'Role systemowe nieusuwalne (403); rola z aktywnymi grantami → 409. Writes ActivityLog: role.deleted.',
+ security: [{ bearerAuth: [] }],
+ parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
+ },
+ },
'/admin/users/{id}/memberships': {
post: {
tags: ['Admin'],
@@ -2584,7 +2761,7 @@ export const openapi: Record = {
tags: ['Admin'],
summary: 'Account history — audit stream scoped to the user (admin)',
description:
- 'scope=onAccount (default): entries performed ON the user (entityType user with his id): logins (IP), edits, bans/suspensions, admin role, creation/deletion. scope=performed: actions made BY the user (actorId). scope=all: union of both streams.',
+ 'scope=onAccount (default): entries performed ON the user (entityType user with his id): logins (IP), edits, bans/suspensions, platform role changes (user.roles.changed), creation/deletion. scope=performed: actions made BY the user (actorId). scope=all: union of both streams. Bez pii:read e-maile w actorze i details maskowane. Wymaga logs:view.',
security: [{ bearerAuth: [] }],
parameters: [
{ name: 'id', in: 'path', required: true, schema: { type: 'string' } },
diff --git a/api/test/helpers.ts b/api/test/helpers.ts
index cc2d1b4..398014f 100644
--- a/api/test/helpers.ts
+++ b/api/test/helpers.ts
@@ -20,10 +20,22 @@ export function rand(): string {
export const PASSWORD = 'Password123!';
+/** Nadanie roli platformowej (grant z gymId = NULL); wymaga ról z seeda migracji. */
+async function grantPlatformRole(userId: string, key: string) {
+ const role = await prisma.role.findUnique({ where: { key } });
+ if (!role) throw new Error(`Role ${key} missing — migrations not applied?`);
+ const existing = await prisma.userRoleGrant.findFirst({ where: { userId, roleId: role.id, gymId: null } });
+ if (existing) return;
+ await prisma.userRoleGrant.create({ data: { userId, roleId: role.id } });
+}
+
export async function createUser(overrides: {
email?: string;
password?: string;
+ /** Nadaje grant roli ADMIN (ekwiwalent dawnego User.isAdmin). */
isAdmin?: boolean;
+ /** Klucze ról platformowych do nadania (np. ['MODERATOR']). */
+ roles?: string[];
firstName?: string;
lastName?: string;
phone?: string;
@@ -34,12 +46,13 @@ export async function createUser(overrides: {
data: {
email,
passwordHash: await bcrypt.hash(password, 10),
- isAdmin: overrides.isAdmin ?? false,
firstName: overrides.firstName,
lastName: overrides.lastName,
phone: overrides.phone,
},
});
+ const roleKeys = new Set([...(overrides.roles ?? []), ...(overrides.isAdmin ? ['ADMIN'] : [])]);
+ for (const key of roleKeys) await grantPlatformRole(user.id, key);
return { user, password };
}
diff --git a/api/test/integration/admin.test.ts b/api/test/integration/admin.test.ts
index 4d7a4f3..aa0237d 100644
--- a/api/test/integration/admin.test.ts
+++ b/api/test/integration/admin.test.ts
@@ -566,7 +566,7 @@ describe('admin routes', () => {
email,
firstName: 'Nowy',
birthDate: '1998-03-14T00:00:00.000Z',
- isAdmin: false,
+ platformRoles: [],
});
expect(res.body.user).not.toHaveProperty('passwordHash');
});
@@ -589,17 +589,23 @@ describe('admin routes', () => {
expect(res.status).toBe(400);
});
- it('promotes a user to admin and revokes their old token', async () => {
+ it('promotes a user with the ADMIN role and revokes their old token', async () => {
const app = buildApp();
const target = await prisma.user.findUnique({ where: { email: targetEmail } });
const targetToken = (await loginViaApi(targetEmail, PASSWORD)).token;
const res = await app
- .patch(`/api/v1/admin/users/${target!.id}`)
+ .put(`/api/v1/admin/users/${target!.id}/roles`)
.set('Authorization', `Bearer ${adminToken}`)
- .send({ isAdmin: true });
+ .send({ roles: ['ADMIN'] });
expect(res.status).toBe(200);
- expect(res.body.user.isAdmin).toBe(true);
+ expect(res.body.roles).toEqual(['ADMIN']);
+
+ const read = await app
+ .get(`/api/v1/admin/users/${target!.id}/roles`)
+ .set('Authorization', `Bearer ${adminToken}`);
+ expect(read.status).toBe(200);
+ expect(read.body.roles).toEqual(['ADMIN']);
const oldToken = await app.get('/api/v1/me').set('Authorization', `Bearer ${targetToken}`);
expect(oldToken.status).toBe(401);
diff --git a/api/test/integration/audit.test.ts b/api/test/integration/audit.test.ts
index 7458813..3219da3 100644
--- a/api/test/integration/audit.test.ts
+++ b/api/test/integration/audit.test.ts
@@ -312,21 +312,21 @@ describe('activity logs (audit trail)', () => {
}
});
- it('admin isAdmin flag logs a separate user.admin.changed entry', async () => {
+ it('changing platform roles logs a separate user.roles.changed entry', async () => {
const admin = await createUser({ isAdmin: true });
const adminLogin = await loginViaApi(admin.user.email, admin.password);
const target = await createUser();
const res = await buildApp()
- .patch(`/api/v1/admin/users/${target.user.id}`)
+ .put(`/api/v1/admin/users/${target.user.id}/roles`)
.set('Authorization', `Bearer ${adminLogin.token}`)
- .send({ isAdmin: true });
+ .send({ roles: ['MODERATOR'] });
expect(res.status).toBe(200);
- expect(res.body.user.isAdmin).toBe(true);
+ expect(res.body.roles).toEqual(['MODERATOR']);
const log = await prisma.activityLog.findFirst({
- where: { entityId: target.user.id, action: 'user.admin.changed' },
+ where: { entityId: target.user.id, action: 'user.roles.changed' },
});
- expect(log?.details).toMatchObject({ actorId: admin.user.id, isAdmin: true });
+ expect(log?.details).toMatchObject({ actorId: admin.user.id, roles: ['MODERATOR'] });
});
it('records membership create/update/delete with roles', async () => {
diff --git a/api/test/integration/auth.test.ts b/api/test/integration/auth.test.ts
index 6033bae..ed58092 100644
--- a/api/test/integration/auth.test.ts
+++ b/api/test/integration/auth.test.ts
@@ -16,7 +16,8 @@ describe('auth routes', () => {
email,
firstName: 'Jan',
lastName: 'Kowalski',
- isAdmin: false,
+ platformRoles: [],
+ permissions: [],
});
expect(res.body.user).not.toHaveProperty('passwordHash');
expect(typeof res.body.accessToken).toBe('string');
diff --git a/api/test/integration/me.test.ts b/api/test/integration/me.test.ts
index 99d505a..3d3bbe0 100644
--- a/api/test/integration/me.test.ts
+++ b/api/test/integration/me.test.ts
@@ -28,7 +28,9 @@ describe('me routes', () => {
const { token, user } = await registerViaApi(`me-${rand()}@test.local`);
const res = await app.get('/api/v1/me').set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(200);
- expect(res.body.user).toMatchObject({ id: user.id, email: user.email, isAdmin: false });
+ expect(res.body.user).toMatchObject({ id: user.id, email: user.email, platformRoles: [] });
+ expect(res.body.user).toHaveProperty('permissions');
+ expect(res.body.user).not.toHaveProperty('isAdmin');
expect(res.body.user).not.toHaveProperty('passwordHash');
expect(res.body.memberships).toEqual([]);
});
diff --git a/api/test/integration/roles.test.ts b/api/test/integration/roles.test.ts
new file mode 100644
index 0000000..f295ed0
--- /dev/null
+++ b/api/test/integration/roles.test.ts
@@ -0,0 +1,252 @@
+import { describe, it, expect, beforeAll } from 'vitest';
+import { prisma } from '../../src/lib/prisma.js';
+import { buildApp, createUser, createUserWithToken, rand, PASSWORD } from '../helpers.js';
+
+describe('RBAC roles and permission gating', () => {
+ let adminToken: string;
+
+ beforeAll(async () => {
+ adminToken = (await createUserWithToken({ isAdmin: true })).token;
+ });
+
+ describe('permission catalog and role list', () => {
+ it('GET /admin/permissions returns the full catalog for ADMIN', async () => {
+ const res = await buildApp().get('/api/v1/admin/permissions').set('Authorization', `Bearer ${adminToken}`);
+ expect(res.status).toBe(200);
+ expect(res.body.permissions).toEqual(
+ expect.arrayContaining(['users:read', 'pii:read', 'roles:manage', 'logs:view']),
+ );
+ expect(res.body.permissions).toHaveLength(9);
+ });
+
+ it('GET /admin/permissions is 403 without roles:manage', async () => {
+ const moderator = await createUserWithToken({ roles: ['MODERATOR'] });
+ const res = await buildApp()
+ .get('/api/v1/admin/permissions')
+ .set('Authorization', `Bearer ${moderator.token}`);
+ expect(res.status).toBe(403);
+ expect(res.body.error.code).toBe('FORBIDDEN');
+ });
+
+ it('GET /admin/roles lists seeded system roles with grant counts', async () => {
+ const res = await buildApp().get('/api/v1/admin/roles').set('Authorization', `Bearer ${adminToken}`);
+ expect(res.status).toBe(200);
+ const admin = res.body.roles.find((r: { key: string }) => r.key === 'ADMIN');
+ const moderator = res.body.roles.find((r: { key: string }) => r.key === 'MODERATOR');
+ expect(admin).toMatchObject({ isSystem: true });
+ expect(admin.permissions).toHaveLength(9);
+ expect(admin.grantCount).toBeGreaterThanOrEqual(1);
+ expect(moderator).toMatchObject({ isSystem: true });
+ expect(moderator.permissions).toEqual(
+ expect.arrayContaining(['users:read', 'users:manage', 'catalog:manage', 'logs:view']),
+ );
+ expect(moderator.permissions).not.toContain('pii:read');
+ });
+ });
+
+ describe('custom role CRUD', () => {
+ it('creates a role (uppercased key, unknown permissions dropped), updates and deletes it', async () => {
+ const app = buildApp();
+ const auth = { Authorization: `Bearer ${adminToken}` };
+ const created = await app
+ .post('/api/v1/admin/roles')
+ .set(auth)
+ .send({ key: 'support', permissions: ['users:read', 'bogus:key'] });
+ expect(created.status).toBe(201);
+ expect(created.body.role).toMatchObject({ key: 'SUPPORT', isSystem: false });
+ expect(created.body.role.permissions).toEqual(['users:read']);
+
+ const updated = await app
+ .patch(`/api/v1/admin/roles/${created.body.role.id}`)
+ .set(auth)
+ .send({ permissions: ['users:read', 'users:manage'] });
+ expect(updated.status).toBe(200);
+ expect(updated.body.role.permissions).toEqual(['users:read', 'users:manage']);
+
+ const deleted = await app.delete(`/api/v1/admin/roles/${created.body.role.id}`).set(auth);
+ expect(deleted.status).toBe(204);
+ });
+
+ it('rejects duplicate role keys with 409 and invalid keys with 400', async () => {
+ const app = buildApp();
+ const auth = { Authorization: `Bearer ${adminToken}` };
+ const key = `R${rand().replace(/[^a-z0-9]/gi, '').slice(0, 12).toUpperCase()}`;
+ const first = await app.post('/api/v1/admin/roles').set(auth).send({ key, permissions: [] });
+ expect(first.status).toBe(201);
+
+ const dup = await app.post('/api/v1/admin/roles').set(auth).send({ key, permissions: [] });
+ expect(dup.status).toBe(409);
+
+ const invalid = await app.post('/api/v1/admin/roles').set(auth).send({ key: '1bad key!', permissions: [] });
+ expect(invalid.status).toBe(400);
+
+ await app.delete(`/api/v1/admin/roles/${first.body.role.id}`).set(auth);
+ });
+
+ it('refuses deleting system roles and roles with grants', async () => {
+ const app = buildApp();
+ const auth = { Authorization: `Bearer ${adminToken}` };
+ const roles = await app.get('/api/v1/admin/roles').set(auth);
+ const adminRole = roles.body.roles.find((r: { key: string }) => r.key === 'ADMIN');
+ const sysDelete = await app.delete(`/api/v1/admin/roles/${adminRole.id}`).set(auth);
+ expect(sysDelete.status).toBe(403);
+
+ const created = await app
+ .post('/api/v1/admin/roles')
+ .set(auth)
+ .send({ key: `G${rand().replace(/[^a-z0-9]/gi, '').slice(0, 12).toUpperCase()}`, permissions: ['logs:view'] });
+ const target = await createUser();
+ const assigned = await app
+ .put(`/api/v1/admin/users/${target.user.id}/roles`)
+ .set(auth)
+ .send({ roles: [created.body.role.key] });
+ expect(assigned.status).toBe(200);
+
+ const blocked = await app.delete(`/api/v1/admin/roles/${created.body.role.id}`).set(auth);
+ expect(blocked.status).toBe(409);
+ });
+ });
+
+ describe('platform role assignment', () => {
+ it('PUT/GET /admin/users/:id/roles round-trips role keys', async () => {
+ const app = buildApp();
+ const auth = { Authorization: `Bearer ${adminToken}` };
+ const target = await createUser();
+ const empty = await app.get(`/api/v1/admin/users/${target.user.id}/roles`).set(auth);
+ expect(empty.body.roles).toEqual([]);
+
+ const set = await app
+ .put(`/api/v1/admin/users/${target.user.id}/roles`)
+ .set(auth)
+ .send({ roles: ['MODERATOR'] });
+ expect(set.status).toBe(200);
+ expect(set.body.roles).toEqual(['MODERATOR']);
+
+ const read = await app.get(`/api/v1/admin/users/${target.user.id}/roles`).set(auth);
+ expect(read.body.roles).toEqual(['MODERATOR']);
+
+ const unknown = await app
+ .put(`/api/v1/admin/users/${target.user.id}/roles`)
+ .set(auth)
+ .send({ roles: ['GHOST_ROLE'] });
+ expect(unknown.status).toBe(400);
+ });
+ });
+
+ describe('MODERATOR capabilities', () => {
+ it('can read and update users but not roles endpoints', async () => {
+ const moderator = await createUserWithToken({ roles: ['MODERATOR'] });
+ const auth = { Authorization: `Bearer ${moderator.token}` };
+ const target = await createUser({ firstName: 'Cel' });
+
+ const list = await buildApp().get('/api/v1/admin/users').set(auth);
+ expect(list.status).toBe(200);
+ const row = list.body.users.find((u: { id: string }) => u.id === target.user.id);
+ expect(row.firstName).toBe('Cel');
+
+ const update = await buildApp()
+ .patch(`/api/v1/admin/users/${target.user.id}`)
+ .set(auth)
+ .send({ firstName: 'Zmieniony' });
+ expect(update.status).toBe(200);
+
+ const roles = await buildApp().get('/api/v1/admin/roles').set(auth);
+ expect(roles.status).toBe(403);
+ });
+
+ it('cannot mutate staff-targeted users without roles:manage', async () => {
+ const moderator = await createUserWithToken({ roles: ['MODERATOR'] });
+ const staff = await createUser({ isAdmin: true });
+ const res = await buildApp()
+ .patch(`/api/v1/admin/users/${staff.user.id}`)
+ .set('Authorization', `Bearer ${moderator.token}`)
+ .send({ firstName: 'Włamanie' });
+ expect(res.status).toBe(403);
+ expect(res.body.error.code).toBe('STAFF_MUTATION_FORBIDDEN');
+ });
+
+ it('cannot set platform roles without roles:manage', async () => {
+ const moderator = await createUserWithToken({ roles: ['MODERATOR'] });
+ const target = await createUser();
+ const res = await buildApp()
+ .put(`/api/v1/admin/users/${target.user.id}/roles`)
+ .set('Authorization', `Bearer ${moderator.token}`)
+ .send({ roles: ['MODERATOR'] });
+ expect(res.status).toBe(403);
+ });
+ });
+
+ describe('server-side PII redaction', () => {
+ const rawEmail = 'pii-mask@test.local';
+ const maskedEmail = 'p******k@t***.local';
+
+ it('masks email and nulls phone/birthDate for readers without pii:read', async () => {
+ const moderator = await createUserWithToken({ roles: ['MODERATOR'] });
+ const auth = { Authorization: `Bearer ${moderator.token}` };
+ const target = await prisma.user.create({
+ data: {
+ email: rawEmail,
+ passwordHash: 'x',
+ firstName: 'Pii',
+ phone: '+48123456789',
+ birthDate: new Date('1990-01-02'),
+ },
+ });
+
+ const read = await buildApp()
+ .get(`/api/v1/admin/users?search=${encodeURIComponent(rawEmail)}`)
+ .set(auth);
+ expect(read.status).toBe(200);
+ expect(read.body.users[0].email).toBe(maskedEmail);
+ expect(read.body.users[0].phone).toBeNull();
+ expect(read.body.users[0].birthDate).toBeNull();
+ });
+
+ it('shows full PII to pii:read holders', async () => {
+ const res = await buildApp()
+ .get(`/api/v1/admin/users?search=${encodeURIComponent(rawEmail)}`)
+ .set('Authorization', `Bearer ${adminToken}`);
+ expect(res.status).toBe(200);
+ expect(res.body.users[0].email).toBe(rawEmail);
+ });
+
+ it('rejects PII fields sent without pii:read with PII_FORBIDDEN', async () => {
+ const moderator = await createUserWithToken({ roles: ['MODERATOR'] });
+ const target = await createUser();
+ const res = await buildApp()
+ .patch(`/api/v1/admin/users/${target.user.id}`)
+ .set('Authorization', `Bearer ${moderator.token}`)
+ .send({ email: `new-${rand()}@test.local` });
+ expect(res.status).toBe(403);
+ expect(res.body.error.code).toBe('PII_FORBIDDEN');
+ });
+ });
+
+ describe('gating for users without platform roles', () => {
+ it('403s admin routes for plain users and lets ADMIN login expose permissions', async () => {
+ const plain = await createUser();
+ const login = await buildApp()
+ .post('/api/v1/auth/login')
+ .send({ email: plain.user.email, password: PASSWORD });
+ expect(login.status).toBe(200);
+ expect(login.body.user.platformRoles).toEqual([]);
+ expect(login.body.user.permissions).toEqual([]);
+
+ const res = await buildApp().get('/api/v1/admin/users').set('Authorization', `Bearer ${login.body.accessToken}`);
+ expect(res.status).toBe(403);
+ });
+
+ it('login exposes MODERATOR role and its permission union', async () => {
+ const moderator = await createUser({ roles: ['MODERATOR'] });
+ const login = await buildApp()
+ .post('/api/v1/auth/login')
+ .send({ email: moderator.user.email, password: PASSWORD });
+ expect(login.status).toBe(200);
+ expect(login.body.user.platformRoles).toEqual(['MODERATOR']);
+ expect(login.body.user.permissions).toEqual(
+ expect.arrayContaining(['users:read', 'users:manage', 'catalog:manage', 'logs:view']),
+ );
+ expect(login.body.user.permissions).not.toContain('pii:read');
+ });
+ });
+});
diff --git a/api/test/unit/middleware-auth.test.ts b/api/test/unit/middleware-auth.test.ts
index f48bbfc..0ff94dc 100644
--- a/api/test/unit/middleware-auth.test.ts
+++ b/api/test/unit/middleware-auth.test.ts
@@ -1,7 +1,12 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { signAccessToken } from '../../src/lib/jwt.js';
-import { authenticate, requireAdmin } from '../../src/middleware/auth.js';
+import {
+ authenticate,
+ requireAnyPermission,
+ requirePermission,
+} from '../../src/middleware/auth.js';
import { AppError } from '../../src/lib/errors.js';
+import { PERMISSIONS } from '../../src/lib/permissions.js';
const findUnique = vi.fn();
const prisma = { user: { findUnique } } as never;
@@ -49,44 +54,86 @@ describe('authenticate middleware', () => {
it('rejects a revoked token (tokenVersion mismatch)', async () => {
const token = signAccessToken('u1', 0);
- findUnique.mockResolvedValue({ id: 'u1', tokenVersion: 1, isAdmin: false });
+ findUnique.mockResolvedValue({ id: 'u1', tokenVersion: 1, roleGrants: [] });
const { nextArg } = await runAuthenticate({ headers: { authorization: `Bearer ${token}` } });
expect((nextArg as AppError).status).toBe(401);
expect((nextArg as AppError).message).toBe('Token revoked');
});
- it('sets req.user for a valid token', async () => {
+ it('sets req.user with platform roles and permissions for a valid token', async () => {
const token = signAccessToken('u1', 2);
- findUnique.mockResolvedValue({ id: 'u1', tokenVersion: 2, isAdmin: true });
+ findUnique.mockResolvedValue({
+ id: 'u1',
+ tokenVersion: 2,
+ roleGrants: [{ role: { key: 'MODERATOR', permissions: [PERMISSIONS.USERS_READ, PERMISSIONS.USERS_MANAGE] } }],
+ });
const { req, nextArg } = await runAuthenticate({ headers: { authorization: `Bearer ${token}` } });
expect(nextArg).toBeUndefined();
- expect(req.user).toEqual({ id: 'u1', isAdmin: true, tokenVersion: 2 });
+ expect(req.user).toEqual({
+ id: 'u1',
+ tokenVersion: 2,
+ platformRoles: ['MODERATOR'],
+ platformPermissions: [PERMISSIONS.USERS_READ, PERMISSIONS.USERS_MANAGE],
+ });
});
});
-describe('requireAdmin middleware', () => {
- function runRequireAdmin(req: { user?: { id: string; isAdmin: boolean; tokenVersion: number } }) {
+describe('requirePermission middleware', () => {
+ function runRequirePermission(req: {
+ user?: { id: string; tokenVersion: number; platformRoles: string[]; platformPermissions: string[] };
+ }) {
const request = req as never;
let nextArg: unknown;
- requireAdmin(request, {} as never, (e?: unknown) => {
+ requirePermission(PERMISSIONS.USERS_MANAGE)(request, {} as never, (e?: unknown) => {
nextArg = e;
});
return { nextArg };
}
it('rejects when req.user is missing', () => {
- const { nextArg } = runRequireAdmin({});
+ const { nextArg } = runRequirePermission({});
expect((nextArg as AppError).status).toBe(403);
});
- it('rejects a non-admin user', () => {
- const { nextArg } = runRequireAdmin({ user: { id: 'u1', isAdmin: false, tokenVersion: 0 } });
+ it('rejects without the required permission', () => {
+ const { nextArg } = runRequirePermission({
+ user: { id: 'u1', tokenVersion: 0, platformRoles: [], platformPermissions: [] },
+ });
expect((nextArg as AppError).status).toBe(403);
- expect((nextArg as AppError).message).toBe('Admin access required');
+ expect((nextArg as AppError).message).toBe(`Missing permission: ${PERMISSIONS.USERS_MANAGE}`);
});
- it('allows an admin user', () => {
- const { nextArg } = runRequireAdmin({ user: { id: 'u1', isAdmin: true, tokenVersion: 0 } });
+ it('allows with the required permission', () => {
+ const { nextArg } = runRequirePermission({
+ user: {
+ id: 'u1',
+ tokenVersion: 0,
+ platformRoles: ['MODERATOR'],
+ platformPermissions: [PERMISSIONS.USERS_MANAGE],
+ },
+ });
expect(nextArg).toBeUndefined();
});
});
+
+describe('requireAnyPermission middleware', () => {
+ function runAny(permissions: string[]) {
+ let nextArg: unknown;
+ requireAnyPermission([PERMISSIONS.GYMS_MANAGE, PERMISSIONS.USERS_MANAGE])(
+ { user: { id: 'u1', tokenVersion: 0, platformRoles: [], platformPermissions: permissions } } as never,
+ {} as never,
+ (e?: unknown) => {
+ nextArg = e;
+ },
+ );
+ return { nextArg };
+ }
+
+ it('passes when any of the permissions is held', () => {
+ expect(runAny([PERMISSIONS.USERS_MANAGE]).nextArg).toBeUndefined();
+ });
+
+ it('rejects when none is held', () => {
+ expect((runAny([PERMISSIONS.LOGS_VIEW]).nextArg as AppError).status).toBe(403);
+ });
+});
diff --git a/api/test/unit/permissions.test.ts b/api/test/unit/permissions.test.ts
new file mode 100644
index 0000000..02bd885
--- /dev/null
+++ b/api/test/unit/permissions.test.ts
@@ -0,0 +1,133 @@
+import { describe, it, expect } from 'vitest';
+import {
+ DEFAULT_ROLES,
+ knownPermissions,
+ maskEmail,
+ PERMISSION_KEYS,
+ permissionsFromGrants,
+ platformRoleKeys,
+ redactUserDto,
+ redactUserDtos,
+ redactLogDetails,
+ PERMISSIONS,
+} from '../../src/lib/permissions.js';
+
+describe('maskEmail', () => {
+ it('masks local part and first domain label', () => {
+ expect(maskEmail('jan@fitos.pl')).toBe('j*n@f****.pl');
+ });
+
+ it('handles short local parts', () => {
+ expect(maskEmail('ab@x.io')).toBe('a*@x*.io');
+ });
+
+ it('returns falsy values untouched', () => {
+ expect(maskEmail(null)).toBeNull();
+ expect(maskEmail(undefined)).toBeUndefined();
+ expect(maskEmail('')).toBe('');
+ });
+
+ it('keeps the stable first/last letter shape', () => {
+ expect(maskEmail('jan.kowalski@fitos.pl')).toBe('j**********i@f****.pl');
+ });
+});
+
+describe('knownPermissions', () => {
+ it('keeps only catalog keys and preserves order', () => {
+ expect(knownPermissions(['users:read', 'bogus:perm', 'logs:view'])).toEqual([
+ 'users:read',
+ 'logs:view',
+ ]);
+ });
+});
+
+describe('role resolution', () => {
+ it('unions permissions across grants and drops unknown keys', () => {
+ const user = {
+ roleGrants: [
+ { role: { key: 'MODERATOR', permissions: ['users:read', 'users:manage', 'ghost:perm'] } },
+ { role: { key: 'CUSTOM', permissions: ['users:manage', 'logs:view'] } },
+ ],
+ };
+ expect(platformRoleKeys(user)).toEqual(['MODERATOR', 'CUSTOM']);
+ expect(permissionsFromGrants(user)).toEqual([
+ 'users:read',
+ 'users:manage',
+ 'logs:view',
+ ]);
+ });
+
+ it('treats a user without grants as permissionless', () => {
+ expect(permissionsFromGrants({})).toEqual([]);
+ expect(platformRoleKeys({})).toEqual([]);
+ });
+
+ it('defines ADMIN with the full catalog and MODERATOR as a subset', () => {
+ const admin = DEFAULT_ROLES.find((r) => r.key === 'ADMIN')!;
+ const moderator = DEFAULT_ROLES.find((r) => r.key === 'MODERATOR')!;
+ expect([...admin.permissions].sort()).toEqual([...PERMISSION_KEYS].sort());
+ for (const perm of moderator.permissions) {
+ expect(admin.permissions).toContain(perm);
+ }
+ expect(moderator.permissions).not.toContain(PERMISSIONS.PII_READ);
+ expect(moderator.permissions).not.toContain(PERMISSIONS.ROLES_MANAGE);
+ expect(admin.isSystem).toBe(true);
+ expect(moderator.isSystem).toBe(true);
+ });
+});
+
+describe('redactUserDto', () => {
+ const user = {
+ id: 'u1',
+ email: 'jan@fitos.pl',
+ phone: '+48123456789',
+ birthDate: '1996-05-05',
+ firstName: 'Jan',
+ };
+
+ it('leaves PII intact for a pii:read viewer', () => {
+ expect(redactUserDto(user, [PERMISSIONS.PII_READ])).toEqual(user);
+ });
+
+ it('masks email and nulls phone/birthDate otherwise', () => {
+ expect(redactUserDto(user, [])).toEqual({
+ id: 'u1',
+ email: 'j*n@f****.pl',
+ phone: null,
+ birthDate: null,
+ firstName: 'Jan',
+ });
+ });
+
+ it('does not mutate the source object', () => {
+ const copy = { ...user };
+ redactUserDto(copy, []);
+ expect(copy).toEqual(user);
+ });
+
+ it('redacts every row in a list', () => {
+ const out = redactUserDtos([user, { ...user, id: 'u2' }], []);
+ expect(out.map((u) => u.email)).toEqual(['j*n@f****.pl', 'j*n@f****.pl']);
+ });
+});
+
+describe('redactLogDetails', () => {
+ it('masks email fields at any depth', () => {
+ const details = {
+ email: 'jan@fitos.pl',
+ nested: { email: 'anna@fitos.pl', keep: 'value' },
+ list: [{ email: 'bob@fitos.pl' }],
+ };
+ expect(redactLogDetails(details, [])).toEqual({
+ email: 'j*n@f****.pl',
+ nested: { email: 'a**a@f****.pl', keep: 'value' },
+ list: [{ email: 'b*b@f****.pl' }],
+ });
+ });
+
+ it('is a no-op for pii:read viewers and null details', () => {
+ const details = { email: 'jan@fitos.pl' };
+ expect(redactLogDetails(details, [PERMISSIONS.PII_READ])).toBe(details);
+ expect(redactLogDetails(null, [])).toBeNull();
+ });
+});
diff --git a/api/test/unit/publicUser.test.ts b/api/test/unit/publicUser.test.ts
index 130515d..809c2de 100644
--- a/api/test/unit/publicUser.test.ts
+++ b/api/test/unit/publicUser.test.ts
@@ -13,7 +13,7 @@ const fakeUser = {
socialMedia: [{ platform: 'INSTAGRAM', url: 'https://instagram.com/jankowalski' }],
birthDate: new Date('1996-05-05T00:00:00Z'),
heightCm: 180.5,
- isAdmin: false,
+ roleGrants: [{ role: { key: 'MODERATOR', permissions: ['users:read'] } }],
tokenVersion: 0,
availability: [{ start: '18:00', end: '20:00' }, null, null, null, null, null, null],
priorities: 'siła',
@@ -38,7 +38,7 @@ describe('publicUser', () => {
socialMedia: [{ platform: 'INSTAGRAM', url: 'https://instagram.com/jankowalski' }],
birthDate: '1996-05-05T00:00:00.000Z',
heightCm: 180.5,
- isAdmin: false,
+ platformRoles: ['MODERATOR'],
availability: [{ start: '18:00', end: '20:00' }, null, null, null, null, null, null],
priorities: 'siła',
exclusions: 'kolana',
diff --git a/api/test/unit/services-admin.test.ts b/api/test/unit/services-admin.test.ts
index 5138afd..658045f 100644
--- a/api/test/unit/services-admin.test.ts
+++ b/api/test/unit/services-admin.test.ts
@@ -6,6 +6,7 @@ import {
updateMembership,
updateUser,
} from '../../src/services/admin.js';
+import { PERMISSIONS } from '../../src/lib/permissions.js';
function mockPrisma() {
return {
@@ -13,39 +14,73 @@ function mockPrisma() {
gym: { findUnique: vi.fn(), update: vi.fn(), delete: vi.fn() },
gymMembership: { findUnique: vi.fn(), create: vi.fn(), update: vi.fn(), delete: vi.fn() },
gymClaim: { findMany: vi.fn().mockResolvedValue([]) },
+ userRoleGrant: {
+ findFirst: vi.fn().mockResolvedValue(null),
+ findMany: vi.fn().mockResolvedValue([]),
+ },
};
}
const prismaNotFound = Object.assign(new Error('Record not found'), { code: 'P2025' });
+/** Uprawnienia pełnego admina (pii:read + roles:manage) dla testów poza strażnikami. */
+const ADMIN_PERMS = [PERMISSIONS.PII_READ, PERMISSIONS.ROLES_MANAGE];
+
describe('updateUser', () => {
it('404 when the user does not exist', async () => {
const prisma = mockPrisma();
prisma.user.findUnique.mockResolvedValue(null);
- await expect(updateUser(prisma, 'u1', { isAdmin: true })).rejects.toMatchObject({
+ await expect(updateUser(prisma, 'u1', { firstName: 'X' })).rejects.toMatchObject({
status: 404,
message: 'User not found',
});
});
- it('increments tokenVersion when the role changes', async () => {
+ it('403 STAFF_MUTATION_FORBIDDEN when the target holds a platform grant', async () => {
const prisma = mockPrisma();
- prisma.user.findUnique.mockResolvedValue({ id: 'u1', isAdmin: false });
- prisma.user.update.mockResolvedValue({ id: 'u1', email: 'u@x.local', createdAt: new Date() });
- await updateUser(prisma, 'u1', { isAdmin: true });
- expect(prisma.user.update).toHaveBeenCalledWith({
- where: { id: 'u1' },
- data: expect.objectContaining({ isAdmin: true, tokenVersion: { increment: 1 } }),
- });
+ prisma.user.findUnique.mockResolvedValue({ id: 'u1' });
+ prisma.userRoleGrant.findFirst.mockResolvedValue({ id: 'grant-1' });
+ await expect(
+ updateUser(prisma, 'u1', { firstName: 'X' }, { permissions: [PERMISSIONS.USERS_MANAGE] }),
+ ).rejects.toMatchObject({ status: 403, code: 'STAFF_MUTATION_FORBIDDEN' });
+ expect(prisma.user.update).not.toHaveBeenCalled();
});
- it('does not touch tokenVersion when the role is unchanged', async () => {
+ it('allows mutating a staff target for a roles:manage holder', async () => {
const prisma = mockPrisma();
- prisma.user.findUnique.mockResolvedValue({ id: 'u1', isAdmin: true });
+ prisma.user.findUnique.mockResolvedValue({ id: 'u1' });
prisma.user.update.mockResolvedValue({ id: 'u1', email: 'u@x.local', createdAt: new Date() });
- await updateUser(prisma, 'u1', { isAdmin: true });
- const call = prisma.user.update.mock.calls[0][0];
- expect(call.data.tokenVersion).toBeUndefined();
+ await expect(
+ updateUser(
+ prisma,
+ 'u1',
+ { firstName: 'X' },
+ { permissions: [PERMISSIONS.USERS_MANAGE, PERMISSIONS.ROLES_MANAGE] },
+ ),
+ ).resolves.toBeDefined();
+ // roles:manage przeskakuje zapytanie o grant celu
+ expect(prisma.userRoleGrant.findFirst).not.toHaveBeenCalled();
+ });
+
+ it('403 PII_FORBIDDEN when email/phone/birthDate arrive without pii:read', async () => {
+ const prisma = mockPrisma();
+ prisma.user.findUnique.mockResolvedValue({ id: 'u1' });
+ await expect(
+ updateUser(prisma, 'u1', { birthDate: null }, { permissions: [PERMISSIONS.USERS_MANAGE] }),
+ ).rejects.toMatchObject({ status: 403, code: 'PII_FORBIDDEN' });
+ expect(prisma.user.update).not.toHaveBeenCalled();
+ });
+
+ it('increments tokenVersion when the account status changes', async () => {
+ const prisma = mockPrisma();
+ prisma.user.findUnique.mockResolvedValue({ id: 'u1', status: 'ACTIVE' });
+ prisma.user.update.mockResolvedValue({ id: 'u1', email: 'u@x.local', createdAt: new Date() });
+ await updateUser(prisma, 'u1', { status: 'SUSPENDED' }, { permissions: ADMIN_PERMS });
+ expect(prisma.user.update).toHaveBeenCalledWith(
+ expect.objectContaining({
+ data: expect.objectContaining({ status: 'SUSPENDED', tokenVersion: { increment: 1 } }),
+ }),
+ );
});
it('409 when the new email is already taken', async () => {
@@ -53,7 +88,9 @@ describe('updateUser', () => {
prisma.user.findUnique
.mockResolvedValueOnce({ id: 'u1', email: 'old@x.local' })
.mockResolvedValueOnce({ id: 'u2', email: 'new@x.local' });
- await expect(updateUser(prisma, 'u1', { email: 'new@x.local' })).rejects.toMatchObject({
+ await expect(
+ updateUser(prisma, 'u1', { email: 'new@x.local' }, { permissions: ADMIN_PERMS }),
+ ).rejects.toMatchObject({
status: 409,
message: 'Email already registered',
});
@@ -63,29 +100,11 @@ describe('updateUser', () => {
const prisma = mockPrisma();
prisma.user.findUnique.mockResolvedValue({ id: 'u1', email: 'u@x.local' });
prisma.user.update.mockResolvedValue({ id: 'u1', email: 'u@x.local', createdAt: new Date() });
- await updateUser(prisma, 'u1', { email: 'U@X.local' });
+ await updateUser(prisma, 'u1', { email: 'U@X.local' }, { permissions: ADMIN_PERMS });
expect(prisma.user.update).toHaveBeenCalledWith(
expect.objectContaining({ data: expect.objectContaining({ email: 'u@x.local' }) }),
);
});
-
- it('blocks demoting the last admin (403)', async () => {
- const prisma = mockPrisma();
- prisma.user.findUnique.mockResolvedValue({ id: 'u1', isAdmin: true });
- prisma.user.count.mockResolvedValue(0);
- await expect(updateUser(prisma, 'u1', { isAdmin: false }, 'u1')).rejects.toMatchObject({
- status: 403,
- });
- expect(prisma.user.update).not.toHaveBeenCalled();
- });
-
- it('allows demoting an admin when another admin exists', async () => {
- const prisma = mockPrisma();
- prisma.user.findUnique.mockResolvedValue({ id: 'u1', isAdmin: true });
- prisma.user.count.mockResolvedValue(1);
- prisma.user.update.mockResolvedValue({ id: 'u1', email: 'u@x.local', createdAt: new Date() });
- await expect(updateUser(prisma, 'u1', { isAdmin: false }, 'u2')).resolves.toBeDefined();
- });
});
describe('updateMembership', () => {
@@ -133,8 +152,9 @@ describe('P2025 mapping', () => {
it('deleteUser: maps P2025 to 404', async () => {
const prisma = mockPrisma();
+ prisma.user.findUnique.mockResolvedValue({ email: 'u@x.local' });
prisma.user.delete.mockRejectedValue(prismaNotFound);
- await expect(deleteUser(prisma, 'u1')).rejects.toMatchObject({
+ await expect(deleteUser(prisma, 'u1', { permissions: ADMIN_PERMS })).rejects.toMatchObject({
status: 404,
message: 'User not found',
});
@@ -142,15 +162,29 @@ describe('P2025 mapping', () => {
it('deleteUser: blocks deleting own account (403)', async () => {
const prisma = mockPrisma();
- await expect(deleteUser(prisma, 'u1', 'u1')).rejects.toMatchObject({ status: 403 });
+ await expect(
+ deleteUser(prisma, 'u1', { actorId: 'u1', permissions: ADMIN_PERMS }),
+ ).rejects.toMatchObject({ status: 403 });
expect(prisma.user.delete).not.toHaveBeenCalled();
});
- it('deleteUser: blocks deleting the last admin (403)', async () => {
+ it('deleteUser: 403 STAFF_MUTATION_FORBIDDEN for staff target without roles:manage', async () => {
const prisma = mockPrisma();
- prisma.user.findUnique.mockResolvedValue({ isAdmin: true });
- prisma.user.count.mockResolvedValue(0);
- await expect(deleteUser(prisma, 'u1', 'u2')).rejects.toMatchObject({ status: 403 });
+ prisma.user.findUnique.mockResolvedValue({ email: 'u@x.local' });
+ prisma.userRoleGrant.findFirst.mockResolvedValue({ id: 'grant-1' });
+ await expect(
+ deleteUser(prisma, 'u1', { actorId: 'u2', permissions: [PERMISSIONS.USERS_MANAGE] }),
+ ).rejects.toMatchObject({ status: 403, code: 'STAFF_MUTATION_FORBIDDEN' });
+ expect(prisma.user.delete).not.toHaveBeenCalled();
+ });
+
+ it('deleteUser: blocks deleting the last roles:manage holder (403 LAST_ROLES_MANAGER)', async () => {
+ const prisma = mockPrisma();
+ prisma.user.findUnique.mockResolvedValue({ email: 'u@x.local' });
+ prisma.userRoleGrant.findMany.mockResolvedValue([{ userId: 'u1' }]);
+ await expect(
+ deleteUser(prisma, 'u1', { actorId: 'u2', permissions: ADMIN_PERMS }),
+ ).rejects.toMatchObject({ status: 403, code: 'LAST_ROLES_MANAGER' });
expect(prisma.user.delete).not.toHaveBeenCalled();
});
});
diff --git a/api/test/unit/services-auth.test.ts b/api/test/unit/services-auth.test.ts
index ead6519..1037a03 100644
--- a/api/test/unit/services-auth.test.ts
+++ b/api/test/unit/services-auth.test.ts
@@ -23,7 +23,7 @@ const userRow = {
lastName: null,
birthDate: null,
heightCm: null,
- isAdmin: false,
+ roleGrants: [] as Array<{ role: { key: string; permissions: string[] } }>,
availability: null,
priorities: null,
exclusions: null,
@@ -61,6 +61,7 @@ describe('register', () => {
});
expect(prisma.user.create).toHaveBeenCalledWith({
data: expect.objectContaining({ email: 'test@test.local', firstName: 'Test' }),
+ include: { roleGrants: expect.objectContaining({ where: { gymId: null } }) },
});
expect(result.accessToken).toBeTruthy();
expect(result.refreshToken).toBeTruthy();
diff --git a/app/src/api/types.ts b/app/src/api/types.ts
index 4e21ef7..c04addf 100644
--- a/app/src/api/types.ts
+++ b/app/src/api/types.ts
@@ -23,7 +23,10 @@ export interface User {
birthDate: string | null;
heightCm: number | null;
phone: string | null;
- isAdmin: boolean;
+ /** Klucze ról platformowych (RBAC); niewykorzystywane w aplikacji użytkownika poza linkiem do panelu. */
+ platformRoles: string[];
+ /** Tylko self (login, /me): unia uprawnień — np. gyms:manage dla tworzenia realnych siłowni. */
+ permissions?: string[];
availability: Availability | null;
priorities: string | null;
exclusions: string | null;
diff --git a/app/src/components/Layout.tsx b/app/src/components/Layout.tsx
index f9e2596..d4c563a 100644
--- a/app/src/components/Layout.tsx
+++ b/app/src/components/Layout.tsx
@@ -75,7 +75,7 @@ const ANNOUNCEMENTS_NAV: NavItem = {
icon: Megaphone,
end: false,
};
-// Panel admina — pierwszy wpis w menu, tylko dla kont z isAdmin=true.
+// Panel admina — pierwszy wpis w menu, tylko dla kont z rolą platformową (RBAC).
const ADMIN_NAV: NavItem = {
to: ADMIN_URL,
labelKey: 'adminPanel',
@@ -238,14 +238,17 @@ export default function Layout() {
if (isTrainer) navItems = [...navItems.slice(0, -1), TRAINEES_NAV, navItems[navItems.length - 1]];
if (pendingInvitations > 0)
navItems = [...navItems.slice(0, -1), INVITATIONS_NAV, navItems[navItems.length - 1]];
- // „Panel admina” — pierwszy wpis w menu, tylko dla administratorów.
- if (user?.isAdmin) navItems = [ADMIN_NAV, ...navItems];
+ // „Panel admina” — pierwszy wpis w menu, tylko dla ekipy panelu (role platformowe).
+ const platformRoles = user?.platformRoles ?? [];
+ if (platformRoles.length > 0) navItems = [ADMIN_NAV, ...navItems];
const fullName =
[user?.firstName, user?.lastName].filter(Boolean).join(' ') || user?.email || '?';
const roles = [
- user?.isAdmin ? t('roleAdmin') : null,
- isTrainer ? t('roleTrainer') : t('roleUser'),
+ ...platformRoles.map((r) =>
+ r === 'ADMIN' ? t('roleAdmin') : r === 'MODERATOR' ? t('roleModerator') : r,
+ ),
+ isTrainer ? t('roleTrainer') : platformRoles.length ? null : t('roleUser'),
]
.filter(Boolean)
.join(' · ');
diff --git a/app/src/components/gyms/GymCreateModal.tsx b/app/src/components/gyms/GymCreateModal.tsx
index 479e686..3693686 100644
--- a/app/src/components/gyms/GymCreateModal.tsx
+++ b/app/src/components/gyms/GymCreateModal.tsx
@@ -11,7 +11,7 @@ import { emptyAvailability } from '../../lib/availability';
/**
* Wspólny modal tworzenia siłowni (strona „Siłownie” i profil).
- * Nie-admin: tylko VIRTUAL (lokalizacja wymagana); admin: wybór typu (domyślnie Wirtualna).
+ * Bez gyms:manage: tylko VIRTUAL (lokalizacja wymagana); z gyms:manage: wybór typu (domyślnie Wirtualna).
* Checkbox „Prywatna” tylko dla VIRTUAL.
*/
export default function GymCreateModal({ open, onClose }: { open: boolean; onClose: () => void }) {
@@ -19,7 +19,8 @@ export default function GymCreateModal({ open, onClose }: { open: boolean; onClo
const { push } = useToast();
const { t } = useTranslation('gyms');
const { data: me } = useMe();
- const isAdmin = me?.user.isAdmin ?? false;
+ // wybór typu REAL = uprawnienie gyms:manage (serwer: POST /gyms kind=REAL inaczej 403)
+ const canCreateReal = me?.user.permissions?.includes('gyms:manage') ?? false;
const [form, setForm] = useState({
name: '',
@@ -97,7 +98,7 @@ export default function GymCreateModal({ open, onClose }: { open: boolean; onClo
required
/>
- {isAdmin && (
+ {canCreateReal && (
| | |