4

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?

4

2 回答 2

8

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.
于 2013-04-20T08:30:31.307 回答
0

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.

于 2016-10-19T19:34:03.437 回答