is there an easy way to configure the authentication system in Django like amazon does it?
If you are going to login in your amazon-account and the you are going to close your browser, even after two days when you are going on the webpage again, amazon is greeting you with your name. When you are going to shop, you still need to retype your password.
Is it possible to do it this way in Djanogo? Do I have to do something special in the settings.py?
As far as I know, I just can log i开发者_JAVA百科n or out, even when I am going to close the browser, I am logged in again without any asking of my password.
Thanks for help!
Craphunter
See the documentation on sessions, in particular the section titled Browser-length sessions vs. persistent sessions.
They explain precisely how to achieve what you're asking: request.session.set_expiry(...)
.
I think most likely what Amazon does is based on time and not on whether you close the browser or not. So most likely what you should do is store in the session, the last time you saw that user. If you saw them over an hour ago, then automatically log them out (use Middleware for this).
request.session['lastseen'] = datetime.datetime.now()
Now in your middlware just be careful in logging them out, as you still need to store their id
or username
in the session. This is still easy to do, just read here:
http://docs.djangoproject.com/en/dev/topics/auth/#how-to-log-a-user-out
So basically what you want to do is to logout a user, then after doing so, store their id
or simply their username
into the session so you can retrieve it later. Doing a logout will completely clear their session, so you need to make sure to add their id
or username
after performing the logout()
command. Then wherever you want to retrieve that data you just pull it from the session variables.
logout(request.user)
request.session['userid'] = request.user.id
Then you now have three possibilities for a user: AnonymousUser w/out saved id
, AnonymousUser w/ saved id
, or Authenticated User.
This way even if someone isn't logged in, you still can get their id
from the session.
精彩评论