2016-06-21 25 views
1

我正在調查ModelBackendDjango ModelBackend.authenticate是如何工作的?

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. 什麼通過usernamepasswordauthenticate()

有時,代碼有效,但我不知道它是如何工作的。

UPDATE

我在看一個項目的源代碼。我找到了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

@DanielRoseman我正在閱讀一個項目的源代碼。我發現了authenticate()的定義,但是我找不到它被調用的地方。 – BAE

+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這個代碼寫出來,或查看官方的Django docsauthenticate()