流明中的auth自定义消息

时间:2019-01-11 12:01:42

标签: laravel lumen

我正在尝试设置auth函数。我所有的API调用都需要两个必填的头文件,它们都是api-token,domain,而没有API应该失败。

我想做的是,我检查两件事是否不存在,响应中应明确指出哪一个不存在或提供错误。

例如,如果api令牌丢失或错误,则错误消息应显示为“错误/无效的API”状态。

这是我的代码。

*AuthServiceProvider.php*

 public function boot()
{
    // Here you may define how you wish users to be authenticated for your Lumen
    // application. The callback which receives the incoming request instance
    // should return either a User instance or null. You're free to obtain
    // the User instance via an API token or any other method necessary.

    $this->app['auth']->viaRequest('api', function ($request) {

        //check domain
        $domainDetails = $this->checkDomain($request->header('domain'));
        // if domain check passed
        if($domainDetails[0]){
            // check api details
            $apiCheck = $this->checkAPI($domainDetails[1],$request->header('api_token'));
            // if the api check  passed
            if($apiCheck[0]){

            }
            // if not passed then throw api error
            else{
                return $apiCheck[1];
            }
        }
        // throw domain error
        else{
            return $domainDetails[1];

        }

        if ($this->checkDomain($request->header('domain')) == 6) {
            return User::where('api_token', $request->input('api_token'))->first();
        }


    });
}

Authenticate.php

/*
 * check api key exists and get the user details
 * @params
 * 1. Domain ID
 * 2. API key
 */
public function checkAPI($_domainNameID, $_apiKey){

    if($_domainNameID == null){
        return [false,'Domain Required'];
    }

    if($_apiKey == null){
        return [false,'API Key required'];
    }

    if($_domainNameID !== null && $_apiKey !== null){

        $userDetails = User::where('client_id','=',$_domainNameID)
                ->where('api_token','=',$_apiKey)
                ->selectRaw('id as `user_id`,'.
                         'email as `username`,'.
                         'qa_designation as `User Designation`,'.
                         'access_type as `User Access`')
                ->first();

        if($userDetails != null){

            return [true,$userDetails];

        }else{
            return [false,'API Key doesn"t exists'];
        }

    }

}


/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @param  string|null  $guard
 * @return mixed
 */
public function handle($request, Closure $next, $guard = null)
{
    if ($this->auth->guard($guard)->guest()) {
        **here how can I display a custom message**
        return response('Unauthorized.', 401);
    }

    return $next($request);
}

web.php

$router->group(['prefix' => 'v1'], function () use ($router) {

    $router->get('/auth',['middleware' => 'auth', function () use ($router) {
        return $router->app->version();
    }]);

});

0 个答案:

没有答案