2017-03-16 63 views
1

算法可行,但一旦密碼已轉換爲散列並保存到數據庫中,它就不會重定向到主頁。相反,它會重定向到登錄頁面,說明登錄憑據不正確。但是如果我嘗試登錄,那沒關係。我究竟做錯了什麼?將md5移植到Laravel中的問題

AuthenticatesUsers.php

protected function attemptLogin(Request $request) 
{ 
    $check = $this->guard()->attempt(
     $this->credentials($request), $request->has('remember') 
    ); 
    if ($check === false) 
    { 
     $user = User::where('username','=',$request->input('username'))->first(); 

     if(isset($user)) { 
      if($user->password == md5($request->input('password'))) { // If their password is still MD5 
       $hashed_password = Hash::make($request['password']); // Convert to new format 
       $user->password = $hashed_password; 
       $user->save(); 

       return $this->guard()->attempt(
        array(
         'username'=>$request->input('username'), 
         'password'=>$hashed_password 
        ), $request->has('remember') 
       ); 

      } else { 
       // Redirect to the login page. 
       return false; 
      } 
     } 
    } 
    return $check; 
} 
+0

所以你想象用戶可以使用'md5 hashed password'登錄? –

+0

是的,因爲我將當前的MD5換成了laravel的哈希。但問題是在那之後。 – EatCodePlaySleep

+0

所以你需要將數據庫中現有的md5密碼轉換爲'laravel hashing'?如果是這樣,試着說'if(password_verify($ request-> input('password'),$ user-> password))'而不是。 –

回答

2

attempt不走哈希密碼,它需要你會從用戶那裏得到的密碼(明文密碼)。用戶不知道密碼的散列版本,並且attempt做了一個需要純文本版本的散列檢查。

如果您已經驗證了用戶及其憑據並擁有代表它們的用戶實例,那麼您也不需要再次調用attempt。只需使用login即可在該點登錄。您不必經過attempt這只是要重新查詢數據庫以獲取用戶,然後檢查您知道的正確的散列,因爲您只需設置它。

在一定程度上,你所擁有的代碼只是重新創建了內部的內容。

此外,您不需要爲用戶自己查詢數據庫。首次調用attempt時,它將保存在從查詢數據庫時發現的「用戶」中。您可以從警衛檢索它,因此您不必再次查詢數據庫,$this->guard()->getLastAttempted()

進行這些更改將消除來自第二個attempt調用的'錯誤憑據'問題,因爲它不會再被調用。這也會將您的查詢從3個選擇和1個更新切換爲1個選擇和1個更新。 (大致)

+0

我明白了,感謝解釋人員,這是我將它保存到數據庫後所做的。 \t \t \t \t'$ request-> session() - > regenerate(); \t \t \t \t $ this-> clearLoginAttempts($ request); \t \t \t \t Auth :: login($ user,true);' – EatCodePlaySleep