Skip to content

Instantly share code, notes, and snippets.

Created June 10, 2019 17:30
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Django authentication middleware to automatically authenticate the users
from django.contrib import auth
from django.contrib.auth.middleware import MiddlewareMixin
from django.http import HttpResponseForbidden
class AutomaticUserLoginMiddleware(MiddlewareMixin):
def process_view(self, request, view_func, view_args, view_kwargs):
if not AutomaticUserLoginMiddleware._is_user_authenticated(request):
user = auth.authenticate(request)
if user is None:
return HttpResponseForbidden()
request.user = user
auth.login(request, user)
def _is_user_authenticated(request):
user = request.user
return user and user.is_authenticated
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment