how to define a custom wsgi middleware for django - django

I want to write a custom wsgi middleware, which is called on every incoming request. It checks the url, and if the user is authenticated and allows the request to proceed or rejects it.
What is the best way to add wsgi middleware in django ?

Why do you want to do this as a WSGI middleware, specifically? Django doesn't operate particularly well with those - there was some work a few years ago to try and harmonize Django middleware with WSGI middleware, but it didn't really get anywhere.
Django has its own version of middleware, which is very well documented, and your request could be done in about three lines.

You do not need a wsgi middleware here and can easily use django middleware.
some_app/middleware.py
from django.http import HttpResponseForbidden
class AuthenticateMiddleware(object):
def process_request(self, request):
#do something with request.path
if request.user.is_authenticated():
#can do something or just pass
#but do not return a response from here
else:
#return a response from here so that view doesn't get called
return HttpResponseForbidden()
process_request() of any middleware is called before the view is processed. If you return an instance of HttpResponse from this method then the view will not be called. Since HttpResponseForbidden is a subclass of HttpResponse, so the view will not be called if the user is not authenticated.
You need to add this custom middleware to MIDDLEWARE_CLASSES.
settings.py
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'some_app.middleware.AuthenticationMiddleware',
)

Related

Django csrf token not refreshed after first login

I have hosted a website at http://cognezic-dev.ap-south-1.elasticbeanstalk.com/login/. On closer inspection, the form has the same csrf token across page refreshes and browsers, which I suspect to be the cause of the issue,this works fine on the local django server.Dont know where this is being cached. I have added CSRF Middleware in the settings.py too.
You can use the test credentials as username bismeet and password bis12345 for testing.
I have also tried creating a custom middleware as follows:
from django.middleware.csrf import rotate_token, CsrfViewMiddleware
from django.utils.deprecation import MiddlewareMixin
class CSRFRefresh(CsrfViewMiddleware,MiddlewareMixin):
def process_response(self, request, response):
print("Custom MiddleWare called")
rotate_token(request)
return response
But it still fails.
My settings.py with custom middleware contains:
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'solvesto.middleware.csrf_refresh.CSRFRefresh'
]
If not using the custom middleware,I use:
'django.middleware.csrf.CsrfViewMiddleware'
instead of
'solvesto.middleware.csrf_refresh.CSRFRefresh'
The only last resort I see to make this work is to remove csrf altogether,which is of course,bad for security.
I removed the csrf security,no other solution,works now.

Disable anonymous user cookie with Django

I use django auth for my website, which needs to have the session middleware installed.
Django session middleware always adds a session cookie, even for anonymous users (users that are not authenticated). When they authenticate the cookie is replaced by another one indicating the user is logged-in.
I want to disable the anonymous user cookie for caching purposes (varnish).
Is there a way to disable anonymous user cookies without removing session middleware which is necessary for apps using auth?
Session data is set in the cookie in the process_response of SessionMiddleware. This function doesn't use any setting or request.user, so you do not have any way of knowing inside this method whether the user is a logged in user or an anonymous user. So, you can't disable sending the session cookie to the browser.
However if you want this functionality then you can subclass SessionMiddleware and overide process_response.
from django.contrib.sessions.middleware import SessionMiddleware
from django.conf import settings
class NewSessionMiddleware(SessionMiddleware):
def process_response(self, request, response):
response = super(NewSessionMiddleware, self).process_response(request, response)
#You have access to request.user in this method
if not request.user.is_authenticated():
del response.cookies[settings.SESSION_COOKIE_NAME]
return response
And you can use your NewSessionMiddleware in place of SessionMiddleware.
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'myapp.middleware.NewSessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.middleware.doc.XViewMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
)

You cannot add messages without installing django.contrib.messages.middleware.MessageMiddleware

