0

I want to perform check and allow access to only specific pattern URLs and exclude few.

Using the following check to match for the allowed URLs

ALLOWED_URL = [
  '/auth/*'
]

and using fnmatch to match the pattern

any(fnmatch(request.path, p) for p in settings.ALLOWED_URL)

This works for the following URL

  • /auth/login/
  • /auth/signup/google/
  • /auth/user-tracking/

But I want to exclude /auth/user-tracking/ from the URL and user should not access it. So I modified the pattern as

MULTI_USER_EXCLUDE_PATH = [
    '/auth/[!user-tracking/*]*'
]

But this is now not working for

  • /auth/signup/google/
Anuj TBE
  • 9,198
  • 27
  • 136
  • 285

1 Answers1

0

You can define a new EXCLUDED_URL list . Then, use the check_url_access function to check if the request path starts with any of the paths in EXCLUDED_URL list. If it does, the function returns False to indicate that access is denied.

import fnmatch

EXCLUDED_URL = [
    '/auth/user-tracking/'
]

ALLOWED_URL = [
  '/auth/*'
]

def check_url_access(request):
    if any(request.path.startswith(p) for p in EXCLUDED_URL):
        return False
    return any(fnmatch.fnmatch(request.path, p) for p in ALLOWED_URL)

# Let's check google, for example:
request = type("Request", (object,), {"path": "/auth/signup/google/"})
if check_url_access(request):
    print("Access allowed")
else:
    print("Access denied")
Access allowed
AboAmmar
  • 5,439
  • 2
  • 13
  • 24