- November 26, 2008
- middleware permissions
- 1 (after 1 ratings)
Wraps specified URL patterns with permission_required decorator. Allows you to quickly require a specific permission for an area of your site based only on a URL pattern.
Assumes a passing knowledge of how Django permissions work and how to use them. See User authentication in Django for more information.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
from django.contrib.auth.decorators import permission_required class RequirePermissionMiddleware(object): """ Middleware component that wraps the permission_check decorator around views for matching URL patterns. To use, add the class to MIDDLEWARE_CLASSES and define RESTRICTED_URLS and RESTRICTED_URLS_EXCEPTIONS in your settings.py. For example: RESTRICTED_URLS = ( (r'/topsecet/(.*)$', 'auth.access_topsecet'), ) RESTRICTED_URLS_EXCEPTIONS = ( r'/topsecet/login(.*)$', r'/topsecet/logout(.*)$', ) RESTRICTED_URLS is where you define URL patterns and their associated required permissions. Each URL pattern must be a valid regex. RESTRICTED_URLS_EXCEPTIONS is, conversely, where you explicitly define any exceptions (like login and logout URLs). """ def __init__(self): self.restricted = tuple([(re.compile(url), url) for url in settings.RESTRICTED_URLS]) self.exceptions = tuple([re.compile(url) for url in settings.RESTRICTED_URLS_EXCEPTIONS]) def process_view(self,request,view_func,view_args,view_kwargs): # An exception match should immediately return None for path in self.exceptions: if path.match(request.path): return None # Requests matching a restricted URL pattern are returned # wrapped with the permission_required decorator for rule in self.restricted: url, required_permission = rule, rule if url.match(request.path): return permission_required(required_permission)(view_func)(request,*view_args,**view_kwargs) # Explicitly return None for all non-matching requests return None
More like this
- AdminPeepingMiddleware by buriy 7 years, 7 months ago
- I18n URLs via Middleware by zerok 7 years, 8 months ago
- Require Login Middleware by mattgrayson 6 years, 5 months ago
- middleware for user_passes_test by gsf0 5 years, 6 months ago
- TLS(SSL) middleware, per URL pattern or whole site by robmadole 4 years, 4 months ago