Files
mtusi2026lab2/app/database_functions/sessions_functions.py

30 lines
930 B
Python

import uuid
from datetime import datetime
from sqlalchemy import delete, func, select
from sqlalchemy.orm import Session
from models import AuthSession
def create_session(db: Session, token_hash: bytes, user_id: uuid.UUID,
created_at: datetime, expires_at: datetime) -> AuthSession:
auth_session = AuthSession(token_hash=token_hash, user_id=user_id, created_at=created_at, expires_at=expires_at)
db.add(auth_session)
db.commit()
return auth_session
def get_active_session(db: Session, token_hash: bytes) -> AuthSession | None:
query = select(AuthSession).where(
AuthSession.token_hash == token_hash,
AuthSession.expires_at > func.now(),
)
return db.scalar(query)
def delete_session(db: Session, token_hash: bytes) -> bool:
result = db.execute(delete(AuthSession).where(AuthSession.token_hash == token_hash))
db.commit()
return result.rowcount > 0