Django Multiple Authentication Backends Based On Status
django, django-admin, django-authentication, django-models, python-2.7
Solution
Since the authentication backend is used by Django to get the user object, it is not known at the time we're calling the backend wether the user will be marked as staff or not.
Is is still possible to use different backends for staff and non-staff user, by chaining backends as explained in Specifying authentication backends. For example if your settings are:
AUTHENTICATION_BACKEND = (
'myapp.auth.StaffUserBackend',
'django.contrib.auth.backends.ModelBackend',
)
where `myapp.auth.StaffUserBackend` only recognizes staff users, this will happen when an user authenticates:
- The credentials are checked against `StaffUserBackend`.
- If the user is staff and the credentials are correct, `StaffUserBackend` returns the user object and we're done.
- If the user is not staff, credentials are checked against `ModelBackend`.
- If the credentials are valid for a standard user, `ModelBackend` returns the `User` object and the user is authenticated as usual.
- If the credentials are not accepted by any backend, the authentication fails.
Problem
I was wondering how to tell Django which authentication backend to use based on if the user is marked as staff or if they are not. Can this be done?