feat(manager): v2 sign-in (login modes, support access, license notice) and an unlock endpoint for the lock screen
Platform-v2 step 2.6b:
- backend: POST /api/auth/unlock {pin|password} checks the CURRENT session's
user and keeps the session (no new login/token); 5 wrong tries end it
(auth.wrong_pin with attempts_left, then auth.session_ended); bootstrap
gains `login` (manager_mode, autofill_username, support)
- manager LoginPage rewritten on @xenia/ui + i18n: client "manager", password
or PIN pad per setting, remembered/only account card, support access panel
(challenge -> code -> 4 h session, not remembered as an account), notice
when the license runs the free tier (expired/inactive/locked/clock/unverified)
- lock screen on /api/auth/unlock with the shared PinPad
- @xenia/ui PinPad: variable length (minLength/maxLength, OK key, Enter)
- e2e manager.mjs: 33 checks (+ lockout after 5 wrong PINs, PIN login mode,
support access with a wrong then right code)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -12,10 +12,11 @@ import PhoneListener from '../components/PhoneListener'
|
||||
import { useTranslation } from '@xenia/i18n'
|
||||
import { pageFor } from '../shell/nav'
|
||||
import RouteGuard from '../shell/RouteGuard'
|
||||
import { errorMessage, isError } from '@xenia/api'
|
||||
import { PinPad } from '@xenia/ui'
|
||||
|
||||
export const LicenseContext = createContext(null)
|
||||
|
||||
const DIGITS = ['1','2','3','4','5','6','7','8','9','','0','⌫']
|
||||
|
||||
// ─── Page title / breadcrumb (from shell/nav.js) ─────────────────────────────
|
||||
|
||||
@@ -127,102 +128,38 @@ function LicenseBanner({ license }) {
|
||||
|
||||
// ─── Lock Screen ──────────────────────────────────────────────────────────────
|
||||
|
||||
function LockScreen({ username, displayName, onUnlock, onLogout }) {
|
||||
const [pin, setPin] = useState('')
|
||||
// The lock screen checks the PIN of the user who owns THIS session (POST /api/auth/unlock,
|
||||
// plan step 2.6b): no new login, no new token. Five wrong tries end the session.
|
||||
function LockScreen({ displayName, onUnlock, onLogout }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const [error, setError] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
|
||||
function pressDigit(d) {
|
||||
if (loading) return
|
||||
if (d === '⌫') { setPin(p => p.slice(0, -1)); setError(''); return }
|
||||
if (d === '') return
|
||||
if (pin.length >= 6) return
|
||||
setPin(p => p + d)
|
||||
}
|
||||
|
||||
async function submitPin(usedPin) {
|
||||
if (usedPin.length < 4) return
|
||||
setError('')
|
||||
setLoading(true)
|
||||
async function tryPin(pin) {
|
||||
try {
|
||||
// A wrong PIN is a 401: say "Wrong PIN" instead of the session-ended logout
|
||||
const { data } = await client.post('/api/auth/login', { username, pin: usedPin }, { xenia: { ignoreUnauthorized: true } })
|
||||
if (!data.user.perm_access_dashboard) {
|
||||
setError('Not a manager account.')
|
||||
setPin('')
|
||||
return
|
||||
}
|
||||
onUnlock(data.user, data.access_token)
|
||||
} catch {
|
||||
setError('Wrong PIN')
|
||||
setPin('')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
const { data } = await client.post('/api/auth/unlock', { pin }, { xenia: { ignoreUnauthorized: true } })
|
||||
setError('')
|
||||
onUnlock(data.user)
|
||||
return true
|
||||
} catch (err) {
|
||||
if (isError(err, 'auth.session_ended')) { onLogout(); return true }
|
||||
setError(errorMessage(err, t))
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (pin.length === 4) submitPin(pin)
|
||||
}, [pin])
|
||||
|
||||
useEffect(() => {
|
||||
function onKeyDown(e) {
|
||||
if (loading) return
|
||||
if (e.key >= '0' && e.key <= '9') pressDigit(e.key)
|
||||
else if (e.key === 'Backspace') pressDigit('⌫')
|
||||
}
|
||||
window.addEventListener('keydown', onKeyDown)
|
||||
return () => window.removeEventListener('keydown', onKeyDown)
|
||||
}, [pin, loading])
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-[9999] flex items-center justify-center bg-black/80 backdrop-blur-md">
|
||||
<div className="bg-white rounded-2xl shadow-2xl p-8 w-full max-w-xs text-center space-y-5">
|
||||
<div className="space-y-1">
|
||||
<div className="flex justify-center">
|
||||
<div className="flex h-12 w-12 items-center justify-center rounded-xl bg-slate-100">
|
||||
<Lock className="h-6 w-6 text-slate-500" />
|
||||
</div>
|
||||
<div className="fixed inset-0 z-[9999] flex items-center justify-center bg-black/80 backdrop-blur-md" data-testid="lock-screen">
|
||||
<div className="bg-surface rounded-dialog shadow-overlay p-8 w-full max-w-xs text-center grid gap-4">
|
||||
<div className="grid gap-1 justify-items-center">
|
||||
<div className="flex h-12 w-12 items-center justify-center rounded-card bg-surface-2">
|
||||
<Lock className="h-6 w-6 text-ink-3" />
|
||||
</div>
|
||||
<p className="text-[15px] font-bold text-slate-900">Locked</p>
|
||||
<p className="text-[13px] text-slate-500">{displayName}</p>
|
||||
<p className="text-body-lg font-bold text-ink">{t('lock.title')}</p>
|
||||
<p className="text-label text-ink-2">{displayName}</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<div className="flex justify-center gap-3">
|
||||
{Array.from({ length: 4 }).map((_, i) => (
|
||||
<div key={i} className={`w-3.5 h-3.5 rounded-full border-2 transition-colors ${
|
||||
i < pin.length ? 'bg-sky-500 border-sky-500' : 'border-slate-300'
|
||||
}`} />
|
||||
))}
|
||||
</div>
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
{DIGITS.map((d, i) => (
|
||||
<button
|
||||
key={i}
|
||||
type="button"
|
||||
onClick={() => pressDigit(d)}
|
||||
disabled={d === '' || loading}
|
||||
className={`h-12 rounded-xl text-lg font-semibold transition-colors ${
|
||||
d === '' ? 'invisible'
|
||||
: d === '⌫' ? 'bg-slate-100 hover:bg-slate-200 text-slate-600'
|
||||
: 'bg-slate-100 hover:bg-sky-100 active:bg-sky-200 text-slate-800'
|
||||
} disabled:opacity-50`}
|
||||
>
|
||||
{d}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && <p className="text-[12px] text-rose-500">{error}</p>}
|
||||
{loading && <p className="text-[12px] text-slate-400">Verifying…</p>}
|
||||
|
||||
<button
|
||||
onClick={onLogout}
|
||||
className="text-[12px] text-slate-400 hover:text-slate-600 transition-colors"
|
||||
>
|
||||
Sign out instead
|
||||
<PinPad minLength={4} maxLength={8} error={error || undefined} onComplete={tryPin} />
|
||||
<button onClick={onLogout} className="text-label text-ink-3 hover:text-ink-2 transition-colors">
|
||||
{t('lock.signOutInstead')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -289,8 +226,8 @@ export default function AppLayout() {
|
||||
navigate('/login', { replace: true, state: { manualLogout: true } })
|
||||
}
|
||||
|
||||
function handleUnlock(u, t) {
|
||||
unlock(u, t)
|
||||
function handleUnlock(u) {
|
||||
unlock(u)
|
||||
lastActivityRef.current = Date.now()
|
||||
}
|
||||
|
||||
|
||||
@@ -1,363 +1,235 @@
|
||||
import { useState, useEffect, useRef } from 'react'
|
||||
import { useNavigate, useLocation } from 'react-router-dom'
|
||||
import { User, Lock, KeyRound } from 'lucide-react'
|
||||
// Manager sign-in on v2 rules (plan step 2.6b, APPS_PLATFORM D-8, D-16).
|
||||
// - POST /api/auth/login {client: "manager", …}: the login mode comes from settings via the
|
||||
// platform bootstrap (`login.manager_mode`: password | pin); managers are never let in by
|
||||
// username only (D-8).
|
||||
// - Support access: a challenge code read to Xenia support, their answer opens a 4-hour
|
||||
// support session (D-16, CS-15). Offered when the site has a SUPPORT_SECRET.
|
||||
// - The license state is shown before sign-in (the venue then runs the free tier).
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { KeyRound, LifeBuoy, ArrowLeft, ShieldAlert } from 'lucide-react'
|
||||
import { errorMessage } from '@xenia/api'
|
||||
import { useAccess } from '@xenia/access'
|
||||
import { useFormat, useTranslation } from '@xenia/i18n'
|
||||
import { Button, Field, Input, PinPad, Spinner } from '@xenia/ui'
|
||||
import useAuthStore from '../store/authStore'
|
||||
import client from '../api/client'
|
||||
import Button from '../ui/Button'
|
||||
import { LabelledInput } from '../ui/Input'
|
||||
|
||||
const DIGITS = ['1','2','3','4','5','6','7','8','9','','0','⌫']
|
||||
|
||||
function PinDots({ length, filled }) {
|
||||
return (
|
||||
<div className="flex justify-center gap-3 py-2">
|
||||
{Array.from({ length }).map((_, i) => (
|
||||
<div key={i} className={`w-3.5 h-3.5 rounded-full border-2 transition-colors ${
|
||||
i < filled ? 'bg-sky-500 border-sky-500' : 'border-slate-300'
|
||||
}`} />
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function PinPad({ pin, onChange, disabled }) {
|
||||
function press(d) {
|
||||
if (disabled) return
|
||||
if (d === '⌫') { onChange(p => p.slice(0, -1)); return }
|
||||
if (d === '') return
|
||||
if (pin.length >= 6) return
|
||||
onChange(p => p + d)
|
||||
}
|
||||
return (
|
||||
<div className="grid grid-cols-3 gap-3">
|
||||
{DIGITS.map((d, i) => (
|
||||
<button
|
||||
key={i}
|
||||
type="button"
|
||||
onClick={() => press(d)}
|
||||
disabled={d === '' || disabled}
|
||||
className={`h-14 rounded-xl text-xl font-semibold transition-colors ${
|
||||
d === ''
|
||||
? 'invisible'
|
||||
: d === '⌫'
|
||||
? 'bg-slate-100 hover:bg-slate-200 text-slate-600'
|
||||
: 'bg-slate-100 hover:bg-sky-100 active:bg-sky-200 text-slate-800'
|
||||
} disabled:opacity-50`}
|
||||
>
|
||||
{d}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ─── Manager picker (multi-manager + login=none) ──────────────────────────────
|
||||
|
||||
function ManagerPicker({ managers, onSelect }) {
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div className="space-y-1">
|
||||
<h1 className="text-xl font-bold text-slate-900">Select account</h1>
|
||||
<p className="text-[13px] text-slate-500">Choose your manager account to continue.</p>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
{managers.map(m => (
|
||||
<button
|
||||
key={m.id}
|
||||
onClick={() => onSelect(m)}
|
||||
className="w-full flex items-center gap-3 rounded-xl border border-slate-200 bg-white p-4 text-left transition hover:border-sky-300 hover:bg-sky-50 active:bg-sky-100"
|
||||
>
|
||||
<div className="flex h-9 w-9 items-center justify-center rounded-full bg-sky-100 text-sky-700 font-semibold text-[13px] flex-shrink-0">
|
||||
{(m.full_name || m.username).charAt(0).toUpperCase()}
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-[13px] font-semibold text-slate-800">{m.full_name || m.username}</p>
|
||||
<p className="text-[12px] text-slate-400">{m.username}</p>
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ─── Main login page ──────────────────────────────────────────────────────────
|
||||
const LOGIN = { xenia: { ignoreUnauthorized: true } } // a wrong password is a 401: show it, don't "log out"
|
||||
|
||||
export default function LoginPage() {
|
||||
const [settings, setSettings] = useState(null)
|
||||
const [managers, setManagers] = useState([])
|
||||
const [loadingInit, setLoadingInit] = useState(true)
|
||||
|
||||
const [selectedManager, setSelectedManager] = useState(null)
|
||||
const [manualMode, setManualMode] = useState(false)
|
||||
const [username, setUsername] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
const [pin, setPin] = useState('')
|
||||
const [error, setError] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
|
||||
const { login } = useAuthStore()
|
||||
const { t } = useTranslation('manager')
|
||||
const { venue, login: loginInfo, license } = useAccess()
|
||||
const login = useAuthStore(s => s.login)
|
||||
const savedUsername = useAuthStore(s => s.savedUsername)
|
||||
const navigate = useNavigate()
|
||||
const location = useLocation()
|
||||
const autoLoginAttempted = useRef(false)
|
||||
// manualLogout comes either from nav state (logout button) or sessionStorage (auto-logout)
|
||||
const manualLogout = location.state?.manualLogout === true
|
||||
|| sessionStorage.getItem('pos_manual_logout') === 'true'
|
||||
const [managers, setManagers] = useState(null) // null = still loading (decides the account card)
|
||||
const [manual, setManual] = useState(false)
|
||||
const [support, setSupport] = useState(false)
|
||||
|
||||
// Write to sessionStorage when nav state says manualLogout, clear it on successful login
|
||||
useEffect(() => {
|
||||
if (location.state?.manualLogout) {
|
||||
sessionStorage.setItem('pos_manual_logout', 'true')
|
||||
}
|
||||
client.get('/api/auth/managers', LOGIN).then(r => setManagers(r.data)).catch(() => setManagers([]))
|
||||
}, [])
|
||||
|
||||
// Load security config + manager list in parallel (both public, no auth needed)
|
||||
useEffect(() => {
|
||||
Promise.all([
|
||||
client.get('/api/setup/security-config').catch(() => ({ data: { login_method: 'password', autofill_username: true } })),
|
||||
client.get('/api/auth/managers').catch(() => ({ data: [] })),
|
||||
]).then(([configRes, managersRes]) => {
|
||||
setSettings(configRes.data)
|
||||
setManagers(managersRes.data)
|
||||
}).finally(() => setLoadingInit(false))
|
||||
}, [])
|
||||
// The account to sign in to without typing a username: the last one used on this browser,
|
||||
// or the only manager there is (when the venue allows the autofill).
|
||||
const single = loginInfo?.autofill_username && managers?.length === 1 ? managers[0].username : null
|
||||
const account = manual ? null : (savedUsername || single)
|
||||
const known = managers?.find(m => m.username === account)
|
||||
|
||||
const loginMethod = settings?.login_method ?? 'password'
|
||||
const autofill = settings?.autofill_username !== false
|
||||
const singleManager = managers.length === 1 ? managers[0] : null
|
||||
|
||||
// Suppressed in manual mode so the free-text input is shown instead
|
||||
const effectiveUsername = manualMode ? null
|
||||
: (selectedManager?.username || (autofill && singleManager ? singleManager.username : null))
|
||||
|
||||
// Auto-login: none method + single manager → attempt exactly once, skip if manual logout
|
||||
useEffect(() => {
|
||||
if (!loadingInit && loginMethod === 'none' && singleManager && !manualLogout && !autoLoginAttempted.current) {
|
||||
autoLoginAttempted.current = true
|
||||
handleAutoLogin(singleManager.username)
|
||||
}
|
||||
}, [loadingInit, loginMethod, singleManager])
|
||||
|
||||
function clearManualLogoutFlag() {
|
||||
sessionStorage.removeItem('pos_manual_logout')
|
||||
function signedIn(data, { remember = true } = {}) {
|
||||
login(data.user, data.access_token, { remember })
|
||||
navigate('/dashboard', { replace: true })
|
||||
}
|
||||
|
||||
async function handleAutoLogin(uname) {
|
||||
setLoading(true)
|
||||
try {
|
||||
const { data } = await client.post('/api/auth/login-no-auth', { username: uname }, { xenia: { ignoreUnauthorized: true } })
|
||||
if (!data.user.perm_access_dashboard) { setLoading(false); return }
|
||||
clearManualLogoutFlag()
|
||||
login(data.user, data.access_token)
|
||||
navigate('/dashboard', { replace: true })
|
||||
} catch {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSubmit(e) {
|
||||
e?.preventDefault()
|
||||
const uname = effectiveUsername || username.trim()
|
||||
if (!uname) return
|
||||
if (loginMethod === 'password' && !password) return
|
||||
if (loginMethod === 'pin' && pin.length < 4) return
|
||||
|
||||
setError('')
|
||||
setLoading(true)
|
||||
try {
|
||||
const body = { username: uname }
|
||||
if (loginMethod === 'password') body.password = password
|
||||
else if (loginMethod === 'pin') body.pin = pin
|
||||
|
||||
// A wrong password is a 401: show it here instead of the session-ended logout
|
||||
const { data } = await client.post('/api/auth/login', body, { xenia: { ignoreUnauthorized: true } })
|
||||
if (!data.user.perm_access_dashboard) {
|
||||
setError('This account does not have manager access.')
|
||||
setPin('')
|
||||
setPassword('')
|
||||
return
|
||||
}
|
||||
clearManualLogoutFlag()
|
||||
login(data.user, data.access_token)
|
||||
navigate('/dashboard', { replace: true })
|
||||
} catch (err) {
|
||||
setError(err.response?.data?.detail || 'Invalid credentials')
|
||||
setPin('')
|
||||
setPassword('')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
// Auto-submit on 4-digit PIN entry
|
||||
useEffect(() => {
|
||||
if (loginMethod === 'pin' && pin.length === 4) handleSubmit()
|
||||
}, [pin])
|
||||
|
||||
// Show spinner while loading OR while auto-login is in progress (none mode, not manual logout)
|
||||
if (loadingInit || (loginMethod === 'none' && singleManager && !manualLogout && !manualMode)) {
|
||||
return (
|
||||
<div className="min-h-screen bg-slate-50 flex items-center justify-center">
|
||||
<div className="w-6 h-6 rounded-full border-2 border-sky-500 border-t-transparent animate-spin" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Multi-manager + none method: show picker first
|
||||
const needsPicker = loginMethod === 'none' && managers.length > 1 && !selectedManager
|
||||
const notice = license?.mode === 'free' && license.reason ? t(`license.${license.reason}`, { defaultValue: '' }) : ''
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gradient-to-br from-slate-50 to-sky-50 flex items-center justify-center p-4">
|
||||
<div className="min-h-screen bg-canvas flex items-center justify-center p-4">
|
||||
<div className="w-full max-w-sm">
|
||||
<div className="bg-white rounded-2xl shadow-xl shadow-slate-200/60 border border-slate-100 p-8">
|
||||
<div className="bg-surface rounded-dialog shadow-overlay border border-line p-8">
|
||||
<div className="flex flex-col items-center text-center mb-6">
|
||||
<div className="flex h-12 w-12 items-center justify-center rounded-card bg-accent text-accent-fg mb-3">
|
||||
{support ? <LifeBuoy size={22} /> : <KeyRound size={22} />}
|
||||
</div>
|
||||
<h1 className="text-title font-semibold text-ink" data-testid="login-title">{support ? t('support.title') : t('login.title')}</h1>
|
||||
<p className="text-body text-ink-2 mt-0.5">{venue?.name || t('login.subtitle')}</p>
|
||||
</div>
|
||||
|
||||
{needsPicker ? (
|
||||
<ManagerPicker managers={managers} onSelect={m => { setSelectedManager(m); handleAutoLogin(m.username) }} />
|
||||
) : (
|
||||
<form onSubmit={handleSubmit} className="space-y-5">
|
||||
<div className="text-center space-y-1">
|
||||
<div className="flex justify-center mb-3">
|
||||
<div className="flex h-12 w-12 items-center justify-center rounded-xl bg-sky-500">
|
||||
<KeyRound className="h-6 w-6 text-white" />
|
||||
</div>
|
||||
</div>
|
||||
<h1 className="text-xl font-bold text-slate-900">Sign In</h1>
|
||||
<p className="text-[13px] text-slate-500">
|
||||
{loginMethod === 'password' ? 'Enter your username and password'
|
||||
: loginMethod === 'pin' ? 'Enter your username and PIN'
|
||||
: 'Select your account'}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Username section */}
|
||||
{manualMode ? (
|
||||
<LabelledInput
|
||||
icon={User}
|
||||
placeholder="Username"
|
||||
value={username}
|
||||
onChange={e => setUsername(e.target.value)}
|
||||
autoComplete="off"
|
||||
autoFocus
|
||||
/>
|
||||
) : effectiveUsername ? (
|
||||
<div className="space-y-1">
|
||||
<div className="flex items-center gap-3 rounded-xl border border-slate-200 bg-slate-50 px-4 py-3">
|
||||
<div className="flex h-8 w-8 items-center justify-center rounded-full bg-sky-100 text-sky-700 font-semibold text-[12px] flex-shrink-0">
|
||||
{effectiveUsername.charAt(0).toUpperCase()}
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-[13px] font-medium text-slate-700">{effectiveUsername}</p>
|
||||
<p className="text-[11px] text-slate-400">Manager</p>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => { setManualMode(true); setSelectedManager(null); setUsername(''); setPassword(''); setPin(''); setError('') }}
|
||||
className="text-[11px] text-slate-400 hover:text-sky-600 transition-colors w-full text-right pr-1"
|
||||
>
|
||||
Sign in as different account
|
||||
</button>
|
||||
</div>
|
||||
) : managers.length > 0 ? (
|
||||
<div className="space-y-2">
|
||||
{managers.map(m => (
|
||||
<button
|
||||
key={m.id}
|
||||
type="button"
|
||||
onClick={() => setUsername(m.username)}
|
||||
className={`w-full flex items-center gap-3 rounded-xl border p-3 text-left transition ${
|
||||
username === m.username
|
||||
? 'border-sky-400 bg-sky-50'
|
||||
: 'border-slate-200 hover:border-slate-300 hover:bg-slate-50'
|
||||
}`}
|
||||
>
|
||||
<div className="flex h-8 w-8 items-center justify-center rounded-full bg-sky-100 text-sky-700 font-semibold text-[12px] flex-shrink-0">
|
||||
{(m.full_name || m.username).charAt(0).toUpperCase()}
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-[13px] font-medium text-slate-800">{m.full_name || m.username}</p>
|
||||
<p className="text-[11px] text-slate-400">{m.username}</p>
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => { setManualMode(true); setUsername(''); setPassword(''); setPin(''); setError('') }}
|
||||
className="text-[11px] text-slate-400 hover:text-sky-600 transition-colors w-full text-right pr-1"
|
||||
>
|
||||
Sign in as different account
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<LabelledInput
|
||||
icon={User}
|
||||
placeholder="Username"
|
||||
value={username}
|
||||
onChange={e => setUsername(e.target.value)}
|
||||
autoComplete="off"
|
||||
autoFocus
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Password input */}
|
||||
{loginMethod === 'password' && (
|
||||
<LabelledInput
|
||||
icon={Lock}
|
||||
placeholder="Password"
|
||||
value={password}
|
||||
onChange={e => setPassword(e.target.value)}
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
autoFocus={!!effectiveUsername}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* PIN pad */}
|
||||
{loginMethod === 'pin' && (
|
||||
<div className="space-y-3">
|
||||
<PinDots length={4} filled={pin.length} />
|
||||
<PinPad pin={pin} onChange={setPin} disabled={loading} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && <p className="text-center text-[13px] text-rose-500">{error}</p>}
|
||||
|
||||
{/* None mode: just a Log In button */}
|
||||
{loginMethod === 'none' && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="primary"
|
||||
disabled={loading || (!effectiveUsername && !username.trim())}
|
||||
className="w-full justify-center py-3"
|
||||
onClick={() => handleAutoLogin(effectiveUsername || username.trim())}
|
||||
>
|
||||
{loading ? 'Signing in…' : 'Log In'}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{/* Password mode: submit button */}
|
||||
{loginMethod === 'password' && (
|
||||
<Button
|
||||
type="submit"
|
||||
variant="primary"
|
||||
disabled={loading || (!effectiveUsername && !username.trim()) || !password}
|
||||
className="w-full justify-center py-3"
|
||||
>
|
||||
{loading ? 'Signing in…' : 'Sign In'}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{/* PIN mode: auto-submits, show verifying text */}
|
||||
{loading && loginMethod === 'pin' && (
|
||||
<p className="text-center text-[13px] text-slate-400">Verifying…</p>
|
||||
)}
|
||||
|
||||
</form>
|
||||
{notice && (
|
||||
<div className="flex gap-2 rounded-control bg-warning-soft text-warning-ink text-label p-3 mb-5" role="status" data-testid="license-notice">
|
||||
<ShieldAlert size={16} className="shrink-0 mt-0.5" />
|
||||
<span>{notice}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{managers === null && !support
|
||||
? <div className="flex justify-center py-6"><Spinner /></div>
|
||||
: support
|
||||
? <SupportAccess onSignedIn={data => signedIn(data, { remember: false })} onBack={() => setSupport(false)} />
|
||||
: (
|
||||
<PasswordOrPin
|
||||
mode={loginInfo?.manager_mode || 'password'}
|
||||
account={account}
|
||||
accountName={known?.full_name}
|
||||
onOtherAccount={() => setManual(true)}
|
||||
onSignedIn={signedIn}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<p className="text-center text-[11px] text-slate-400 mt-4">Xenia POS · Manager Dashboard</p>
|
||||
{!support && loginInfo?.support && (
|
||||
<div className="text-center mt-4">
|
||||
<button type="button" className="text-label text-ink-3 hover:text-ink-2 underline-offset-2 hover:underline" onClick={() => setSupport(true)}>
|
||||
{t('login.supportLink')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function PasswordOrPin({ mode, account, accountName, onOtherAccount, onSignedIn }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const [username, setUsername] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
const [error, setError] = useState('')
|
||||
const [busy, setBusy] = useState(false)
|
||||
const user = account || username.trim()
|
||||
|
||||
async function send(secret) {
|
||||
setError('')
|
||||
try {
|
||||
const { data } = await client.post('/api/auth/login', { client: 'manager', username: user, ...secret }, LOGIN)
|
||||
onSignedIn(data)
|
||||
return true
|
||||
} catch (err) {
|
||||
setError(errorMessage(err, t))
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
async function submitPassword(e) {
|
||||
e.preventDefault()
|
||||
if (!user || !password || busy) return
|
||||
setBusy(true)
|
||||
const ok = await send({ password })
|
||||
setBusy(false)
|
||||
if (!ok) setPassword('')
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="grid gap-4" data-testid="login-form">
|
||||
{account
|
||||
? (
|
||||
<div className="flex items-center gap-3 rounded-control border border-line bg-surface-2 px-4 py-3" data-testid="login-account">
|
||||
<div className="flex h-9 w-9 items-center justify-center rounded-full bg-accent-soft text-accent-ink font-semibold text-label shrink-0">
|
||||
{(accountName || account).slice(0, 1).toUpperCase()}
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="text-body font-medium text-ink truncate">{accountName || account}</div>
|
||||
{accountName && <div className="text-caption text-ink-3 truncate">{account}</div>}
|
||||
</div>
|
||||
<button type="button" className="text-label text-accent-ink hover:underline shrink-0" onClick={onOtherAccount}>
|
||||
{t('login.otherAccount')}
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
: (
|
||||
<Field label={t('login.username')}>
|
||||
<Input value={username} onChange={e => setUsername(e.target.value)} autoComplete="username" autoCapitalize="none" autoFocus />
|
||||
</Field>
|
||||
)}
|
||||
|
||||
{mode === 'pin'
|
||||
? (
|
||||
<div className={user ? '' : 'opacity-50 pointer-events-none'}>
|
||||
<PinPad
|
||||
minLength={4}
|
||||
maxLength={8}
|
||||
title={t('login.pin')}
|
||||
error={error || undefined}
|
||||
captureKeyboard={!!account}
|
||||
onComplete={pin => send({ pin })}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
: (
|
||||
<form onSubmit={submitPassword} className="grid gap-4">
|
||||
<Field label={t('login.password')} error={error || undefined}>
|
||||
<Input type="password" value={password} onChange={e => setPassword(e.target.value)} autoComplete="current-password" autoFocus={!!account} />
|
||||
</Field>
|
||||
<Button type="submit" block loading={busy} disabled={!user || !password}>{t('login.signIn')}</Button>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function SupportAccess({ onSignedIn, onBack }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const f = useFormat()
|
||||
const [challenge, setChallenge] = useState(null)
|
||||
const [code, setCode] = useState('')
|
||||
const [error, setError] = useState('')
|
||||
const [busy, setBusy] = useState(false)
|
||||
const latest = useRef(0) // only the newest request may show its code (no stale challenge on screen)
|
||||
|
||||
async function newChallenge() {
|
||||
const id = ++latest.current
|
||||
setError('')
|
||||
setCode('')
|
||||
try {
|
||||
const { data } = await client.post('/api/auth/support/challenge', null, LOGIN)
|
||||
if (id === latest.current) setChallenge(data)
|
||||
} catch (err) {
|
||||
if (id !== latest.current) return
|
||||
setChallenge(null)
|
||||
setError(errorMessage(err, t))
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
newChallenge()
|
||||
return () => { latest.current++ } // unmounted (or React dev's double mount): ignore the answer
|
||||
}, []) // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
async function verify(e) {
|
||||
e.preventDefault()
|
||||
if (!challenge || !code.trim() || busy) return
|
||||
setBusy(true)
|
||||
setError('')
|
||||
try {
|
||||
const { data } = await client.post('/api/auth/support/verify', { challenge: challenge.challenge, code: code.trim() }, LOGIN)
|
||||
onSignedIn(data)
|
||||
} catch (err) {
|
||||
setError(errorMessage(err, t))
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={verify} className="grid gap-4">
|
||||
<p className="text-body text-ink-2 text-center">{t('support.intro')}</p>
|
||||
{challenge && (
|
||||
<div className="text-center">
|
||||
<div className="text-caption text-ink-3 mb-1">{t('support.challenge')}</div>
|
||||
<div className="font-mono text-display tracking-widest text-ink select-all" data-testid="support-challenge">{challenge.challenge}</div>
|
||||
<div className="text-caption text-ink-3 mt-1">{t('support.expires', { time: f.formatTime(challenge.expires_at) })}</div>
|
||||
</div>
|
||||
)}
|
||||
<Field label={t('support.answer')} error={error || undefined}>
|
||||
<Input value={code} onChange={e => setCode(e.target.value)} autoCapitalize="characters" autoComplete="off" spellCheck={false} disabled={!challenge} />
|
||||
</Field>
|
||||
<Button type="submit" block loading={busy} disabled={!challenge || !code.trim()}>{t('support.verify')}</Button>
|
||||
<div className="flex justify-between text-label">
|
||||
<button type="button" className="inline-flex items-center gap-1 text-ink-3 hover:text-ink-2" onClick={onBack}>
|
||||
<ArrowLeft size={14} /> {t('support.back')}
|
||||
</button>
|
||||
<button type="button" className="text-accent-ink hover:underline" onClick={newChallenge}>{t('support.newChallenge')}</button>
|
||||
</div>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -6,11 +6,12 @@ const useAuthStore = create((set) => ({
|
||||
savedUsername: localStorage.getItem('manager_username') || null,
|
||||
locked: sessionStorage.getItem('manager_locked') === 'true',
|
||||
|
||||
login(user, token) {
|
||||
// remember=false: don't offer this account on the next sign-in (support sessions)
|
||||
login(user, token, { remember = true } = {}) {
|
||||
localStorage.setItem('manager_token', token)
|
||||
localStorage.setItem('manager_username', user.username)
|
||||
if (remember) localStorage.setItem('manager_username', user.username)
|
||||
sessionStorage.removeItem('manager_locked')
|
||||
set({ user, token, savedUsername: user.username, locked: false })
|
||||
set(s => ({ user, token, savedUsername: remember ? user.username : s.savedUsername, locked: false }))
|
||||
},
|
||||
|
||||
// Restores user after a page refresh without touching the lock state.
|
||||
@@ -31,10 +32,10 @@ const useAuthStore = create((set) => ({
|
||||
set({ locked: true })
|
||||
},
|
||||
|
||||
unlock(user, token) {
|
||||
localStorage.setItem('manager_token', token)
|
||||
// The same session continues (POST /api/auth/unlock): no new token
|
||||
unlock(user) {
|
||||
sessionStorage.removeItem('manager_locked')
|
||||
set({ user, token, locked: false })
|
||||
set({ user, locked: false })
|
||||
},
|
||||
|
||||
updateUser(updatedUser) {
|
||||
|
||||
Reference in New Issue
Block a user