Move allauth + auth UI to legacy/

allauth/ (44 files) is a django-allauth React UI — a separate concern
from the Mizan protocol. Moved to legacy/ pending extraction into a
standalone mizan-django-allauth package.

Also moved to legacy/:
- client/AuthContext.tsx — generic auth state from /me endpoint
- client/RouterContext.tsx — framework-agnostic router adapter
- client/routing.tsx — UserRoute/StaffRoute/AnonymousRoute guards
- client/nextjs.tsx — Next.js router adapter for auth

These are auth UI infrastructure, not Mizan protocol. The Mizan core
only needs JWT for auth header selection (jwt/ stays — MizanProvider
depends on useJWT() to decide between Bearer and session auth).

Cleaned up re-exports in client/react.ts and vitest aliases.

33 React tests pass.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-04-07 03:41:22 -04:00
parent 24ff0ae66d
commit 27c30d7e50
50 changed files with 0 additions and 8 deletions

View File

@@ -0,0 +1,79 @@
'use client'
import { useStyles, cx } from '../../contexts/StylesContext'
import { ProfileSection } from './ProfileSection'
import { EmailsSection } from './EmailsSection'
import { PasswordSection } from './PasswordSection'
import { PasskeysSection } from './PasskeysSection'
import { ConnectionsSection } from './ConnectionsSection'
import { MFASection } from './MFASection'
import { SessionsSection } from './SessionsSection'
import { Button } from './SettingsComponents'
type SettingsSectionType = 'profile' | 'emails' | 'password' | 'passkeys' | 'connections' | 'mfa' | 'sessions'
interface AuthSettingsProps {
/** Title shown at the top of the settings page */
title?: string
/** Called when user clicks sign out */
onSignOut?: () => void
/** Which sections to show. Defaults to all. */
sections?: SettingsSectionType[]
/** URL to redirect back to after OAuth connect (for connections section) */
oauthRedirectUrl?: string
}
const DEFAULT_SECTIONS: SettingsSectionType[] = ['profile', 'emails', 'password', 'passkeys', 'connections', 'mfa', 'sessions']
/**
* AuthSettings renders a complete account settings page.
*
* It includes sections for:
* - Profile (display user info)
* - Email addresses (manage, verify, set primary)
* - Password change
* - Passkeys (add/remove passwordless login)
* - Connected accounts (OAuth providers)
* - Two-factor authentication (TOTP, recovery codes)
* - Active sessions (view/end sessions)
*
* @example
* ```tsx
* <AuthSettings
* onSignOut={() => router.push('/logout')}
* sections={['profile', 'password', 'mfa']} // Only show these sections
* />
* ```
*/
export function AuthSettings({
title = 'Account Settings',
onSignOut,
sections = DEFAULT_SECTIONS,
oauthRedirectUrl,
}: AuthSettingsProps) {
const styles = useStyles()
const sectionSet = new Set(sections)
return (
<div className={styles.settingsContainer}>
<h1 className={styles.settingsPageTitle}>{title}</h1>
{sectionSet.has('profile') && <ProfileSection />}
{sectionSet.has('emails') && <EmailsSection />}
{sectionSet.has('password') && <PasswordSection />}
{sectionSet.has('passkeys') && <PasskeysSection />}
{sectionSet.has('connections') && <ConnectionsSection redirectUrl={oauthRedirectUrl} />}
{sectionSet.has('mfa') && <MFASection />}
{sectionSet.has('sessions') && <SessionsSection />}
{/* Sign Out */}
{onSignOut && (
<section className={styles.settingsCard}>
<Button variant="danger" onClick={onSignOut}>
Sign Out
</Button>
</section>
)}
</div>
)
}

View File

@@ -0,0 +1,87 @@
'use client'
import { useState, useEffect } from 'react'
import { useConfig } from '../../contexts/AuthContext'
import { useAllauthAPI } from '../../contexts/APIContext'
import { SettingsSection, SettingsItem, SettingsList, Button } from './SettingsComponents'
interface Connection {
uid: string
provider: { id: string; name: string }
display: string
}
interface ConnectionsSectionProps {
/** URL to redirect back to after OAuth connect */
redirectUrl?: string
}
export function ConnectionsSection({ redirectUrl = '/account' }: ConnectionsSectionProps) {
const api = useAllauthAPI()
const config = useConfig()
const [connections, setConnections] = useState<Connection[]>([])
const [loading, setLoading] = useState(true)
const availableProviders = config?.data?.socialaccount?.providers || []
const fetchConnections = async () => {
const res = await api.oauth.list()
if (res.status === 200 && res.data) {
setConnections(res.data)
}
setLoading(false)
}
useEffect(() => { fetchConnections() }, [])
const handleConnect = (providerId: string) => {
api.oauth.provider(providerId).connect.withRedirect(redirectUrl)
}
const handleDisconnect = async (providerId: string, uid: string) => {
if (!confirm('Disconnect this account?')) return
await api.oauth.provider(providerId).removeFrom(uid)
fetchConnections()
}
// Don't render if no providers configured or still loading
if (loading) return null
const connectedProviderIds = connections.map(c => c.provider.id)
const unconnectedProviders = availableProviders.filter(
(p: { id: string }) => !connectedProviderIds.includes(p.id)
)
// Hide section entirely if no social providers
if (connections.length === 0 && availableProviders.length === 0) return null
return (
<SettingsSection title="Connected Accounts">
<SettingsList>
{connections.map(conn => (
<SettingsItem
key={conn.uid}
label={conn.provider.name}
meta={conn.display}
actions={
<Button variant="danger" onClick={() => handleDisconnect(conn.provider.id, conn.uid)}>
Disconnect
</Button>
}
/>
))}
{unconnectedProviders.map((provider: { id: string; name: string }) => (
<SettingsItem
key={provider.id}
label={provider.name}
actions={
<Button onClick={() => handleConnect(provider.id)}>
Connect
</Button>
}
/>
))}
</SettingsList>
</SettingsSection>
)
}

View File

@@ -0,0 +1,120 @@
'use client'
import { useState, useEffect } from 'react'
import { useAllauthAPI } from '../../contexts/APIContext'
import { useStyles } from '../../contexts/StylesContext'
import { useDjangoFormCore } from 'mizan'
import { SettingsSection, SettingsItem, SettingsList, Badge, Button } from './SettingsComponents'
interface Email {
email: string
primary: boolean
verified: boolean
}
export function EmailsSection() {
const api = useAllauthAPI()
const styles = useStyles()
const [emails, setEmails] = useState<Email[]>([])
const [loading, setLoading] = useState(true)
const addEmailForm = useDjangoFormCore<Record<string, unknown>>({ name: 'add_email' })
const fetchEmails = async () => {
const res = await api.account.emails.list()
if (res.status === 200 && res.data) {
setEmails(res.data)
}
setLoading(false)
}
useEffect(() => { fetchEmails() }, [])
const handleAdd = async (e: React.FormEvent) => {
e.preventDefault()
const result = await addEmailForm.submit()
if (result.success) {
addEmailForm.reset()
fetchEmails()
}
}
const handleRemove = async (email: string) => {
if (!confirm(`Remove ${email}?`)) return
await api.account.emails.remove(email)
fetchEmails()
}
const handleSetPrimary = async (email: string) => {
await api.account.emails.setPrimary(email)
fetchEmails()
}
const handleResendVerification = async (email: string) => {
await api.account.emails.verification.dispatch(email)
alert('Verification email sent!')
}
if (loading) return null
return (
<SettingsSection title="Email Addresses">
<SettingsList>
{emails.map(email => (
<SettingsItem
key={email.email}
label={
<>
{email.email}
{email.primary && <Badge variant="primary">Primary</Badge>}
{!email.verified && <Badge variant="warning">Unverified</Badge>}
</>
}
actions={
<>
{!email.verified && (
<Button variant="secondary" onClick={() => handleResendVerification(email.email)}>
Verify
</Button>
)}
{!email.primary && email.verified && (
<Button onClick={() => handleSetPrimary(email.email)}>
Make Primary
</Button>
)}
{!email.primary && (
<Button variant="danger" onClick={() => handleRemove(email.email)}>
Remove
</Button>
)}
</>
}
/>
))}
</SettingsList>
{!addEmailForm.loading && (
<form onSubmit={handleAdd} className={styles.inlineForm}>
<div className={styles.field}>
<label className={styles.fieldLabel}>
{addEmailForm.schema?.fields.email?.label || 'Add Email'}
</label>
<input
type="email"
value={(addEmailForm.data.email as string) || ''}
onChange={(e) => addEmailForm.set('email', e.target.value)}
onBlur={() => addEmailForm.touch('email')}
className={styles.fieldInput}
required
/>
{addEmailForm.getFieldErrors('email').map((err, i) => (
<p key={i} className={styles.fieldError}>{err.message}</p>
))}
</div>
<Button type="submit">
{addEmailForm.schema?.submit_label || 'Add'}
</Button>
</form>
)}
</SettingsSection>
)
}

View File

@@ -0,0 +1,171 @@
'use client'
import { useState, useEffect } from 'react'
import { useAllauthAPI } from '../../contexts/APIContext'
import { useStyles } from '../../contexts/StylesContext'
import { SettingsSection, SettingsItem, Badge, Button } from './SettingsComponents'
import type { Authenticator, TOTPStatus } from '../../types'
interface TOTPSetup {
secret: string
totp_url: string
}
export function MFASection() {
const api = useAllauthAPI()
const [authenticators, setAuthenticators] = useState<Authenticator[]>([])
const [loading, setLoading] = useState(true)
const [available, setAvailable] = useState(true)
const fetchAuthenticators = async () => {
try {
const res = await api.mfa.list()
if (res.status === 200 && res.data) {
setAuthenticators(res.data as Authenticator[])
} else {
// Non-200 status means MFA not available
setAvailable(false)
}
} catch {
setAvailable(false)
}
setLoading(false)
}
useEffect(() => { fetchAuthenticators() }, [])
if (loading || !available) return null
const hasTOTP = authenticators.some(a => a.type === 'totp')
return (
<SettingsSection title="Two-Factor Authentication">
<TOTPSubsection
hasTOTP={hasTOTP}
onUpdate={fetchAuthenticators}
/>
{hasTOTP && (
<RecoveryCodesSubsection />
)}
</SettingsSection>
)
}
// --- TOTP Subsection ---
function TOTPSubsection({ hasTOTP, onUpdate }: { hasTOTP: boolean; onUpdate: () => void }) {
const api = useAllauthAPI()
const styles = useStyles()
const [showSetup, setShowSetup] = useState(false)
const [setup, setSetup] = useState<TOTPSetup | null>(null)
const [code, setCode] = useState('')
const handleStartSetup = async () => {
const res = await api.mfa.totp.getStatus()
// allauth returns TOTP status with secret and totp_url for setup
const data = res.data as TOTPStatus | undefined
if (data?.secret && data?.totp_url) {
setSetup({ secret: data.secret, totp_url: data.totp_url })
setShowSetup(true)
}
}
const handleActivate = async (e: React.FormEvent) => {
e.preventDefault()
const res = await api.mfa.totp.activate(code)
if (res.status === 200) {
setShowSetup(false)
setSetup(null)
setCode('')
onUpdate()
}
}
const handleDeactivate = async () => {
if (!confirm('Disable authenticator app?')) return
await api.mfa.totp.deactivate()
onUpdate()
}
return (
<>
<h3 className={styles.settingsSubtitle}>Authenticator App</h3>
{showSetup && setup ? (
<div className={styles.totpSetup}>
<p>Scan this QR code with your authenticator app:</p>
<img
src={`https://api.qrserver.com/v1/create-qr-code/?size=180x180&data=${encodeURIComponent(setup.totp_url)}`}
alt="TOTP QR Code"
className={styles.qrCode}
/>
<p className={styles.settingsItemMeta}>Secret: {setup.secret}</p>
<form onSubmit={handleActivate} className={styles.inlineForm}>
<div className={styles.field}>
<input
type="text"
value={code}
onChange={(e) => setCode(e.target.value)}
placeholder="Verification Code"
className={styles.fieldInput}
/>
</div>
<Button type="submit">Activate</Button>
<Button type="button" variant="secondary" onClick={() => setShowSetup(false)}>
Cancel
</Button>
</form>
</div>
) : hasTOTP ? (
<SettingsItem
label={<>Authenticator App <Badge variant="success">Active</Badge></>}
actions={<Button variant="danger" onClick={handleDeactivate}>Disable</Button>}
/>
) : (
<Button onClick={handleStartSetup}>Set Up Authenticator</Button>
)}
</>
)
}
// --- Recovery Codes Subsection ---
function RecoveryCodesSubsection() {
const api = useAllauthAPI()
const styles = useStyles()
const [codes, setCodes] = useState<string[]>([])
const handleView = async () => {
const res = await api.mfa.recoveryCodes.list()
if (res.status === 200) {
setCodes(res.data?.unused_codes || [])
}
}
const handleRegenerate = async () => {
if (!confirm('Generate new codes? Old codes will stop working.')) return
const res = await api.mfa.recoveryCodes.regenerate()
if (res.status === 200) {
setCodes(res.data?.unused_codes || [])
}
}
return (
<>
<h3 className={styles.settingsSubtitle}>Recovery Codes</h3>
{codes.length > 0 ? (
<div>
<div className={styles.recoveryCodes}>
{codes.map((code, i) => <span key={i}>{code}</span>)}
</div>
<p className={styles.settingsItemMeta}>Store these safely. Each code works once.</p>
<Button variant="secondary" onClick={handleRegenerate}>Regenerate</Button>
</div>
) : (
<Button variant="secondary" onClick={handleView}>View Recovery Codes</Button>
)}
</>
)
}

