Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Template error and solution (using extra middleware) when using silk authentication #739

Open
thclark opened this issue Sep 5, 2024 · 0 comments

Comments

@thclark
Copy link

thclark commented Sep 5, 2024

Problem

I get a template error when using Silk's authentication/authorisation.

With settings:

SILKY_AUTHENTICATION = True 
SILKY_AUTHORISATION = True
SILKY_PERMISSIONS = lambda user: user.is_superuser

The error is:

TemplateDoesNotExist at /accounts/#/
registration/#.html
Request Method: | GET
http://localhost:8000/accounts/#/?next=/silk/
TemplateDoesNotExist
registration/#.html

Solution

Being able to specify either a path, or arguments to django's reverse(), to resolve the correct redirection in the event of an unauthorised user would solve this.

Workaround

I used middleware to redirect users to log into the admin before accessing silk endpoints:

from django.shortcuts import redirect
from django.urls import reverse
from django.utils.http import urlencode


class SilkyStaffMiddleware:
    """
    Middleware to ensure only authenticated staff users can access Silk URLs.
    """
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        if request.path.startswith('/silk/'):
            if not (request.user.is_authenticated and request.user.is_staff):
                login_url = reverse('admin:login')
                query_string = urlencode({'next': request.path})
                return redirect(f"{login_url}?{query_string}")
        return self.get_response(request)
# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant