Ticket #31288: middleware.py

File middleware.py, 2.1 KB (added by Théo Huchard, 5 years ago)

The middleware code

Line 
1from django.shortcuts import redirect
2from django.urls import resolve
3from django.conf import settings
4
5
6class ReplaceAuthMiddleware:
7 def __init__(self, get_response):
8 self.get_response = get_response
9 self.unauthorized_urls_for_logged_user = settings.REPLACE_URL_IF_LOGGED["replace"]
10 self.unauthorized_urls_for_unlogged_user = settings.REPLACE_URL_IF_UNLOGGED["replace"]
11 self.redirect_url_for_unauthorized_logged_user = settings.REPLACE_URL_IF_LOGGED["by"]
12 self.redirect_url_for_unauthorized_unlogged_user = settings.REPLACE_URL_IF_UNLOGGED["by"]
13
14 def __call__(self, request):
15
16 # Before the response of the view changes, checks if the url is authorized or not.
17 if self.unauthorized_url_for_logged_user(request):
18 return redirect(self.redirect_url_for_unauthorized_logged_user)
19 elif self.unauthorized_url_for_unlogged_user(request):
20 return redirect(self.redirect_url_for_unauthorized_unlogged_user)
21
22 # Get the response of the view.
23 response = self.get_response(request)
24
25 # After the response of the view changes, checks if the url is authorized or not.
26 if self.unauthorized_url_for_logged_user(request):
27 return redirect(self.redirect_url_for_unauthorized_logged_user)
28 elif self.unauthorized_url_for_unlogged_user(request):
29 return redirect(self.redirect_url_for_unauthorized_unlogged_user)
30
31 # Return the default response of the view if no redirection is needed.
32 return response
33
34 @staticmethod
35 def user_is_logged(request):
36 return hasattr(request, 'user') and request.user.is_authenticated
37
38 def unauthorized_url_for_unlogged_user(self, request):
39 return not self.user_is_logged(request) and resolve(
40 request.path_info).url_name in self.unauthorized_urls_for_unlogged_user
41
42 def unauthorized_url_for_logged_user(self, request):
43 return self.user_is_logged(request) and resolve(
44 request.path_info).url_name in self.unauthorized_urls_for_logged_user
Back to Top