import re import uuid from typing import Optional from fastapi import Depends from common.auth import decode, hash_password, issue_tokens, verify_password from common.database.db_session_manager import DB_SESSION_MNG from common.database.model.models import User from common.enums import ErrorType from config.settings import settings from crud.user_crud import UserCRUD LOGIN_ID = re.compile(r"^[a-z0-9_]{4,20}$") PASSWORD_MIN = 8 NICKNAME = re.compile(r"^\S.{0,10}\S$") class AuthService: def __init__(self, crud: UserCRUD = Depends(UserCRUD)) -> None: self.crud = crud async def signup(self, login_id: str, password: str, nickname: str) -> tuple[ErrorType, Optional[User]]: if not LOGIN_ID.match(login_id) or len(password) < PASSWORD_MIN or not NICKNAME.match(nickname): return ErrorType.INVALID_INPUT, None err, exists = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.by_login_id(s, login_id)) if err is not ErrorType.SUCCESS: return err, None if exists is not None: return ErrorType.AUTH_DUPLICATE_ID, None hashed = await hash_password(password) err, user = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.create(s, login_id, hashed, nickname)) return (err, user) if err is ErrorType.SUCCESS else (ErrorType.AUTH_DUPLICATE_ID, None) async def login(self, login_id: str, password: str) -> tuple[ErrorType, Optional[User]]: err, user = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.by_login_id(s, login_id)) if err is not ErrorType.SUCCESS: return err, None if user is None or user.password is None or user.status != 1 or not await verify_password(password, user.password): return ErrorType.AUTH_FAILED, None return ErrorType.SUCCESS, user async def refresh(self, refresh_token: str) -> tuple[ErrorType, Optional[User]]: claims = decode(refresh_token, settings.jwt_refresh_secret, "refresh") if claims is None: return ErrorType.AUTH_TOKEN_INVALID, None err, user = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.get(s, uuid.UUID(claims["sub"]))) if err is not ErrorType.SUCCESS or user is None or user.status != 1 or user.token_version != claims.get("ver"): return ErrorType.AUTH_TOKEN_INVALID, None return ErrorType.SUCCESS, user @staticmethod def tokens(user: User) -> tuple[str, str]: return issue_tokens(user)