mirror of
https://github.com/fastapi-practices/fastapi_best_architecture.git
synced 2025-08-20 16:40:10 +08:00
Add OAuth 2.0 authorization login (#293)
* [WIP] Add OAuth 2.0 authorization login * Add social user relationship table * Update social user relationship table back_populates * Add OAuth 2.0 related interface * Automatically redirect authorization addresses * Update OAuth2 authorization to GitHub * Add implementation code * fix the callback interface return * fix typo * fix the api return * fix imports * Fix logic for creating system users and social tables * Fix user information storage * Add OAuth2 source link * remove unnecessary db refresh * remove the front end docker-compose annotation
This commit is contained in:
35
backend/app/api/v1/auth/github.py
Normal file
35
backend/app/api/v1/auth/github.py
Normal file
@ -0,0 +1,35 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
from fastapi import APIRouter, BackgroundTasks, Depends, Request
|
||||
from fastapi_oauth20 import FastAPIOAuth20, GitHubOAuth20
|
||||
|
||||
from backend.app.common.response.response_schema import ResponseModel, response_base
|
||||
from backend.app.core.conf import settings
|
||||
from backend.app.services.github_service import github_service
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
github_client = GitHubOAuth20(settings.OAUTH2_GITHUB_CLIENT_ID, settings.OAUTH2_GITHUB_CLIENT_SECRET)
|
||||
github_oauth2 = FastAPIOAuth20(github_client, settings.OAUTH2_GITHUB_REDIRECT_URI)
|
||||
|
||||
|
||||
@router.get('/github', summary='获取 Github 授权链接')
|
||||
async def auth_github() -> ResponseModel:
|
||||
auth_url = await github_client.get_authorization_url(redirect_uri=settings.OAUTH2_GITHUB_REDIRECT_URI)
|
||||
return await response_base.success(data=auth_url)
|
||||
|
||||
|
||||
@router.get(
|
||||
'/github/callback',
|
||||
summary='Github 授权重定向',
|
||||
description='Github 授权后,自动重定向到当前地址并获取用户信息,通过用户信息自动创建系统用户',
|
||||
response_model=None,
|
||||
)
|
||||
async def login_github(
|
||||
request: Request, background_tasks: BackgroundTasks, oauth: FastAPIOAuth20 = Depends(github_oauth2)
|
||||
) -> ResponseModel:
|
||||
token, state = oauth
|
||||
access_token = token['access_token']
|
||||
user = await github_client.get_userinfo(access_token)
|
||||
data = await github_service.add_with_login(request, background_tasks, user)
|
||||
return await response_base.success(data=data)
|
Reference in New Issue
Block a user