"""Accounts (by email), refresh tokens, password resets and linked social identities.""" from datetime import datetime from uuid import UUID from sqlalchemy import select, update from app.common.base_repository import BaseRepository from app.modules.accounts.models import Account from app.modules.auth.models import AuthIdentity, PasswordReset, RefreshToken from app.modules.teams.models import Team class AuthAccountRepository(BaseRepository[Account]): model = Account async def by_email(self, email: str) -> Account | None: return await self.first_by(email=email) async def team_code(self, team_id: UUID | None) -> str | None: if team_id is None: return None return await self.session.scalar(select(Team.code).where(Team.id == team_id)) class RefreshTokenRepository(BaseRepository[RefreshToken]): model = RefreshToken async def by_hash_for_update(self, token_hash: str) -> RefreshToken | None: """Row-locked so two concurrent refreshes with one token cannot both rotate it.""" return (await self.session.scalars( select(RefreshToken).where(RefreshToken.token_hash == token_hash).with_for_update())).first() async def revoke_family(self, family_id: UUID, now: datetime) -> None: await self.session.execute(update(RefreshToken).where( RefreshToken.family_id == family_id, RefreshToken.revoked_at.is_(None)).values(revoked_at=now)) async def revoke_all(self, account_id: UUID, now: datetime) -> None: await self.session.execute(update(RefreshToken).where( RefreshToken.account_id == account_id, RefreshToken.revoked_at.is_(None)).values(revoked_at=now)) class PasswordResetRepository(BaseRepository[PasswordReset]): model = PasswordReset async def by_hash_for_update(self, token_hash: str) -> PasswordReset | None: return (await self.session.scalars( select(PasswordReset).where(PasswordReset.token_hash == token_hash).with_for_update())).first() class AuthIdentityRepository(BaseRepository[AuthIdentity]): model = AuthIdentity