Closed site middleware
@login_required is great but it doesn’t close off your site, just a method. I didn’t see anything in the docs for this so I wrote this middleware to close off my site to only authenticated users:
from django.contrib.auth.views import logout_then_login, login
class SiteLogin:
\"\"\"
do some authentication work
hey good lookin' be back to document you latter
\"\"\"
def process_request(self, request):
if request.user.is_anonymous() and request.META['PATH_INFO'] != '/registration/login/'
if not request.user.is_anonymous():
return logout_then_login(request, settings.LOGIN_URL+settings.LOGIN_NEXT)
else:
if request.POST:
return login(request)
The above is simple enough. If you have a question, feel free to inquire further.
For the login, I made things easier for myself. I created “registration/login.html”. The reason for this is that django.contrib.auth.login redirects to the admin’s registration/login.html. BTW, would be nice if you could specify in settings.py . It gets to ugly with all the redirects and what not to pass it around. By creating my own, it will be used instead. Here is what it looks like:
{% extends \"base\" %}
{% block navlinks %}
{% endblock %}
{% block main-column %}
{% if form.error_dict %}
Errors
{% for err in form.error_dict.username %}
username: {{ err }}
{% endfor %}
{% for err in form.error_dict.password %}
password: {{ err }}
{% endfor %}
{% endif %}
{% endblock %}
