Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django two-factor authentication, require 2FA on specific views

I am implementing Django two-factor-auth on my website and I would love to have some views protected by two-FA, and some other not.

In order to do so, I use the decorator @otp_required which works great, but unfortunately asks the users to input their credentials again (to handle user sessions, I use the registration module).

Would you be able to give me a good to way to hack the form in order to just ask the user to input the token (skipping a step of the form, basically) ?

Thanks a lot,

like image 455
justinlevol Avatar asked Jun 29 '26 16:06

justinlevol


1 Answers

For those who care, I found a way to do it that is quite clean.

The trick was to override the LoginView class in the core.py module of the two_factor_authentication module.

In order to do so, go to your views and insert the following code:

class CustomLoginView(LoginView):

    form_list = (
        ('token', AuthenticationTokenForm),
        ('backup', BackupTokenForm),
    )

    def get_user(self):
        self.request.user.backend = 'django.contrib.auth.backends.ModelBackend'
        return self.request.user

Basically, I erase the 'auth' step and override the method get_user() in order to return the current user. The backend must be specified otherwise Django raises an error.

Now, to make that class be used instead of the LoginView, go to your urls and insert the following line BEFORE including the two_factor.urls.

url(r'^account/login/$', tradingviews.CustomLoginView.as_view(), name='login'),

That's it!

like image 79
justinlevol Avatar answered Jul 02 '26 04:07

justinlevol