feat: 구글 로그인 — 로그인 창에 구글로 계속하기 버튼, 서버가 구글 ID 토큰 서명·클라이언트 ID·만료를 확인, 처음이면 자동 닉네임으로 가입(구글 이름·이메일은 저장 안 함)
This commit is contained in:
1 parent
eb2151164f
commit
4e9b0bacba
15 files changed
+407
-13
No files matched your search
@@ -0,0 +1,43 @@
|
||||
import time
|
||||
from typing import Optional
|
||||
|
||||
import httpx
|
||||
from jose import JWTError, jwt
|
||||
|
||||
from common.logger import LOG
|
||||
from config.settings import settings
|
||||
|
||||
CERTS_URL = "https://www.googleapis.com/oauth2/v3/certs"
|
||||
ISSUERS = ("accounts.google.com", "https://accounts.google.com")
|
||||
_CERTS_TTL = 3600
|
||||
_certs: dict = {"keys": [], "at": 0.0}
|
||||
|
||||
|
||||
async def _keys(force: bool = False) -> list[dict]:
|
||||
"""구글 서명 공개키. 한 시간 캐시하고, 모르는 키가 오면 한 번 다시 받는다."""
|
||||
if force or not _certs["keys"] or time.monotonic() - _certs["at"] > _CERTS_TTL:
|
||||
async with httpx.AsyncClient(timeout=5) as c:
|
||||
res = await c.get(CERTS_URL)
|
||||
res.raise_for_status()
|
||||
_certs["keys"], _certs["at"] = res.json()["keys"], time.monotonic()
|
||||
return _certs["keys"]
|
||||
|
||||
|
||||
async def verify(credential: str) -> Optional[str]:
|
||||
"""구글 로그인 버튼이 준 ID 토큰을 확인하고 구글 사용자 고유 번호(sub)를 돌려준다. 서명·발급처·우리 클라이언트 ID·만료가 하나라도 안 맞으면 None."""
|
||||
if not settings.google_client_id:
|
||||
LOG.error("[google] GOOGLE_CLIENT_ID is empty")
|
||||
return None
|
||||
try:
|
||||
kid = jwt.get_unverified_header(credential).get("kid")
|
||||
keys = await _keys()
|
||||
key = next((k for k in keys if k.get("kid") == kid), None) or next((k for k in await _keys(force=True) if k.get("kid") == kid), None)
|
||||
if key is None:
|
||||
return None
|
||||
claims = jwt.decode(credential, key, algorithms=["RS256"], audience=settings.google_client_id, options={"verify_at_hash": False})
|
||||
except (JWTError, httpx.HTTPError, KeyError, ValueError) as e:
|
||||
LOG.warning("[google] id token rejected: %s", type(e).__name__)
|
||||
return None
|
||||
if claims.get("iss") not in ISSUERS or not claims.get("sub"):
|
||||
return None
|
||||
return str(claims["sub"])
|
||||
@@ -37,6 +37,9 @@ class Settings(BaseSettings):
|
||||
# 사람 글 사진을 저장할 폴더 (compose 볼륨)
|
||||
upload_dir: str = "uploads"
|
||||
|
||||
# 구글 로그인 OAuth 클라이언트 ID (공개값). 비면 구글 로그인을 받지 않는다
|
||||
google_client_id: str = ""
|
||||
|
||||
jwt_access_secret: str = ""
|
||||
jwt_refresh_secret: str = ""
|
||||
jwt_access_minutes: int = 60
|
||||
|
||||
@@ -22,6 +22,12 @@ class UserCRUD:
|
||||
await s.flush()
|
||||
return user
|
||||
|
||||
async def create_google(self, s: AsyncSession, sub: str, nickname: str) -> User:
|
||||
user = User(login_id=f"google_{sub}", provider_uid=sub, nickname=nickname, provider=2)
|
||||
s.add(user)
|
||||
await s.flush()
|
||||
return user
|
||||
|
||||
async def update(self, s: AsyncSession, user_id: uuid.UUID, values: dict) -> Optional[User]:
|
||||
user = await self.get(s, user_id)
|
||||
if user is None:
|
||||
|
||||
@@ -4,7 +4,8 @@ from common.auth import current_user
|
||||
from common.database.model.models import User
|
||||
from common.enums import AuthProvider, ErrorType
|
||||
from common.models.errors import error_info
|
||||
from router.v1.auth.protocol import Me, Req_Login, Req_Refresh, Req_Signup, Req_UpdateMe, Res_Auth, Res_Logout, Res_Me
|
||||
from config.settings import settings
|
||||
from router.v1.auth.protocol import Me, Req_Google, Req_Login, Req_Refresh, Req_Signup, Req_UpdateMe, Res_Auth, Res_AuthConfig, Res_Logout, Res_Me
|
||||
from services.auth_service import AuthService
|
||||
|
||||
router = APIRouter(prefix="/v1/auth", tags=["auth"])
|
||||
@@ -33,6 +34,17 @@ async def login(req: Req_Login, service: AuthService = Depends()) -> Res_Auth:
|
||||
return _auth(err, user, service)
|
||||
|
||||
|
||||
@router.post("/google", response_model=Res_Auth, response_model_exclude_none=True, summary="구글 로그인 (처음이면 자동 닉네임으로 가입)")
|
||||
async def google_login(req: Req_Google, service: AuthService = Depends()) -> Res_Auth:
|
||||
err, user = await service.google(req.credential)
|
||||
return _auth(err, user, service)
|
||||
|
||||
|
||||
@router.get("/config", response_model=Res_AuthConfig, response_model_exclude_none=True, summary="로그인 화면 설정 (구글 클라이언트 ID)")
|
||||
async def auth_config() -> Res_AuthConfig:
|
||||
return Res_AuthConfig(google_client_id=settings.google_client_id or None)
|
||||
|
||||
|
||||
@router.post("/refresh", response_model=Res_Auth, response_model_exclude_none=True, summary="토큰 재발급")
|
||||
async def refresh(req: Req_Refresh, service: AuthService = Depends()) -> Res_Auth:
|
||||
err, user = await service.refresh(req.refresh_token)
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
from common.enums import AuthProvider
|
||||
from common.models.gmodel import Req_WebPacketProtocol, Res_WebPacketProtocol, WebPacketProtocol
|
||||
|
||||
@@ -15,6 +17,10 @@ class Req_Login(Req_WebPacketProtocol):
|
||||
password: str
|
||||
|
||||
|
||||
class Req_Google(Req_WebPacketProtocol):
|
||||
credential: str = Field(min_length=20, max_length=4096, description="구글 로그인 버튼이 준 ID 토큰")
|
||||
|
||||
|
||||
class Req_Refresh(Req_WebPacketProtocol):
|
||||
refresh_token: str
|
||||
|
||||
@@ -47,3 +53,7 @@ class Res_Logout(Res_WebPacketProtocol):
|
||||
|
||||
class Res_Me(Res_WebPacketProtocol):
|
||||
me: Optional[Me] = None
|
||||
|
||||
|
||||
class Res_AuthConfig(Res_WebPacketProtocol):
|
||||
google_client_id: Optional[str] = Field(None, description="구글 로그인 버튼에 쓸 OAuth 클라이언트 ID. 없으면 구글 로그인을 숨긴다")
|
||||
@@ -1,4 +1,5 @@
|
||||
import re
|
||||
import secrets
|
||||
import uuid
|
||||
from typing import Optional
|
||||
|
||||
@@ -6,6 +7,7 @@ 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.google_id import verify as verify_google
|
||||
from common.database.model.models import User
|
||||
from common.enums import ErrorType
|
||||
from config.settings import settings
|
||||
@@ -19,6 +21,15 @@ COLORS = ("orange", "blue", "green", "purple", "pink", "brown")
|
||||
MOODS = ("clear", "partly", "cloudy", "rain", "thunder", "snow", "fog", "rainbow")
|
||||
|
||||
|
||||
_NICK_WORDS = ("맑은", "포근한", "산들", "반짝", "느긋한", "보슬", "선선한", "따끈한")
|
||||
_NICK_ANIMALS = {"rabbit": "토끼", "bear": "곰", "dog": "강아지", "sun": "해님", "moon": "달님", "cloud": "구름"}
|
||||
|
||||
|
||||
def auto_nickname() -> str:
|
||||
"""구글로 처음 들어온 사람의 이름: 맑은토끼 482. 내 정보에서 바꿀 수 있다."""
|
||||
return f"{secrets.choice(_NICK_WORDS)}{secrets.choice(list(_NICK_ANIMALS.values()))} {secrets.randbelow(900) + 100}"
|
||||
|
||||
|
||||
class AuthService:
|
||||
def __init__(self, crud: UserCRUD = Depends(UserCRUD)) -> None:
|
||||
self.crud = crud
|
||||
@@ -47,6 +58,26 @@ class AuthService:
|
||||
return ErrorType.AUTH_FAILED, None
|
||||
return ErrorType.SUCCESS, user
|
||||
|
||||
async def google(self, credential: str) -> tuple[ErrorType, Optional[User]]:
|
||||
"""구글 ID 토큰으로 로그인. 처음이면 자동 닉네임으로 계정을 만든다. 구글 이름·이메일은 저장하지 않는다."""
|
||||
sub = await verify_google(credential)
|
||||
if sub is None:
|
||||
return ErrorType.AUTH_FAILED, None
|
||||
login_id = f"google_{sub}"
|
||||
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:
|
||||
err, user = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.create_google(s, sub, auto_nickname()))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
# 같은 계정이 동시에 처음 들어온 경우엔 먼저 만들어진 쪽을 쓴다
|
||||
err, user = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.by_login_id(s, login_id))
|
||||
if err is not ErrorType.SUCCESS or user is None:
|
||||
return ErrorType.DB_ERROR, None
|
||||
if user.status != 1:
|
||||
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:
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import time
|
||||
|
||||
import pytest
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import rsa
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
from jose import jwk, jwt
|
||||
|
||||
import common.google_id as google_id
|
||||
import services.auth_service as auth_service
|
||||
from config.settings import settings
|
||||
from router.router import app
|
||||
|
||||
CLIENT_ID = "test-client.apps.googleusercontent.com"
|
||||
|
||||
|
||||
def client():
|
||||
return AsyncClient(transport=ASGITransport(app=app), base_url="http://test")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def google_keys(monkeypatch):
|
||||
"""가짜 구글 서명키. 공개키는 _keys 대신 돌려준다."""
|
||||
monkeypatch.setattr(settings, "google_client_id", CLIENT_ID)
|
||||
key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
||||
pem = key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption())
|
||||
public = jwk.construct(key.public_key().public_bytes(serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo), "RS256").to_dict()
|
||||
public["kid"] = "k1"
|
||||
|
||||
async def keys(force: bool = False):
|
||||
return [public]
|
||||
|
||||
monkeypatch.setattr(google_id, "_keys", keys)
|
||||
|
||||
def sign(**over):
|
||||
claims = {"iss": "https://accounts.google.com", "aud": CLIENT_ID, "sub": "1234567890", "exp": int(time.time()) + 600, "iat": int(time.time()), "name": "홍길동", "email": "a@example.com"}
|
||||
claims.update(over)
|
||||
return jwt.encode(claims, pem, algorithm="RS256", headers={"kid": "k1"})
|
||||
|
||||
return sign
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_verify_accepts_only_our_valid_tokens(google_keys):
|
||||
assert await google_id.verify(google_keys()) == "1234567890"
|
||||
assert await google_id.verify(google_keys(aud="other.apps.googleusercontent.com")) is None
|
||||
assert await google_id.verify(google_keys(iss="https://evil.example")) is None
|
||||
assert await google_id.verify(google_keys(exp=int(time.time()) - 10)) is None
|
||||
assert await google_id.verify(google_keys()[:-4] + "abcd") is None
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_google_login_creates_once_with_auto_nickname_and_no_real_name(google_keys):
|
||||
async with client() as c:
|
||||
first = (await c.post("/v1/auth/google", json={"credential": google_keys()})).json()
|
||||
assert first["access_token"] and first["me"]["provider"] == 2
|
||||
nick = first["me"]["nickname"]
|
||||
assert "홍길동" not in nick and "@" not in nick
|
||||
again = (await c.post("/v1/auth/google", json={"credential": google_keys()})).json()
|
||||
assert again["me"]["nickname"] == nick and again["me"]["login_id"] == first["me"]["login_id"]
|
||||
other = (await c.post("/v1/auth/google", json={"credential": google_keys(sub="999")})).json()
|
||||
assert other["me"]["login_id"] != first["me"]["login_id"]
|
||||
bad = (await c.post("/v1/auth/google", json={"credential": google_keys(aud="x")})).json()
|
||||
assert bad["result"]["desc"] == "AUTH_FAILED"
|
||||
me = (await c.get("/v1/auth/me", headers={"Authorization": f"Bearer {first['access_token']}"})).json()["me"]
|
||||
assert me["nickname"] == nick
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_config_exposes_client_id_only_when_set(monkeypatch):
|
||||
async with client() as c:
|
||||
monkeypatch.setattr(settings, "google_client_id", "")
|
||||
assert "google_client_id" not in (await c.get("/v1/auth/config")).json()
|
||||
monkeypatch.setattr(settings, "google_client_id", CLIENT_ID)
|
||||
assert (await c.get("/v1/auth/config")).json()["google_client_id"] == CLIENT_ID
|
||||
|
||||
|
||||
def test_auto_nickname_fits_nickname_rule():
|
||||
for _ in range(50):
|
||||
assert auth_service.NICKNAME.match(auth_service.auto_nickname())
|
||||
Reference in new issue
Block a user