Created
April 3, 2017 13:31
-
-
Save dedayoa/af981caa8c2be98881390db4f401201b to your computer and use it in GitHub Desktop.
Django middleware to automatically log user out after X minutes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import arrow #you can use datetime here | |
from django.contrib import auth | |
from django.utils import timezone | |
from django.conf import settings # where I have set FORCE_LOGOUT_IN to 5 | |
class AutoForceLogoutMiddleware(object): | |
SESSION_KEY = 'auto-force-logout' | |
def __init__(self, get_response=None): | |
self.get_response = get_response | |
def callback(sender, user=None, request=None, **kwargs): | |
if request: | |
request.session[self.SESSION_KEY] = arrow.utcnow().replace(minutes=settings.FORCE_LOGOUT_IN).timestamp | |
auth.signals.user_logged_in.connect(callback, weak=False) | |
def __call__(self, request): | |
response = self.get_response(request) | |
return response | |
def process_view(self, request, *args, **kwargs): | |
try: | |
if not request.user.is_authenticated(): | |
return | |
except AttributeError: | |
return | |
try: | |
logout_time = arrow.get(request.session[self.SESSION_KEY]).datetime | |
except KeyError: | |
# May not have logged in since we started populating this key. | |
return | |
if timezone.now() < logout_time: | |
request.session[self.SESSION_KEY] = arrow.utcnow().replace(minutes=settings.FORCE_LOGOUT_IN).timestamp | |
return | |
auth.logout(request) | |
## Note ## | |
# Because this hits the DB for every request, you should be using some form of session caching # |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment