"""Request-local, verified room identity; never use a global last-room cookie.""" from contextvars import ContextVar from functools import wraps from urllib.parse import urlsplit, parse_qs _current = ContextVar('kronic_room_access', default=None) def current(uid): scope = _current.get() return scope[1] if scope and scope[0] == int(uid) else None def clear(): return _current.set(None) def restore(token): _current.reset(token) def bind(uid, room_id): from media_accounts import open_database, AccountError with open_database() as db: row = db.execute('''SELECT r.id FROM managed_rooms r JOIN groups g ON g.id=r.group_id JOIN room_memberships m ON m.room_id=r.id WHERE r.id=? AND m.user_id=? AND r.enabled=1 AND g.status='active' ''', (room_id,uid)).fetchone() if not row: raise AccountError(403,'Selected room is not assigned to this account') _current.set((int(uid),int(row['id']))) return int(row['id']) def bind_request(handler): from media_accounts import session_user, assigned_rooms, AccountError # A handler can call the same authorization guard more than once. # The enclosing HTTP-method decorator resets this context for every request. if _current.get() is not None: return _current.get()[1] token=handler.get_session_token(); user=session_user(token); uid=int(user['id']) rooms=assigned_rooms(token) raw=handler.headers.get('X-Kronic-Room') url_room=parse_qs(urlsplit(handler.path).query,keep_blank_values=True).get('kronic_room',[]) if len(url_room)>1 or (url_room and raw is not None and raw!=url_room[0]): raise AccountError(400,'Conflicting room selectors') if url_room: raw=url_room[0] ref=urlsplit(handler.headers.get('Referer','')) name=None if ref.path in ('/','/app','/m','/m/','/desktop','/desktop/') and ref.netloc.lower()==(handler.headers.get('Host') or '').lower(): name=parse_qs(ref.query).get('room',[None])[0] if raw is not None: if not raw.isascii() or not raw.isdigit() or len(raw)>19 or not 0