Login

LoginRequiredMiddleware

Author:
aasmpro
Posted:
April 6, 2019
Language:
Python
Version:
2.0
Score:
0 (after 0 ratings)

settings.py

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'utils.LoginRequiredMiddleware',
]

LOGIN_REQUIRED_URLS = [
    r'^panel/(.*)$'
]

this will help any url under panel/ require login.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
# utils.py
from re import compile
from django.conf import settings
from django.shortcuts import redirect, reverse
from django.utils.deprecation import MiddlewareMixin

login_required_urls = [compile(expr) for expr in getattr(settings, 'LOGIN_REQUIRED_URLS', [])]


class LoginRequiredMiddleware(MiddlewareMixin):
    def process_request(self, request):
        if not request.user.is_authenticated:
            path = request.path_info.lstrip('/')
            if any(m.match(path) for m in login_required_urls):
                return redirect('{}?next={}'.format(reverse(settings.LOGIN_URL), request.path))

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks ago

Comments

Please login first before commenting.