View File

@@ -0,0 +1,103 @@
'use client'
import { useState, useEffect } from 'react'
import { useAllauthAPI } from '../../contexts/APIContext'
import { useConfig } from '../../contexts/AuthContext'
import { useStyles } from '../../contexts/StylesContext'
import { SettingsSection, SettingsItem, SettingsList, Button } from './SettingsComponents'
import type { Authenticator, WebAuthnAuthenticator } from '../../types'
export function PasskeysSection() {
const api = useAllauthAPI()
const config = useConfig()
const styles = useStyles()
const [passkeys, setPasskeys] = useState<WebAuthnAuthenticator[]>([])
const [loading, setLoading] = useState(true)
// Check if passkey login is enabled
const passkeyLoginEnabled = config?.data?.mfa?.passkey_login_enabled
const fetchPasskeys = async () => {
try {
const res = await api.mfa.list()
if (res.status === 200 && res.data) {
const authenticators = res.data as Authenticator[]
setPasskeys(authenticators.filter((a): a is WebAuthnAuthenticator => a.type === 'webauthn'))
}
} catch {
// Silently fail - passkeys just won't show
}
setLoading(false)
}
useEffect(() => { fetchPasskeys() }, [])
// Don't render if passkey login isn't enabled
if (!passkeyLoginEnabled) return null
if (loading) return null
const handleAdd = async () => {
try {
const { startRegistration } = await import('@simplewebauthn/browser')
// Request creation options - use passwordless=true for login passkeys
const optionsRes = await api.webauthn.requestOptions.creation(true)
if (optionsRes.status !== 200) {
return
}
const publicKeyOptions = optionsRes.data?.creation_options?.publicKey
if (!publicKeyOptions) throw new Error('Invalid options response')
// @simplewebauthn/browser v13+ expects { optionsJSON: ... }
const credential = await startRegistration({ optionsJSON: publicKeyOptions as any })
const name = prompt('Name this passkey:') || 'Passkey'
const res = await api.webauthn.add(name, credential)
if (res.status === 200) {
fetchPasskeys()
}
} catch (e: any) {
if (e.name !== 'AbortError') {
alert(e.message || 'Failed to add passkey')
}
}
}
const handleRemove = async (id: number) => {
if (!confirm('Remove this passkey? You won\'t be able to use it to sign in anymore.')) return
await api.webauthn.delete([id])
fetchPasskeys()
}
return (
<SettingsSection title="Passkeys">
<p className={styles.settingsItemMeta} style={{ marginBottom: '1rem' }}>
Passkeys let you sign in quickly using your device's biometrics or security key.
No password needed.
</p>
{passkeys.length > 0 && (
<SettingsList>
{passkeys.map(passkey => (
<SettingsItem
key={passkey.id}
label={passkey.name}
meta={`Added ${new Date(passkey.created_at * 1000).toLocaleDateString()}`}
actions={
<Button variant="danger" onClick={() => handleRemove(passkey.id)}>
Remove
</Button>
}
/>
))}
</SettingsList>
)}
<Button onClick={handleAdd}>
{passkeys.length > 0 ? 'Add Another Passkey' : 'Set Up Passkey'}
</Button>
</SettingsSection>
)
}

