session_service.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. # app/services/session_service.py
  2. from datetime import datetime
  3. from typing import Optional
  4. from sqlalchemy.ext.asyncio import AsyncSession
  5. from sqlalchemy import select, delete
  6. from app.models.session import VasSession
  7. from app.models.user import VasUser
  8. class SessionService:
  9. @staticmethod
  10. async def get_user_by_token(
  11. db: AsyncSession,
  12. session_id: str
  13. ) -> Optional[VasUser]:
  14. result = await db.execute(
  15. select(VasSession).where(VasSession.id == session_id)
  16. )
  17. session_obj = result.scalar_one_or_none()
  18. if not session_obj:
  19. return None
  20. if session_obj.expire_at < datetime.utcnow():
  21. await SessionService.delete_session(db, session_id)
  22. return None
  23. result = await db.execute(
  24. select(VasUser).where(VasUser.id == session_obj.user_id)
  25. )
  26. return result.scalar_one_or_none()
  27. @staticmethod
  28. async def delete_session(
  29. db: AsyncSession,
  30. session_id: str
  31. ) -> None:
  32. await db.execute(
  33. delete(VasSession).where(VasSession.id == session_id)
  34. )
  35. await db.commit()