2016-06-21 3 views
1

나는 ModelBackend을 조사 중입니다.Django 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. authenticate()-usernamepassword을 어떻게 통과?

때로는 코드가 작동하지만, 나는 그것이 어떻게 작동하는지 모르겠어요.

내가 하나 개의 프로젝트의 소스 코드를 읽고있다

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 필드 로그인 폼이있는 경우 당신은 당신 post() 방법에 authenticate(username, password)를 호출 할 것입니다.

예 :

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.") 

이 코드에 쓸 또는 authenticate()에 공식 장고 docs을 확인 전체에 대한 here를 참조하십시오. 사용자를 인증 할 때

관련 문제