From 7706bf24703a70139cf4195323ceec90f04be845 Mon Sep 17 00:00:00 2001 From: bonamin Date: Mon, 23 Nov 2026 12:51:37 +0200 Subject: [PATCH] feat(backend,waiter,terminal,manager): sign-in: ask before signing a waiter's other phone out, usernames on paired screens - auth.single_session_waiter gains 'ask', the new default (Alembic 0051 moves venues on 'off' to it): a second phone gets auth.session_elsewhere {device, since}; Continue retries with replace=true and the first phone is signed out at once (live session.ended, reason "replaced") and says why on its sign-in page. Only phones count (terminal sessions are their own client). refuse_new / end_old unchanged. - auth.session_ended now carries the reason; the waiter app keeps it until the next sign-in. - The waiter app sends queued offline ops on every (re)connection, so an order queued on a phone that was signed out by another goes out after the next sign-in there (e2e checked). - auth.terminal_require_username (venue) + Device.require_username (per device, wins): GET /api/devices/me/users lists nobody, the screen asks for a username then PIN/password, a picked user_id is refused (auth.username_required), "tap" falls back to PIN. - Manager: Sign-in settings (ask, the new switch), the device dialog's usernames choice. Plan platform-v2 6F.7. Co-Authored-By: Claude Opus 5.5 --- local_backend/core/errors.py | 1 + local_backend/core/sessions.py | 46 +++++++- .../migrations/versions/0051_sign_in.py | 30 ++++++ local_backend/models/device.py | 3 +- local_backend/modules/core/manifest.py | 3 +- local_backend/routers/auth.py | 10 +- local_backend/routers/devices.py | 14 ++- local_backend/routers/settings.py | 3 + local_backend/schemas/auth.py | 1 + local_backend/tests/test_override.py | 7 +- local_backend/tests/test_sessions.py | 1 + local_backend/tests/test_sign_in.py | 101 ++++++++++++++++++ .../Settings/sections/SignInSettings.jsx | 10 +- .../src/pages/platform/DevicesPage.jsx | 21 ++++ packages/i18n/locales/el/errors.json | 1 + packages/i18n/locales/el/manager.json | 15 ++- packages/i18n/locales/el/terminal.json | 5 +- packages/i18n/locales/el/waiter.json | 8 +- packages/i18n/locales/en/errors.json | 1 + packages/i18n/locales/en/manager.json | 15 ++- packages/i18n/locales/en/terminal.json | 5 +- packages/i18n/locales/en/waiter.json | 8 +- terminal/src/screens/SignInScreen.jsx | 34 +++++- tests/e2e/manager.mjs | 20 +++- tests/e2e/terminal.mjs | 24 +++++ tests/e2e/waiter.mjs | 47 ++++++++ waiter_pwa/src/api/client.js | 4 +- waiter_pwa/src/context/LiveContext.jsx | 20 +++- waiter_pwa/src/hooks/useWebSocket.js | 4 + waiter_pwa/src/logic/signedOut.js | 25 +++++ waiter_pwa/src/pages/LoginPage.jsx | 48 ++++++++- 31 files changed, 494 insertions(+), 41 deletions(-) create mode 100644 local_backend/migrations/versions/0051_sign_in.py create mode 100644 local_backend/tests/test_sign_in.py create mode 100644 waiter_pwa/src/logic/signedOut.js diff --git a/local_backend/core/errors.py b/local_backend/core/errors.py index 6860fed..c604a05 100644 --- a/local_backend/core/errors.py +++ b/local_backend/core/errors.py @@ -57,6 +57,7 @@ CODES: dict[str, tuple[int, str]] = { "auth.invalid_credentials": (401, "Wrong username or password."), "auth.session_ended": (401, "Your session has ended. Please log in again."), "auth.session_exists": (409, "You're already logged in on another {client}. Log out there first."), + "auth.session_elsewhere": (409, "You're signed in on another device ({device}, since {since}). Continue? It will be signed out."), "auth.login_mode_not_allowed": (403, "This way of logging in isn't enabled ({mode})."), "auth.mode_needs_device": (403, "Logging in by {mode} only works on a paired device."), "auth.username_required": (422, "Enter your username."), diff --git a/local_backend/core/sessions.py b/local_backend/core/sessions.py index 7c9beb2..0398047 100644 --- a/local_backend/core/sessions.py +++ b/local_backend/core/sessions.py @@ -2,7 +2,11 @@ Sessions - start(db, user, client, request) creates a row and applies the client's single-session - rule (setting auth.single_session_: off | refuse_new | end_old). + rule (setting auth.single_session_: off | refuse_new | end_old | ask). + `ask` (waiters, the default since 6F.7): a login while signed in elsewhere is refused with + auth.session_elsewhere (where, since when) until the app retries with replace=True; then + the old sessions end with reason "replaced" (their sockets get session.ended at once). + Only the waiter's phones count: a terminal session (the counter) is its own client. - validate(sid) is called on every authenticated request (routers.deps.decode_token). Results are cached for CACHE_TTL_S; end()/end_for_user() drop the cache entry at once, so an ended session is refused on its very next request. @@ -61,15 +65,32 @@ def _setting(db, key: str, default: str) -> str: def single_session_rule(db, client: str) -> str: - return _setting(db, f"auth.single_session_{client}", "off") if client in ("manager", "waiter") else "off" + if client == "waiter": + return _setting(db, "auth.single_session_waiter", "ask") # 6F.7: ask is the default + return _setting(db, "auth.single_session_manager", "off") if client == "manager" else "off" # ── lifecycle ──────────────────────────────────────────────────────────────── -def start(db, user, client: str, request=None, *, device=None, expires_at=None): +def device_label(user_agent: str | None) -> str: + """A short, language-neutral name for where a session runs ("Android · Chrome").""" + ua = user_agent or "" + system = next((name for key, name in (("iPhone", "iPhone"), ("iPad", "iPad"), ("Android", "Android"), + ("Windows", "Windows"), ("Macintosh", "Mac"), ("Linux", "Linux")) + if key in ua), "") + browser = next((name for key, name in (("EdgA", "Edge"), ("Edg/", "Edge"), ("Firefox", "Firefox"), ("FxiOS", "Firefox"), + ("CriOS", "Chrome"), ("Chrome", "Chrome"), ("Safari", "Safari")) + if key in ua), "") + if "; wv)" in ua: + browser = "app" + return " · ".join(x for x in (system, browser) if x) + + +def start(db, user, client: str, request=None, *, device=None, expires_at=None, replace: bool = False): """Create a session for user (None user_id for the support account). Commits. `device`: the paired device of a terminal login; its previous sessions are replaced - (a shared screen shows one user at a time).""" + (a shared screen shows one user at a time). `replace`: the person said yes to signing + out their other session (rule `ask`).""" from models.session import LoginSession if client not in CLIENTS: raise ValueError(f"unknown client {client!r}") @@ -80,6 +101,11 @@ def start(db, user, client: str, request=None, *, device=None, expires_at=None): LoginSession.ended_at.is_(None)).all() if active and rule == "refuse_new": raise XeniaError("auth.session_exists", client=client) + if active and rule == "ask" and not replace: + last = max(active, key=lambda s: s.created_at) + from core.timeutil import iso_z + raise XeniaError("auth.session_elsewhere", client=client, since=iso_z(last.created_at), + device=device_label(last.user_agent) or "?", ip=last.ip or "") for s in active: _end_row(s, "replaced") if device is not None: @@ -186,7 +212,8 @@ def validate(sid: str | None, db=None) -> Active: if row is None or row.ended_at is not None: with _lock: _cache.pop(sid, None) - raise XeniaError("auth.session_ended") + # why it ended (replaced, logout, idle...): the app can say "you signed in elsewhere" + raise XeniaError("auth.session_ended", reason=(row.end_reason if row is not None else None) or "unknown") info = Active(row.user_id, row.device_id, row.expires_at) stale = utcnow() - row.last_seen_at > timedelta(seconds=LAST_SEEN_EVERY_S) finally: @@ -233,3 +260,12 @@ def waiter_login_mode(db) -> str: def waiter_requires_username(db) -> bool: return _setting(db, "auth.waiter_require_username", "false") == "true" + + +def terminal_requires_username(db, device=None) -> bool: + """Paired screens (6F.7): type a username instead of picking a name. The device's own + choice (Device.require_username) wins over the venue's auth.terminal_require_username.""" + own = getattr(device, "require_username", None) + if own is not None: + return bool(own) + return _setting(db, "auth.terminal_require_username", "false") == "true" diff --git a/local_backend/migrations/versions/0051_sign_in.py b/local_backend/migrations/versions/0051_sign_in.py new file mode 100644 index 0000000..a77ee4a --- /dev/null +++ b/local_backend/migrations/versions/0051_sign_in.py @@ -0,0 +1,30 @@ +"""Sign-in (owner 2026-11-23, plan 6F.7). + +- devices.require_username: a paired screen's own choice (NULL = the venue's + auth.terminal_require_username). +- auth.single_session_waiter: 'ask' is the new default; a venue that has the row set to + 'off' gets 'ask' too (Q-9). A venue that chose refuse_new / end_old keeps its choice. + +Revision ID: 0051_sign_in +Revises: 0050_split_bills +Create Date: 2026-11-23 22:00:00 +""" +from alembic import op +import sqlalchemy as sa + +revision = '0051_sign_in' +down_revision = '0050_split_bills' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + with op.batch_alter_table('devices') as b: + b.add_column(sa.Column('require_username', sa.Boolean(), nullable=True)) + op.get_bind().execute(sa.text("update pos_settings set value = 'ask' " + "where key = 'auth.single_session_waiter' and value = 'off'")) + + +def downgrade() -> None: + with op.batch_alter_table('devices') as b: + b.drop_column('require_username') diff --git a/local_backend/models/device.py b/local_backend/models/device.py index cb0ad1a..88cb3e7 100644 --- a/local_backend/models/device.py +++ b/local_backend/models/device.py @@ -13,7 +13,7 @@ Devices are never deleted: revoked rows keep their token hash so the device is t `device.revoked` (not "unknown"), and old sessions/audit rows keep a valid device_id. Read and written through routers/devices.py and core/access/context.py. """ -from sqlalchemy import JSON, Column, ForeignKey, Integer, String +from sqlalchemy import JSON, Boolean, Column, ForeignKey, Integer, String from core.timeutil import UTCDateTime, utcnow from database import Base @@ -29,6 +29,7 @@ class Device(Base): app_key = Column(String, nullable=False, index=True) # a kind="app" module with device_app config = Column(JSON, nullable=True) # app-specific (e.g. KDS prep zone) login_mode = Column(String, nullable=True) # NULL = site default auth.default_login_mode + require_username = Column(Boolean, nullable=True) # NULL = site default auth.terminal_require_username (6F.7) token_hash = Column(String, nullable=True, unique=True) # sha256 hex; NULL until the device picks it up linked_device_id = Column(Integer, ForeignKey("devices.id", ondelete="SET NULL"), nullable=True) user_agent = Column(String, nullable=True) # from the pairing request diff --git a/local_backend/modules/core/manifest.py b/local_backend/modules/core/manifest.py index 06c80ea..26b1fe9 100644 --- a/local_backend/modules/core/manifest.py +++ b/local_backend/modules/core/manifest.py @@ -27,7 +27,8 @@ MODULE = Module( SettingDef('auth.default_login_mode', 'pin', "How staff log in on paired devices (KDS, counter POS) unless the device sets its own: 'pin' | 'password' | 'tap' | 'none'. Apps that can't use it fall back to their first mode.", type='enum', choices=('pin', 'password', 'tap', 'none')), SettingDef('auth.waiter_require_username', 'false', 'Waiters must type their username instead of picking their name', type='bool'), SettingDef('auth.single_session_manager', 'off', "One manager session per user: 'off' | 'refuse_new' | 'end_old'", type='enum', choices=('off', 'refuse_new', 'end_old')), - SettingDef('auth.single_session_waiter', 'off', "One waiter session per user (no double login): 'off' | 'refuse_new' | 'end_old'", type='enum', choices=('off', 'refuse_new', 'end_old')), + SettingDef('auth.single_session_waiter', 'ask', "One waiter session per user, phones only (no double login): 'off' | 'refuse_new' | 'end_old' | 'ask' (the default: the phone asks, yes signs the other one out)", type='enum', choices=('off', 'refuse_new', 'end_old', 'ask')), + SettingDef('auth.terminal_require_username', 'false', 'Paired screens (counter, KDS): type a username instead of picking a name; no names are listed, and "tap" is not used. A device can choose otherwise on the Devices page.', type='bool'), SettingDef('auth.idle_days', '14', 'Sign people out after this many days without using the app (manager, waiter, paired-device sessions; support has its own 4 h). 0 = never.', type='int'), SettingDef('system.log_retention_days', '30', 'Days of daily backend log files to keep in data/logs (default 30). Applied at backend start.', type='int'), SettingDef('venue.language', 'en', 'Default language (en | el) for staff without their own language, and for printed reports/receipts and tickets of zones without one.', type='str'), diff --git a/local_backend/routers/auth.py b/local_backend/routers/auth.py index 0e9e1e5..7526501 100644 --- a/local_backend/routers/auth.py +++ b/local_backend/routers/auth.py @@ -44,7 +44,7 @@ def _check_secret(user, pin, password, db) -> bool: def do_login(db: Session, request: Request, *, client: str, username: str | None, user_id: int | None, - pin: str | None, password: str | None) -> TokenResponse: + pin: str | None, password: str | None, replace: bool = False) -> TokenResponse: """The one login path. Applies the client's login mode, its access key and the single-session rule, then creates a session (core/sessions.py).""" if client not in ("manager", "waiter", "terminal"): @@ -81,7 +81,7 @@ def do_login(db: Session, request: Request, *, client: str, username: str | None if not holds(user, needed): raise XeniaError("auth.client_not_allowed", client=client) - row = sessions.start(db, user, client, request) + row = sessions.start(db, user, client, request, replace=replace) return TokenResponse(access_token=make_token(user, row.id), user=UserOut.model_validate(user)) @@ -104,6 +104,10 @@ def _terminal_login(db: Session, request: Request, *, username, user_id, pin, pa raise XeniaError("auth.login_mode_not_allowed", mode="password") if mode == "password" and not password: raise XeniaError("auth.login_mode_not_allowed", mode="pin") + if sessions.terminal_requires_username(db, device): + if not username: + raise XeniaError("auth.username_required") + user_id = None # usernames only: a picked id isn't enough (6F.7) q = db.query(User).filter(User.is_active == True) # noqa: E712 user = q.filter(User.username == username).first() if username else ( @@ -122,7 +126,7 @@ def login(body: LoginRequest, request: Request, db: Session = Depends(get_db)): """POST {client: "manager"|"waiter"|"terminal", username?, user_id?, pin?, password?}. "terminal" = a user on a paired device: send the X-Xenia-Device header.""" return do_login(db, request, client=body.client, username=body.username, - user_id=body.user_id, pin=body.pin, password=body.password) + user_id=body.user_id, pin=body.pin, password=body.password, replace=body.replace) @router.post("/refresh", response_model=TokenResponse) diff --git a/local_backend/routers/devices.py b/local_backend/routers/devices.py index 9199f37..2789f3a 100644 --- a/local_backend/routers/devices.py +++ b/local_backend/routers/devices.py @@ -151,6 +151,8 @@ def effective_login_mode(db, device) -> str: can't use that one, the app's first mode (signage etc.: 'none').""" modes = _app(device.app_key).device_app.login_modes mode = device.login_mode or sessions._setting(db, "auth.default_login_mode", "pin") + if mode == "tap" and sessions.terminal_requires_username(db, device): + mode = next((m for m in ("pin", "password") if m in modes), mode) # usernames: no name to tap (6F.7) return mode if mode in modes else modes[0] @@ -175,6 +177,8 @@ def _out(d: Device, db) -> dict: "id": d.id, "uuid": d.uuid, "name": d.name, "app_key": d.app_key, "config": _effective_config(d, db) if d.app_key in registry() else {}, "login_mode": d.login_mode, + "require_username": d.require_username, + "effective_require_username": sessions.terminal_requires_username(db, d), "effective_login_mode": effective_login_mode(db, d) if d.app_key in registry() else None, "linked_device_id": d.linked_device_id, "user_agent": d.user_agent, "paired_at": iso_z(d.paired_at), "paired_by": d.paired_by, @@ -191,6 +195,7 @@ def _self_out(d: Device, db) -> dict: return { "id": d.id, "uuid": d.uuid, "name": d.name, "app_key": d.app_key, "config": _effective_config(d, db), "login_mode": effective_login_mode(db, d), + "require_username": sessions.terminal_requires_username(db, d), "linked_device": ({"id": linked.id, "uuid": linked.uuid, "name": linked.name, "app_key": linked.app_key} if linked is not None and linked.revoked_at is None else None), "app_status": status, # "ok" | "module.disabled" | "module.not_licensed": show "app disabled" @@ -249,6 +254,7 @@ class PairApprove(BaseModel): name: str = Field(min_length=1, max_length=60) config: Optional[dict] = None login_mode: Optional[str] = None # None/"" = site default + require_username: Optional[bool] = None # None = site default (6F.7) linked_device_id: Optional[int] = None @@ -256,6 +262,7 @@ class DevicePatch(BaseModel): name: Optional[str] = Field(None, min_length=1, max_length=60) config: Optional[dict] = None login_mode: Optional[str] = None # "" or null = back to the site default + require_username: Optional[bool] = None # null = back to the site default (6F.7) linked_device_id: Optional[int] = None # null/0 = unlink @@ -285,6 +292,7 @@ def approve_device(body: PairApprove, db: Session = Depends(get_db), user=Depend d = Device(uuid=uuidlib.uuid4().hex, name=body.name.strip(), app_key=body.app_key, config=_config(body.app_key, body.config, db), login_mode=_check_mode(body.app_key, body.login_mode), + require_username=body.require_username, linked_device_id=_check_link(db, None, body.linked_device_id), user_agent=row.user_agent, paired_at=now, paired_by=getattr(user, "id", None) or None) db.add(d) @@ -307,8 +315,8 @@ def device_users(db: Session = Depends(get_db), device=Depends(require_device()) """Who can log in on this device (holders of '.access'), for the name picker.""" from core.access.queries import users_with_key from models.user import User - if effective_login_mode(db, device) == "none": - return [] + if effective_login_mode(db, device) == "none" or sessions.terminal_requires_username(db, device): + return [] # usernames on (6F.7): nobody is listed, the screen asks for a username users = users_with_key(db, f"{device.app_key}.access").order_by(User.full_name).all() return [{"id": u.id, "full_name": u.full_name, "nickname": u.nickname, "avatar_url": u.avatar_url} for u in users if u.role != "superadmin"] @@ -357,6 +365,8 @@ def update_device(device_id: int, body: DevicePatch, db: Session = Depends(get_d d.config = _config(d.app_key, body.config, db) if "login_mode" in sent: d.login_mode = _check_mode(d.app_key, body.login_mode) + if "require_username" in sent: + d.require_username = body.require_username if "linked_device_id" in sent: d.linked_device_id = _check_link(db, d.id, body.linked_device_id) db.commit() diff --git a/local_backend/routers/settings.py b/local_backend/routers/settings.py index 408997c..0efc228 100644 --- a/local_backend/routers/settings.py +++ b/local_backend/routers/settings.py @@ -89,4 +89,7 @@ def update_setting( timeutil.invalidate() # live: next call re-reads the setting if key == "venue.language": i18n.invalidate() + if key in ("auth.default_login_mode", "auth.terminal_require_username"): + from services import ws_bus + ws_bus.notify_device(every_device=True) # paired screens re-read how people sign in (6F.7) return {"key": setting.key, "value": setting.value} diff --git a/local_backend/schemas/auth.py b/local_backend/schemas/auth.py index e057c43..eaea5c6 100644 --- a/local_backend/schemas/auth.py +++ b/local_backend/schemas/auth.py @@ -8,6 +8,7 @@ class LoginRequest(BaseModel): user_id: int | None = None # waiter picks their name (when the username isn't required) pin: str | None = None password: str | None = None + replace: bool = False # rule "ask": yes, sign my other phone out (6F.7) class TokenResponse(BaseModel): diff --git a/local_backend/tests/test_override.py b/local_backend/tests/test_override.py index 1803a1f..31abed4 100644 --- a/local_backend/tests/test_override.py +++ b/local_backend/tests/test_override.py @@ -104,7 +104,10 @@ def test_token_is_bound_to_its_key(client, db, venue, make_user, login): assert r.status_code == 200, r.text -def test_token_is_bound_to_its_session(client, venue, login): +def test_token_is_bound_to_its_session(client, db, venue, login): + from models.settings import PosSettings + db.add(PosSettings(key="auth.single_session_waiter", value="off")) # two phones of one waiter + db.commit() v = venue token = approve(client, v["waiter_h"], "ordering.orders.cancel", v["manager"].username).json()["override_token"] other_phone = login(v["waiter"], client="waiter") @@ -192,7 +195,7 @@ def test_check_consumes_a_valid_token(db, venue): from core.access import override from core.access.check import AccessContext, check v = venue - row = sessions.start(db, v["waiter"], "waiter") + row = sessions.start(db, v["waiter"], "waiter", replace=True) token, _ = override.grant(db, key="ordering.orders.cancel", username=v["manager"].username, pin=TEST_PIN, requester=v["waiter"], sid=row.id) ctx = AccessContext(user=v["waiter"], session=row.id, override_token=token, target="unit") diff --git a/local_backend/tests/test_sessions.py b/local_backend/tests/test_sessions.py index 1442c02..e8ca4ff 100644 --- a/local_backend/tests/test_sessions.py +++ b/local_backend/tests/test_sessions.py @@ -68,6 +68,7 @@ def test_waiter_pin_by_id(client, make_user): def test_waiter_modes(client, make_user, admin_h): w = make_user(role="waiter") + _set(client, admin_h, "auth.single_session_waiter", "off") # several logins of one waiter here _set(client, admin_h, "auth.waiter_login_mode", "password") r = client.post("/api/auth/login", json={"client": "waiter", "user_id": w.id, "pin": TEST_PIN}) assert r.json()["error"]["code"] == "auth.login_mode_not_allowed" diff --git a/local_backend/tests/test_sign_in.py b/local_backend/tests/test_sign_in.py new file mode 100644 index 0000000..50b1a6e --- /dev/null +++ b/local_backend/tests/test_sign_in.py @@ -0,0 +1,101 @@ +"""Sign-in (plan 6F.7): one session per waiter asks before signing the other phone out (the +default), only phones count; usernames on paired screens (venue setting + the device's own).""" +import pytest + +from conftest import TEST_PIN +from tests.test_live import err, owner_h, pair # noqa: F401 (fixtures) + +ANDROID = "Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0 Mobile Safari/537.36" + + +def _phone(client, user, **extra): + return client.post("/api/auth/login", headers={"user-agent": ANDROID}, + json={"client": "waiter", "user_id": user.id, "pin": TEST_PIN, **extra}) + + +def _h(r): + assert r.status_code == 200, r.text + return {"Authorization": f"Bearer {r.json()['access_token']}"} + + +@pytest.fixture +def ended(monkeypatch): + from services import ws_bus + got = [] + real = ws_bus.end_session + monkeypatch.setattr(ws_bus, "end_session", lambda sid, reason: (got.append(reason), real(sid, reason))[1]) + return got + + +def test_ask_is_the_default_and_says_where(client, make_user, ended): + w = make_user(role="waiter") + first = _h(_phone(client, w)) + r = _phone(client, w) + assert r.status_code == 409 and err(r) == "auth.session_elsewhere" + params = r.json()["error"]["params"] + assert params["device"] == "Android · Chrome" and params["since"].endswith("Z") + assert client.get("/api/auth/me", headers=first).status_code == 200 # asking ends nothing + second = _h(_phone(client, w, replace=True)) + gone = client.get("/api/auth/me", headers=first) + assert gone.status_code == 401 and err(gone) == "auth.session_ended" + assert gone.json()["error"]["params"]["reason"] == "replaced" # the old phone can say why + assert ended == ["replaced"] # its socket was told at once + assert client.get("/api/auth/me", headers=second).status_code == 200 + + +def test_replace_does_not_bypass_refuse_new(client, make_user, owner_h): + assert client.put("/api/settings/auth.single_session_waiter", headers=owner_h, json={"value": "refuse_new"}).status_code == 200 + w = make_user(role="waiter") + _h(_phone(client, w)) + r = _phone(client, w, replace=True) + assert r.status_code == 409 and err(r) == "auth.session_exists" + + +def test_only_phones_count(client, make_user, pair): + owner = make_user(role="owner") + token, dev = pair("pos_counter", "Till") + till = client.post("/api/auth/login", headers={"X-Xenia-Device": token}, + json={"client": "terminal", "user_id": owner.id, "pin": TEST_PIN}) + assert till.status_code == 200, till.text + _h(_phone(client, owner)) # the counter's session isn't a phone: no question + till_h = {"Authorization": f"Bearer {till.json()['access_token']}", "X-Xenia-Device": token} + assert client.get("/api/auth/me", headers=till_h).status_code == 200 + + +def test_usernames_on_terminals(client, make_user, owner_h, pair): + cashier = make_user(role="owner") + token, dev = pair("pos_counter", "Till") + dh = {"X-Xenia-Device": token} + assert len(client.get("/api/devices/me/users", headers=dh).json()) > 0 + assert client.put("/api/settings/auth.terminal_require_username", headers=owner_h, json={"value": "true"}).status_code == 200 + assert client.get("/api/devices/me/users", headers=dh).json() == [] + assert client.get("/api/devices/me", headers=dh).json()["require_username"] is True + by_id = client.post("/api/auth/login", headers=dh, json={"client": "terminal", "user_id": cashier.id, "pin": TEST_PIN}) + assert by_id.status_code == 422 and err(by_id) == "auth.username_required" + wrong = client.post("/api/auth/login", headers=dh, json={"client": "terminal", "username": "nobody_here", "pin": TEST_PIN}) + assert wrong.status_code == 401 and err(wrong) == "auth.invalid_credentials" + ok = client.post("/api/auth/login", headers=dh, json={"client": "terminal", "username": cashier.username, "pin": TEST_PIN}) + assert ok.status_code == 200, ok.text + + # "tap" can't go with usernames: the screen asks for the PIN instead + dev_id = dev.json()["id"] + assert client.patch(f"/api/devices/{dev_id}", headers=owner_h, json={"login_mode": "tap"}).status_code == 200 + assert client.get("/api/devices/me", headers=dh).json()["login_mode"] == "pin" + tap = client.post("/api/auth/login", headers=dh, json={"client": "terminal", "username": cashier.username}) + assert tap.status_code == 403 and err(tap) == "auth.login_mode_not_allowed" + + # the device's own choice wins over the venue's + out = client.patch(f"/api/devices/{dev_id}", headers=owner_h, json={"require_username": False}).json() + assert out["require_username"] is False and out["effective_require_username"] is False + assert client.get("/api/devices/me", headers=dh).json()["login_mode"] == "tap" + assert len(client.get("/api/devices/me/users", headers=dh).json()) > 0 + out = client.patch(f"/api/devices/{dev_id}", headers=owner_h, json={"require_username": None}).json() + assert out["require_username"] is None and out["effective_require_username"] is True + + +def test_device_label(): + from core.sessions import device_label + assert device_label(ANDROID) == "Android · Chrome" + assert device_label("Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 Version/17.0 Mobile/15E148 Safari/604.1") == "iPhone · Safari" + assert device_label("Mozilla/5.0 (Linux; Android 14; wv) AppleWebKit/537.36 Chrome/130.0 Mobile Safari/537.36".replace("wv)", "Pixel; wv)")) == "Android · app" + assert device_label(None) == "" diff --git a/manager_dashboard/src/pages/Settings/sections/SignInSettings.jsx b/manager_dashboard/src/pages/Settings/sections/SignInSettings.jsx index c1ac089..878d284 100644 --- a/manager_dashboard/src/pages/Settings/sections/SignInSettings.jsx +++ b/manager_dashboard/src/pages/Settings/sections/SignInSettings.jsx @@ -3,6 +3,8 @@ // auth.default_login_mode (paired devices; a device can choose its own on the Devices page), // auth.single_session_manager / _waiter, security.autofill_username (the sign-in page) and // auth.idle_days (sign out after N days without use, 0 = never; owner decision 2026-11-14, 2.99d). +// 6F.7: waiters get 'ask' (the default: the phone asks before signing the other one out; only +// phones count), and auth.terminal_require_username (paired screens list nobody). // Replaces the v1 "login method" card, whose setting (security.login_method) no longer exists. import { useId } from 'react' import { useTranslation } from '@xenia/i18n' @@ -11,6 +13,7 @@ import { SettingRow, SettingsCard } from './SettingsCard' import { useSettings } from './useSettings' const SESSION_RULES = ['off', 'refuse_new', 'end_old'] +const WAITER_SESSION_RULES = ['ask', 'off', 'refuse_new', 'end_old'] const IDLE_DAYS = ['7', '14', '30', '60', '90', '0'] export default function SignInSettings() { @@ -56,11 +59,14 @@ export default function SignInSettings() { {select('auth.default_login_mode', 'pin', opts(['pin', 'password', 'tap', 'none'], 'settings.mode'), idDevice)} + + {toggle('auth.terminal_require_username', 'false', t('settings.signIn.terminalUsername'))} + {select('auth.single_session_manager', 'off', opts(SESSION_RULES, 'settings.session'), idSingleManager)} - - {select('auth.single_session_waiter', 'off', opts(SESSION_RULES, 'settings.session'), idSingleWaiter)} + + {select('auth.single_session_waiter', 'ask', opts(WAITER_SESSION_RULES, 'settings.session'), idSingleWaiter)} {select('auth.idle_days', '14', idleOptions, idIdle)} diff --git a/manager_dashboard/src/pages/platform/DevicesPage.jsx b/manager_dashboard/src/pages/platform/DevicesPage.jsx index 0fd6d67..134ad5f 100644 --- a/manager_dashboard/src/pages/platform/DevicesPage.jsx +++ b/manager_dashboard/src/pages/platform/DevicesPage.jsx @@ -277,10 +277,24 @@ function PairDialog({ apps, usage, devices, appName, limitLabel, initialApp, onC ) } +/** Usernames on this screen (6F.7): the venue's choice, or its own yes / no. */ +function usernameOptions(device, t) { + // the venue's value = what applies when the device has no choice of its own + const venue = device.require_username == null ? device.effective_require_username : null + const yes = t('devices.form.usernamesYes') + const no = t('devices.form.usernamesNo') + return [ + { value: '', label: venue == null ? t('devices.signIn.defaultPlain') : t('devices.form.usernamesDefault', { value: venue ? yes : no }) }, + { value: 'true', label: yes }, + { value: 'false', label: no }, + ] +} + function EditDialog({ device, apps, devices, onClose, onSave }) { const { t } = useTranslation('manager') const [name, setName] = useState(device.name) const [mode, setMode] = useState(device.login_mode || '') + const [usernames, setUsernames] = useState(device.require_username == null ? '' : String(device.require_username)) const [link, setLink] = useState(device.linked_device_id ? String(device.linked_device_id) : '') const app = apps.find(a => a.key === device.app_key) const fields = app?.device_app?.config || [] @@ -293,6 +307,7 @@ function EditDialog({ device, apps, devices, onClose, onSave }) { e.preventDefault() if (!name.trim() || busy) return run({ name: name.trim(), login_mode: mode || null, linked_device_id: link ? Number(link) : null, + ...(modes ? { require_username: usernames === '' ? null : usernames === 'true' } : {}), ...(fields.length ? { config } : {}) }) } @@ -308,6 +323,12 @@ function EditDialog({ device, apps, devices, onClose, onSave }) { setUsernames(e.target.value)} data-testid="device-usernames" + options={usernameOptions(device, t)} /> + + )} {targets.length > 0 && ( setUsername(e.target.value)} autoFocus autoComplete="off" + autoCapitalize="none" spellCheck={false} data-testid="username-input" /> + + + + ) +} + function PasswordForm({ onSubmit, error }) { const { t } = useTranslation('terminal') const [password, setPassword] = useState('') diff --git a/tests/e2e/manager.mjs b/tests/e2e/manager.mjs index 63a9b83..b1224c1 100644 --- a/tests/e2e/manager.mjs +++ b/tests/e2e/manager.mjs @@ -189,7 +189,7 @@ try { await page.getByRole('button', { name: 'Pair a device' }).first().click() await dlg.getByLabel('Code shown on the device').fill('zz-zz-zz') await dlg.getByLabel('App to run').selectOption('kds') - await dlg.getByLabel('Name').fill('Kitchen') + await dlg.getByLabel('Name', { exact: true }).fill('Kitchen') await dlg.getByRole('button', { name: 'Pair a device' }).click() await page.getByTestId('pair-error').waitFor({ timeout: 5000 }).catch(() => {}) r.check('devices: a wrong code is refused with a message', (await page.getByTestId('pair-error').textContent().catch(() => '')).includes('pairing code is wrong')) @@ -221,12 +221,15 @@ try { r.check('devices: the screen opens a live connection with its device token alone (3.1a)', await sock.ready) await row.getByRole('button', { name: 'Edit' }).click() r.check('devices: the edit dialog shows the device setting', await dlg.getByLabel('Sign out after').inputValue() === '10') - await dlg.getByLabel('Name').fill('Kitchen 1') + await dlg.getByLabel('Name', { exact: true }).fill('Kitchen 1') await dlg.getByLabel('Sign out after').selectOption('5') + await dlg.getByTestId('device-usernames').selectOption('true') // 6F.7: this screen asks for usernames await dlg.getByRole('button', { name: 'Save' }).click() await page.waitForFunction(() => document.querySelector('[data-testid^="device-"][data-status]')?.textContent.includes('Kitchen 1'), null, { timeout: 8000 }).catch(() => {}) const me2 = await asDevice(deviceToken, '/api/devices/me').then(x => x.json()) r.check('devices: renamed, setting changed', (await row.textContent()).includes('Kitchen 1') && me2.name === 'Kitchen 1' && me2.config?.auto_sign_out_minutes === 5, JSON.stringify(me2)) + r.check('6F.7: a device set to "staff type their username" lists nobody', me2.require_username === true + && (await asDevice(deviceToken, '/api/devices/me/users').then(x => x.json())).length === 0) await sleep(300) r.check('devices: the screen is told at once (device.updated)', sock.messages.some(m => m.type === 'device.updated'), JSON.stringify(sock.messages)) @@ -667,11 +670,18 @@ try { (await api('GET', '/api/platform/bootstrap')).login.manager_mode === 'pin') await page.screenshot({ path: path.join(OUT, 'manager-settings-sign-in.png'), fullPage: true }) await page.getByTestId('setting-auth.manager_login_mode').selectOption('password') + const sessionDefault = await page.getByTestId('setting-auth.single_session_waiter').inputValue() + r.check('6F.7: one session per waiter is "ask" by default', sessionDefault === 'ask', sessionDefault) + await page.getByTestId('setting-auth.terminal_require_username').click() + await sleep(800) + r.check('6F.7: "staff type their username" on paired devices is saved', await settingValue('auth.terminal_require_username') === 'true') + await page.getByTestId('setting-auth.terminal_require_username').click() + await sleep(800) await page.getByTestId('setting-auth.single_session_waiter').selectOption('end_old') await sleep(800) r.check('settings: one session per waiter → "sign out the older one"', await settingValue('auth.single_session_waiter') === 'end_old' && await settingValue('auth.manager_login_mode') === 'password' && await settingValue('auth.waiter_login_mode') === 'pin') - await page.getByTestId('setting-auth.single_session_waiter').selectOption('off') + await page.getByTestId('setting-auth.single_session_waiter').selectOption('ask') const idleSel = page.getByTestId('setting-auth.idle_days') const idleDefault = await idleSel.inputValue() await idleSel.selectOption('30') @@ -912,7 +922,7 @@ try { const odlg = o.getByRole('dialog') await odlg.getByLabel('Code shown on the device').fill(kitchenCode) await odlg.getByLabel('App to run').selectOption('kds') - await odlg.getByLabel('Name').fill('Kitchen pass') + await odlg.getByLabel('Name', { exact: true }).fill('Kitchen pass') await odlg.getByLabel('How staff sign in').selectOption('pin') await odlg.getByRole('button', { name: 'Pair a device' }).click() await odlg.waitFor({ state: 'detached', timeout: 8000 }).catch(() => {}) @@ -971,7 +981,7 @@ try { r.check(`${ov} a shift started for a waiter with €20.50 (typed with a comma)`, await ovRow.waitFor({ timeout: 8000 }).then(() => true).catch(() => false) && (await api('GET', '/api/shifts/?active_only=true', { token: boss })).shifts.some(s => s.waiter_id === ovWaiter.id && s.starting_cash === 20.5)) const freeTable = (await api('GET', '/api/tables/', { token: boss })).find(t => !t.open_order_id && !t.current_order_id) - const ovOrder = await api('POST', '/api/orders/', { token: await loginApi('demo_maria', { pin: '3302', client: 'waiter' }), body: { table_id: freeTable.id } }) + const ovOrder = await api('POST', '/api/orders/', { token: await loginApi('demo_maria', { pin: '3302', client: 'waiter', replace: true }), body: { table_id: freeTable.id } }) const chip = page.locator(`[data-testid="table-chip"][data-state="open"]`).filter({ hasText: freeTable.label || `T${freeTable.number}` }).first() r.check(`${ov} a table a waiter opens turns "open" by itself (live)`, await chip.waitFor({ timeout: 8000 }).then(() => true).catch(() => false)) await chip.click() diff --git a/tests/e2e/terminal.mjs b/tests/e2e/terminal.mjs index 37f5c74..2a904f4 100644 --- a/tests/e2e/terminal.mjs +++ b/tests/e2e/terminal.mjs @@ -308,6 +308,30 @@ try { await api('POST', `/api/auth/sessions/${sid}/end`, { token: boss }) r.check('session ended by a manager → the screen is back at sign-in at once', await shown(page, 'sign-in-screen', 8000)) + // ── 6F.7: usernames on paired screens (venue setting, the device's own choice wins) ── + await api('PUT', '/api/settings/auth.terminal_require_username', { token: boss, body: { value: 'true' } }) + r.check('6F.7: usernames on → the screen lists nobody and asks for a username (live)', + await shown(page, 'username-form', 8000) && await page.getByTestId('user-grid').count() === 0) + await page.screenshot({ path: path.join(OUT, 'terminal-username.png') }) + const byName = async name => { + await page.getByTestId('username-input').fill(name) + await page.getByRole('button', { name: 'Next' }).click() + await page.getByLabel('Password').fill('password') + await page.getByRole('button', { name: 'Sign in' }).click() + } + await byName('nobody_here') + await sleep(1200) + r.check('6F.7: a wrong username is refused', await page.getByTestId('app-kds').count() === 0 && await page.getByTestId('sign-in-screen').count() === 1) + await page.getByRole('button', { name: 'Back' }).click() + await byName('manager') + r.check('6F.7: username + password signs in', await shown(page, 'app-kds')) + await page.getByRole('button', { name: 'Sign out' }).click() + await api('PATCH', `/api/devices/${kitchen.id}`, { token: boss, body: { require_username: false } }) + r.check('6F.7: the device\'s own "no" wins: the names are back', await shown(page, 'user-grid', 8000)) + await api('PATCH', `/api/devices/${kitchen.id}`, { token: boss, body: { require_username: null } }) + await api('PUT', '/api/settings/auth.terminal_require_username', { token: boss, body: { value: 'false' } }) + await shown(page, 'user-grid', 8000) + // ── app off / on ────────────────────────────────────────────────────────── await api('PUT', '/api/platform/modules/kds', { token: boss, body: { enabled: false } }) r.check('KDS turned off → "turned off" screen, live', await shown(page, 'blocked-screen', 8000) diff --git a/tests/e2e/waiter.mjs b/tests/e2e/waiter.mjs index b2bf74e..90dec81 100644 --- a/tests/e2e/waiter.mjs +++ b/tests/e2e/waiter.mjs @@ -596,6 +596,53 @@ try { await a.getByRole('button', { name: /Dark theme/ }).click() await a.reload() + // ── 6F.7: "ask" (the default): the second phone asks; Continue signs the first one out and it + // says why; an order queued offline on the first phone goes out after it signs in again ── + { + await setting(boss, 'auth.single_session_waiter', 'ask') + const busy7 = new Set((await api('GET', '/api/orders/', { token: boss })).map(o => o.table_id)) + const tq = (await api('GET', '/api/tables/', { token: boss })).find(x => x.is_active !== false && !busy7.has(x.id)) + const status7 = async () => (await api('GET', `/api/tables/${tq.id}/status`, { token: boss })).active_order_id + await a.goto(`${APP}/tables/${tq.id}/add?new=1`) + await addOn(tq.id, plain) + await ctxA.setOffline(true) + await a.getByTestId('cart-open').click() + await waitFor(async () => (await total().innerText().catch(() => '')).includes('offline'), 30_000, 1000) + await a.getByRole('button', { name: /^(SEND|SUMMARY)/ }).last().click() + if (await shown(a, 'summary-total', 3000)) await a.getByRole('button', { name: /SEND/ }).last().click() + await sleep(1500) + // the second phone + await b.reload() + await b.getByTestId('waiter-card').filter({ hasText: 'Κωνσταντίνου' }).click({ timeout: 10_000 }) + await pin(b, '3302') + const asked = await shown(b, 'login-elsewhere', 5000) + const askText = await b.getByTestId('login-elsewhere').innerText().catch(() => '') + r.check('6F.7: a second phone asks (where, since when) instead of refusing', asked && /\d\d:\d\d/.test(askText) && !(await tokenOf(b)), askText.replace(/\s+/g, ' ')) + await b.screenshot({ path: path.join(OUT, 'waiter-signed-in-elsewhere.png') }) + await b.getByTestId('login-elsewhere-continue').click() + await b.waitForURL(u => u.pathname !== '/login', { timeout: 10_000 }).catch(() => {}) + r.check('6F.7: Continue signs this phone in', !!(await tokenOf(b)) && await pathOf(b) !== '/login', await pathOf(b)) + // the first phone comes back: signed out, says why, the order still queued + await ctxA.setOffline(false) + const outA = await a.waitForURL(u => u.pathname === '/login', { timeout: 45_000 }).then(() => true).catch(() => false) + const noteA = await a.getByTestId('signed-out-note').innerText({ timeout: 10_000 }).catch(() => '') + r.check('6F.7: the first phone, back online, is signed out and says why', outA && /another device|άλλη συσκευή/.test(noteA), noteA) + await a.screenshot({ path: path.join(OUT, 'waiter-signed-out-replaced.png') }) + r.check('6F.7: its order queued offline was not sent with the ended session', !(await status7())) + // it signs in again (asks: the second phone now); the second phone leaves at once (live) + await a.getByTestId('waiter-card').filter({ hasText: 'Κωνσταντίνου' }).click({ timeout: 10_000 }) + await pin(a, '3302') + await a.getByTestId('login-elsewhere-continue').click({ timeout: 5000 }) + await a.waitForURL(u => u.pathname !== '/login', { timeout: 10_000 }).catch(() => {}) + const outB = await b.waitForURL(u => u.pathname === '/login', { timeout: 10_000 }).then(() => true).catch(() => false) + const noteB = await b.getByTestId('signed-out-note').innerText({ timeout: 5000 }).catch(() => '') + r.check('6F.7: the other phone is signed out at once (live) and says why', outB && /another device|άλλη συσκευή/.test(noteB), noteB) + const flushed = await waitFor(status7, 30_000, 1000) + r.check('6F.7: …and the order queued offline goes out after signing in again', !!flushed) + if (flushed) await api('DELETE', `/api/orders/${flushed}`, { token: boss }).catch(() => {}) + await a.goto(`${APP}/tables`) + } + // ── 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: /Sign out/ }).last().click() diff --git a/waiter_pwa/src/api/client.js b/waiter_pwa/src/api/client.js index 597e495..4b63c8e 100644 --- a/waiter_pwa/src/api/client.js +++ b/waiter_pwa/src/api/client.js @@ -6,6 +6,7 @@ import axios from 'axios' import { createApiClient } from '@xenia/api' import { apiBase, storageKey } from '../config/server' +import { noteSignedOut } from '../logic/signedOut' const client = createApiClient({ axios, @@ -15,7 +16,8 @@ const client = createApiClient({ onOffline: () => window.dispatchEvent(new Event('backend-offline')), // A 401 on a normal request = the session ended (expired, ended by a manager, signed in // elsewhere): sign out. The login and PIN forms opt out with { xenia: { ignoreUnauthorized: true } }. - onUnauthorized: () => { + onUnauthorized: x => { + if (x?.code === 'auth.session_ended') noteSignedOut(x.params?.reason) // 6F.7: the sign-in page says why localStorage.removeItem(storageKey('token')) localStorage.removeItem(storageKey('savedUsername')) window.location.href = '/login' diff --git a/waiter_pwa/src/context/LiveContext.jsx b/waiter_pwa/src/context/LiveContext.jsx index e61f565..3ccf53f 100644 --- a/waiter_pwa/src/context/LiveContext.jsx +++ b/waiter_pwa/src/context/LiveContext.jsx @@ -7,6 +7,8 @@ import { useWebSocket } from '../hooks/useWebSocket' import db from '../db/posdb' import client from '../api/client' import { flushAllOfflineOps } from '../services/offlineOrders' +import { noteSignedOut } from '../logic/signedOut' +import { storageKey } from '../config/server' import useChatStore from '../store/chatStore' import useKdsReadyStore from '../store/kdsReadyStore' @@ -108,13 +110,13 @@ export function LiveProvider({ children }) { // ── Called whenever we confirm the server is reachable again ───────────────── + // 6F.7: every (re)connection sends what is still queued, not only after "offline": a phone + // signed out by another one keeps its queued orders, and they go out after the next sign-in + // here even if the connection never looked lost (only unsynced ops are sent, once). const handleCameOnline = useCallback(async () => { - const wasOffline = useConnectionStore.getState().status !== 'online' setOnlineRef.current() window.dispatchEvent(new Event('live-reconnected')) - if (wasOffline) { - await flushOfflineQueue() - } + await flushOfflineQueue() await fullRefresh() }, [fullRefresh, flushOfflineQueue]) @@ -124,6 +126,16 @@ export function LiveProvider({ children }) { window.dispatchEvent(new CustomEvent('live-event', { detail: { type, data } })) switch (type) { + case 'session.ended': { + // another phone took over (reason "replaced"), a manager ended it, … : say why on the + // sign-in page. Our own sign-out ("logout") already left. Queued orders stay queued. + if (data?.reason === 'logout') break + noteSignedOut(data?.reason || 'unknown') + localStorage.removeItem(storageKey('token')) + localStorage.removeItem(storageKey('savedUsername')) + window.location.href = '/login' + break + } case 'order_updated': { try { const full = await client.get(`/api/orders/${data.order_id}`) diff --git a/waiter_pwa/src/hooks/useWebSocket.js b/waiter_pwa/src/hooks/useWebSocket.js index 772680d..d8c1947 100644 --- a/waiter_pwa/src/hooks/useWebSocket.js +++ b/waiter_pwa/src/hooks/useWebSocket.js @@ -12,6 +12,7 @@ import { useCallback, useEffect, useRef } from 'react' import { createLiveClient } from '@xenia/api' import db from '../db/posdb' import { wsUrl } from '../config/server' +import client from '../api/client' const CURSOR_KEY = 'ws_last_seq' @@ -56,6 +57,9 @@ export function useWebSocket({ token, onEvent, onConnect, onDisconnect, enabled onEvent: (type, data) => onEventRef.current?.(type, data), onReady: () => onConnectRef.current?.(), onDisconnect: () => onDisconnectRef.current?.(), + // the session ended while the phone was away (6F.7): one request gets the 401 with the + // reason, and the client's sign-out runs from there + onRefused: code => { if (code === 'auth.session_ended') client.get('/api/auth/me').catch(() => {}) }, }) liveRef.current = live live.start() diff --git a/waiter_pwa/src/logic/signedOut.js b/waiter_pwa/src/logic/signedOut.js new file mode 100644 index 0000000..d14e1fa --- /dev/null +++ b/waiter_pwa/src/logic/signedOut.js @@ -0,0 +1,25 @@ +// Why the phone was signed out (plan 6F.7): kept until the next sign-in so the sign-in page can +// say it ("Signed out: you signed in on another device"). Set by a 401 that names the reason +// (auth.session_ended {reason}) and by the live socket's session.ended (reason "replaced" the +// moment another phone takes over). A sign-out the waiter asked for ("logout") says nothing. +import { storageKey } from '../config/server' + +const KEY = () => storageKey('signedOut') + +export function noteSignedOut(reason) { + if (!reason || reason === 'logout') return + try { localStorage.setItem(KEY(), reason) } catch { /* storage unavailable */ } +} + +export function signedOutReason() { + try { return localStorage.getItem(KEY()) } catch { return null } +} + +export function clearSignedOut() { + try { localStorage.removeItem(KEY()) } catch { /* storage unavailable */ } +} + +/** The text key for a reason: "replaced" has its own, the rest a plain "you were signed out". */ +export function signedOutText(reason) { + return reason === 'replaced' ? 'login.signedOutReplaced' : 'login.signedOut' +} diff --git a/waiter_pwa/src/pages/LoginPage.jsx b/waiter_pwa/src/pages/LoginPage.jsx index cb37fc6..8542ad9 100644 --- a/waiter_pwa/src/pages/LoginPage.jsx +++ b/waiter_pwa/src/pages/LoginPage.jsx @@ -1,12 +1,13 @@ import { useCallback, useEffect, useState } from 'react' import { useNavigate } from 'react-router-dom' import { useAccess } from '@xenia/access' -import { useTranslation } from '@xenia/i18n' +import { useFormat, useTranslation } from '@xenia/i18n' import PinPad from '../components/PinPad' import useAuthStore from '../store/authStore' import client from '../api/client' import { apiError } from '../api/errors' import { assetUrl, deliveryMode, getActiveVenue } from '../config/server' +import { clearSignedOut, signedOutReason, signedOutText } from '../logic/signedOut' // ─── Waiter card ────────────────────────────────────────────────────────────── @@ -89,6 +90,9 @@ function WaiterCard({ waiter, onClick }) { // 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. +// 6F.7: signed in on another phone (rule "ask", auth.session_elsewhere {device, since}): the +// page asks; Continue sends the same sign-in with replace: true and the other phone is +// signed out at once. Why this phone was signed out (logic/signedOut.js) shows on top. export default function LoginPage() { const { t } = useTranslation('waiter') @@ -107,6 +111,9 @@ export default function LoginPage() { const [error, setError] = useState('') const [loading, setLoading] = useState(false) const [attempt, setAttempt] = useState(0) // remounts the PIN pad (clears the dots) after a miss + const [elsewhere, setElsewhere] = useState(null) // { secret, device, since }: asking before taking over + const [outReason] = useState(signedOutReason) + const { formatTime } = useFormat() const loadWaiters = useCallback(() => { setLoadingWaiters(true) @@ -129,17 +136,23 @@ export default function LoginPage() { .finally(() => setLoadingWaiters(false)) }, [typeUsername, mode]) - async function signIn(secret) { + async function signIn(secret, replace = false) { const who = typeUsername ? { username: username.trim() } : { user_id: selectedWaiter?.id } if (!who.username && who.user_id == null) return setError('') + setElsewhere(null) setLoading(true) try { - const { data } = await client.post('/api/auth/login', { client: 'waiter', ...who, ...secret }, + const { data } = await client.post('/api/auth/login', { client: 'waiter', ...who, ...secret, ...(replace ? { replace: true } : {}) }, { xenia: { ignoreUnauthorized: true, noOverride: true } }) + clearSignedOut() login({ id: data.user.id, username: data.user.username, role: data.user.role }, data.access_token) navigate('/tables', { replace: true }) } catch (err) { + if (err.xenia?.code === 'auth.session_elsewhere') { + setElsewhere({ secret, device: err.xenia.params?.device, since: err.xenia.params?.since }) + return + } setError(apiError(err, mode === 'password' ? t('login.wrongPassword') : t('login.wrongPin'))) setPassword('') setAttempt(a => a + 1) @@ -148,6 +161,15 @@ export default function LoginPage() { } } + const outNote = outReason && ( +

+ {t(signedOutText(outReason))} +

+ ) + const venueSwitch = deliveryMode() === 'native' && ( + + + ) : mode === 'password' ? (
{ e.preventDefault(); if (password) signIn({ password }) }} style={{ display: 'grid', gap: 10, marginTop: 10 }}