feat(waiter): sign-in v2 on the phones (platform-v2 step 4.2)

- Login follows auth.waiter_login_mode / auth.waiter_require_username from the
  bootstrap: name + PIN, name + password, typed username, or a "paired screens
  only" message for tap mode. POST /api/auth/login {client: "waiter"}; a miss
  shows the translated error without a reload.
- POST /api/auth/login-by-id removed; bootstrap login carries waiter_mode and
  waiter_require_username.
- Sign-out ends the session on the server (POST /api/auth/logout), so
  single_session_waiter = refuse_new no longer strands a waiter.
- Lock on the phone: menu "Lock", automatic lock / sign-out after inactivity
  (security.auto_lock*, auto_logout*), unlock with the PIN in the same session,
  lock kept across app restarts (restore() no longer clears it).
- e2e: new waiter.mjs (22 checks) in run-all; android.mjs signs in for real and
  locks/unlocks on the emulator; TLS live check waits for the socket; the
  rediscovery helper re-attaches to a stale WebView handle.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-16 15:25:00 +02:00
co-authored by Claude Opus 5.5
parent 9f5498332a
commit 8299184e3a
14 changed files with 664 additions and 106 deletions
+1 -1
View File
@@ -186,7 +186,7 @@ Design tokens are CSS variables prefixed `--x-` (`packages/ui/src/tokens.css`),
New UI text goes into `packages/i18n/locales/en/<ns>.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. Module names, their limits and **every permission key** have texts in `modules.json` (`modules:<module>.name`, `.limits.<key>`, `.permissions.<rest of the key, nested by its dots>`); `tests/test_module_texts.py` fails for a new module or key without them in both languages. The v1 apps' Greek strings convert in phases 4 and 6. The `@xenia/ui` components get their texts from `<UiLabelsProvider labels={useUiLabels()}>` 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 } }`. 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 `<AccessProvider client token i18n>`: 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)` / `<Can>` / `<RequireModule>` (the backend still checks, CS-14). Live events: `createLiveClient` (one implementation; don't open sockets by hand). A paired device passes `credentials: () => ({ device, token })` (sent in the first frame, never in the URL) and `onRefused(code)`. In the manager there is one connection, `live/LiveProvider.jsx` (opened with the signed-in shell); components listen with `useLiveEvent(type, handler)` (`'ready'` fires after each reconnect: refetch then).
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 the waiter `client: "waiter"` (`user_id` or `username` + `pin` or `password`); both read their mode from bootstrap `login` (`manager_mode`, `waiter_mode`, `waiter_require_username`). Signing out calls `POST /api/auth/logout` so single-session venues free the seat; restoring the user after a reopen must not clear a lock (the waiter's `authStore.restore`, not `login`). The app root is `<AccessProvider client token i18n>`: 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)` / `<Can>` / `<RequireModule>` (the backend still checks, CS-14). Live events: `createLiveClient` (one implementation; don't open sockets by hand). A paired device passes `credentials: () => ({ device, token })` (sent in the first frame, never in the URL) and `onRefused(code)`. In the manager there is one connection, `live/LiveProvider.jsx` (opened with the signed-in shell); components listen with `useLiveEvent(type, handler)` (`'ready'` fires after each reconnect: refetch then).
**CS-19. Device apps: who hears what, and replays** (branch `platform-v2`, phase 3).
- A screen with sign-in `none` (customer display) receives **every** broadcast event; send what is meant for one screen with `device_ids=[…]` (the customer display's `display.state` goes only to the displays linked to that POS) and what is meant for a role with `user_ids=[…]` plus the screens that need it (`call_incoming`: users with `caller_id.use` + the counter screens).
+4
View File
@@ -82,6 +82,10 @@ def _login_info(db: Session) -> dict:
from core import sessions
return {
"manager_mode": sessions.manager_login_mode(db), # password | pin
# the waiter app's sign-in (plan 4.2): pin | password | tap (tap = paired screens only:
# a phone shows that it can't sign in that way)
"waiter_mode": sessions.waiter_login_mode(db),
"waiter_require_username": sessions.waiter_requires_username(db),
"autofill_username": _setting(db, "security.autofill_username", "true") == "true",
"support": bool(cfg.SUPPORT_SECRET and cfg.SITE_ID), # "Support access" is offered
}
-9
View File
@@ -19,9 +19,6 @@ from pydantic import BaseModel as _PydanticBase
_logger = logging.getLogger(__name__)
class LoginByIdRequest(_PydanticBase):
waiter_id: int
pin: str
from schemas.user import UserOut
from core.i18n import normalize_language
from routers.deps import bearer, get_current_user, make_token, decode_token, make_support_user
@@ -128,12 +125,6 @@ def login(body: LoginRequest, request: Request, db: Session = Depends(get_db)):
user_id=body.user_id, pin=body.pin, password=body.password)
@router.post("/login-by-id", response_model=TokenResponse, dependencies=[Depends(public())], deprecated=True)
def login_by_id(body: LoginByIdRequest, request: Request, db: Session = Depends(get_db)):
"""DEPRECATED (current waiter app): = POST /login {client: "waiter", user_id, pin}. Removed in phase 4."""
return do_login(db, request, client="waiter", username=None, user_id=body.waiter_id, pin=body.pin, password=None)
@router.post("/refresh", response_model=TokenResponse)
def refresh(credentials: HTTPAuthorizationCredentials = Depends(bearer), db: Session = Depends(get_db),
user: User = Depends(get_current_user)):
+11 -2
View File
@@ -57,10 +57,10 @@ def test_wrong_password_and_wrong_app(client, make_user):
# ── waiter logins ────────────────────────────────────────────────────────────
def test_waiter_pin_by_id_and_deprecated_endpoint(client, make_user):
def test_waiter_pin_by_id(client, make_user):
w = make_user(role="waiter")
assert client.post("/api/auth/login", json={"client": "waiter", "user_id": w.id, "pin": TEST_PIN}).status_code == 200
assert client.post("/api/auth/login-by-id", json={"waiter_id": w.id, "pin": TEST_PIN}).status_code == 200
assert client.post("/api/auth/login-by-id", json={"waiter_id": w.id, "pin": TEST_PIN}).status_code == 404 # removed in 4.2
chef = make_user(role="chef")
r = client.post("/api/auth/login", json={"client": "waiter", "user_id": chef.id, "pin": TEST_PIN})
assert r.json()["error"]["code"] == "auth.client_not_allowed"
@@ -217,3 +217,12 @@ def test_idle_days_setting_and_zero_means_never(client, db, make_user, admin_h):
_set(client, admin_h, "auth.idle_days", "3")
_age(db, 4, user_id=w.id)
assert client.get("/api/auth/me", headers=wh).status_code == 401
def test_bootstrap_tells_the_waiter_app_how_to_sign_in(client, admin_h):
login = client.get("/api/platform/bootstrap").json()["login"]
assert (login["waiter_mode"], login["waiter_require_username"]) == ("pin", False)
_set(client, admin_h, "auth.waiter_login_mode", "password")
_set(client, admin_h, "auth.waiter_require_username", "true")
login = client.get("/api/platform/bootstrap").json()["login"]
assert (login["waiter_mode"], login["waiter_require_username"]) == ("password", True)
+39 -11
View File
@@ -71,14 +71,29 @@ async function basics() {
r.check('pairing saves and activates the venue', st?.active === 'test-site-1' && st.venues['test-site-1'].baseUrl.includes(`${H}:`), JSON.stringify(st))
r.check('login screen shows the venue + "Αλλαγή"', (await v.evaluate('document.body.innerText')).includes('Αλλαγή'))
await v.evaluate(`localStorage.setItem('xenia:test-site-1:token', ${JSON.stringify(token)})`)
v = await reloadApp(v, '/tables')
await sleep(7000)
r.check('logged in: /tables', (await v.evaluate('location.pathname')) === '/tables')
// 4.2: a real sign-in in the native app: pick your name, PIN on the pad, start the shift
await fetch(`${b1.url}/api/business-day/open`, { method: 'POST', headers: { 'content-type': 'application/json', authorization: `Bearer ${token}` }, body: '{}' }).catch(() => {})
await tap(v, '[data-testid="waiter-card"]', 'Κωνσταντίνου')
for (const d of '3302') await tap(v, 'button.pin-btn', d)
await tap(v, 'button', 'Έναρξη Βάρδιας', { timeout: 15_000 })
await waitFor(() => v.evaluate("location.pathname === '/tables'"), 15_000, 500)
await sleep(3000)
r.check('signed in with name + PIN on the pad: /tables', (await v.evaluate('location.pathname')) === '/tables'
&& !!(await v.evaluate("localStorage.getItem('xenia:test-site-1:token')")))
const dbs = await v.evaluate('indexedDB.databases().then(d => d.map(x => x.name))')
r.check('IndexedDB namespaced per venue', dbs.includes('pos_snapshot__test-site-1'), dbs.join(','))
r.check('live WebSocket (green bar)', (await connectivityColor(v)) === GREEN)
// 4.2: lock from the menu, unlock with the PIN on the pad (same session)
const before = await v.evaluate("localStorage.getItem('xenia:test-site-1:token')")
await tap(v, 'button[title="Μενού χρήστη"]')
await tap(v, '[data-testid="menu-lock"]')
const lockedOk = await waitFor(() => v.evaluate("!!document.querySelector('[data-testid=lock-screen]')"), 5000, 300)
for (const d of '3302') await tap(v, '[data-testid="lock-screen"] button.pin-btn', d)
const unlocked = await waitFor(() => v.evaluate("!document.querySelector('[data-testid=lock-screen]')"), 8000, 300)
r.check('lock from the menu, unlock with the PIN: same session', !!lockedOk && !!unlocked
&& (await v.evaluate("localStorage.getItem('xenia:test-site-1:token')")) === before)
back()
await sleep(1500)
r.check('hardware back on /tables keeps the app open', focusedWindow().includes(APP_ID))
@@ -157,9 +172,21 @@ async function rediscovery() {
v = await reloadApp(v)
// waits for what the screen shows instead of fixed sleeps (KI-009): the app reloads at the
// new address, so the WebView handle may need re-attaching meanwhile
const onScreen = (check, ms = 30_000) => waitFor(async () => {
try { return await check(v) } catch { v = await attach().catch(() => v); return false }
// A handle can also go stale without throwing (it keeps answering for a document that is
// gone): re-attach every ~5 s of "not yet". A timeout saves a real screenshot for the log.
let shots = 0
const onScreen = async (check, ms = 30_000) => {
let misses = 0
const ok = await waitFor(async () => {
try {
if (await check(v)) return true
if (++misses % 10 === 0) v = await attach().catch(() => v)
return false
} catch { v = await attach().catch(() => v); return false }
}, ms, 500)
if (!ok) shot(`android-rediscovery-timeout-${++shots}`)
return ok
}
r.check('setup: paired and logged in', !!(await onScreen(async vv => (await vv.evaluate('location.pathname')) === '/tables', 45_000)))
const stale = async (vv) => {
@@ -173,19 +200,19 @@ async function rediscovery() {
v = await stale(v)
r.check('logged in: server "moved" → found and saved', !!(await found()))
r.check('logged in: back on /tables, live', !!(await onScreen(async vv =>
(await vv.evaluate('location.pathname')) === '/tables' && (await connectivityColor(vv)) === GREEN, 40_000)))
(await vv.evaluate('location.pathname')) === '/tables' && (await connectivityColor(vv)) === GREEN, 40_000)), `${await v.evaluate('location.pathname').catch(() => '?')} ${await connectivityColor(v).catch(() => '?')}`)
await v.evaluate("localStorage.removeItem('xenia:test-site-1:token')")
v = await stale(v)
r.check('logged out: found and saved', !!(await found()))
r.check('logged out: found and saved', !!(await found()), await v.evaluate('location.pathname + " | " + document.body.innerText.slice(0, 200)').catch(e => String(e)))
r.check('logged out: waiter list loads from the new address', !!(await onScreen(async vv =>
(await vv.evaluate('document.body.innerText')).includes('Manager'), 40_000)))
(await vv.evaluate('document.body.innerText')).includes('Manager'), 40_000)), await v.evaluate('location.pathname + " | " + document.body.innerText.slice(0, 200)').catch(e => String(e)))
await backend.stop()
v = await stale(v)
const offlineShown = await onScreen(async vv => (await vv.evaluate('location.pathname')) === '/offline', 45_000)
r.check('server really down: saved address untouched', (await venuesState(v)).venues['test-site-1'].baseUrl.includes('.99:'))
r.check('server really down: offline screen', !!offlineShown)
r.check('server really down: offline screen', !!offlineShown, await v.evaluate('location.pathname + " | " + document.body.innerText.slice(0, 200)').catch(e => String(e)))
await v.evaluate("[...document.querySelectorAll('button')].find(e => e.textContent.includes('Αναζήτηση server')).click()")
const notFound = await waitFor(async () => (await v.evaluate('document.body.innerText')).includes('Ο server δεν βρέθηκε'), 60_000)
r.check('manual search ends with "not found" guidance', !!notFound)
@@ -252,7 +279,8 @@ server { listen 443 ssl; ssl_certificate /t/cert.pem; ssl_certificate_key /t/key
await sleep(1500)
v = await relaunch()
await waitFor(async () => (await v.evaluate('location.pathname')) === '/tables', 30_000)
r.check('TLS: /tables + live wss', (await connectivityColor(v)) === GREEN)
const t0 = Date.now(); const wssUp = await waitFor(async () => (await connectivityColor(v)) === GREEN, 20_000, 300)
r.check('TLS: /tables + live wss', !!wssUp, `after ${Date.now() - t0} ms: ` + `${await v.evaluate('location.pathname').catch(() => '?')} ${await connectivityColor(v).catch(() => '?')}`)
adb('logcat', '-c')
const impostor = await v.evaluate(`fetch('https://${H}:18444/api/system/identity').then(r => 'OK ' + r.status, () => 'FAILED')`)
const genuine = await v.evaluate(`fetch('https://${H}:18443/api/system/identity').then(r => 'OK ' + r.status, () => 'FAILED')`)
+1
View File
@@ -23,6 +23,7 @@ const suites = [
['license (cloud + site)', PYTHON, ['license_e2e.py'], E2E],
['browser', 'node', ['browser.mjs'], E2E],
['ui (@xenia/ui + @xenia/i18n)', 'node', ['ui.mjs'], E2E],
['waiter (sign-in, lock, approvals)', 'node', ['waiter.mjs'], E2E],
['manager (login, bootstrap, approvals)', 'node', ['manager.mjs'], E2E],
['terminal (pairing, sign-in, states)', 'node', ['terminal.mjs'], E2E],
['order app (cloud: takeaway + delivery + bookings)', 'node', ['order_app.mjs'], E2E],
+186
View File
@@ -0,0 +1,186 @@
// Waiter app suite (plan phase 4): sign-in v2 on the phone (4.2): each login mode, wrong PIN,
// one session per waiter, lock / unlock / idle sign-out, a manager's approval on the phone.
// Starts its own backend (:8061) and the venue-mode dev build (:5181), phone-sized Edge.
// node waiter.mjs
import path from 'node:path'
import { chromium } from 'playwright'
import { BROWSER_CHANNEL, OUT, reporter, sleep } from './lib/env.mjs'
import { login, startBackend, startViteNative } from './lib/proc.mjs'
const backend = await startBackend({ port: 8061, siteId: 'test-site-1', env: { LICENSE_MODE: 'off' } })
const vite = await startViteNative({ port: 5181, backendUrl: backend.url })
const APP = 'http://localhost:5181'
const TOKEN_KEY = 'xenia:dev:token'
const browser = await chromium.launch(BROWSER_CHANNEL ? { channel: BROWSER_CHANNEL } : {})
const r = reporter('waiter: sign-in v2, lock, approvals (4.2)')
const errors = []
let failures = 0
async function api(method, url, { token, body, raw = false } = {}) {
const res = await fetch(backend.url + url, {
method, headers: { 'content-type': 'application/json', ...(token ? { authorization: `Bearer ${token}` } : {}) },
body: body === undefined ? undefined : JSON.stringify(body),
})
if (raw) return res
const text = await res.text()
let data = null
try { data = JSON.parse(text) } catch { data = text }
if (!res.ok) throw new Error(`${method} ${url} → ${res.status} ${text.slice(0, 200)}`)
return data
}
const phone = () => browser.newContext({ viewport: { width: 393, height: 852 }, deviceScaleFactor: 2, isMobile: true, hasTouch: true })
async function open(ctx, url = `${APP}/login`) {
const page = await ctx.newPage()
page.on('pageerror', e => errors.push(e.message))
await page.goto(url)
return page
}
const shown = (page, testId, timeout = 10_000) => page.getByTestId(testId).first().waitFor({ timeout }).then(() => true).catch(() => false)
const gone = (page, testId, timeout = 10_000) => page.getByTestId(testId).first().waitFor({ state: 'detached', timeout }).then(() => true).catch(() => false)
async function pin(page, digits) {
for (const d of digits) await page.getByRole('button', { name: d, exact: true }).first().click()
}
const tokenOf = page => page.evaluate(k => localStorage.getItem(k), TOKEN_KEY)
const pathOf = page => page.evaluate(() => location.pathname)
const setting = (boss, key, value) => api('PUT', `/api/settings/${key}`, { token: boss, body: { value } })
try {
const boss = await login(backend.url)
await api('POST', '/api/business-day/open', { token: boss, body: {} }).catch(() => {})
const waiters = await api('GET', '/api/auth/waiters')
const maria = waiters.find(w => (w.full_name || '').includes('Κωνσταντίνου'))
// ── login-by-id is gone ────────────────────────────────────────────────────
const old = await api('POST', '/api/auth/login-by-id', { body: { waiter_id: maria?.id, pin: '3302' }, raw: true })
r.check('POST /api/auth/login-by-id is gone (404)', old.status === 404, String(old.status))
// ── PIN mode: pick your name, wrong PIN, right PIN ─────────────────────────
const ctxA = await phone()
const a = await open(ctxA)
r.check('PIN mode: the phone lists the waiters to pick from', await shown(a, 'waiter-card'))
await a.getByTestId('waiter-card').filter({ hasText: 'Κωνσταντίνου' }).click()
r.check('PIN mode: then the PIN pad', await shown(a, 'login-secret') && await a.getByTestId('login-secret').getAttribute('data-mode') === 'pin')
await a.evaluate(() => { window.__noReload = true })
await pin(a, '0000')
r.check('wrong PIN: a message, no reload, still on the PIN pad',
await shown(a, 'login-error', 5000) && await a.evaluate(() => window.__noReload === true) && await pathOf(a) === '/login',
await a.getByTestId('login-error').textContent().catch(() => ''))
await pin(a, '3302')
await a.waitForURL(u => u.pathname !== '/login', { timeout: 10_000 }).catch(() => {})
const tokenA = await tokenOf(a)
r.check('right PIN: signed in (a session token, off the login page)', !!tokenA && await pathOf(a) !== '/login', await pathOf(a))
const sessions = await api('GET', '/api/auth/sessions', { token: boss })
r.check('the session is a "waiter" session', sessions.some(s => s.username === 'demo_maria' && s.client === 'waiter'), JSON.stringify(sessions.map(s => [s.username, s.client])))
// start the shift on the phone (the gate after sign-in)
await a.getByRole('button', { name: /Έναρξη Βάρδιας/ }).click({ timeout: 10_000 }).catch(() => {})
await a.waitForURL(u => u.pathname.startsWith('/tables'), { timeout: 10_000 }).catch(() => {})
await sleep(1500)
// ── One session per waiter (refuse_new) ────────────────────────────────────
await setting(boss, 'auth.single_session_waiter', 'refuse_new')
const ctxB = await phone()
const b = await open(ctxB)
await b.getByTestId('waiter-card').filter({ hasText: 'Κωνσταντίνου' }).click({ timeout: 10_000 })
await pin(b, '3302')
r.check('second phone, same waiter (refuse_new): refused with a message, stays on sign-in',
await shown(b, 'login-error', 5000) && await pathOf(b) === '/login' && !(await tokenOf(b)),
await b.getByTestId('login-error').textContent().catch(() => ''))
// ── Lock from the menu, wrong PIN, right PIN (same session) ────────────────
await a.getByRole('button', { name: 'demo_maria' }).first().click({ timeout: 10_000 })
await a.getByTestId('menu-lock').click()
r.check('menu "Κλείδωμα" locks the phone', await shown(a, 'lock-screen', 5000))
await a.reload()
r.check('still locked after the app is reopened', await shown(a, 'lock-screen', 10_000))
await pin(a, '0000')
const lockErr = await a.getByTestId('unlock-error').textContent({ timeout: 5000 }).catch(() => '')
r.check('wrong PIN on the lock: tries left shown', /4/.test(lockErr), lockErr)
await a.screenshot({ path: path.join(OUT, 'waiter-lock.png') })
await pin(a, '3302')
r.check('right PIN unlocks: same session, same token', await gone(a, 'lock-screen', 5000) && await tokenOf(a) === tokenA)
// ── A manager's approval on the same phone (cancel without the key) ─────────
const tables = await api('GET', '/api/tables/', { token: boss })
const table = tables.find(t => !t.open_order_id && !t.current_order_id) || tables[0]
const order = await api('POST', '/api/orders/', { token: tokenA, body: { table_id: table.id } })
await a.evaluate(id => {
window.__res = window.__xeniaClient.delete(`/api/orders/${id}`)
.then(res => ({ ok: true, status: res.status }), e => ({ ok: false, code: e.xenia?.code }))
}, order.id)
const dialog = a.getByRole('dialog')
await dialog.waitFor({ timeout: 10_000 }).catch(() => {})
r.check('approval dialog opens on the phone for ordering.orders.cancel', await a.getByTestId('override-key').textContent().catch(() => '') === 'ordering.orders.cancel')
await a.screenshot({ path: path.join(OUT, 'waiter-approval.png') })
const inputs = dialog.locator('input')
await inputs.nth(0).fill('manager')
await inputs.nth(1).fill('1234')
await inputs.nth(1).press('Enter')
const result = await a.evaluate(() => window.__res)
r.check("the manager's PIN completes the cancel on the phone", result.ok === true, JSON.stringify(result))
// ── Signing out ends the session on the server: the second phone can sign in ─
await a.getByRole('button', { name: 'demo_maria' }).first().click({ timeout: 10_000 })
await a.getByRole('button', { name: /Αποσύνδεση/ }).last().click()
await a.waitForURL(u => u.pathname === '/login', { timeout: 10_000 }).catch(() => {})
await sleep(1000)
const after = await api('GET', '/api/auth/sessions', { token: boss })
r.check('sign-out ends the session on the server', !after.some(s => s.username === 'demo_maria' && s.client === 'waiter'))
await b.reload()
await b.getByTestId('waiter-card').filter({ hasText: 'Κωνσταντίνου' }).click({ timeout: 10_000 })
await pin(b, '3302')
await b.waitForURL(u => u.pathname !== '/login', { timeout: 10_000 }).catch(() => {})
r.check('…and then the second phone signs in', !!(await tokenOf(b)) && await pathOf(b) !== '/login', await pathOf(b))
// ── Auto-lock and idle sign-out follow the venue's settings ────────────────
await setting(boss, 'security.auto_lock', 'true')
await setting(boss, 'security.auto_lock_seconds', '3')
await setting(boss, 'security.auto_logout', 'true')
await setting(boss, 'security.auto_logout_seconds', '9')
await b.reload()
r.check('idle past auto_lock_seconds: the phone locks by itself', await shown(b, 'lock-screen', 10_000))
r.check('idle past auto_logout_seconds: signed out', await b.waitForURL(u => u.pathname === '/login', { timeout: 15_000 }).then(() => true).catch(() => false)
&& !(await tokenOf(b)))
await setting(boss, 'security.auto_lock', 'false')
await setting(boss, 'security.auto_logout', 'false')
await ctxA.close(); await ctxB.close()
// ── Username + password mode ───────────────────────────────────────────────
await setting(boss, 'auth.waiter_login_mode', 'password')
await setting(boss, 'auth.waiter_require_username', 'true')
const ctxC = await phone()
const c = await open(ctxC)
r.check('password mode with username: a username field and a password field',
await shown(c, 'login-username') && await shown(c, 'login-password') && await c.getByTestId('waiter-card').count() === 0)
await c.getByTestId('login-username').fill('manager')
await c.getByTestId('login-password').fill('wrong-one')
await c.getByTestId('login-submit').click()
r.check('wrong password: a message', await shown(c, 'login-error', 5000), await c.getByTestId('login-error').textContent().catch(() => ''))
await c.getByTestId('login-password').fill('password')
await c.getByTestId('login-submit').click()
await c.waitForURL(u => u.pathname !== '/login', { timeout: 10_000 }).catch(() => {})
r.check('right password: signed in', !!(await tokenOf(c)) && await pathOf(c) !== '/login', await pathOf(c))
await ctxC.close()
// ── Tap mode: phones say so instead of offering a sign-in ──────────────────
await setting(boss, 'auth.waiter_login_mode', 'tap')
await setting(boss, 'auth.waiter_require_username', 'false')
const ctxD = await phone()
const d = await open(ctxD)
r.check('tap mode: the phone explains that sign-in is on the paired screens', await shown(d, 'login-tap-only'))
await d.screenshot({ path: path.join(OUT, 'waiter-tap-only.png') })
await ctxD.close()
await setting(boss, 'auth.waiter_login_mode', 'pin')
r.check('no page errors', errors.length === 0, errors.join(' | '))
failures += r.done()
} catch (e) {
console.error(e)
failures += 1 + r.done()
} finally {
await browser.close()
vite.stop()
await backend.stop()
}
process.exit(failures ? 1 : 0)
+19 -4
View File
@@ -33,6 +33,7 @@ import InstallAppDialog from './components/InstallAppDialog'
import VenuesPage from './pages/VenuesPage'
import ServerRediscovery from './components/ServerRediscovery'
import BundleSync from './components/BundleSync'
import LockScreen, { IdleGuard } from './components/LockScreen'
import { deliveryMode, getActiveVenue } from './config/server'
// ─── Utility ─────────────────────────────────────────────────────────────────
@@ -275,19 +276,33 @@ function AppLayout() {
return <Outlet />
}
/** Signed-in screens with the idle guard and the lock screen over them (plan step 4.2): the
* lock covers everything, the shift gates included, and what was open stays underneath. */
function ProtectedLayout() {
const token = useAuthStore(s => s.token)
const locked = useAuthStore(s => s.locked)
return (
<>
{token && <IdleGuard />}
{token && locked && <LockScreen />}
<AppLayout />
</>
)
}
// ─── Global helpers ───────────────────────────────────────────────────────────
/** Who is signed in comes with the bootstrap (plan 4.1): online it's the server's answer;
* offline the bootstrap cached for this token keeps the waiter signed in (CS-3). A token the
* server no longer knows comes back with no user: sign out. */
function AuthRehydrator() {
const { token, user, login, logout } = useAuthStore()
const { token, user, restore, logout } = useAuthStore()
const access = useAccess()
useEffect(() => {
if (!token || user) return
if (access.user) login(access.user, token)
if (access.user) restore(access.user)
else if (!access.offline) logout()
}, [token, user, access.user, access.offline, login, logout])
}, [token, user, access.user, access.offline, restore, logout])
return null
}
@@ -461,7 +476,7 @@ function Routed() {
<Route path="/login" element={<LoginGuard><LoginPage /></LoginGuard>} />
<Route path="/offline" element={<OfflinePage />} />
<Route path="/venues" element={deliveryMode() === 'native' ? <VenuesPage /> : <Navigate to="/" replace />} />
<Route element={<AppLayout />}>
<Route element={<ProtectedLayout />}>
<Route index element={<Navigate to="/tables?tab=tables" replace />} />
<Route path="/tables" element={<TableListRoute />} />
<Route path="/tables/:tableId" element={<TableDetailPage />} />
+165
View File
@@ -0,0 +1,165 @@
// Lock and idle sign-out on the phone (plan step 4.2), following the venue's settings
// security.auto_lock(_seconds) and security.auto_logout(_seconds), as the manager does.
//
// Locked: the screen is covered and the same waiter unlocks with their own PIN (or password,
// when the venue signs waiters in with passwords): POST /api/auth/unlock with the session's
// own token, so the session (and its token) simply continues. Five wrong tries end the
// session on the server (auth.session_ended) and the phone goes back to sign-in.
// "Sign out" is always offered, so a different waiter can take the phone.
//
// The last touch is kept per venue, so a phone left closed past the limits is locked (or
// signed out) when it is opened again.
import { useEffect, useRef, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useAccess } from '@xenia/access'
import { isError } from '@xenia/api'
import PinPad from './PinPad'
import useAuthStore from '../store/authStore'
import client from '../api/client'
import { apiError } from '../api/errors'
import { getVenueSettings } from '../api/venueSettings'
import { storageKey } from '../config/server'
import { idleAction, idleLimits } from '../logic/idle'
const ACTIVITY_EVENTS = ['pointerdown', 'keydown', 'touchstart', 'scroll']
const SAVE_EVERY_MS = 5_000
const CHECK_EVERY_MS = 1_000
function lastActiveKey() { return storageKey('lastActive') }
/** Watches for inactivity while someone is signed in; renders nothing. */
export function IdleGuard() {
const navigate = useNavigate()
const lastRef = useRef(null)
const limitsRef = useRef({ lockMs: Infinity, logoutMs: Infinity })
useEffect(() => {
let alive = true
getVenueSettings().then(r => { if (alive) limitsRef.current = idleLimits(r.data) }).catch(() => {})
const refresh = setInterval(() => {
getVenueSettings().then(r => { if (alive) limitsRef.current = idleLimits(r.data) }).catch(() => {})
}, 60_000)
const saved = parseInt(localStorage.getItem(lastActiveKey()) || '', 10)
lastRef.current = Number.isFinite(saved) ? saved : Date.now()
let lastSaved = 0
function onActivity() {
const now = Date.now()
lastRef.current = now
if (now - lastSaved > SAVE_EVERY_MS) {
lastSaved = now
try { localStorage.setItem(lastActiveKey(), String(now)) } catch { /* storage full */ }
}
}
ACTIVITY_EVENTS.forEach(ev => window.addEventListener(ev, onActivity, { passive: true }))
const tick = setInterval(() => {
const { token, locked, lock, logout } = useAuthStore.getState()
if (!token) return
const action = idleAction(Date.now() - lastRef.current, limitsRef.current, locked)
if (action === 'logout') {
logout()
navigate('/login', { replace: true })
} else if (action === 'lock') {
lock()
}
}, CHECK_EVERY_MS)
return () => {
alive = false
clearInterval(refresh)
clearInterval(tick)
ACTIVITY_EVENTS.forEach(ev => window.removeEventListener(ev, onActivity))
}
}, [navigate])
return null
}
/** Mark the phone as just used (after unlocking), so the guard doesn't lock it again at once. */
function touchActivity() {
try { localStorage.setItem(lastActiveKey(), String(Date.now())) } catch { /* storage full */ }
window.dispatchEvent(new Event('keydown'))
}
export default function LockScreen() {
const { user, savedUsername, unlock, logout } = useAuthStore()
const { login: modes } = useAccess()
const usePassword = modes?.waiter_mode === 'password'
const navigate = useNavigate()
const [error, setError] = useState('')
const [busy, setBusy] = useState(false)
const [password, setPassword] = useState('')
const [attempt, setAttempt] = useState(0)
function signOut() {
logout()
navigate('/login', { replace: true })
}
async function tryUnlock(secret) {
setBusy(true)
setError('')
try {
const { data } = await client.post('/api/auth/unlock', secret,
{ xenia: { ignoreUnauthorized: true, noOverride: true } })
touchActivity()
unlock(data.user)
} catch (err) {
if (isError(err, 'auth.session_ended')) { signOut(); return }
setError(apiError(err, usePassword ? 'Λανθασμένος κωδικός' : 'Λανθασμένο PIN'))
setPassword('')
setAttempt(a => a + 1)
} finally {
setBusy(false)
}
}
return (
<div
data-testid="lock-screen"
style={{
position: 'fixed', inset: 0, zIndex: 9999,
background: 'var(--bg)', display: 'flex', alignItems: 'center', justifyContent: 'center',
padding: 16,
}}
>
<div className="login-box" style={{ textAlign: 'center' }}>
<div style={{ fontSize: 40 }}>🔒</div>
<p style={{ fontSize: 18, fontWeight: 700, color: 'var(--text)', margin: '6px 0 2px' }}>Κλειδωμένο</p>
<p style={{ fontSize: 14, color: 'var(--muted)', marginBottom: 12 }}>{user?.full_name || user?.username || savedUsername}</p>
{usePassword ? (
<form onSubmit={e => { e.preventDefault(); if (password) tryUnlock({ password }) }} style={{ display: 'grid', gap: 10 }}>
<input
type="password"
value={password}
onChange={e => setPassword(e.target.value)}
placeholder="Κωδικός"
autoComplete="current-password"
data-testid="unlock-password"
style={{
width: '100%', boxSizing: 'border-box', padding: '12px 14px', borderRadius: 10,
border: '1px solid var(--border)', background: 'var(--bg2)', color: 'var(--text)', fontSize: 16,
}}
/>
<button type="submit" className="btn btn--primary btn--lg" disabled={busy || !password}>Ξεκλείδωμα</button>
</form>
) : (
<PinPad key={attempt} onSubmit={pin => tryUnlock({ pin })} loading={busy} />
)}
{error && <p className="error-msg" data-testid="unlock-error">{error}</p>}
<button
onClick={signOut}
data-testid="lock-sign-out"
style={{ marginTop: 16, background: 'none', border: 'none', color: 'var(--muted)', fontSize: 13, cursor: 'pointer' }}
>
Αποσύνδεση (άλλος σερβιτόρος)
</button>
</div>
</div>
)
}
+7 -1
View File
@@ -26,7 +26,7 @@ export default function UserMenu() {
const [busy, setBusy] = useState(false)
const ref = useRef(null)
const navigate = useNavigate()
const { user, logout } = useAuthStore()
const { user, logout, lock } = useAuthStore()
const { dark, toggle } = useThemeStore()
const {
shift, selfEndAllowed,
@@ -187,6 +187,12 @@ export default function UserMenu() {
<div className="user-menu-divider" />
{/* ── Lock (plan step 4.2): the same waiter unlocks with their PIN ── */}
<button className="user-menu-item" data-testid="menu-lock" onClick={() => { setOpen(false); lock() }}>
<span className="user-menu-item__icon">🔒</span>
<span>Κλείδωμα</span>
</button>
<button className="user-menu-item user-menu-item--danger" onClick={handleLogout}>
<span className="user-menu-item__icon">⏏</span>
<span>Αποσύνδεση</span>
+22
View File
@@ -0,0 +1,22 @@
// What a phone does after a while without a touch (plan step 4.2). Pure: unit-tested
// (tests/idle.test.mjs). Settings (venue): security.auto_lock + security.auto_lock_seconds,
// security.auto_logout + security.auto_logout_seconds — the same ones the manager follows.
/** settings: the GET /api/settings/ map. → { lockMs, logoutMs } (Infinity = never). */
export function idleLimits(settings) {
const get = (k, d) => settings?.[k]?.value ?? d
const secs = (on, k, d) => {
if (get(on, 'false') !== 'true') return Infinity
const n = parseInt(get(k, d), 10)
return Number.isFinite(n) && n > 0 ? n * 1000 : Infinity
}
return { lockMs: secs('security.auto_lock', 'security.auto_lock_seconds', '300'),
logoutMs: secs('security.auto_logout', 'security.auto_logout_seconds', '1800') }
}
/** 'logout' | 'lock' | null for this much idle time. Signing out wins over locking. */
export function idleAction(idleMs, { lockMs, logoutMs }, locked) {
if (idleMs >= logoutMs) return 'logout'
if (!locked && idleMs >= lockMs) return 'lock'
return null
}
+133 -57
View File
@@ -1,5 +1,6 @@
import { useEffect, useState } from 'react'
import { useCallback, useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useAccess } from '@xenia/access'
import PinPad from '../components/PinPad'
import useAuthStore from '../store/authStore'
import client from '../api/client'
@@ -9,17 +10,20 @@ import { assetUrl, deliveryMode, getActiveVenue } from '../config/server'
// ─── Waiter card ──────────────────────────────────────────────────────────────
function WaiterCard({ waiter, onClick }) {
const initials = (waiter.full_name || waiter.nickname || '?')
function initialsOf(waiter) {
return (waiter.full_name || waiter.nickname || '?')
.split(' ')
.map(w => w[0])
.join('')
.slice(0, 2)
.toUpperCase()
}
function WaiterCard({ waiter, onClick }) {
return (
<button
onClick={onClick}
data-testid="waiter-card"
style={{
display: 'flex', alignItems: 'center', gap: 14,
padding: '14px 16px',
@@ -45,7 +49,7 @@ function WaiterCard({ waiter, onClick }) {
}}>
{waiter.avatar_url
? <img src={assetUrl(waiter.avatar_url)} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
: initials
: initialsOf(waiter)
}
</div>
@@ -75,19 +79,35 @@ function WaiterCard({ waiter, onClick }) {
}
// ─── Main page ────────────────────────────────────────────────────────────────
// Sign-in v2 (plan step 4.2). How waiters sign in is the venue's choice, read from the
// bootstrap (settings auth.waiter_login_mode and auth.waiter_require_username):
// pin pick your name (or type your username), then your PIN
// password pick your name (or type your username), then your password
// tap only on paired screens; a phone says so instead of offering a sign-in
// Sends POST /api/auth/login {client: "waiter", user_id | username, pin | password}. The
// server's refusals (wrong PIN, one session per waiter, no waiter app for this account…)
// are shown in the user's language.
export default function LoginPage() {
const { login } = useAuthStore()
const { login, savedUsername } = useAuthStore()
const { login: modes } = useAccess()
const mode = modes?.waiter_mode || 'pin'
const typeUsername = !!modes?.waiter_require_username
const navigate = useNavigate()
const [waiters, setWaiters] = useState([])
const [loadingWaiters, setLoadingWaiters] = useState(true)
const [loadingWaiters, setLoadingWaiters] = useState(!typeUsername && mode !== 'tap')
const [serverUnreachable, setServerUnreachable] = useState(false)
const [selectedWaiter, setSelectedWaiter] = useState(null)
const [username, setUsername] = useState(savedUsername || '')
const [password, setPassword] = useState('')
const [error, setError] = useState('')
const [loading, setLoading] = useState(false)
const [attempt, setAttempt] = useState(0) // remounts the PIN pad (clears the dots) after a miss
useEffect(() => {
const loadWaiters = useCallback(() => {
setLoadingWaiters(true)
setServerUnreachable(false)
client.get('/api/auth/waiters')
.then(r => { setWaiters(r.data); setServerUnreachable(false) })
.catch(err => {
@@ -98,25 +118,61 @@ export default function LoginPage() {
.finally(() => setLoadingWaiters(false))
}, [])
async function handlePin(pin) {
if (!selectedWaiter) return
useEffect(() => {
if (typeUsername || mode === 'tap') return
client.get('/api/auth/waiters')
.then(r => setWaiters(r.data))
.catch(err => { if (!err.response) setServerUnreachable(true) })
.finally(() => setLoadingWaiters(false))
}, [typeUsername, mode])
async function signIn(secret) {
const who = typeUsername ? { username: username.trim() } : { user_id: selectedWaiter?.id }
if (!who.username && who.user_id == null) return
setError('')
setLoading(true)
try {
// We send waiter id as identifier; backend matches by id+pin
const { data } = await client.post('/api/auth/login-by-id', { waiter_id: selectedWaiter.id, pin }, { xenia: { ignoreUnauthorized: true } })
const { data } = await client.post('/api/auth/login', { client: 'waiter', ...who, ...secret },
{ xenia: { ignoreUnauthorized: true, noOverride: true } })
login({ id: data.user.id, username: data.user.username, role: data.user.role }, data.access_token)
navigate('/tables', { replace: true })
} catch (err) {
setError(apiError(err, 'Λανθασμένο PIN'))
setError(apiError(err, mode === 'password' ? 'Λανθασμένος κωδικός' : 'Λανθασμένο PIN'))
setPassword('')
setAttempt(a => a + 1)
} finally {
setLoading(false)
}
}
// ── Waiter picker screen ───────────────────────────────────────────────────
const venueSwitch = deliveryMode() === 'native' && (
<button
onClick={() => navigate('/venues')}
style={{ marginTop: 10, background: 'none', border: 'none', color: 'var(--muted)', fontSize: 13, cursor: 'pointer' }}
>
🏪 {getActiveVenue()?.name} · <span style={{ color: 'var(--accent)' }}>Αλλαγή</span>
</button>
)
if (!selectedWaiter) {
// ── "Tap your name" is for paired screens only ─────────────────────────────
if (mode === 'tap') {
return (
<div className="page page--centered">
<div className="login-box" style={{ textAlign: 'center' }} data-testid="login-tap-only">
<h1 className="app-title">XeniaPOS</h1>
<p style={{ color: 'var(--text)', fontSize: 15, lineHeight: 1.5 }}>
Σε αυτό το κατάστημα οι σερβιτόροι συνδέονται πατώντας το όνομά τους στις συνδεδεμένες οθόνες.
Από κινητό δεν γίνεται σύνδεση με αυτόν τον τρόπο — ζητήστε από τον διαχειριστή να αλλάξει
τον τρόπο σύνδεσης σε PIN ή κωδικό.
</p>
{venueSwitch}
</div>
</div>
)
}
// ── Step 1: who are you (pick your name) ───────────────────────────────────
if (!typeUsername && !selectedWaiter) {
// Sort: on-shift first, then alphabetical
const sorted = [...waiters].sort((a, b) => {
if (a.on_shift !== b.on_shift) return a.on_shift ? -1 : 1
@@ -129,14 +185,7 @@ export default function LoginPage() {
<div style={{ flexShrink: 0, padding: '40px 16px 20px', textAlign: 'center' }}>
<h1 className="app-title" style={{ marginBottom: 10 }}>Xenia POS</h1>
<p className="app-subtitle">Ποιος είσαι;</p>
{deliveryMode() === 'native' && (
<button
onClick={() => navigate('/venues')}
style={{ marginTop: 10, background: 'none', border: 'none', color: 'var(--muted)', fontSize: 13, cursor: 'pointer' }}
>
🏪 {getActiveVenue()?.name} · <span style={{ color: 'var(--accent)' }}>Αλλαγή</span>
</button>
)}
{venueSwitch}
</div>
{/* Scrollable card list */}
@@ -154,19 +203,7 @@ export default function LoginPage() {
Δεν είναι δυνατή η σύνδεση με τον Manager.<br />
Δεν μπορεί να ξεκινήσει βάρδια χωρίς σύνδεση.
</p>
<button
className="btn btn--secondary"
onClick={() => {
setLoadingWaiters(true)
setServerUnreachable(false)
client.get('/api/auth/waiters')
.then(r => { setWaiters(r.data); setServerUnreachable(false) })
.catch(err => { if (!err.response) setServerUnreachable(true) })
.finally(() => setLoadingWaiters(false))
}}
>
⟳ Επανάληψη
</button>
<button className="btn btn--secondary" onClick={loadWaiters}>⟳ Επανάληψη</button>
</div>
) : waiters.length === 0 ? (
<p style={{ textAlign: 'center', color: 'var(--muted)', padding: 32 }}>Δεν βρέθηκαν σερβιτόροι</p>
@@ -183,17 +220,20 @@ export default function LoginPage() {
)
}
// ── PIN screen ─────────────────────────────────────────────────────────────
const initials = (selectedWaiter.full_name || selectedWaiter.nickname || '?')
.split(' ').map(w => w[0]).join('').slice(0, 2).toUpperCase()
// ── Step 2: PIN or password ────────────────────────────────────────────────
const inputStyle = {
width: '100%', boxSizing: 'border-box', padding: '12px 14px', borderRadius: 10,
border: '1px solid var(--border)', background: 'var(--bg2)', color: 'var(--text)', fontSize: 16,
}
const w = selectedWaiter
return (
<div className="page page--centered">
<div className="login-box">
<div className="login-box" data-testid="login-secret" data-mode={mode}>
<h1 className="app-title">XeniaPOS</h1>
{/* Selected waiter mini-card */}
{w ? (
/* Selected waiter mini-card */
<div style={{
display: 'flex', alignItems: 'center', gap: 12,
background: 'var(--bg2)', border: '1px solid var(--border)',
@@ -201,38 +241,74 @@ export default function LoginPage() {
}}>
<div style={{
width: 40, height: 40, borderRadius: '50%', flexShrink: 0,
background: selectedWaiter.avatar_url ? 'transparent' : 'var(--bg3)',
border: `2px solid ${selectedWaiter.on_shift ? '#22c55e' : 'var(--border)'}`,
background: w.avatar_url ? 'transparent' : 'var(--bg3)',
border: `2px solid ${w.on_shift ? '#22c55e' : 'var(--border)'}`,
overflow: 'hidden',
display: 'flex', alignItems: 'center', justifyContent: 'center',
fontSize: 15, fontWeight: 700, color: 'var(--text)',
}}>
{selectedWaiter.avatar_url
? <img src={assetUrl(selectedWaiter.avatar_url)} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
: initials
{w.avatar_url
? <img src={assetUrl(w.avatar_url)} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
: initialsOf(w)
}
</div>
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontSize: 14, fontWeight: 700, color: 'var(--text)' }}>
{selectedWaiter.full_name || selectedWaiter.nickname}
</div>
{selectedWaiter.nickname && selectedWaiter.full_name && (
<div style={{ fontSize: 12, color: 'var(--muted)' }}>{selectedWaiter.nickname}</div>
)}
<div style={{ fontSize: 14, fontWeight: 700, color: 'var(--text)' }}>{w.full_name || w.nickname}</div>
{w.nickname && w.full_name && <div style={{ fontSize: 12, color: 'var(--muted)' }}>{w.nickname}</div>}
</div>
<button
onClick={() => { setSelectedWaiter(null); setError('') }}
onClick={() => { setSelectedWaiter(null); setError(''); setPassword('') }}
style={{ background: 'none', border: 'none', color: 'var(--muted)', cursor: 'pointer', fontSize: 13, padding: '4px 8px' }}
>
Αλλαγή
</button>
</div>
) : (
<>
{venueSwitch && <div style={{ textAlign: 'center' }}>{venueSwitch}</div>}
<input
value={username}
onChange={e => setUsername(e.target.value)}
placeholder="Όνομα χρήστη"
autoComplete="username"
autoCapitalize="none"
style={{ ...inputStyle, marginTop: 8 }}
data-testid="login-username"
/>
</>
)}
<p style={{ textAlign: 'center', color: 'var(--muted)', fontSize: 13, marginBottom: 12 }}>Εισάγετε PIN</p>
{mode === 'password' ? (
<form
onSubmit={e => { e.preventDefault(); if (password) signIn({ password }) }}
style={{ display: 'grid', gap: 10, marginTop: 10 }}
>
<input
type="password"
value={password}
onChange={e => setPassword(e.target.value)}
placeholder="Κωδικός"
autoComplete="current-password"
style={inputStyle}
data-testid="login-password"
/>
<button
type="submit"
className="btn btn--primary btn--lg"
disabled={loading || !password || (!w && !username.trim())}
data-testid="login-submit"
>
{loading ? '…' : 'Σύνδεση'}
</button>
</form>
) : (
<>
<p style={{ textAlign: 'center', color: 'var(--muted)', fontSize: 13, margin: '10px 0 12px' }}>Εισάγετε PIN</p>
<PinPad key={attempt} onSubmit={pin => signIn({ pin })} loading={loading} />
</>
)}
<PinPad onSubmit={handlePin} loading={loading} />
{error && <p className="error-msg">{error}</p>}
{error && <p className="error-msg" data-testid="login-error">{error}</p>}
</div>
</div>
)
+34 -3
View File
@@ -1,26 +1,57 @@
import { create } from 'zustand'
import client from '../api/client'
import { storageKey } from '../config/server'
const TOKEN_KEY = storageKey('token')
const USERNAME_KEY = storageKey('savedUsername')
// Plan step 4.2: a locked phone stays locked when the app is closed and opened again
const LOCKED_KEY = storageKey('locked')
const savedUsername = localStorage.getItem(USERNAME_KEY)
const useAuthStore = create((set) => ({
const useAuthStore = create((set, get) => ({
user: null,
token: localStorage.getItem(TOKEN_KEY) || null,
savedUsername: savedUsername || null,
locked: !!localStorage.getItem(TOKEN_KEY) && localStorage.getItem(LOCKED_KEY) === 'true',
login(user, token) {
localStorage.setItem(TOKEN_KEY, token)
localStorage.setItem(USERNAME_KEY, user.username)
set({ user, token, savedUsername: user.username })
localStorage.removeItem(LOCKED_KEY)
set({ user, token, savedUsername: user.username, locked: false })
},
// Who is signed in, after the app is reopened (the bootstrap answers): the lock stays
restore(user) {
set({ user })
},
/** Signs out here and ends the session on the server too (plan step 4.2), so a venue with
* "one session per waiter" lets the same waiter sign in again straight away. Offline the
* session simply runs out on the server by itself. */
logout() {
const token = get().token
if (token) {
// the header is set here: the stored token is gone before the request goes out
client.post('/api/auth/logout', {}, { headers: { Authorization: `Bearer ${token}` },
xenia: { ignoreUnauthorized: true, noOverride: true } }).catch(() => {})
}
localStorage.removeItem(TOKEN_KEY)
localStorage.removeItem(USERNAME_KEY)
set({ user: null, token: null, savedUsername: null })
localStorage.removeItem(LOCKED_KEY)
set({ user: null, token: null, savedUsername: null, locked: false })
},
lock() {
localStorage.setItem(LOCKED_KEY, 'true')
set({ locked: true })
},
// The same session continues (POST /api/auth/unlock): no new token
unlock(user) {
localStorage.removeItem(LOCKED_KEY)
set(s => ({ user: user ?? s.user, locked: false }))
},
clearSavedUsername() {
+24
View File
@@ -0,0 +1,24 @@
// Locking and signing out an idle phone (plan step 4.2).
import assert from 'node:assert/strict'
import { test } from 'node:test'
import { idleAction, idleLimits } from '../src/logic/idle.js'
const on = (lock, logout) => ({
'security.auto_lock': { value: lock ? 'true' : 'false' }, 'security.auto_lock_seconds': { value: String(lock || 300) },
'security.auto_logout': { value: logout ? 'true' : 'false' }, 'security.auto_logout_seconds': { value: String(logout || 1800) },
})
test('limits from the venue settings (off = never)', () => {
assert.deepEqual(idleLimits(on(60, 600)), { lockMs: 60_000, logoutMs: 600_000 })
assert.deepEqual(idleLimits(on(0, 0)), { lockMs: Infinity, logoutMs: Infinity })
assert.deepEqual(idleLimits({}), { lockMs: Infinity, logoutMs: Infinity })
assert.equal(idleLimits({ ...on(60), 'security.auto_lock_seconds': { value: 'x' } }).lockMs, Infinity)
})
test('lock, then sign out; nothing twice', () => {
const l = idleLimits(on(60, 600))
assert.equal(idleAction(30_000, l, false), null)
assert.equal(idleAction(60_000, l, false), 'lock')
assert.equal(idleAction(90_000, l, true), null, 'already locked')
assert.equal(idleAction(600_000, l, true), 'logout')
})