/
Provider.php
375 lines (345 loc) · 11.2 KB
/
Provider.php
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
<?php
require_once 'Zend/Oauth/Exception.php';
require_once 'Zend/Oauth/Http/Utility.php';
require_once 'Zend/Uri/Http.php';
/**
*
* Basic OAuth provider class
*/
class Zend_Oauth_Provider
{
/**
* OAuth result statuses
*/
const OK = 0;
const BAD_NONCE = 1;
const BAD_TIMESTAMP = 2;
const CONSUMER_KEY_UNKNOWN = 3;
const CONSUMER_KEY_REFUSED = 4;
const INVALID_SIGNATURE = 5;
const TOKEN_USED = 6;
const TOKEN_EXPIRED = 7;
const TOKEN_REVOKED = 8;
const TOKEN_REJECTED = 9;
const PARAMETER_ABSENT = 10;
const SIGNATURE_METHOD_REJECTED = 11;
const OAUTH_VERIFIER_INVALID = 12;
/**
* Error names for error reporting
* @var array
*/
protected $errnames = array(
self::BAD_NONCE => "nonce_used",
self::BAD_TIMESTAMP => "timestamp_refused",
self::CONSUMER_KEY_UNKNOWN => "consumer_key_unknown",
self::CONSUMER_KEY_REFUSED => "consumer_key_refused",
self::INVALID_SIGNATURE => "signature_invalid",
self::TOKEN_USED => "token_used",
self::TOKEN_EXPIRED => "token_expired",
self::TOKEN_REVOKED => "token_revoked",
self::TOKEN_REJECTED => "token_rejected",
self::PARAMETER_ABSENT => "parameter_absent",
self::SIGNATURE_METHOD_REJECTED => "signature_method_rejected",
self::OAUTH_VERIFIER_INVALID => "verifier_invalid",
);
public $token;
public $token_secret;
public $consumer_key;
public $consumer_secret;
public $verifier;
public $callback;
protected $problem;
protected $tokenHandler;
protected $consumerHandler;
protected $nonceHandler;
protected $oauth_params;
protected $requestPath;
/**
* Current URL
* @var Zend_Uri_Http
*/
protected $url;
/**
*
* Required OAuth parameters
* @var array
*/
protected $required = array("oauth_consumer_key", "oauth_signature", "oauth_signature_method", "oauth_nonce", "oauth_timestamp");
/**
* Set consumer key handler
* @param string $callback
* @return Zend_Oauth_Provider
*/
public function setConsumerHandler($callback)
{
$this->consumerHandler = $callback;
return $this;
}
/**
* Set nonce/ts handler
* @param string $callback
* @return Zend_Oauth_Provider
*/
public function setTimestampNonceHandler($callback)
{
$this->nonceHandler = $callback;
return $this;
}
/**
* Set token handler
* @param string $callback
* @return Zend_Oauth_Provider
*/
public function setTokenHandler($callback)
{
$this->tokenHandler = $callback;
return $this;
}
/**
* Set URL for requesting token (doesn't need token)
* @param string $req_path
* @return Zend_Oauth_Provider
*/
public function setRequestTokenPath($req_path)
{
$this->requestPath = $req_path;
return $this;
}
/**
* Set this request as token endpoint
* @param string $request
* @return Zend_Oauth_Provider
*/
public function isRequestTokenEndpoint($request)
{
$this->is_request = $request;
return $this;
}
/**
* Report problem in OAuth as string
* @param Zend_Oauth_Exception $e
* @return string
*/
public function reportProblem(Zend_Oauth_Exception $e)
{
$code = $e->getCode();
if($code == self::PARAMETER_ABSENT) {
return "oauth_problem=parameter_absent&oauth_parameters_absent={$this->problem}";
}
if($code == self::INVALID_SIGNATURE) {
return "oauth_problem=signature_invalid&debug_sbs={$this->problem}";
}
if(isset($this->errnames[$code])) {
return "oauth_problem=".$this->errnames[$code];
}
return "oauth_problem=unknown_problem&code=$code";
}
/**
* Check if this request needs token
* Requests made to requestPath do not need a token
* @return bool
*/
protected function needsToken()
{
if(!empty($this->is_request)) {
return false;
}
if(empty($this->requestPath)) {
return true;
}
if($this->requestPath[0] == '/') {
return $this->url->getPath() != $this->requestPath;
}
return $this->url->getUri() != $this->requestPath;
}
/**
* Check if all required parameters are there
* @param array $params
* @throws Zend_Oauth_Exception
*/
protected function checkRequiredParams($params)
{
foreach($this->required as $param) {
if(!isset($params[$param])) {
$this->problem = $param;
throw new Zend_Oauth_Exception("Missing parameter: $param", self::PARAMETER_ABSENT);
}
}
if($this->needsToken() && !isset($params["oauth_token"])) {
$this->problem = "oauth_token";
throw new Zend_Oauth_Exception("Missing parameter: oauth_token", self::PARAMETER_ABSENT);
}
return true;
}
/**
* Check if signature method is supported
* @param string $signatureMethod
* @throws Zend_Oauth_Exception
*/
protected function checkSignatureMethod($signatureMethod)
{
$className = '';
$hashAlgo = null;
$parts = explode('-', $signatureMethod);
if (count($parts) > 1) {
$className = 'Zend_Oauth_Signature_' . ucfirst(strtolower($parts[0]));
} else {
$className = 'Zend_Oauth_Signature_' . ucfirst(strtolower($signatureMethod));
}
$filename = str_replace('_', '/', $className) . '.php';
if(file_exists($filename)) {
require_once $filename;
}
if(!class_exists($className)) {
throw new Zend_Oauth_Exception("Invalid signature method", self::SIGNATURE_METHOD_REJECTED);
}
}
/**
* Collect request parameters from the environment
* FIXME: uses GET/POST/SERVER, needs to be made injectable instead
* @param string $method HTTP method being used
* @param string $params Extra parameters
* @return array List of all oauth params in the request
*/
protected function assembleParams($method, $params = array())
{
$params = array_merge($_GET, $params);
if($method == 'POST') {
$params = array_merge($_POST, $params);
}
$auth = null;
if(function_exists('apache_request_headers')) {
$headers = apache_request_headers();
if(isset($headers['Authorization'])) {
$auth = $headers['Authorization'];
} elseif(isset($headers['authorization'])) {
$auth = $headers['authorization'];
}
}
if(empty($auth) && !empty($_SERVER['HTTP_AUTHORIZATION'])) {
$auth = $_SERVER['HTTP_AUTHORIZATION'];
}
if(!empty($auth) && substr($auth, 0, 6) == 'OAuth ') {
// import header data
if (preg_match_all('/(oauth_[a-z_-]*)=(:?"([^"]*)"|([^,]*))/', $auth, $matches)) {
foreach ($matches[1] as $num => $header) {
if($header == 'realm') {
continue;
}
$params[$header] = urldecode(empty($matches[3][$num])? $matches[4][$num] : $matches[3][$num]);
}
}
}
return $params;
}
/**
* Get full current request URL
* @return string
*/
protected function getRequestUrl()
{
$proto = "http";
if(empty($_SERVER['SERVER_PORT']) || empty($_SERVER['HTTP_HOST']) || empty($_SERVER['REQUEST_URI'])) {
return Zend_Uri_Http::fromString("http://localhost/");
}
if($_SERVER['SERVER_PORT'] == 443 || (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (!empty($_SERVER['HTTP_HTTPS']) && $_SERVER['HTTP_HTTPS'] == 'on')) {
$proto = 'https';
}
return Zend_Uri_Http::fromString("$proto://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}");
}
/**
* Returns oauth parameters
* @return array
*/
public function getOAuthParams()
{
return $this->oauth_params;
}
/**
* Validate OAuth request
* @param Zend_Uri_Http $url Request URL, will use current if null
* @param array $params Additional parameters
* @return bool
* @throws Zend_Oauth_Exception
*/
public function checkOAuthRequest(Zend_Uri_Http $url = null, $params = array())
{
if(empty($url)) {
$this->url = $this->getRequestUrl();
} else {
$this->url = clone $url;
}
// We'll ignore query for the pruposes of URL matching
$this->url->setQuery('');
// FIXME: make it injectable
if(isset($_SERVER['REQUEST_METHOD'])) {
$method = $_SERVER['REQUEST_METHOD'];
} elseif(isset($_SERVER['HTTP_METHOD'])) {
$method = $_SERVER['HTTP_METHOD'];
} else {
$method = 'GET';
}
$params = $this->assembleParams($method, $params);
$this->oauth_params = $params;
$this->checkSignatureMethod($params['oauth_signature_method']);
$this->checkRequiredParams($params);
$this->timestamp = $params['oauth_timestamp'];
$this->nonce = $params['oauth_nonce'];
$this->consumer_key = $params['oauth_consumer_key'];
if (isset($params['oauth_callback'])) {
$this->callback = $params['oauth_callback'];
}
if(!is_callable($this->nonceHandler)) {
throw new Zend_Oauth_Exception("Nonce handler not callable", self::BAD_NONCE);
}
$res = call_user_func($this->nonceHandler, $this);
if($res != self::OK) {
throw new Zend_Oauth_Exception("Invalid request", $res);
}
if(!is_callable($this->consumerHandler)) {
throw new Zend_Oauth_Exception("Consumer handler not callable", self::CONSUMER_KEY_UNKNOWN);
}
$res = call_user_func($this->consumerHandler, $this);
// this will set $this->consumer_secret if OK
if($res != self::OK) {
throw new Zend_Oauth_Exception("Consumer key invalid", $res);
}
if($this->needsToken()) {
$this->token = $params['oauth_token'];
if(isset($params['oauth_verifier'])) {
$this->verifier = $params['oauth_verifier'];
}
if(!is_callable($this->tokenHandler)) {
throw new Zend_Oauth_Exception("Token handler not callable", self::TOKEN_REJECTED);
}
$res = call_user_func($this->tokenHandler, $this);
// this will set $this->token_secret if OK
if($res != self::OK) {
throw new Zend_Oauth_Exception("Token invalid", $res);
}
}
$util = new Zend_Oauth_Http_Utility();
$req_sign = $params['oauth_signature'];
unset($params['oauth_signature']);
$our_sign = $util->sign($params, $params['oauth_signature_method'], $this->consumer_secret,
$this->token_secret, $method, $this->url->getUri());
if($req_sign != $our_sign) {
// TODO: think how to extract signature base string
$this->problem = $our_sign;
throw new Zend_Oauth_Exception("Invalid signature", self::INVALID_SIGNATURE);
}
return true;
}
/**
* Generate new token
* @param int $size How many characters?
*/
public function generateToken($size)
{
$str = '';
while(strlen($str) < $size) {
$str .= md5(uniqid(mt_rand(), true), true);
}
return substr($str, 0, $size);
}
}