feat(auth): add TOTP 2FA setup and login verification
Some checks failed
CI / test (push) Failing after 21s

- add user twofa fields and migration

- add 2FA setup/enable/disable endpoints

- enforce OTP on login when 2FA enabled

- add web login OTP field and settings UI
This commit is contained in:
2026-03-08 11:43:51 +03:00
parent e685a38be6
commit 27d3340a37
12 changed files with 287 additions and 7 deletions

View File

@@ -5,8 +5,8 @@ export async function registerRequest(email: string, name: string, username: str
await http.post("/auth/register", { email, name, username, password });
}
export async function loginRequest(email: string, password: string): Promise<TokenPair> {
const { data } = await http.post<TokenPair>("/auth/login", { email, password });
export async function loginRequest(email: string, password: string, otpCode?: string): Promise<TokenPair> {
const { data } = await http.post<TokenPair>("/auth/login", { email, password, otp_code: otpCode || undefined });
return data;
}
@@ -32,3 +32,21 @@ export async function revokeSession(jti: string): Promise<void> {
export async function revokeAllSessions(): Promise<void> {
await http.delete("/auth/sessions");
}
export interface TwoFactorSetupResponse {
secret: string;
otpauth_url: string;
}
export async function setupTwoFactor(): Promise<TwoFactorSetupResponse> {
const { data } = await http.post<TwoFactorSetupResponse>("/auth/2fa/setup");
return data;
}
export async function enableTwoFactor(code: string): Promise<void> {
await http.post("/auth/2fa/enable", { code });
}
export async function disableTwoFactor(code: string): Promise<void> {
await http.post("/auth/2fa/disable", { code });
}

View File

@@ -77,6 +77,7 @@ export interface AuthUser {
bio?: string | null;
avatar_url: string | null;
email_verified: boolean;
twofa_enabled?: boolean;
allow_private_messages: boolean;
created_at: string;
updated_at: string;

View File

@@ -12,6 +12,7 @@ export function AuthPanel() {
const [name, setName] = useState("");
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [otpCode, setOtpCode] = useState("");
const [error, setError] = useState<string | null>(null);
const [success, setSuccess] = useState<string | null>(null);
@@ -26,7 +27,7 @@ export function AuthPanel() {
setMode("login");
return;
}
await login(email, password);
await login(email, password, otpCode.trim() || undefined);
} catch {
setError("Auth request failed.");
}
@@ -51,6 +52,14 @@ export function AuthPanel() {
</>
)}
<input className="w-full rounded bg-slate-800 px-3 py-2" placeholder="Password" type="password" value={password} onChange={(e) => setPassword(e.target.value)} />
{mode === "login" ? (
<input
className="w-full rounded bg-slate-800 px-3 py-2"
placeholder="2FA code (if enabled)"
value={otpCode}
onChange={(e) => setOtpCode(e.target.value.replace(/\D/g, "").slice(0, 8))}
/>
) : null}
<button className="w-full rounded bg-accent px-3 py-2 font-semibold text-black disabled:opacity-50" disabled={loading} type="submit">
{mode === "login" ? "Sign in" : "Create account"}
</button>

View File

@@ -1,7 +1,7 @@
import { useEffect, useMemo, useState } from "react";
import { createPortal } from "react-dom";
import { listBlockedUsers, updateMyProfile } from "../api/users";
import { listSessions, revokeAllSessions, revokeSession } from "../api/auth";
import { disableTwoFactor, enableTwoFactor, listSessions, revokeAllSessions, revokeSession, setupTwoFactor } from "../api/auth";
import type { AuthSession, AuthUser } from "../chat/types";
import { useAuthStore } from "../store/authStore";
import { AppPreferences, getAppPreferences, updateAppPreferences } from "../utils/preferences";
@@ -22,6 +22,10 @@ export function SettingsPanel({ open, onClose }: Props) {
const [allowPrivateMessages, setAllowPrivateMessages] = useState(true);
const [sessions, setSessions] = useState<AuthSession[]>([]);
const [sessionsLoading, setSessionsLoading] = useState(false);
const [twofaCode, setTwofaCode] = useState("");
const [twofaSecret, setTwofaSecret] = useState<string | null>(null);
const [twofaUrl, setTwofaUrl] = useState<string | null>(null);
const [twofaError, setTwofaError] = useState<string | null>(null);
const [profileDraft, setProfileDraft] = useState({
name: "",
username: "",
@@ -285,6 +289,91 @@ export function SettingsPanel({ open, onClose }: Props) {
disabled={savingPrivacy}
/>
</section>
<section className="rounded border border-slate-700/70 bg-slate-800/50 p-3">
<div className="mb-2 flex items-center justify-between">
<p className="text-xs uppercase tracking-wide text-slate-400">Two-Factor Authentication</p>
<span className="text-[11px] text-slate-400">{me.twofa_enabled ? "Enabled" : "Disabled"}</span>
</div>
{!me.twofa_enabled ? (
<>
<button
className="mb-2 rounded bg-slate-700 px-2 py-1 text-xs"
onClick={async () => {
setTwofaError(null);
try {
const setup = await setupTwoFactor();
setTwofaSecret(setup.secret);
setTwofaUrl(setup.otpauth_url);
} catch {
setTwofaError("Failed to setup 2FA");
}
}}
type="button"
>
Generate secret
</button>
{twofaSecret ? (
<div className="mb-2 rounded bg-slate-900/50 px-2 py-2">
<p className="text-[11px] text-slate-400">Secret</p>
<p className="break-all text-xs text-slate-200">{twofaSecret}</p>
{twofaUrl ? <p className="mt-1 break-all text-[11px] text-slate-500">{twofaUrl}</p> : null}
</div>
) : null}
<div className="flex gap-2">
<input
className="w-full rounded bg-slate-800 px-2 py-1.5 text-xs"
placeholder="Enter app code"
value={twofaCode}
onChange={(e) => setTwofaCode(e.target.value.replace(/\D/g, "").slice(0, 8))}
/>
<button
className="rounded bg-sky-500 px-2 py-1 text-xs font-semibold text-slate-950"
onClick={async () => {
setTwofaError(null);
try {
await enableTwoFactor(twofaCode);
await useAuthStore.getState().loadMe();
setTwofaCode("");
} catch {
setTwofaError("Invalid 2FA code");
}
}}
type="button"
>
Enable
</button>
</div>
</>
) : (
<div className="flex gap-2">
<input
className="w-full rounded bg-slate-800 px-2 py-1.5 text-xs"
placeholder="Code to disable"
value={twofaCode}
onChange={(e) => setTwofaCode(e.target.value.replace(/\D/g, "").slice(0, 8))}
/>
<button
className="rounded bg-red-500 px-2 py-1 text-xs font-semibold text-white"
onClick={async () => {
setTwofaError(null);
try {
await disableTwoFactor(twofaCode);
await useAuthStore.getState().loadMe();
setTwofaCode("");
setTwofaSecret(null);
setTwofaUrl(null);
} catch {
setTwofaError("Invalid 2FA code");
}
}}
type="button"
>
Disable
</button>
</div>
)}
{twofaError ? <p className="mt-2 text-xs text-red-400">{twofaError}</p> : null}
</section>
<section className="rounded border border-slate-700/70 bg-slate-800/50 p-3">
<div className="mb-2 flex items-center justify-between">
<p className="text-xs uppercase tracking-wide text-slate-400">Active Sessions</p>

View File

@@ -8,7 +8,7 @@ interface AuthState {
me: AuthUser | null;
loading: boolean;
setTokens: (accessToken: string, refreshToken: string) => void;
login: (email: string, password: string) => Promise<void>;
login: (email: string, password: string, otpCode?: string) => Promise<void>;
loadMe: () => Promise<void>;
refresh: () => Promise<void>;
logout: () => void;
@@ -27,10 +27,10 @@ export const useAuthStore = create<AuthState>((set, get) => ({
localStorage.setItem(REFRESH_KEY, refreshToken);
set({ accessToken, refreshToken });
},
login: async (email, password) => {
login: async (email, password, otpCode) => {
set({ loading: true });
try {
const data = await loginRequest(email, password);
const data = await loginRequest(email, password, otpCode);
get().setTokens(data.access_token, data.refresh_token);
await get().loadMe();
} finally {