Custom LoginView in Django 2

Akshay picture Akshay · Dec 19, 2017 · Viewed 7.8k times · Source

I am trying to customise the authentication and view in Django 2 but the problem is that if the user is already authenticated the login form is still shown and it is not redirected to the appropriate URL. To get over this I have done the following:

class CustomLoginView(LoginView):

    form_class = LoginForm
    template_name = 'login.html'

    def get_initial(self):
        if self.request.user.is_authenticated and self.request.user.is_staff and has_2fa(self.request.user):
            return HttpResponseRedirect(reverse('{}'.format(self.request.GET.get('next', 'portal_home'))))
        else:
            return self.initial.copy()

    def form_valid(self, form):

        if self.request.user.is_staff and not has_2fa(self.request.user):
            logger.info('is staff but does not have 2FA, redirecting to Authy account creator')
            auth_login(self.request, form.get_user())
            return redirect('2fa_register')
        auth_login(self.request, form.get_user())

        return HttpResponseRedirect(self.get_success_url())

But the HttpResponseRedirect in get_initial() does not redirect to the /portal/ page. I have also tried redirect('portal_home') but nothing happens or do I need to write a custom dispatch?

Any help would be much appreciated.

Answer

Akshay picture Akshay · Dec 19, 2017

Overriding get() clears the problem see https://docs.djangoproject.com/en/dev/ref/class-based-views/mixins-editing/#django.views.generic.edit.ProcessFormView

class CustomLoginView(LoginView):
    """
    Custom login view.
    """

    form_class = LoginForm
    template_name = 'login.html'

    def get(self, request, *args, **kwargs):
        if self.request.user.is_authenticated and self.request.user.is_staff and has_2fa(self.request):
            return redirect('{}'.format(self.request.GET.get('next', 'portal_home')))

        return super(CustomLoginView, self).get(request, *args, **kwargs)

    def form_valid(self, form):

        if self.request.user.is_staff and not has_2fa(self.request):
            logger.info('is staff but does not have 2FA, redirecting to Authy account creator')
            auth_login(self.request, form.get_user(), backend='django.contrib.auth.backends.ModelBackend')
            return redirect('2fa_register')

        return super(CustomLoginView, self).form_valid(form)