Platform v2 step 1.5 (APPS_PLATFORM D-7, D-17, §3, §6.1).
- user_permissions(user_id, key); revision 0005 copies existing v1 flags into
keys (frozen mapping) and drops the perm_* columns; can_cancel_orders gone
- core/access: check() = module effective + key held (superadmin implicit,
override keys wired for 1.9); holds()/can(); markers require/require_any/
public/require_device; role templates from manifests; queries.holders_filter
replaces User.perm_x == True; legacy.py projects/accepts the v1 booleans
for the current manager/waiter UIs only (§3.3, temporary)
- routers.deps: require_manager/... are now aliases of require("<key>");
history endpoints use history.view; superadmin-only = core.system.admin;
get_current_user carries the "signed_in" marker
- every inline perm_* read in routers/services converted to holds()
- staff API: permission catalogue by module with role templates, get/set a
user's keys, reset to role template; legacy flag toggles still work; a
non-superadmin can only grant keys they hold (access.cannot_grant)
- setup wizard creates the first account as owner (v1: store_manager, who
couldn't change settings); demo/seed manager is owner
- roles.py keeps only the role list and labels
- guards: every route has an access marker (19 open routes marked public()
on purpose; /waiters/roles now needs sign-in), no perm_* attribute reads
- tests: check matrix, templates, projection, staff permission API, grant
guard, 0005 data copy; pack rule CS-14
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
227 lines
9.3 KiB
Python
227 lines
9.3 KiB
Python
from core.access.deps import public
|
|
from core.access.check import holds
|
|
from core.access.queries import holders_filter
|
|
import bcrypt
|
|
import logging
|
|
from fastapi import APIRouter, Depends, HTTPException, status
|
|
from sqlalchemy.orm import Session
|
|
|
|
from database import get_db
|
|
from config import settings
|
|
from models.user import User
|
|
from schemas.auth import LoginRequest, TokenResponse, UpdateMeRequest
|
|
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 get_current_user, make_token, decode_token, blacklist_token, _make_ghost_superadmin
|
|
from routers.recovery import try_recovery_code
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
class NoAuthLoginRequest(_PydanticBase):
|
|
username: str
|
|
|
|
|
|
@router.post("/login-no-auth", response_model=TokenResponse, dependencies=[Depends(public())])
|
|
def login_no_auth(body: NoAuthLoginRequest, db: Session = Depends(get_db)):
|
|
"""Login with no credentials — only works when security.login_method = 'none'."""
|
|
from models.settings import PosSettings
|
|
setting = db.query(PosSettings).filter(PosSettings.key == "security.login_method").first()
|
|
if not setting or setting.value != "none":
|
|
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="No-auth login is not enabled.")
|
|
user = db.query(User).filter(User.username == body.username, User.is_active == True).first()
|
|
if not user or not holds(user, "core.dashboard.access"):
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid credentials")
|
|
token = make_token(user)
|
|
return TokenResponse(access_token=token, user=UserOut.model_validate(user))
|
|
|
|
|
|
@router.post("/login", response_model=TokenResponse, dependencies=[Depends(public())])
|
|
def login(body: LoginRequest, db: Session = Depends(get_db)):
|
|
# Break-glass master account — checked before DB, never stored as a real user
|
|
if (
|
|
settings.MASTER_USERNAME
|
|
and settings.MASTER_PASSWORD
|
|
and body.username == settings.MASTER_USERNAME
|
|
and body.password == settings.MASTER_PASSWORD
|
|
):
|
|
_logger.warning("MASTER LOGIN USED from username=%s", body.username)
|
|
ghost = _make_ghost_superadmin()
|
|
token = make_token(ghost)
|
|
return TokenResponse(access_token=token, user=UserOut.model_validate(ghost))
|
|
|
|
user = db.query(User).filter(User.username == body.username, User.is_active == True).first()
|
|
if not user:
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid credentials")
|
|
|
|
authenticated = False
|
|
if body.password and user.password_hash:
|
|
authenticated = bcrypt.checkpw(body.password.encode(), user.password_hash.encode())
|
|
elif body.pin and user.pin_hash:
|
|
authenticated = bcrypt.checkpw(body.pin.encode(), user.pin_hash.encode())
|
|
|
|
# If normal auth failed, check if the submitted value is a recovery code
|
|
if not authenticated and body.password:
|
|
authenticated = try_recovery_code(body.password, user, db)
|
|
|
|
if not authenticated:
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid credentials")
|
|
|
|
token = make_token(user)
|
|
return TokenResponse(access_token=token, user=UserOut.model_validate(user))
|
|
|
|
|
|
@router.post("/login-by-id", response_model=TokenResponse, dependencies=[Depends(public())])
|
|
def login_by_id(body: LoginByIdRequest, db: Session = Depends(get_db)):
|
|
"""Login using waiter id + PIN (used by the waiter-picker login screen)."""
|
|
user = db.query(User).filter(User.id == body.waiter_id, User.is_active == True).first()
|
|
if not user or not bcrypt.checkpw(body.pin.encode(), user.pin_hash.encode()):
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Λανθασμένο PIN")
|
|
token = make_token(user)
|
|
return TokenResponse(access_token=token, user=UserOut.model_validate(user))
|
|
|
|
|
|
@router.post("/refresh", response_model=TokenResponse, dependencies=[Depends(public())])
|
|
def refresh(token: str, db: Session = Depends(get_db)):
|
|
payload = decode_token(token)
|
|
user = db.query(User).filter(User.id == int(payload["sub"]), User.is_active == True).first()
|
|
if not user:
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="User not found")
|
|
blacklist_token(token)
|
|
new_token = make_token(user)
|
|
return TokenResponse(access_token=new_token, user=UserOut.model_validate(user))
|
|
|
|
|
|
@router.post("/logout", dependencies=[Depends(public())])
|
|
def logout(token: str):
|
|
blacklist_token(token)
|
|
return {"status": "logged out"}
|
|
|
|
|
|
@router.get("/me", response_model=UserOut)
|
|
def me(user: User = Depends(get_current_user)):
|
|
return user
|
|
|
|
|
|
# ─── Public manager list (login screen — no auth required) ───────────────────
|
|
|
|
class PublicManagerOut(_PydanticBase):
|
|
id: int
|
|
username: str
|
|
full_name: str | None
|
|
model_config = {"from_attributes": True}
|
|
|
|
|
|
@router.get("/managers", response_model=list[PublicManagerOut], dependencies=[Depends(public())])
|
|
def public_manager_list(db: Session = Depends(get_db)):
|
|
"""Public endpoint — returns accounts with dashboard access for login screen."""
|
|
managers = db.query(User).filter(
|
|
holders_filter("core.dashboard.access"),
|
|
User.is_active == True,
|
|
).all()
|
|
return [PublicManagerOut(id=m.id, username=m.username, full_name=m.full_name) for m in managers]
|
|
|
|
|
|
# ─── Public waiter list (login screen — no auth required) ────────────────────
|
|
|
|
from pydantic import BaseModel as _BaseModel
|
|
|
|
class PublicWaiterOut(_BaseModel):
|
|
id: int
|
|
full_name: str | None
|
|
nickname: str | None
|
|
avatar_url: str | None
|
|
on_shift: bool
|
|
model_config = {"from_attributes": True}
|
|
|
|
|
|
@router.get("/waiters", response_model=list[PublicWaiterOut], dependencies=[Depends(public())])
|
|
def public_waiter_list(db: Session = Depends(get_db)):
|
|
"""Public endpoint — returns active waiters with on-shift flag. No auth required."""
|
|
from models.shift import WaiterShift
|
|
waiters = db.query(User).filter(holders_filter("waiter_app.access"), User.is_active == True).all()
|
|
on_shift_ids = {
|
|
row.waiter_id
|
|
for row in db.query(WaiterShift).filter(WaiterShift.ended_at == None).all()
|
|
}
|
|
return [
|
|
PublicWaiterOut(
|
|
id=w.id,
|
|
full_name=w.full_name,
|
|
nickname=w.nickname,
|
|
avatar_url=w.avatar_url,
|
|
on_shift=w.id in on_shift_ids,
|
|
)
|
|
for w in waiters
|
|
]
|
|
|
|
|
|
@router.patch("/me", response_model=UserOut)
|
|
def update_me(body: UpdateMeRequest, db: Session = Depends(get_db), user: User = Depends(get_current_user)):
|
|
# Password change — requires current_password verification
|
|
if body.new_password is not None:
|
|
if not body.current_password:
|
|
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="current_password is required to set a new password")
|
|
if not user.password_hash:
|
|
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Account has no password set")
|
|
if not bcrypt.checkpw(body.current_password.encode(), user.password_hash.encode()):
|
|
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Current password is incorrect")
|
|
if len(body.new_password) < 6:
|
|
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="New password must be at least 6 characters")
|
|
user.password_hash = bcrypt.hashpw(body.new_password.encode(), bcrypt.gensalt()).decode()
|
|
|
|
# PIN change — no current PIN required (already authenticated)
|
|
if body.new_pin is not None:
|
|
if len(body.new_pin) < 4:
|
|
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="PIN must be at least 4 digits")
|
|
user.pin_hash = bcrypt.hashpw(body.new_pin.encode(), bcrypt.gensalt()).decode()
|
|
|
|
# Username change — check uniqueness
|
|
if body.username is not None and body.username != user.username:
|
|
conflict = db.query(User).filter(User.username == body.username, User.id != user.id).first()
|
|
if conflict:
|
|
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="Username already taken")
|
|
user.username = body.username
|
|
|
|
# Display name
|
|
if body.full_name is not None:
|
|
user.full_name = body.full_name
|
|
|
|
# Personal language (D-12); "" = inherit
|
|
if body.language is not None:
|
|
user.language = normalize_language(body.language)
|
|
|
|
db.commit()
|
|
db.refresh(user)
|
|
return user
|
|
|
|
|
|
class WaiterSettingsPayload(_PydanticBase):
|
|
settings: str # raw JSON string
|
|
|
|
|
|
@router.get("/me/settings")
|
|
def get_my_settings(user: User = Depends(get_current_user)):
|
|
"""Return the stored waiter settings JSON blob for the current user."""
|
|
return {"settings": user.waiter_settings or "{}"}
|
|
|
|
|
|
@router.put("/me/settings")
|
|
def put_my_settings(body: WaiterSettingsPayload, db: Session = Depends(get_db), user: User = Depends(get_current_user)):
|
|
"""Replace the stored waiter settings JSON blob."""
|
|
import json as _json
|
|
try:
|
|
_json.loads(body.settings) # validate it's valid JSON
|
|
except Exception:
|
|
raise HTTPException(status_code=422, detail="settings must be valid JSON")
|
|
user.waiter_settings = body.settings
|
|
db.commit()
|
|
return {"settings": user.waiter_settings}
|