Skip to content

Instantly share code, notes, and snippets.

@LowerDeez
Created April 30, 2017 09:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LowerDeez/8656fed976921dc98802cd99c3514ae8 to your computer and use it in GitHub Desktop.
Save LowerDeez/8656fed976921dc98802cd99c3514ae8 to your computer and use it in GitHub Desktop.
Middleware заменяющий @login_required
# промежуточный класс для перенправления незарегистрированного пользователя на страницу входа
import re
from django.conf import settings
from django.shortcuts import redirect
from django.contrib.auth import logout
from django.urls import reverse
EXEMPT_URLS = [re.compile(settings.LOGIN_URL.lstrip('/'))]
if hasattr(settings, 'LOGIN_EXEMPT_URLS'):
EXEMPT_URLS += [re.compile(url) for url in settings.LOGIN_EXEMPT_URLS]
class LoginRequiredMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
response = self.get_response(request)
return response
def process_view(self, request, view_func, view_args, view_kwargs):
assert hasattr(request, 'user')
path = request.path_info.lstrip('/')
# print(path)
url_is_exempt = any(url.match(path) for url in EXEMPT_URLS)
# print(reverse('logout'))
if path == reverse('account:logout').lstrip('/'):
logout(request)
if request.user.is_authenticated() and url_is_exempt:
return redirect(settings.LOGIN_REDIRECT_URL)
elif request.user.is_authenticated() or url_is_exempt:
return None
else:
return redirect(settings.LOGIN_URL)
MIDDLEWARE = [
...
'tutorial.middleware.LoginRequiredMiddleware',
...
]
LOGIN_EXEMPT_URLS = (
r'^account/login/$',
r'^account/logout/$',
r'^account/register/$',
r'^account/password_reset/$',
r'^account/password_reset/done/$',
r'^account/reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
r'^account/reset/done/$'
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment