|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | +from fastapi import APIRouter, BackgroundTasks, Depends, Request, Response |
| 4 | +from fastapi_limiter.depends import RateLimiter |
| 5 | +from fastapi_oauth20 import FastAPIOAuth20, GoogleOAuth20 |
| 6 | +from starlette.responses import RedirectResponse |
| 7 | + |
| 8 | +from backend.common.enums import UserSocialType |
| 9 | +from backend.common.response.response_schema import ResponseSchemaModel, response_base |
| 10 | +from backend.core.conf import settings |
| 11 | +from backend.plugin.oauth2.service.oauth2_service import oauth2_service |
| 12 | + |
| 13 | +router = APIRouter() |
| 14 | + |
| 15 | +google_client = GoogleOAuth20(settings.OAUTH2_GOOGLE_CLIENT_ID, settings.OAUTH2_GOOGLE_CLIENT_SECRET) |
| 16 | + |
| 17 | + |
| 18 | +@router.get('', summary='获取 google 授权链接') |
| 19 | +async def get_google_oauth2_url(request: Request) -> ResponseSchemaModel[str]: |
| 20 | + auth_url = await google_client.get_authorization_url(redirect_uri=f'{request.url}/callback') |
| 21 | + return response_base.success(data=auth_url) |
| 22 | + |
| 23 | + |
| 24 | +@router.get( |
| 25 | + '/callback', |
| 26 | + summary='google 授权自动重定向', |
| 27 | + description='google 授权后,自动重定向到当前地址并获取用户信息,通过用户信息自动创建系统用户', |
| 28 | + dependencies=[Depends(RateLimiter(times=5, minutes=1))], |
| 29 | +) |
| 30 | +async def google_oauth2_callback( |
| 31 | + request: Request, |
| 32 | + response: Response, |
| 33 | + background_tasks: BackgroundTasks, |
| 34 | + oauth2: FastAPIOAuth20 = Depends(FastAPIOAuth20(google_client, redirect_route_name='google_oauth2_callback')), |
| 35 | +): |
| 36 | + token, _state = oauth2 |
| 37 | + access_token = token['access_token'] |
| 38 | + user = await google_client.get_userinfo(access_token) |
| 39 | + data = await oauth2_service.create_with_login( |
| 40 | + request=request, |
| 41 | + response=response, |
| 42 | + background_tasks=background_tasks, |
| 43 | + user=user, |
| 44 | + social=UserSocialType.google, |
| 45 | + ) |
| 46 | + return RedirectResponse( |
| 47 | + url=f'{settings.OAUTH2_FRONTEND_REDIRECT_URI}?access_token={data.access_token}&session_uuid={data.session_uuid}' |
| 48 | + ) |
0 commit comments