Passed
Branch master (b73fcd)
by Thomas
02:06
created

ZohoOAuthClient::refreshAccessToken()   A

Complexity

Conditions 4
Paths 13

Size

Total Lines 24
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 18
c 1
b 0
f 0
dl 0
loc 24
rs 9.6666
cc 4
nc 13
nop 2
1
<?php
2
namespace Zoho\OAuth;
3
4
5
use Zoho\OAuth\Exception\ZohoOAuthException;
6
use Zoho\OAuth\Utility\Logger;
7
use Zoho\OAuth\Utility\ZohoOAuthConstants;
8
use Zoho\OAuth\Utility\ZohoOAuthHTTPConnector;
9
use Zoho\OAuth\Utility\ZohoOAuthTokens;
10
11
class ZohoOAuthClient
12
{
13
14
    private static $zohoOAuthClient;
15
    private $zohoOAuthParams;
16
17
    private function __construct($params)
18
    {
19
        $this->zohoOAuthParams = $params;
20
    }
21
22
    public static function getInstance($params)
23
    {
24
        self::$zohoOAuthClient = new ZohoOAuthClient($params);
25
26
        return self::$zohoOAuthClient;
27
    }
28
29
    public static function getInstanceWithOutParam()
30
    {
31
        return self::$zohoOAuthClient;
32
    }
33
34
    public function getAccessToken($userEmailId)
35
    {
36
        $persistence = ZohoOAuth::getPersistenceHandlerInstance();
37
        try {
38
            $tokens = $persistence->getOAuthTokens($userEmailId);
39
        } catch (ZohoOAuthException $ex) {
40
            Logger::severe("Exception while retrieving tokens from persistence - " . $ex);
41
            throw $ex;
42
        }
43
        try {
44
            return $tokens->getAccessToken();
45
        } catch (ZohoOAuthException $ex) {
46
            Logger::info("Access Token has expired. Hence refreshing.");
47
            $tokens = self::refreshAccessToken($tokens->getRefreshToken(), $userEmailId);
48
49
            return $tokens->getAccessToken();
50
        }
51
    }
52
53
    public function refreshAccessToken($refreshToken, $userEmailId)
54
    {
55
56
        if ($refreshToken == null) {
57
            throw new ZohoOAuthException("Refresh token is not provided.");
58
        }
59
        try {
60
            $conn = self::getZohoConnector(ZohoOAuth::getRefreshTokenURL());
61
            $conn->addParam(ZohoOAuthConstants::GRANT_TYPE, ZohoOAuthConstants::GRANT_TYPE_REFRESH);
62
            $conn->addParam(ZohoOAuthConstants::REFRESH_TOKEN, $refreshToken);
63
            $response = $conn->post();
64
            $responseJSON = self::processResponse($response);
65
            if (array_key_exists(ZohoOAuthConstants::ACCESS_TOKEN, $responseJSON)) {
66
                $tokens = self::getTokensFromJSON($responseJSON);
67
                $tokens->setRefreshToken($refreshToken);
68
                $tokens->setUserEmailId($userEmailId);
69
                ZohoOAuth::getPersistenceHandlerInstance()->saveOAuthData($tokens);
70
71
                return $tokens;
72
            } else {
73
                throw new ZohoOAuthException("Exception while fetching access token from refresh token - " . $response);
74
            }
75
        } catch (ZohoOAuthException $ex) {
76
            throw new ZohoOAuthException($ex);
77
        }
78
    }
79
80
    private function getZohoConnector($url)
81
    {
82
        $zohoHttpCon = new ZohoOAuthHTTPConnector();
83
        $zohoHttpCon->setUrl($url);
84
        $zohoHttpCon->addParam(ZohoOAuthConstants::CLIENT_ID, $this->zohoOAuthParams->getClientId());
85
        $zohoHttpCon->addParam(ZohoOAuthConstants::CLIENT_SECRET, $this->zohoOAuthParams->getClientSecret());
86
        $zohoHttpCon->addParam(ZohoOAuthConstants::REDIRECT_URL, $this->zohoOAuthParams->getRedirectURL());
87
88
        return $zohoHttpCon;
89
    }
90
91
    public function processResponse($apiResponse)
92
    {
93
        [$headers, $content] = explode("\r\n\r\n", $apiResponse, 2);
94
        $jsonResponse = json_decode($content, true);
95
96
        return $jsonResponse;
97
    }
98
99
    private function getTokensFromJSON($responseObj)
100
    {
101
        $oAuthTokens = new ZohoOAuthTokens();
102
        $expiresIn = $responseObj[ZohoOAuthConstants::EXPIRES_IN];
103
        if (!array_key_exists(ZohoOAuthConstants::EXPIRES_IN_SEC, $responseObj)) {
104
            $expiresIn = $expiresIn * 1000;
105
        }
106
        $oAuthTokens->setExpiryTime($oAuthTokens->getCurrentTimeInMillis() + $expiresIn);
107
        $accessToken = $responseObj[ZohoOAuthConstants::ACCESS_TOKEN];
108
        $oAuthTokens->setAccessToken($accessToken);
109
        if (array_key_exists(ZohoOAuthConstants::REFRESH_TOKEN, $responseObj)) {
110
            $refreshToken = $responseObj[ZohoOAuthConstants::REFRESH_TOKEN];
111
            $oAuthTokens->setRefreshToken($refreshToken);
112
        }
113
114
        return $oAuthTokens;
115
    }
116
117
    public function generateAccessToken($grantToken)
118
    {
119
        if ($grantToken == null) {
120
            throw new ZohoOAuthException("Grant Token is not provided.");
121
        }
122
        try {
123
            $conn = self::getZohoConnector(ZohoOAuth::getTokenURL());
124
            $conn->addParam(ZohoOAuthConstants::GRANT_TYPE, ZohoOAuthConstants::GRANT_TYPE_AUTH_CODE);
125
            $conn->addParam(ZohoOAuthConstants::CODE, $grantToken);
126
            $resp = $conn->post();
127
            $responseJSON = self::processResponse($resp);
128
            if (array_key_exists(ZohoOAuthConstants::ACCESS_TOKEN, $responseJSON)) {
129
                $tokens = self::getTokensFromJSON($responseJSON);
130
                $tokens->setUserEmailId(self::getUserEmailIdFromIAM($tokens->getAccessToken()));
131
                ZohoOAuth::getPersistenceHandlerInstance()->saveOAuthData($tokens);
132
133
                return $tokens;
134
            } else {
135
                throw new ZohoOAuthException("Exception while fetching access token from grant token - " . $resp);
136
            }
137
        } catch (ZohoOAuthException $ex) {
138
            throw new ZohoOAuthException($ex);
139
        }
140
    }
141
142
    public function getUserEmailIdFromIAM($accessToken)
143
    {
144
        $connector = new ZohoOAuthHTTPConnector();
145
        $connector->setUrl(ZohoOAuth::getUserInfoURL());
146
        $connector->addHeadder(ZohoOAuthConstants::AUTHORIZATION,
147
            ZohoOAuthConstants::OAUTH_HEADER_PREFIX . $accessToken);
148
        $apiResponse = $connector->get();
149
        $jsonResponse = self::processResponse($apiResponse);
150
        if (!array_key_exists("Email", $jsonResponse)) {
151
            throw new ZohoOAuthException("Exception while fetching UserID from access token, Make sure AAAserver.profile.Read scope is included while generating the Grant token " . $jsonResponse);
152
        }
153
154
        return $jsonResponse['Email'];
155
    }
156
157
    public function generateAccessTokenFromRefreshToken($refreshToken, $userEmailId)
158
    {
159
        self::refreshAccessToken($refreshToken, $userEmailId);
160
    }
161
162
    /**
163
     * zohoOAuthParams
164
     *
165
     * @return
166
     */
167
    public function getZohoOAuthParams()
168
    {
169
        return $this->zohoOAuthParams;
170
    }
171
172
    /**
173
     * zohoOAuthParams
174
     *
175
     * @param $zohoOAuthParams
176
     */
177
    public function setZohoOAuthParams($zohoOAuthParams)
178
    {
179
        $this->zohoOAuthParams = $zohoOAuthParams;
180
    }
181
}