Require login by 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

  1. Super User Conditional Page Exception Reporting by zbyte64 4 years, 10 months ago
  2. Another Cookieless Session Middleware by lvscar 4 years ago
  3. RandomFileExtensionMiddleware by jezdez 5 years ago
  4. Simple Age Verification Middleware by eculver 3 years, 10 months ago
  5. Require Login Middleware by mattgrayson 4 years, 6 months ago

Comments

daevaorn (on August 13, 2008):

Why not to use decorators?

#

David (on August 13, 2008):

Not sure I understand how this is better than this?

from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):

#

dakrauth (on August 13, 2008):

In response to the first two commenters, I see this as an alternative to repetitive and possibly error-prone situation where certain "nodes" of the site require blanket authentication. It really just adds specificity to snippet 136

Rather than applying the login_required decorator to each and every view (which could be a significant number), this method affords the opportunity to be a tad DRYier, in my view.

What I would like to see (and it probably exists on this site somewhere if I looked hard enough) is an extension of the include callable that took another decorator / callable to apply to all views. For instance:

urlpatterns = patterns('',
    (r'^payment/', include_ex('payment.urls', login_required)
)

#

zbyte64 (on October 8, 2008):

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.

#

(Forgotten your password?)