title: PHP Slim Framework REST API - Validating an access token before each route?
body: <p>I've set up a RESTful API and a separate client website that makes calls to it.</p>
  
  <p>The client website uses the Resource Owner Password Credentials grant type of oAuth2 to obtain an access token from the API (from <a href="https://myapi.com/v1/oauth/token" rel="nofollow">https://myapi.com/v1/oauth/token</a>)</p>
  
  <p>Every other call to the API must contain the access token to access data.</p>
  
  <p>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?</p>
  
  <p>I want to do something like this but I'm not exactly sure how...</p>
  
  <pre><code>function validateAccessToken() {
      $access_token = $_GET["access_token"];
      $user = \models\user::where("access_token", "=", $access_token)-&gt;first();
  
      if($user === NULL) {
          throw new exception("Invalid access token");
      }
  
      return $user
  }
  
  $app-&gt;get("/v1/emails", validateAccessToken(), function() use ($app) {
      $emails = \models\emails::where("user_id", "=", $user-&gt;id)-&gt;toArray();
      echo(json_encode($emails));
  });
  </code></pre>