An example of using it in your settings.py:
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.middleware.doc.XViewMiddleware',
'util.loginmiddleware.RequireLoginMiddleware',
)
LOGIN_REQUIRED_URLS = (
r'/payment/(.*)$',
r'/accounts/home/(.*)$',
r'/accounts/edit-account/(.*)$',
)
In a nutshell this requires the user to login for any url that matches against whats listing in LOGIN_REQUIRED_URLS. The system will redirect to LOGIN_URL
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | from django.conf import settings
from django.http import HttpResponseRedirect
import re
class RequireLoginMiddleware(object):
def __init__(self):
self.urls = tuple([re.compile(url) for url in settings.LOGIN_REQUIRED_URLS])
self.require_login_path = getattr(settings, 'LOGIN_URL', '/accounts/login/')
def process_request(self, request):
for url in self.urls:
if url.match(request.path) and request.user.is_anonymous():
return HttpResponseRedirect('%s?next=%s' % (self.require_login_path, request.path))
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Why not to use decorators?
#
Not sure I understand how this is better than this?
#
dakrauth hits the nail on the head, but also you may not always have "access" to the views in question. Lets say you include an app, you can either a) modify the views in that app with the decorator, or b) use another method
I'm not a big fan of a because its like tainting code with something rather specific. This middleware is more for site wide login required rather then a few views.
#
Please login first before commenting.