import uuid from datetime import datetime, timezone from sqlalchemy import delete, select from sqlalchemy.orm import Session from app.db.models import Session as UserSession class SessionRepository: def __init__(self, db: Session): self.db = db def create( self, user_id: uuid.UUID, token_hash: str, expires_at: datetime, ) -> UserSession: session = UserSession( user_id=user_id, token_hash=token_hash, expires_at=expires_at, ) self.db.add(session) self.db.flush() return session def get_by_token_hash( self, token_hash: str, ) -> UserSession | None: statement = select(UserSession).where( UserSession.token_hash == token_hash ) return self.db.scalar(statement) def get_valid_session( self, token_hash: str, ) -> UserSession | None: now = datetime.now(timezone.utc) statement = select(UserSession).where( UserSession.token_hash == token_hash, UserSession.expires_at > now, ) return self.db.scalar(statement) def delete_by_token_hash( self, token_hash: str, ) -> bool: statement = ( delete(UserSession) .where(UserSession.token_hash == token_hash) .returning(UserSession.id) ) return self.db.scalar(statement) is not None def delete_expired(self) -> int: now = datetime.now(timezone.utc) statement = ( delete(UserSession) .where(UserSession.expires_at <= now) ) result = self.db.execute(statement) return result.rowcount