Files
gti d21a9d1140 Add 'fiscal/' from commit '102ba84500dbd9655a0471288c3e278652593ca9'
git-subtree-dir: fiscal
git-subtree-mainline: d95165fc8f
git-subtree-split: 102ba84500
2026-09-29 14:43:23 -03:00

18 lines
967 B
Python

"""Bearer authentication storing only SHA-256 token digests."""
import hashlib, hmac
from sqlalchemy import select
from .models import Agent, Tenant
def token_hash(token): return hashlib.sha256(token.encode()).hexdigest()
def bootstrap(session, token):
digest = token_hash(token); agent = session.scalar(select(Agent).where(Agent.token_hash == digest))
if agent: return agent
tenant = session.scalar(select(Tenant).where(Tenant.name == "development")) or Tenant(name="development")
session.add(tenant); session.flush(); agent = Agent(tenant_id=tenant.id, name="development-agent", token_hash=digest); session.add(agent); session.commit(); return agent
def authenticate(session, token):
digest = token_hash(token)
for agent in session.scalars(select(Agent)).all():
if hmac.compare_digest(agent.token_hash, digest):
return agent if agent.enabled else None # a disabled (revoked) Agent must not authenticate
return None