apiOAuth2.php
7.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
<?php
/*
* Copyright 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Authentication class that deals with the OAuth 2 web-server authentication flow
*
* @author Chris Chabot <chabotc@google.com>
*
*/
class apiOAuth2 extends apiAuth {
public $clientId;
public $clientSecret;
public $developerKey;
public $accessToken;
public $redirectUri;
const OAUTH2_TOKEN_URI = "https://accounts.google.com/o/oauth2/token";
const OAUTH2_AUTH_URL = "https://accounts.google.com/o/oauth2/auth";
/**
* Instantiates the class, but does not initiate the login flow, leaving it
* to the discretion of the caller (which is done by calling authenticate()).
*/
public function __construct() {
global $apiConfig;
if (! empty($apiConfig['developer_key'])) {
$this->developerKey = $apiConfig['developer_key'];
}
if (! empty($apiConfig['oauth2_client_id'])) {
$this->clientId = $apiConfig['oauth2_client_id'];
}
if (! empty($apiConfig['oauth2_client_secret'])) {
$this->clientSecret = $apiConfig['oauth2_client_secret'];
}
if (! empty($apiConfig['oauth2_redirect_uri'])) {
$this->redirectUri = $apiConfig['oauth2_redirect_uri'];
}
}
public function authenticate($service) {
//echo "s90";
if ($this->io == null) {
global $apiClient;
$this->io = $apiClient->getIo();
}
//cho "s91";
if (isset($_GET['code'])) {
//echo "::".self::OAUTH2_TOKEN_URI."::";
// We got here from the redirect from a successful authorization grant, fetch the access token
//print_r(new apiHttpRequest(self::OAUTH2_TOKEN_URI, 'POST', array(), array(
// 'code' => $_GET['code'],
// 'grant_type' => 'authorization_code',
// 'redirect_uri' => $this->redirectUri,
// 'client_id' => $this->clientId,
// 'client_secret' => $this->clientSecret
//)));
$request = $this->io->makeRequest(new apiHttpRequest(self::OAUTH2_TOKEN_URI, 'POST', array(), array(
'code' => $_GET['code'],
'grant_type' => 'authorization_code',
'redirect_uri' => $this->redirectUri,
'client_id' => $this->clientId,
'client_secret' => $this->clientSecret
)));
//echo "s92-";
//echo $request->getResponseHttpCode();
if ($request->getResponseHttpCode() == '200') {
//echo "200";
//print_r($request);
//echo $request->getResponseBody();
$suka = json_decode($request->getResponseBody(), true);
//print_r($suka);
//echo $suka['access_token'];
//$this->setAccessToken($request->getResponseBody());
//$this->accessToken['created'] = time();
//echo $request->getResponseBody();
$this->accessToken = $suka;
return $suka['access_token'];
} else {
$response = $request->getResponseBody();
//echo "s94-";
//echo $ressepon;
$decodedResponse = json_decode($ressepon, true);
if ($decodedResponse != $response && $decodedResponse != null && $decodedResponse['error']) {
$response = $decodedResponse['error'];
}
throw new apiAuthException("Error fetching OAuth2 access token, message: '$response'", $request->getResponseHttpCode());
}
}
$authUrl = $this->createAuthUrl($service);
header('Location: ' . $authUrl);
}
public function createAuthUrl($service) {
$params = array(
'response_type=code',
'redirect_uri=' . urlencode($this->redirectUri),
'client_id=' . urlencode($this->clientId),
'scope=' . urlencode($service['scope'])
);
$params = implode('&', $params);
return self::OAUTH2_AUTH_URL . "?$params";
}
public function setAccessToken($accessToken) {
$accessToken = json_decode($accessToken, true);
//if ($accessToken == null) {
// throw new apiAuthException("Could not json decode the access token");
//}
//if (! isset($accessToken['access_token']) || ! isset($accessToken['expires_in']) || ! //isset($accessToken['refresh_token'])) {
// throw new apiAuthException("Invalid token format");
//}
$this->accessToken = $accessToken;
}
public function getAccessToken() {
return json_encode($this->accessToken);
}
public function setDeveloperKey($developerKey) {
$this->developerKey = $developerKey;
}
public function sign(apiHttpRequest $request) {
// add the developer key to the request before signing it
echo "PDR-1</br>";
if ($this->developerKey) {
$request->setUrl($request->getUrl() . ((strpos($request->getUrl(), '?') === false) ? '?' : '&') . 'key=' . urlencode($this->developerKey));
}
echo "PDR-2</br>";
// Cannot sign the request without an OAuth access token.
if (null == $this->accessToken) {
return $request;
}
echo "PDR-3</br>";
if (($this->accessToken['created'] + ($this->accessToken['expires_in'] - 30)) < time()) {
// if the token is set to expire in the next 30 seconds (or has already expired), refresh it and set the new token
//FIXME this is mostly a copy and paste mashup from the authenticate and setAccessToken functions, should generalize them into a function instead of this mess
$refreshRequest = $this->io->makeRequest(new apiHttpRequest(self::OAUTH2_TOKEN_URI, 'POST', array(), array(
'client_id' => $this->clientId,
'client_secret' => $this->clientSecret,
'refresh_token' => $this->accessToken['refresh_token'],
'grant_type' => 'refresh_token'
)));
echo "PDR-4</br>";
if ($refreshRequest->getResponseHttpCode() == '200') {
$token = json_decode($refreshRequest->getResponseBody(), true);
if ($token == null) {
//throw new apiAuthException("Could not json decode the access token");
}
echo "PDR-5</br>";
if (! isset($token['access_token']) || ! isset($token['expires_in'])) {
//throw new apiAuthException("Invalid token format");
}
echo "PDR-6</br>";
$this->accessToken['access_token'] = $token['access_token'];
$this->accessToken['expires_in'] = $token['expires_in'];
$this->accessToken['created'] = time();
} else {
$response = $refreshRequest->getResponseBody();
$decodedResponse = json_decode($response, true);
if ($decodedResponse != $response && $decodedResponse != null && $decodedResponse['error']) {
$response = $decodedResponse['error'];
}
//throw new apiAuthException("Error refreshing the OAuth2 token, message: '$response'", $refreshRequest->getResponseHttpCode());
}
}
echo "PDR-7</br>";
// Add the OAuth2 header to the request
$headers = $request->getHeaders();
$headers[] = "Authorization: OAuth " . $this->accessToken['access_token'];
$request->setHeaders($headers);
return $request;
}
}