April 22, 2008

Django snippets to check http_referer

Filed under: deep-linking, dev, django, snippet, tip — michaelangela @ 6:31 pm

Django snippets: Referer-checking view decorators

Here are a couple of Django decorators for limiting access to a view based on the request’s HTTP_REFERER. Both raise a Django PermissionDenied exception if the referer test fails (or a referer simply isn’t provided).

The first, referer_matches_hostname, takes a hostname
(and port, if specified) and matches it against the referer’s. If
multiple arguments are supplied a match against any of the hostnames
will be considered valid.

The second, referer_matches_re, takes a regex pattern (like Django’s urlpattern) and tests if it matches the referer. This is obviously more flexible than referer_matches_hostname providing the ability to match not just the hostname, but any part of the referer url.

Finally there’s an simple example decorator, local_referer_only, that limits a view to the current site by using Django’s django.contrib.sites to look up the current hostname.


Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: