mirror of
https://github.com/maziggy/bambuddy.git
synced 2026-10-09 07:25:44 +02:00
feat: Two-Factor Authentication (TOTP, Email OTP) and OIDC/SSO – full implementation with admin UI (#933)
feat: Two-Factor Authentication (TOTP, Email OTP) and OIDC/SSO – full implementation with admin UI (#933)
This commit is contained in:
@@ -0,0 +1,344 @@
|
||||
import { useState } from 'react';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { Plus, Edit2, Trash2, Globe, Check, X, RefreshCw, ExternalLink } from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { api } from '../api/client';
|
||||
import type { OIDCProvider, OIDCProviderCreate } from '../api/client';
|
||||
import { Card, CardContent, CardHeader } from './Card';
|
||||
import { Button } from './Button';
|
||||
import { Toggle } from './Toggle';
|
||||
import { ConfirmModal } from './ConfirmModal';
|
||||
import { useToast } from '../contexts/ToastContext';
|
||||
|
||||
const EMPTY_FORM: OIDCProviderCreate = {
|
||||
name: '',
|
||||
issuer_url: '',
|
||||
client_id: '',
|
||||
client_secret: '',
|
||||
scopes: 'openid email profile',
|
||||
is_enabled: true,
|
||||
auto_create_users: false,
|
||||
icon_url: undefined,
|
||||
};
|
||||
|
||||
// ─── Provider form (create / edit) ───────────────────────────────────────────
|
||||
function ProviderForm({
|
||||
initial,
|
||||
isEdit = false,
|
||||
onSave,
|
||||
onCancel,
|
||||
isPending,
|
||||
}: {
|
||||
initial: OIDCProviderCreate;
|
||||
isEdit?: boolean;
|
||||
onSave: (data: OIDCProviderCreate) => void;
|
||||
onCancel: () => void;
|
||||
isPending: boolean;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const [form, setForm] = useState<OIDCProviderCreate>(initial);
|
||||
const [secretChanged, setSecretChanged] = useState(false);
|
||||
const set = (key: keyof OIDCProviderCreate, value: unknown) =>
|
||||
setForm((prev) => ({ ...prev, [key]: value }));
|
||||
|
||||
const inputCls =
|
||||
'w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors text-sm';
|
||||
const labelCls = 'block text-sm font-medium text-white mb-1';
|
||||
|
||||
const handleSave = () => {
|
||||
const payload = { ...form };
|
||||
if (isEdit && !secretChanged) {
|
||||
delete (payload as Partial<OIDCProviderCreate>).client_secret;
|
||||
}
|
||||
onSave(payload);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className={labelCls}>{t('settings.oidc.form.name')} <span className="text-red-400">*</span></label>
|
||||
<input className={inputCls} value={form.name} onChange={(e) => set('name', e.target.value)} placeholder="Google" />
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>{t('settings.oidc.form.issuerUrl')} <span className="text-red-400">*</span></label>
|
||||
<input className={inputCls} value={form.issuer_url} onChange={(e) => set('issuer_url', e.target.value)} placeholder="https://accounts.google.com" />
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>{t('settings.oidc.form.clientId')} <span className="text-red-400">*</span></label>
|
||||
<input className={inputCls} value={form.client_id} onChange={(e) => set('client_id', e.target.value)} placeholder="your-client-id" />
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>
|
||||
{t('settings.oidc.form.clientSecret')}
|
||||
{!isEdit && <span className="text-red-400"> *</span>}
|
||||
{isEdit && <span className="text-bambu-gray text-xs ml-1">({t('settings.oidc.form.secretHint')})</span>}
|
||||
</label>
|
||||
<input
|
||||
className={inputCls}
|
||||
type="password"
|
||||
value={secretChanged ? form.client_secret : ''}
|
||||
placeholder={isEdit && !secretChanged ? '••••••••' : t('settings.oidc.form.secretPlaceholder')}
|
||||
onChange={(e) => {
|
||||
setSecretChanged(true);
|
||||
set('client_secret', e.target.value);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>{t('settings.oidc.form.scopes')}</label>
|
||||
<input className={inputCls} value={form.scopes} onChange={(e) => set('scopes', e.target.value)} placeholder="openid email profile" />
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>{t('settings.oidc.form.iconUrl')}</label>
|
||||
<input className={inputCls} value={form.icon_url ?? ''} onChange={(e) => set('icon_url', e.target.value || undefined)} placeholder="https://..." />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap gap-6 pt-2">
|
||||
<label className="flex items-center gap-3 cursor-pointer">
|
||||
<Toggle checked={form.is_enabled ?? true} onChange={(v) => set('is_enabled', v)} />
|
||||
<span className="text-white text-sm">{t('settings.oidc.form.enabled')}</span>
|
||||
</label>
|
||||
<label className="flex items-center gap-3 cursor-pointer">
|
||||
<Toggle checked={form.auto_create_users ?? false} onChange={(v) => set('auto_create_users', v)} />
|
||||
<div>
|
||||
<p className="text-white text-sm">{t('settings.oidc.form.autoCreate')}</p>
|
||||
<p className="text-bambu-gray text-xs">{t('settings.oidc.form.autoCreateDesc')}</p>
|
||||
</div>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-3 pt-2">
|
||||
<Button variant="secondary" onClick={onCancel} className="flex-1">
|
||||
{t('common.cancel')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="primary"
|
||||
className="flex-1"
|
||||
disabled={!form.name || !form.issuer_url || !form.client_id || (!isEdit && !form.client_secret) || (isEdit && secretChanged && !form.client_secret) || isPending}
|
||||
onClick={handleSave}
|
||||
>
|
||||
{isPending ? t('common.saving') : t('common.save')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Main component ───────────────────────────────────────────────────────────
|
||||
export function OIDCProviderSettings() {
|
||||
const { t } = useTranslation();
|
||||
const queryClient = useQueryClient();
|
||||
const { showToast } = useToast();
|
||||
|
||||
const [showCreate, setShowCreate] = useState(false);
|
||||
const [editingId, setEditingId] = useState<number | null>(null);
|
||||
const [deleteTarget, setDeleteTarget] = useState<OIDCProvider | null>(null);
|
||||
|
||||
const { data: providers, isLoading } = useQuery({
|
||||
queryKey: ['oidc-providers-all'],
|
||||
queryFn: () => api.getOIDCProvidersAll(),
|
||||
});
|
||||
|
||||
const createMutation = useMutation({
|
||||
mutationFn: (data: OIDCProviderCreate) => api.createOIDCProvider(data),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['oidc-providers-all'] });
|
||||
setShowCreate(false);
|
||||
showToast(t('settings.oidc.created'), 'success');
|
||||
},
|
||||
onError: (e: Error) => showToast(e.message, 'error'),
|
||||
});
|
||||
|
||||
const updateMutation = useMutation({
|
||||
mutationFn: ({ id, data }: { id: number; data: Partial<OIDCProviderCreate> }) =>
|
||||
api.updateOIDCProvider(id, data),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['oidc-providers-all'] });
|
||||
setEditingId(null);
|
||||
showToast(t('settings.oidc.updated'), 'success');
|
||||
},
|
||||
onError: (e: Error) => showToast(e.message, 'error'),
|
||||
});
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: (id: number) => api.deleteOIDCProvider(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['oidc-providers-all'] });
|
||||
setDeleteTarget(null);
|
||||
showToast(t('settings.oidc.deleted'), 'success');
|
||||
},
|
||||
onError: (e: Error) => showToast(e.message, 'error'),
|
||||
});
|
||||
|
||||
const toggleEnabled = (provider: OIDCProvider) =>
|
||||
updateMutation.mutate({ id: provider.id, data: { is_enabled: !provider.is_enabled } });
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<RefreshCw className="w-6 h-6 animate-spin text-bambu-green" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Header */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h3 className="text-white font-semibold">{t('settings.oidc.title')}</h3>
|
||||
<p className="text-bambu-gray text-sm">{t('settings.oidc.desc')}</p>
|
||||
</div>
|
||||
{!showCreate && (
|
||||
<Button variant="primary" size="sm" onClick={() => setShowCreate(true)} className="flex items-center gap-2">
|
||||
<Plus className="w-4 h-4" />
|
||||
{t('settings.oidc.addProvider')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</CardHeader>
|
||||
|
||||
{showCreate && (
|
||||
<CardContent>
|
||||
<div className="border-t border-bambu-dark-tertiary pt-4">
|
||||
<h4 className="text-white font-medium mb-4">{t('settings.oidc.newProvider')}</h4>
|
||||
<ProviderForm
|
||||
initial={EMPTY_FORM}
|
||||
onSave={(data) => createMutation.mutate(data)}
|
||||
onCancel={() => setShowCreate(false)}
|
||||
isPending={createMutation.isPending}
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
{/* Provider list */}
|
||||
{providers && providers.length === 0 && !showCreate && (
|
||||
<Card>
|
||||
<CardContent>
|
||||
<div className="text-center py-8 space-y-3">
|
||||
<Globe className="w-12 h-12 text-bambu-gray mx-auto" />
|
||||
<p className="text-bambu-gray">{t('settings.oidc.empty')}</p>
|
||||
<Button variant="primary" size="sm" onClick={() => setShowCreate(true)} className="inline-flex items-center gap-2">
|
||||
<Plus className="w-4 h-4" />
|
||||
{t('settings.oidc.addProvider')}
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{providers?.map((provider) => (
|
||||
<Card key={provider.id}>
|
||||
<CardHeader>
|
||||
<div className="flex items-center gap-3">
|
||||
{provider.icon_url ? (
|
||||
<img src={provider.icon_url} alt={provider.name} className="w-8 h-8 rounded object-contain" onError={(e) => { (e.target as HTMLImageElement).style.display = 'none'; }} />
|
||||
) : (
|
||||
<div className="w-8 h-8 rounded-full bg-bambu-dark-tertiary flex items-center justify-center">
|
||||
<Globe className="w-4 h-4 text-bambu-gray" />
|
||||
</div>
|
||||
)}
|
||||
<div className="flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<h4 className="text-white font-medium">{provider.name}</h4>
|
||||
{provider.is_enabled ? (
|
||||
<span className="flex items-center gap-1 text-xs text-green-400 bg-green-400/10 px-2 py-0.5 rounded-full">
|
||||
<Check className="w-3 h-3" /> {t('common.enabled')}
|
||||
</span>
|
||||
) : (
|
||||
<span className="flex items-center gap-1 text-xs text-bambu-gray bg-bambu-dark-tertiary px-2 py-0.5 rounded-full">
|
||||
<X className="w-3 h-3" /> {t('common.disabled')}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-1 text-bambu-gray text-xs mt-0.5">
|
||||
<ExternalLink className="w-3 h-3" />
|
||||
<span>{provider.issuer_url}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Toggle
|
||||
checked={provider.is_enabled}
|
||||
onChange={() => toggleEnabled(provider)}
|
||||
disabled={updateMutation.isPending}
|
||||
/>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={() => setEditingId(editingId === provider.id ? null : provider.id)}
|
||||
>
|
||||
<Edit2 className="w-4 h-4" />
|
||||
</Button>
|
||||
<Button variant="danger" size="sm" onClick={() => setDeleteTarget(provider)}>
|
||||
<Trash2 className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
|
||||
{editingId === provider.id && (
|
||||
<CardContent>
|
||||
<div className="border-t border-bambu-dark-tertiary pt-4">
|
||||
<ProviderForm
|
||||
isEdit={true}
|
||||
initial={{
|
||||
name: provider.name,
|
||||
issuer_url: provider.issuer_url,
|
||||
client_id: provider.client_id,
|
||||
client_secret: '',
|
||||
scopes: provider.scopes,
|
||||
is_enabled: provider.is_enabled,
|
||||
auto_create_users: provider.auto_create_users,
|
||||
icon_url: provider.icon_url ?? undefined,
|
||||
}}
|
||||
onSave={(data) => updateMutation.mutate({ id: provider.id, data })}
|
||||
onCancel={() => setEditingId(null)}
|
||||
isPending={updateMutation.isPending}
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
)}
|
||||
|
||||
{editingId !== provider.id && (
|
||||
<CardContent>
|
||||
<dl className="grid grid-cols-2 sm:grid-cols-3 gap-x-6 gap-y-2 text-sm">
|
||||
<div>
|
||||
<dt className="text-bambu-gray">{t('settings.oidc.form.clientId')}</dt>
|
||||
<dd className="text-white font-mono truncate">{provider.client_id}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-bambu-gray">{t('settings.oidc.form.scopes')}</dt>
|
||||
<dd className="text-white">{provider.scopes}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-bambu-gray">{t('settings.oidc.form.autoCreate')}</dt>
|
||||
<dd className={provider.auto_create_users ? 'text-green-400' : 'text-bambu-gray'}>
|
||||
{provider.auto_create_users ? t('common.yes') : t('common.no')}
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</CardContent>
|
||||
)}
|
||||
</Card>
|
||||
))}
|
||||
|
||||
{/* Delete confirm */}
|
||||
{deleteTarget && (
|
||||
<ConfirmModal
|
||||
title={t('settings.oidc.deleteTitle')}
|
||||
message={t('settings.oidc.deleteMessage', { name: deleteTarget.name })}
|
||||
confirmText={t('common.delete')}
|
||||
variant="danger"
|
||||
onConfirm={() => deleteMutation.mutate(deleteTarget.id)}
|
||||
onCancel={() => setDeleteTarget(null)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,547 @@
|
||||
import { useState } from 'react';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { ShieldCheck, ShieldOff, Mail, Smartphone, Key, RefreshCw, Trash2, X, Eye, EyeOff, Copy } from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { api } from '../api/client';
|
||||
import { Card, CardContent, CardHeader } from './Card';
|
||||
import { Button } from './Button';
|
||||
import { useToast } from '../contexts/ToastContext';
|
||||
import { useAuth } from '../contexts/AuthContext';
|
||||
|
||||
// ─── Small reusable code input ────────────────────────────────────────────────
|
||||
function CodeInput({
|
||||
value,
|
||||
onChange,
|
||||
placeholder,
|
||||
maxLength = 6,
|
||||
}: {
|
||||
value: string;
|
||||
onChange: (v: string) => void;
|
||||
placeholder?: string;
|
||||
maxLength?: number;
|
||||
}) {
|
||||
return (
|
||||
<input
|
||||
type="text"
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value.toUpperCase().replace(/\s/g, ''))}
|
||||
maxLength={maxLength}
|
||||
className="w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors font-mono tracking-widest text-center"
|
||||
placeholder={placeholder}
|
||||
autoComplete="one-time-code"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Backup codes display ─────────────────────────────────────────────────────
|
||||
function BackupCodesDisplay({ codes, onDone }: { codes: string[]; onDone: () => void }) {
|
||||
const { t } = useTranslation();
|
||||
const [copied, setCopied] = useState(false);
|
||||
|
||||
const handleCopy = () => {
|
||||
navigator.clipboard.writeText(codes.join('\n'));
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 2000);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="bg-amber-500/10 border border-amber-500/30 rounded-lg p-4">
|
||||
<p className="text-amber-400 text-sm font-medium">{t('settings.twoFa.backupCodesWarning')}</p>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
{codes.map((code, index) => (
|
||||
<code key={index} className="bg-bambu-dark-secondary rounded px-3 py-2 text-center font-mono text-sm text-white tracking-widest">
|
||||
{code}
|
||||
</code>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex gap-3">
|
||||
<Button variant="secondary" size="sm" onClick={handleCopy} className="flex items-center gap-2">
|
||||
<Copy className="w-4 h-4" />
|
||||
{copied ? t('common.copied') : t('common.copy')}
|
||||
</Button>
|
||||
<Button variant="primary" size="sm" onClick={onDone} className="flex-1">
|
||||
{t('settings.twoFa.savedCodes')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── TOTP setup wizard ────────────────────────────────────────────────────────
|
||||
function TOTPSetupWizard({ onDone }: { onDone: () => void }) {
|
||||
const { t } = useTranslation();
|
||||
const queryClient = useQueryClient();
|
||||
const { showToast } = useToast();
|
||||
const [step, setStep] = useState<'qr' | 'confirm' | 'backup'>('qr');
|
||||
const [code, setCode] = useState('');
|
||||
const [backupCodes, setBackupCodes] = useState<string[]>([]);
|
||||
const [showSecret, setShowSecret] = useState(false);
|
||||
|
||||
const { data: setupData, isLoading } = useQuery({
|
||||
queryKey: ['totp-setup'],
|
||||
queryFn: () => api.setupTOTP(),
|
||||
staleTime: Infinity,
|
||||
});
|
||||
|
||||
const enableMutation = useMutation({
|
||||
mutationFn: (c: string) => api.enableTOTP(c),
|
||||
onSuccess: (data) => {
|
||||
setBackupCodes(data.backup_codes);
|
||||
setStep('backup');
|
||||
queryClient.invalidateQueries({ queryKey: ['2fa-status'] });
|
||||
},
|
||||
onError: () => showToast(t('settings.twoFa.invalidCode'), 'error'),
|
||||
});
|
||||
|
||||
if (isLoading || !setupData) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<RefreshCw className="w-6 h-6 animate-spin text-bambu-green" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (step === 'qr') {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<p className="text-bambu-gray-light text-sm">{t('settings.twoFa.setupInstructions')}</p>
|
||||
<div className="flex justify-center">
|
||||
<img
|
||||
src={`data:image/png;base64,${setupData.qr_code_b64}`}
|
||||
alt="TOTP QR Code"
|
||||
className="w-48 h-48 rounded-lg"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-xs text-bambu-gray mb-1">{t('settings.twoFa.manualEntry')}</p>
|
||||
<div className="flex items-center gap-2 bg-bambu-dark-secondary rounded-lg px-3 py-2">
|
||||
<code className="text-white text-xs font-mono flex-1 break-all">
|
||||
{showSecret ? setupData.secret : '••••••••••••••••'}
|
||||
</code>
|
||||
<button onClick={() => setShowSecret(!showSecret)} className="text-bambu-gray hover:text-white">
|
||||
{showSecret ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => { navigator.clipboard.writeText(setupData.secret); }}
|
||||
className="text-bambu-gray hover:text-white"
|
||||
>
|
||||
<Copy className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<Button variant="primary" className="w-full" onClick={() => setStep('confirm')}>
|
||||
{t('settings.twoFa.scannedContinue')}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (step === 'confirm') {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<p className="text-bambu-gray-light text-sm">{t('settings.twoFa.enterCodeToConfirm')}</p>
|
||||
<CodeInput value={code} onChange={setCode} placeholder="000000" />
|
||||
<div className="flex gap-3">
|
||||
<Button variant="secondary" onClick={() => setStep('qr')} className="flex-1">
|
||||
{t('common.back')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="primary"
|
||||
className="flex-1"
|
||||
disabled={code.length !== 6 || enableMutation.isPending}
|
||||
onClick={() => enableMutation.mutate(code)}
|
||||
>
|
||||
{enableMutation.isPending ? t('common.saving') : t('settings.twoFa.activate')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// step === 'backup'
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<h3 className="text-white font-medium">{t('settings.twoFa.backupCodesTitle')}</h3>
|
||||
<BackupCodesDisplay codes={backupCodes} onDone={onDone} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Main component ───────────────────────────────────────────────────────────
|
||||
export function TwoFactorSettings() {
|
||||
const { t } = useTranslation();
|
||||
const queryClient = useQueryClient();
|
||||
const { showToast } = useToast();
|
||||
const { user } = useAuth();
|
||||
|
||||
const [showTOTPSetup, setShowTOTPSetup] = useState(false);
|
||||
const [showDisableTOTP, setShowDisableTOTP] = useState(false);
|
||||
const [showRegenBackup, setShowRegenBackup] = useState(false);
|
||||
const [disableCode, setDisableCode] = useState('');
|
||||
const [regenCode, setRegenCode] = useState('');
|
||||
const [newBackupCodes, setNewBackupCodes] = useState<string[] | null>(null);
|
||||
|
||||
// Email OTP enable: two-step proof-of-possession flow
|
||||
const [emailSetupToken, setEmailSetupToken] = useState<string | null>(null);
|
||||
const [emailSetupCode, setEmailSetupCode] = useState('');
|
||||
|
||||
// Email OTP disable: requires account password
|
||||
const [showDisableEmail, setShowDisableEmail] = useState(false);
|
||||
const [emailDisablePassword, setEmailDisablePassword] = useState('');
|
||||
const [showEmailDisablePassword, setShowEmailDisablePassword] = useState(false);
|
||||
|
||||
const { data: status, isLoading } = useQuery({
|
||||
queryKey: ['2fa-status'],
|
||||
queryFn: () => api.get2FAStatus(),
|
||||
});
|
||||
|
||||
const { data: oidcLinks } = useQuery({
|
||||
queryKey: ['oidc-links'],
|
||||
queryFn: () => api.getOIDCLinks(),
|
||||
});
|
||||
|
||||
// Step 1: request verification code (proof of possession)
|
||||
const enableEmailRequestMutation = useMutation({
|
||||
mutationFn: () => api.enableEmailOTP(),
|
||||
onSuccess: (data: { message: string; setup_token: string }) => {
|
||||
setEmailSetupToken(data.setup_token);
|
||||
showToast(data.message, 'success');
|
||||
},
|
||||
onError: (e: Error) => {
|
||||
const msg = e.message ?? '';
|
||||
if (msg.toLowerCase().includes('smtp')) {
|
||||
showToast(t('settings.twoFa.smtpRequired'), 'error');
|
||||
} else {
|
||||
showToast(msg, 'error');
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
// Step 2: confirm with the code received by email
|
||||
const enableEmailConfirmMutation = useMutation({
|
||||
mutationFn: () => api.confirmEnableEmailOTP(emailSetupToken!, emailSetupCode),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['2fa-status'] });
|
||||
setEmailSetupToken(null);
|
||||
setEmailSetupCode('');
|
||||
showToast(t('settings.twoFa.emailOtpEnabled'), 'success');
|
||||
},
|
||||
onError: (e: Error) => showToast(e.message, 'error'),
|
||||
});
|
||||
|
||||
const disableEmailMutation = useMutation({
|
||||
mutationFn: (password: string) => api.disableEmailOTP(password),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['2fa-status'] });
|
||||
setShowDisableEmail(false);
|
||||
setEmailDisablePassword('');
|
||||
showToast(t('settings.twoFa.emailOtpDisabled'), 'success');
|
||||
},
|
||||
onError: (e: Error) => showToast(e.message, 'error'),
|
||||
});
|
||||
|
||||
const disableTOTPMutation = useMutation({
|
||||
mutationFn: (code: string) => api.disableTOTP(code),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['2fa-status'] });
|
||||
setShowDisableTOTP(false);
|
||||
setDisableCode('');
|
||||
showToast(t('settings.twoFa.totpDisabled'), 'success');
|
||||
},
|
||||
onError: () => showToast(t('settings.twoFa.invalidCode'), 'error'),
|
||||
});
|
||||
|
||||
const regenMutation = useMutation({
|
||||
mutationFn: (code: string) => api.regenerateBackupCodes(code),
|
||||
onSuccess: (data) => {
|
||||
queryClient.invalidateQueries({ queryKey: ['2fa-status'] });
|
||||
setShowRegenBackup(false);
|
||||
setRegenCode('');
|
||||
setNewBackupCodes(data.backup_codes);
|
||||
},
|
||||
onError: () => showToast(t('settings.twoFa.invalidCode'), 'error'),
|
||||
});
|
||||
|
||||
const unlinkOIDCMutation = useMutation({
|
||||
mutationFn: (providerId: number) => api.deleteOIDCLink(providerId),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['oidc-links'] });
|
||||
showToast(t('settings.twoFa.oidcUnlinked'), 'success');
|
||||
},
|
||||
onError: (e: Error) => showToast(e.message, 'error'),
|
||||
});
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<RefreshCw className="w-6 h-6 animate-spin text-bambu-green" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const hasEmail = !!user?.email;
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* ── TOTP ─────────────────────────────────────────────────────────── */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className={`w-10 h-10 rounded-full flex items-center justify-center ${status?.totp_enabled ? 'bg-green-500/20' : 'bg-gray-500/20'}`}>
|
||||
<Smartphone className={`w-5 h-5 ${status?.totp_enabled ? 'text-green-400' : 'text-gray-400'}`} />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-white font-semibold">{t('settings.twoFa.totpTitle')}</h3>
|
||||
<p className="text-bambu-gray text-sm">{t('settings.twoFa.totpDesc')}</p>
|
||||
</div>
|
||||
<div className="ml-auto">
|
||||
{status?.totp_enabled ? (
|
||||
<span className="flex items-center gap-1 text-green-400 text-sm font-medium">
|
||||
<ShieldCheck className="w-4 h-4" /> {t('common.enabled')}
|
||||
</span>
|
||||
) : (
|
||||
<span className="flex items-center gap-1 text-bambu-gray text-sm">
|
||||
<ShieldOff className="w-4 h-4" /> {t('common.disabled')}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{/* TOTP Setup wizard */}
|
||||
{showTOTPSetup ? (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<h4 className="text-white font-medium">{t('settings.twoFa.setupAuthApp')}</h4>
|
||||
<button onClick={() => { setShowTOTPSetup(false); queryClient.removeQueries({ queryKey: ['totp-setup'] }); }} className="text-bambu-gray hover:text-white">
|
||||
<X className="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
<TOTPSetupWizard onDone={() => { setShowTOTPSetup(false); queryClient.removeQueries({ queryKey: ['totp-setup'] }); }} />
|
||||
</div>
|
||||
) : showDisableTOTP ? (
|
||||
<div className="space-y-4">
|
||||
<p className="text-bambu-gray-light text-sm">{t('settings.twoFa.disableConfirmHint')}</p>
|
||||
<CodeInput value={disableCode} onChange={setDisableCode} placeholder="000000 or XXXXXXXX" maxLength={8} />
|
||||
<div className="flex gap-3">
|
||||
<Button variant="secondary" onClick={() => { setShowDisableTOTP(false); setDisableCode(''); }} className="flex-1">
|
||||
{t('common.cancel')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="danger"
|
||||
className="flex-1"
|
||||
disabled={disableCode.length < 6 || disableTOTPMutation.isPending}
|
||||
onClick={() => disableTOTPMutation.mutate(disableCode)}
|
||||
>
|
||||
{disableTOTPMutation.isPending ? t('common.saving') : t('settings.twoFa.disableTotp')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : showRegenBackup ? (
|
||||
<div className="space-y-4">
|
||||
<p className="text-bambu-gray-light text-sm">{t('settings.twoFa.regenBackupHint')}</p>
|
||||
<CodeInput value={regenCode} onChange={setRegenCode} placeholder="000000 or XXXXXXXX" maxLength={8} />
|
||||
<div className="flex gap-3">
|
||||
<Button variant="secondary" onClick={() => { setShowRegenBackup(false); setRegenCode(''); }} className="flex-1">
|
||||
{t('common.cancel')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="primary"
|
||||
className="flex-1"
|
||||
disabled={regenCode.length < 6 || regenMutation.isPending}
|
||||
onClick={() => regenMutation.mutate(regenCode)}
|
||||
>
|
||||
{regenMutation.isPending ? t('common.saving') : t('settings.twoFa.regenBackup')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : newBackupCodes ? (
|
||||
<div className="space-y-4">
|
||||
<h4 className="text-white font-medium">{t('settings.twoFa.newBackupCodes')}</h4>
|
||||
<BackupCodesDisplay codes={newBackupCodes} onDone={() => setNewBackupCodes(null)} />
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{!status?.totp_enabled ? (
|
||||
<Button variant="primary" onClick={() => setShowTOTPSetup(true)} className="flex items-center gap-2">
|
||||
<Smartphone className="w-4 h-4" />
|
||||
{t('settings.twoFa.setupTotp')}
|
||||
</Button>
|
||||
) : (
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<div className="flex items-center gap-2 text-sm text-bambu-gray-light">
|
||||
<Key className="w-4 h-4" />
|
||||
{t('settings.twoFa.backupCodesRemaining', { count: status.backup_codes_remaining })}
|
||||
</div>
|
||||
<Button variant="secondary" size="sm" onClick={() => setShowRegenBackup(true)} className="flex items-center gap-2">
|
||||
<RefreshCw className="w-4 h-4" />
|
||||
{t('settings.twoFa.regenBackup')}
|
||||
</Button>
|
||||
<Button variant="danger" size="sm" onClick={() => setShowDisableTOTP(true)} className="flex items-center gap-2">
|
||||
<Trash2 className="w-4 h-4" />
|
||||
{t('settings.twoFa.disableTotp')}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* ── Email OTP ─────────────────────────────────────────────────────── */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className={`w-10 h-10 rounded-full flex items-center justify-center ${status?.email_otp_enabled ? 'bg-green-500/20' : 'bg-gray-500/20'}`}>
|
||||
<Mail className={`w-5 h-5 ${status?.email_otp_enabled ? 'text-green-400' : 'text-gray-400'}`} />
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<h3 className="text-white font-semibold">{t('settings.twoFa.emailOtpTitle')}</h3>
|
||||
<p className="text-bambu-gray text-sm">
|
||||
{hasEmail
|
||||
? t('settings.twoFa.emailOtpDesc', { email: user?.email })
|
||||
: t('settings.twoFa.emailOtpNoEmail')}
|
||||
</p>
|
||||
</div>
|
||||
{/* Show status badge; enable/disable handled in CardContent */}
|
||||
<div className="ml-auto">
|
||||
{status?.email_otp_enabled ? (
|
||||
<span className="flex items-center gap-1 text-green-400 text-sm font-medium">
|
||||
<ShieldCheck className="w-4 h-4" /> {t('common.enabled')}
|
||||
</span>
|
||||
) : (
|
||||
<span className="flex items-center gap-1 text-bambu-gray text-sm">
|
||||
<ShieldOff className="w-4 h-4" /> {t('common.disabled')}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{!hasEmail ? (
|
||||
<p className="text-amber-400 text-sm">{t('settings.twoFa.addEmailFirst')}</p>
|
||||
) : emailSetupToken ? (
|
||||
/* Step 2: enter the code that was sent to the email */
|
||||
<div className="space-y-4">
|
||||
<p className="text-bambu-gray-light text-sm">{t('settings.twoFa.emailSetupEnterCode')}</p>
|
||||
<CodeInput value={emailSetupCode} onChange={setEmailSetupCode} placeholder="000000" />
|
||||
<div className="flex gap-3">
|
||||
<Button
|
||||
variant="secondary"
|
||||
onClick={() => { setEmailSetupToken(null); setEmailSetupCode(''); }}
|
||||
className="flex-1"
|
||||
>
|
||||
{t('common.cancel')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="primary"
|
||||
className="flex-1"
|
||||
disabled={emailSetupCode.length !== 6 || enableEmailConfirmMutation.isPending}
|
||||
onClick={() => enableEmailConfirmMutation.mutate()}
|
||||
>
|
||||
{enableEmailConfirmMutation.isPending ? t('common.saving') : t('settings.twoFa.verifyAndEnable')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : showDisableEmail ? (
|
||||
/* Disable: require account password for re-auth */
|
||||
<div className="space-y-4">
|
||||
<p className="text-bambu-gray-light text-sm">{t('settings.twoFa.emailDisablePasswordHint')}</p>
|
||||
<div className="relative">
|
||||
<input
|
||||
type={showEmailDisablePassword ? 'text' : 'password'}
|
||||
value={emailDisablePassword}
|
||||
onChange={(e) => setEmailDisablePassword(e.target.value)}
|
||||
placeholder={t('settings.twoFa.passwordPlaceholder')}
|
||||
className="w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowEmailDisablePassword(!showEmailDisablePassword)}
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white"
|
||||
>
|
||||
{showEmailDisablePassword ? <EyeOff className="w-5 h-5" /> : <Eye className="w-5 h-5" />}
|
||||
</button>
|
||||
</div>
|
||||
<div className="flex gap-3">
|
||||
<Button
|
||||
variant="secondary"
|
||||
onClick={() => { setShowDisableEmail(false); setEmailDisablePassword(''); }}
|
||||
className="flex-1"
|
||||
>
|
||||
{t('common.cancel')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="danger"
|
||||
className="flex-1"
|
||||
disabled={!emailDisablePassword || disableEmailMutation.isPending}
|
||||
onClick={() => disableEmailMutation.mutate(emailDisablePassword)}
|
||||
>
|
||||
{disableEmailMutation.isPending ? t('common.saving') : t('settings.twoFa.disableEmailOtp')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex gap-3">
|
||||
{!status?.email_otp_enabled ? (
|
||||
<Button
|
||||
variant="primary"
|
||||
disabled={!hasEmail || enableEmailRequestMutation.isPending}
|
||||
onClick={() => enableEmailRequestMutation.mutate()}
|
||||
className="flex items-center gap-2"
|
||||
>
|
||||
<Mail className="w-4 h-4" />
|
||||
{enableEmailRequestMutation.isPending ? t('common.saving') : t('settings.twoFa.enableEmailOtp')}
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
variant="danger"
|
||||
size="sm"
|
||||
onClick={() => setShowDisableEmail(true)}
|
||||
className="flex items-center gap-2"
|
||||
>
|
||||
<Trash2 className="w-4 h-4" />
|
||||
{t('settings.twoFa.disableEmailOtp')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* ── Linked SSO accounts ───────────────────────────────────────────── */}
|
||||
{oidcLinks && oidcLinks.length > 0 && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<h3 className="text-white font-semibold">{t('settings.twoFa.linkedAccounts')}</h3>
|
||||
<p className="text-bambu-gray text-sm">{t('settings.twoFa.linkedAccountsDesc')}</p>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-3">
|
||||
{oidcLinks.map((link) => (
|
||||
<div key={link.id} className="flex items-center justify-between py-2 border-b border-bambu-dark-tertiary last:border-0">
|
||||
<div>
|
||||
<p className="text-white text-sm font-medium">{link.provider_name}</p>
|
||||
{link.provider_email && (
|
||||
<p className="text-bambu-gray text-xs">{link.provider_email}</p>
|
||||
)}
|
||||
</div>
|
||||
<Button
|
||||
variant="danger"
|
||||
size="sm"
|
||||
onClick={() => unlinkOIDCMutation.mutate(link.provider_id)}
|
||||
disabled={unlinkOIDCMutation.isPending}
|
||||
>
|
||||
<Trash2 className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user