Using django-allauth for Google Login to any Django App
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.
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...
1from allauth.account.adapter import DefaultAccountAdapter2from allauth.socialaccount.adapter import DefaultSocialAccountAdapter3from django.conf import settings4from django.http import HttpRequest567class AccountAdapter(DefaultAccountAdapter):89 def is_open_for_signup(self, request: HttpRequest):10 return getattr(settings, "ACCOUNT_ALLOW_REGISTRATION", True)111213class SocialAccountAdapter(DefaultSocialAccountAdapter):1415 def is_open_for_signup(self, request: HttpRequest, sociallogin: Any):16 return getattr(settings, "ACCOUNT_ALLOW_REGISTRATION", True)
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):34 def is_open_for_signup(self, request: HttpRequest):5 return getattr(settings, "ACCOUNT_ALLOW_REGISTRATION", False)6...
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 migrateto 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):23 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 messages8 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)1415 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 = True3ACCOUNT_EMAIL_VERIFICATION = 'mandatory'4ACCOUNT_ADAPTER = 'myapp.users.adapters.AccountAdapter'5SOCIALACCOUNT_ADAPTER = 'myapp.users.adapters.SocialAccountAdapter'6SOCIALACCOUNT_QUERY_EMAIL = True7SOCIALACCOUNT_AUTO_SIGNUP = True8ACCOUNT_USERNAME_REQUIRED = False
That's all for now. As ever comments and questions below!