59 lines
1.7 KiB
Python
59 lines
1.7 KiB
Python
import httpx
|
|
from fastapi import APIRouter, Request
|
|
from fastapi.responses import RedirectResponse
|
|
import os
|
|
|
|
router = APIRouter()
|
|
|
|
GOOGLE_CLIENT_ID = os.getenv("GOOGLE_CLIENT_ID")
|
|
GOOGLE_CLIENT_SECRET = os.getenv("GOOGLE_CLIENT_SECRET")
|
|
|
|
REDIRECT_URI = "http://localhost:8000/auth/callback"
|
|
|
|
GOOGLE_AUTH_URL = "https://accounts.google.com/o/oauth2/v2/auth"
|
|
GOOGLE_TOKEN_URL = "https://oauth2.googleapis.com/token"
|
|
GOOGLE_USERINFO_URL = "https://www.googleapis.com/oauth2/v2/userinfo"
|
|
|
|
|
|
@router.get("/login/google")
|
|
def login_google():
|
|
url = (
|
|
f"{GOOGLE_AUTH_URL}"
|
|
f"?client_id={GOOGLE_CLIENT_ID}"
|
|
f"&redirect_uri={REDIRECT_URI}"
|
|
f"&response_type=code"
|
|
f"&scope=openid email profile"
|
|
)
|
|
return RedirectResponse(url)
|
|
|
|
|
|
@router.get("/auth/callback")
|
|
async def auth_callback(code: str):
|
|
async with httpx.AsyncClient() as client:
|
|
# 1. 用 code 换 token
|
|
token_res = await client.post(
|
|
GOOGLE_TOKEN_URL,
|
|
data={
|
|
"code": code,
|
|
"client_id": GOOGLE_CLIENT_ID,
|
|
"client_secret": GOOGLE_CLIENT_SECRET,
|
|
"redirect_uri": REDIRECT_URI,
|
|
"grant_type": "authorization_code",
|
|
},
|
|
)
|
|
token_json = token_res.json()
|
|
access_token = token_json["access_token"]
|
|
|
|
# 2. 获取用户信息
|
|
user_res = await client.get(
|
|
GOOGLE_USERINFO_URL,
|
|
headers={"Authorization": f"Bearer {access_token}"},
|
|
)
|
|
user_info = user_res.json()
|
|
|
|
# 这里你可以写入数据库
|
|
return {
|
|
"email": user_info["email"],
|
|
"name": user_info["name"],
|
|
"picture": user_info["picture"],
|
|
} |