core/auth/oauth.py

52 lines
1.6 KiB
Python
Raw Normal View History

2021-07-08 14:48:35 +00:00
from authlib.integrations.starlette_client import OAuth
from starlette.responses import PlainTextResponse
2021-07-09 07:14:16 +00:00
from auth.authorize import Authorize
from auth.identity import Identity
2021-07-08 14:48:35 +00:00
oauth = OAuth()
oauth.register(
2021-07-09 07:14:16 +00:00
name='facebook',
client_id='222122999761250',
client_secret='',
access_token_url='https://graph.facebook.com/v11.0/oauth/access_token',
access_token_params=None,
authorize_url='https://www.facebook.com/v11.0/dialog/oauth',
authorize_params=None,
api_base_url='https://graph.facebook.com/',
client_kwargs={'scope': 'user:email'},
)
oauth.register(
name='github',
client_id='58877ba7ad9baef280b4',
client_secret='',
access_token_url='https://github.com/login/oauth/access_token',
access_token_params=None,
authorize_url='https://github.com/login/oauth/authorize',
authorize_params=None,
api_base_url='https://api.github.com/',
client_kwargs={'scope': 'user:email'},
2021-07-08 14:48:35 +00:00
)
async def oauth_login(request):
2021-07-09 07:14:16 +00:00
github = oauth.create_client('github')
redirect_uri = request.url_for('oauth_authorize')
return await github.authorize_redirect(request, redirect_uri)
2021-07-08 14:48:35 +00:00
async def oauth_authorize(request):
2021-07-09 07:14:16 +00:00
github = oauth.create_client('github')
token = await github.authorize_access_token(request)
resp = await github.get('user', token=token)
profile = resp.json()
oauth_id = profile["id"]
user_input = {
"oauth_id" : oauth_id,
"email" : profile["email"],
"username" : profile["name"]
}
user = Identity.identity_oauth(oauth_id=oauth_id, input=user_input)
token = await Authorize.authorize(user, device="pc", auto_delete=False)
return PlainTextResponse(token)