diff --git a/middleware/__init__.py b/middleware/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/middleware/login_required_middleware.py b/middleware/login_required_middleware.py new file mode 100644 index 0000000000..4e83e953ae --- /dev/null +++ b/middleware/login_required_middleware.py @@ -0,0 +1,31 @@ +from django.http import HttpResponseRedirect +from django.conf import settings +from re import compile + +EXEMPT_URLS = [compile(settings.LOGIN_URL.lstrip('/'))] +if hasattr(settings, 'LOGIN_EXEMPT_URLS'): + EXEMPT_URLS += [compile(expr) for expr in settings.LOGIN_EXEMPT_URLS] + +class LoginRequiredMiddleware: + """ + Middleware that requires a user to be authenticated to view any page other + than LOGIN_URL. Exemptions to this requirement can optionally be specified + in settings via a list of regular expressions in LOGIN_EXEMPT_URLS (which + you can copy from your urls.py). + + Requires authentication middleware and template context processors to be + loaded. You'll get an error if they aren't. + """ + def process_request(self, request): + #print request['user'] + assert hasattr(request, 'user'), "The Login Required middleware\ + requires authentication middleware to be installed. Edit your\ + MIDDLEWARE_CLASSES setting to insert\ + 'django.contrib.auth.middlware.AuthenticationMiddleware'. If that doesn't\ + work, ensure your TEMPLATE_CONTEXT_PROCESSORS setting includes\ + 'django.core.context_processors.auth'." + if not request.user.is_authenticated(): + path = request.path_info.lstrip('/') + if not any(m.match(path) for m in EXEMPT_URLS): + return HttpResponseRedirect(settings.LOGIN_URL) + diff --git a/settings.py b/settings.py index 05f93a0953..e8c97ae51d 100644 --- a/settings.py +++ b/settings.py @@ -95,6 +95,7 @@ MIDDLEWARE_CLASSES = ( 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', + 'middleware.login_required_middleware.LoginRequiredMiddleware', 'pagination.middleware.PaginationMiddleware', ) @@ -137,8 +138,27 @@ TEMPLATE_CONTEXT_PROCESSORS = ( #--------- Grappelli ---------------- #GRAPPELLI_ADMIN_TITLE = PROJECT_TITLE #--------- Django ------------------- -#LOGIN_URL = '/login/' -#LOGIN_REDIRECT_URL = '/' +LOGIN_URL = '/login/' +LOGIN_REDIRECT_URL = '/' +#-------- LoginRequiredMiddleware ---------- +LOGIN_EXEMPT_URLS = ( + r'^favicon\.ico$', + r'^about\.html$', + r'^legal/', # allow the entire /legal/* subsection + r'^%s-site_media/' % PROJECT_NAME, + + r'^accounts/register/$', + r'^accounts/register/complete/$', + r'^accounts/register/closed/$', + + r'^accounts/activate/complete/', + r'^accounts/activate/(?P\w+)/$', + + r'^password/reset/$', + r'^password/reset/confirm/(?P[0-9A-Za-z]+)-(?P.+)/$', + r'^password/reset/complete/$', + r'^password/reset/done/$', +) #--------- Pagination ------------------ #PAGINATION_DEFAULT_PAGINATION = 10 #--------- Web theme app ---------------