How to configure timeout for user in django? - python-2.7

i use this line :
request.session.set_expiry(60)
to logout after one minute of inactivity but it logout after one minute from logging time
what can i use for this,
and thanks

Only requests which cause the session to be altered are considered activity.
Use the SESSION_SAVE_EVERY_REQUEST setting to alter the session every request if you don't mind the overhead. Other wise you can simply call it in every view ( with a decorator ) or add a middleware to do so.

Related

How to force logout when Knox created token has expired?

I developed my Django based webapp with token authentication by following this tutorial of Brad Traversy (https://www.youtube.com/watch?v=0d7cIfiydAc) using Knox for authentication and React/Redux for the frontend. Login/logout works fine (here is Brad's code: https://github.com/bradtraversy/lead_manager_react_django/blob/master/leadmanager/frontend/src/actions/auth.js --> logout using a POST request), besides one issue: When the user stays away from the computer for a long time, the token expires in the meanwhile. So when the user returns he is still in the logged in zone of the website, but as soon as he opens a React component with data loading from the DB a 401 error is thrown in the console ("Failed to load resource: the server responded with a status of 401 (Unauthorized)"). Then the user has to go on "logout" and login again.
This is not optimal, I would prefer that after the user returns, the system realizes the token expiry and logs the user automatically out. I have thought of the following approaches, but I am not sure how to implement it or which one is best:
1) For every API request: if the answer is 401 --> logout (this might also log the user out in case the token has not expired, but if there is some other permission problem) - seems not optimal to me.
2) Instead one could also create a testing route e.g. api/auth/check with a Django view including the typical check
permission_classes = [permissions.IsAuthenticated]
and if 401 returned --> logout. So that would mean for every database request I have another rather unspecific database request before.
3) Check at every API request specifically if the token has expired --> how to do it? In the docs (https://james1345.github.io/django-rest-knox/) I couldn't find a method to check token validity. I see in the database table "knox_authtoken" an expiry date and a huge code in the column "digest", but this is obviously encrypted data and cannot be compared with the token value that one has in the browser under local storage.
I would be glad to receive recommendations on how to best implement this!
This can be done in multiple ways.
I dont see the reason kicking a user out automatically, but if you want to do that you can either:
Create an URL which will be only for checking if the authentication is valid every 5 secs or so
Use web sockets to send a realtime message once the token has expired.
Put the logic in the frontend, for example store how long the token is valid, and run a timeout, after the timeout is finished relocate him to login.
Jazzy's answer - option 3 - brought me on the right way (thank you!), but working with timers on the frontend side, was initially not successful, since starting a timer within a React component would only run as long as this component is visible. I have no component that is visible all the time of the user session. I changed the expiry duration of the token within Django settings from default value of 8 hours to 72 hours and implemented an idle check on the frontend with this package: https://www.npmjs.com/package/react-idle-timer . So as soon as my application is not used for 2 hours I call the logout action (api/auth/logout). With this approach I don't need to care about the expiry time of the token on Django side, since no user will be active throughout 72 hours. As soon as he logs in again, he will receive a new token.
New solution:
I decided to not bother users too often with logging in and found this nice strategy:
we choose to never expire Knox tokens
we set expiry date for Django session to 90 days from last login
if user does not log in for > 90 days, he will make at some point a request to the backend (e.g. data requests), there we include a check if the session data is available
if 'some_session_variable' in request.session:
# whatever logic you need
else:
return HttpResponse("logout")
Since session variable will not be available after the expiry the 'logout' string is returned. On the frontend we check every response for 'logout' string. If it is being returned we initiate the logout process. The idle timer is not used anymore (as it is not so reliable in my experience).

How does one enforce automatic logout due to inactivity in a Django application?

In my Django application, I would like for the user to be automatically logged out after 30 minutes of inactivity, so I used this setting in settings.py:
SESSION_COOKIE_AGE = 1800
However, using this setting logs the user out in 30 minutes regardless of activity. How does one enforce automatic logout due to inactivity in a Django application?
As an update on this topic. Django now has the SESSION_SAVE_EVERY_REQUEST setting which makes it a lot easier.
django-session-security notes the user activity based on server side and javascript events such as mousemove, keypress, etc, etc ... Also, it warns the user before expiring the session, and tries not to expire the session (where there any activity maybe from another browser tab ?).
Just install it and set settings.SESSION_SECURITY_EXPIRE_AFTER=1800. You could also set settings.SESSION_SECURITY_WARN_AFTER=1740.
You could update the session of an user when he accesses your site. For example in a middleware, this force session to be set again.
class ActivateUser(object):
def process_request(self, request):
if request.user.is_authenticated():
request.session.modified = True

Auto logout using sessions in Django (outside views)

I'm trying to build a auto-logout function in a Django application.
Basically, with each request to the site I want to set the current timestamp in the session (if not set), and then checking that value with the current time. If the difference is too great, it should redirect to logout.
Is there a easy way to set the session on each request without adding a function to each of my views?
I know it's possible to use sessions outside views, but then I have to supply the session_key, and I'm not sure where I should get it from, or generate it myself.
I'm not sure what timestamp you are comparing with what here, or why.
The usual way to manage auto-logout is to simply set a short expiry on the session cookie, via the SESSION_COOKIE_AGE setting. If the cookie expires, the user will automatically be redirected to the login page if they try and access a page that requires authentication.

django increase inactivity timeout

If I am logged into my Django site but am inactive for a while it automatically logs me out. Is there a way to stop this all together or at least increase the timeout to say an hour or so?
Try changing session cookies age. There is a setting: http://docs.djangoproject.com/en/dev/topics/http/sessions/#session-cookie-age

How to disable Middleware and Request Context in some views

I am creating a chat like facebook chat... so in views.py of my Chat Application, I need to retrieve only the last messages every 3-4 seconds with ajax poll ( the latency is not a problem for me ).
If I can disable some Middlewares and some Request Context in this view, the response will be faster... no ?
My question is:
Is there a way to disable some Middlewares and some Request Context in some views ?
This is not likely to be feasible. Best to have a second Django project or WSGI app to handle these requests.