import { useEffect, useState } from 'react'; import { useTranslation } from 'react-i18next'; import { Link, useLocation, useNavigate, useSearchParams } from 'react-router'; import { syncAdminCookie, useAuth } from '../components/auth/AuthProvider'; import { Wordmark } from '../components/Logo'; import { Button } from '../components/ui/button'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '../components/ui/card'; import { Input } from '../components/ui/input'; import { useAuthSettings } from '../hooks/api'; import { authErrorKey } from '../lib/auth-errors'; import { getSafeRedirect, leavesThisHost, performRedirect } from '../lib/safe-redirect'; type OAuthProvider = 'google' | 'microsoft'; const providerConfig: Record = { google: { label: 'Google', icon: ( ), }, microsoft: { label: 'Microsoft', icon: ( ), }, }; export default function Login() { const { t } = useTranslation(); const navigate = useNavigate(); const location = useLocation(); const [searchParams] = useSearchParams(); const { user, isSuperAdmin, signIn, signUp } = useAuth(); const { data: authSettings } = useAuthSettings(); // Default to signup mode if on /signup route const [isSignUp, setIsSignUp] = useState(location.pathname === '/signup'); const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [name, setName] = useState(''); const [error, setError] = useState(''); const [loading, setLoading] = useState(false); const [magicLinkSent, setMagicLinkSent] = useState(false); const [verificationSent, setVerificationSent] = useState(false); const [showMagicLink, setShowMagicLink] = useState(false); // Derive enabled providers from settings const providers = authSettings?.settings?.providers; const enabledProviders = (['google', 'microsoft'] as const).filter( (provider) => providers?.[provider] ); // Why the user landed here: a failed social or magic-link sign-in, or a // sensitive action that needs a fresh sign-in. const notice = searchParams.get('reason') === 'reauth' ? t('auth.errors.reauthRequired') : searchParams.get('error') === 'magic_link' ? t('auth.errors.magicLinkFailed') : searchParams.get('error') ? t('auth.oauthFailed') : ''; const magicLinkEnabled = authSettings?.settings?.magicLinkEnabled ?? true; // Sync isSignUp state with route useEffect(() => { setIsSignUp(location.pathname === '/signup'); }, [location.pathname]); // Redirect if already logged in. Await the ForwardAuth-cookie mint first: // this effect IS the bounce path when an admin's vc-admin-token expired on // a subdomain tool (ForwardAuth 302s here with ?redirect=), so the cookie // must be set before we send the browser back. Minting needs a session // that passed two-factor while MFA is on, so for a subdomain the mint may // ask for a code first. Without the cookie, the subdomain would only send // the browser back here: go to the dashboard instead. useEffect(() => { if (user) { const safeRedirect = getSafeRedirect(searchParams.get('redirect')); const away = leavesThisHost(safeRedirect); syncAdminCookie(isSuperAdmin, { stepUp: away }).then((minted) => performRedirect(away && !minted ? '/dashboard' : safeRedirect, navigate) ); } }, [user, isSuperAdmin, navigate, searchParams]); const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); setError(''); setLoading(true); try { const safeRedirect = getSafeRedirect(searchParams.get('redirect')); // On success the session lands in the AuthProvider, and the effect // above mints the admin cookie and redirects. if (isSignUp) { const { signedIn } = await signUp(email, password, name); if (!signedIn) setVerificationSent(true); } else { const { requiresMfa } = await signIn.email(email, password); if (requiresMfa) { // Second step, keeping the intended destination navigate(`/mfa-verify?redirect=${encodeURIComponent(safeRedirect)}`); } } } catch (err) { setError(t(authErrorKey(err))); } finally { setLoading(false); } }; const handleMagicLink = async (e: React.FormEvent) => { e.preventDefault(); if (!email) return; setError(''); setLoading(true); try { await signIn.magicLink(email); setMagicLinkSent(true); } catch (err) { setError(t(authErrorKey(err, 'auth.magicLinkFailed'))); } finally { setLoading(false); } }; const handleOAuth = async (provider: OAuthProvider) => { setLoading(true); setError(''); try { await signIn[provider](); } catch (err) { setError(t(authErrorKey(err, 'auth.oauthFailed'))); setLoading(false); } }; return (
{/* Header */}
{/* Main content */}
{magicLinkSent || verificationSent ? t('auth.checkYourEmail') : isSignUp ? t('auth.createAccount') : t('auth.signIn')} {magicLinkSent ? t('auth.magicLinkSent', { email }) : verificationSent ? t('auth.verificationSent', { email }) : isSignUp ? t('auth.signUpDescription') : t('auth.signInDescription')} {magicLinkSent || verificationSent ? (

{magicLinkSent ? t('auth.magicLinkExpiry') : t('auth.verificationHint')}

) : showMagicLink ? ( <>
{error && (
{error}
)} setEmail(e.target.value)} required autoFocus />
) : ( <>
{notice && !error && (
{notice}
)} {error && (
{error}
)} {isSignUp && ( setName(e.target.value)} /> )} setEmail(e.target.value)} required autoFocus /> setPassword(e.target.value)} required minLength={8} />
{magicLinkEnabled && !isSignUp && ( )} {!isSignUp && ( {t('auth.forgotPassword')} )}
{enabledProviders.length > 0 && ( <>
{t('auth.orContinueWith')}
{enabledProviders.map((provider) => ( ))}
)}

{isSignUp ? t('auth.alreadyHaveAccount') : t('auth.dontHaveAccount')}{' '}

)}
); }