flightphp / core

An extensible micro-framework for PHP
https://docs.flightphp.com
MIT License
2.6k stars 407 forks source link

Protecting api routes #345

Closed sukhy-ghataore closed 5 months ago

sukhy-ghataore commented 6 years ago

I have blade and eloquent running with flightphp along with JWT

I was wondering whether its possible to protect api routes

I currently have this at the moment. Is there a better way of achieving this >


$app->route('/api/*', function() use($app) {
        $request = $app->request();
        $NonAuthRoutes = [
            [ "route" => '/login', "ctrl" => 'Api\AuthController@postLogin' ],
            [ "route" => '/register', "ctrl" => 'Api\AuthController@postRegister' ],
            [ "route" => '/verify/register/@token', "ctrl" => 'Api\AuthController@verifyRegisterToken', "params" => ["token"] ],
        ];
        foreach($NonAuthRoutes as $route) {
            $first = explode('@', $route['route'])[0];
            $second = str_replace("/api", "", $request->url);
            if( strncmp($first, $second, strlen($first)) === 0 ) {
                $ctrl = explode('@', $route['ctrl']);
                $class = $ctrl[0];
                $method = $ctrl[1];
                $params = isset($route['params']) ? $route['params'] : [];
                $intiClass = new $class($app);
                return call_user_func_array(array($intiClass, $method), $params);
            }
        }
        if( !$app->jwt() ) {
            return $app->json([
                "error"  => true,
                "message"  => "User has not been authenticated, api_key is not present",
                "current_route" => $app->router()->current()
            ], 403);
        }
    })
pierresh commented 3 years ago

I check the JWT just after the autoload.php, before I handle the route. If the JWT is not valid, I reject a 401 error, otherwise, I create a variable (one array) in which I load the user rights for the connected user.

Then, inside each route, I check if the user rights allow the user to access that route. If the user is not allowed, it returns a 403 error, otherwise, the controller is executed.

You can see this concretely in my skeleton. I am not sure if this is the cleanest way but I do like this for several years and it works very well.

n0nag0n commented 5 months ago

So I guess what you're asking is can Flight handle middleware? We're building support for that with #514 Hopefully that gets you where you're hoping for.