From 49a412d7487ad86241c2a84cdc9e87ed3d62fb79 Mon Sep 17 00:00:00 2001 From: bonamin Date: Fri, 13 Nov 2026 22:17:09 +0200 Subject: [PATCH] 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 --- docs/README.md | 2 +- local_backend/core/errors.py | 1 + local_backend/core/modules/api.py | 15 +- local_backend/routers/auth.py | 40 ++ local_backend/tests/test_unlock.py | 74 +++ manager_dashboard/src/layouts/AppLayout.jsx | 117 +---- manager_dashboard/src/pages/LoginPage.jsx | 550 ++++++++------------ manager_dashboard/src/store/authStore.js | 13 +- packages/access/src/AccessProvider.jsx | 1 + packages/i18n/locales/el/common.json | 3 +- packages/i18n/locales/el/errors.json | 3 +- packages/i18n/locales/el/manager.json | 31 ++ packages/i18n/locales/en/common.json | 3 +- packages/i18n/locales/en/errors.json | 3 +- packages/i18n/locales/en/manager.json | 31 ++ packages/i18n/src/hooks.js | 1 + packages/ui/src/components.css | 2 + packages/ui/src/components/PinPad.jsx | 55 +- packages/ui/src/components/labels.js | 1 + packages/ui/src/components/pin.js | 6 + packages/ui/tests/pin.test.mjs | 13 +- tests/e2e/manager.mjs | 84 ++- 22 files changed, 574 insertions(+), 475 deletions(-) create mode 100644 local_backend/tests/test_unlock.py diff --git a/docs/README.md b/docs/README.md index 0cd8885..0465975 100644 --- a/docs/README.md +++ b/docs/README.md @@ -171,7 +171,7 @@ Design tokens are CSS variables prefixed `--x-` (`packages/ui/src/tokens.css`), New UI text goes into `packages/i18n/locales/en/.json` first, then `el` (same keys, same `{{placeholders}}`), and is shown with `t()` from `@xenia/i18n` (`useTranslation`, re-exported). Dates and times are shown only through `useFormat()` (`formatTime`, `formatDateTime`, `formatDate`, `formatRelative`), which use the venue zone from bootstrap; money with `formatMoney`, numbers with `formatNumber`; typed numbers are read with `parseNumber` (comma or dot). Business dates (`YYYY-MM-DD`) go to `formatDate` as they are. `npm test -w @xenia/i18n` runs `scripts/check-i18n.mjs`, which fails on keys missing in English, placeholder mismatches, and `toLocale…String()` / `new Intl.DateTimeFormat(` without `timeZone` in new code (`packages/*`, `terminal/`); it warns for missing Greek. The v1 apps' Greek strings convert in phases 4 and 6. The `@xenia/ui` components get their texts from `` at the app root. **CS-18. Frontends talk to the backend through `@xenia/api` and read access from bootstrap** (branch `platform-v2`, D-7, D-10, §9). -An app makes one client with `createApiClient({ axios, baseURL, getToken, getDeviceToken, onUnauthorized })` (its own axios; the waiter passes `baseURL: () => apiBase()` when it moves, CS-8). Errors carry `err.xenia = { code, params, message, status, offline }`; show them with `errorMessage(err, t)` (texts in `packages/i18n/locales/*/errors.json`, which a test keeps complete against `core/errors.py`: a new backend code needs both texts). A 401 means "session ended" and logs out, so a form whose own wrong-credentials answer is a 401 (login, unlock, PIN checks) passes `{ xenia: { ignoreUnauthorized: true } }`. The app root is ``: it reloads bootstrap whenever the token changes and mounts the manager-approval dialog, so any request refused with `access.override_possible` is retried after a manager's PIN without extra code. Hide UI with `useCan(key)` / `` / `` (the backend still checks, CS-14). Live events: `createLiveClient` (one implementation; don't open sockets by hand). +An app makes one client with `createApiClient({ axios, baseURL, getToken, getDeviceToken, onUnauthorized })` (its own axios; the waiter passes `baseURL: () => apiBase()` when it moves, CS-8). Errors carry `err.xenia = { code, params, message, status, offline }`; show them with `errorMessage(err, t)` (texts in `packages/i18n/locales/*/errors.json`, which a test keeps complete against `core/errors.py`: a new backend code needs both texts). A 401 means "session ended" and logs out, so a form whose own wrong-credentials answer is a 401 (login, unlock, PIN checks) passes `{ xenia: { ignoreUnauthorized: true } }`. Lock screens never log in again: they call `POST /api/auth/unlock {pin}` with the current session (same token; 5 wrong PINs end the session); manager sign-in sends `client: "manager"` and reads its mode from bootstrap `login`. The app root is ``: it reloads bootstrap whenever the token changes and mounts the manager-approval dialog, so any request refused with `access.override_possible` is retried after a manager's PIN without extra code. Hide UI with `useCan(key)` / `` / `` (the backend still checks, CS-14). Live events: `createLiveClient` (one implementation; don't open sockets by hand). **CS-15. Support access is a challenge code, never a password** (branch `platform-v2`, D-16). There is no master account. A site's `SUPPORT_SECRET` (env only) comes from `tools/support_code.py --site-secret `, derived from the builder's master key in `%USERPROFILE%\.xenia\support_master_key.txt` (outside the repo, back it up). The derivation lives in `local_backend/core/support_codes.py` (stdlib only, the tool loads it by path) and is re-implemented for the e2e suites in `tests/e2e/lib/support.mjs`; `tests/test_support.py` pins a vector both must match. The e2e backends log in through support access (`login()` in `lib/proc.mjs`). diff --git a/local_backend/core/errors.py b/local_backend/core/errors.py index c2970c3..2e08635 100644 --- a/local_backend/core/errors.py +++ b/local_backend/core/errors.py @@ -62,6 +62,7 @@ CODES: dict[str, tuple[int, str]] = { "auth.username_required": (422, "Enter your username."), "auth.client_not_allowed": (403, "This account can't use the {client} app."), "auth.session_not_found": (404, "Session not found."), + "auth.wrong_pin": (401, "Wrong PIN. {attempts_left} tries left before you are signed out."), "auth.support_not_configured": (503, "Support access isn't set up on this site."), "auth.support_code_invalid": (401, "That support code is wrong or has expired. Ask for a new challenge."), "auth.support_rate_limited": (429, "Too many support challenges. Wait a few minutes and try again."), diff --git a/local_backend/core/modules/api.py b/local_backend/core/modules/api.py index eb286ab..5891f5c 100644 --- a/local_backend/core/modules/api.py +++ b/local_backend/core/modules/api.py @@ -1,7 +1,8 @@ """Platform endpoints (APPS_PLATFORM §4.1, §7.2, §9): /api/platform/... GET /bootstrap what every frontend loads first: venue (name, tz, language, - currency), the effective modules, and, if logged in, the user, + currency), the effective modules, the license state, the login + settings a login screen needs, and, if logged in, the user, their language and permission keys. Works without login (login screens need the venue language and zone). GET /modules the full catalogue with each module's state (logged in). @@ -75,6 +76,16 @@ def _module_out(m, enabled: dict, effective: frozenset) -> dict: } +def _login_info(db: Session) -> dict: + from config import settings as cfg + from core import sessions + return { + "manager_mode": sessions.manager_login_mode(db), # password | pin + "autofill_username": _setting(db, "security.autofill_username", "true") == "true", + "support": bool(cfg.SUPPORT_SECRET and cfg.SITE_ID), # "Support access" is offered + } + + @router.get("/bootstrap", dependencies=[Depends(public())]) def bootstrap( request: Request, @@ -98,6 +109,8 @@ def bootstrap( }, "modules": [{"key": m.key, "kind": m.kind} for m in registry().values() if m.key in effective], "license": {"mode": entitlements.current().mode, "reason": entitlements.current().reason}, + # what a login screen needs before anyone is signed in (plan step 2.6b) + "login": _login_info(db), "languages": list(i18n.SUPPORTED_LANGUAGES), "user": None, "language": i18n.venue_language(), diff --git a/local_backend/routers/auth.py b/local_backend/routers/auth.py index 757dcd5..60d139b 100644 --- a/local_backend/routers/auth.py +++ b/local_backend/routers/auth.py @@ -3,6 +3,7 @@ from core.access.check import holds from core.access.queries import holders_filter import bcrypt import logging +import threading from typing import Optional import jwt @@ -143,6 +144,45 @@ def refresh(credentials: HTTPAuthorizationCredentials = Depends(bearer), db: Ses return TokenResponse(access_token=make_token(user, payload["sid"]), user=UserOut.model_validate(user)) +# ── Unlock (plan step 2.6b) ────────────────────────────────────────────────── +# The manager's lock screen (and later the apps' own) checks the PIN of the user who owns +# the CURRENT session, and keeps that session: no new login, no new token, so the +# single-session rules never see a second login. After UNLOCK_MAX_FAILURES wrong tries +# the session is ended (someone is guessing on an unattended screen). + +UNLOCK_MAX_FAILURES = 5 +_unlock_failures: dict[str, int] = {} # sid -> wrong tries since the last success +_unlock_lock = threading.Lock() + + +class UnlockRequest(_PydanticBase): + pin: Optional[str] = None + password: Optional[str] = None + + +@router.post("/unlock") +def unlock(body: UnlockRequest, request: Request, db: Session = Depends(get_db), + user: User = Depends(get_current_user)): + """POST {pin} (or {password}) with the session's own token. 200 {user} = unlocked. + Wrong: 401 auth.wrong_pin {attempts_left}; the last allowed miss ends the session + (401 auth.session_ended).""" + sid = getattr(request.state, "xenia_sid", None) + if _check_secret(user, body.pin, body.password, db): + with _unlock_lock: + _unlock_failures.pop(sid, None) + return {"user": UserOut.model_validate(user)} + with _unlock_lock: + failures = _unlock_failures.get(sid, 0) + 1 + _unlock_failures[sid] = failures + if failures >= UNLOCK_MAX_FAILURES: + with _unlock_lock: + _unlock_failures.pop(sid, None) + sessions.end(db, sid, "unlock_failed") + _logger.warning("auth.unlock: too many wrong PINs, session ended user=%s", user.id) + raise XeniaError("auth.session_ended") + raise XeniaError("auth.wrong_pin", attempts_left=UNLOCK_MAX_FAILURES - failures) + + @router.post("/logout", dependencies=[Depends(public())]) def logout(credentials: Optional[HTTPAuthorizationCredentials] = Depends(_optional_bearer), token: Optional[str] = None, db: Session = Depends(get_db)): diff --git a/local_backend/tests/test_unlock.py b/local_backend/tests/test_unlock.py new file mode 100644 index 0000000..e160455 --- /dev/null +++ b/local_backend/tests/test_unlock.py @@ -0,0 +1,74 @@ +"""Lock-screen unlock (plan step 2.6b): the session's own PIN, the same session kept, +too many wrong tries end the session; the login settings in bootstrap.""" +from routers import auth as auth_router + +TEST_PIN = "1234" + + +def err(r): + return r.json()["error"]["code"] + + +def test_right_pin_unlocks_and_keeps_the_session(client, make_user, login): + user = make_user("store_manager") + headers = login(user) + r = client.post("/api/auth/unlock", json={"pin": TEST_PIN}, headers=headers) + assert r.status_code == 200, r.text + assert r.json()["user"]["id"] == user.id + assert "access_token" not in r.json() # no new token, no new session + assert client.get("/api/auth/me", headers=headers).status_code == 200 + + +def test_password_also_unlocks(client, make_user, login): + from tests.conftest import TEST_PASSWORD + headers = login(make_user("store_manager")) + assert client.post("/api/auth/unlock", json={"password": TEST_PASSWORD}, headers=headers).status_code == 200 + + +def test_wrong_pin_counts_down_then_ends_the_session(client, make_user, login): + headers = login(make_user("store_manager")) + left = [] + for _ in range(auth_router.UNLOCK_MAX_FAILURES - 1): + r = client.post("/api/auth/unlock", json={"pin": "0000"}, headers=headers) + assert r.status_code == 401 and err(r) == "auth.wrong_pin" + left.append(r.json()["error"]["params"]["attempts_left"]) + assert left == list(range(auth_router.UNLOCK_MAX_FAILURES - 1, 0, -1)) + assert client.get("/api/auth/me", headers=headers).status_code == 200, "still signed in before the last try" + r = client.post("/api/auth/unlock", json={"pin": "0000"}, headers=headers) + assert r.status_code == 401 and err(r) == "auth.session_ended" + assert err(client.get("/api/auth/me", headers=headers)) == "auth.session_ended" + + +def test_a_success_resets_the_count(client, make_user, login): + headers = login(make_user("store_manager")) + for _ in range(auth_router.UNLOCK_MAX_FAILURES - 1): + client.post("/api/auth/unlock", json={"pin": "0000"}, headers=headers) + assert client.post("/api/auth/unlock", json={"pin": TEST_PIN}, headers=headers).status_code == 200 + r = client.post("/api/auth/unlock", json={"pin": "0000"}, headers=headers) + assert r.json()["error"]["params"]["attempts_left"] == auth_router.UNLOCK_MAX_FAILURES - 1 + + +def test_the_pin_is_the_session_owners(client, make_user, login): + import bcrypt + other = make_user("store_manager", pin_hash=bcrypt.hashpw(b"5678", bcrypt.gensalt(4)).decode()) + headers = login(other) # another user's PIN (1234) must not unlock it + assert err(client.post("/api/auth/unlock", json={"pin": TEST_PIN}, headers=headers)) == "auth.wrong_pin" + + +def test_needs_a_session(client): + assert client.post("/api/auth/unlock", json={"pin": TEST_PIN}).status_code in (401, 403) + + +def test_bootstrap_has_the_login_settings(client, db): + from models.settings import PosSettings + b = client.get("/api/platform/bootstrap").json() + assert b["login"]["manager_mode"] == "password" + assert b["login"]["autofill_username"] is True + assert b["login"]["support"] in (True, False) + row = db.query(PosSettings).filter(PosSettings.key == "auth.manager_login_mode").first() + if row is None: + db.add(PosSettings(key="auth.manager_login_mode", value="pin")) + else: + row.value = "pin" + db.commit() + assert client.get("/api/platform/bootstrap").json()["login"]["manager_mode"] == "pin" diff --git a/manager_dashboard/src/layouts/AppLayout.jsx b/manager_dashboard/src/layouts/AppLayout.jsx index be24343..31397bb 100644 --- a/manager_dashboard/src/layouts/AppLayout.jsx +++ b/manager_dashboard/src/layouts/AppLayout.jsx @@ -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 ( -
-
-
-
-
- -
+
+
+
+
+
-

Locked

-

{displayName}

+

{t('lock.title')}

+

{displayName}

- -
-
- {Array.from({ length: 4 }).map((_, i) => ( -
- ))} -
-
- {DIGITS.map((d, i) => ( - - ))} -
-
- - {error &&

{error}

} - {loading &&

Verifying…

} - -
@@ -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() } diff --git a/manager_dashboard/src/pages/LoginPage.jsx b/manager_dashboard/src/pages/LoginPage.jsx index a21a2b4..03bc3ff 100644 --- a/manager_dashboard/src/pages/LoginPage.jsx +++ b/manager_dashboard/src/pages/LoginPage.jsx @@ -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 ( -
- {Array.from({ length }).map((_, i) => ( -
- ))} -
- ) -} - -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 ( -
- {DIGITS.map((d, i) => ( - - ))} -
- ) -} - -// ─── Manager picker (multi-manager + login=none) ────────────────────────────── - -function ManagerPicker({ managers, onSelect }) { - return ( -
-
-

