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