Skip to content

Commit

Permalink
fix(google): get_avatar_url sometimes returns None
Browse files Browse the repository at this point in the history
Update allauth/socialaccount/providers/google/views.py

Co-authored-by: Raymond Penners <[email protected]>
  • Loading branch information
pennersr committed Jan 5, 2024
1 parent 0bb3cec commit 89ebcc5
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
23 changes: 23 additions & 0 deletions allauth/socialaccount/providers/google/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@

CERTS_URL = "https://www.googleapis.com/oauth2/v1/certs"

IDENTITY_URL = "https://www.googleapis.com/oauth2/v2/userinfo"

ACCESS_TOKEN_URL = (
getattr(settings, "SOCIALACCOUNT_PROVIDERS", {})
Expand All @@ -45,12 +46,20 @@
.get("ID_TOKEN_ISSUER", "https://accounts.google.com")
)

FETCH_USERINFO = (
getattr(settings, "SOCIALACCOUNT_PROVIDERS", {})
.get("google", {})
.get("FETCH_USERINFO", False)
)


class GoogleOAuth2Adapter(OAuth2Adapter):
provider_id = GoogleProvider.id
access_token_url = ACCESS_TOKEN_URL
authorize_url = AUTHORIZE_URL
id_token_issuer = ID_TOKEN_ISSUER
identity_url = IDENTITY_URL
fetch_userinfo = FETCH_USERINFO

def complete_login(self, request, app, token, response, **kwargs):
try:
Expand All @@ -73,6 +82,20 @@ def complete_login(self, request, app, token, response, **kwargs):
)
except jwt.PyJWTError as e:
raise OAuth2Error("Invalid id_token") from e

if self.fetch_userinfo and "picture" not in identity_data:
resp = (
get_adapter()
.get_requests_session()
.get(
self.identity_url,
headers={"Authorization": "Bearer {}".format(token)},
)
)
if not resp.ok:
raise OAuth2Error("Request to user info failed")
identity_data["picture"] = resp.json()["picture"]

login = self.get_provider().sociallogin_from_response(request, identity_data)
return login

Expand Down
17 changes: 17 additions & 0 deletions docs/socialaccount/providers/google.rst
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,23 @@ receive a refresh token on first login and on reauthentication requests
without involving the user's browser). When unspecified, Google defaults
to ``online``.

By default, the userinfo endpoint will not be fetched. In most cases,
this will be fine, as most in scope user data is gained via decoding
the JWT. However if users have a private style of avatar_url
then this will not ordinarily be returned in the JWT and
as such, subsequent calls to get_avatar_url will return None.

You can optionally specify the following setting so that the userinfo
endpoint will be used to populate the avatar_url for those users
who have a private style of avatar_url.

.. code-block:: python
SOCIALACCOUNT_PROVIDERS = {
'google': {
'FETCH_USERINFO' : True
}
}
One Tap Sign-In
***************
Expand Down

0 comments on commit 89ebcc5

Please sign in to comment.