fooder-api/fooder/domain/token.py

72 lines
1.8 KiB
Python
Raw Normal View History

from sqlalchemy.orm import Mapped, mapped_column
2023-04-02 15:20:53 +02:00
from sqlalchemy import ForeignKey, Integer
2023-04-02 14:38:22 +02:00
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from typing import Optional
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"
"""
token = cls(
user_id=user_id,
token=token,
)
session.add(token)
try:
await session.flush()
except Exception:
raise AssertionError("invalid token")
return 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()