Last active
August 29, 2015 13:56
-
-
Save jerivas/9335869 to your computer and use it in GitHub Desktop.
[Django] Active User Middleware. Let's you blacklist URLs requiring user auth without decorating every view. Whitelist approach here: https://djangosnippets.org/snippets/2845/
This file contains hidden or 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
from re import compile | |
from django.conf import settings | |
from django.contrib.auth import REDIRECT_FIELD_NAME | |
from django.contrib.auth.views import redirect_to_login | |
if hasattr(settings, "LOGIN_REQUIRED_URLS"): | |
URLS = [compile(expr) for expr in settings.LOGIN_REQUIRED_URLS] | |
class ActiveUserRequiredMiddleware: | |
""" | |
Middleware that requires a user to be active to view any page specified in | |
settings.LOGIN_REQUIRED_URLS. Since these urls are reguralar expressions, | |
you can copy them from your urls.py. | |
Requires authentication middleware and template context processors to be | |
loaded. You'll get an error if they aren't. | |
""" | |
def process_request(self, request): | |
path = request.path_info.lstrip("/") | |
if any(u.match(path) for u in URLS): | |
if not request.user.is_active: | |
next_url = request.get_full_path() | |
return redirect_to_login(next_url, settings.LOGIN_URL, | |
REDIRECT_FIELD_NAME) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In
settings.py