from datetime import datetime from .database import BotDatabase from .domain import Binding, OAuthCredentials class BotOAuthRepository: """Транзакционные операции с OAuth-данными Битрикса. Обертка над хранимыми функциями БД.""" def __init__(self, database: BotDatabase) -> None: self.database = database async def get(self, binding: Binding) -> OAuthCredentials | None: async with self.database.transaction() as connection: cursor = await connection.execute( "SELECT * FROM oauth.get_credentials_v1(%s, %s)", (binding.member_id, binding.bitrix_user_id) ) row = await cursor.fetchone() # pyrefly: ignore [bad-argument-type] return self._credentials(row) if row else None async def claim_refresh(self, credentials: OAuthCredentials) -> bool: async with self.database.transaction() as connection: cursor = await connection.execute( "SELECT oauth.claim_refresh_v1(%s, %s, %s)", ( credentials.member_id, credentials.bitrix_user_id, credentials.version ) ) row = await cursor.fetchone() # pyrefly: ignore [missing-attribute] return bool(row and next(iter(row.values()))) async def finish_refresh( self, credentials: OAuthCredentials, access_token: bytes, refresh_token: bytes, expires_at: datetime ) -> bool: async with self.database.transaction() as connection: cursor = await connection.execute( "SELECT oauth.finish_refresh_v1(%s, %s, %s, %s, %s, %s)", ( credentials.member_id, credentials.bitrix_user_id, credentials.version, access_token, refresh_token, expires_at ) ) row = await cursor.fetchone() # pyrefly: ignore [missing-attribute] return bool(row and next(iter(row.values()))) async def release_refresh(self, credentials: OAuthCredentials) -> None: async with self.database.transaction() as connection: await connection.execute( "SELECT oauth.release_refresh_v1(%s, %s, %s)", ( credentials.member_id, credentials.bitrix_user_id, credentials.version ) ) @staticmethod def _credentials(row: dict) -> OAuthCredentials: return OAuthCredentials( member_id=str(row["member_id"]), domain=str(row["domain"]), bitrix_user_id=int(row["bitrix_user_id"]), access_token=bytes(row["access_token"]), refresh_token=bytes(row["refresh_token"]), expires_at=row["expires_at"], version=int(row["version"]) )