/** * Login page for the Tloto web app (platform admin and player access). * Authenticates via `/api/v1/auth/login`, stores tokens in auth context, * and redirects to the route the user attempted before sign-in. */ import { Alert, Box, Button, Card, CardContent, IconButton, InputAdornment, Link, Stack, TextField, Typography, } from '@mui/material'; import ArrowBackRoundedIcon from '@mui/icons-material/ArrowBackRounded'; import VisibilityOffRoundedIcon from '@mui/icons-material/VisibilityOffRounded'; import VisibilityRoundedIcon from '@mui/icons-material/VisibilityRounded'; import { useState, useCallback } from 'react'; import { Navigate, useLocation, useNavigate, Link as RouterLink } from 'react-router-dom'; import { useQuery } from '@tanstack/react-query'; import { useTranslation } from 'react-i18next'; import { api } from '../../shared/services/api'; import { useAuth } from '../../shared/auth/AuthContext'; import { LanguageSwitcher } from '../../shared/i18n/LanguageSwitcher'; import { apiErrorMessage } from '../../shared/utils/apiError'; import { PrediqoLogo } from '../../shared/brand/PrediqoLogo'; import { TurnstileWidget } from './components/TurnstileWidget'; type LoginResponse = { accessToken: string; refreshToken: string; expiresIn: number; user: { id: string; emailHash: string; role: string; roles: string[]; permissions: string[]; primaryRole: string; }; }; type CaptchaChallenge = { provider: 'turnstile' | 'math'; siteKey?: string | null; challengeToken?: string; prompt?: string; }; type CaptchaConfig = { enabled: boolean; provider: 'turnstile' | 'math'; siteKey: string | null; afterFailures: number; }; /** Sign-in form with optional TOTP; redirects to `from` route on success. */ export function LoginPage() { const { t } = useTranslation(); const nav = useNavigate(); const loc = useLocation() as any; const { setAuth, isAuthenticated } = useAuth(); const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [showPassword, setShowPassword] = useState(false); const [totpCode, setTotpCode] = useState(''); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const [emailNotVerified, setEmailNotVerified] = useState(false); const [resendLoading, setResendLoading] = useState(false); const [resendSuccess, setResendSuccess] = useState(null); const [devVerifyUrl, setDevVerifyUrl] = useState(null); const [captchaToken, setCaptchaToken] = useState(null); const [captchaRequired, setCaptchaRequired] = useState(false); const [mathChallenge, setMathChallenge] = useState(null); const [mathAnswer, setMathAnswer] = useState(''); const [turnstileSiteKey, setTurnstileSiteKey] = useState(null); const [turnstileMountKey, setTurnstileMountKey] = useState(0); const from = loc.state?.from ?? '/home'; const verifyHint = loc.state?.verifyEmail === true; const captchaQ = useQuery({ queryKey: ['captcha-config'], queryFn: async () => { const res = await api.get('/api/v1/auth/captcha-config'); return res.data; }, }); const refreshTurnstile = useCallback((siteKey?: string | null) => { const key = (siteKey || captchaQ.data?.siteKey || '').trim(); setTurnstileSiteKey(key || null); setCaptchaToken(null); setTurnstileMountKey((k) => k + 1); }, [captchaQ.data?.siteKey]); const applyCaptchaChallenge = useCallback((challenge?: CaptchaChallenge | null) => { setCaptchaRequired(true); setCaptchaToken(null); setMathAnswer(''); if (challenge?.provider === 'math' && challenge.challengeToken && challenge.prompt) { setMathChallenge(challenge); setTurnstileSiteKey(null); return; } if (challenge?.provider === 'turnstile' || captchaQ.data?.provider === 'turnstile') { setMathChallenge(null); refreshTurnstile(challenge?.siteKey ?? captchaQ.data?.siteKey); return; } // Fallback: fetch a fresh math challenge when provider is math. void api .get('/api/v1/auth/captcha-challenge') .then((res) => { if (res.data.provider === 'math') { setMathChallenge(res.data); setTurnstileSiteKey(null); return; } if (res.data.provider === 'turnstile') { setMathChallenge(null); refreshTurnstile(res.data.siteKey); } }) .catch(() => { /* ignore */ }); }, [captchaQ.data?.provider, captchaQ.data?.siteKey, refreshTurnstile]); const onCaptchaToken = useCallback((token: string | null) => { setCaptchaToken(token); if (token) { // Clear a prior CAPTCHA_REQUIRED banner once the widget succeeds. setError((prev) => prev === t('auth.captchaRequired') || prev === t('auth.captchaInvalid') ? null : prev ); } }, [t]); const setupQ = useQuery({ queryKey: ['setup-status'], queryFn: async () => { const res = await api.get<{ needsSetup: boolean; setupEnabled: boolean }>('/api/v1/setup/status'); return res.data; }, }); if (isAuthenticated) { return ; } const resendVerification = async () => { setResendSuccess(null); setDevVerifyUrl(null); if (!email.trim()) { setError(t('auth.enterEmailFirst')); return; } setResendLoading(true); try { const res = await api.post<{ message: string; devVerifyUrl?: string }>( '/api/v1/auth/resend-verification-email', { email: email.trim() } ); setResendSuccess(res.data.message); if (res.data.devVerifyUrl) setDevVerifyUrl(res.data.devVerifyUrl); } catch (e: unknown) { setError(apiErrorMessage(e, t('auth.resendFailed'))); } finally { setResendLoading(false); } }; /** Validates credentials, calls the login API, and updates auth state. */ const submit = async () => { setError(null); setEmailNotVerified(false); setResendSuccess(null); setDevVerifyUrl(null); if (!email.trim() || !password) { setError(t('auth.emailPasswordRequired')); return; } let tokenToSend = captchaToken; if ( captchaRequired && mathChallenge?.provider === 'math' && mathChallenge.challengeToken && mathAnswer.trim() ) { tokenToSend = `math:${mathChallenge.challengeToken}:${mathAnswer.trim()}`; } if (captchaRequired && !tokenToSend?.trim()) { setError(t('auth.captchaRequired')); if (turnstileSiteKey || captchaQ.data?.provider === 'turnstile') { refreshTurnstile(turnstileSiteKey || captchaQ.data?.siteKey); } else { applyCaptchaChallenge(mathChallenge); } return; } setLoading(true); try { const res = await api.post('/api/v1/auth/login', { email: email.trim(), password, ...(totpCode.trim() ? { totpCode: totpCode.trim() } : {}), ...(tokenToSend ? { captchaToken: tokenToSend } : {}), }); setAuth({ accessToken: res.data.accessToken, refreshToken: res.data.refreshToken, userId: res.data.user.id, role: res.data.user.primaryRole ?? res.data.user.role, roles: res.data.user.roles ?? [res.data.user.role], permissions: res.data.user.permissions ?? [], }); nav(from, { replace: true }); } catch (e: any) { const code = e?.response?.data?.code; const retryAfterMinutes = e?.response?.data?.retryAfterMinutes; const challenge = e?.response?.data?.captcha as CaptchaChallenge | undefined; const msg = code === 'CAPTCHA_REQUIRED' ? t('auth.captchaRequired') : code === 'CAPTCHA_INVALID' ? t('auth.captchaInvalid') : code === 'ACCOUNT_LOCKED' ? t('auth.accountLocked', { minutes: typeof retryAfterMinutes === 'number' && retryAfterMinutes > 0 ? retryAfterMinutes : 1, }) : apiErrorMessage(e, t('auth.loginFailed')); setError(String(msg)); setEmailNotVerified(code === 'EMAIL_NOT_VERIFIED'); // Turnstile tokens are single-use: always remount after a failed attempt. if (code === 'CAPTCHA_REQUIRED' || code === 'CAPTCHA_INVALID' || captchaRequired) { applyCaptchaChallenge(challenge ?? null); } } finally { setLoading(false); } }; return ( {t('auth.backToPublicHome')} {t('auth.brandSubtitle')} {verifyHint && {t('auth.verifyEmailHint')}} {setupQ.data?.needsSetup && ( {t('auth.noAdminConfigured')}{' '} {t('auth.initializePlatform')} )} {error && {error}} {emailNotVerified && ( {t('auth.emailNotVerified')} )} {resendSuccess && {resendSuccess}} {devVerifyUrl && ( {t('auth.devVerifyLink')}{' '} {t('auth.openVerificationUrl')} )} setEmail(e.target.value)} autoComplete="email" fullWidth /> setPassword(e.target.value)} type={showPassword ? 'text' : 'password'} autoComplete="current-password" fullWidth slotProps={{ input: { endAdornment: ( setShowPassword((v) => !v)} edge="end" size="small" > {showPassword ? : } ), }, }} /> setTotpCode(e.target.value)} slotProps={{ htmlInput: { inputMode: 'numeric', pattern: '[0-9]*' } as any }} fullWidth /> {captchaRequired && (turnstileSiteKey || captchaQ.data?.provider === 'turnstile' || mathChallenge?.provider === 'turnstile') && (turnstileSiteKey || captchaQ.data?.siteKey || mathChallenge?.siteKey) && ( )} {captchaRequired && mathChallenge?.provider === 'math' && mathChallenge.prompt && ( setMathAnswer(e.target.value)} helperText={t('auth.captchaMathHelper')} slotProps={{ htmlInput: { inputMode: 'numeric', pattern: '[0-9]*' } as any }} fullWidth autoFocus /> )} {t('auth.forgotPassword')} {t('auth.faqLink')} {t('auth.noAccount')}{' '} {t('auth.createOne')} ); }