Laravel 5.5授权,提供额外的凭证,调用retrieveByCredentials()

时间:2018-01-23 01:27:26

标签: php laravel authorization credentials laravel-5.5

从4.2升级。我试图挂钩5.5的Auth模型,并且(正如许多人所做的那样)需要额外的字段(凭证)。大多数人似乎只是绕过了auth结构。我们宁愿“正确地”做到这一点,并且完全集成在Laravel提供的Auth功能中。

但我不确定如何在登录上下文中调用 retrieveByCredentials($ array)。 (对于api文档,请参阅:https://laravel.com/api/5.5/Illuminate/Auth/EloquentUserProvider.html#method_retrieveByCredentials

那么,你能帮助我使用什么,以及如何调用方法?

-Thanks

对于想要通过覆盖AuthenticateUsers Trait来了解添加凭据的人,请在 LoginController()

首先,添加到文件顶部:

use Illuminate\Foundation\Auth\AuthenticatesUsers; 

然后在课堂内,在顶部添加:

use AuthenticatesUsers;

然后在类的主体中添加这两个函数:

/**
 * Get the needed authorization credentials from the request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return array
 */
protected function credentials(Request $request)
{

    // NOTE: Add fields here to regulate login requirements.
    // ORIGINAL CODE: return $request->only($this->username(), 'password', 'verified');

    // CODE WITH ADDITIONAL FIELDS (you can use any syntax you want to add to the array)
    // Note that the binary '1' values are still in single quotes cover all circumstances.

    return array_merge($request->only($this->username(), 'password'), ['verified' => '1', 'can_login' => '1']);

}


/**
 * Get the failed login response instance.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Symfony\Component\HttpFoundation\Response
 *
 * @throws ValidationException
 */
protected function sendFailedLoginResponse(Request $request)
{
     // MY QUESTION IS: INSTEAD OF CALLING THIS:
     $user = SysUserModel::where('email', '=', $request->email)->firstOrFail(['email','verified','can_login', 'state']);


    //HOW DO I CALL THIS? (And is this correct? Is there a better way to capture the user data without an additional call to the database?)

    $user = retrieveByCredentials( $request->only($this->username(), 'password'));

    // SO THAT I CAN DETERMINE IF 
    // (a) the user-email/pw doesn't exist
    // (b) the user-email/pw exists but 'verified' = 0
    // (c) the user-email/pw exists, 'verified' = 1, but 'can_login' = 0

    // SO THAT I CAN RETURN THE APPROPRIATE ERROR MESSAGE HERE

    throw ValidationException::withMessages([
        $this->username() => [trans('auth.failed')],
    ]);


}

1 个答案:

答案 0 :(得分:2)

在自定义身份验证过程时,您应该实现自定义防护。这样您就需要更改框架代码或广泛覆盖任何内容。如下所示,控制器具有guard属性,可调用attempt。这是你的警卫将处理传入的附加字段的地方。

/**
  * Attempt to log the user into the application.
  *
  * @param  \Illuminate\Http\Request  $request
  * @return bool
  */
 protected function attemptLogin(Request $request)
 {
     return $this->guard()->attempt(
         $this->credentials($request), $request->has('remember')
     );
 }

请参阅此处了解如何实施自定义后卫:

https://laravel.com/docs/5.5/authentication#adding-custom-guards

最后,您在config/auth.php

中设置了新的警卫