From 512e73b3b63f59eb4462e6741a03488542c4501c Mon Sep 17 00:00:00 2001 From: knst-kotov Date: Thu, 26 Aug 2021 18:16:44 +0300 Subject: [PATCH] oauth via google,facebook,github --- Pipfile | 2 +- auth/oauth.py | 36 ++++++++++++++++++++++++++---------- 2 files changed, 27 insertions(+), 11 deletions(-) diff --git a/Pipfile b/Pipfile index f2c6b603..08debf93 100644 --- a/Pipfile +++ b/Pipfile @@ -13,7 +13,7 @@ passlib = "*" PyJWT = "*" SQLAlchemy = "*" itsdangerous = "*" -httpx = "*" +httpx = "<0.18.2" psycopg2-binary = "*" Authlib = "*" bson = "*" diff --git a/auth/oauth.py b/auth/oauth.py index 987ced3a..3d71be48 100644 --- a/auth/oauth.py +++ b/auth/oauth.py @@ -17,7 +17,7 @@ oauth.register( 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'}, + client_kwargs={'scope': 'public_profile email'}, ) oauth.register( @@ -36,14 +36,30 @@ oauth.register( name='google', client_id=OAUTH_CLIENTS["GOOGLE"]["id"], client_secret=OAUTH_CLIENTS["GOOGLE"]["key"], - 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/', + server_metadata_url="https://accounts.google.com/.well-known/openid-configuration", client_kwargs={'scope': 'openid email profile'} ) +async def google_profile(client, request, token): + profile = await client.parse_id_token(request, token) + profile["id"] = profile["sub"] + return profile + +async def facebook_profile(client, request, token): + profile = await client.get('me?fields=name,id,email', token=token) + return profile.json() + +async def github_profile(client, request, token): + profile = await client.get('user', token=token) + return profile.json() + +profile_callbacks = { + "google" : google_profile, + "facebook" : facebook_profile, + "github" : github_profile +} + + async def oauth_login(request): provider = request.path_params['provider'] request.session['provider'] = provider @@ -55,11 +71,11 @@ async def oauth_authorize(request): provider = request.session['provider'] client = oauth.create_client(provider) token = await client.authorize_access_token(request) - resp = await client.get('user', token=token) - profile = resp.json() - oauth = profile["id"] + get_profile = profile_callbacks[provider] + profile = await get_profile(client, request, token) + user_oauth_info = "%s:%s" % (provider, profile["id"]) user_input = { - "oauth" : oauth, + "oauth" : user_oauth_info, "email" : profile["email"], "username" : profile["name"] }