fooder-api/fooder/domain/token.py

72 lines
1.7 KiB
Python
Raw Permalink Normal View History

2023-04-02 14:38:22 +02:00
from typing import Optional
2024-08-04 16:17:16 +02:00
from sqlalchemy import ForeignKey, Integer, select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import Mapped, mapped_column
2023-04-02 14:38:22 +02:00
from .base import Base, CommonMixin
class RefreshToken(Base, CommonMixin):
"""Diary represents user diary for given day"""
2023-04-02 15:20:53 +02:00
user_id: Mapped[int] = mapped_column(Integer, ForeignKey("user.id"))
2023-04-02 14:38:22 +02:00
token: Mapped[str]
@classmethod
async def get_token(
cls,
session: AsyncSession,
user_id: int,
2023-04-02 15:20:53 +02:00
token: str,
2023-04-02 14:38:22 +02:00
) -> "Optional[RefreshToken]":
2023-04-02 15:20:53 +02:00
"""get_token.
:param session:
:type session: AsyncSession
:param user_id:
:type user_id: int
:param token:
:type token: str
:rtype: "Optional[RefreshToken]"
"""
query = select(cls).where(cls.user_id == user_id).where(cls.token == token)
2023-04-02 14:38:22 +02:00
return await session.scalar(query)
@classmethod
async def create(
cls, session: AsyncSession, user_id: int, token: str
) -> "RefreshToken":
"""create.
:param session:
:type session: AsyncSession
:param user_id:
:type user_id: int
:param token:
:type token: str
:rtype: "RefreshToken"
"""
2024-05-20 13:45:21 +02:00
db_token = cls(
2023-04-02 14:38:22 +02:00
user_id=user_id,
token=token,
)
2024-05-20 13:45:21 +02:00
session.add(db_token)
2023-04-02 14:38:22 +02:00
try:
await session.flush()
except Exception:
raise AssertionError("invalid token")
2024-05-20 13:45:21 +02:00
return db_token
2023-04-02 15:20:53 +02:00
async def delete(self, session: AsyncSession) -> None:
"""delete.
:param session:
:type session: AsyncSession
:rtype: None
"""
await session.delete(self)
await session.flush()