diff --git a/.cursor/rules/admin-super-admin-access.mdc b/.cursor/rules/admin-super-admin-access.mdc new file mode 100644 index 00000000..91b8513e --- /dev/null +++ b/.cursor/rules/admin-super-admin-access.mdc @@ -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. diff --git a/.cursor/rules/platform-setup-referral.mdc b/.cursor/rules/platform-setup-referral.mdc new file mode 100644 index 00000000..0b2302f5 --- /dev/null +++ b/.cursor/rules/platform-setup-referral.mdc @@ -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. diff --git a/README.md b/README.md index 6a8791b2..b8eba4f9 100644 --- a/README.md +++ b/README.md @@ -146,7 +146,7 @@ To enable withdrawals, insert a hot wallet per asset (e.g. via script or admin): ## 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 : @@ -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` +### 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) ```bash diff --git a/backend/src/controllers/candlePredictController.ts b/backend/src/controllers/candlePredictController.ts index 5da9a5dd..6436ba23 100644 --- a/backend/src/controllers/candlePredictController.ts +++ b/backend/src/controllers/candlePredictController.ts @@ -1,6 +1,7 @@ import { Response } from 'express'; import { AuthRequest } from '../middleware/auth'; +import { hasAdminAccess } from '../utils/roleAccess'; import * as candlePredictService from '../services/candlePredictService'; import { parseStakeAmountFromBody } from '../utils/stakeAmountValidation'; @@ -26,7 +27,7 @@ export async function getState(req: AuthRequest, res: Response): Promise { 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, { includeInternal, @@ -72,7 +73,7 @@ export async function getCandles(req: AuthRequest, res: Response): Promise beforeOpenMs, - includeInternal: req.user?.role === 'admin', + includeInternal: req.user ? hasAdminAccess(req.user) : false, }); diff --git a/backend/src/controllers/gamePlayController.ts b/backend/src/controllers/gamePlayController.ts index 727634a4..58b95d6d 100644 --- a/backend/src/controllers/gamePlayController.ts +++ b/backend/src/controllers/gamePlayController.ts @@ -15,6 +15,7 @@ function buildCtx(req: AuthRequest): GameRequestContext { return { userId: req.user?.userId, role: req.user?.role, + roles: req.user?.roles, query: req.query as Record, body: (req.body ?? {}) as Record, params: req.params as Record, diff --git a/backend/src/games/modules/candle-predict/candlePredictModule.ts b/backend/src/games/modules/candle-predict/candlePredictModule.ts index 010b8f98..ef838ab5 100644 --- a/backend/src/games/modules/candle-predict/candlePredictModule.ts +++ b/backend/src/games/modules/candle-predict/candlePredictModule.ts @@ -1,6 +1,7 @@ import * as candlePredictService from '../../../services/candlePredictService'; import { parseStakeAmountFromBody } from '../../../utils/stakeAmountValidation'; import { UnsupportedGameActionError } from '../../errors'; +import { hasAdminAccess } from '../../../utils/roleAccess'; import type { GameModule } from '../../types'; function parseIntervalMinutes(value: unknown): number | undefined { @@ -32,9 +33,9 @@ export const candlePredictModule: GameModule = { startEngine: () => candlePredictService.startCandlePredictEngine(), - getState: ({ userId, query, role }) => + getState: ({ userId, query, role, roles }) => candlePredictService.getGameState(userId, parseIntervalMinutes(query.intervalMinutes), { - includeInternal: role === 'admin', + includeInternal: hasAdminAccess({ role, roles }), }), placeBet: ({ userId, body }) => { @@ -95,7 +96,7 @@ export const candlePredictModule: GameModule = { limit: limit > 0 ? limit : undefined, intervalMinutes: parseIntervalMinutes(ctx.query.intervalMinutes), beforeOpenMs, - includeInternal: ctx.role === 'admin', + includeInternal: hasAdminAccess(ctx), }); } throw new UnsupportedGameActionError(action); diff --git a/backend/src/games/types.ts b/backend/src/games/types.ts index d480cbb3..f43832f6 100644 --- a/backend/src/games/types.ts +++ b/backend/src/games/types.ts @@ -3,6 +3,8 @@ * Each prediction game implements GameModule and registers at startup. */ +import type { RoleName } from '../models'; + export type GameImplementationKey = 'candle-predict'; /** Actions exposed via the generic game API (subset shared across games). */ @@ -25,7 +27,8 @@ export type GameCapabilities = { export type GameRequestContext = { userId?: string; - role?: string; + role?: RoleName; + roles?: RoleName[]; query: Record; body: Record; params: Record; diff --git a/backend/src/middleware/auth.ts b/backend/src/middleware/auth.ts index 5d27a490..4e852640 100644 --- a/backend/src/middleware/auth.ts +++ b/backend/src/middleware/auth.ts @@ -9,6 +9,7 @@ import { verifyToken } from '../services/authService'; import { touchAppPresence } from '../realtime/redis/onlinePresence'; import { JwtPayload } from '../types'; import type { RoleName } from '../models'; +import { hasAdminAccess, hasStaffAccess, userRoleList } from '../utils/roleAccess'; /** Express request extended with the authenticated user's JWT payload. */ export interface AuthRequest extends Request { @@ -16,9 +17,7 @@ export interface AuthRequest extends Request { } function userRoles(user: JwtPayload): RoleName[] { - if (user.roles?.length) return user.roles; - if (user.role) return [user.role]; - return []; + return userRoleList(user); } function userHasAnyRole(user: JwtPayload, roles: string[]): boolean { @@ -60,7 +59,11 @@ export function requireRoles(...roles: string[]) { next(); 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(); return; } diff --git a/backend/src/realtime/ws/hub.ts b/backend/src/realtime/ws/hub.ts index d3dd85ea..78700aef 100644 --- a/backend/src/realtime/ws/hub.ts +++ b/backend/src/realtime/ws/hub.ts @@ -2,6 +2,7 @@ import type WebSocket from 'ws'; import { getGameState, placeBet } from '../../domain/candle-predict/index'; import { config } from '../../config'; +import { hasAdminAccess } from '../../utils/roleAccess'; import { connectRedis, getRedisSubscriber } from '../redis/client'; import { removeGamePresence, touchAppPresence, touchGamePresence } from '../redis/onlinePresence'; import { parseRealtimeEvent } from '../redis/pubsub'; @@ -122,7 +123,7 @@ export class GameWsHub { for (const client of this.clients) { 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); if (event.type === 'round.updated') { @@ -205,7 +206,7 @@ export class GameWsHub { } client.intervals.add(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, { type: 'subscribed', diff --git a/backend/src/repositories/referralRepository.ts b/backend/src/repositories/referralRepository.ts index 6f6cbcd5..0d11c5b6 100644 --- a/backend/src/repositories/referralRepository.ts +++ b/backend/src/repositories/referralRepository.ts @@ -228,6 +228,29 @@ export async function generateUniqueReferralCode(): Promise { 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 { + 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 { + 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: { beneficiaryUserId: string; referredUserId: string; diff --git a/backend/src/services/authService.ts b/backend/src/services/authService.ts index 240feaec..fff612c3 100644 --- a/backend/src/services/authService.ts +++ b/backend/src/services/authService.ts @@ -23,6 +23,7 @@ import { SystemSettings } from '../models'; import { parseUserGender, type UserGender } from '../models/userGender'; import { JwtPayload, RoleName } from '../types'; import * as roleRepository from '../repositories/roleRepository'; +import { hasAdminAccess } from '../utils/roleAccess'; import { v4 as uuidv4 } from 'uuid'; 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 ok = allowed.some((r) => roles.includes(r)) || - (allowed.includes('admin') && roles.includes('super_admin')); + (allowed.includes('admin') && hasAdminAccess(payload)); if (!ok) throw new Error('Forbidden'); }; } diff --git a/backend/src/services/referralService.ts b/backend/src/services/referralService.ts index a1246b75..e807e610 100644 --- a/backend/src/services/referralService.ts +++ b/backend/src/services/referralService.ts @@ -104,6 +104,16 @@ export async function resolveReferrerId(referralCode?: string | null): Promise { + const referralCode = await referralRepository.ensureUserReferralCode(superAdminUserId); + await referralRepository.updateSettings({ defaultReferrerUserId: superAdminUserId }); + return referralCode; +} + export async function assertReferrerEligible(referrerId: string): Promise { const settings = await referralRepository.getSettings(); const referrer = await userRepository.findById(referrerId); @@ -117,8 +127,11 @@ export async function assertReferrerEligible(referrerId: string): Promise throw new ReferralError('Referrer must have a verified email'); } if (settings.referrer_must_have_deposited) { + const isDefaultRoot = settings.default_referrer_user_id === 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 { await assertReferralChainHasNoLoop(referrerId); diff --git a/backend/src/services/setupService.ts b/backend/src/services/setupService.ts index 7781f2f2..9e3f0ba2 100644 --- a/backend/src/services/setupService.ts +++ b/backend/src/services/setupService.ts @@ -8,6 +8,7 @@ import { config } from '../config'; import * as userRepository from '../repositories/userRepository'; import * as roleRepository from '../repositories/roleRepository'; import * as auditLogRepository from '../repositories/auditLogRepository'; +import * as referralService from './referralService'; import { hashForIndex, encrypt } from '../utils/crypto'; export type SetupStatus = { @@ -53,7 +54,7 @@ export async function createFirstAdmin(input: { password: string; fullName: string; setupToken: string; -}): Promise<{ userId: string; message: string }> { +}): Promise<{ userId: string; referralCode: string; message: string }> { await ensureNoAdminYet(); assertSetupToken(input.setupToken.trim()); @@ -89,16 +90,19 @@ export async function createFirstAdmin(input: { await userRepository.setEmailVerified(user.id, true); await roleRepository.setUserRoles(user.id, ['admin', 'super_admin']); + const referralCode = await referralService.bootstrapReferralRootAtPlatformSetup(user.id); + await auditLogRepository.create({ userId: user.id, action: 'setup_first_admin_created', resourceType: 'user', resourceId: user.id, - metadata: { email }, + metadata: { email, referral_code: referralCode }, }); return { userId: user.id, + referralCode, message: 'Administrator account created. You can now sign in.', }; } @@ -107,7 +111,7 @@ export async function promoteExistingUserToAdmin(input: { email: string; setupToken: string; role?: 'admin' | 'moderator'; -}): Promise<{ userId: string; role: string; message: string }> { +}): Promise<{ userId: string; role: string; referralCode: string; message: string }> { await ensureNoAdminYet(); assertSetupToken(input.setupToken.trim()); @@ -129,17 +133,20 @@ export async function promoteExistingUserToAdmin(input: { await roleRepository.setUserRoles(user.id, ['admin', 'super_admin']); await userRepository.setEmailVerified(user.id, true); + const referralCode = await referralService.bootstrapReferralRootAtPlatformSetup(user.id); + await auditLogRepository.create({ userId: user.id, action: 'setup_first_admin_promoted', resourceType: 'user', resourceId: user.id, - metadata: { email, role: targetRole }, + metadata: { email, role: targetRole, referral_code: referralCode }, }); return { userId: user.id, role: targetRole, + referralCode, message: `User promoted to ${targetRole}. They can sign in with their existing password.`, }; } diff --git a/backend/src/services/supportService.ts b/backend/src/services/supportService.ts index e9e01eb9..49d38e49 100644 --- a/backend/src/services/supportService.ts +++ b/backend/src/services/supportService.ts @@ -13,7 +13,7 @@ import { setTypingIndicator, } 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 { return !!role && STAFF_ROLES.has(role); diff --git a/backend/src/tests/roleAccess.test.ts b/backend/src/tests/roleAccess.test.ts new file mode 100644 index 00000000..c0f064d1 --- /dev/null +++ b/backend/src/tests/roleAccess.test.ts @@ -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']); + }); +}); diff --git a/backend/src/utils/roleAccess.ts b/backend/src/utils/roleAccess.ts new file mode 100644 index 00000000..b2286c01 --- /dev/null +++ b/backend/src/utils/roleAccess.ts @@ -0,0 +1,29 @@ +import type { RoleName } from '../models'; +import type { JwtPayload } from '../types'; + +type RoleCarrier = Pick | { 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); +} diff --git a/docs/DEPLOY-VPS.md b/docs/DEPLOY-VPS.md index abac8a9b..ef7cba38 100644 --- a/docs/DEPLOY-VPS.md +++ b/docs/DEPLOY-VPS.md @@ -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**). +**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 @@ -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). @@ -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). -2. Saisissez le **`INITIAL_SETUP_TOKEN`** (valeur de `.env` sur le serveur). -3. Créez le compte admin ou promouvez un utilisateur existant. -4. Connectez-vous sur **/login**. +> Résumé des commandes de démarrage : [section 4](#4-démarrage-sur-base-de-données-vierge-vps-et-local). + +1. Ouvrez la page **setup** (voir URLs ci-dessous). +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**. +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 | |--------|----------| -| **1er déploiement HTTP** | `npm run phase-b:init` | -| **1er déploiement HTTPS** | `npm run phase-b:init:https` | -| Démarrer / rebuild (HTTP) | `npm run phase-b:up` | -| Migrations seules | `npm run db:migrate` | +| **1er déploiement HTTP (VPS)** | `npm run phase-b:init` | +| **1er déploiement HTTPS (VPS)** | `npm run phase-b:init:https` | +| **1er démarrage local Docker** | `npm run docker:local:init` | +| 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` | | Logs en direct | `npm run phase-b:logs` | | 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 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 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 | |-----------|------| @@ -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` @@ -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 : @@ -518,10 +698,11 @@ Aucune modification des autres projets n’est nécessaire. --- -## 12. Fichiers `.env` — rappel +## 13. Fichiers `.env` — rappel -| Fichier | VPS Docker | -|---------|------------| -| **`.env` (racine)** | **Oui — fichier principal** | -| `backend/.env` | Non requis (dev local Node seulement) | -| `prediqo_web/.env` | Non requis (Docker utilise `VITE_*` du `.env` racine) | +| Fichier | Usage | +|---------|--------| +| **`.env` (racine)** | **VPS Docker** — fichier principal | +| **`.env.docker`** | **Local Docker** — copie de `.env.docker.example`, gitignored | +| `backend/.env` | Dev local Node seulement (sans Docker) | +| `prediqo_web/.env` | Dev frontend Vite seulement ; en Docker, `VITE_*` vient du `.env` racine | diff --git a/prediqo_mobile/lib/features/auth/bloc/auth_state.dart b/prediqo_mobile/lib/features/auth/bloc/auth_state.dart index 27e2c4a3..6d95346d 100644 --- a/prediqo_mobile/lib/features/auth/bloc/auth_state.dart +++ b/prediqo_mobile/lib/features/auth/bloc/auth_state.dart @@ -28,8 +28,8 @@ class AuthState extends Equatable { final String? errorMessage; final Map? totpData; - /// Whether the signed-in user has the admin role. - bool get isAdmin => role == 'admin'; + /// Whether the signed-in user has administrator access (admin or super_admin). + bool get isAdmin => role == 'admin' || role == 'super_admin'; @override List get props => [status, userId, role, errorMessage, totpData]; diff --git a/prediqo_web/src/app/router/router.tsx b/prediqo_web/src/app/router/router.tsx index b353aa79..bdb5e4ae 100644 --- a/prediqo_web/src/app/router/router.tsx +++ b/prediqo_web/src/app/router/router.tsx @@ -76,12 +76,10 @@ export const router = createBrowserRouter([ { index: true, element: }, { path: 'home', element: }, { path: 'games/:slug', element: }, - { path: 'dashboard', element: }, { path: 'wallet', element: }, { path: 'referral', element: }, { path: 'profile', element: }, { path: 'help/faq', element: }, - { path: 'options', element: }, { element: , children: [ @@ -92,6 +90,8 @@ export const router = createBrowserRouter([ { element: , children: [ + { path: 'dashboard', element: }, + { path: 'options', element: }, { path: 'admin/users', element: }, { path: 'admin/reports', element: }, { path: 'admin/reports/:reportKey', element: }, diff --git a/prediqo_web/src/features/auth/SetupPage.tsx b/prediqo_web/src/features/auth/SetupPage.tsx index 80117687..65f2ff9e 100644 --- a/prediqo_web/src/features/auth/SetupPage.tsx +++ b/prediqo_web/src/features/auth/SetupPage.tsx @@ -36,6 +36,7 @@ export function SetupPage() { const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const [success, setSuccess] = useState(null); + const [referralCode, setReferralCode] = useState(null); const statusQ = useQuery({ queryKey: ['setup-status'], @@ -51,16 +52,18 @@ export function SetupPage() { const submitCreate = async () => { setError(null); setSuccess(null); + setReferralCode(null); setLoading(true); 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(), password, fullName: fullName.trim(), setupToken: setupToken.trim(), }); setSuccess(res.data.message); - setTimeout(() => nav('/login', { replace: true }), 2000); + setReferralCode(res.data.referralCode ?? null); + setTimeout(() => nav('/login', { replace: true }), 5000); } catch (e: unknown) { const err = e as { response?: { data?: { error?: string } }; message?: string }; setError(err?.response?.data?.error ?? err?.message ?? t('setup.setupFailed')); @@ -72,14 +75,16 @@ export function SetupPage() { const submitPromote = async () => { setError(null); setSuccess(null); + setReferralCode(null); setLoading(true); 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(), setupToken: setupToken.trim(), }); setSuccess(res.data.message); - setTimeout(() => nav('/login', { replace: true }), 2000); + setReferralCode(res.data.referralCode ?? null); + setTimeout(() => nav('/login', { replace: true }), 5000); } catch (e: unknown) { const err = e as { response?: { data?: { error?: string } }; message?: string }; setError(err?.response?.data?.error ?? err?.message ?? t('setup.promotionFailed')); @@ -214,6 +219,17 @@ export function SetupPage() { {success && ( {success} + {referralCode && ( + + }} + /> +
+ {t('setup.referralRootHint')} +
+ )}
)} diff --git a/prediqo_web/src/shared/auth/AuthContext.tsx b/prediqo_web/src/shared/auth/AuthContext.tsx index e79c7fae..b4babc42 100644 --- a/prediqo_web/src/shared/auth/AuthContext.tsx +++ b/prediqo_web/src/shared/auth/AuthContext.tsx @@ -3,6 +3,7 @@ */ import React, { createContext, useContext, useMemo, useState } from 'react'; import { clearAuth, readAuth, writeAuth } from './tokenStorage'; +import { hasAdminAccess, hasStaffAccess } from './roleAccess'; export type AuthState = { accessToken: string | null; @@ -48,8 +49,8 @@ export function AuthProvider({ children }: { children: React.ReactNode }) { const hasRole = (name: string) => roles.includes(name); const hasPermission = (key: string) => permissions.includes(key); const isSuperAdmin = hasRole('super_admin'); - const isAdmin = hasRole('admin') || isSuperAdmin; - const isStaff = isAdmin || hasRole('moderator'); + const isAdmin = hasAdminAccess(roles, auth.role); + const isStaff = hasStaffAccess(roles, auth.role); const canApproveFundOps = hasPermission('fund_operation.approve'); return { auth, diff --git a/prediqo_web/src/shared/auth/RequireAuth.tsx b/prediqo_web/src/shared/auth/RequireAuth.tsx index 59e413eb..be2a5ff4 100644 --- a/prediqo_web/src/shared/auth/RequireAuth.tsx +++ b/prediqo_web/src/shared/auth/RequireAuth.tsx @@ -8,7 +8,7 @@ import { useAuth } from './AuthContext'; /** * 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. */ export function RequireAuth({ diff --git a/prediqo_web/src/shared/auth/roleAccess.ts b/prediqo_web/src/shared/auth/roleAccess.ts new file mode 100644 index 00000000..a15ea130 --- /dev/null +++ b/prediqo_web/src/shared/auth/roleAccess.ts @@ -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); +} diff --git a/prediqo_web/src/shared/i18n/locales/en.ts b/prediqo_web/src/shared/i18n/locales/en.ts index eccf4321..9a838c3e 100644 --- a/prediqo_web/src/shared/i18n/locales/en.ts +++ b/prediqo_web/src/shared/i18n/locales/en.ts @@ -168,6 +168,9 @@ export const en = { setupFailed: 'Setup failed', promotionFailed: 'Promotion failed', backToLogin: 'Back to sign in', + referralRootCode: 'Root referral code: {{code}}', + referralRootHint: + 'New users who register without a referral code will automatically be linked to this administrator account.', }, gender: { label: 'Gender', diff --git a/prediqo_web/src/shared/i18n/locales/fr.ts b/prediqo_web/src/shared/i18n/locales/fr.ts index f4f94df7..76c41cdf 100644 --- a/prediqo_web/src/shared/i18n/locales/fr.ts +++ b/prediqo_web/src/shared/i18n/locales/fr.ts @@ -174,6 +174,9 @@ export const fr = { setupFailed: 'Échec de l’initialisation', promotionFailed: 'Échec de la promotion', backToLogin: 'Retour à la connexion', + referralRootCode: 'Code de parrainage racine : {{code}}', + referralRootHint: + 'Les nouveaux utilisateurs qui s’inscrivent sans code de parrainage seront automatiquement rattachés à ce compte administrateur.', }, gender: { label: 'Sexe', diff --git a/prediqo_web/src/shared/layout/AppShell.tsx b/prediqo_web/src/shared/layout/AppShell.tsx index 9e7f4b64..689befa4 100644 --- a/prediqo_web/src/shared/layout/AppShell.tsx +++ b/prediqo_web/src/shared/layout/AppShell.tsx @@ -250,7 +250,7 @@ export function AppShell() {