Django Middleware: object.__new__() takes no parameters - django

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

Related

Django 1.8 request.user is removed

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.

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.

object() takes no parameters in django 1.10

I'm trying to allow CORS in my app, so that my cross-domain javascript client can access my API, I've installed django-cors-headers. And I'm now trying to add the middleware:
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware', # Remove this and it works
'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',
]
However this gives me a TypeError:
TypeError: object() takes no parameters
This worked fine before the django 1.10 update. Any ideas?
If you have custom middleware and you've moved from MIDDLEWARE_CLASSES to MIDDLEWARE, then you need to update your middleware. Details on: this Django documentation page. TL;DR, subclass from MiddlewareMixin instead of object:
from django.utils.deprecation import MiddlewareMixin
class FOOMiddleware(MiddlewareMixin):
pass
This issue says that django-cors-headers is no longer supported, and suggests using django-cors-middleware instead.

Django REST Framework w/ TokenAuthentication issue with CSRF/CORS

I am using TokenAuthentication in Django REST Framework to have a script remotely access my API. The domain running the API is behind a TLS certificate.
I have scoured through MANY sources, and tried many options before coming here to figure out what my problem is. In short, I continue to get the CSRF verification failed. Request aborted. error when I attempt to post.
Here is my view:
# #csrf_exempt
#api_view(['POST'])
#authentication_classes((TokenAuthentication,))
#permission_classes((permissions.IsAuthenticated,))
def create_object(request):
csrf_exempt decorator has done nothing here. So, I have also tried it on my urls.py:
url(r'^create_object/', csrf_exempt(views.create_object),),
I even tried writing a custom decorator, and using this suggestion. Even when I do this, I cannot even seem to get that decorator to execute before getting the failure. Perhaps there is an issue with the ordering of my middleware?
'sslify.middleware.SSLifyMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'corsheaders.middleware.CorsPostCsrfMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.RemoteUserMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
Here are my django cors settings:
CORS_ORIGIN_ALLOW_ALL = False
CORS_ORIGIN_WHITELIST = ('example.com',)
CORS_REPLACE_HTTPS_REFERER = True
As promised, here is the solution that I came up with. Admittedly, this is not perfect. I was not able to figure the underlying problem (why on HTTPS the app was not responding to csrf_exempt, or CORS_REPLACE_HTTPS_REFERER), but came up with this limited solution.
STEP 1
First, I subclassed the entire CsrfViewMiddleware class into my own version, and placed it into my middleware (changes from original quertion marked):
'sslify.middleware.SSLifyMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
#'django.middleware.csrf.CsrfViewMiddleware', ##CHANGE
'myapp.csrf.CsrfViewMiddleware', ##CHANGE
'corsheaders.middleware.CorsPostCsrfMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.RemoteUserMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
At about line 160 of my version of CsrfViewMiddleware, I replaced the existing conditional to this:
acceptable_referers = ['https://%s' % u for u in settings.CORS_ORIGIN_WHITELIST] + ['http://%s' % u for u in settings.CORS_ORIGIN_WHITELIST]
if not same_origin(referer, good_referer) and referer not in acceptable_referers:
This got me past the invalid referer issue, which is fine because I am whitelisting the domains that are okay. It essentially comes to the same result as CORS_REPLACE_HTTPS_REFERER. My version cross-references the referer header with settings.CORS_ORIGIN_WHITELIST, while the CORS_REPLACE_HTTPS_REFERER method temporarily changes the request referer. Neither seems to me a sufficient enough security solution--but that is another conversation.
STEP 2
At this point, I was still getting the csrf cookie not found error. To circumvent this problem, and since csrf_exempt was not respoding (it seemed as if the middleware was executing too early), I added a new piece of middleware:
'sslify.middleware.SSLifyMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'myapp.csrf.CsrfSkipMiddleware' ##ADDED
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
#'django.middleware.csrf.CsrfViewMiddleware', ##REMOVED
'myapp.csrf.CsrfViewMiddleware', ##ADDED
'corsheaders.middleware.CorsPostCsrfMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.RemoteUserMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
This new piece of middleware essentially sets a flag on the request object (_dont_enforce_csrf_checks) that already exists on the stock version of CsrfViewMiddleware and tells the script to ignore the rest of the csrf check. In order to do that, it checks the page path against a list of paths that I have selected to remove from csrf in settings.CSRF_SKIP_URLS.
class CsrfSkipMiddleware(object):
def process_request(self, request):
CSRF_SKIP_URLS = [re.compile(expr) for expr in settings.CSRF_SKIP_URLS]
path = request.path_info.lstrip('/')
if any(m.match(path) for m in CSRF_SKIP_URLS):
setattr(request, '_dont_enforce_csrf_checks', True)
THOUGHTS
Again, not the best implementation. But, for my purposes it works. Thoughts are still welcome.
I see you're using django cors headers.
I was facing a similar issue and specifying:
CORS_REPLACE_HTTPS_REFERER = True in settings.py resolved the problem.

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.