Weird-Sheep-Labs / django-azure-auth

A simple Django app for user authentication with Azure Active Directory/Entra ID.
MIT License
17 stars 10 forks source link

PUBLIC_URLS not working with url patterns with arguments (or I can't figure it out how) #9

Closed sebastian-muthwill closed 1 year ago

sebastian-muthwill commented 1 year ago

I have currently the issue that I can't set a view from another module to be publicly available because the url pattern can not be reversed.

Problem: url patterns like path('"/go/<slug:link>"', link-view, name='link-view') can't be resolved since the argument is missing.

My solution: Since I could not find a better way how to overcome this I extended the middleware and added a PUBLIC_PATHS variable to settings. With this setup you can match against the path string and not against the view.

def __call__(self, request):
        public_views = ["azure_auth:login", "azure_auth:logout", "azure_auth:callback"]
        public_views.extend(settings.AZURE_AUTH.get("PUBLIC_URLS", []))
        public_urls = [reverse(view_name) for view_name in public_views]

        public_paths = settings.AZURE_AUTH.get("PUBLIC_PATHS", [])  # added to resolve paths

        if request.path_info in public_urls:
            return self.get_response(request)

        # added to resolve paths
        for path in public_paths:
            if request.path_info.startswith(path):
                return self.get_response(request)

        if AuthHandler(request).get_token_from_cache():
            # If the user is authenticated
            if request.user.is_authenticated:
                return self.get_response(request)
        return redirect("azure_auth:login")

And in settings.py you can than specify the path with

AZURE_AUTH = {
    ...
    "PUBLIC_URLS": [],  # Optional, public views accessible by non-authenticated users
    "PUBLIC_PATHS": ['/go/'],  # Optional, public paths accessible by non-authenticated users
    ...
    }

Maybe someone can come up with a better solution. :-)

regoawt commented 1 year ago

@sebastian-muthwill Apologies for the delay.

What you've added seems simple and effective, thanks. Will add to next release.

sebastian-muthwill commented 1 year ago

I can provide a PR.