Select account

-

Choose your manager account to continue.

-
-
- {managers.map(m => ( - - ))} -
-
- ) -} - -// ─── 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 ( -
-
-
- ) - } - - // 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 ( -
+
-
+
+
+
+ {support ? : } +
+

{support ? t('support.title') : t('login.title')}

+

{venue?.name || t('login.subtitle')}

+
- {needsPicker ? ( - { setSelectedManager(m); handleAutoLogin(m.username) }} /> - ) : ( -
-
-
-
- -
-
-

Sign In

-

- {loginMethod === 'password' ? 'Enter your username and password' - : loginMethod === 'pin' ? 'Enter your username and PIN' - : 'Select your account'} -

-
- - {/* Username section */} - {manualMode ? ( - setUsername(e.target.value)} - autoComplete="off" - autoFocus - /> - ) : effectiveUsername ? ( -
-
-
- {effectiveUsername.charAt(0).toUpperCase()} -
-
-

{effectiveUsername}

-

Manager

-
-
- -
- ) : managers.length > 0 ? ( -
- {managers.map(m => ( - - ))} - -
- ) : ( - setUsername(e.target.value)} - autoComplete="off" - autoFocus - /> - )} - - {/* Password input */} - {loginMethod === 'password' && ( - setPassword(e.target.value)} - type="password" - autoComplete="current-password" - autoFocus={!!effectiveUsername} - /> - )} - - {/* PIN pad */} - {loginMethod === 'pin' && ( -
- - -
- )} - - {error &&

{error}

} - - {/* None mode: just a Log In button */} - {loginMethod === 'none' && ( - - )} - - {/* Password mode: submit button */} - {loginMethod === 'password' && ( - - )} - - {/* PIN mode: auto-submits, show verifying text */} - {loading && loginMethod === 'pin' && ( -

Verifying…

- )} - - + {notice && ( +
+ + {notice} +
)} + + {managers === null && !support + ?
+ : support + ? signedIn(data, { remember: false })} onBack={() => setSupport(false)} /> + : ( + setManual(true)} + onSignedIn={signedIn} + /> + )}
-

