Login

LoginRequiredMiddleware

Author:
aasmpro
Posted:
April 6, 2019
Language:
Python
Version:
2.0
Tags:
middleware authentication login_required
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

Comments

Please login first before commenting.