diff options
author | ArthurHoaro <arthur@hoa.ro> | 2016-12-15 10:13:00 +0100 |
---|---|---|
committer | ArthurHoaro <arthur@hoa.ro> | 2016-12-15 10:36:00 +0100 |
commit | 18e6796726d73d7dc90ecdd16c181493941f5487 (patch) | |
tree | 17159284be5072b505eead31efdc064b6d5a35d0 /application/api/ApiUtils.php | |
parent | 423ab02846286f94276d21e38ca1e296646618bf (diff) | |
download | Shaarli-18e6796726d73d7dc90ecdd16c181493941f5487.tar.gz Shaarli-18e6796726d73d7dc90ecdd16c181493941f5487.tar.zst Shaarli-18e6796726d73d7dc90ecdd16c181493941f5487.zip |
REST API structure using Slim framework
* REST API routes are handle by Slim.
* Every API controller go through ApiMiddleware which handles security.
* First service implemented `/info`, for tests purpose.
Diffstat (limited to 'application/api/ApiUtils.php')
-rw-r--r-- | application/api/ApiUtils.php | 51 |
1 files changed, 51 insertions, 0 deletions
diff --git a/application/api/ApiUtils.php b/application/api/ApiUtils.php new file mode 100644 index 00000000..fbb1e72f --- /dev/null +++ b/application/api/ApiUtils.php | |||
@@ -0,0 +1,51 @@ | |||
1 | <?php | ||
2 | |||
3 | namespace Shaarli\Api; | ||
4 | |||
5 | use Shaarli\Api\Exceptions\ApiAuthorizationException; | ||
6 | |||
7 | /** | ||
8 | * Class ApiUtils | ||
9 | * | ||
10 | * Utility functions for the API. | ||
11 | */ | ||
12 | class ApiUtils | ||
13 | { | ||
14 | /** | ||
15 | * Validates a JWT token authenticity. | ||
16 | * | ||
17 | * @param string $token JWT token extracted from the headers. | ||
18 | * @param string $secret API secret set in the settings. | ||
19 | * | ||
20 | * @throws ApiAuthorizationException the token is not valid. | ||
21 | */ | ||
22 | public static function validateJwtToken($token, $secret) | ||
23 | { | ||
24 | $parts = explode('.', $token); | ||
25 | if (count($parts) != 3 || strlen($parts[0]) == 0 || strlen($parts[1]) == 0) { | ||
26 | throw new ApiAuthorizationException('Malformed JWT token'); | ||
27 | } | ||
28 | |||
29 | $genSign = hash_hmac('sha512', $parts[0] .'.'. $parts[1], $secret); | ||
30 | if ($parts[2] != $genSign) { | ||
31 | throw new ApiAuthorizationException('Invalid JWT signature'); | ||
32 | } | ||
33 | |||
34 | $header = json_decode(base64_decode($parts[0])); | ||
35 | if ($header === null) { | ||
36 | throw new ApiAuthorizationException('Invalid JWT header'); | ||
37 | } | ||
38 | |||
39 | $payload = json_decode(base64_decode($parts[1])); | ||
40 | if ($payload === null) { | ||
41 | throw new ApiAuthorizationException('Invalid JWT payload'); | ||
42 | } | ||
43 | |||
44 | if (empty($payload->iat) | ||
45 | || $payload->iat > time() | ||
46 | || time() - $payload->iat > ApiMiddleware::$TOKEN_DURATION | ||
47 | ) { | ||
48 | throw new ApiAuthorizationException('Invalid JWT issued time'); | ||
49 | } | ||
50 | } | ||
51 | } | ||