View File

@@ -0,0 +1,54 @@
'use client'
import { useDjangoFormCore } from 'mizan'
import { useStyles } from '../../contexts/StylesContext'
import { SettingsSection, Button } from './SettingsComponents'
export function PasswordSection() {
const styles = useStyles()
const form = useDjangoFormCore<Record<string, unknown>>({ name: 'change_password' })
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
const result = await form.submit()
if (result.success) {
form.reset()
alert('Password changed successfully!')
}
}
if (form.loading) return null
return (
<SettingsSection title={form.schema?.title || 'Change Password'}>
<form onSubmit={handleSubmit} className={styles.form}>
<div className={styles.fieldsContainer}>
{form.schema?.fieldOrder.map(fieldName => {
const field = form.schema!.fields[fieldName]
return (
<div key={fieldName} className={styles.field}>
<label className={styles.fieldLabel}>{field.label}</label>
<input
type={field.type}
value={(form.data[fieldName] as string) || ''}
onChange={(e) => form.set(fieldName, e.target.value)}
onBlur={() => form.touch(fieldName)}
className={styles.fieldInput}
required={field.required}
/>
{form.touchedFields.has(fieldName) &&
form.getFieldErrors(fieldName).map((err, i) => (
<p key={i} className={styles.fieldError}>{err.message}</p>
))
}
</div>
)
})}
</div>
<Button type="submit" disabled={form.submitting}>
{form.submitting ? 'Changing...' : (form.schema?.submit_label || 'Change Password')}
</Button>
</form>
</SettingsSection>
)
}

View File

@@ -0,0 +1,22 @@
'use client'
import { useUser } from '../../contexts/AuthContext'
import { SettingsSection, SettingsItem, SettingsList } from './SettingsComponents'
export function ProfileSection() {
const user = useUser()
return (
<SettingsSection title="Profile">
<SettingsList>
<SettingsItem label="Email" meta={user?.email} />
{user?.first_name && (
<SettingsItem
label="Name"
meta={`${user.first_name} ${user.last_name || ''}`.trim()}
/>
)}
</SettingsList>
</SettingsSection>
)
}

View File

