Question

I've set up a RESTful API and a separate client website that makes calls to it.

The client website uses the Resource Owner Password Credentials grant type of oAuth2 to obtain an access token from the API (from https://myapi.com/v1/oauth/token)

Every other call to the API must contain the access token to access data.

Using Slim framework, how can I pick up the access token, query the database for the user belonging to the access token and have that user model available to the route?

I want to do something like this but I'm not exactly sure how...

function validateAccessToken() {
    $access_token = $_GET["access_token"];
    $user = \models\user::where("access_token", "=", $access_token)->first();

    if($user === NULL) {
        throw new exception("Invalid access token");
    }

    return $user
}

$app->get("/v1/emails", validateAccessToken(), function() use ($app) {
    $emails = \models\emails::where("user_id", "=", $user->id)->toArray();
    echo(json_encode($emails));
});
Was it helpful?

Solution

$validateAccessToken= function($app) {
    return function () use ($app) {
       $access_token = $app->request()->get("access_token");
       $user = \models\user::where("access_token", "=", $access_token)->first();

       if($user === NULL) {
           $app->redirect("/errorpage");
       }


    };
};

$app->get("/v1/emails", $validateAccessToken($app), function() use ($app) {
    // here you have to define $user once again
    $access_token = $app->request()->get("access_token");
    $user = \models\user::where("access_token", "=", $access_token)->first();

    $emails = \models\emails::where("user_id", "=", $user->id)->toArray();
    echo(json_encode($emails));
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top