Permalink
Browse files

Tentatively working session support. Messy.

  • Loading branch information...
1 parent d68e539 commit 7b689dadbd6869adfe7ad4bb6fde7bbfbf0b16c8 @onyxfish onyxfish committed Aug 7, 2012
Showing with 67 additions and 11 deletions.
  1. +26 −5 client/static/js/views/root.js
  2. +3 −1 config/settings.py
  3. +38 −4 panda/api/utils.py
  4. +0 −1 panda/views.py
@@ -43,6 +43,31 @@ PANDA.views.Root = Backbone.View.extend({
// Setup occasional updates of notifications
this.notifications_refresh_timer_id = window.setInterval(this.refresh_notifications, PANDA.settings.NOTIFICATIONS_INTERVAL);
+ // TODO - abstract into a method
+ $.ajaxSetup({
+ beforeSend: function(xhr, settings) {
+ function getCookie(name) {
+ var cookieValue = null;
+ if (document.cookie && document.cookie != '') {
+ var cookies = document.cookie.split(';');
+ for (var i = 0; i < cookies.length; i++) {
+ var cookie = jQuery.trim(cookies[i]);
+ // Does this cookie string begin with the name we want?
+ if (cookie.substring(0, name.length + 1) == (name + '=')) {
+ cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
+ break;
+ }
+ }
+ }
+ return cookieValue;
+ }
+ if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
+ // Only send the token to relative URLs i.e. locally.
+ xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
+ }
+ }
+ });
+
return this;
},
@@ -76,14 +101,12 @@ PANDA.views.Root = Backbone.View.extend({
var id = $.cookie("id");
var email = $.cookie("email");
- var api_key = $.cookie("api_key");
var is_staff = $.cookie("is_staff") === "true" ? true : false;
- if (email && api_key) {
+ if (email) {
this.set_current_user(new PANDA.models.User({
"id": id,
"email": email,
- "api_key": api_key,
"is_staff": is_staff
}));
@@ -114,12 +137,10 @@ PANDA.views.Root = Backbone.View.extend({
if (this._current_user) {
$.cookie("id", this._current_user.get("id"), { expires: 30 });
$.cookie("email", this._current_user.get("email"), { expires: 30 });
- $.cookie("api_key", this._current_user.get("api_key"), { expires: 30 });
$.cookie("is_staff", this._current_user.get("is_staff").toString(), { expires: 30 });
} else {
$.cookie("id", null);
$.cookie("email", null);
- $.cookie("api_key", null);
$.cookie("is_staff", null);
$.cookie("activity_recorded", null)
}
View
@@ -76,11 +76,13 @@
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.media',
'django.contrib.auth.context_processors.auth',
- 'django.contrib.messages.context_processors.messages'
+ 'django.contrib.messages.context_processors.messages',
+ 'django.core.context_processors.csrf'
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
+ 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware'
View
@@ -2,8 +2,11 @@
from urllib import unquote
+from django.conf import settings
from django.conf.urls.defaults import url
from django.http import HttpResponse
+from django.middleware.csrf import _sanitize_token, constant_time_compare
+from django.utils.http import same_origin
from tastypie.authentication import ApiKeyAuthentication
from tastypie.bundle import Bundle
from tastypie.fields import ApiField, CharField
@@ -111,6 +114,29 @@ class PandaApiKeyAuthentication(ApiKeyAuthentication):
Custom API Auth that accepts parameters as cookies or headers as well as GET params.
"""
def is_authenticated(self, request, **kwargs):
+ # Session handling shamelessly cribbed from a newer version of Tastypie
+ csrf_token = _sanitize_token(request.COOKIES.get(settings.CSRF_COOKIE_NAME, ''))
+
+ if request.is_secure():
+ referer = request.META.get('HTTP_REFERER')
+
+ if referer is None:
+ return False
+
+ good_referer = 'https://%s/' % request.get_host()
+
+ if not same_origin(referer, good_referer):
+ return False
+
+ request_csrf_token = request.META.get('HTTP_X_CSRFTOKEN', '')
+
+ if not constant_time_compare(request_csrf_token, csrf_token):
+ return False
+
+ if request.user.is_authenticated():
+ return request.user.is_authenticated()
+
+ # Now check for API credentials in the request
email = request.COOKIES.get('email') or request.META.get('HTTP_PANDA_EMAIL') or request.GET.get('email')
api_key = request.COOKIES.get('api_key') or request.META.get('HTTP_PANDA_API_KEY') or request.GET.get('api_key')
@@ -125,12 +151,20 @@ def is_authenticated(self, request, **kwargs):
except (UserProxy.DoesNotExist, UserProxy.MultipleObjectsReturned):
return self._unauthorized()
- if not user.is_active:
- return self._unauthorized()
+ if user.is_active:
+ request.user = user
+
+ return self.get_key(user, api_key)
- request.user = user
+ return self._unauthorized()
- return self.get_key(user, api_key)
+ def get_identifier(self, request):
+ """
+ Provides a unique string identifier for the requestor.
+
+ This implementation returns the user's username.
+ """
+ return request.user.username
class PandaSerializer(Serializer):
"""
View
@@ -66,7 +66,6 @@ def make_user_login_response(user):
return {
'id': user.id,
'email': user.email,
- 'api_key': user.api_key.key,
'is_staff': user.is_staff,
'show_login_help': user.get_profile().show_login_help,
'notifications': notifications

0 comments on commit 7b689da

Please sign in to comment.