Backend+Admin+App: RBAC faza 1 - silnik rol platformowych (tabele Role/UserRoleGrant z addytywna migracja i backfillem z isAdmin, katalog 9 uprawnien, bramy per endpoint + guardy STAFF_MUTATION_FORBIDDEN/LAST_ROLES_MANAGER/PII_FORBIDDEN, redakcja PII po stronie serwera, panel Role i moderator w adminie, link panelu w apce wg platformRoles; login/me/DTO zwracaja platformRoles+permissions)

This commit is contained in:
tisachi
2026-11-25 23:53:11 +01:00
parent 2f9aa9abf7
commit 61e28ff723
82 changed files with 3182 additions and 641 deletions

View File

@@ -1,4 +1,4 @@
import { useEffect } from 'react';
import { useEffect, type ReactNode } from 'react';
import { Routes, Route, Navigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useAuth } from './store/auth';
@@ -16,6 +16,7 @@ import UsersList from './pages/users/UsersList';
import UserForm from './pages/users/UserForm';
import UserDetail from './pages/users/UserDetail';
import UserLogsPage from './pages/users/UserLogsPage';
import Roles from './pages/Roles';
import FocusAreas from './pages/catalog/FocusAreas';
import Exercises from './pages/catalog/Exercises';
import EquipmentCatalog from './pages/catalog/Equipment';
@@ -23,6 +24,18 @@ import Announcements from './pages/announcements/Announcements';
import Logs from './pages/Logs';
import VerificationsList, { VerificationDetail } from './pages/Verifications';
/** Kolejność lądowania po logowaniu — pierwsza trasa, do której mamy uprawnienie. */
const LANDING: Array<[perm: string, path: string]> = [
['gyms:manage', '/gyms'],
['users:read', '/users'],
['users:manage', '/users'],
['roles:manage', '/roles'],
['verifications:view', '/verifications'],
['announcements:manage', '/announcements'],
['catalog:manage', '/focus-areas'],
['logs:view', '/logs'],
];
export default function App() {
const { t } = useTranslation();
const { user, ready, init } = useAuth();
@@ -37,31 +50,194 @@ export default function App() {
);
}
const perms = user?.permissions ?? [];
const can = (perm: string) => perms.includes(perm);
const Guard = ({ perm, children }: { perm: string; children: ReactNode }) =>
can(perm) ? <>{children}</> : <Navigate to="/" replace />;
const landing = LANDING.find(([perm]) => can(perm))?.[1];
return (
<Routes>
<Route path="/login" element={user ? <Navigate to="/" replace /> : <Login />} />
<Route element={user ? <Layout /> : <Navigate to="/login" replace />}>
<Route path="/" element={<Navigate to="/gyms" replace />} />
<Route path="/gyms" element={<GymsList />} />
<Route path="/gyms/new" element={<GymForm />} />
<Route path="/gyms/:id" element={<GymDetail />} />
<Route path="/gyms/:id/board" element={<GymBoard />} />
<Route path="/gyms/:id/gallery" element={<GymGalleryPage />} />
<Route path="/gyms/:id/equipment" element={<GymEquipmentPage />} />
<Route path="/gyms/:id/announcements" element={<GymAnnouncementsPage />} />
<Route path="/gyms/:id/logs" element={<GymLogsPage />} />
<Route path="/users" element={<UsersList />} />
<Route path="/users/new" element={<UserForm />} />
<Route path="/users/:id" element={<UserDetail />} />
<Route path="/users/:id/edit" element={<UserForm />} />
<Route path="/users/:id/logs" element={<UserLogsPage />} />
<Route path="/focus-areas" element={<FocusAreas />} />
<Route path="/exercises" element={<Exercises />} />
<Route path="/equipment" element={<EquipmentCatalog />} />
<Route path="/verifications" element={<VerificationsList />} />
<Route path="/verifications/:id" element={<VerificationDetail />} />
<Route path="/announcements" element={<Announcements />} />
<Route path="/logs" element={<Logs />} />
<Route
path="/"
element={
landing ? (
<Navigate to={landing} replace />
) : (
<div className="py-10 text-center text-dim">{t('noAccess')}</div>
)
}
/>
<Route
path="/gyms"
element={
<Guard perm="gyms:manage">
<GymsList />
</Guard>
}
/>
<Route
path="/gyms/new"
element={
<Guard perm="gyms:manage">
<GymForm />
</Guard>
}
/>
<Route
path="/gyms/:id"
element={
<Guard perm="gyms:manage">
<GymDetail />
</Guard>
}
/>
<Route
path="/gyms/:id/board"
element={
<Guard perm="gyms:manage">
<GymBoard />
</Guard>
}
/>
<Route
path="/gyms/:id/gallery"
element={
<Guard perm="gyms:manage">
<GymGalleryPage />
</Guard>
}
/>
<Route
path="/gyms/:id/equipment"
element={
<Guard perm="gyms:manage">
<GymEquipmentPage />
</Guard>
}
/>
<Route
path="/gyms/:id/announcements"
element={
<Guard perm="gyms:manage">
<GymAnnouncementsPage />
</Guard>
}
/>
<Route
path="/gyms/:id/logs"
element={
<Guard perm="gyms:manage">
<GymLogsPage />
</Guard>
}
/>
<Route
path="/users"
element={
<Guard perm="users:read">
<UsersList />
</Guard>
}
/>
<Route
path="/users/new"
element={
<Guard perm="users:manage">
<UserForm />
</Guard>
}
/>
<Route
path="/users/:id"
element={
<Guard perm="users:read">
<UserDetail />
</Guard>
}
/>
<Route
path="/users/:id/edit"
element={
<Guard perm="users:manage">
<UserForm />
</Guard>
}
/>
<Route
path="/users/:id/logs"
element={
<Guard perm="logs:view">
<UserLogsPage />
</Guard>
}
/>
<Route
path="/roles"
element={
<Guard perm="roles:manage">
<Roles />
</Guard>
}
/>
<Route
path="/focus-areas"
element={
<Guard perm="catalog:manage">
<FocusAreas />
</Guard>
}
/>
<Route
path="/exercises"
element={
<Guard perm="catalog:manage">
<Exercises />
</Guard>
}
/>
<Route
path="/equipment"
element={
<Guard perm="catalog:manage">
<EquipmentCatalog />
</Guard>
}
/>
<Route
path="/verifications"
element={
<Guard perm="verifications:view">
<VerificationsList />
</Guard>
}
/>
<Route
path="/verifications/:id"
element={
<Guard perm="verifications:view">
<VerificationDetail />
</Guard>
}
/>
<Route
path="/announcements"
element={
<Guard perm="announcements:manage">
<Announcements />
</Guard>
}
/>
<Route
path="/logs"
element={
<Guard perm="logs:view">
<Logs />
</Guard>
}
/>
</Route>
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>

View File

@@ -25,7 +25,10 @@ export interface User {
birthDate: string | null;
heightCm: number | null;
phone: string | null;
isAdmin: boolean;
/** Klucze ról platformowych (RBAC). E-mail/phone/birthDate już zredagowane przez serwer wg uprawnień. */
platformRoles: string[];
/** Tylko self (login, /me): unia uprawnień platformowych tej osoby. */
permissions?: string[];
availability: Availability | null;
priorities: string | null;
exclusions: string | null;
@@ -42,6 +45,15 @@ export interface User {
memberships?: { gymId: string; roles: GymRole[]; gym: Gym }[];
}
/** Rola platformowa (RBAC) — odpowiedź /admin/roles. */
export interface PlatformRole {
id: string;
key: string;
permissions: string[];
isSystem: boolean;
grantCount: number;
}
export interface FocusArea {
id: string;
name: string;

View File

@@ -5,6 +5,7 @@ import {
AppWindow,
Building2,
Dumbbell,
KeyRound,
LogOut,
Megaphone,
Menu,
@@ -33,6 +34,8 @@ interface NavItem {
end: boolean;
/** Link na inny origin (np. aplikacja) — <a href>, nie <NavLink>. */
external?: boolean;
/** Uprawnienie wymagane do wyświetlenia pozycji (RBAC); brak = widoczna dla każdego staffu. */
perm?: string;
}
interface NavSection {
@@ -44,24 +47,61 @@ const SECTIONS: NavSection[] = [
{
labelKey: 'nav.management',
items: [
{ to: '/gyms', labelKey: 'nav.gyms', icon: Building2, end: false },
{ to: '/verifications', labelKey: 'nav.verifications', icon: ShieldCheck, end: false },
{ to: '/users', labelKey: 'nav.users', icon: Users, end: false },
{ to: '/announcements', labelKey: 'nav.announcements', icon: Megaphone, end: false },
{ to: '/gyms', labelKey: 'nav.gyms', icon: Building2, end: false, perm: 'gyms:manage' },
{
to: '/verifications',
labelKey: 'nav.verifications',
icon: ShieldCheck,
end: false,
perm: 'verifications:view',
},
{ to: '/users', labelKey: 'nav.users', icon: Users, end: false, perm: 'users:read' },
{
to: '/roles',
labelKey: 'nav.roles',
icon: KeyRound,
end: false,
perm: 'roles:manage',
},
{
to: '/announcements',
labelKey: 'nav.announcements',
icon: Megaphone,
end: false,
perm: 'announcements:manage',
},
],
},
{
labelKey: 'nav.dictionaries',
items: [
{ to: '/focus-areas', labelKey: 'nav.focusAreas', icon: Target, end: false },
{ to: '/exercises', labelKey: 'nav.exercises', icon: Dumbbell, end: false },
{ to: '/equipment', labelKey: 'nav.equipment', icon: Wrench, end: false },
{
to: '/focus-areas',
labelKey: 'nav.focusAreas',
icon: Target,
end: false,
perm: 'catalog:manage',
},
{
to: '/exercises',
labelKey: 'nav.exercises',
icon: Dumbbell,
end: false,
perm: 'catalog:manage',
},
{
to: '/equipment',
labelKey: 'nav.equipment',
icon: Wrench,
end: false,
perm: 'catalog:manage',
},
],
},
{
labelKey: 'nav.system',
items: [
{ to: '/logs', labelKey: 'nav.logs', icon: ScrollText, end: true },
{ to: '/logs', labelKey: 'nav.logs', icon: ScrollText, end: true, perm: 'logs:view' },
// Powrót do aplikacji użytkownika — zawsze na końcu, inny origin (aplikacja
// wznowi sesję z własnego ciastka fitos_refresh, panelu nie dotyka).
{ to: APP_URL, labelKey: 'nav.application', icon: AppWindow, end: false, external: true },
@@ -155,9 +195,14 @@ function NavLinks({
function NavSections({ collapsed, onNavigate }: { collapsed: boolean; onNavigate?: () => void }) {
const { t } = useTranslation();
const perms = useAuth((s) => s.user?.permissions) ?? [];
const visible = SECTIONS.map((section) => ({
...section,
items: section.items.filter((item) => !item.perm || perms.includes(item.perm)),
})).filter((section) => section.items.length > 0);
return (
<div className={cn('flex flex-col', collapsed ? 'gap-2' : 'gap-4')}>
{SECTIONS.map((section) => (
{visible.map((section) => (
<div key={section.labelKey}>
{!collapsed && (
<div className="mb-1 px-6 text-[10.5px] font-bold uppercase tracking-[0.13em] text-dim/80">
@@ -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(' · ');

View File

@@ -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, unknown>): 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[] }) {
</td>
<td className="px-4 py-3">
<div className="font-semibold">{actorName(log)}</div>
<div className="text-[0.875rem] text-dim">{maskEmail(log.actor.email)}</div>
<div className="text-[0.875rem] text-dim">{log.actor.email}</div>
<div className="font-mono text-[0.75rem] text-dim/70" title={log.actor.id}>
{log.actor.id}
</div>

View File

@@ -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({
>
<span className="min-w-0 truncate">{userLabel(u)}</span>
{u.firstName && (
<span className="shrink-0 text-[0.875rem] text-dim">{maskEmail(u.email)}</span>
<span className="shrink-0 text-[0.875rem] text-dim">{u.email}</span>
)}
</button>
))

View File

@@ -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;

View File

@@ -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.",

View File

@@ -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}}",

View File

@@ -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",

View File

@@ -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"
}
}
}

View File

@@ -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"
}
}

View File

@@ -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",

View File

@@ -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.",

View File

@@ -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}}",

View File

@@ -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",

View File

@@ -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"
}
}
}

View File

@@ -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"
}
}

View File

@@ -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ę",

View File

@@ -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(), {

260
admin/src/pages/Roles.tsx Normal file
View File

@@ -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<PlatformRole | null>(null);
const [key, setKey] = useState('');
const [perms, setPerms] = useState<string[]>([]);
const [formError, setFormError] = useState<string | null>(null);
const [deleting, setDeleting] = useState<PlatformRole | null>(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 (
<>
<Muted className="mb-4 block">{t('intro')}</Muted>
{isLoading && <Loading />}
{error && (
<ErrorText>
{t('common:errorPrefix')}
{(error as Error).message}
</ErrorText>
)}
{formError && !formOpen && (
<div className="mb-4">
<ErrorText>{formError}</ErrorText>
</div>
)}
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
{roles.map((r) => (
<Card key={r.id} className="mb-0">
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<div className="flex flex-wrap items-center gap-2">
<span className="text-[1.05rem] font-semibold">
{t(`names.${r.key}`, { defaultValue: r.key })}
</span>
{r.isSystem && <Badge color="blue">{t('systemBadge')}</Badge>}
</div>
<div className="mt-0.5 font-mono text-[0.75rem] text-dim">{r.key}</div>
<div className="mt-1.5 flex flex-wrap gap-1">
{r.permissions.map((p) => (
<Badge key={p} color="gray">
{t(permKey(p), { defaultValue: p })}
</Badge>
))}
</div>
</div>
<div className="flex shrink-0 items-center gap-1">
<Button
variant="ghost"
size="sm"
onClick={() => openEdit(r)}
aria-label={t('editAria', { name: r.key })}
>
<Pencil className="h-4 w-4" />
</Button>
<Button
variant="ghost"
size="sm"
className="text-danger hover:text-danger"
onClick={() => setDeleting(r)}
disabled={r.isSystem || r.grantCount > 0}
title={
r.isSystem
? t('deleteBlockedSystem')
: r.grantCount > 0
? t('deleteBlockedAssigned')
: undefined
}
aria-label={t('removeAria', { name: r.key })}
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</div>
<div className="mt-2 text-[0.8rem] text-dim">
{t('grantCount', { count: r.grantCount })}
</div>
</Card>
))}
</div>
{!isLoading && !error && roles.length === 0 && (
<Card>
<EmptyState icon={KeyRound} title={t('emptyTitle')} description={t('emptyDesc')} />
</Card>
)}
<Modal
open={formOpen}
onClose={() => setFormOpen(false)}
title={editing ? t('editRole') : t('newRole')}
>
<div className="flex flex-col gap-3.5">
<Field label={t('keyLabel')}>
<Input
value={key}
disabled={editing?.isSystem}
onChange={(e) => setKey(e.target.value.toUpperCase())}
placeholder="EX. SUPPORT"
className="font-mono"
/>
</Field>
<div>
<div className="mb-1.5 text-[0.8rem] font-bold uppercase tracking-[0.08em] text-dim">
{t('permsTitle')}
</div>
<div className="flex flex-col gap-1 rounded-xl border border-line bg-input/40 p-3">
{allPerms.map((p) => (
<label key={p} className="flex items-center gap-2.5 text-[0.9rem]">
<input
type="checkbox"
className="h-4 w-4"
checked={perms.includes(p)}
disabled={editing?.isSystem && p === 'roles:manage'}
onChange={() => toggle(p)}
/>
<span className="min-w-0">
<span className="flex items-center gap-1.5">
{t(permKey(p), { defaultValue: p })}
{editing?.isSystem && p === 'roles:manage' && (
<ShieldCheck className="h-3.5 w-3.5 text-accent-text" />
)}
</span>
<span className="block font-mono text-[0.7rem] text-dim">{p}</span>
</span>
</label>
))}
</div>
{pinned && <p className="mt-1.5 text-[0.78rem] text-dim">{t('pinnedNote')}</p>}
</div>
{formError && <ErrorText>{formError}</ErrorText>}
<div className="flex justify-end gap-2">
<Button variant="secondary" onClick={() => setFormOpen(false)}>
{t('common:cancel')}
</Button>
<Button onClick={() => save.mutate()} disabled={save.isPending || !key.trim()}>
{editing ? t('common:save') : t('common:add')}
</Button>
</div>
</div>
</Modal>
<ConfirmDialog
open={deleting != null}
onClose={() => 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}
/>
</>
);
}

View File

@@ -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 <a download>. */
@@ -285,7 +285,7 @@ export function VerificationDetail() {
<InfoItem label={tr('companyNameLabel')}>{claim.companyName || '—'}</InfoItem>
<InfoItem label={tr('nipLabel')}>{claim.nip || '—'}</InfoItem>
<InfoItem label={tr('phoneLabel')}>{claim.phone || '—'}</InfoItem>
<InfoItem label={tr('emailLabel')}>{claim.email ? maskEmail(claim.email) : '—'}</InfoItem>
<InfoItem label={tr('emailLabel')}>{claim.email || '—'}</InfoItem>
</div>
</Card>
@@ -298,7 +298,7 @@ export function VerificationDetail() {
{applicantName(claim)}
</span>
</InfoItem>
<InfoItem label={tr('emailLabel')}>{maskEmail(claim.user.email)}</InfoItem>
<InfoItem label={tr('emailLabel')}>{claim.user.email}</InfoItem>
{claim.user.phone != null && (
<InfoItem label={tr('phoneLabel')}>{claim.user.phone}</InfoItem>
)}

View File

@@ -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({
>
<td className="px-3 py-2.5 align-top">
<div className="font-semibold">{memberLabel(m)}</div>
<div className="text-[0.78rem] text-dim">{maskEmail(m.user.email)}</div>
<div className="text-[0.78rem] text-dim">{m.user.email}</div>
</td>
<td className="px-3 py-2.5 align-top">
<RoleBadges roles={m.roles} />

View File

@@ -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;

View File

@@ -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() {
<span>{`${t('reasonPrefix')}${user.restrictionReason}`}</span>
)}
{user.nickname && <Badge color="blue">@{user.nickname}</Badge>}
{user.isAdmin && <Badge color="blue">{t('adminBadge')}</Badge>}
{user.platformRoles.map((r) => (
<Badge key={r} color="blue">
{t(`roles:names.${r}`, { defaultValue: r })}
</Badge>
))}
{staffLocked && <Badge color="gray">{t('staffLockedBadge')}</Badge>}
</span>
<span>{t('createdOn', { date: fmtDate(user.createdAt) })}</span>
</div>
<div className="grid grid-cols-2 divide-x divide-line sm:grid-cols-4">
<div
className={
canVerify
? 'grid grid-cols-2 divide-x divide-line sm:grid-cols-4'
: 'grid grid-cols-3 divide-x divide-line'
}
>
<StatCell
label={t('statLastLogin')}
value={user.lastLoginAt ? fmtDateTime(user.lastLoginAt) : '—'}
@@ -184,11 +205,13 @@ export default function UserDetail() {
value={String(memberships.length)}
icon={<Building2 className="h-3.5 w-3.5" />}
/>
<StatCell
label={t('statClaims')}
value={String(claims.length)}
icon={<FileText className="h-3.5 w-3.5" />}
/>
{canVerify && (
<StatCell
label={t('statClaims')}
value={String(claims.length)}
icon={<FileText className="h-3.5 w-3.5" />}
/>
)}
<StatCell
label={t('statCreated')}
value={fmtDate(user.createdAt)}
@@ -227,10 +250,16 @@ export default function UserDetail() {
{memberships.map((m) => (
<tr
key={m.gymId}
onClick={() =>
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',
)}
>
<td className="px-3 py-2.5 align-top">
<div className="font-semibold">{m.gym.name}</div>
@@ -250,81 +279,85 @@ export default function UserDetail() {
</Card>
{/* LOGI KONTA: ostatnie 10 + przejście do pełnej podstrony (jak logi w konsoli siłowni) */}
<Card className="mb-0">
<div className="mb-2 flex items-center justify-between gap-2">
<H3 className="mb-0">{t('logsCardTitle')}</H3>
<Link
to={`/users/${user.id}/logs`}
className="text-[0.85rem] font-semibold text-accent-text hover:underline"
>
{t('allLogs')}
</Link>
</div>
{logs.length === 0 ? (
<p className="text-[0.85rem] text-dim">{t('noActivity')}</p>
) : (
<div className="divide-y divide-line">
{logs.map((log) => {
const details = detailsText(log);
return (
<div
key={log.id}
className="flex flex-wrap items-baseline gap-x-3 gap-y-1 py-2.5"
>
<span className="font-display text-dim text-[0.8rem] tabular-nums">
{formatLogDate(log.createdAt)}
</span>
<Badge color={actionColor(log.action)}>{actionLabel(log.action)}</Badge>
<span className="text-[0.875rem]">
{t('byActor', { actor: actorName(log) })}
</span>
{details && <span className="text-[0.8rem] text-dim">{details}</span>}
</div>
);
})}
{canLogs && (
<Card className="mb-0">
<div className="mb-2 flex items-center justify-between gap-2">
<H3 className="mb-0">{t('logsCardTitle')}</H3>
<Link
to={`/users/${user.id}/logs`}
className="text-[0.85rem] font-semibold text-accent-text hover:underline"
>
{t('allLogs')}
</Link>
</div>
)}
</Card>
{logs.length === 0 ? (
<p className="text-[0.85rem] text-dim">{t('noActivity')}</p>
) : (
<div className="divide-y divide-line">
{logs.map((log) => {
const details = detailsText(log);
return (
<div
key={log.id}
className="flex flex-wrap items-baseline gap-x-3 gap-y-1 py-2.5"
>
<span className="font-display text-dim text-[0.8rem] tabular-nums">
{formatLogDate(log.createdAt)}
</span>
<Badge color={actionColor(log.action)}>{actionLabel(log.action)}</Badge>
<span className="text-[0.875rem]">
{t('byActor', { actor: actorName(log) })}
</span>
{details && <span className="text-[0.8rem] text-dim">{details}</span>}
</div>
);
})}
</div>
)}
</Card>
)}
</div>
<aside className="flex min-w-0 flex-col gap-4">
{/* WNIOSKI siłowni złożone przez usera (read-only; decyzje w /verifications) */}
<Card className="mb-0">
<H3 className="mb-2">{t('claims')}</H3>
{claims.length === 0 ? (
<p className="text-[0.85rem] text-dim">{t('noClaimsDesc')}</p>
) : (
<div className="-mb-1 flex flex-col">
{claims.map((c) => (
<div
key={c.id}
className="flex flex-wrap items-center gap-2 border-b border-line/50 py-2 text-[0.83rem] last:border-b-0"
>
<Link
to={`/verifications/${c.id}`}
className="font-semibold hover:text-accent-text"
{canVerify && (
<Card className="mb-0">
<H3 className="mb-2">{t('claims')}</H3>
{claims.length === 0 ? (
<p className="text-[0.85rem] text-dim">{t('noClaimsDesc')}</p>
) : (
<div className="-mb-1 flex flex-col">
{claims.map((c) => (
<div
key={c.id}
className="flex flex-wrap items-center gap-2 border-b border-line/50 py-2 text-[0.83rem] last:border-b-0"
>
{c.gym?.name ?? c.gymName ?? '—'}
</Link>
<Badge
color={
c.status === 'PENDING'
? 'yellow'
: c.status === 'APPROVED'
? 'green'
: 'red'
}
>
{t(`claimStatus${c.status.charAt(0)}${c.status.slice(1).toLowerCase()}`)}
</Badge>
<span className="ml-auto text-[0.76rem] tabular-nums text-dim">
{fmtDate(c.createdAt)}
</span>
</div>
))}
</div>
)}
</Card>
<Link
to={`/verifications/${c.id}`}
className="font-semibold hover:text-accent-text"
>
{c.gym?.name ?? c.gymName ?? '—'}
</Link>
<Badge
color={
c.status === 'PENDING'
? 'yellow'
: c.status === 'APPROVED'
? 'green'
: 'red'
}
>
{t(`claimStatus${c.status.charAt(0)}${c.status.slice(1).toLowerCase()}`)}
</Badge>
<span className="ml-auto text-[0.76rem] tabular-nums text-dim">
{fmtDate(c.createdAt)}
</span>
</div>
))}
</div>
)}
</Card>
)}
</aside>
</div>

View File

@@ -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 (
<ul className="mb-2 mt-1.5 space-y-0.5 rounded-xl border border-line bg-input/40 px-3 py-2 text-[0.875rem] text-dim">
{items.map((g) => (
<li key={g} className="flex gap-1.5">
<span className="text-accent-text">•</span>
<span>{g}</span>
</li>
))}
</ul>
);
}
/**
* 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<HTMLFormElement>(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<string[]>([]);
// domyślnie zero wierszy — pierwszą siłownię dodaje admin (mile widziana w stanie pustym)
const [rows, setRows] = useState<MembershipRow[]>([]);
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<string, unknown> = {
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() {
/>
</Field>
<Field label={t('auth:email')}>
{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
<Input value={maskEmail(form.email)} readOnly disabled />
{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
<Input value={form.email} readOnly disabled />
) : (
<Input
type="email"
@@ -332,18 +335,20 @@ export default function UserForm() {
/>
)}
</Field>
<Field label={t('birthDate')}>
<Input
type="date"
max={todayStr()}
value={form.birthDate}
onChange={(e) => setForm({ ...form, birthDate: e.target.value })}
/>
</Field>
{canPii && (
<Field label={t('birthDate')}>
<Input
type="date"
max={todayStr()}
value={form.birthDate}
onChange={(e) => setForm({ ...form, birthDate: e.target.value })}
/>
</Field>
)}
</div>
</Card>
{/* Krok 2 — role w panelu */}
{/* Krok 2 — role platformowe */}
<Card>
<div className="mb-3 flex items-center gap-2.5">
<span className="grid h-7 w-7 place-items-center rounded-full bg-accent/10 text-[0.8rem] font-bold text-accent-text">
@@ -352,49 +357,59 @@ export default function UserForm() {
<H3 className="mb-0">{t('stepRoles')}</H3>
</div>
{/* Rola administratora platformy */}
<div className="rounded-xl border border-line bg-input/40 p-3">
<div className="flex items-center justify-between gap-3">
<label className="flex min-w-0 cursor-pointer items-center gap-3">
<input
type="checkbox"
className="h-4 w-4"
checked={form.isAdmin}
onChange={(e) => setForm({ ...form, isAdmin: e.target.checked })}
/>
<span className="min-w-0">
<span className="flex items-center gap-1.5 text-[0.95rem] font-semibold">
<ShieldCheck className="h-4 w-4 text-accent-text" />
{t('adminPlatformTitle')}
</span>
<span className="block text-[0.8125rem] text-dim">
{t(`common:${ADMIN_ROLE_META.summaryKey}`)}
</span>
</span>
</label>
<button
type="button"
onClick={() => setAdminExplain((v) => !v)}
className="shrink-0 cursor-pointer p-1 text-dim hover:text-ink"
aria-label={adminExplain ? t('ariaHideAdmin') : t('ariaShowAdmin')}
>
<ChevronDown
className={`h-4 w-4 transition-transform ${adminExplain ? 'rotate-180' : ''}`}
/>
</button>
{canRoles ? (
<div className="rounded-xl border border-line bg-input/40 p-3">
<p className="mb-2 text-[0.8125rem] text-dim">{t('platformRolesHint')}</p>
<div className="flex flex-col gap-1.5">
{platformRoles.map((r) => (
<label
key={r.id}
className="flex cursor-pointer items-center gap-3 rounded-lg px-1 py-1.5 hover:bg-line/30"
>
<input
type="checkbox"
className="h-4 w-4"
checked={roleKeys.includes(r.key)}
onChange={(e) =>
setRoleKeys((ks) =>
e.target.checked ? [...ks, r.key] : ks.filter((k) => k !== r.key),
)
}
/>
<span className="flex min-w-0 items-center gap-1.5 text-[0.95rem] font-semibold">
<ShieldCheck className="h-4 w-4 shrink-0 text-accent-text" />
{t(`roles:names.${r.key}`, { defaultValue: r.key })}
</span>
<Badge color="gray" className="ml-auto shrink-0">
{t('roles:grantCount', { count: r.grantCount })}
</Badge>
</label>
))}
</div>
</div>
<AdminExplain
open={adminExplain}
items={ADMIN_ROLE_META.grantKeys.map((k) => t(`common:${k}`))}
/>
</div>
) : (
<div className="rounded-xl border border-line bg-input/40 p-3">
{isEdit && (user?.platformRoles?.length ?? 0) > 0 ? (
<div className="flex flex-wrap gap-1.5">
{(user?.platformRoles ?? []).map((k) => (
<Badge key={k} color="blue">
{t(`roles:names.${k}`, { defaultValue: k })}
</Badge>
))}
</div>
) : (
<p className="text-[0.875rem] text-dim">{t('noPlatformRoles')}</p>
)}
<p className="mt-2 text-[0.8125rem] text-dim">{t('rolesNeedManageNote')}</p>
</div>
)}
</Card>
{/* Krok 3 — członkostwa w siłowniach (edytor: tworzenie POST, edycja POST/PATCH/DELETE) */}
<Card>
<div className="mb-3 flex items-center gap-2.5">
<span className="grid h-7 w-7 place-items-center rounded-full bg-accent/10 text-[0.8rem] font-bold text-accent-text">
{isEdit ? 4 : 3}
3
</span>
<div className="flex min-w-0 flex-1 items-center justify-between gap-3">
<H3 className="mb-0">{t('membershipsTitle')}</H3>
@@ -443,7 +458,7 @@ export default function UserForm() {
/>
</div>
<div>
<Label>{t('stepRoles')}</Label>
<Label>{t('gymRolesLabel')}</Label>
<GymRolePicker
value={r.roles}
onChange={(roles) => updateRow(r.key, { roles })}

View File

@@ -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() {
<Badge color="yellow">{t('statusSuspended')}</Badge>
)}
{u.status === 'BANNED' && <Badge color="red">{t('statusBanned')}</Badge>}
{u.isAdmin && <Badge color="blue">{t('adminBadge')}</Badge>}
{u.platformRoles.map((r) => (
<Badge key={r} color="blue">
{t(`roles:names.${r}`, { defaultValue: r })}
</Badge>
))}
<Badge color="gray">
{t('gymsShort', { count: u.memberships?.length ?? 0 })}
</Badge>

View File

@@ -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() {

View File

@@ -32,9 +32,9 @@ export const useAuth = create<AuthState>((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<AuthState>((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