import datetime from typing import Optional, Sequence from sqlalchemy import update, delete from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.future import select from app.domain.models.sessions import Session class SessionsRepository: def __init__(self, db: AsyncSession): self.db = db async def create(self, session: Session) -> Session: self.db.add(session) await self.db.commit() await self.db.refresh(session) return session async def get_by_id(self, session_id: int) -> Optional[Session]: result = await self.db.execute( select(Session).filter_by(id=session_id) ) return result.scalars().first() async def get_by_token(self, token: str) -> Optional[Session]: result = await self.db.execute( select(Session).filter_by(token=token, is_active=True) ) return result.scalars().first() async def get_by_user_id(self, user_id: int) -> Sequence[Session]: result = await self.db.execute( select(Session).filter_by(user_id=user_id, is_active=True) ) return result.scalars().all() async def deactivate_session(self, session_id: int) -> None: await self.db.execute( update(Session).filter_by(id=session_id).values(is_active=False) ) await self.db.commit() async def deactivate_all_sessions(self, user_id: int) -> None: await self.db.execute( update(Session).filter_by(user_id=user_id).values(is_active=False) ) await self.db.commit() async def cleanup_expired_sessions(self) -> None: await self.db.execute( delete(Session).filter(Session.expires_at < datetime.datetime.now()) ) await self.db.commit()