Skip to content
Fluffy Clouds and Lines
GitHubGitLabLinkedIn

Using django-allauth for Google Login to any Django App

Python, Cookiecutter3 min read

A recent app I have been working on, I wanted to allow login via Google, but wanted to ensure that only pre-approved users could login using social login - the application is for a closed user group, not designed for the random public. It's essentially access via invite only. I tried django-invitations, but it felt more geared towards non-social login (sorry guys if I am mis-selling what looks like a great library!). Therefore, it was back to customising django-allauth.

If you're using django-cookiecutter for your new projects (and if you're not, you should) you may know that it comes with out of the box user login management, backed up by django-allauth. This package provides you the framework to build your own user management experience.

This tutorial isn't going to cover getting djang-allauth working from scratch - either take a peek at the django-cookiecutter source, or follow the installation from the docs here, we're looking at novel ways to change the django-allauth workflow.


Changing Behaviour

django-allauth allows for the over-riding default behaviour to built custom functionality via the use of adaptors.  Using cookiecutter? a custom adaptor stub has already been created for you under <project name>/users/adapters.py.  If not, go ahead and create an adapters.py file under one of your Django apps in your project - if you have a 'core' or 'settings' app this might be the best place for it. The location doesn't really matter, as you have to specify the location in your Django settings.

1...
2ACCOUNT_ADAPTER = 'myapp.users.adapters.AccountAdapter'
3SOCIALACCOUNT_ADAPTER = 'myapp.users.adapters.SocialAccountAdapter'
4...

settings.py

1from allauth.account.adapter import DefaultAccountAdapter
2from allauth.socialaccount.adapter import DefaultSocialAccountAdapter
3from django.conf import settings
4from django.http import HttpRequest
5
6
7class AccountAdapter(DefaultAccountAdapter):
8
9 def is_open_for_signup(self, request: HttpRequest):
10 return getattr(settings, "ACCOUNT_ALLOW_REGISTRATION", True)
11
12
13class SocialAccountAdapter(DefaultSocialAccountAdapter):
14
15 def is_open_for_signup(self, request: HttpRequest, sociallogin: Any):
16 return getattr(settings, "ACCOUNT_ALLOW_REGISTRATION", True)

adapters.py

All credit for this code snip goes to the django-cookiecutter devs, it's simple and get's the point across. At the moment both Account and Social based logins are open for business, this adaptor has no net effect on operation at the moment.

My requirement is to allow Social login and signup only, so first off, let's disable account based signup.

1...
2class AccountAdapter(DefaultAccountAdapter):
3
4 def is_open_for_signup(self, request: HttpRequest):
5 return getattr(settings, "ACCOUNT_ALLOW_REGISTRATION", False)
6...

adapters.py

If you head over to http://app/accounts/signup/, you should be told that signup is closed. Great. Next to get Social Logon working. To take the example of Google, you need to do the following;

  • ensure you have run ./manage.py migrate to ensure that the required social login tables have been created,
  • ensure you have added 'allauth.socialaccount.providers.google', to your INSTALLED_APPS
  • head over and create your Google OAuth Credentials,
  • Login to your Django Admin and create a new Social Application object of type 'Google'.

If you head to http://app/accounts/login/, Google should be listed as a login provider. Test your Google Login, it should allow you to login with your Google account without any issues. A new user will be  created under Users and Social Account.

We're nearly there, last step is to restrict to only 'pre-approved' users only. Go ahead and delete via Django Admin the Social Account object created just now (leave the User in place). The way we are going to restrict to pre-approved users is to change the SocialAccountAdapter behaviour. We only want only social logins from an email address with a valid User object already created (either manually via Django Admin or another management screen).

1class SocialAccountAdapter(DefaultSocialAccountAdapter):
2
3 def pre_social_login(self, request, sociallogin):
4 try:
5 get_user_model().objects.get(email=sociallogin.user.email)
6 except get_user_model().DoesNotExist:
7 from django.contrib import messages
8 messages.add_message(request, messages.ERROR, 'Social logon from this account not allowed.')
9 raise ImmediateHttpResponse(HttpResponse(status=500))
10 else:
11 user = get_user_model().objects.get(email=sociallogin.user.email)
12 if not sociallogin.is_existing:
13 sociallogin.connect(request, user)
14
15 def is_open_for_signup(self, request, sociallogin):
16 return True

This is our updated Social adapter. is_open_for_signup still returns true as even a pre-authorised User still hits the signup code path on their first login. pre_social_login is invoked when Social Login is completed, but before the conversion to a valid Django session is done. Therefore, this is the point to check for pre-authorisation.

The try block looks for an existing User against the email provided by the social login request. If a user exists, link the social logon and continue, if not, abort the attempt and leave an update in the 'message' queue.

That's it, this should give a basis for pre-approved social login. A few improvements to make this production ready;

  • ensure you force email verification, as some social networks (i.e Facebook) have been flagged as having questionable verification procedures for email addresses. By forcing email verification, it is an extra step of protection,
  • Start to override the default templates to provide logon buttons / logos for each provider you decide to use,
  • make the user experience slicker by suppressing the need for a username.

A suggested config to get you started;

1ACCOUNT_AUTHENTICATION_METHOD = 'email'
2ACCOUNT_EMAIL_REQUIRED = True
3ACCOUNT_EMAIL_VERIFICATION = 'mandatory'
4ACCOUNT_ADAPTER = 'myapp.users.adapters.AccountAdapter'
5SOCIALACCOUNT_ADAPTER = 'myapp.users.adapters.SocialAccountAdapter'
6SOCIALACCOUNT_QUERY_EMAIL = True
7SOCIALACCOUNT_AUTO_SIGNUP = True
8ACCOUNT_USERNAME_REQUIRED = False

That's all for now. As ever comments and questions below!

© 2024 by Fluffy Clouds and Lines. All rights reserved.
Theme by LekoArts