Open Journal Systems  3.3.0
ApiTokenDecodingMiddleware.inc.php
1 <?php
2 
16 use \Firebase\JWT\JWT;
17 
20  protected $_handler = null;
21 
27  public function __construct(APIHandler $handler) {
28  $this->_handler = $handler;
29  }
30 
37  protected function _decode($slimRequest) {
38  $secret = Config::getVar('security', 'api_key_secret', '');
39  if ($secret !== '' && !is_null($jwt = $slimRequest->getQueryParam('apiToken'))) {
40  try {
41  $apiToken = JWT::decode($jwt, $secret, array('HS256'));
42  $this->_handler->setApiToken($apiToken);
43  return true;
44  } catch (Exception $e) {
45  // If JWT decoding fails, it throws an
46  // 'UnexpectedValueException'. If JSON decoding fails
47  // (of the JWT payload), it throws a 'DomainException'.
48  if (is_a($e, 'UnexpectedValueException') || is_a($e, 'DomainException')) {
49  $request = $this->_handler->getRequest();
50  $router = $request->getRouter();
51  $result = $router->handleAuthorizationFailure($request, $e->getMessage());
52  switch(1) {
53  case is_string($result): return $result;
54  case is_a($result, 'JSONMessage'): return $result->getString();
55  default:
56  assert(false);
57  return null;
58  }
59  }
60  throw $e;
61  }
62  }
63  // If we do not have a token, it's for the authentication logic
64  // to decide if that's a problem.
65  return true;
66  }
67 
76  public function __invoke($request, $response, $next) {
77  $result = $this->_decode($request);
78  if ($result !== true) {
79  return $result;
80  }
81 
82  $response = $next($request, $response);
83  return $response;
84  }
85 }
86 
87 
ApiTokenDecodingMiddleware\_decode
_decode($slimRequest)
Definition: ApiTokenDecodingMiddleware.inc.php:40
ApiTokenDecodingMiddleware\$_handler
$_handler
Definition: ApiTokenDecodingMiddleware.inc.php:23
Config\getVar
static getVar($section, $key, $default=null)
Definition: Config.inc.php:35
APIHandler
Base request API handler.
Definition: APIHandler.inc.php:22
ApiTokenDecodingMiddleware\__construct
__construct(APIHandler $handler)
Definition: ApiTokenDecodingMiddleware.inc.php:30
ApiTokenDecodingMiddleware
Slim middleware which decodes and validates JSON Web Tokens.
Definition: ApiTokenDecodingMiddleware.inc.php:18
ApiTokenDecodingMiddleware\__invoke
__invoke($request, $response, $next)
Definition: ApiTokenDecodingMiddleware.inc.php:79