xref: /plugin/oauth/Service/AbstractOAuth2Base.php (revision c82ad624fa9f1d4a669d251578a03706028cf90a)
1a9ed3890SAndreas Gohr<?php
2a9ed3890SAndreas Gohr
3a9ed3890SAndreas Gohrnamespace dokuwiki\plugin\oauth\Service;
4a9ed3890SAndreas Gohr
5a9ed3890SAndreas Gohruse OAuth\Common\Http\Exception\TokenResponseException;
6a9ed3890SAndreas Gohruse OAuth\OAuth2\Service\AbstractService;
7a9ed3890SAndreas Gohruse OAuth\OAuth2\Token\StdOAuth2Token;
8a9ed3890SAndreas Gohr
9a9ed3890SAndreas Gohr/**
10a9ed3890SAndreas Gohr * Implements the parseAccessTokenResponse like most services do it. Can be used as a base
11a9ed3890SAndreas Gohr * for custom services.
12a9ed3890SAndreas Gohr */
13a9ed3890SAndreas Gohrabstract class AbstractOAuth2Base extends AbstractService
14a9ed3890SAndreas Gohr{
15a9ed3890SAndreas Gohr
16a9ed3890SAndreas Gohr    /** @inheritdoc */
17a9ed3890SAndreas Gohr    protected function parseAccessTokenResponse($responseBody)
18a9ed3890SAndreas Gohr    {
19a9ed3890SAndreas Gohr        $data = json_decode($responseBody, true);
20a9ed3890SAndreas Gohr
21a9ed3890SAndreas Gohr        if (null === $data || !is_array($data)) {
22a9ed3890SAndreas Gohr            throw new TokenResponseException('Unable to parse response.');
23a9ed3890SAndreas Gohr        } elseif (isset($data['error'])) {
24a9ed3890SAndreas Gohr            throw new TokenResponseException('Error in retrieving token: "' . $data['error'] . '"');
25a9ed3890SAndreas Gohr        }
26a9ed3890SAndreas Gohr
27a9ed3890SAndreas Gohr        $token = new StdOAuth2Token();
28a9ed3890SAndreas Gohr        $token->setAccessToken($data['access_token']);
29a9ed3890SAndreas Gohr        unset($data['access_token']);
30a9ed3890SAndreas Gohr
31*c82ad624SAndreas Gohr        if (isset($data['expires_in'])) {
32*c82ad624SAndreas Gohr            $token->setLifeTime($data['expires_in']);
33*c82ad624SAndreas Gohr            unset($data['expires_in']);
34a9ed3890SAndreas Gohr        } else {
35a9ed3890SAndreas Gohr            $token->setEndOfLife(StdOAuth2Token::EOL_NEVER_EXPIRES);
36a9ed3890SAndreas Gohr        }
37a9ed3890SAndreas Gohr
38a9ed3890SAndreas Gohr        if (isset($data['refresh_token'])) {
39a9ed3890SAndreas Gohr            $token->setRefreshToken($data['refresh_token']);
40a9ed3890SAndreas Gohr            unset($data['refresh_token']);
41a9ed3890SAndreas Gohr        }
42a9ed3890SAndreas Gohr
43a9ed3890SAndreas Gohr        $token->setExtraParams($data);
44a9ed3890SAndreas Gohr
45a9ed3890SAndreas Gohr        return $token;
46a9ed3890SAndreas Gohr    }
47a9ed3890SAndreas Gohr}
48