Skip to content

Instantly share code, notes, and snippets.

@yannbriancon
Created June 10, 2019 17:30
Show Gist options
  • Save yannbriancon/1aa2a308d0722a7b1fccd23bbad76f86 to your computer and use it in GitHub Desktop.
Save yannbriancon/1aa2a308d0722a7b1fccd23bbad76f86 to your computer and use it in GitHub Desktop.
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)
@staticmethod
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