core/auth/oauth.py

69 lines
2.2 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-26 07:05:08 +00:00
from settings import OAUTH_CLIENTS
2021-07-13 09:15:15 +00:00
2021-07-08 14:48:35 +00:00
oauth = OAuth()
oauth.register(
2021-07-09 07:14:16 +00:00
name='facebook',
2021-07-26 07:05:08 +00:00
client_id=OAUTH_CLIENTS["FACEBOOK"]["id"],
client_secret=OAUTH_CLIENTS["FACEBOOK"]["key"],
2021-07-09 07:14:16 +00:00
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',
2021-07-26 07:05:08 +00:00
client_id=OAUTH_CLIENTS["GITHUB"]["id"],
client_secret=OAUTH_CLIENTS["GITHUB"]["key"],
2021-07-09 07:14:16 +00:00
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
)
2021-07-13 09:15:15 +00:00
oauth.register(
name='google',
2021-07-26 07:05:08 +00:00
client_id=OAUTH_CLIENTS["GOOGLE"]["id"],
client_secret=OAUTH_CLIENTS["GOOGLE"]["key"],
2021-07-13 09:15:15 +00:00
access_token_url='https://oauth2.googleapis.com/token',
access_token_params=None,
authorize_url='https://accounts.google.com/o/oauth2/v2/auth',
authorize_params=None,
api_base_url='https://oauth2.googleapis.com/',
client_kwargs={'scope': 'openid email profile'}
)
2021-07-08 14:48:35 +00:00
async def oauth_login(request):
2021-07-13 09:15:15 +00:00
provider = request.path_params['provider']
request.session['provider'] = provider
client = oauth.create_client(provider)
2021-07-09 07:14:16 +00:00
redirect_uri = request.url_for('oauth_authorize')
2021-07-13 09:15:15 +00:00
return await client.authorize_redirect(request, redirect_uri)
2021-07-08 14:48:35 +00:00
async def oauth_authorize(request):
2021-07-13 09:15:15 +00:00
provider = request.session['provider']
client = oauth.create_client(provider)
token = await client.authorize_access_token(request)
resp = await client.get('user', token=token)
2021-07-09 07:14:16 +00:00
profile = resp.json()
2021-08-19 15:33:39 +00:00
oauth = profile["id"]
2021-07-09 07:14:16 +00:00
user_input = {
2021-08-19 15:33:39 +00:00
"oauth" : oauth,
2021-07-09 07:14:16 +00:00
"email" : profile["email"],
"username" : profile["name"]
}
2021-07-14 14:45:31 +00:00
user = Identity.identity_oauth(user_input)
2021-08-25 08:31:51 +00:00
token = await Authorize.authorize(user, device="pc")
2021-07-09 07:14:16 +00:00
return PlainTextResponse(token)