5 use Shaarli\Api\Exceptions\ApiAuthorizationException
;
13 * Validates a JWT token authenticity.
15 * @param string $token JWT token extracted from the headers.
16 * @param string $secret API secret set in the settings.
18 * @throws ApiAuthorizationException the token is not valid.
20 public static function validateJwtToken($token, $secret)
22 $parts = explode('.', $token);
23 if (count($parts) != 3 || strlen($parts[0]) == 0 || strlen($parts[1]) == 0) {
24 throw new ApiAuthorizationException('Malformed JWT token');
27 $genSign = Base64Url
::encode(hash_hmac('sha512', $parts[0] .'.'. $parts[1], $secret, true));
28 if ($parts[2] != $genSign) {
29 throw new ApiAuthorizationException('Invalid JWT signature');
32 $header = json_decode(Base64Url
::decode($parts[0]));
33 if ($header === null) {
34 throw new ApiAuthorizationException('Invalid JWT header');
37 $payload = json_decode(Base64Url
::decode($parts[1]));
38 if ($payload === null) {
39 throw new ApiAuthorizationException('Invalid JWT payload');
42 if (empty($payload->iat
)
43 || $payload->iat
> time()
44 || time() - $payload->iat
> ApiMiddleware
::$TOKEN_DURATION
46 throw new ApiAuthorizationException('Invalid JWT issued time');
51 * Format a Link for the REST API.
53 * @param array $link Link data read from the datastore.
54 * @param string $indexUrl Shaarli's index URL (used for relative URL).
56 * @return array Link data formatted for the REST API.
58 public static function formatLink($link, $indexUrl)
60 $out['id'] = $link['id'];
61 // Not an internal link
62 if ($link['url'][0] != '?') {
63 $out['url'] = $link['url'];
65 $out['url'] = $indexUrl . $link['url'];
67 $out['shorturl'] = $link['shorturl'];
68 $out['title'] = $link['title'];
69 $out['description'] = $link['description'];
70 $out['tags'] = preg_split('/\s+/', $link['tags'], -1, PREG_SPLIT_NO_EMPTY
);
71 $out['private'] = $link['private'] == true;
72 $out['created'] = $link['created']->format(\DateTime
::ATOM
);
73 if (! empty($link['updated'])) {
74 $out['updated'] = $link['updated']->format(\DateTime
::ATOM
);