]>
Commit | Line | Data |
---|---|---|
18e67967 A |
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 | } | |
c3b00963 A |
51 | |
52 | /** | |
53 | * Format a Link for the REST API. | |
54 | * | |
55 | * @param array $link Link data read from the datastore. | |
56 | * @param string $indexUrl Shaarli's index URL (used for relative URL). | |
57 | * | |
58 | * @return array Link data formatted for the REST API. | |
59 | */ | |
60 | public static function formatLink($link, $indexUrl) | |
61 | { | |
62 | $out['id'] = $link['id']; | |
63 | // Not an internal link | |
64 | if ($link['url'][0] != '?') { | |
65 | $out['url'] = $link['url']; | |
66 | } else { | |
67 | $out['url'] = $indexUrl . $link['url']; | |
68 | } | |
69 | $out['shorturl'] = $link['shorturl']; | |
70 | $out['title'] = $link['title']; | |
71 | $out['description'] = $link['description']; | |
72 | $out['tags'] = preg_split('/\s+/', $link['tags'], -1, PREG_SPLIT_NO_EMPTY); | |
73 | $out['private'] = $link['private'] == true; | |
74 | $out['created'] = $link['created']->format(\DateTime::ATOM); | |
75 | if (! empty($link['updated'])) { | |
76 | $out['updated'] = $link['updated']->format(\DateTime::ATOM); | |
77 | } else { | |
78 | $out['updated'] = ''; | |
79 | } | |
80 | return $out; | |
81 | } | |
18e67967 | 82 | } |