Enhance TOTP login flow
- Implement TOTP prompts during login: if login returns requires_totp, show TOTP input and verify via /auth/totp/verify to complete authentication. - Update API client to support TOTP flow, store tokens after successful TOTP verification. - Wire AuthContext and LoginPage to handle TOTP challenge, returning requiresTotp from login and proceeding after verification. - Preserve token on 401 for credential-related steps; clear only on true session-invalid responses. X-Lovable-Edit-ID: edt-0672a4fb-c58a-4d0c-88dc-86bcee853964
This commit is contained in:
@@ -2,11 +2,16 @@ import { createContext, useContext, useState, useEffect, useCallback, ReactNode
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { api, User, ApiError, tokenManager } from '@/lib/api';
|
||||
|
||||
interface LoginResult {
|
||||
requiresTotp: boolean;
|
||||
}
|
||||
|
||||
interface AuthContextType {
|
||||
user: User | null;
|
||||
isLoading: boolean;
|
||||
isAuthenticated: boolean;
|
||||
login: (email: string, password: string, rememberMe?: boolean) => Promise<void>;
|
||||
login: (email: string, password: string, rememberMe?: boolean) => Promise<LoginResult>;
|
||||
verifyTotp: (code: string, isBackupCode?: boolean) => Promise<void>;
|
||||
logout: () => Promise<void>;
|
||||
refreshUser: () => Promise<void>;
|
||||
}
|
||||
@@ -53,8 +58,24 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
checkAuth();
|
||||
}, []);
|
||||
|
||||
const login = useCallback(async (email: string, password: string, rememberMe = false) => {
|
||||
const login = useCallback(async (email: string, password: string, rememberMe = false): Promise<LoginResult> => {
|
||||
const response = await api.auth.login(email, password, rememberMe);
|
||||
|
||||
// If TOTP is required, don't set user yet - wait for TOTP verification
|
||||
if (response.requires_totp) {
|
||||
return { requiresTotp: true };
|
||||
}
|
||||
|
||||
// Login complete, set user and navigate
|
||||
if (response.user) {
|
||||
setUser(response.user);
|
||||
navigate('/profile');
|
||||
}
|
||||
return { requiresTotp: false };
|
||||
}, [navigate]);
|
||||
|
||||
const verifyTotp = useCallback(async (code: string, isBackupCode = false) => {
|
||||
const response = await api.totp.verify(code, isBackupCode);
|
||||
setUser(response.user);
|
||||
navigate('/profile');
|
||||
}, [navigate]);
|
||||
@@ -75,6 +96,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
isLoading,
|
||||
isAuthenticated: !!user,
|
||||
login,
|
||||
verifyTotp,
|
||||
logout,
|
||||
refreshUser,
|
||||
}}
|
||||
|
||||
+20
-8
@@ -45,9 +45,9 @@ export interface OrganizationsResponse {
|
||||
}
|
||||
|
||||
export interface LoginResponse {
|
||||
user: User;
|
||||
token: string;
|
||||
expires_at: string;
|
||||
user?: User;
|
||||
token?: string;
|
||||
expires_at?: string;
|
||||
requires_totp?: boolean;
|
||||
}
|
||||
|
||||
@@ -211,10 +211,13 @@ export const api = {
|
||||
const response = await request<LoginResponse>('/auth/login', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ email, password, remember_me }),
|
||||
credentials: 'include', // Required for TOTP session tracking
|
||||
}, false); // Login doesn't require auth
|
||||
|
||||
// Store token on successful login
|
||||
tokenManager.setToken(response.token, response.expires_at);
|
||||
// Only store token if login is complete (no TOTP required)
|
||||
if (response.token && response.expires_at && !response.requires_totp) {
|
||||
tokenManager.setToken(response.token, response.expires_at);
|
||||
}
|
||||
|
||||
return response;
|
||||
},
|
||||
@@ -270,11 +273,20 @@ export const api = {
|
||||
}, true, { clearTokenOn401: false }),
|
||||
|
||||
// Verify TOTP code during login (no auth required - uses session state)
|
||||
verify: (code: string, isBackupCode = false) =>
|
||||
request<TotpVerifyResponse>('/auth/totp/verify', {
|
||||
verify: async (code: string, isBackupCode = false): Promise<TotpVerifyResponse> => {
|
||||
const response = await request<TotpVerifyResponse>('/auth/totp/verify', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ code, is_backup_code: isBackupCode }),
|
||||
}, false),
|
||||
credentials: 'include', // Required for TOTP session tracking
|
||||
}, false);
|
||||
|
||||
// Store token after successful TOTP verification
|
||||
if (response.token && response.expires_at) {
|
||||
tokenManager.setToken(response.token, response.expires_at);
|
||||
}
|
||||
|
||||
return response;
|
||||
},
|
||||
|
||||
// Get TOTP status
|
||||
status: () =>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useState } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
import { Mail, Lock, ArrowRight, Fingerprint } from "lucide-react";
|
||||
import { Mail, Lock, ArrowRight, Fingerprint, ArrowLeft, ShieldCheck } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
@@ -9,23 +9,37 @@ import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { useAuth } from "@/contexts/AuthContext";
|
||||
import { ApiError } from "@/lib/api";
|
||||
import { useToast } from "@/hooks/use-toast";
|
||||
import {
|
||||
InputOTP,
|
||||
InputOTPGroup,
|
||||
InputOTPSlot,
|
||||
} from "@/components/ui/input-otp";
|
||||
|
||||
type LoginStep = 'credentials' | 'totp';
|
||||
|
||||
export default function LoginPage() {
|
||||
const { login } = useAuth();
|
||||
const { login, verifyTotp } = useAuth();
|
||||
const { toast } = useToast();
|
||||
const [email, setEmail] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [rememberMe, setRememberMe] = useState(false);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [step, setStep] = useState<LoginStep>('credentials');
|
||||
const [totpCode, setTotpCode] = useState("");
|
||||
const [useBackupCode, setUseBackupCode] = useState(false);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setIsLoading(true);
|
||||
|
||||
try {
|
||||
await login(email, password, rememberMe);
|
||||
const result = await login(email, password, rememberMe);
|
||||
if (result.requiresTotp) {
|
||||
setStep('totp');
|
||||
setTotpCode("");
|
||||
}
|
||||
// If no TOTP required, navigation happens in AuthContext
|
||||
} catch (error) {
|
||||
// Log to console in dev mode for easier debugging
|
||||
if (import.meta.env.DEV) {
|
||||
console.error("[Gatehouse] Login failed:", error);
|
||||
}
|
||||
@@ -46,6 +60,149 @@ export default function LoginPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const handleTotpSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
if (totpCode.length < 6) {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Invalid code",
|
||||
description: "Please enter your complete verification code.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
|
||||
try {
|
||||
await verifyTotp(totpCode, useBackupCode);
|
||||
// Navigation happens in AuthContext
|
||||
} catch (error) {
|
||||
if (import.meta.env.DEV) {
|
||||
console.error("[Gatehouse] TOTP verification failed:", error);
|
||||
}
|
||||
|
||||
const message = error instanceof ApiError
|
||||
? error.message
|
||||
: import.meta.env.DEV && error instanceof Error
|
||||
? error.message
|
||||
: "Invalid verification code";
|
||||
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Verification failed",
|
||||
description: message,
|
||||
});
|
||||
setTotpCode("");
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleBackToCredentials = () => {
|
||||
setStep('credentials');
|
||||
setTotpCode("");
|
||||
setUseBackupCode(false);
|
||||
};
|
||||
|
||||
// Auto-submit when OTP is complete
|
||||
const handleOtpChange = (value: string) => {
|
||||
setTotpCode(value);
|
||||
if (value.length === 6 && !useBackupCode) {
|
||||
// Small delay to allow the UI to update before submitting
|
||||
setTimeout(() => {
|
||||
const form = document.getElementById('totp-form') as HTMLFormElement;
|
||||
if (form) form.requestSubmit();
|
||||
}, 100);
|
||||
}
|
||||
};
|
||||
|
||||
// TOTP verification step
|
||||
if (step === 'totp') {
|
||||
return (
|
||||
<div className="auth-card">
|
||||
<div className="text-center mb-8">
|
||||
<div className="mx-auto w-12 h-12 rounded-full bg-primary/10 flex items-center justify-center mb-4">
|
||||
<ShieldCheck className="w-6 h-6 text-primary" />
|
||||
</div>
|
||||
<h1 className="text-2xl font-semibold text-foreground tracking-tight">
|
||||
Two-factor authentication
|
||||
</h1>
|
||||
<p className="text-muted-foreground mt-2">
|
||||
Enter the 6-digit code from your authenticator app
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<form id="totp-form" onSubmit={handleTotpSubmit} className="space-y-6">
|
||||
{useBackupCode ? (
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="backup-code">Backup code</Label>
|
||||
<Input
|
||||
id="backup-code"
|
||||
type="text"
|
||||
placeholder="Enter 16-character backup code"
|
||||
value={totpCode}
|
||||
onChange={(e) => setTotpCode(e.target.value.toUpperCase())}
|
||||
className="text-center font-mono tracking-widest"
|
||||
maxLength={16}
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex justify-center">
|
||||
<InputOTP
|
||||
maxLength={6}
|
||||
value={totpCode}
|
||||
onChange={handleOtpChange}
|
||||
autoFocus
|
||||
>
|
||||
<InputOTPGroup>
|
||||
<InputOTPSlot index={0} />
|
||||
<InputOTPSlot index={1} />
|
||||
<InputOTPSlot index={2} />
|
||||
<InputOTPSlot index={3} />
|
||||
<InputOTPSlot index={4} />
|
||||
<InputOTPSlot index={5} />
|
||||
</InputOTPGroup>
|
||||
</InputOTP>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Button type="submit" className="w-full" disabled={isLoading}>
|
||||
{isLoading ? (
|
||||
"Verifying..."
|
||||
) : (
|
||||
<>
|
||||
Verify
|
||||
<ArrowRight className="w-4 h-4 ml-2" />
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
<div className="mt-6 space-y-3">
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="w-full text-muted-foreground"
|
||||
onClick={() => setUseBackupCode(!useBackupCode)}
|
||||
>
|
||||
{useBackupCode ? "Use authenticator app" : "Use a backup code instead"}
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="w-full text-muted-foreground"
|
||||
onClick={handleBackToCredentials}
|
||||
>
|
||||
<ArrowLeft className="w-4 h-4 mr-2" />
|
||||
Back to sign in
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Credentials step (default)
|
||||
return (
|
||||
<div className="auth-card">
|
||||
<div className="text-center mb-8">
|
||||
|
||||
Reference in New Issue
Block a user