2

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

Amal S R
  • 870
  • 7
  • 21

1 Answers1

1

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
yousof
  • 277
  • 5
  • 15
  • I tried this solution already. But the problem is, each time i define a route for HR then I want to specify it in middleware also. Is there any another options ? – Amal S R Nov 03 '21 at 06:19
  • Try to use regular expressions, than you can make complete url-routes and subroutes in the rule with a single entry – Leeuwtje Nov 03 '21 at 08:54