I am new to Django.
I am trying to run an app and I need to add a new user to admin. The server is running. When I enter the info fir the new user and hit "save" I get the error below. I am using django-trunk.
MessageFailure at /admin/auth/user/add/
You cannot add messages without installing
django.contrib.messages.middleware.MessageMiddleware
Request Method: POST
Request URL: http://localhost:8000/admin/auth/user/add/
Django Version: 1.6.dev20130403090717
Exception Type: MessageFailure
Exception Value: You cannot add messages without installing django.contrib.messages.middleware.MessageMiddleware
Any ideas of what might be happening?
For me the problem was specific to unit testing. It turns out that some middleware won't work in some kinds of unit tests, more info here:
https://code.djangoproject.com/ticket/17971
and here:
Why don't my Django unittests know that MessageMiddleware is installed?
My solution was to just mock out the messages framework for those tests, there may be better solutions (the django test client?)
Check if you have django.contrib.messages in INSTALLED_APPS and django.contrib.messages.middleware.MessageMiddleware in MIDDLEWARE_CLASSES.
If you are running normal django code, you should add
django.contrib.messages.middleware.MessageMiddleware to your middlewares as others have suggested
If you are running a test case and using request factory then as #hwjp answered above, it's a bug (that won't be fixed). The request factory doesn't call the middlewares and developers don't intend to change this behaviour.
There is however a simple solution.
in your test settings file (i.e settings/test.py) add the following line
MESSAGE_STORAGE = 'django.contrib.messages.storage.cookie.CookieStorage'
in your test code you can write code like this
request = RequestFactory().get("/")
# Add support django messaging framework
request._messages = messages.storage.default_storage(request)
and that's it. Passing this request object to any code that uses django messages will work without a problem.
Check if it is
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
instead of
MIDDLEWARE = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
Tuple name should be MIDDLEWARE_CLASSES
MIDDLEWARE_CLASSES depreciated https://docs.djangoproject.com/en/2.1/releases/1.10/#id3
2018 update
In django 2.0+ name in settings was changed.
Right now use MIDDLEWARE instead of MIDDLEWARE_CLASSES name of list in settings!
If the request is needed in tests, it can be mocked as suggested by #Ramast.
I found the solution mentioned in the bug ticket (closed, won't fix) to be helpful.
from django.contrib.messages.storage.fallback import FallbackStorage
from django.test import RequestFactory
def dummy_request():
"""Dummy request for testing purposes with message support."""
request = RequestFactory().get('/')
# Add support django messaging framework
setattr(request, 'session', 'session')
setattr(request, '_messages', FallbackStorage(request))
return request
Probably you put a wrong WSGI_request when usually called request as a parameter to add_message() method
I met the same error.
You have to notice the order of middleware in MIDDLEWARE_CLASSES.
Insert the corresponding middleware in the final.Like this,
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
Note the order arrangement.
If your issue is simulating these middlewares during unit testing, you can spoof this by writing a couple of little helpers:
def add_session_to_request(request: HttpRequest) -> HttpRequest:
"""Adds session support to a RequestFactory generated request."""
middleware = SessionMiddleware(get_response=lambda request: None)
middleware.process_request(request)
request.session.save()
return request
def add_messages_to_request(request: HttpRequest) -> HttpRequest:
"""Adds message/alert support to a RequestFactory generated request."""
request._messages = FallbackStorage(request)
return request
You can then call these in your test function at the point your request needs to have the middleware bound and just pass in the request you're using, which should keep your tests happy. :)
# To suppress the errors raised when triggering .messages through APIRequestFactory(),
# we need to bind both a session and messages storage on the fly
add_session_to_request(replacement_request)
add_messages_to_request(replacement_request)

django post request data caching

hi have a template with a form and many inputs that pass some data trough a POST request to a view, that process them and send the result to another template. in the final template, if i use the browser back button to jump to the first view, i can see again old data. i refresh the page and i insert new data, i submit again but some old data remain when i see the final view. the problem remain even if i restart the debug server. how can i prevent it? it seems that there's some data-caching that i can solve only flushing browser cache. this is the view code: http://dpaste.com/640956/ and the first template code: http://dpaste.com/640960/
any idea?
tnx - luke
Is not django who populate form. Is cache navigator. You should switch off cache navigator. I use a custom middleware to do this:
from django.http import HttpResponse
class NoCacheMiddleware(object):
def process_response(self, request, response):
response['Pragma'] = 'no-cache'
response['Cache-Control'] = 'no-cache must-revalidate proxy-revalidate no-store'
return response
Remember to add middleware on settings.py:
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',
'ghap.utils.middleware.NoCacheMiddleware',
)
Maybe autocomplete="off" in the form tag can help you.
https://developer.mozilla.org/en/How_to_Turn_Off_Form_Autocompletion

Django - Losing Auth Session

I am with some trouble in Django...
After login I am losing auth session for some pages.
If I access "accounts/login/","accounts/logout/",""accounts/register/" the session always will be there, but if I access different page I cant access the user variable.
This is strange because I am using the same "base.html" for all pages and inside has the logic "if user.is_authenticated", how I said this condition is true just when I access pages that have "accounts" in the URL.
in the settings file I enabled theses three middleware:
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
)
Thanks
Just a guess here: are you including RequestContext in your context in the views that you cannot access user?
In other words, if you call generic views the RequestContext is automatically included but if you are using render_to_response() then you need to call it like this:
return render_to_response('template_name',
{ your context dict },
context_instance=RequestContext(request))