Code, Django, Uncategorized

Making django-sitetree’s Display Permissions Show Access Denied

I like django-sitetree for what it is. There aren’t any other modules with as many features. One thing that bothers me is the permissions options just hide links. Anyone with a URL can still go to pages they aren’t allowed to. If this is how you are doing security for your site this can be a huge security risk.

Using custom middleware you can use django-sitetree’s own methods to check if you should show a page.

First, if you have multiple sitetrees come up with some logic to decide what sitetree you should look up based off the path.

If have:
alias = 'control_panel' if 'control_panel/action' in request.path else 'main_menu'

This makes it use the ‘control_panel’ sitetree and the ‘main_menu’ sitetree if ‘control_panel/action’ is not in the path.

Next make a middleware class based of whats below. Pay attention to the alias line you made earlier and replace it:

from sitetree.sitetreeapp import SiteTree, get_sitetree

class CheckAccessMiddleware(object): 

def process_request(self, request):
tree = get_sitetree()
context = SiteTree.get_global_context()
context['user'] = request.user
context['request'] = request
------REPLACE THIS------
alias = 'control_panel' if 'control_panel/action' in request.path else 'main_menu'
------REPLACE THIS------
tree.init_tree(alias, context)
page = tree.get_tree_current_item(alias)
if page:
    access = tree.check_access(page, context)
    if not access:
         # This should happen very rarely. A user will not
         # be shown a URL they don't have access to
         from django.core.exceptions import PermissionDenied
         raise PermissionDenied

Add this class to you MIDDLEWARE_CLASSES in That should be it. If a path is not in your sitetree it won’t do anything. So make sure everything sensitive is in the sitetree. Don’t have items in your sitetree without a trailing slash and a trailing slash in your Django will just redirect to the URL with the trailing slash and this will be run on the URL that does not exist in your sitetree.

One other thing of note, when looking through django-sitetree’s code I noticed they put the requests in a global variable and access it though a singleton. It seems to me that doing that is a definite no no as requests could bleed from one user to the other. I’m not well versed enough in how Django splits up requests among processes to know. It just doesn’t feel particularly right.