After finalise with the internationarization of web part2
This commit is contained in:
parent
067e412bde
commit
2af8daacec
20
.cursor/rules/admin-super-admin-access.mdc
Normal file
20
.cursor/rules/admin-super-admin-access.mdc
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
---
|
||||||
|
description: Super administrators inherit all administrator page and API access
|
||||||
|
globs: backend/src/**/*.ts,prediqo_web/src/shared/auth/**/*.ts,prediqo_web/src/app/router/**/*.tsx,prediqo_mobile/lib/features/auth/**/*.dart
|
||||||
|
alwaysApply: false
|
||||||
|
---
|
||||||
|
|
||||||
|
# Admin access — super_admin parity
|
||||||
|
|
||||||
|
`super_admin` must have access to **every** page and API route available to `admin`.
|
||||||
|
|
||||||
|
## Rules
|
||||||
|
|
||||||
|
- Use `hasAdminAccess()` (`backend/src/utils/roleAccess.ts` or `prediqo_web/src/shared/auth/roleAccess.ts`) instead of `role === 'admin'`.
|
||||||
|
- Route guards: `requireRoles('admin')` already treats `super_admin` as admin; do not duplicate stricter checks downstream.
|
||||||
|
- Staff tools (support, FAQ admin): include `super_admin` in staff role checks (`hasStaffAccess` / `isStaffRole`).
|
||||||
|
- UI: derive visibility from `isAdmin` (web) or `isAdmin` getter (mobile), never from `role == 'admin'` alone.
|
||||||
|
|
||||||
|
## JWT note
|
||||||
|
|
||||||
|
`primaryRole` for users with both roles is `super_admin`. Code that only checks `req.user.role === 'admin'` will wrongly deny super admins.
|
||||||
30
.cursor/rules/platform-setup-referral.mdc
Normal file
30
.cursor/rules/platform-setup-referral.mdc
Normal file
@ -0,0 +1,30 @@
|
|||||||
|
---
|
||||||
|
description: Referral network bootstrap during initial platform setup (super admin root)
|
||||||
|
globs: backend/src/services/setupService.ts,backend/src/services/referralService.ts,backend/src/services/authService.ts,prediqo_web/src/features/auth/SetupPage.tsx
|
||||||
|
alwaysApply: false
|
||||||
|
---
|
||||||
|
|
||||||
|
# Platform setup — referral root
|
||||||
|
|
||||||
|
When the first Super Administrator is created during initial deployment (`setupService.createFirstAdmin` or `promoteExistingUserToAdmin`):
|
||||||
|
|
||||||
|
1. **Assign a unique referral code** to that account (same generator as standard users: `referralRepository.ensureUserReferralCode`).
|
||||||
|
2. **Set `referral_program_settings.default_referrer_user_id`** to the super admin's user id (`referralService.bootstrapReferralRootAtPlatformSetup`).
|
||||||
|
|
||||||
|
The super admin is the **root of the referral network**.
|
||||||
|
|
||||||
|
## Registration behaviour (`authService.register`)
|
||||||
|
|
||||||
|
- User provides a **valid** referral code → that referrer is used (`referralService.resolveReferrerId`).
|
||||||
|
- User provides **no** code (or empty) → `default_referrer_user_id` (super admin) is used.
|
||||||
|
- Invalid codes fall back to the default referrer (existing behaviour).
|
||||||
|
|
||||||
|
## Eligibility
|
||||||
|
|
||||||
|
The default referrer (platform root) may act as referrer **without** a completed deposit, even when `referrer_must_have_deposited` is enabled (`assertReferrerEligible` exemption).
|
||||||
|
|
||||||
|
## Do not break
|
||||||
|
|
||||||
|
- Do not skip referral bootstrap on first-admin setup paths.
|
||||||
|
- Do not clear `default_referrer_user_id` when promoting later admins (only the **first** setup sets the root).
|
||||||
|
- Setup API responses should include `referralCode` for operator visibility.
|
||||||
11
README.md
11
README.md
@ -146,7 +146,7 @@ To enable withdrawals, insert a hot wallet per asset (e.g. via script or admin):
|
|||||||
|
|
||||||
## Docker deployment (VPS)
|
## Docker deployment (VPS)
|
||||||
|
|
||||||
**Guide complet (français) :** [docs/DEPLOY-VPS.md](docs/DEPLOY-VPS.md)
|
**Guide complet (français) :** [docs/DEPLOY-VPS.md](docs/DEPLOY-VPS.md) — **section 4** : démarrage sur base vierge (VPS et local).
|
||||||
|
|
||||||
Résumé — depuis la racine du dépôt :
|
Résumé — depuis la racine du dépôt :
|
||||||
|
|
||||||
@ -163,6 +163,15 @@ npm run phase-b:up:https # build + démarrage
|
|||||||
|
|
||||||
Commandes : `npm run phase-b:status` · `phase-b:logs` · `phase-b:restart` · `phase-b:down`
|
Commandes : `npm run phase-b:status` · `phase-b:logs` · `phase-b:restart` · `phase-b:down`
|
||||||
|
|
||||||
|
### Docker local (base vierge)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cp .env.docker.example .env.docker
|
||||||
|
# Éditer secrets + INITIAL_SETUP_TOKEN ; créer la base PostgreSQL locale
|
||||||
|
npm run docker:local:init
|
||||||
|
# Setup : http://localhost:9080/setup
|
||||||
|
```
|
||||||
|
|
||||||
### Run with Docker Compose (legacy / local)
|
### Run with Docker Compose (legacy / local)
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
|||||||
@ -1,6 +1,7 @@
|
|||||||
import { Response } from 'express';
|
import { Response } from 'express';
|
||||||
|
|
||||||
import { AuthRequest } from '../middleware/auth';
|
import { AuthRequest } from '../middleware/auth';
|
||||||
|
import { hasAdminAccess } from '../utils/roleAccess';
|
||||||
|
|
||||||
import * as candlePredictService from '../services/candlePredictService';
|
import * as candlePredictService from '../services/candlePredictService';
|
||||||
import { parseStakeAmountFromBody } from '../utils/stakeAmountValidation';
|
import { parseStakeAmountFromBody } from '../utils/stakeAmountValidation';
|
||||||
@ -26,7 +27,7 @@ export async function getState(req: AuthRequest, res: Response): Promise<void> {
|
|||||||
|
|
||||||
const intervalMinutes = parseIntervalMinutes(req.query.intervalMinutes);
|
const intervalMinutes = parseIntervalMinutes(req.query.intervalMinutes);
|
||||||
|
|
||||||
const includeInternal = req.user?.role === 'admin';
|
const includeInternal = req.user ? hasAdminAccess(req.user) : false;
|
||||||
|
|
||||||
const state = await candlePredictService.getGameState(req.user?.userId, intervalMinutes, {
|
const state = await candlePredictService.getGameState(req.user?.userId, intervalMinutes, {
|
||||||
includeInternal,
|
includeInternal,
|
||||||
@ -72,7 +73,7 @@ export async function getCandles(req: AuthRequest, res: Response): Promise<void>
|
|||||||
|
|
||||||
beforeOpenMs,
|
beforeOpenMs,
|
||||||
|
|
||||||
includeInternal: req.user?.role === 'admin',
|
includeInternal: req.user ? hasAdminAccess(req.user) : false,
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@ -15,6 +15,7 @@ function buildCtx(req: AuthRequest): GameRequestContext {
|
|||||||
return {
|
return {
|
||||||
userId: req.user?.userId,
|
userId: req.user?.userId,
|
||||||
role: req.user?.role,
|
role: req.user?.role,
|
||||||
|
roles: req.user?.roles,
|
||||||
query: req.query as Record<string, unknown>,
|
query: req.query as Record<string, unknown>,
|
||||||
body: (req.body ?? {}) as Record<string, unknown>,
|
body: (req.body ?? {}) as Record<string, unknown>,
|
||||||
params: req.params as Record<string, string>,
|
params: req.params as Record<string, string>,
|
||||||
|
|||||||
@ -1,6 +1,7 @@
|
|||||||
import * as candlePredictService from '../../../services/candlePredictService';
|
import * as candlePredictService from '../../../services/candlePredictService';
|
||||||
import { parseStakeAmountFromBody } from '../../../utils/stakeAmountValidation';
|
import { parseStakeAmountFromBody } from '../../../utils/stakeAmountValidation';
|
||||||
import { UnsupportedGameActionError } from '../../errors';
|
import { UnsupportedGameActionError } from '../../errors';
|
||||||
|
import { hasAdminAccess } from '../../../utils/roleAccess';
|
||||||
import type { GameModule } from '../../types';
|
import type { GameModule } from '../../types';
|
||||||
|
|
||||||
function parseIntervalMinutes(value: unknown): number | undefined {
|
function parseIntervalMinutes(value: unknown): number | undefined {
|
||||||
@ -32,9 +33,9 @@ export const candlePredictModule: GameModule = {
|
|||||||
|
|
||||||
startEngine: () => candlePredictService.startCandlePredictEngine(),
|
startEngine: () => candlePredictService.startCandlePredictEngine(),
|
||||||
|
|
||||||
getState: ({ userId, query, role }) =>
|
getState: ({ userId, query, role, roles }) =>
|
||||||
candlePredictService.getGameState(userId, parseIntervalMinutes(query.intervalMinutes), {
|
candlePredictService.getGameState(userId, parseIntervalMinutes(query.intervalMinutes), {
|
||||||
includeInternal: role === 'admin',
|
includeInternal: hasAdminAccess({ role, roles }),
|
||||||
}),
|
}),
|
||||||
|
|
||||||
placeBet: ({ userId, body }) => {
|
placeBet: ({ userId, body }) => {
|
||||||
@ -95,7 +96,7 @@ export const candlePredictModule: GameModule = {
|
|||||||
limit: limit > 0 ? limit : undefined,
|
limit: limit > 0 ? limit : undefined,
|
||||||
intervalMinutes: parseIntervalMinutes(ctx.query.intervalMinutes),
|
intervalMinutes: parseIntervalMinutes(ctx.query.intervalMinutes),
|
||||||
beforeOpenMs,
|
beforeOpenMs,
|
||||||
includeInternal: ctx.role === 'admin',
|
includeInternal: hasAdminAccess(ctx),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
throw new UnsupportedGameActionError(action);
|
throw new UnsupportedGameActionError(action);
|
||||||
|
|||||||
@ -3,6 +3,8 @@
|
|||||||
* Each prediction game implements GameModule and registers at startup.
|
* Each prediction game implements GameModule and registers at startup.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
import type { RoleName } from '../models';
|
||||||
|
|
||||||
export type GameImplementationKey = 'candle-predict';
|
export type GameImplementationKey = 'candle-predict';
|
||||||
|
|
||||||
/** Actions exposed via the generic game API (subset shared across games). */
|
/** Actions exposed via the generic game API (subset shared across games). */
|
||||||
@ -25,7 +27,8 @@ export type GameCapabilities = {
|
|||||||
|
|
||||||
export type GameRequestContext = {
|
export type GameRequestContext = {
|
||||||
userId?: string;
|
userId?: string;
|
||||||
role?: string;
|
role?: RoleName;
|
||||||
|
roles?: RoleName[];
|
||||||
query: Record<string, unknown>;
|
query: Record<string, unknown>;
|
||||||
body: Record<string, unknown>;
|
body: Record<string, unknown>;
|
||||||
params: Record<string, string>;
|
params: Record<string, string>;
|
||||||
|
|||||||
@ -9,6 +9,7 @@ import { verifyToken } from '../services/authService';
|
|||||||
import { touchAppPresence } from '../realtime/redis/onlinePresence';
|
import { touchAppPresence } from '../realtime/redis/onlinePresence';
|
||||||
import { JwtPayload } from '../types';
|
import { JwtPayload } from '../types';
|
||||||
import type { RoleName } from '../models';
|
import type { RoleName } from '../models';
|
||||||
|
import { hasAdminAccess, hasStaffAccess, userRoleList } from '../utils/roleAccess';
|
||||||
|
|
||||||
/** Express request extended with the authenticated user's JWT payload. */
|
/** Express request extended with the authenticated user's JWT payload. */
|
||||||
export interface AuthRequest extends Request {
|
export interface AuthRequest extends Request {
|
||||||
@ -16,9 +17,7 @@ export interface AuthRequest extends Request {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function userRoles(user: JwtPayload): RoleName[] {
|
function userRoles(user: JwtPayload): RoleName[] {
|
||||||
if (user.roles?.length) return user.roles;
|
return userRoleList(user);
|
||||||
if (user.role) return [user.role];
|
|
||||||
return [];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function userHasAnyRole(user: JwtPayload, roles: string[]): boolean {
|
function userHasAnyRole(user: JwtPayload, roles: string[]): boolean {
|
||||||
@ -60,7 +59,11 @@ export function requireRoles(...roles: string[]) {
|
|||||||
next();
|
next();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (roles.includes('admin') && userHasAnyRole(req.user, ['super_admin'])) {
|
if (roles.includes('admin') && hasAdminAccess(req.user)) {
|
||||||
|
next();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (roles.includes('moderator') && hasStaffAccess(req.user)) {
|
||||||
next();
|
next();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -2,6 +2,7 @@ import type WebSocket from 'ws';
|
|||||||
|
|
||||||
import { getGameState, placeBet } from '../../domain/candle-predict/index';
|
import { getGameState, placeBet } from '../../domain/candle-predict/index';
|
||||||
import { config } from '../../config';
|
import { config } from '../../config';
|
||||||
|
import { hasAdminAccess } from '../../utils/roleAccess';
|
||||||
import { connectRedis, getRedisSubscriber } from '../redis/client';
|
import { connectRedis, getRedisSubscriber } from '../redis/client';
|
||||||
import { removeGamePresence, touchAppPresence, touchGamePresence } from '../redis/onlinePresence';
|
import { removeGamePresence, touchAppPresence, touchGamePresence } from '../redis/onlinePresence';
|
||||||
import { parseRealtimeEvent } from '../redis/pubsub';
|
import { parseRealtimeEvent } from '../redis/pubsub';
|
||||||
@ -122,7 +123,7 @@ export class GameWsHub {
|
|||||||
|
|
||||||
for (const client of this.clients) {
|
for (const client of this.clients) {
|
||||||
if (intervalMinutes != null && !client.intervals.has(intervalMinutes)) continue;
|
if (intervalMinutes != null && !client.intervals.has(intervalMinutes)) continue;
|
||||||
const isAdmin = client.auth?.role === 'admin';
|
const isAdmin = client.auth ? hasAdminAccess({ role: client.auth.role }) : false;
|
||||||
const round = enrichRoundPayload(baseRound, pools, isAdmin);
|
const round = enrichRoundPayload(baseRound, pools, isAdmin);
|
||||||
|
|
||||||
if (event.type === 'round.updated') {
|
if (event.type === 'round.updated') {
|
||||||
@ -205,7 +206,7 @@ export class GameWsHub {
|
|||||||
}
|
}
|
||||||
client.intervals.add(msg.intervalMinutes);
|
client.intervals.add(msg.intervalMinutes);
|
||||||
const snapshot = await getGameState(client.auth?.userId, msg.intervalMinutes, {
|
const snapshot = await getGameState(client.auth?.userId, msg.intervalMinutes, {
|
||||||
includeInternal: client.auth?.role === 'admin',
|
includeInternal: client.auth ? hasAdminAccess({ role: client.auth.role }) : false,
|
||||||
});
|
});
|
||||||
this.send(client, {
|
this.send(client, {
|
||||||
type: 'subscribed',
|
type: 'subscribed',
|
||||||
|
|||||||
@ -228,6 +228,29 @@ export async function generateUniqueReferralCode(): Promise<string> {
|
|||||||
throw new Error('Failed to generate unique referral code');
|
throw new Error('Failed to generate unique referral code');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the user's referral code, or null if none is assigned.
|
||||||
|
*/
|
||||||
|
export async function getUserReferralCode(userId: string): Promise<string | null> {
|
||||||
|
const rows = await query<{ referral_code: string | null }[]>(
|
||||||
|
'SELECT referral_code FROM users WHERE id = $1',
|
||||||
|
[userId]
|
||||||
|
);
|
||||||
|
return rows[0]?.referral_code ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ensures the user has a unique referral code, generating one when missing.
|
||||||
|
*/
|
||||||
|
export async function ensureUserReferralCode(userId: string): Promise<string> {
|
||||||
|
const existing = await getUserReferralCode(userId);
|
||||||
|
if (existing) return existing;
|
||||||
|
|
||||||
|
const code = await generateUniqueReferralCode();
|
||||||
|
await query('UPDATE users SET referral_code = $1, updated_at = NOW() WHERE id = $2', [code, userId]);
|
||||||
|
return code;
|
||||||
|
}
|
||||||
|
|
||||||
export async function recordCommissionPayout(input: {
|
export async function recordCommissionPayout(input: {
|
||||||
beneficiaryUserId: string;
|
beneficiaryUserId: string;
|
||||||
referredUserId: string;
|
referredUserId: string;
|
||||||
|
|||||||
@ -23,6 +23,7 @@ import { SystemSettings } from '../models';
|
|||||||
import { parseUserGender, type UserGender } from '../models/userGender';
|
import { parseUserGender, type UserGender } from '../models/userGender';
|
||||||
import { JwtPayload, RoleName } from '../types';
|
import { JwtPayload, RoleName } from '../types';
|
||||||
import * as roleRepository from '../repositories/roleRepository';
|
import * as roleRepository from '../repositories/roleRepository';
|
||||||
|
import { hasAdminAccess } from '../utils/roleAccess';
|
||||||
import { v4 as uuidv4 } from 'uuid';
|
import { v4 as uuidv4 } from 'uuid';
|
||||||
|
|
||||||
authenticator.options = { digits: 6, step: 30 };
|
authenticator.options = { digits: 6, step: 30 };
|
||||||
@ -529,7 +530,7 @@ export function requireRole(allowed: RoleName[]): (payload: JwtPayload) => void
|
|||||||
const roles = payload.roles ?? (payload.role ? [payload.role] : []);
|
const roles = payload.roles ?? (payload.role ? [payload.role] : []);
|
||||||
const ok =
|
const ok =
|
||||||
allowed.some((r) => roles.includes(r)) ||
|
allowed.some((r) => roles.includes(r)) ||
|
||||||
(allowed.includes('admin') && roles.includes('super_admin'));
|
(allowed.includes('admin') && hasAdminAccess(payload));
|
||||||
if (!ok) throw new Error('Forbidden');
|
if (!ok) throw new Error('Forbidden');
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@ -104,6 +104,16 @@ export async function resolveReferrerId(referralCode?: string | null): Promise<s
|
|||||||
return settings.default_referrer_user_id;
|
return settings.default_referrer_user_id;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bootstraps the referral network root during initial platform setup.
|
||||||
|
* Assigns a unique referral code to the super admin and sets them as the default referrer.
|
||||||
|
*/
|
||||||
|
export async function bootstrapReferralRootAtPlatformSetup(superAdminUserId: string): Promise<string> {
|
||||||
|
const referralCode = await referralRepository.ensureUserReferralCode(superAdminUserId);
|
||||||
|
await referralRepository.updateSettings({ defaultReferrerUserId: superAdminUserId });
|
||||||
|
return referralCode;
|
||||||
|
}
|
||||||
|
|
||||||
export async function assertReferrerEligible(referrerId: string): Promise<void> {
|
export async function assertReferrerEligible(referrerId: string): Promise<void> {
|
||||||
const settings = await referralRepository.getSettings();
|
const settings = await referralRepository.getSettings();
|
||||||
const referrer = await userRepository.findById(referrerId);
|
const referrer = await userRepository.findById(referrerId);
|
||||||
@ -117,8 +127,11 @@ export async function assertReferrerEligible(referrerId: string): Promise<void>
|
|||||||
throw new ReferralError('Referrer must have a verified email');
|
throw new ReferralError('Referrer must have a verified email');
|
||||||
}
|
}
|
||||||
if (settings.referrer_must_have_deposited) {
|
if (settings.referrer_must_have_deposited) {
|
||||||
|
const isDefaultRoot = settings.default_referrer_user_id === referrerId;
|
||||||
const hasDeposit = await referralRepository.beneficiaryHasCompletedDeposit(referrerId);
|
const hasDeposit = await referralRepository.beneficiaryHasCompletedDeposit(referrerId);
|
||||||
if (!hasDeposit) throw new ReferralError('Referrer must have completed at least one deposit');
|
if (!hasDeposit && !isDefaultRoot) {
|
||||||
|
throw new ReferralError('Referrer must have completed at least one deposit');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
await assertReferralChainHasNoLoop(referrerId);
|
await assertReferralChainHasNoLoop(referrerId);
|
||||||
|
|||||||
@ -8,6 +8,7 @@ import { config } from '../config';
|
|||||||
import * as userRepository from '../repositories/userRepository';
|
import * as userRepository from '../repositories/userRepository';
|
||||||
import * as roleRepository from '../repositories/roleRepository';
|
import * as roleRepository from '../repositories/roleRepository';
|
||||||
import * as auditLogRepository from '../repositories/auditLogRepository';
|
import * as auditLogRepository from '../repositories/auditLogRepository';
|
||||||
|
import * as referralService from './referralService';
|
||||||
import { hashForIndex, encrypt } from '../utils/crypto';
|
import { hashForIndex, encrypt } from '../utils/crypto';
|
||||||
|
|
||||||
export type SetupStatus = {
|
export type SetupStatus = {
|
||||||
@ -53,7 +54,7 @@ export async function createFirstAdmin(input: {
|
|||||||
password: string;
|
password: string;
|
||||||
fullName: string;
|
fullName: string;
|
||||||
setupToken: string;
|
setupToken: string;
|
||||||
}): Promise<{ userId: string; message: string }> {
|
}): Promise<{ userId: string; referralCode: string; message: string }> {
|
||||||
await ensureNoAdminYet();
|
await ensureNoAdminYet();
|
||||||
assertSetupToken(input.setupToken.trim());
|
assertSetupToken(input.setupToken.trim());
|
||||||
|
|
||||||
@ -89,16 +90,19 @@ export async function createFirstAdmin(input: {
|
|||||||
await userRepository.setEmailVerified(user.id, true);
|
await userRepository.setEmailVerified(user.id, true);
|
||||||
await roleRepository.setUserRoles(user.id, ['admin', 'super_admin']);
|
await roleRepository.setUserRoles(user.id, ['admin', 'super_admin']);
|
||||||
|
|
||||||
|
const referralCode = await referralService.bootstrapReferralRootAtPlatformSetup(user.id);
|
||||||
|
|
||||||
await auditLogRepository.create({
|
await auditLogRepository.create({
|
||||||
userId: user.id,
|
userId: user.id,
|
||||||
action: 'setup_first_admin_created',
|
action: 'setup_first_admin_created',
|
||||||
resourceType: 'user',
|
resourceType: 'user',
|
||||||
resourceId: user.id,
|
resourceId: user.id,
|
||||||
metadata: { email },
|
metadata: { email, referral_code: referralCode },
|
||||||
});
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
userId: user.id,
|
userId: user.id,
|
||||||
|
referralCode,
|
||||||
message: 'Administrator account created. You can now sign in.',
|
message: 'Administrator account created. You can now sign in.',
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@ -107,7 +111,7 @@ export async function promoteExistingUserToAdmin(input: {
|
|||||||
email: string;
|
email: string;
|
||||||
setupToken: string;
|
setupToken: string;
|
||||||
role?: 'admin' | 'moderator';
|
role?: 'admin' | 'moderator';
|
||||||
}): Promise<{ userId: string; role: string; message: string }> {
|
}): Promise<{ userId: string; role: string; referralCode: string; message: string }> {
|
||||||
await ensureNoAdminYet();
|
await ensureNoAdminYet();
|
||||||
assertSetupToken(input.setupToken.trim());
|
assertSetupToken(input.setupToken.trim());
|
||||||
|
|
||||||
@ -129,17 +133,20 @@ export async function promoteExistingUserToAdmin(input: {
|
|||||||
await roleRepository.setUserRoles(user.id, ['admin', 'super_admin']);
|
await roleRepository.setUserRoles(user.id, ['admin', 'super_admin']);
|
||||||
await userRepository.setEmailVerified(user.id, true);
|
await userRepository.setEmailVerified(user.id, true);
|
||||||
|
|
||||||
|
const referralCode = await referralService.bootstrapReferralRootAtPlatformSetup(user.id);
|
||||||
|
|
||||||
await auditLogRepository.create({
|
await auditLogRepository.create({
|
||||||
userId: user.id,
|
userId: user.id,
|
||||||
action: 'setup_first_admin_promoted',
|
action: 'setup_first_admin_promoted',
|
||||||
resourceType: 'user',
|
resourceType: 'user',
|
||||||
resourceId: user.id,
|
resourceId: user.id,
|
||||||
metadata: { email, role: targetRole },
|
metadata: { email, role: targetRole, referral_code: referralCode },
|
||||||
});
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
userId: user.id,
|
userId: user.id,
|
||||||
role: targetRole,
|
role: targetRole,
|
||||||
|
referralCode,
|
||||||
message: `User promoted to ${targetRole}. They can sign in with their existing password.`,
|
message: `User promoted to ${targetRole}. They can sign in with their existing password.`,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@ -13,7 +13,7 @@ import {
|
|||||||
setTypingIndicator,
|
setTypingIndicator,
|
||||||
} from './supportRealtimeService';
|
} from './supportRealtimeService';
|
||||||
|
|
||||||
const STAFF_ROLES = new Set(['admin', 'moderator']);
|
const STAFF_ROLES = new Set(['admin', 'moderator', 'super_admin']);
|
||||||
|
|
||||||
export function isStaffRole(role: string | undefined): boolean {
|
export function isStaffRole(role: string | undefined): boolean {
|
||||||
return !!role && STAFF_ROLES.has(role);
|
return !!role && STAFF_ROLES.has(role);
|
||||||
|
|||||||
23
backend/src/tests/roleAccess.test.ts
Normal file
23
backend/src/tests/roleAccess.test.ts
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
import { describe, test } from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
|
||||||
|
import { hasAdminAccess, hasStaffAccess, userRoleList } from '../utils/roleAccess';
|
||||||
|
|
||||||
|
describe('roleAccess', () => {
|
||||||
|
test('hasAdminAccess accepts admin and super_admin', () => {
|
||||||
|
assert.equal(hasAdminAccess({ roles: ['admin'] }), true);
|
||||||
|
assert.equal(hasAdminAccess({ roles: ['super_admin'] }), true);
|
||||||
|
assert.equal(hasAdminAccess({ role: 'super_admin' }), true);
|
||||||
|
assert.equal(hasAdminAccess({ roles: ['user'] }), false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('hasStaffAccess includes moderators and admins', () => {
|
||||||
|
assert.equal(hasStaffAccess({ roles: ['moderator'] }), true);
|
||||||
|
assert.equal(hasStaffAccess({ roles: ['super_admin'] }), true);
|
||||||
|
assert.equal(hasStaffAccess({ roles: ['user'] }), false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('userRoleList falls back to legacy single role', () => {
|
||||||
|
assert.deepEqual(userRoleList({ role: 'admin', roles: [] }), ['admin']);
|
||||||
|
});
|
||||||
|
});
|
||||||
29
backend/src/utils/roleAccess.ts
Normal file
29
backend/src/utils/roleAccess.ts
Normal file
@ -0,0 +1,29 @@
|
|||||||
|
import type { RoleName } from '../models';
|
||||||
|
import type { JwtPayload } from '../types';
|
||||||
|
|
||||||
|
type RoleCarrier = Pick<JwtPayload, 'roles' | 'role'> | { roles?: RoleName[]; role?: RoleName | string };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolves the effective role list from JWT claims (supports legacy single-role tokens).
|
||||||
|
*/
|
||||||
|
export function userRoleList(user: RoleCarrier): RoleName[] {
|
||||||
|
if (user.roles?.length) return user.roles;
|
||||||
|
if (user.role) return [user.role as RoleName];
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* True when the user has platform administrator access (admin or super_admin).
|
||||||
|
*/
|
||||||
|
export function hasAdminAccess(user: RoleCarrier): boolean {
|
||||||
|
const roles = userRoleList(user);
|
||||||
|
return roles.includes('admin') || roles.includes('super_admin');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* True when the user has staff desk access (moderator, admin, or super_admin).
|
||||||
|
*/
|
||||||
|
export function hasStaffAccess(user: RoleCarrier): boolean {
|
||||||
|
const roles = userRoleList(user);
|
||||||
|
return roles.includes('moderator') || hasAdminAccess(user);
|
||||||
|
}
|
||||||
@ -2,6 +2,8 @@
|
|||||||
|
|
||||||
Ce guide décrit comment lancer Prediqo sur un serveur Linux (VPS) **sans perturber** les autres applications (ports dédiés **9080** / **9443**).
|
Ce guide décrit comment lancer Prediqo sur un serveur Linux (VPS) **sans perturber** les autres applications (ports dédiés **9080** / **9443**).
|
||||||
|
|
||||||
|
**Démarrage sur base vierge (VPS + local) :** voir la [section 4](#4-démarrage-sur-base-de-données-vierge-vps-et-local).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 1. Prérequis sur le VPS
|
## 1. Prérequis sur le VPS
|
||||||
@ -185,7 +187,167 @@ error: database "crypto_wallet" does not exist
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 4. Lancer l’application
|
## 4. Démarrage sur base de données vierge (VPS et local)
|
||||||
|
|
||||||
|
Cette section regroupe les commandes à exécuter lorsque PostgreSQL est **vide** (base créée, mais **sans schéma**). L’ordre est toujours le même :
|
||||||
|
|
||||||
|
1. **Créer la base** PostgreSQL (voir section 3).
|
||||||
|
2. **Configurer** les secrets et `INITIAL_SETUP_TOKEN` dans le fichier d’environnement.
|
||||||
|
3. **Appliquer les migrations** (création des tables).
|
||||||
|
4. **Démarrer la stack** (API, frontend, Redis, workers…).
|
||||||
|
5. **Configurer la plateforme** via la page **`/setup`** (premier super administrateur).
|
||||||
|
|
||||||
|
> Les scripts `*:init` enchaînent automatiquement **migrations + démarrage** en une seule commande.
|
||||||
|
|
||||||
|
### Prérequis communs
|
||||||
|
|
||||||
|
| Étape | Détail |
|
||||||
|
|-------|--------|
|
||||||
|
| Base PostgreSQL | Base vide créée (`games_platform_db` ou `crypto_wallet` selon `.env`) |
|
||||||
|
| Jeton setup | `INITIAL_SETUP_TOKEN` — min. 16 caractères, **32+ aléatoires recommandés** |
|
||||||
|
| Fichier env | VPS → `.env` · Local Docker → `.env.docker` |
|
||||||
|
| Connexion Docker → Postgres | `DATABASE_URL` avec **`host.docker.internal`**, pas `localhost` |
|
||||||
|
|
||||||
|
Vérifier que l’API répond avant `/setup` :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -s http://127.0.0.1:9080/api/v1/setup/status
|
||||||
|
# attendu : {"needsSetup":true,"setupEnabled":true}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Sur le VPS
|
||||||
|
|
||||||
|
À la racine du projet (`games_app/`) :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cp .env.example .env
|
||||||
|
# Éditer .env : PostgreSQL, secrets, INITIAL_SETUP_TOKEN, URLs publiques
|
||||||
|
```
|
||||||
|
|
||||||
|
**Premier déploiement (base vierge) — migrations + stack :**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# HTTP (test rapide)
|
||||||
|
npm run phase-b:init
|
||||||
|
|
||||||
|
# HTTPS (production — certificat DNS requis une fois avant)
|
||||||
|
npm run ssl:dns-init
|
||||||
|
npm run phase-b:init:https
|
||||||
|
```
|
||||||
|
|
||||||
|
Équivalents Docker directs (sans Node.js sur le VPS) :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Migrations seules
|
||||||
|
docker compose run --rm --no-deps --build backend node dist/db/migrate.js
|
||||||
|
|
||||||
|
# Puis démarrage
|
||||||
|
docker compose --profile http up -d --build # HTTP
|
||||||
|
docker compose --profile https-dns up -d --build # HTTPS
|
||||||
|
```
|
||||||
|
|
||||||
|
**Démarrages suivants** (base déjà migrée, pas de changement de schéma) :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run phase-b:up # HTTP
|
||||||
|
npm run phase-b:up:https # HTTPS
|
||||||
|
```
|
||||||
|
|
||||||
|
**Configuration initiale (navigateur) :**
|
||||||
|
|
||||||
|
| Mode | URL setup |
|
||||||
|
|------|-----------|
|
||||||
|
| HTTP | `http://prediqo.redirectme.net:9080/setup` |
|
||||||
|
| HTTPS | `https://prediqo.redirectme.net:9443/setup` |
|
||||||
|
|
||||||
|
1. Saisir le **`INITIAL_SETUP_TOKEN`** (valeur de `.env` sur le serveur).
|
||||||
|
2. Créer le premier administrateur **ou** promouvoir un compte existant.
|
||||||
|
3. Un **code de parrainage racine** est généré automatiquement pour ce super admin ; les inscriptions sans code y seront rattachées.
|
||||||
|
4. Se connecter sur **`/login`**.
|
||||||
|
|
||||||
|
### En local — Docker (même stack que le VPS)
|
||||||
|
|
||||||
|
Fichier d’environnement dédié : **`.env.docker`** (non versionné).
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cp .env.docker.example .env.docker
|
||||||
|
# Éditer .env.docker : POSTGRES_PASSWORD, JWT_SECRET, ENCRYPTION_KEY,
|
||||||
|
# PLATFORM_MNEMONIC, INITIAL_SETUP_TOKEN
|
||||||
|
# Créer la base vide sur PostgreSQL local, ex. games_platform_db
|
||||||
|
```
|
||||||
|
|
||||||
|
**Premier démarrage (base vierge) :**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run docker:local:init
|
||||||
|
```
|
||||||
|
|
||||||
|
Équivalent :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose --env-file .env.docker run --rm --no-deps --build backend node dist/db/migrate.js
|
||||||
|
docker compose --env-file .env.docker --profile http up -d --build
|
||||||
|
```
|
||||||
|
|
||||||
|
**Configuration initiale :** [http://localhost:9080/setup](http://localhost:9080/setup)
|
||||||
|
|
||||||
|
**Démarrages suivants :**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run docker:local:up
|
||||||
|
```
|
||||||
|
|
||||||
|
**Migrations seules** (après `git pull` avec changement de schéma) :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run docker:local:migrate
|
||||||
|
# ou : npm run db:migrate (utilise .env racine, pas .env.docker)
|
||||||
|
```
|
||||||
|
|
||||||
|
Autres commandes locales utiles : `npm run docker:local:status` · `docker:local:logs` · `docker:local:down`
|
||||||
|
|
||||||
|
### En local — sans Docker (backend Node + Postgres sur la machine)
|
||||||
|
|
||||||
|
Utile pour le développement backend pur :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd backend
|
||||||
|
cp .env.example .env
|
||||||
|
# DATABASE_URL=postgresql://user:pass@localhost:5432/crypto_wallet
|
||||||
|
npm run migrate
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
Frontend en dev (autre terminal) :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd prediqo_web
|
||||||
|
cp .env.example .env
|
||||||
|
# VITE_API_BASE_URL=http://localhost:4000
|
||||||
|
npm install
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
Page setup : **`http://localhost:5173/setup`** (ou le port Vite affiché), l’API étant sur le port configuré dans `VITE_API_BASE_URL`.
|
||||||
|
|
||||||
|
### Table récapitulative
|
||||||
|
|
||||||
|
| Contexte | Fichier env | 1er démarrage (base vierge) | Page setup |
|
||||||
|
|----------|-------------|-----------------------------|------------|
|
||||||
|
| **VPS HTTP** | `.env` | `npm run phase-b:init` | `:9080/setup` |
|
||||||
|
| **VPS HTTPS** | `.env` | `npm run phase-b:init:https` | `:9443/setup` |
|
||||||
|
| **Local Docker** | `.env.docker` | `npm run docker:local:init` | `http://localhost:9080/setup` |
|
||||||
|
| **Local sans Docker** | `backend/.env` | `cd backend && npm run migrate` puis `npm run dev` | frontend dev + `/setup` |
|
||||||
|
|
||||||
|
| Action | VPS | Local Docker |
|
||||||
|
|--------|-----|--------------|
|
||||||
|
| Migrations seules | `npm run db:migrate` | `npm run docker:local:migrate` |
|
||||||
|
| État conteneurs | `npm run phase-b:status` | `npm run docker:local:status` |
|
||||||
|
| Logs | `npm run phase-b:logs` | `npm run docker:local:logs` |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Lancer l’application
|
||||||
|
|
||||||
Deux parcours : **HTTP rapide** (test) ou **HTTPS recommandé** (production).
|
Deux parcours : **HTTP rapide** (test) ou **HTTPS recommandé** (production).
|
||||||
|
|
||||||
@ -245,25 +407,43 @@ Le port **9080** redirige automatiquement vers **9443**.
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 5. Premier administrateur
|
## 6. Premier administrateur
|
||||||
|
|
||||||
1. Ouvrez **https://prediqo.redirectme.net:9443/setup** (ou `:9080` en HTTP).
|
> Résumé des commandes de démarrage : [section 4](#4-démarrage-sur-base-de-données-vierge-vps-et-local).
|
||||||
2. Saisissez le **`INITIAL_SETUP_TOKEN`** (valeur de `.env` sur le serveur).
|
|
||||||
3. Créez le compte admin ou promouvez un utilisateur existant.
|
1. Ouvrez la page **setup** (voir URLs ci-dessous).
|
||||||
4. Connectez-vous sur **/login**.
|
2. Saisissez le **`INITIAL_SETUP_TOKEN`** (valeur de `.env` ou `.env.docker` — **identique** à celle du serveur, min. 16 caractères).
|
||||||
|
3. **Créez** le compte administrateur **ou** **promouvez** un utilisateur déjà inscrit via Register.
|
||||||
|
4. Le système génère automatiquement un **code de parrainage racine** pour ce super administrateur ; les nouveaux utilisateurs sans code de parrainage y seront rattachés.
|
||||||
|
5. Connectez-vous sur **`/login`**.
|
||||||
|
|
||||||
|
| Contexte | URL setup |
|
||||||
|
|----------|-----------|
|
||||||
|
| VPS HTTPS | `https://prediqo.redirectme.net:9443/setup` |
|
||||||
|
| VPS HTTP | `http://prediqo.redirectme.net:9080/setup` |
|
||||||
|
| Local Docker | `http://localhost:9080/setup` |
|
||||||
|
|
||||||
Ensuite, gérez les rôles depuis **Admin → Users**.
|
Ensuite, gérez les rôles depuis **Admin → Users**.
|
||||||
|
|
||||||
|
Si `setupEnabled` est `false` dans `/api/v1/setup/status`, vérifiez que `INITIAL_SETUP_TOKEN` est défini (32+ caractères recommandés) et redémarrez le backend :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose restart backend
|
||||||
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 6. Commandes utiles
|
## 7. Commandes utiles
|
||||||
|
|
||||||
| Action | Commande |
|
| Action | Commande |
|
||||||
|--------|----------|
|
|--------|----------|
|
||||||
| **1er déploiement HTTP** | `npm run phase-b:init` |
|
| **1er déploiement HTTP (VPS)** | `npm run phase-b:init` |
|
||||||
| **1er déploiement HTTPS** | `npm run phase-b:init:https` |
|
| **1er déploiement HTTPS (VPS)** | `npm run phase-b:init:https` |
|
||||||
| Démarrer / rebuild (HTTP) | `npm run phase-b:up` |
|
| **1er démarrage local Docker** | `npm run docker:local:init` |
|
||||||
| Migrations seules | `npm run db:migrate` |
|
| Démarrer / rebuild (HTTP VPS) | `npm run phase-b:up` |
|
||||||
|
| Démarrer local Docker | `npm run docker:local:up` |
|
||||||
|
| Migrations seules (VPS) | `npm run db:migrate` |
|
||||||
|
| Migrations seules (local Docker) | `npm run docker:local:migrate` |
|
||||||
| État des conteneurs | `npm run phase-b:status` |
|
| État des conteneurs | `npm run phase-b:status` |
|
||||||
| Logs en direct | `npm run phase-b:logs` |
|
| Logs en direct | `npm run phase-b:logs` |
|
||||||
| Redémarrer | `npm run phase-b:restart` |
|
| Redémarrer | `npm run phase-b:restart` |
|
||||||
@ -279,7 +459,7 @@ docker compose logs -f nginx-https-dns
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 7. Mise à jour après `git pull`
|
## 8. Mise à jour après `git pull`
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cd ~/games_app
|
cd ~/games_app
|
||||||
@ -296,7 +476,7 @@ docker compose --profile https-dns up -d
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 8. Renouveler le certificat SSL (~tous les 90 jours)
|
## 9. Renouveler le certificat SSL (~tous les 90 jours)
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm run ssl:dns-renew
|
npm run ssl:dns-renew
|
||||||
@ -306,7 +486,7 @@ Même procédure TXT DNS que lors de la création initiale.
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 9. Architecture des conteneurs
|
## 10. Architecture des conteneurs
|
||||||
|
|
||||||
| Conteneur | Rôle |
|
| Conteneur | Rôle |
|
||||||
|-----------|------|
|
|-----------|------|
|
||||||
@ -322,7 +502,7 @@ PostgreSQL tourne **sur l’hôte**, pas dans Docker (sauf profil `docker-db` op
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 10. Dépannage
|
## 11. Dépannage
|
||||||
|
|
||||||
### `database "crypto_wallet" does not exist`
|
### `database "crypto_wallet" does not exist`
|
||||||
|
|
||||||
@ -506,7 +686,7 @@ Puis : `sudo npm run phase-b:up` (rebuild `prediqo-web`).
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 11. Migration vers un VPS dédié (futur)
|
## 12. Migration vers un VPS dédié (futur)
|
||||||
|
|
||||||
Quand Prediqo aura son propre serveur :
|
Quand Prediqo aura son propre serveur :
|
||||||
|
|
||||||
@ -518,10 +698,11 @@ Aucune modification des autres projets n’est nécessaire.
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 12. Fichiers `.env` — rappel
|
## 13. Fichiers `.env` — rappel
|
||||||
|
|
||||||
| Fichier | VPS Docker |
|
| Fichier | Usage |
|
||||||
|---------|------------|
|
|---------|--------|
|
||||||
| **`.env` (racine)** | **Oui — fichier principal** |
|
| **`.env` (racine)** | **VPS Docker** — fichier principal |
|
||||||
| `backend/.env` | Non requis (dev local Node seulement) |
|
| **`.env.docker`** | **Local Docker** — copie de `.env.docker.example`, gitignored |
|
||||||
| `prediqo_web/.env` | Non requis (Docker utilise `VITE_*` du `.env` racine) |
|
| `backend/.env` | Dev local Node seulement (sans Docker) |
|
||||||
|
| `prediqo_web/.env` | Dev frontend Vite seulement ; en Docker, `VITE_*` vient du `.env` racine |
|
||||||
|
|||||||
@ -28,8 +28,8 @@ class AuthState extends Equatable {
|
|||||||
final String? errorMessage;
|
final String? errorMessage;
|
||||||
final Map<String, dynamic>? totpData;
|
final Map<String, dynamic>? totpData;
|
||||||
|
|
||||||
/// Whether the signed-in user has the admin role.
|
/// Whether the signed-in user has administrator access (admin or super_admin).
|
||||||
bool get isAdmin => role == 'admin';
|
bool get isAdmin => role == 'admin' || role == 'super_admin';
|
||||||
|
|
||||||
@override
|
@override
|
||||||
List<Object?> get props => [status, userId, role, errorMessage, totpData];
|
List<Object?> get props => [status, userId, role, errorMessage, totpData];
|
||||||
|
|||||||
@ -76,12 +76,10 @@ export const router = createBrowserRouter([
|
|||||||
{ index: true, element: <Navigate to="/home" replace /> },
|
{ index: true, element: <Navigate to="/home" replace /> },
|
||||||
{ path: 'home', element: <HomePage /> },
|
{ path: 'home', element: <HomePage /> },
|
||||||
{ path: 'games/:slug', element: <GamePlayRoute /> },
|
{ path: 'games/:slug', element: <GamePlayRoute /> },
|
||||||
{ path: 'dashboard', element: <DashboardPage /> },
|
|
||||||
{ path: 'wallet', element: <WalletPage /> },
|
{ path: 'wallet', element: <WalletPage /> },
|
||||||
{ path: 'referral', element: <ReferralPage /> },
|
{ path: 'referral', element: <ReferralPage /> },
|
||||||
{ path: 'profile', element: <ProfilePage /> },
|
{ path: 'profile', element: <ProfilePage /> },
|
||||||
{ path: 'help/faq', element: <FaqPage /> },
|
{ path: 'help/faq', element: <FaqPage /> },
|
||||||
{ path: 'options', element: <OptionsPage /> },
|
|
||||||
{
|
{
|
||||||
element: <RequireAuth staffOnly />,
|
element: <RequireAuth staffOnly />,
|
||||||
children: [
|
children: [
|
||||||
@ -92,6 +90,8 @@ export const router = createBrowserRouter([
|
|||||||
{
|
{
|
||||||
element: <RequireAuth adminOnly />,
|
element: <RequireAuth adminOnly />,
|
||||||
children: [
|
children: [
|
||||||
|
{ path: 'dashboard', element: <DashboardPage /> },
|
||||||
|
{ path: 'options', element: <OptionsPage /> },
|
||||||
{ path: 'admin/users', element: <UserManagementPage /> },
|
{ path: 'admin/users', element: <UserManagementPage /> },
|
||||||
{ path: 'admin/reports', element: <ReportsHubPage /> },
|
{ path: 'admin/reports', element: <ReportsHubPage /> },
|
||||||
{ path: 'admin/reports/:reportKey', element: <ReportDetailPage /> },
|
{ path: 'admin/reports/:reportKey', element: <ReportDetailPage /> },
|
||||||
|
|||||||
@ -36,6 +36,7 @@ export function SetupPage() {
|
|||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const [success, setSuccess] = useState<string | null>(null);
|
const [success, setSuccess] = useState<string | null>(null);
|
||||||
|
const [referralCode, setReferralCode] = useState<string | null>(null);
|
||||||
|
|
||||||
const statusQ = useQuery({
|
const statusQ = useQuery({
|
||||||
queryKey: ['setup-status'],
|
queryKey: ['setup-status'],
|
||||||
@ -51,16 +52,18 @@ export function SetupPage() {
|
|||||||
const submitCreate = async () => {
|
const submitCreate = async () => {
|
||||||
setError(null);
|
setError(null);
|
||||||
setSuccess(null);
|
setSuccess(null);
|
||||||
|
setReferralCode(null);
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
try {
|
try {
|
||||||
const res = await api.post<{ message: string }>('/api/v1/setup/first-admin', {
|
const res = await api.post<{ message: string; referralCode?: string }>('/api/v1/setup/first-admin', {
|
||||||
email: email.trim(),
|
email: email.trim(),
|
||||||
password,
|
password,
|
||||||
fullName: fullName.trim(),
|
fullName: fullName.trim(),
|
||||||
setupToken: setupToken.trim(),
|
setupToken: setupToken.trim(),
|
||||||
});
|
});
|
||||||
setSuccess(res.data.message);
|
setSuccess(res.data.message);
|
||||||
setTimeout(() => nav('/login', { replace: true }), 2000);
|
setReferralCode(res.data.referralCode ?? null);
|
||||||
|
setTimeout(() => nav('/login', { replace: true }), 5000);
|
||||||
} catch (e: unknown) {
|
} catch (e: unknown) {
|
||||||
const err = e as { response?: { data?: { error?: string } }; message?: string };
|
const err = e as { response?: { data?: { error?: string } }; message?: string };
|
||||||
setError(err?.response?.data?.error ?? err?.message ?? t('setup.setupFailed'));
|
setError(err?.response?.data?.error ?? err?.message ?? t('setup.setupFailed'));
|
||||||
@ -72,14 +75,16 @@ export function SetupPage() {
|
|||||||
const submitPromote = async () => {
|
const submitPromote = async () => {
|
||||||
setError(null);
|
setError(null);
|
||||||
setSuccess(null);
|
setSuccess(null);
|
||||||
|
setReferralCode(null);
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
try {
|
try {
|
||||||
const res = await api.post<{ message: string }>('/api/v1/setup/promote-admin', {
|
const res = await api.post<{ message: string; referralCode?: string }>('/api/v1/setup/promote-admin', {
|
||||||
email: email.trim(),
|
email: email.trim(),
|
||||||
setupToken: setupToken.trim(),
|
setupToken: setupToken.trim(),
|
||||||
});
|
});
|
||||||
setSuccess(res.data.message);
|
setSuccess(res.data.message);
|
||||||
setTimeout(() => nav('/login', { replace: true }), 2000);
|
setReferralCode(res.data.referralCode ?? null);
|
||||||
|
setTimeout(() => nav('/login', { replace: true }), 5000);
|
||||||
} catch (e: unknown) {
|
} catch (e: unknown) {
|
||||||
const err = e as { response?: { data?: { error?: string } }; message?: string };
|
const err = e as { response?: { data?: { error?: string } }; message?: string };
|
||||||
setError(err?.response?.data?.error ?? err?.message ?? t('setup.promotionFailed'));
|
setError(err?.response?.data?.error ?? err?.message ?? t('setup.promotionFailed'));
|
||||||
@ -214,6 +219,17 @@ export function SetupPage() {
|
|||||||
{success && (
|
{success && (
|
||||||
<Alert severity="success" sx={{ mt: 2 }}>
|
<Alert severity="success" sx={{ mt: 2 }}>
|
||||||
{success}
|
{success}
|
||||||
|
{referralCode && (
|
||||||
|
<Typography component="div" variant="body2" sx={{ mt: 1 }}>
|
||||||
|
<Trans
|
||||||
|
i18nKey="setup.referralRootCode"
|
||||||
|
values={{ code: referralCode }}
|
||||||
|
components={{ strong: <strong /> }}
|
||||||
|
/>
|
||||||
|
<br />
|
||||||
|
{t('setup.referralRootHint')}
|
||||||
|
</Typography>
|
||||||
|
)}
|
||||||
</Alert>
|
</Alert>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
|||||||
@ -3,6 +3,7 @@
|
|||||||
*/
|
*/
|
||||||
import React, { createContext, useContext, useMemo, useState } from 'react';
|
import React, { createContext, useContext, useMemo, useState } from 'react';
|
||||||
import { clearAuth, readAuth, writeAuth } from './tokenStorage';
|
import { clearAuth, readAuth, writeAuth } from './tokenStorage';
|
||||||
|
import { hasAdminAccess, hasStaffAccess } from './roleAccess';
|
||||||
|
|
||||||
export type AuthState = {
|
export type AuthState = {
|
||||||
accessToken: string | null;
|
accessToken: string | null;
|
||||||
@ -48,8 +49,8 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
|||||||
const hasRole = (name: string) => roles.includes(name);
|
const hasRole = (name: string) => roles.includes(name);
|
||||||
const hasPermission = (key: string) => permissions.includes(key);
|
const hasPermission = (key: string) => permissions.includes(key);
|
||||||
const isSuperAdmin = hasRole('super_admin');
|
const isSuperAdmin = hasRole('super_admin');
|
||||||
const isAdmin = hasRole('admin') || isSuperAdmin;
|
const isAdmin = hasAdminAccess(roles, auth.role);
|
||||||
const isStaff = isAdmin || hasRole('moderator');
|
const isStaff = hasStaffAccess(roles, auth.role);
|
||||||
const canApproveFundOps = hasPermission('fund_operation.approve');
|
const canApproveFundOps = hasPermission('fund_operation.approve');
|
||||||
return {
|
return {
|
||||||
auth,
|
auth,
|
||||||
|
|||||||
@ -8,7 +8,7 @@ import { useAuth } from './AuthContext';
|
|||||||
/**
|
/**
|
||||||
* Protects nested routes by requiring a valid session and, optionally, an admin role.
|
* Protects nested routes by requiring a valid session and, optionally, an admin role.
|
||||||
*
|
*
|
||||||
* @param props.adminOnly - When true, only users with the admin role may access child routes.
|
* @param props.adminOnly - When true, only users with admin or super_admin role may access child routes.
|
||||||
* @returns A redirect to login or dashboard, or an outlet for authorized child routes.
|
* @returns A redirect to login or dashboard, or an outlet for authorized child routes.
|
||||||
*/
|
*/
|
||||||
export function RequireAuth({
|
export function RequireAuth({
|
||||||
|
|||||||
19
prediqo_web/src/shared/auth/roleAccess.ts
Normal file
19
prediqo_web/src/shared/auth/roleAccess.ts
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
/**
|
||||||
|
* Shared role helpers for route guards and UI visibility.
|
||||||
|
* Super administrators inherit every administrator capability.
|
||||||
|
*/
|
||||||
|
export function userRoleList(roles: string[] | undefined, role?: string | null): string[] {
|
||||||
|
if (roles?.length) return roles;
|
||||||
|
if (role) return [role];
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function hasAdminAccess(roles: string[] | undefined, role?: string | null): boolean {
|
||||||
|
const list = userRoleList(roles, role);
|
||||||
|
return list.includes('admin') || list.includes('super_admin');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function hasStaffAccess(roles: string[] | undefined, role?: string | null): boolean {
|
||||||
|
const list = userRoleList(roles, role);
|
||||||
|
return list.includes('moderator') || hasAdminAccess(roles, role);
|
||||||
|
}
|
||||||
@ -168,6 +168,9 @@ export const en = {
|
|||||||
setupFailed: 'Setup failed',
|
setupFailed: 'Setup failed',
|
||||||
promotionFailed: 'Promotion failed',
|
promotionFailed: 'Promotion failed',
|
||||||
backToLogin: 'Back to sign in',
|
backToLogin: 'Back to sign in',
|
||||||
|
referralRootCode: 'Root referral code: <strong>{{code}}</strong>',
|
||||||
|
referralRootHint:
|
||||||
|
'New users who register without a referral code will automatically be linked to this administrator account.',
|
||||||
},
|
},
|
||||||
gender: {
|
gender: {
|
||||||
label: 'Gender',
|
label: 'Gender',
|
||||||
|
|||||||
@ -174,6 +174,9 @@ export const fr = {
|
|||||||
setupFailed: 'Échec de l’initialisation',
|
setupFailed: 'Échec de l’initialisation',
|
||||||
promotionFailed: 'Échec de la promotion',
|
promotionFailed: 'Échec de la promotion',
|
||||||
backToLogin: 'Retour à la connexion',
|
backToLogin: 'Retour à la connexion',
|
||||||
|
referralRootCode: 'Code de parrainage racine : <strong>{{code}}</strong>',
|
||||||
|
referralRootHint:
|
||||||
|
'Les nouveaux utilisateurs qui s’inscrivent sans code de parrainage seront automatiquement rattachés à ce compte administrateur.',
|
||||||
},
|
},
|
||||||
gender: {
|
gender: {
|
||||||
label: 'Sexe',
|
label: 'Sexe',
|
||||||
|
|||||||
@ -250,7 +250,7 @@ export function AppShell() {
|
|||||||
<Chip
|
<Chip
|
||||||
size="small"
|
size="small"
|
||||||
label={`${t('common.role')}: ${role}`}
|
label={`${t('common.role')}: ${role}`}
|
||||||
color={role === 'admin' ? 'primary' : 'default'}
|
color={isAdmin ? 'primary' : 'default'}
|
||||||
variant="outlined"
|
variant="outlined"
|
||||||
sx={{ display: { xs: 'none', sm: 'inline-flex' } }}
|
sx={{ display: { xs: 'none', sm: 'inline-flex' } }}
|
||||||
/>
|
/>
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user