"""Signup, login and membership lookups.""" from __future__ import annotations import uuid from dataclasses import dataclass from sqlalchemy import select from core.auth.jwt import hash_password, verify_password from core.db.session import Database from core.tenancy.models import Membership, Role, Tenant, User class AuthError(Exception): pass @dataclass(frozen=True) class SignupResult: tenant_id: uuid.UUID user_id: uuid.UUID async def signup(db: Database, *, business_name: str, email: str, password: str) -> SignupResult: """Create a tenant and its owner. Each insert runs bound to the new tenant (RLS WITH CHECK).""" email = email.strip().lower() async with db.session() as s, s.begin(): if (await s.execute(select(User.id).where(User.email == email))).first(): raise AuthError("email already registered") user = User(email=email, password_hash=hash_password(password)) s.add(user) tenant_id = uuid.uuid4() async with db.session(tenant_id=tenant_id, user_id=user.id) as s, s.begin(): s.add(Tenant(id=tenant_id, name=business_name)) await s.flush() s.add(Membership(tenant_id=tenant_id, user_id=user.id, role=Role.OWNER)) return SignupResult(tenant_id=tenant_id, user_id=user.id) async def authenticate(db: Database, email: str, password: str) -> User: async with db.session() as s: user = ( await s.execute(select(User).where(User.email == email.strip().lower())) ).scalar_one_or_none() if user is None or not user.is_active or not verify_password(password, user.password_hash): raise AuthError("invalid credentials") return user async def memberships_for(db: Database, user_id: uuid.UUID) -> list[Membership]: """RLS policy on memberships also matches ``user_id = app.user_id``.""" async with db.session(user_id=user_id) as s: rows = await s.execute(select(Membership).where(Membership.user_id == user_id)) return list(rows.scalars()) async def role_in(db: Database, user_id: uuid.UUID, tenant_id: uuid.UUID) -> Role | None: async with db.session(tenant_id=tenant_id, user_id=user_id) as s: m = ( await s.execute( select(Membership).where( Membership.user_id == user_id, Membership.tenant_id == tenant_id ) ) ).scalar_one_or_none() return m.role if m else None async def add_member( db: Database, tenant_id: uuid.UUID, *, email: str, password: str, role: Role ) -> uuid.UUID: email = email.strip().lower() async with db.session() as s, s.begin(): user = (await s.execute(select(User).where(User.email == email))).scalar_one_or_none() if user is None: user = User(email=email, password_hash=hash_password(password)) s.add(user) async with db.session(tenant_id=tenant_id) as s, s.begin(): s.add(Membership(tenant_id=tenant_id, user_id=user.id, role=role)) return user.id