Xenia POS · Manager Dashboard

+ {!support && loginInfo?.support && ( +
+ +
+ )}
) } + +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 ( +
+ {account + ? ( +
+
+ {(accountName || account).slice(0, 1).toUpperCase()} +
+
+
{accountName || account}
+ {accountName &&
{account}
} +
+ +
+ ) + : ( + + setUsername(e.target.value)} autoComplete="username" autoCapitalize="none" autoFocus /> + + )} + + {mode === 'pin' + ? ( +
+ send({ pin })} + /> +
+ ) + : ( +
+ + setPassword(e.target.value)} autoComplete="current-password" autoFocus={!!account} /> + + +
+ )} +
+ ) +} + +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 ( +
+

{t('support.intro')}

+ {challenge && ( +
+
{t('support.challenge')}
+
{challenge.challenge}
+
{t('support.expires', { time: f.formatTime(challenge.expires_at) })}
+
+ )} + + setCode(e.target.value)} autoCapitalize="characters" autoComplete="off" spellCheck={false} disabled={!challenge} /> + + +
+ + +
+
+ ) +} diff --git a/manager_dashboard/src/store/authStore.js b/manager_dashboard/src/store/authStore.js index 4f472d7..9b6830c 100644 --- a/manager_dashboard/src/store/authStore.js +++ b/manager_dashboard/src/store/authStore.js @@ -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) { diff --git a/packages/access/src/AccessProvider.jsx b/packages/access/src/AccessProvider.jsx index 1799263..3405501 100644 --- a/packages/access/src/AccessProvider.jsx +++ b/packages/access/src/AccessProvider.jsx @@ -48,6 +48,7 @@ export function AccessProvider({ venue: d.venue, user: d.user, license: d.license, + login: d.login, languages: d.languages, language: d.language, modules: new Set((d.modules || []).map(m => m.key)), diff --git a/packages/i18n/locales/el/common.json b/packages/i18n/locales/el/common.json index d96363b..8b4a29d 100644 --- a/packages/i18n/locales/el/common.json +++ b/packages/i18n/locales/el/common.json @@ -31,7 +31,8 @@ "moreInfo": "Περισσότερες πληροφορίες", "notifications": "Ειδοποιήσεις", "backspace": "Διαγραφή", - "pinProgress": "{{count}} από {{total}} ψηφία" + "pinProgress": "{{count}} από {{total}} ψηφία", + "submit": "OK" }, "override": { "title": "Έγκριση υπευθύνου", diff --git a/packages/i18n/locales/el/errors.json b/packages/i18n/locales/el/errors.json index e63fa43..25a5be3 100644 --- a/packages/i18n/locales/el/errors.json +++ b/packages/i18n/locales/el/errors.json @@ -35,7 +35,8 @@ "session_not_found": "Η σύνδεση δεν βρέθηκε.", "support_not_configured": "Η πρόσβαση υποστήριξης δεν έχει ρυθμιστεί σε αυτό το κατάστημα.", "support_code_invalid": "Ο κωδικός υποστήριξης είναι λάθος ή έχει λήξει. Ζητήστε νέο κωδικό πρόκλησης.", - "support_rate_limited": "Πολλές αιτήσεις υποστήριξης. Περιμένετε λίγα λεπτά και δοκιμάστε ξανά." + "support_rate_limited": "Πολλές αιτήσεις υποστήριξης. Περιμένετε λίγα λεπτά και δοκιμάστε ξανά.", + "wrong_pin": "Λάθος PIN. Απομένουν {{attempts_left}} προσπάθειες πριν αποσυνδεθείτε." }, "device": { "revoked": "Αυτή η συσκευή αφαιρέθηκε. Κάντε ξανά σύζευξη.", diff --git a/packages/i18n/locales/el/manager.json b/packages/i18n/locales/el/manager.json index 75f8c41..21c1461 100644 --- a/packages/i18n/locales/el/manager.json +++ b/packages/i18n/locales/el/manager.json @@ -46,5 +46,36 @@ "edit": "Επεξεργασία προφίλ", "signOut": "Αποσύνδεση", "language": "Γλώσσα" + }, + "login": { + "title": "Σύνδεση", + "subtitle": "Πίνακας διαχείρισης", + "username": "Όνομα χρήστη", + "password": "Κωδικός", + "pin": "PIN", + "signIn": "Σύνδεση", + "otherAccount": "Άλλος λογαριασμός", + "supportLink": "Πρόσβαση υποστήριξης" + }, + "support": { + "title": "Πρόσβαση υποστήριξης", + "intro": "Διαβάστε αυτόν τον κωδικό στην υποστήριξη της Xenia. Θα σας δώσουν έναν κωδικό πίσω.", + "challenge": "Κωδικός για την υποστήριξη", + "answer": "Κωδικός της υποστήριξης", + "verify": "Άνοιγμα συνεδρίας υποστήριξης", + "newChallenge": "Νέος κωδικός", + "back": "Πίσω στη σύνδεση", + "expires": "Ο κωδικός ισχύει μέχρι τις {{time}}." + }, + "license": { + "expired": "Η άδεια έχει λήξει. Το κατάστημα λειτουργεί με τη δωρεάν έκδοση μέχρι την ανανέωση: κάποιες λειτουργίες είναι κλειστές.", + "inactive": "Η άδεια δεν είναι ενεργή. Το κατάστημα λειτουργεί με τη δωρεάν έκδοση: κάποιες λειτουργίες είναι κλειστές.", + "locked": "Ο πάροχος κλείδωσε την άδεια του καταστήματος. Λειτουργεί με τη δωρεάν έκδοση: κάποιες λειτουργίες είναι κλειστές.", + "clock": "Το ρολόι του server γύρισε πίσω, οπότε η άδεια δεν μπορεί να ελεγχθεί. Διορθώστε την ημερομηνία και ώρα του server ή συνδέστε τον στο internet.", + "unverified": "Η άδεια δεν έχει ελεγχθεί ακόμα (δεν υπάρχει σύνδεση με τον server αδειών). Προς το παρόν λειτουργεί η δωρεάν έκδοση." + }, + "lock": { + "title": "Κλειδωμένο", + "signOutInstead": "Αποσύνδεση" } } diff --git a/packages/i18n/locales/en/common.json b/packages/i18n/locales/en/common.json index b2cde66..31bd885 100644 --- a/packages/i18n/locales/en/common.json +++ b/packages/i18n/locales/en/common.json @@ -31,7 +31,8 @@ "moreInfo": "More info", "notifications": "Notifications", "backspace": "Delete", - "pinProgress": "{{count}} of {{total}} digits entered" + "pinProgress": "{{count}} of {{total}} digits entered", + "submit": "OK" }, "override": { "title": "Manager approval", diff --git a/packages/i18n/locales/en/errors.json b/packages/i18n/locales/en/errors.json index badba1d..0d281d8 100644 --- a/packages/i18n/locales/en/errors.json +++ b/packages/i18n/locales/en/errors.json @@ -35,7 +35,8 @@ "session_not_found": "Session not found.", "support_not_configured": "Support access isn't set up on this site.", "support_code_invalid": "That support code is wrong or has expired. Ask for a new challenge.", - "support_rate_limited": "Too many support challenges. Wait a few minutes and try again." + "support_rate_limited": "Too many support challenges. Wait a few minutes and try again.", + "wrong_pin": "Wrong PIN. {{attempts_left}} tries left before you are signed out." }, "device": { "revoked": "This device was removed. Pair it again.", diff --git a/packages/i18n/locales/en/manager.json b/packages/i18n/locales/en/manager.json index bf53567..0b4e983 100644 --- a/packages/i18n/locales/en/manager.json +++ b/packages/i18n/locales/en/manager.json @@ -46,5 +46,36 @@ "edit": "Edit profile", "signOut": "Sign out", "language": "Language" + }, + "login": { + "title": "Sign in", + "subtitle": "Manager dashboard", + "username": "Username", + "password": "Password", + "pin": "PIN", + "signIn": "Sign in", + "otherAccount": "Use another account", + "supportLink": "Support access" + }, + "support": { + "title": "Support access", + "intro": "Read this code to Xenia support. They will give you a code back.", + "challenge": "Code for support", + "answer": "Support's code", + "verify": "Open support session", + "newChallenge": "New code", + "back": "Back to sign in", + "expires": "This code is valid until {{time}}." + }, + "license": { + "expired": "The license has expired. This venue runs the free version until it's renewed: some features are off.", + "inactive": "The license isn't active. This venue runs the free version: some features are off.", + "locked": "The license provider locked this venue. It runs the free version: some features are off.", + "clock": "The server's clock went back in time, so the license can't be trusted. Fix the server's date and time or connect it to the internet.", + "unverified": "The license hasn't been verified yet (no connection to the license server). This venue runs the free version for now." + }, + "lock": { + "title": "Locked", + "signOutInstead": "Sign out instead" } } diff --git a/packages/i18n/src/hooks.js b/packages/i18n/src/hooks.js index 5b434d7..3321659 100644 --- a/packages/i18n/src/hooks.js +++ b/packages/i18n/src/hooks.js @@ -34,6 +34,7 @@ export function useUiLabels() { moreInfo: t('ui.moreInfo'), notifications: t('ui.notifications'), backspace: t('ui.backspace'), + submit: t('ui.submit'), pinProgress: (count, total) => t('ui.pinProgress', { count, total }), }), [t, language]) // eslint-disable-line react-hooks/exhaustive-deps } diff --git a/packages/ui/src/components.css b/packages/ui/src/components.css index 3729bcf..d80e49c 100644 --- a/packages/ui/src/components.css +++ b/packages/ui/src/components.css @@ -193,6 +193,8 @@ .x-pinpad__key:focus-visible { outline: none; box-shadow: var(--x-focus-ring); } .x-pinpad__key:disabled { opacity: 0.5; cursor: not-allowed; } .x-pinpad__key--backspace { background: transparent; color: var(--x-ink-2); } +.x-pinpad__key--submit { background: var(--x-accent); color: var(--x-accent-fg); } +.x-pinpad__key--submit:hover:not(:disabled) { background: var(--x-accent-strong); } @keyframes x-shake { 20% { transform: translateX(-8px); } 40% { transform: translateX(7px); } 60% { transform: translateX(-5px); } 80% { transform: translateX(3px); } diff --git a/packages/ui/src/components/PinPad.jsx b/packages/ui/src/components/PinPad.jsx index fbedaa6..1e9056b 100644 --- a/packages/ui/src/components/PinPad.jsx +++ b/packages/ui/src/components/PinPad.jsx @@ -1,32 +1,40 @@ import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react' import { cx } from '../internal/cx.js' import { Spinner } from './Spinner.jsx' -import { nextPin, pinAction } from './pin.js' +import { canSubmit, nextPin, pinAction } from './pin.js' import { useLabels } from './labels.js' const KEYS = ['1', '2', '3', '4', '5', '6', '7', '8', '9', null, '0', 'Backspace'] +const KEYS_VARIABLE = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'Enter', '0', 'Backspace'] /** * Numeric PIN entry: dots + a 3×4 keypad, also driven by the physical keyboard. * * { await unlock(pin) }} /> * - * onComplete(pin) runs when `length` digits are in. If it returns a promise the pad + * Fixed length (`length`, default 4): onComplete(pin) runs as soon as `length` digits are in. + * Variable length (`minLength` + `maxLength`, e.g. PINs of 4–8 digits): an OK key (and the + * Enter key) submits once at least `minLength` digits are in. + * + * If onComplete returns a promise the pad * shows a spinner until it settles. If it throws / rejects (or returns false), the pad * shakes, shows `error` text if given, and clears for another try. On success it clears too. * * error: text under the dots (e.g. "Wrong PIN"); a change of it also shakes the pad. * captureKeyboard (default true): digits/Backspace typed anywhere go to the pad, * except while the user is typing in a field. - * backspaceLabel / progressLabel(n, length) override the UiLabelsProvider texts. + * backspaceLabel / submitLabel / progressLabel(n, length) override the UiLabelsProvider texts. */ export function PinPad({ - length = 4, onComplete, onChange, disabled = false, error, title, - captureKeyboard = true, backspaceLabel, progressLabel, className, + length = 4, minLength, maxLength, onComplete, onChange, disabled = false, error, title, + captureKeyboard = true, backspaceLabel, submitLabel, progressLabel, className, }) { const labels = useLabels() const backspaceText = backspaceLabel ?? labels.backspace + const submitText = submitLabel ?? labels.submit const progress = progressLabel ?? labels.pinProgress + const variable = minLength != null && maxLength != null + const max = variable ? maxLength : length const [value, setValue] = useState('') const [busy, setBusy] = useState(false) const [shake, setShake] = useState(0) @@ -61,12 +69,16 @@ export function PinPad({ const { value: current, busy: isBusy, disabled: isDisabled } = latest.current const action = pinAction(key) if (!action || isBusy || isDisabled) return - const next = nextPin(current, action, length) + if (action.type === 'submit') { + if (variable && canSubmit(current, minLength)) submit(current) + return + } + const next = nextPin(current, action, max) if (next === current) return setValue(next) onChange?.(next) - if (next.length === length) submit(next) - }, [length, onChange, submit]) + if (!variable && next.length === max) submit(next) + }, [variable, minLength, max, onChange, submit]) useEffect(() => { if (!captureKeyboard) return @@ -74,38 +86,47 @@ export function PinPad({ if (e.ctrlKey || e.metaKey || e.altKey) return const t = e.target if (t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable)) return - if (pinAction(e.key)) { e.preventDefault(); press(e.key) } + const action = pinAction(e.key) + if (!action || (action.type === 'submit' && !variable)) return // Enter only means "OK" in variable mode + e.preventDefault() + press(e.key) } document.addEventListener('keydown', onKey) return () => document.removeEventListener('keydown', onKey) - }, [captureKeyboard, press]) + }, [captureKeyboard, press, variable]) return (
{title &&
{title}
} {/* Re-keyed on every failed attempt and on every new error text, which replays the shake */}
0 || error) && 'x-pinpad__dots--shake')} aria-hidden="true"> - {Array.from({ length }, (_, i) => ( + {Array.from({ length: variable ? Math.max(minLength, value.length) : max }, (_, i) => ( ))}
-
{progress(value.length, length)}
+
{progress(value.length, variable ? minLength : max)}
{busy ? : error ? {error} : null}
- {KEYS.map(k => k === null + {(variable ? KEYS_VARIABLE : KEYS).map(k => k === null ?