首页 > 解决方案 > Laravel 护照在登录前检查用户是否处于活动状态

问题描述

我使用Guzzle向护照发送邮寄请求,oauth/token代码如下:

public function login (Request $request) {
    $http = new \GuzzleHttp\Client;

    try {
        $response = $http->post(config('services.passport.login_endpoint'), [
            'form_params' => [
                'grant_type' => 'password',
                'client_id' => config('services.passport.client_id'),
                'client_secret' => config('services.passport.client_secret'),
                'username' => $request -> email,
                'password' => $request -> password,
            ],
        ]);
        return $response->getBody();
    } catch (\GuzzleHttp\Exception\BadResponseException $e) {
        if ($e->getCode() === 400)
            return response()->json('Invalid Request. Please enter a username or a password.', $e->getCode());
        else if ($e->getCode() === 401)
            return response()->json('Your credentials are incorrect. Please try again', $e->getCode());
        else if ($e->getCode() === 408)
            return response()->json('User is deactivated. Please try again', $e->getCode());

        return response()->json('Something went wrong on the server.', $e->getCode());
    }
}

我正在尝试做的事情:

我对每个用户都有一个活动字段1 is active and 0 is deactivated

我想在用户登录之前检查是否处于活动状态,并像我在 if 语句中所做的那样发送带有 408 代码和消息的响应。

我试图做的事情:

我试图将其添加到User.php模型中:

public function findForPassport($identifier) {
    return User::orWhere('email', $identifier)->where('active', 1)->first();
 }

它工作正常。

问题是:

1)如果不活动,这将返回 401 的响应,我想返回 408。

2)我不知道这是否是最好的方法。

标签: phplaravelapioauth

解决方案


为什么您使用 guzzle 而不是常规方式登录?如果您只是在测试,请改用邮递员。也许看看这个:https ://laravel.com/docs/5.7/passport#sumption-your-api-with-javascript

但要回答您的问题,您可以修改此自定义 issueToken 方法并在那里添加活动检查。此外,使用此护照客户端 id/secret 中间件“代理”,因为 id/secret 不应该对公众可见。


推荐阅读