简体   繁体   中英

Laravel trigger route after filter

I built a filter which checks some keys and ids sent and then gives the go or no go. The problem is that a filter in Laravel should return a string while I just wnat to return a boolean and let it trigger the intended route.

Filter:

Route::filter('api_checkauth', function($route)
{
  //user"ok"
    $user_id = (int) $route->getParameter('user_id');

    $sig = $route->getParameter('sig');

    $user = User::find($user_id);

    if($user) {
      //user email
      $email = $user->email;
      //user api key
      $api_key = $user->api_key;
      //recreate signature

      $_sig = hash_hmac("sha256", $email . $user_id, $api_key);

      if($_sig === $sig) {
          return Response::json(array("message"=>"Request Ok"),200);
      } else {
          return Response::json(array("message"=>"Request Bad"),400);
      }
    } else {
      return Response::json(array("message"=>"Request not authorized"),401);
    }

});

Routes:

// Route group for API versioning
Route::group(array('prefix' => 'api/v1', 'before' => 'api_checkauth'), function()
{

    Route::get('/pim/{user_id}/{sig}', 'MoreOrLessController@index');
});

So the question is, how can I still trigger the route which i defined in the group? Because what happens now is a that only a message is printed instead of a controller method that should be triggered.

Thanks

In Laravel, if a filter returns a response, that response is considered the response to the request and the route is not executed. So, in order for the route to be executed return a response only if the user is not authorized.

if($user) {

  $email = $user->email;

  $api_key = $user->api_key;

  $_sig = hash_hmac("sha256", $email . $user_id, $api_key);

  if($_sig !== $sig) {

    return Response::json(array("message"=>"Request Bad"),400);
  }

} else {

  return Response::json(array("message"=>"Request not authorized"),401);
}

The answer is that you're returning your 200 HTTP response in the wrong place.

As you noted, you will always get a JSON string response from the filter no matter what happens, due to the structure of your if/else statement.

Instead of returning your 200 response in the filter, handle that in your MoreOrLessController@index action. So, to clarify, *do not return ANYTHING in the filter when you confirm $_sig === $sig*.

That should do it!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM