Jacob Valenta
Jacob Valenta

Reputation: 6769

Re-Authenticate / Confirm credentials of User

I understand how to log a user in/out as well as authenticate within django, but one thing that is mission critical to a new project of mine.

I would like to have the user logged in (which I have), and I would like to then ask the user for their credentials again on certain pages.

I have one method through a EmployeeAuthenticatedMixin that I have made, which checks the POST data for the credentials. The main problem is the Mixin does not redirect, it merely serves up a page. So a user can hit the refresh button and resubmit the form, giving them access again.

Is there any way to ask for the user credentials and allow them access to the next page? Maybe an internal Django thing? Sessions? Messages?

Upvotes: 1

Views: 396

Answers (2)

Jacob Valenta
Jacob Valenta

Reputation: 6769

I wrote a signal that would fire after login:

from django.contrib.auth.signals import user_logged_in

import datetime

def reauthentication(sender, user, request, **kwargs):
    request.session['last_login_time'] = str(datetime.datetime.now())
    request.session.save()

user_logged_in.connect(reauthentication)

Then I wrote middleware to catch views that require reauthentication if the sessions last_login_time is older than 3 minutes.

Upvotes: 1

Dap
Dap

Reputation: 2359

You can log them out forcing them to log back in, using request(logout) pseudo-coded

def confirm_crednetials(request)
     logout(request)
     render 'form'

or First prompt the user with a form if they do not have a cookie, you can check and set the cookie with this built in django method resp.set_cookie(foo, cookie) but after you authenticate the user.

if 'id' in request.COOKIES:
**render page
else:
    authenticate_user(username=foo, password=bar)
    resp.set_cookie(foo, cookie)

Upvotes: 2

Related Questions