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 <noreply@anthropic.com>
This commit is contained in:
@@ -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."),
|
||||
|
||||
@@ -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_<client>: off | refuse_new | end_old).
|
||||
rule (setting auth.single_session_<client>: 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"
|
||||
|
||||
@@ -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')
|
||||
@@ -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
|
||||
|
||||
@@ -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'),
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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 '<app>.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()
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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) == ""
|
||||
Reference in New Issue
Block a user