44 lines
1.9 KiB
Python
44 lines
1.9 KiB
Python
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"])
|