How can I request an already logged in user to confirm password to enter a specific page in django?

Viewed 319

I'm working on a django application. The application has a dashboard. How can i make it so that everytime the user wants to access the dashboard, he/she has to confirm their identity, with the same password they use to log into the same application?

Thank you

3 Answers

#Verify that the USERNAME and PASSWORD combination exist USING THE AUTHENTICATE METHOD,

Views.py:

from django.contrib.auth.models import User
from django.contrib.auth import authenticate

#IN YOUR CASE get the pwd using forms or something,

instance_password = request.post.get('the_pwd_field')

user = authenticate(request, username= request.user.username, password= instance_password)

if user is not None:
    # REDIRECT TO THE DASHBOARD
else:
    # FAIL CASE SCENARIO

In views.py

from django.contrib.auth.hashers import check_password

form = YourFormForPassword(request.POST or None)
if form.is_valid():
    currentpasswordentered = form.cleaned_data.get("try_password")
    currentpassword = request.user.password

    authenticate_user = check_password(currentpasswordentered, currentpassword)

if authenticate_user:
    # REDIRECT TO THE DASHBOARD
else:
   #Redirect to other page or keep same login page

If you want, user to enter credentials explicitly before accessing the dashboard, then you have to return the "form" that accepts creds from user, when they try to access the dashboard.

def dashboard_login_view(request):
    context = {}
    if request.method == 'POST':
        form = DashboardLoginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('dashboard_login_username').lower()
            password = form.cleaned_data.get('dashboard_login_password')
            authenticated = check_password(password)
            if authenticated:
                return HttpResponseRedirect(reverse('dashboard_view'))
            else:
                messages.error('User is not authenticated.')
                return HttpResponseRedirect(reverse('login'))
    else:
        context['form_one'] = DashboardLoginForm()
 
    return render(request, 'dashboardlogin.html', context)
Related