Django 1.8 request.user is removed - django

I am using django 1.8 along with mongoengine and a custom Middleware that is supposed to add a user and a toked to a django request.
These two are passed in the header of the request.
The middleware class is the following :
from models import MongoToken
class TokenAuthenticationMiddleware(object):
def process_request(self, request):
if "HTTP_AUTHORIZATION" not in request.META:
return
tokenkey = get_authorization_header(request).split()[1]
token = MongoToken.objects.get(key=tokenkey)
user = User.objects.get(username=request.META.get("HTTP_USERNAME"))
if token.key == tokenkey and token.user.is_active:
request.user = user
request.token = tokenkey
I also put this in my MIDDLEWARE_CLASSES block of the settings.py files:
MIDDLEWARE_CLASSES = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'myproject.middleware.MongoAuthenticationMiddleware',
'myproject.middleware.TokenAuthenticationMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
And when the considered view is reached, my token is here because thanks to the header params but the user is Null.
Then I am wondering if I did something wrong with this because it does not work.
Thank you for your help.
Alex.

Related

How to implement the SimpleMiddleware?

I am struggling getting MiddleWare to work. I put this in my settings.py:
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'portal.middleware.SimpleMiddleware'
]
and I implemented this class in portal/middleware/MiddleWare.py:
class SimpleMiddleware:
def __init__(self, get_response):
self.get_response = get_response
# One-time configuration and initialization.
def __call__(self, request):
# Code to be executed for each request before
# the view (and later middleware) are called.
response = self.get_response(request)
# Code to be executed for each request/response after
# the view is called.
return response
But when running, I get a TypeError:
TypeError: __init__() takes exactly 2 arguments (1 given)
Since you are writing a new-style middleware, you should use MIDDLEWARE instead of MIDDLEWARE_CLASSES in your settings.
You also need to make sure that your entry in the settings matches the location of the middleware. The entry 'portal.middleware.SimpleMiddleware' suggests a SimpleMiddleware class in portal/middleware.py, which does not match your filename portal/middleware/MiddleWare.py.

#csrf_protect in django services

I'm trying to use #csrf_protect in my services by following Cross Site Request Forgery protection article but it is not working for me.
This is my settings file
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'corsheaders.middleware.CorsMiddleware',
]
and this is how I'm Acquiring the token
var csrftoken = Cookies.get('csrftoken');
And this is how I'm configuring the $http provider with the cookie and header names:
$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
But when I call any service, it returns 403 forbidden error. Any Idea what I'm missing or doing wrong?
Any kind of help will be appreciated.

Django 1.8 XFrameOptionsMiddleware and xframe_options_exempt decorators not working

I have a website I have built in Django 1.8 which must load in a Box.com iframe. However it is not loading in Chrome and I get the x-frame-options SAMEORIGIN error.
But I have added the following middleware classes:
MIDDLEWARE_CLASSES = (
# Default Django middleware.
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
and in my views.py added the xframe_options_exempt decorator like so:
#api_view(['GET'])
#xframe_options_exempt
def category_list(request):
"""
List all categories.
"""
if request.method == 'GET':
categories = Category.objects.order_by('-category_type')
serializer = CategorySerializer(categories, many=True)
return Response(serializer.data)
Plus I have tried adding the following setting with no luck:
X_FRAME_OPTIONS = 'ALLOW-FROM https://app.box.com/'
Can anyone help me discover why this is still not allowing the page to load?
Do I also need to add the decorator function in urls.py like this?
from django.views.decorators.clickjacking import xframe_options_exempt
urlpatterns = patterns('base.views',
url(r'^categories$', xframe_options_exempt(category_list)),
)
Thanks very much for any help.

Is my Django middleware order is correct?

MIDDLEWARE_CLASSES = (
'django.middleware.gzip.GZipMiddleware',
'htmlmin.middleware.HtmlMinifyMiddleware',
'django.middleware.http.ConditionalGetMiddleware',
'johnny.middleware.LocalStoreClearMiddleware',
'johnny.middleware.QueryCacheMiddleware',
'announce.middleware.AnnounceCookieMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.transaction.TransactionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'giaola.middleware.ForceDefaultLanguageMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'mediagenerator.middleware.MediaMiddleware',
'django.contrib.redirects.middleware.RedirectFallbackMiddleware',
'minidetector.Middleware',
# Uncomment the next line for simple clickjacking protection:
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'breadcrumbs.middleware.BreadcrumbsMiddleware',
'achievements.middleware.AutoAchievementChecker',
)
These are all my middleware and I'm not entirely sure they're in the correct order.
I have my doubts about GZip and HTMLmin being at the top with caching following after them but middleware has always been my weakpoint in Django.
"ForceDefaultLanguageMiddleware" is just to enforce the language, like so:
def process_request(self, request):
if request.META.has_key('HTTP_ACCEPT_LANGUAGE'):
del request.META['HTTP_ACCEPT_LANGUAGE']
Any input would be more than appreciated.

Django Middleware: object.__new__() takes no parameters

I am trying to get middleware to work with Django, but I get an error:
object.__new__() takes no parameters
I have added the middleware tuple:
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
My view looks like so:
from middleware import my_mw
#my_mw
def start(request):
do stuff...
return render_to_response('a.html', {})
middleware.py:
class my_mw(object):
def process_request(self, request):
x = 6
return None
I have also tried various other middleware functions that I have copy pasted from examples. I always get the same error. At this point I'd really just like to get any middleware function to work!
I needed to add the middleware function to the middleware tuple:
'my_app.middleware.my_mw',
And then I don't include #my_mw