diff --git a/backend/src/controllers/rbacController.ts b/backend/src/controllers/rbacController.ts index 968c5fd3..0bdb6fff 100644 --- a/backend/src/controllers/rbacController.ts +++ b/backend/src/controllers/rbacController.ts @@ -112,3 +112,85 @@ export async function getMyPermissions(req: AuthRequest, res: Response): Promise res.status(400).json({ error: msg }); } } + +export async function listAdminUsers(req: AuthRequest, res: Response): Promise { + try { + const q = req.query as Record; + const exceptionRaw = q.exception ?? 'all'; + const exception = + exceptionRaw === 'any' || + exceptionRaw === 'allow' || + exceptionRaw === 'deny' || + exceptionRaw === 'none' || + exceptionRaw === 'all' + ? exceptionRaw + : 'all'; + const data = await rbacService.listAdminUsers({ + search: q.search, + role: q.role, + exception, + permission: q.permission, + limit: q.limit ? parseInt(q.limit, 10) : 50, + offset: q.offset ? parseInt(q.offset, 10) : 0, + }); + res.json(data); + } catch (e) { + const msg = e instanceof Error ? e.message : 'Failed to list admin users'; + res.status(400).json({ error: msg }); + } +} + +export async function getAdminUser(req: AuthRequest, res: Response): Promise { + try { + const userId = req.params.userId; + const data = await rbacService.getAdminUser(userId); + if (!data) { + res.status(404).json({ error: 'User not found' }); + return; + } + res.json(data); + } catch (e) { + const msg = e instanceof Error ? e.message : 'Failed to load admin user'; + res.status(400).json({ error: msg }); + } +} + +export async function getAdminUserPermissions(req: AuthRequest, res: Response): Promise { + try { + const userId = req.params.userId; + const data = await rbacService.getAdminUser(userId); + if (!data) { + res.status(404).json({ error: 'User not found' }); + return; + } + res.json({ + user: data.user, + permissions: data.permissions, + categories: data.categories, + }); + } catch (e) { + const msg = e instanceof Error ? e.message : 'Failed to load permissions'; + res.status(400).json({ error: msg }); + } +} + +export async function updateAdminUserPermissions(req: AuthRequest, res: Response): Promise { + try { + const userId = req.params.userId; + const body = req.body as { + permissionKey?: string; + action?: 'allow' | 'deny' | 'reset'; + changes?: Array<{ key: string; action: 'allow' | 'deny' | 'reset' }>; + }; + const changes = + body.changes ?? + (body.permissionKey && body.action + ? [{ key: body.permissionKey, action: body.action }] + : []); + const data = await rbacService.applyUserPermissionChanges(userId, changes, req.user!.userId); + res.json(data); + } catch (e) { + const msg = e instanceof Error ? e.message : 'Failed to update permissions'; + res.status(400).json({ error: msg }); + } +} diff --git a/backend/src/db/schema.sql b/backend/src/db/schema.sql index aced9cc9..965c24f5 100644 --- a/backend/src/db/schema.sql +++ b/backend/src/db/schema.sql @@ -104,6 +104,22 @@ CREATE TABLE IF NOT EXISTS user_roles ( CREATE INDEX IF NOT EXISTS idx_user_roles_role ON user_roles(role_id); +-- Per-user permission exceptions (allow / deny) layered on top of role grants +CREATE TABLE IF NOT EXISTS user_permission_overrides ( + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + permission_id INTEGER NOT NULL REFERENCES permissions(id) ON DELETE CASCADE, + effect VARCHAR(8) NOT NULL CHECK (effect IN ('allow', 'deny')), + created_at TIMESTAMPTZ DEFAULT NOW(), + updated_at TIMESTAMPTZ DEFAULT NOW(), + updated_by UUID REFERENCES users(id), + PRIMARY KEY (user_id, permission_id) +); + +CREATE INDEX IF NOT EXISTS idx_user_permission_overrides_permission + ON user_permission_overrides(permission_id); +CREATE INDEX IF NOT EXISTS idx_user_permission_overrides_effect + ON user_permission_overrides(effect); + -- Backfill user_roles from legacy users.role_id INSERT INTO user_roles (user_id, role_id) SELECT u.id, u.role_id FROM users u @@ -2467,7 +2483,8 @@ INSERT INTO system_settings (key, value) VALUES ('sybil_auto_suspend_accounts', 'true'), ('login_risk_auto_suspend_accounts', 'false'), ('login_risk_auto_suspend_threshold', '70'), - ('encryption_key_rotated_at', '') + ('encryption_key_rotated_at', ''), + ('engine_audit_log_retention_days', '7') ON CONFLICT (key) DO NOTHING; -- Referral commissions on each validated prediction (stake-based) diff --git a/backend/src/domain/candle-predict/index.ts b/backend/src/domain/candle-predict/index.ts index 83905ced..441c20fe 100644 --- a/backend/src/domain/candle-predict/index.ts +++ b/backend/src/domain/candle-predict/index.ts @@ -8,6 +8,7 @@ import * as settingsRepository from '../../repositories/settingsRepository'; import { assertPositiveStakeAmount, parseStakeAmountFromBody } from '../../utils/stakeAmountValidation'; import { queueUserAdminStatsRefresh } from '../../services/userAdminStatsService'; import * as predictionAuditService from '../../services/predictionAuditService'; +import { startEngineAuditRetentionJob } from '../../services/engineAuditRetentionService'; import { processPredictionReferralCommissions } from '../../services/referralService'; import { generateSyntheticCandle, @@ -2497,4 +2498,5 @@ export function startCandlePredictEngine(): void { setTimeout(run, tickMs); }; setTimeout(run, 5000); + startEngineAuditRetentionJob(); } diff --git a/backend/src/models/settings.model.ts b/backend/src/models/settings.model.ts index 060d61a6..d99e1597 100644 --- a/backend/src/models/settings.model.ts +++ b/backend/src/models/settings.model.ts @@ -27,6 +27,8 @@ export interface SystemSettings { candle_predict_backfill_max_per_tick: number; candle_predict_backfill_interval_ms: number; candle_predict_backfill_seed_max: number; + /** Days to keep engine-only audit rows such as prediction_round_settled (0 = never purge). */ + engine_audit_log_retention_days: number; /** Network fee deducted from user USDT balance per withdrawal (6-decimal micro units). */ withdrawal_network_fee_usdt_micro: number; /** When true, admin/super_admin routes require TOTP to be enabled. */ diff --git a/backend/src/rbac/permissionResolver.ts b/backend/src/rbac/permissionResolver.ts index 293c6777..3dda7216 100644 --- a/backend/src/rbac/permissionResolver.ts +++ b/backend/src/rbac/permissionResolver.ts @@ -49,3 +49,18 @@ export function userHasAllPermissions(userPerms: string[], required: string[]): export function userHasAnyPermission(userPerms: string[], required: string[]): boolean { return required.some((p) => userHasPermission(userPerms, p)); } + +/** + * Effective permissions = role grants ∪ individual allows − individual denies. + * Deny always wins over inherited and direct allow. + */ +export function mergePermissionSets( + inherited: string[], + directAllow: string[], + directDeny: string[] +): string[] { + const set = new Set(inherited); + for (const key of directAllow) set.add(key); + for (const key of directDeny) set.delete(key); + return [...set].sort(); +} diff --git a/backend/src/rbac/syncPermissions.ts b/backend/src/rbac/syncPermissions.ts index 66b8a89e..42b6fd1f 100644 --- a/backend/src/rbac/syncPermissions.ts +++ b/backend/src/rbac/syncPermissions.ts @@ -24,6 +24,26 @@ export async function syncPermissionCatalog(): Promise { ALTER TABLE permissions ADD COLUMN IF NOT EXISTS is_system BOOLEAN NOT NULL DEFAULT TRUE; `); + await query(` + CREATE TABLE IF NOT EXISTS user_permission_overrides ( + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + permission_id INTEGER NOT NULL REFERENCES permissions(id) ON DELETE CASCADE, + effect VARCHAR(8) NOT NULL CHECK (effect IN ('allow', 'deny')), + created_at TIMESTAMPTZ DEFAULT NOW(), + updated_at TIMESTAMPTZ DEFAULT NOW(), + updated_by UUID REFERENCES users(id), + PRIMARY KEY (user_id, permission_id) + ) + `); + await query(` + CREATE INDEX IF NOT EXISTS idx_user_permission_overrides_permission + ON user_permission_overrides(permission_id) + `); + await query(` + CREATE INDEX IF NOT EXISTS idx_user_permission_overrides_effect + ON user_permission_overrides(effect) + `); + // Mark system roles for (const name of SYSTEM_ROLE_NAMES) { await query(`UPDATE roles SET is_system = TRUE WHERE name = $1`, [name]); diff --git a/backend/src/repositories/auditLogRepository.ts b/backend/src/repositories/auditLogRepository.ts index f7d00434..d451aa9f 100644 --- a/backend/src/repositories/auditLogRepository.ts +++ b/backend/src/repositories/auditLogRepository.ts @@ -53,9 +53,30 @@ export type AuditLogRow = { created_at: Date; }; +export const ENGINE_AUDIT_ACTIONS = ['prediction_round_settled'] as const; + +export async function deleteEngineAuditLogsOlderThan(cutoff: Date, batchSize = 5000): Promise { + const result = await query<{ count: string }[]>( + `WITH deleted AS ( + DELETE FROM audit_logs + WHERE ctid IN ( + SELECT ctid FROM audit_logs + WHERE action = ANY($1::text[]) + AND created_at < $2 + LIMIT $3 + ) + RETURNING 1 + ) + SELECT COUNT(*)::text AS count FROM deleted`, + [ENGINE_AUDIT_ACTIONS, cutoff, Math.min(Math.max(batchSize, 100), 20_000)] + ); + return parseInt(result[0]?.count ?? '0', 10); +} + export async function listAuditLogs(filters: { action?: string; actions?: string[]; + excludeActions?: string[]; userId?: string; from?: Date; to?: Date; @@ -72,6 +93,9 @@ export async function listAuditLogs(filters: { } else if (filters.actions?.length) { conditions.push(`action = ANY($${i++})`); params.push(filters.actions); + } else if (filters.excludeActions?.length) { + conditions.push(`NOT (action = ANY($${i++}))`); + params.push(filters.excludeActions); } if (filters.userId) { conditions.push(`user_id = $${i++}`); @@ -110,6 +134,7 @@ export async function listAuditLogs(filters: { export async function exportAuditLogsCsv(filters: { action?: string; actions?: string[]; + excludeActions?: string[]; userId?: string; from?: Date; to?: Date; diff --git a/backend/src/repositories/roleRepository.ts b/backend/src/repositories/roleRepository.ts index bbae463e..4971453f 100644 --- a/backend/src/repositories/roleRepository.ts +++ b/backend/src/repositories/roleRepository.ts @@ -2,10 +2,10 @@ * Roles, permissions, and user_roles (many-to-many). */ -import { query } from '../db/connection'; +import { beginAuthorizedTransaction, getClient, query } from '../db/connection'; import type { RoleName } from '../models'; import { SYSTEM_ROLE_NAMES, isSystemRole } from '../rbac/permissionCatalog'; -import { userHasPermission as resolvePermission } from '../rbac/permissionResolver'; +import { userHasPermission as resolvePermission, mergePermissionSets } from '../rbac/permissionResolver'; const ALL_ROLE_NAMES: RoleName[] = ['user', 'moderator', 'admin', 'super_admin']; @@ -160,7 +160,7 @@ export async function getUserRoleNames(userId: string): Promise { return legacy[0] ? [legacy[0].name] : ['user']; } -export async function getUserPermissions(userId: string): Promise { +export async function getUserInheritedPermissionKeys(userId: string): Promise { const rows = await query<{ key: string }[]>( `SELECT DISTINCT p.key FROM user_roles ur @@ -177,12 +177,374 @@ export async function getUserPermissions(userId: string): Promise { JOIN role_permissions rp ON rp.role_id = u.role_id JOIN permissions p ON p.id = rp.permission_id WHERE u.id = $1 + AND NOT EXISTS (SELECT 1 FROM user_roles ur WHERE ur.user_id = u.id) ORDER BY p.key`, [userId] ); return legacy.map((r) => r.key); } +export type PermissionOverrideRow = { + key: string; + effect: 'allow' | 'deny'; +}; + +export async function getUserPermissionOverrides(userId: string): Promise { + const rows = await query( + `SELECT p.key, o.effect + FROM user_permission_overrides o + JOIN permissions p ON p.id = o.permission_id + WHERE o.user_id = $1 + ORDER BY p.key`, + [userId] + ); + return rows; +} + +export async function getUserPermissions(userId: string): Promise { + const [inherited, overrides] = await Promise.all([ + getUserInheritedPermissionKeys(userId), + getUserPermissionOverrides(userId), + ]); + const allow = overrides.filter((o) => o.effect === 'allow').map((o) => o.key); + const deny = overrides.filter((o) => o.effect === 'deny').map((o) => o.key); + return mergePermissionSets(inherited, allow, deny); +} + +export async function setUserPermissionOverride( + userId: string, + permissionKey: string, + effect: 'allow' | 'deny', + actorUserId: string +): Promise { + const result = await query<{ id: number }[]>( + `INSERT INTO user_permission_overrides (user_id, permission_id, effect, updated_by, updated_at) + SELECT $1, p.id, $3, $4, NOW() + FROM permissions p + WHERE p.key = $2 + ON CONFLICT (user_id, permission_id) DO UPDATE SET + effect = EXCLUDED.effect, + updated_by = EXCLUDED.updated_by, + updated_at = NOW() + RETURNING permission_id AS id`, + [userId, permissionKey, effect, actorUserId] + ); + if (!result[0]) throw new Error(`Unknown permission: ${permissionKey}`); +} + +export async function deleteUserPermissionOverride(userId: string, permissionKey: string): Promise { + await query( + `DELETE FROM user_permission_overrides o + USING permissions p + WHERE o.permission_id = p.id AND o.user_id = $1 AND p.key = $2`, + [userId, permissionKey] + ); +} + +export async function applyUserPermissionOverrideChanges( + userId: string, + changes: Array<{ key: string; action: 'allow' | 'deny' | 'reset' }>, + actorUserId: string +): Promise { + const client = await getClient(); + try { + await beginAuthorizedTransaction(client); + for (const change of changes) { + if (change.action === 'reset') { + await client.query( + `DELETE FROM user_permission_overrides o + USING permissions p + WHERE o.permission_id = p.id AND o.user_id = $1 AND p.key = $2`, + [userId, change.key] + ); + continue; + } + const result = await client.query( + `INSERT INTO user_permission_overrides (user_id, permission_id, effect, updated_by, updated_at) + SELECT $1, p.id, $3, $4, NOW() + FROM permissions p + WHERE p.key = $2 + ON CONFLICT (user_id, permission_id) DO UPDATE SET + effect = EXCLUDED.effect, + updated_by = EXCLUDED.updated_by, + updated_at = NOW() + RETURNING permission_id`, + [userId, change.key, change.action, actorUserId] + ); + if (!result.rows[0]) throw new Error(`Unknown permission: ${change.key}`); + } + await client.query('COMMIT'); + } catch (e) { + await client.query('ROLLBACK').catch(() => undefined); + throw e; + } finally { + client.release(); + } +} + +export type PermissionBreakdownRow = { + key: string; + description: string | null; + category: string | null; + inherited: boolean; + directAllow: boolean; + directDeny: boolean; + sources: string[]; +}; + +export async function getUserPermissionBreakdown(userId: string): Promise { + const [catalog, inherited, overrides, sources] = await Promise.all([ + listAllPermissions(), + getUserInheritedPermissionKeys(userId), + getUserPermissionOverrides(userId), + query<{ key: string; role_name: string }[]>( + `SELECT DISTINCT p.key, r.name AS role_name + FROM user_roles ur + JOIN roles r ON r.id = ur.role_id + JOIN role_permissions rp ON rp.role_id = ur.role_id + JOIN permissions p ON p.id = rp.permission_id + WHERE ur.user_id = $1`, + [userId] + ), + ]); + const inheritedSet = new Set(inherited); + const allowSet = new Set(overrides.filter((o) => o.effect === 'allow').map((o) => o.key)); + const denySet = new Set(overrides.filter((o) => o.effect === 'deny').map((o) => o.key)); + const sourcesByKey = new Map(); + for (const row of sources) { + const list = sourcesByKey.get(row.key) ?? []; + list.push(row.role_name); + sourcesByKey.set(row.key, list); + } + return catalog.map((p) => ({ + key: p.key, + description: p.description, + category: p.category, + inherited: inheritedSet.has(p.key), + directAllow: allowSet.has(p.key), + directDeny: denySet.has(p.key), + sources: sourcesByKey.get(p.key) ?? [], + })); +} + +export type RoleAssignedUserRow = { + id: string; + email_encrypted: string | null; + first_name: string | null; + last_name: string | null; +}; + +export async function listUsersForRole(roleId: number): Promise { + return query( + `SELECT u.id, u.email_encrypted, u.first_name, u.last_name + FROM user_roles ur + JOIN users u ON u.id = ur.user_id + WHERE ur.role_id = $1 AND u.deleted_at IS NULL + ORDER BY u.created_at DESC + LIMIT 100`, + [roleId] + ); +} + +export type AdminStaffListFilters = { + searchHash?: string | null; + searchText?: string | null; + role?: string | null; + exception?: 'all' | 'any' | 'allow' | 'deny' | 'none'; + permission?: string | null; + limit: number; + offset: number; +}; + +export type AdminStaffListRow = { + id: string; + email_encrypted: string | null; + first_name: string | null; + last_name: string | null; + is_enabled: boolean; + roles: string[]; + inherited_count: number; + allow_count: number; + deny_count: number; + effective_count: number; +}; + +export async function listAdministrativeUsers( + filters: AdminStaffListFilters +): Promise<{ users: AdminStaffListRow[]; total: number }> { + const conditions: string[] = ['u.deleted_at IS NULL']; + const values: unknown[] = []; + let i = 1; + + conditions.push(`( + EXISTS ( + SELECT 1 FROM user_roles urx + JOIN roles rx ON rx.id = urx.role_id + WHERE urx.user_id = u.id AND rx.name <> 'user' + ) + OR EXISTS (SELECT 1 FROM user_permission_overrides ox WHERE ox.user_id = u.id) + )`); + + if (filters.role?.trim()) { + conditions.push(`EXISTS ( + SELECT 1 FROM user_roles urf + JOIN roles rf ON rf.id = urf.role_id + WHERE urf.user_id = u.id AND rf.name = $${i++} + )`); + values.push(filters.role.trim().toLowerCase()); + } + + if (filters.searchHash) { + conditions.push(`u.email_hash = $${i++}`); + values.push(filters.searchHash); + } else if (filters.searchText) { + conditions.push(`( + u.first_name ILIKE $${i} OR u.last_name ILIKE $${i} OR u.id::text ILIKE $${i} + )`); + values.push(`%${filters.searchText}%`); + i++; + } + + if (filters.exception === 'any') { + conditions.push(`EXISTS (SELECT 1 FROM user_permission_overrides o WHERE o.user_id = u.id)`); + } else if (filters.exception === 'allow') { + conditions.push( + `EXISTS (SELECT 1 FROM user_permission_overrides o WHERE o.user_id = u.id AND o.effect = 'allow')` + ); + } else if (filters.exception === 'deny') { + conditions.push( + `EXISTS (SELECT 1 FROM user_permission_overrides o WHERE o.user_id = u.id AND o.effect = 'deny')` + ); + } else if (filters.exception === 'none') { + conditions.push(`NOT EXISTS (SELECT 1 FROM user_permission_overrides o WHERE o.user_id = u.id)`); + } + + if (filters.permission?.trim()) { + conditions.push(`( + ( + EXISTS ( + SELECT 1 FROM user_roles urp + JOIN role_permissions rpp ON rpp.role_id = urp.role_id + JOIN permissions pp ON pp.id = rpp.permission_id + WHERE urp.user_id = u.id AND pp.key = $${i} + ) + OR EXISTS ( + SELECT 1 FROM user_permission_overrides oa + JOIN permissions pa ON pa.id = oa.permission_id + WHERE oa.user_id = u.id AND oa.effect = 'allow' AND pa.key = $${i} + ) + ) + AND NOT EXISTS ( + SELECT 1 FROM user_permission_overrides od + JOIN permissions pd ON pd.id = od.permission_id + WHERE od.user_id = u.id AND od.effect = 'deny' AND pd.key = $${i} + ) + )`); + values.push(filters.permission.trim()); + i++; + } + + const where = conditions.join(' AND '); + const countRows = await query<{ count: string }[]>( + `SELECT COUNT(*)::text AS count FROM users u WHERE ${where}`, + values + ); + const total = parseInt(countRows[0]?.count ?? '0', 10); + + const limit = Math.min(Math.max(filters.limit, 1), 100); + const offset = Math.max(filters.offset, 0); + const listValues = [...values, limit, offset]; + const limitIdx = i; + const offsetIdx = i + 1; + + const rows = await query< + { + id: string; + email_encrypted: string | null; + first_name: string | null; + last_name: string | null; + is_enabled: boolean; + roles: string[] | null; + inherited_count: string; + allow_count: string; + deny_count: string; + effective_count: string; + }[] + >( + `SELECT u.id, u.email_encrypted, u.first_name, u.last_name, u.is_enabled, + COALESCE(( + SELECT array_agg(r.name ORDER BY r.is_system DESC, r.name) + FROM user_roles ur JOIN roles r ON r.id = ur.role_id + WHERE ur.user_id = u.id + ), ARRAY[]::text[]) AS roles, + COALESCE(( + SELECT COUNT(DISTINCT p.id)::text + FROM user_roles ur + JOIN role_permissions rp ON rp.role_id = ur.role_id + JOIN permissions p ON p.id = rp.permission_id + WHERE ur.user_id = u.id + ), '0') AS inherited_count, + COALESCE(( + SELECT COUNT(*)::text FROM user_permission_overrides o + WHERE o.user_id = u.id AND o.effect = 'allow' + ), '0') AS allow_count, + COALESCE(( + SELECT COUNT(*)::text FROM user_permission_overrides o + WHERE o.user_id = u.id AND o.effect = 'deny' + ), '0') AS deny_count, + COALESCE(( + SELECT COUNT(*)::text FROM ( + SELECT p.key + FROM user_roles ur + JOIN role_permissions rp ON rp.role_id = ur.role_id + JOIN permissions p ON p.id = rp.permission_id + WHERE ur.user_id = u.id + UNION + SELECT p.key + FROM user_permission_overrides oa + JOIN permissions p ON p.id = oa.permission_id + WHERE oa.user_id = u.id AND oa.effect = 'allow' + ) combined + WHERE NOT EXISTS ( + SELECT 1 FROM user_permission_overrides od + JOIN permissions pd ON pd.id = od.permission_id + WHERE od.user_id = u.id AND od.effect = 'deny' AND pd.key = combined.key + ) + ), '0') AS effective_count + FROM users u + WHERE ${where} + ORDER BY u.created_at DESC + LIMIT $${limitIdx} OFFSET $${offsetIdx}`, + listValues + ); + + return { + total, + users: rows.map((r) => ({ + id: r.id, + email_encrypted: r.email_encrypted, + first_name: r.first_name, + last_name: r.last_name, + is_enabled: r.is_enabled, + roles: Array.isArray(r.roles) ? r.roles : [], + inherited_count: parseInt(r.inherited_count, 10) || 0, + allow_count: parseInt(r.allow_count, 10) || 0, + deny_count: parseInt(r.deny_count, 10) || 0, + effective_count: parseInt(r.effective_count, 10) || 0, + })), + }; +} + +export async function getUserNameFields( + userId: string +): Promise<{ first_name: string | null; last_name: string | null } | null> { + const rows = await query<{ first_name: string | null; last_name: string | null }[]>( + `SELECT first_name, last_name FROM users WHERE id = $1 AND deleted_at IS NULL`, + [userId] + ); + return rows[0] ?? null; +} + export async function userHasPermission(userId: string, permissionKey: string): Promise { const perms = await getUserPermissions(userId); return resolvePermission(perms, permissionKey); diff --git a/backend/src/repositories/settingsRepository.ts b/backend/src/repositories/settingsRepository.ts index dc1e9ceb..433ac198 100644 --- a/backend/src/repositories/settingsRepository.ts +++ b/backend/src/repositories/settingsRepository.ts @@ -61,6 +61,7 @@ function buildDefaults(): SystemSettings { candle_predict_backfill_interval_ms: config.candlePredict.backfillIntervalMs, candle_predict_backfill_seed_max: config.candlePredict.backfillSeedMax, + engine_audit_log_retention_days: 7, withdrawal_network_fee_usdt_micro: config.withdrawal.networkFeeUsdtMicro, @@ -136,6 +137,8 @@ const INTEGER_KEYS = new Set([ 'candle_predict_backfill_seed_max', + 'engine_audit_log_retention_days', + 'withdrawal_network_fee_usdt_micro', 'login_max_failed_attempts', @@ -264,6 +267,8 @@ const UPDATABLE_KEYS = [ 'candle_predict_backfill_seed_max', + 'engine_audit_log_retention_days', + 'withdrawal_network_fee_usdt_micro', 'require_admin_2fa', diff --git a/backend/src/routes/index.ts b/backend/src/routes/index.ts index ab00ae8f..0216a3ac 100644 --- a/backend/src/routes/index.ts +++ b/backend/src/routes/index.ts @@ -283,6 +283,10 @@ router.get('/admin/rbac/roles/:roleId', requireRoles('admin'), requirePermission router.post('/admin/rbac/roles', requireRoles('admin'), requirePermissions('admin.rbac.manage'), asyncHandler(rbacController.createRole)); router.patch('/admin/rbac/roles/:roleId', requireRoles('admin'), requirePermissions('admin.rbac.manage'), asyncHandler(rbacController.updateRole)); router.delete('/admin/rbac/roles/:roleId', requireRoles('admin'), requirePermissions('admin.rbac.manage'), asyncHandler(rbacController.deleteRole)); +router.get('/admin/rbac/admin-users', requireRoles('admin'), requirePermissions('admin.rbac.view'), asyncHandler(rbacController.listAdminUsers)); +router.get('/admin/rbac/admin-users/:userId/permissions', requireRoles('admin'), requirePermissions('admin.rbac.view'), asyncHandler(rbacController.getAdminUserPermissions)); +router.patch('/admin/rbac/admin-users/:userId/permissions', requireRoles('admin'), requirePermissions('admin.rbac.manage'), asyncHandler(rbacController.updateAdminUserPermissions)); +router.get('/admin/rbac/admin-users/:userId', requireRoles('admin'), requirePermissions('admin.rbac.view'), asyncHandler(rbacController.getAdminUser)); router.get('/admin/rbac/me', authMiddleware, asyncHandler(rbacController.getMyPermissions)); router.delete( '/admin/users/:userId', diff --git a/backend/src/services/engineAuditRetentionService.ts b/backend/src/services/engineAuditRetentionService.ts new file mode 100644 index 00000000..e78637f7 --- /dev/null +++ b/backend/src/services/engineAuditRetentionService.ts @@ -0,0 +1,43 @@ +/** + * Periodically deletes engine-only audit rows (prediction_round_settled) + * older than the configured retention window. + */ +import * as settingsRepository from '../repositories/settingsRepository'; +import * as auditLogRepository from '../repositories/auditLogRepository'; + +const PURGE_INTERVAL_MS = 15 * 60 * 1000; +const MAX_BATCHES_PER_RUN = 20; + +let started = false; + +export async function purgeExpiredEngineAuditLogs(): Promise { + const settings = await settingsRepository.getSettings(); + const days = settings.engine_audit_log_retention_days; + if (!Number.isFinite(days) || days <= 0) return 0; + + const cutoff = new Date(Date.now() - days * 24 * 60 * 60 * 1000); + let deleted = 0; + for (let i = 0; i < MAX_BATCHES_PER_RUN; i += 1) { + const batch = await auditLogRepository.deleteEngineAuditLogsOlderThan(cutoff); + deleted += batch; + if (batch === 0) break; + } + if (deleted > 0) { + console.log(`[engine-audit-retention] purged ${deleted} prediction_round_settled row(s) older than ${days} day(s)`); + } + return deleted; +} + +export function startEngineAuditRetentionJob(): void { + if (started) return; + started = true; + const run = async () => { + try { + await purgeExpiredEngineAuditLogs(); + } catch (e) { + console.error('[engine-audit-retention] purge failed:', e); + } + setTimeout(run, PURGE_INTERVAL_MS); + }; + setTimeout(run, 20_000); +} diff --git a/backend/src/services/rbacService.ts b/backend/src/services/rbacService.ts index 3317c17d..a4c87bb1 100644 --- a/backend/src/services/rbacService.ts +++ b/backend/src/services/rbacService.ts @@ -6,6 +6,7 @@ import * as roleRepository from '../repositories/roleRepository'; import * as auditLogRepository from '../repositories/auditLogRepository'; import * as userRepository from '../repositories/userRepository'; import { isSystemRole, PERMISSION_CATALOG } from '../rbac/permissionCatalog'; +import { decrypt, hashForIndex } from '../utils/crypto'; export type RoleDto = { id: number; @@ -59,11 +60,14 @@ export async function listRoles(): Promise { return result; } -export async function getRole(roleId: number): Promise { +export async function getRole(roleId: number): Promise<(RoleDto & { + assignedUsers: Array<{ id: string; email: string | null; fullName: string | null }>; +}) | null> { const role = await roleRepository.findRoleById(roleId); if (!role) return null; const permissionKeys = await roleRepository.getRolePermissionKeys(roleId); const userCount = await roleRepository.countUsersWithRoleId(roleId); + const assigned = await roleRepository.listUsersForRole(roleId); return { id: role.id, name: role.name, @@ -71,6 +75,11 @@ export async function getRole(roleId: number): Promise { isSystem: role.is_system, permissionKeys, userCount, + assignedUsers: assigned.map((u) => ({ + id: u.id, + email: decryptEmail(u.email_encrypted), + fullName: fullName(u.first_name, u.last_name), + })), }; } @@ -136,13 +145,17 @@ export async function updateRole( let newName = role.name; if (input.name !== undefined) { + const normalizedIncoming = input.name.trim().toLowerCase().replace(/\s+/g, '_'); if (role.is_system) { - throw new Error('System role names cannot be changed'); - } - newName = validateCustomRoleName(input.name); - const existing = await roleRepository.findRoleByName(newName); - if (existing && existing.id !== roleId) { - throw new Error('A role with this name already exists'); + if (normalizedIncoming !== role.name) { + throw new Error('System role names cannot be changed'); + } + } else { + newName = validateCustomRoleName(input.name); + const existing = await roleRepository.findRoleByName(newName); + if (existing && existing.id !== roleId) { + throw new Error('A role with this name already exists'); + } } } @@ -200,3 +213,187 @@ async function bumpTokenVersionForRoleUsers(roleId: number): Promise { export async function bumpUserTokenOnRoleChange(userId: string): Promise { await userRepository.incrementTokenVersion(userId); } + +function decryptEmail(encrypted: string | null): string | null { + if (!encrypted) return null; + try { + return decrypt(encrypted); + } catch { + return null; + } +} + +function fullName(first: string | null, last: string | null): string | null { + const name = [first, last].filter(Boolean).join(' ').trim(); + return name || null; +} + +async function assertAdministrativeUser(userId: string): Promise { + const user = await userRepository.getForAdmin(userId); + if (!user) throw new Error('User not found'); + const roles = await roleRepository.getUserRoleNames(userId); + const overrides = await roleRepository.getUserPermissionOverrides(userId); + const isAdminStaff = roles.some((r) => r !== 'user') || overrides.length > 0; + if (!isAdminStaff) { + throw new Error('Permission overrides can only be applied to administrative users'); + } + return roles; +} + +export type AdminStaffUserDto = { + id: string; + email: string | null; + fullName: string | null; + isEnabled: boolean; + roles: string[]; + inheritedCount: number; + allowCount: number; + denyCount: number; + effectiveCount: number; +}; + +export async function listAdminUsers(filters: { + search?: string; + role?: string; + exception?: 'all' | 'any' | 'allow' | 'deny' | 'none'; + permission?: string; + limit?: number; + offset?: number; +}): Promise<{ users: AdminStaffUserDto[]; total: number }> { + const search = filters.search?.trim() ?? ''; + let searchHash: string | null = null; + let searchText: string | null = null; + if (search.includes('@')) { + searchHash = hashForIndex(search.toLowerCase()); + } else if (search) { + searchText = search; + } + + const result = await roleRepository.listAdministrativeUsers({ + searchHash, + searchText, + role: filters.role ?? null, + exception: filters.exception ?? 'all', + permission: filters.permission ?? null, + limit: filters.limit ?? 50, + offset: filters.offset ?? 0, + }); + + return { + total: result.total, + users: result.users.map((u) => ({ + id: u.id, + email: decryptEmail(u.email_encrypted), + fullName: fullName(u.first_name, u.last_name), + isEnabled: u.is_enabled, + roles: u.roles, + inheritedCount: u.inherited_count, + allowCount: u.allow_count, + denyCount: u.deny_count, + effectiveCount: u.effective_count, + })), + }; +} + +export type UserPermissionItemDto = { + key: string; + description: string | null; + category: string | null; + inherited: boolean; + directAllow: boolean; + directDeny: boolean; + effective: boolean; + sources: string[]; +}; + +export async function getAdminUser(userId: string): Promise<{ + user: AdminStaffUserDto; + permissions: UserPermissionItemDto[]; + categories: Record; +} | null> { + const user = await userRepository.getForAdmin(userId); + if (!user) return null; + const [roles, inherited, overrides, breakdown, names] = await Promise.all([ + roleRepository.getUserRoleNames(userId), + roleRepository.getUserInheritedPermissionKeys(userId), + roleRepository.getUserPermissionOverrides(userId), + roleRepository.getUserPermissionBreakdown(userId), + roleRepository.getUserNameFields(userId), + ]); + const allow = overrides.filter((o) => o.effect === 'allow'); + const deny = overrides.filter((o) => o.effect === 'deny'); + const items: UserPermissionItemDto[] = breakdown.map((p) => ({ + key: p.key, + description: p.description, + category: p.category, + inherited: p.inherited, + directAllow: p.directAllow, + directDeny: p.directDeny, + effective: (p.inherited || p.directAllow) && !p.directDeny, + sources: p.sources, + })); + const categories: Record = {}; + for (const item of items) { + const cat = item.category ?? 'other'; + if (!categories[cat]) categories[cat] = []; + categories[cat].push(item); + } + return { + user: { + id: user.id, + email: decryptEmail(user.email_encrypted), + fullName: fullName(names?.first_name ?? null, names?.last_name ?? null), + isEnabled: user.is_enabled, + roles, + inheritedCount: inherited.length, + allowCount: allow.length, + denyCount: deny.length, + effectiveCount: items.filter((p) => p.effective).length, + }, + permissions: items, + categories, + }; +} + +export async function applyUserPermissionChanges( + userId: string, + changes: Array<{ key: string; action: 'allow' | 'deny' | 'reset' }>, + actorUserId: string +): Promise<{ + user: AdminStaffUserDto; + permissions: UserPermissionItemDto[]; + categories: Record; +}> { + if (!changes.length) throw new Error('At least one permission change is required'); + await assertAdministrativeUser(userId); + const catalogKeys = new Set(PERMISSION_CATALOG.map((p) => p.key)); + + for (const change of changes) { + if (!catalogKeys.has(change.key)) { + throw new Error(`Unknown permission: ${change.key}`); + } + } + + await roleRepository.applyUserPermissionOverrideChanges(userId, changes, actorUserId); + await bumpUserTokenOnRoleChange(userId); + + for (const change of changes) { + const action = + change.action === 'allow' + ? 'admin_user_permission_override_added' + : change.action === 'deny' + ? 'admin_user_permission_override_removed' + : 'admin_user_permission_override_reset'; + await auditLogRepository.create({ + userId: actorUserId, + action, + resourceType: 'user', + resourceId: userId, + metadata: { permissionKey: change.key, effect: change.action }, + }); + } + + const updated = await getAdminUser(userId); + if (!updated) throw new Error('User not found'); + return updated; +} diff --git a/backend/src/services/settingsService.ts b/backend/src/services/settingsService.ts index 5b5a31d5..6c8fb88e 100644 --- a/backend/src/services/settingsService.ts +++ b/backend/src/services/settingsService.ts @@ -127,6 +127,20 @@ function validateUpdates(updates: Partial): void { } + if (updates.engine_audit_log_retention_days !== undefined) { + + updates.engine_audit_log_retention_days = clampInt( + + updates.engine_audit_log_retention_days, + + 0, + + 365 + + ); + + } + if (updates.withdrawal_network_fee_usdt_micro !== undefined) { updates.withdrawal_network_fee_usdt_micro = clampInt( @@ -309,6 +323,12 @@ export function parseSettingsUpdates(body: Record): Partial { + test('adds individual allows on top of inherited role permissions', () => { + const effective = mergePermissionSets( + ['admin.users.view', 'admin.reports.view'], + ['admin.treasury.view'], + [] + ); + assert.deepEqual(effective, ['admin.reports.view', 'admin.treasury.view', 'admin.users.view']); + }); + + test('individual deny removes an inherited permission without affecting others', () => { + const effective = mergePermissionSets( + ['admin.users.view', 'admin.users.edit', 'admin.users.delete'], + [], + ['admin.users.delete'] + ); + assert.deepEqual(effective, ['admin.users.edit', 'admin.users.view']); + }); + + test('deny wins over a matching direct allow', () => { + const effective = mergePermissionSets( + ['admin.users.view'], + ['admin.users.delete'], + ['admin.users.delete'] + ); + assert.deepEqual(effective, ['admin.users.view']); + }); + + test('reset is represented by omitting the key from allow and deny', () => { + const inherited = ['admin.users.view', 'admin.reports.view']; + const afterDeny = mergePermissionSets(inherited, [], ['admin.reports.view']); + assert.deepEqual(afterDeny, ['admin.users.view']); + const afterReset = mergePermissionSets(inherited, [], []); + assert.deepEqual(afterReset, inherited.slice().sort()); + }); +}); diff --git a/backend/src/validation/querySchemas.ts b/backend/src/validation/querySchemas.ts index a6472671..43458ad8 100644 --- a/backend/src/validation/querySchemas.ts +++ b/backend/src/validation/querySchemas.ts @@ -101,6 +101,7 @@ export const paginationQuerySchema = z.object({ export const auditLogQuerySchema = paginationQuerySchema.extend({ action: z.string().trim().max(128).optional(), actions: commaActionsQuery, + excludeActions: commaActionsQuery, userId: optionalUuidQuery, from: optionalIsoDateQuery, to: optionalIsoDateQuery, diff --git a/prediqo_web/src/app/router/router.tsx b/prediqo_web/src/app/router/router.tsx index 7b0a6d21..ef7a1af2 100644 --- a/prediqo_web/src/app/router/router.tsx +++ b/prediqo_web/src/app/router/router.tsx @@ -38,6 +38,8 @@ import { FaqPublicPage } from '../../features/faq/FaqPublicPage'; import { FaqPage } from '../../features/faq/FaqPage'; import { FaqAdminPage } from '../../features/faq/FaqAdminPage'; import { RoleManagementPage } from '../../features/rbac/RoleManagementPage'; +import { AdminUsersPage } from '../../features/rbac/AdminUsersPage'; +import { AdminUserPermissionsPage } from '../../features/rbac/AdminUserPermissionsPage'; import { GamePlayRoute } from '../../features/games/GamePlayRoute'; /** Browser router instance with login, dashboard, options, and admin route trees. */ @@ -116,6 +118,8 @@ export const router = createBrowserRouter([ { path: 'admin/countries', element: }, { path: 'admin/network', element: }, { path: 'admin/rbac', element: }, + { path: 'admin/admin-users', element: }, + { path: 'admin/admin-users/:userId/permissions', element: }, ], }, ], diff --git a/prediqo_web/src/app/theme/theme.ts b/prediqo_web/src/app/theme/theme.ts index fea43f48..8c73acd9 100644 --- a/prediqo_web/src/app/theme/theme.ts +++ b/prediqo_web/src/app/theme/theme.ts @@ -6,6 +6,10 @@ import { createTheme, type ThemeOptions } from '@mui/material/styles'; import { enUS, frFR } from '@mui/material/locale'; import { normalizeLocale } from '../../shared/i18n'; +const SURFACE_BORDER = '1px solid rgba(255,255,255,0.12)'; +const SURFACE_BG = '#1B2438'; +const NESTED_SURFACE_BG = 'rgba(255,255,255,0.045)'; + const baseThemeOptions: ThemeOptions = { palette: { mode: 'dark', @@ -13,10 +17,10 @@ const baseThemeOptions: ThemeOptions = { secondary: { main: '#7C5CFF' }, // bonus / accent purple background: { default: '#0B0F1A', - paper: '#12182B', + paper: SURFACE_BG, }, }, - shape: { borderRadius: 14 }, + shape: { borderRadius: 8 }, typography: { fontFamily: [ 'system-ui', @@ -28,16 +32,73 @@ const baseThemeOptions: ThemeOptions = { ].join(','), }, components: { + MuiPaper: { + styleOverrides: { + root: { + backgroundImage: 'none', + backgroundColor: SURFACE_BG, + borderRadius: 12, + '&:not(.MuiDrawer-paper):not(.MuiAppBar-root):not(.MuiDialog-paper):not(.MuiAccordion-root):not(.MuiPopover-paper)': + { + border: SURFACE_BORDER, + }, + }, + }, + }, MuiCard: { styleOverrides: { root: { - border: '1px solid rgba(255,255,255,0.06)', + borderRadius: 12, + border: SURFACE_BORDER, + backgroundImage: 'none', + backgroundColor: SURFACE_BG, + }, + }, + }, + MuiAccordion: { + defaultProps: { disableGutters: true, elevation: 0 }, + styleOverrides: { + root: { + backgroundImage: 'none', + backgroundColor: NESTED_SURFACE_BG, + border: SURFACE_BORDER, + borderRadius: 12, + overflow: 'hidden', + '&:before': { display: 'none' }, + '&:not(:last-of-type)': { marginBottom: 8 }, + }, + }, + }, + MuiAccordionSummary: { + styleOverrides: { + root: { + minHeight: 64, + }, + }, + }, + MuiAlert: { + styleOverrides: { + root: { + border: SURFACE_BORDER, + }, + }, + }, + MuiDialog: { + styleOverrides: { + paper: { + borderRadius: 12, + border: SURFACE_BORDER, backgroundImage: 'none', }, }, }, MuiButton: { defaultProps: { disableElevation: true }, + styleOverrides: { + root: { + borderRadius: 10, + }, + }, }, }, }; diff --git a/prediqo_web/src/features/auth/VerifyEmailPage.tsx b/prediqo_web/src/features/auth/VerifyEmailPage.tsx index 4fa19550..a2a854b2 100644 --- a/prediqo_web/src/features/auth/VerifyEmailPage.tsx +++ b/prediqo_web/src/features/auth/VerifyEmailPage.tsx @@ -76,7 +76,7 @@ export function VerifyEmailPage() { width: '100%', maxWidth: 480, p: { xs: 3, sm: 4 }, - borderRadius: 4, + borderRadius: 2, border: '1px solid rgba(255,255,255,0.08)', }} > diff --git a/prediqo_web/src/features/candle-predict/CandlePredictPage.tsx b/prediqo_web/src/features/candle-predict/CandlePredictPage.tsx index 4f60a6aa..ec0c8aa6 100644 --- a/prediqo_web/src/features/candle-predict/CandlePredictPage.tsx +++ b/prediqo_web/src/features/candle-predict/CandlePredictPage.tsx @@ -608,7 +608,7 @@ export function CandlePredictPage() { {isAdmin && } - + {renderBettingPanels()} diff --git a/prediqo_web/src/features/candle-predict/components/AutoPredictionPanel.tsx b/prediqo_web/src/features/candle-predict/components/AutoPredictionPanel.tsx index ff9452a9..937ebd34 100644 --- a/prediqo_web/src/features/candle-predict/components/AutoPredictionPanel.tsx +++ b/prediqo_web/src/features/candle-predict/components/AutoPredictionPanel.tsx @@ -299,7 +299,7 @@ export function AutoPredictionPanel({ @@ -74,9 +74,9 @@ export function PoolBar({ round, poolWinnerRule }: Props) { value={longPct} sx={{ height: 8, - borderRadius: 4, + borderRadius: '4px', backgroundColor: alpha('#4CAF50', 0.15), - '& .MuiLinearProgress-bar': { backgroundColor: '#4CAF50', borderRadius: 4 }, + '& .MuiLinearProgress-bar': { backgroundColor: '#4CAF50', borderRadius: '4px' }, }} /> diff --git a/prediqo_web/src/features/candle-predict/components/RecentPredictionsPanel.tsx b/prediqo_web/src/features/candle-predict/components/RecentPredictionsPanel.tsx index 1c7f9fda..25f1b21e 100644 --- a/prediqo_web/src/features/candle-predict/components/RecentPredictionsPanel.tsx +++ b/prediqo_web/src/features/candle-predict/components/RecentPredictionsPanel.tsx @@ -425,7 +425,7 @@ export function RecentPredictionsPanel({ const cols = 'candlePredict.recentPredictions.columns'; return ( - + + diff --git a/prediqo_web/src/features/catalog/CatalogAdminPage.tsx b/prediqo_web/src/features/catalog/CatalogAdminPage.tsx index e1a15007..3f1bf0f1 100644 --- a/prediqo_web/src/features/catalog/CatalogAdminPage.tsx +++ b/prediqo_web/src/features/catalog/CatalogAdminPage.tsx @@ -266,7 +266,7 @@ export function CatalogAdminPage() { }} > {sortedGames.map((game) => ( - + {sortedAds.map((ad) => ( - + { - const res = await api.get<{ items: CountryRow[]; total: number }>('/api/v1/admin/countries'); - return res.data; - }, + queryFn: fetchAdminCountries, }); + const countryRows: CountryRow[] = adminCountryItems(q.data).map((c) => ({ + code: c.code, + name: c.name, + registrationAllowed: c.registrationAllowed !== false, + })); const syncMut = useMutation({ mutationFn: async () => { @@ -69,16 +72,15 @@ export function CountriesAdminPage() { }); const filtered = useMemo(() => { - const items = q.data?.items ?? []; const term = search.trim().toLowerCase(); - return items.filter((c) => { + return countryRows.filter((c) => { if (showBlockedOnly && c.registrationAllowed) return false; if (!term) return true; return c.name.toLowerCase().includes(term) || c.code.toLowerCase().includes(term); }); - }, [q.data?.items, search, showBlockedOnly]); + }, [countryRows, search, showBlockedOnly]); - const blockedCount = (q.data?.items ?? []).filter((c) => !c.registrationAllowed).length; + const blockedCount = countryRows.filter((c) => !c.registrationAllowed).length; return ( @@ -138,13 +140,13 @@ export function CountriesAdminPage() { )} - {q.data?.total === 0 && ( + {countryRows.length === 0 && !q.isLoading && !q.isError && ( {t('admin.countries.emptyDb')} )} - + { + const res = await api.get<{ items?: AdminCountryItem[]; total?: number } | AdminCountryItem[]>( + '/api/v1/admin/countries' + ); + return normalizeAdminCountries(res.data); +} + +export function normalizeAdminCountries( + data: { items?: AdminCountryItem[]; total?: number } | AdminCountryItem[] | undefined +): AdminCountriesPayload { + if (Array.isArray(data)) { + return { items: data, total: data.length }; + } + const items = Array.isArray(data?.items) ? data.items : []; + return { items, total: typeof data?.total === 'number' ? data.total : items.length }; +} + +export function adminCountryItems( + data: AdminCountriesPayload | AdminCountryItem[] | undefined +): AdminCountryItem[] { + return normalizeAdminCountries(data).items; +} + /** Resolves ISO 3166-1 alpha-2 codes to country names (admin catalog). */ export function useCountryNames() { const q = useQuery({ queryKey: ['admin-countries'], - queryFn: async () => { - const res = await api.get<{ items: Array<{ code: string; name: string }> }>( - '/api/v1/admin/countries' - ); - return res.data.items ?? []; - }, + queryFn: fetchAdminCountries, staleTime: 5 * 60_000, }); + const items = adminCountryItems(q.data); + const nameByCode = useMemo(() => { const map = new Map(); - for (const c of q.data ?? []) { + for (const c of items) { map.set(c.code, c.name); } return map; - }, [q.data]); + }, [items]); const label = useCallback( (code: string | null | undefined) => { diff --git a/prediqo_web/src/features/dashboard/components/DashboardFiltersBar.tsx b/prediqo_web/src/features/dashboard/components/DashboardFiltersBar.tsx index b052423a..afd6f65b 100644 --- a/prediqo_web/src/features/dashboard/components/DashboardFiltersBar.tsx +++ b/prediqo_web/src/features/dashboard/components/DashboardFiltersBar.tsx @@ -52,7 +52,7 @@ export function DashboardFiltersBar({ {Array.from({ length: 6 }).map((_, i) => ( - + ))} ) : filtered.length === 0 ? ( diff --git a/prediqo_web/src/features/home/components/GameCard.tsx b/prediqo_web/src/features/home/components/GameCard.tsx index 4f95cdfd..ad402d57 100644 --- a/prediqo_web/src/features/home/components/GameCard.tsx +++ b/prediqo_web/src/features/home/components/GameCard.tsx @@ -50,7 +50,7 @@ export function GameCard({ game, onPlay }: Props) { ); } @@ -54,7 +54,7 @@ export function PromoCarousel({ ads, loading }: Props) { { const Icon = card.icon; return ( - + nav(card.path)} sx={{ height: '100%' }}> diff --git a/prediqo_web/src/features/profile/ProfilePage.tsx b/prediqo_web/src/features/profile/ProfilePage.tsx index fbdc3a62..5aaef568 100644 --- a/prediqo_web/src/features/profile/ProfilePage.tsx +++ b/prediqo_web/src/features/profile/ProfilePage.tsx @@ -80,7 +80,7 @@ export function ProfilePage() { sx={{ p: { xs: 2.5, md: 3 }, mb: 2.5, - borderRadius: 4, + borderRadius: 2, border: '1px solid rgba(214,178,94,0.25)', background: 'linear-gradient(135deg, rgba(214,178,94,0.16) 0%, rgba(124,92,255,0.1) 60%, rgba(18,23,36,0.92) 100%)', @@ -160,7 +160,7 @@ export function ProfilePage() { gridTemplateColumns: { xs: '1fr', lg: '1.4fr 1fr' }, }} > - + - + {t('profile.emailVerification')} @@ -216,7 +216,7 @@ export function ProfilePage() { - + {t('profile.referralProgram')} @@ -225,7 +225,7 @@ export function ProfilePage() { - + {t('profile.accountDetails')} @@ -270,7 +270,7 @@ export function ProfilePage() { gridTemplateColumns: { xs: '1fr', md: 'repeat(2, 1fr)' }, }} > - + {t('profile.changePassword')} @@ -282,7 +282,7 @@ export function ProfilePage() { - + {t('profile.twoFactorAuth')} @@ -305,7 +305,7 @@ export function ProfilePage() { )} {tab === 1 && ( - + diff --git a/prediqo_web/src/features/rbac/AdminUserPermissionsPage.tsx b/prediqo_web/src/features/rbac/AdminUserPermissionsPage.tsx new file mode 100644 index 00000000..15e727d0 --- /dev/null +++ b/prediqo_web/src/features/rbac/AdminUserPermissionsPage.tsx @@ -0,0 +1,290 @@ +/** + * Per-user permission exceptions: inherited, direct allow, direct deny, effective. + */ +import { + Alert, + Box, + Button, + Chip, + IconButton, + Paper, + Stack, + TextField, + ToggleButton, + ToggleButtonGroup, + Tooltip, + Typography, +} from '@mui/material'; +import ArrowBackRoundedIcon from '@mui/icons-material/ArrowBackRounded'; +import AddRoundedIcon from '@mui/icons-material/AddRounded'; +import BlockRoundedIcon from '@mui/icons-material/BlockRounded'; +import RestartAltRoundedIcon from '@mui/icons-material/RestartAltRounded'; +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; +import { useMemo, useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import { Link as RouterLink, useParams } from 'react-router-dom'; +import { api } from '../../shared/services/api'; +import { PageHeader, RefreshIconButton } from '../../shared/components/PageHeader'; +import { useAuth } from '../../shared/auth/AuthContext'; +import type { AdminStaffUser } from './AdminUsersPage'; + +type PermissionItem = { + key: string; + description: string | null; + category: string | null; + inherited: boolean; + directAllow: boolean; + directDeny: boolean; + effective: boolean; + sources: string[]; +}; + +type DetailResponse = { + user: AdminStaffUser; + permissions: PermissionItem[]; + categories: Record; +}; + +type OriginFilter = 'all' | 'inherited' | 'allow' | 'deny' | 'effective' | 'inactive'; + +export function AdminUserPermissionsPage() { + const { t } = useTranslation(); + const { userId = '' } = useParams(); + const { can } = useAuth(); + const canManage = can('admin.rbac.manage'); + const qc = useQueryClient(); + const [search, setSearch] = useState(''); + const [origin, setOrigin] = useState('all'); + const [error, setError] = useState(null); + + const detailQ = useQuery({ + queryKey: ['rbac-admin-user', userId], + enabled: !!userId, + queryFn: async () => { + const res = await api.get(`/api/v1/admin/rbac/admin-users/${userId}/permissions`); + return res.data; + }, + }); + + const mut = useMutation({ + mutationFn: async (body: { permissionKey: string; action: 'allow' | 'deny' | 'reset' }) => { + const res = await api.patch( + `/api/v1/admin/rbac/admin-users/${userId}/permissions`, + body + ); + return res.data; + }, + onSuccess: (data) => { + setError(null); + qc.setQueryData(['rbac-admin-user', userId], data); + void qc.invalidateQueries({ queryKey: ['rbac-admin-users'] }); + }, + onError: (e: unknown) => { + setError( + (e as { response?: { data?: { error?: string } } })?.response?.data?.error ?? + t('admin.rbac.userPermissions.saveFailed') + ); + }, + }); + + const user = detailQ.data?.user; + const categories = useMemo(() => { + const q = search.trim().toLowerCase(); + const raw = detailQ.data?.categories; + const grouped = raw && !Array.isArray(raw) ? raw : {}; + return Object.entries(grouped) + .map(([cat, items]) => ({ + cat, + items: (Array.isArray(items) ? items : []).filter((p) => { + if (q && !p.key.toLowerCase().includes(q) && !(p.description ?? '').toLowerCase().includes(q)) { + return false; + } + if (origin === 'inherited') return p.inherited; + if (origin === 'allow') return p.directAllow; + if (origin === 'deny') return p.directDeny; + if (origin === 'effective') return p.effective; + if (origin === 'inactive') return !p.effective; + return true; + }), + })) + .filter((g) => g.items.length > 0); + }, [detailQ.data?.categories, search, origin]); + + return ( + + + + + } + title={user?.fullName || user?.email || t('admin.rbac.userPermissions.title')} + subtitle={t('admin.rbac.userPermissions.subtitle')} + actions={ void detailQ.refetch()} disabled={detailQ.isFetching} />} + /> + + {detailQ.isError && ( + + {t('admin.rbac.userPermissions.loadFailed')} + + )} + {error && ( + setError(null)}> + {error} + + )} + + {user && ( + + + + {user.email} + + + {(Array.isArray(user.roles) ? user.roles : []).map((r) => ( + + ))} + + + + + + + + + + )} + + + setSearch(e.target.value)} + /> + v && setOrigin(v)} + sx={{ flexWrap: 'wrap' }} + > + {t('common.all')} + {t('admin.rbac.userPermissions.filterInherited')} + {t('admin.rbac.userPermissions.filterAllow')} + {t('admin.rbac.userPermissions.filterDeny')} + {t('admin.rbac.userPermissions.filterEffective')} + {t('admin.rbac.userPermissions.filterInactive')} + + + + + {categories.map(({ cat, items }) => ( + + + {t(`admin.rbac.categories.${cat}`, { defaultValue: cat.replace(/_/g, ' ') })} + + + {items.map((p) => ( + + + + {p.key} + + {p.description && ( + + {p.description} + + )} + + {p.inherited && ( + + )} + {p.directAllow && ( + + )} + {p.directDeny && ( + + )} + + {p.sources.map((s) => ( + + ))} + + + {canManage && ( + + + + + + + + + + + + + + + + + + )} + + ))} + + + ))} + {detailQ.isSuccess && categories.length === 0 && ( + {t('admin.rbac.userPermissions.empty')} + )} + + + ); +} diff --git a/prediqo_web/src/features/rbac/AdminUsersPage.tsx b/prediqo_web/src/features/rbac/AdminUsersPage.tsx new file mode 100644 index 00000000..466d268c --- /dev/null +++ b/prediqo_web/src/features/rbac/AdminUsersPage.tsx @@ -0,0 +1,230 @@ +/** + * Dedicated list of administrative users (staff roles and permission exceptions). + */ +import { + Alert, + Box, + Button, + Chip, + FormControl, + InputLabel, + MenuItem, + Pagination, + Paper, + Select, + Stack, + TextField, + Typography, +} from '@mui/material'; +import ManageAccountsRoundedIcon from '@mui/icons-material/ManageAccountsRounded'; +import { useQuery } from '@tanstack/react-query'; +import { useEffect, useMemo, useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import { Link as RouterLink, useSearchParams } from 'react-router-dom'; +import { api } from '../../shared/services/api'; +import { PageHeader, RefreshIconButton } from '../../shared/components/PageHeader'; +import { PermissionGate } from '../../shared/auth/PermissionGate'; + +export type AdminStaffUser = { + id: string; + email: string | null; + fullName: string | null; + isEnabled: boolean; + roles: string[]; + inheritedCount: number; + allowCount: number; + denyCount: number; + effectiveCount: number; +}; + +type ExceptionFilter = 'all' | 'any' | 'allow' | 'deny' | 'none'; + +const PAGE_SIZE = 25; + +function asArray(value: T[] | undefined | null): T[] { + return Array.isArray(value) ? value : []; +} + +export function AdminUsersPage() { + const { t } = useTranslation(); + const [searchParams, setSearchParams] = useSearchParams(); + const [search, setSearch] = useState(searchParams.get('search') ?? ''); + const [debounced, setDebounced] = useState(search); + const role = searchParams.get('role') ?? ''; + const exception = (searchParams.get('exception') as ExceptionFilter | null) ?? 'all'; + const permission = searchParams.get('permission') ?? ''; + const page = Math.max(1, parseInt(searchParams.get('page') ?? '1', 10) || 1); + + useEffect(() => { + const timer = window.setTimeout(() => setDebounced(search.trim()), 350); + return () => window.clearTimeout(timer); + }, [search]); + + const rolesQ = useQuery({ + queryKey: ['rbac-roles'], + queryFn: async () => { + const res = await api.get<{ roles?: Array<{ name: string }> } | Array<{ name: string }>>( + '/api/v1/admin/rbac/roles' + ); + const payload = res.data; + return Array.isArray(payload) ? payload : asArray(payload?.roles); + }, + staleTime: 60_000, + }); + + const staffQ = useQuery({ + queryKey: ['rbac-admin-users', debounced, role, exception, permission, page], + queryFn: async () => { + const res = await api.get<{ users: AdminStaffUser[]; total: number }>('/api/v1/admin/rbac/admin-users', { + params: { + search: debounced || undefined, + role: role || undefined, + exception: exception !== 'all' ? exception : undefined, + permission: permission || undefined, + limit: PAGE_SIZE, + offset: (page - 1) * PAGE_SIZE, + }, + }); + return res.data; + }, + }); + + const roleOptions = useMemo( + () => asArray(rolesQ.data).filter((r) => r.name !== 'user').map((r) => r.name), + [rolesQ.data] + ); + + const totalPages = Math.max(1, Math.ceil((staffQ.data?.total ?? 0) / PAGE_SIZE)); + + function updateParam(key: string, value: string) { + const next = new URLSearchParams(searchParams); + if (value) next.set(key, value); + else next.delete(key); + if (key !== 'page') next.delete('page'); + setSearchParams(next); + } + + return ( + + void staffQ.refetch()} disabled={staffQ.isFetching} />} + /> + + {staffQ.isError && ( + + {t('admin.rbac.adminUsers.loadFailed')} + + )} + + + + setSearch(e.target.value)} + onBlur={() => setDebounced(search.trim())} + onKeyDown={(e) => { + if (e.key === 'Enter') setDebounced(search.trim()); + }} + sx={{ minWidth: 240, flex: 1 }} + /> + + {t('admin.rbac.adminUsers.roleFilter')} + + + + {t('admin.rbac.adminUsers.exceptionFilter')} + + + updateParam('permission', e.target.value.trim())} + sx={{ minWidth: 220 }} + /> + + + + + {asArray(staffQ.data?.users).map((user) => ( + + + + {user.fullName || user.email || user.id.slice(0, 8)} + {user.email && user.fullName && ( + + {user.email} + + )} + + {asArray(user.roles).map((r) => ( + + ))} + {!user.isEnabled && } + + + + + + + + + + + + + + ))} + {!staffQ.isLoading && asArray(staffQ.data?.users).length === 0 && ( + {t('admin.rbac.adminUsers.empty')} + )} + + + {totalPages > 1 && ( + updateParam('page', p === 1 ? '' : String(p))} + /> + )} + + ); +} diff --git a/prediqo_web/src/features/rbac/RoleManagementPage.tsx b/prediqo_web/src/features/rbac/RoleManagementPage.tsx index fea47bac..ea0912ae 100644 --- a/prediqo_web/src/features/rbac/RoleManagementPage.tsx +++ b/prediqo_web/src/features/rbac/RoleManagementPage.tsx @@ -25,6 +25,7 @@ import LockRoundedIcon from '@mui/icons-material/LockRounded'; import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; import { useMemo, useState } from 'react'; import { useTranslation } from 'react-i18next'; +import { Link as RouterLink } from 'react-router-dom'; import { api } from '../../shared/services/api'; import { PageHeader, RefreshIconButton } from '../../shared/components/PageHeader'; import { PermissionGate } from '../../shared/auth/PermissionGate'; @@ -63,8 +64,9 @@ export function RoleManagementPage() { const rolesQ = useQuery({ queryKey: ['rbac-roles'], queryFn: async () => { - const res = await api.get<{ roles: RoleDto[] }>('/api/v1/admin/rbac/roles'); - return res.data.roles; + const res = await api.get<{ roles?: RoleDto[] } | RoleDto[]>('/api/v1/admin/rbac/roles'); + const payload = res.data; + return Array.isArray(payload) ? payload : payload?.roles ?? []; }, }); @@ -76,19 +78,33 @@ export function RoleManagementPage() { }, }); - const categories = useMemo(() => permsQ.data ?? {}, [permsQ.data]); + const categories = useMemo(() => { + const raw = permsQ.data as unknown; + if (!raw || Array.isArray(raw) || typeof raw !== 'object') return {}; + const maybeWrapped = raw as { categories?: Record }; + if (maybeWrapped.categories && typeof maybeWrapped.categories === 'object' && !Array.isArray(maybeWrapped.categories)) { + return maybeWrapped.categories; + } + return raw as Record; + }, [permsQ.data]); const saveMut = useMutation({ mutationFn: async () => { - const body = { - name: name.trim(), + const body: { + name?: string; + description?: string; + permissionKeys: string[]; + } = { description: description.trim() || undefined, permissionKeys: [...selected], }; + if (!editing?.isSystem) { + body.name = name.trim(); + } if (editing) { await api.patch(`/api/v1/admin/rbac/roles/${editing.id}`, body); } else { - await api.post('/api/v1/admin/rbac/roles', body); + await api.post('/api/v1/admin/rbac/roles', { ...body, name: name.trim() }); } }, onSuccess: async () => { @@ -160,6 +176,9 @@ export function RoleManagementPage() { actions={ <> rolesQ.refetch()} disabled={rolesQ.isFetching} /> +