Files

93 lines
4.6 KiB
Python

import re
import uuid
from typing import Optional
from fastapi import Depends
from common.auth import PASSWORD_MAX_BYTES, 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$")
CHARACTERS = ("rabbit", "bear", "dog", "sun", "moon", "cloud")
COLORS = ("orange", "blue", "green", "purple", "pink", "brown")
MOODS = ("clear", "partly", "cloudy", "rain", "thunder", "snow", "fog", "rainbow")
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 len(password.encode()) > PASSWORD_MAX_BYTES 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))
if err is ErrorType.SUCCESS:
return err, user
# 같은 아이디가 동시에 가입된 경우만 중복으로, 나머지는 DB 오류 그대로
_, exists = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.by_login_id(s, login_id))
return (ErrorType.AUTH_DUPLICATE_ID if exists is not None else err), 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
async def logout(self, user: User) -> ErrorType:
"""이 사용자의 모든 기기 토큰을 무효로 만든다."""
return await DB_SESSION_MNG.execute_lambda_run([lambda s: self.crud.update(s, user.user_id, {"token_version": user.token_version + 1})])
async def update_me(self, user: User, nickname: Optional[str], character: Optional[str], color: Optional[str] = None, mood: Optional[str] = None) -> tuple[ErrorType, Optional[User]]:
"""닉네임·캐릭터·배경색·기분 중 보낸 것만 바꾼다. 기분을 빈 문자열로 보내면 지운다."""
values: dict = {}
if nickname is not None:
nickname = nickname.strip()
if not NICKNAME.match(nickname):
return ErrorType.INVALID_INPUT, None
values["nickname"] = nickname
if character is not None:
if character not in CHARACTERS:
return ErrorType.INVALID_INPUT, None
values["character"] = character
if color is not None:
if color not in COLORS:
return ErrorType.INVALID_INPUT, None
values["color"] = color
if mood is not None:
if mood and mood not in MOODS:
return ErrorType.INVALID_INPUT, None
values["mood"] = mood or None
if not values:
return ErrorType.SUCCESS, user
err, updated = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.update(s, user.user_id, values))
if err is not ErrorType.SUCCESS:
return err, None
return (ErrorType.SUCCESS, updated) if updated is not None else (ErrorType.NOT_FOUND, None)
@staticmethod
def tokens(user: User) -> tuple[str, str]:
return issue_tokens(user)