I'm trying to use this library to add two factor authentication to my project. I noticed that the module's has its own login view, that you can find right here, see class LoginView(IdempotentSessionWizardView):
.
The problem i'm having with this it's that i already have my own login view to handle an authentication form, so why would i use the module's view? I would just need to add the 2FA part to my own view, instead of using another one, but unfortunately that module is not really clear on this part.
So the problem is: how do i integrate their login view into my own login view? How can i just add the 2fa part to my own one without using another login handler?
Any advice is welcome, here is my already existing login view:
def login_request(request):
if request.method == "POST":
if result['success']:
form = AuthenticationForm(request, data=request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
messages.info(request, f"You are now logged in as {username}")
return redirect("main:homepage")
else:
messages.error(request, "Invalid username or password")
else:
messages.error(request, "Invalid username or password")
Edit: I've been suggested to use their own login view. Yes, it would be easier. But in the future i would like to add more stuff to the login, such as a captcha form or other fields. But that wouldn't be possible, since i would not be using my own view but the module's view. Is that right?
Converting the discussion from the comments here:
In general, you want to use the batteries-provided views provided by Django before rolling your own, and even before rolling your own from the beginning, you'd want to inherit from and extend the Django views such as LoginView.
The same principle applies to (well-architected) external libraries like the linked django-two-factor-auth
.
At first, you'd just use the views included within, probably by directly include()
ing the urls
module.
Then, if you do need to customize something in those views, you'd inherit from that view, e.g.
from two_factor.views import LoginView
class MyLoginView(LoginView):
template_name = 'super_fancy_login_template.html'
form_list = (
('auth', MyAwesomeAuthenticationForm),
# ... the rest from the original here ...
)
and hook it up in your urls
before the library-provided view on the same path:
from django.conf.urls import url
from my_awesome_app.views import MyLoginView
urlpatterns = [
url(
regex=r'^account/login/$',
view=MyLoginView.as_view(),
name='login',
),
include(...),
]
and hey presto, you've replaced a view with your own.
Obviously, the more you replace pieces like this, the less you have any "warranty" (not that open-source software comes with a warranty at all ;) ) that things still work as they should.