I need to check user authorization in every view of one of my Django apps (I don't use Django's built in auth system) and redirect user to a "login please" page, if authorization has failed.
Code looks like this:
try:
admin_from_session = request.session['admin'];
admin = Administrator.objects.get(login = admin_from_session.login, password = admin_from_session.password, enabled=True);
except KeyError, Administrator.DoesNotExist:
return HttpResponseRedirect('/controlpanel/login')
Question is: how can I run this code at the beginning of every view, without repeating it every time?
If I would write my program on PHP, i would put this code in separate file and write something like this at the beginning of every page that requires authorization:
include("redirect_if_not_logged_in.inc.php");
The solutions I found was:
The task seems trivial, but I can't find a solution. I would be very grateful for any help.
Look at the source code for django.contrib.auth decorators. They do exactly what you want, but for the built-in Django authentication system (see the documentation). It shouldn't be hard to do something similar for your authentication system.
BTW, why don't you use the built-in auth? You can use it with custom authentication backends...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With