Reputation: 930
I implemented a custom authentication setup for my Django project. There are some user roles for users. Now I want to ensure that some specific routs may acceptable only of specific user roles. Let's say the edit/uploaded-files
can be acceptable only for the user with role = 1
. So I created a middleware for that.
from django.shortcuts import redirect
class HRMiddleware(object):
def process_request(self, request):
user = request.user
if not (user and user.is_authenticated() and user.email):
return redirect('')
if user.role_id.id != 1:
raise 403
return None
Now how can i apply this middleware for some specific routes only ?
I found some solutions like using decorator @decorator_from_middleware(MyMiddleware)
and specifying the routes in middle ware. Is there any better way to do this ? Actually I am a Laravel developer. This is my first Django project. In laravel we can specify the middlewares in the routes. Please help me
Upvotes: 2
Views: 1904
Reputation: 146
This is better I think
from django.http import Http404
URLS = ['/dashboard/']
class HRMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
user = request.user
response = self.get_response(request)
if not (user and user.is_authenticated and user.email) and request.path in URLS:
return redirect('')
if user.role_id.id != 1:
raise Http404
return response
Upvotes: 0
Reputation: 287
Try this:
URLS = ['/some_path/']
class HRMiddleware(object):
def process_request(self, request):
user = request.user
if not (user and user.is_authenticated() and user.email) and request.path in URLS:
return redirect('')
if user.role_id.id != 1:
raise 403
return None
Upvotes: 1