Django ModelBackend.authenticate是如何工作的?

时间:2016-06-21 20:40:18

标签: python django authentication

我正在研究ModelBackend

def authenticate(self, username=None, password=None, **kwargs):
    UserModel = get_user_model()
    if username is None:
        username = kwargs.get(UserModel.USERNAME_FIELD)
    try:
        user = UserModel._default_manager.get_by_natural_key(username)
    except UserModel.DoesNotExist:
        # Run the default password hasher once to reduce the timing
        # difference between an existing and a non-existing user (#20760).
        UserModel().set_password(password)
    else:
        if user.check_password(password) and self.user_can_authenticate(user):
            return user

我很困惑。

  1. 调用authenticate()的位置。
  2. usernamepassword传递给authenticate()的内容是什么?
  3. 有时,代码有效,但我不知道它是如何工作的。

    更新

    我正在阅读一个项目的源代码。我找到了authenticate()的定义,但我找不到它的名字。

    grep -r "authenticate" .
    
    ./src/myproject/views.py:   if request.user.is_authenticated():
    ./src/lib/backend.py:   def authenticate(self, username = None, password = None, **kwargs):
    ./src/lib/middleware.py:        if not request.user.is_authenticated():
    ./src/lib/decorators.py:        if request.user.is_authenticated():
    

1 个答案:

答案 0 :(得分:2)

authenticate()本身并不“有效”。

如果您的项目或应用程序实现了登录表单,那么您或您用于身份验证的应用程序的开发人员将调用authenticate()

例如,如果您的登录表单中包含username& password字段,然后您在authenticate(username, password)方法中调用post()

例如;

if request.method == 'POST':
    # Gather the username and password provided by the user.
    # This information is obtained from the login form.
    username = request.POST['username']
    password = request.POST['password']

    # Use Django's machinery to attempt to see if the username/password
    # combination is valid - a User object is returned if it is.
    user = authenticate(username=username, password=password)
    # If we have a User object, the details are correct.
    # If None (Python's way of representing the absence of a value), no user
    # with matching credentials was found.
    if user:
        # Is the account active? It could have been disabled.
        if user.is_active:
            # If the account is valid and active, we can log the user in.
            # We'll send the user back to the homepage.
            login(request, user)
            return HttpResponseRedirect('/rango/')
        else:
            # An inactive account was used - no logging in!
            return HttpResponse("Your Rango account is disabled.")
    else:
        # Bad login details were provided. So we can't log the user in.
        print "Invalid login details: {0}, {1}".format(username, password)
        return HttpResponse("Invalid login details supplied.")

有关此代码的完整说明,请参阅here,或查看authenticate()上的官方django docs