129 lines
6.7 KiB
Python
129 lines
6.7 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 AuthProvider, ErrorType
|
|
from common.logger import LOG
|
|
from config.settings import settings
|
|
from crud.user_crud import UserCRUD
|
|
from services.external import toss_login
|
|
|
|
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")
|
|
TOSS_REFERRERS = ("DEFAULT", "SANDBOX")
|
|
|
|
|
|
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 toss_login(self, authorization_code: str, referrer: str) -> tuple[ErrorType, Optional[User]]:
|
|
"""토스 userKey 로 계정을 찾고, 없으면 만든다. 이름·전화번호 같은 개인정보는 받지 않는다."""
|
|
if not authorization_code or referrer not in TOSS_REFERRERS:
|
|
return ErrorType.INVALID_INPUT, None
|
|
try:
|
|
key = str(await toss_login.user_key(authorization_code, referrer))
|
|
except toss_login.TossLoginError as e:
|
|
LOG.error(f"[auth] toss login: {e}")
|
|
return ErrorType.AUTH_FAILED, None
|
|
provider = AuthProvider.TOSS.value
|
|
err, user = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.by_provider_uid(s, provider, key))
|
|
if err is not ErrorType.SUCCESS:
|
|
return err, None
|
|
if user is None:
|
|
err, user = await DB_SESSION_MNG.execute_lambda_write(
|
|
lambda s: self.crud.create_social(s, provider, key, f"toss_{key}", f"토스{key[-4:]}")
|
|
)
|
|
if err is not ErrorType.SUCCESS:
|
|
# 같은 사람이 동시에 두 번 들어온 경우 먼저 만든 계정을 쓴다
|
|
err, user = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.by_provider_uid(s, provider, key))
|
|
if err is not ErrorType.SUCCESS or user is None:
|
|
return err if err is not ErrorType.SUCCESS else ErrorType.DB_ERROR, None
|
|
if user.status != 1:
|
|
return ErrorType.AUTH_FAILED, None
|
|
return ErrorType.SUCCESS, user
|
|
|
|
async def toss_unlink(self, user_key: str) -> ErrorType:
|
|
"""토스에서 연결을 끊으면 그 계정의 모든 토큰을 무효로 만든다. 계정이 없어도 성공으로 본다."""
|
|
err, user = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.by_provider_uid(s, AuthProvider.TOSS.value, user_key))
|
|
if err is not ErrorType.SUCCESS or user is None:
|
|
return err
|
|
return await self.logout(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)
|