Django Allauth Social Login For Pre Approved Users Only

Snippet 1
  

 

from allauth.account.adapter import DefaultAccountAdapter
from allauth.socialaccount.adapter import DefaultSocialAccountAdapter
from django.conf import settings
from django.http import HttpRequest
from django.contrib.auth import get_user_model
from django.http import HttpResponse
from allauth.exceptions import ImmediateHttpResponse


class AccountAdapter(DefaultAccountAdapter):
  def is_open_for_signup(self, request: HttpRequest):
      return getattr(settings, "ACCOUNT_ALLOW_REGISTRATION", False)

class SocialAccountAdapter(DefaultSocialAccountAdapter):

  def pre_social_login(self, request, sociallogin):
      try:
          get_user_model().objects.get(email=sociallogin.user.email)
      except get_user_model().DoesNotExist:
          from django.contrib import messages
          messages.add_message(request, messages.ERROR, 'Social logon from this account not allowed.')
          raise ImmediateHttpResponse(HttpResponse(status=500))
      else:
          user = get_user_model().objects.get(email=sociallogin.user.email)
          if not sociallogin.is_existing:
              sociallogin.connect(request, user)

  def is_open_for_signup(self, request, sociallogin):
      return True
 

# Add following in your settings.py file

 

ACCOUNT_ADAPTER = 'site.custom_allauth_account_adaptor.AccountAdapter'
SOCIALACCOUNT_ADAPTER  = 'site.custom_allauth_account_adaptor.SocialAccountAdapter'