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?
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?
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:
StaffUserBackend
.StaffUserBackend
returns the user object and we're done.ModelBackend
.ModelBackend
returns the User
object and the user is authenticated as usual.As Django Runs all the backends one after another. What you can do is use the authenticate function in your views.py file.
For example you want check for staff user then
email = form.cleaned_data['email']
try:
name = StaffUser.objects.get(email=email)
except StaffUser.DoesNotExist:
return "Do whatever you want"
user = authenticate(username=form.cleaned_data['email'], password=form.cleaned_data['password'])
In this your autheticaton function will be called only when the user exists.
This is kind of rough idea use it as per your convenience.