Django's contrib auth + allauth's MFA - 2FA Setup

I added a feature called 2FA to my django project using django-allauth[mfa]. I also setuped the social account login process using google.

  • login form is from django.contrib.auth
  • 2FA form is from allauth.mfa

authentication/views.py - my custom django contrib auth view

class CustomLoginView(LoginView):
    form_class = UserLoginForm
    template_name='authentication/login.html'
    redirect_authenticated_user=True
    mfa_enabled = False

    def dispatch(self, request, *args, **kwargs):
        if self.redirect_authenticated_user and self.request.user.is_authenticated:
            if self.mfa_enabled:
                return HttpResponseRedirect(resolve_url('account_login'))
            else:
                redirect_to = self.get_success_url()
                if redirect_to == self.request.path:
                    raise ValueError(
                        "Redirection loop for authenticated user detected. Check that "
                        "your LOGIN_REDIRECT_URL doesn't point to a login page."
                    )
                return HttpResponseRedirect(redirect_to)
        return super().dispatch(request, *args, **kwargs)

    def form_valid(self, form):
        user = form.get_user()
        if self.has_mfa(user):
            self.mfa_enabled = True
            print("2FA enabled")
        else:
            auth_login(self.request, user)
        return super().form_valid(form)

    def has_mfa(self, user):
        return is_mfa_enabled(user) 

and this code is not working at all. After login successed, it redirected to homepage. I want to redirect to 2FA form if user account is 2fa activated.

path('accounts/2fa/authenticate/', views.Custom2FAAuthenticateView.as_view(), name='account_login'),

this is my customized 2FA auth form. It worked with social account like google, it redirect to 2FA form if account is 2FA activated.

this is my 2FA auth customized view file

# 2FA authentication view for social login
class Custom2FAAuthenticateView(Base2FAAuthenticateView):
    template_name = "authentication/mfa/authenticate.html"

I tried many ways. when resolver_url('account_login') is redirected, the broswer was crushed. How to customize and what changes need to fix this. Please someone who experience this help me..

Thanks!!!

Вернуться на верх