Created
January 17, 2014 23:19
-
-
Save gkmngrgn/8483510 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.conf import settings | |
from django.http.request import validate_host | |
from django.middleware.csrf import _sanitize_token, constant_time_compare | |
from tastypie.authorization import ReadOnlyAuthorization | |
from tastypie.authentication import Authentication | |
from urlparse import urlparse | |
class InternalResourceAuthentication(Authentication): | |
def is_authenticated(self, request, **kwargs): | |
# you maybe want to visit api url directly in development process: | |
if not settings.DEBUG: | |
# check request type: | |
if not request.is_ajax(): | |
return False | |
# check referer: | |
if not self.validate_referer(request): | |
return False | |
# check csrf token: | |
csrf_token = _sanitize_token( | |
request.COOKIES.get(settings.CSRF_COOKIE_NAME, '')) | |
request_csrf_token = request.META.get('HTTP_X_CSRFTOKEN', '') | |
if not constant_time_compare(request_csrf_token, csrf_token): | |
return False | |
return super(InternalResourceAuthentication, self).is_authenticated( | |
request, **kwargs) | |
def validate_referer(self, request): | |
referer = request.META.get('HTTP_REFERER') | |
if referer is None: | |
return False | |
parsed_url = urlparse(referer) | |
return validate_host(parsed_url.hostname, settings.ALLOWED_HOSTS) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Satır 12 de:
yazsak?