Search code examples
djangodjango-allauth

django-allauth - Critical login required : Allow users stored in a database only to login


I have implemented login form for username/password method, and that works perfect.

I want user to be also able to login using their social accounts.

I am using django-allauth to map social users to django-users.

Now I want to allow only those social accounts to login, that are mapped to django-users and not everyone.

Is there a way to override callback view? or something else can be done?


Solution

  • Finally After reading the documents thoroughly and doing a lot of trials and errors I got to what I was looking for.

    I had to set following parameters as a part of configuration specified in docs.

    ACCOUNT_EMAIL_REQUIRED (=False)
    The user is required to hand over an e-mail address when signing up.

    and

    SOCIALACCOUNT_QUERY_EMAIL (=ACCOUNT_EMAIL_REQUIRED)
    Request e-mail address from 3rd party account provider? E.g. using OpenID AX, or the Facebook “email” permission.

    I had to set ACCOUNT_EMAIL_REQUIRED = True as it was required to check if that email id is already registerd with us.

    and then finally I overridden pre_social_login like below.

    from allauth.socialaccount.adapter import DefaultSocialAccountAdapter  
    
    class NoNewSocialLogin(DefaultSocialAccountAdapter):
    
        def pre_social_login(self, request, sociallogin):
            try:
                cr_user = auth_user.objects.get(email=sociallogin.user.email)
    
                if cr_user and cr_user.is_active:
                    user_login = login(request, cr_user, 'django.contrib.auth.backends.ModelBackend')
                    raise ImmediateHttpResponse(HttpResponseRedirect(reverse('protect')))
                else:
                    raise  ImmediateHttpResponse(render_to_response("account/authentication_error.html"))
            except ObjectDoesNotExist as e:
                raise ImmediateHttpResponse(render_to_response("socialaccount/authentication_error.html"))
            except Exception as e:
                raise ImmediateHttpResponse(HttpResponseRedirect(reverse('protect')))