@@ -0,0 +1,88 @@
'use client'
import { useState, useEffect } from 'react'
import { useAllauthAPI } from '../../contexts/APIContext'
import { SettingsSection, SettingsItem, SettingsList, Badge, Button } from './SettingsComponents'
import type { Session } from '../../types'
function parseUserAgent(ua: string): string {
if (ua.includes('Chrome')) return 'Chrome'
if (ua.includes('Firefox')) return 'Firefox'
if (ua.includes('Safari')) return 'Safari'
if (ua.includes('Edge')) return 'Edge'
return 'Unknown Browser'
}
export function SessionsSection() {
const api = useAllauthAPI()
const [sessions, setSessions] = useState<Session[]>([])
const [loading, setLoading] = useState(true)
const [available, setAvailable] = useState(true)
const fetchSessions = async () => {
try {
const res = await api.session.list()
if (res.status === 200 && res.data) {
setSessions(res.data as Session[])
} else {
// Non-200 status means sessions feature not available
setAvailable(false)
}
} catch {
setAvailable(false)
}
setLoading(false)
}
useEffect(() => { fetchSessions() }, [])
const handleEnd = async (id: number) => {
if (!confirm('End this session?')) return
await api.session.remove([id])
fetchSessions()
}
const handleEndAllOthers = async () => {
const otherIds = sessions.filter(s => !s.is_current).map(s => s.id)
if (otherIds.length === 0) return
if (!confirm(`End ${otherIds.length} other session(s)?`)) return
await api.session.remove(otherIds)
fetchSessions()
}
if (loading || !available) return null
const otherSessions = sessions.filter(s => !s.is_current)
return (
<SettingsSection title="Active Sessions">
<SettingsList>
{sessions.map(session => (
<SettingsItem
key={session.id}
label={
<>
{parseUserAgent(session.user_agent)}
{session.is_current && <Badge variant="success">Current</Badge>}
</>
}
meta={`${session.ip} · ${session.last_seen_at ? new Date(session.last_seen_at * 1000).toLocaleString() : 'Unknown'}`}
actions={
!session.is_current && (
<Button variant="danger" onClick={() => handleEnd(session.id)}>
End
</Button>
)
}
/>
))}
</SettingsList>
{otherSessions.length > 0 && (
<Button variant="danger" onClick={handleEndAllOthers}>
End All Other Sessions
</Button>
)}
</SettingsSection>
)
}

View File

@@ -0,0 +1,76 @@
'use client'
import { useStyles, cx } from '../../contexts/StylesContext'
interface SettingsSectionProps {
title: string
children: React.ReactNode
}
export function SettingsSection({ title, children }: SettingsSectionProps) {
const styles = useStyles()
return (
<section className={styles.settingsCard}>
<h2 className={styles.settingsSectionTitle}>{title}</h2>
{children}
</section>
)
}
interface SettingsItemProps {
label: React.ReactNode
meta?: React.ReactNode
actions?: React.ReactNode
}
export function SettingsItem({ label, meta, actions }: SettingsItemProps) {
const styles = useStyles()
return (
<div className={styles.settingsItem}>
<div className={styles.settingsItemInfo}>
<span className={styles.settingsItemLabel}>{label}</span>
{meta && <span className={styles.settingsItemMeta}>{meta}</span>}
</div>
{actions && <div className={styles.settingsItemActions}>{actions}</div>}
</div>
)
}
export function SettingsList({ children }: { children: React.ReactNode }) {
const styles = useStyles()
return <div className={styles.settingsList}>{children}</div>
}
type BadgeVariant = 'primary' | 'success' | 'warning' | 'danger'
export function Badge({ variant, children }: { variant: BadgeVariant, children: React.ReactNode }) {
const styles = useStyles()
const variantClass = {
primary: styles.badgePrimary,
success: styles.badgeSuccess,
warning: styles.badgeUnverified,
danger: styles.badgeDanger,
}[variant]
return <span className={cx(styles.badge, variantClass)}>{children}</span>
}
interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
variant?: 'primary' | 'secondary' | 'danger'
size?: 'small' | 'normal'
}
export function Button({ variant = 'primary', size = 'small', className, children, ...props }: ButtonProps) {
const styles = useStyles()
const variantClass = {
primary: styles.smallButtonPrimary,
secondary: styles.smallButtonSecondary,
danger: styles.smallButtonDanger,
}[variant]
return (
<button className={cx(styles.smallButton, variantClass, className)} {...props}>
{children}
</button>
)
}

View File

@@ -0,0 +1,20 @@
// Main settings component
export { AuthSettings } from './AuthSettings'
// Individual sections (for custom layouts)
export { ProfileSection } from './ProfileSection'
export { EmailsSection } from './EmailsSection'
export { PasswordSection } from './PasswordSection'
export { PasskeysSection } from './PasskeysSection'
export { ConnectionsSection } from './ConnectionsSection'
export { MFASection } from './MFASection'
export { SessionsSection } from './SessionsSection'
// Building blocks (for custom components)
export {
SettingsSection,
SettingsItem,
SettingsList,
Badge,
Button,
} from './SettingsComponents'