from functools import wraps from flask import abort, g, request from obsigil import Obsigil, ObsigilError, generate_uuid7 from backend.app.api.context import ledger from backend.app.common.constants import AUTH_AUDIENCE, AUTH_LIFETIME from backend.app.common.utils import utc_now from backend.app.infrastructure.persistence import repositories from backend.app.infrastructure.persistence.connection import database def sign_in(user_id, username): now = int(utc_now().timestamp()) expires_at = now + int(AUTH_LIFETIME.total_seconds()) tid = generate_uuid7() token = Obsigil.mint( clauses={}, mandate_key=ledger().obsigil_key, tid=tid, sub=user_id, aud=[AUTH_AUDIENCE], exp=expires_at, manifest={"iss": AUTH_AUDIENCE, "claims": {"username": username}}, ).token() connection = database() with connection: repositories.delete_auth_session(connection, g.token_id) repositories.create_auth_session(connection, tid, user_id, expires_at) return {"id": user_id, "username": username, "access_token": token} def claimed_username(token): claims = Obsigil(token, max_decoded_len=4096).claims() or {} username = claims.get("username") return username if isinstance(username, str) else None def load_identity(): g.user = None g.token = None g.token_id = None authorization = request.headers.get("Authorization", "").split() if len(authorization) != 2 or authorization[0].lower() != "bearer": return token = authorization[1] if len(token) > 4096: return now = int(utc_now().timestamp()) try: clauses = Obsigil( token, keys=ledger().obsigil_key, audience=AUTH_AUDIENCE, now=now, max_decoded_len=4096, ).clauses() except ObsigilError: return user_id = clauses.get("sub") if not isinstance(user_id, str) or clauses.get("aud") != [AUTH_AUDIENCE]: return row = repositories.get_auth_user(database(), clauses["tid"], user_id, clauses["exp"], now) if row is not None: g.user = dict(row) g.token = token g.token_id = clauses["tid"] def owner_session(route): @wraps(route) def guarded(*args, **kwargs): if g.user is None: abort(401, "Authentication required") return route(*args, **kwargs) return guarded