Skip to content

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

Open
@thclark

Description

@thclark

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/login/
registration/login.html
Request Method: | GET
http://localhost:8000/accounts/login/?next=/silk/
TemplateDoesNotExist
registration/login.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)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions