games_app/prediqo_web/src/features/auth/LoginPage.tsx
2026-11-15 19:48:21 +02:00

423 lines
15 KiB
TypeScript

/**
* 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<string | null>(null);
const [emailNotVerified, setEmailNotVerified] = useState(false);
const [resendLoading, setResendLoading] = useState(false);
const [resendSuccess, setResendSuccess] = useState<string | null>(null);
const [devVerifyUrl, setDevVerifyUrl] = useState<string | null>(null);
const [captchaToken, setCaptchaToken] = useState<string | null>(null);
const [captchaRequired, setCaptchaRequired] = useState(false);
const [mathChallenge, setMathChallenge] = useState<CaptchaChallenge | null>(null);
const [mathAnswer, setMathAnswer] = useState('');
const [turnstileSiteKey, setTurnstileSiteKey] = useState<string | null>(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<CaptchaConfig>('/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<CaptchaChallenge>('/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 <Navigate to={typeof from === 'string' ? from : '/home'} replace />;
}
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<LoginResponse>('/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 (
<Box sx={{ minHeight: '100vh', display: 'grid', placeItems: 'center', px: 2, position: 'relative' }}>
<Box
sx={{
position: 'absolute',
top: 16,
left: 16,
right: 16,
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
gap: 1,
zIndex: 1,
}}
>
<Link
component={RouterLink}
to="/"
underline="hover"
sx={{
display: 'inline-flex',
alignItems: 'center',
gap: 0.75,
fontWeight: 700,
fontSize: '0.9rem',
}}
>
<ArrowBackRoundedIcon fontSize="small" />
{t('auth.backToPublicHome')}
</Link>
<LanguageSwitcher />
</Box>
<Card sx={{ width: '100%', maxWidth: 520, mt: { xs: 5, sm: 0 } }}>
<CardContent>
<Box
component={RouterLink}
to="/"
aria-label={t('auth.backToPublicHome')}
sx={{ textDecoration: 'none', color: 'inherit', display: 'inline-flex' }}
>
<PrediqoLogo size={48} />
</Box>
<Typography sx={{ opacity: 0.75, mt: 1.25 }}>{t('auth.brandSubtitle')}</Typography>
<Stack spacing={2} sx={{ mt: 3 }}>
{verifyHint && <Alert severity="info">{t('auth.verifyEmailHint')}</Alert>}
{setupQ.data?.needsSetup && (
<Alert severity="warning">
{t('auth.noAdminConfigured')}{' '}
<Link component={RouterLink} to="/setup">
{t('auth.initializePlatform')}
</Link>
</Alert>
)}
{error && <Alert severity="error">{error}</Alert>}
{emailNotVerified && (
<Alert severity="warning">
<Typography variant="body2" sx={{ mb: 1 }}>
{t('auth.emailNotVerified')}
</Typography>
<Button
size="small"
variant="outlined"
onClick={resendVerification}
disabled={resendLoading || !email.trim()}
>
{resendLoading ? t('common.sending') : t('auth.resendVerification')}
</Button>
</Alert>
)}
{resendSuccess && <Alert severity="success">{resendSuccess}</Alert>}
{devVerifyUrl && (
<Alert severity="info">
{t('auth.devVerifyLink')}{' '}
<Link href={devVerifyUrl} target="_blank" rel="noreferrer">
{t('auth.openVerificationUrl')}
</Link>
</Alert>
)}
<TextField
label={t('common.email')}
value={email}
onChange={(e) => setEmail(e.target.value)}
autoComplete="email"
fullWidth
/>
<TextField
label={t('common.password')}
value={password}
onChange={(e) => setPassword(e.target.value)}
type={showPassword ? 'text' : 'password'}
autoComplete="current-password"
fullWidth
slotProps={{
input: {
endAdornment: (
<InputAdornment position="end">
<IconButton
aria-label={showPassword ? t('common.hidePassword') : t('common.showPassword')}
onClick={() => setShowPassword((v) => !v)}
edge="end"
size="small"
>
{showPassword ? <VisibilityOffRoundedIcon /> : <VisibilityRoundedIcon />}
</IconButton>
</InputAdornment>
),
},
}}
/>
<TextField
label={t('auth.totpOptional')}
value={totpCode}
onChange={(e) => 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) && (
<TurnstileWidget
key={turnstileMountKey}
siteKey={
(turnstileSiteKey || mathChallenge?.siteKey || captchaQ.data?.siteKey)!
}
onToken={onCaptchaToken}
/>
)}
{captchaRequired && mathChallenge?.provider === 'math' && mathChallenge.prompt && (
<TextField
label={t('auth.captchaMathLabel', { prompt: mathChallenge.prompt })}
value={mathAnswer}
onChange={(e) => setMathAnswer(e.target.value)}
helperText={t('auth.captchaMathHelper')}
slotProps={{ htmlInput: { inputMode: 'numeric', pattern: '[0-9]*' } as any }}
fullWidth
autoFocus
/>
)}
<Button variant="contained" onClick={submit} disabled={loading}>
{loading ? t('auth.signingIn') : t('auth.signIn')}
</Button>
<Typography variant="body2" sx={{ textAlign: 'center', opacity: 0.8 }}>
<Link component={RouterLink} to="/forgot-password">
{t('auth.forgotPassword')}
</Link>
</Typography>
<Typography variant="body2" sx={{ textAlign: 'center', opacity: 0.8 }}>
<Link component={RouterLink} to="/faq">
{t('auth.faqLink')}
</Link>
</Typography>
<Typography variant="body2" sx={{ textAlign: 'center', opacity: 0.8 }}>
{t('auth.noAccount')}{' '}
<Link component={RouterLink} to="/register">
{t('auth.createOne')}
</Link>
</Typography>
</Stack>
</CardContent>
</Card>
</Box>
);
}