root/sampleapps/OAuth.php

Revision 84, 17.2 kB (checked in by plindner@…, 2 years ago)

Sync up with my sample unit tests

Line 
1<?php
2// vim: foldmethod=marker
3
4/* Generic exception class
5 */
6class OAuthException extends Exception {/*{{{*/
7  // pass
8}/*}}}*/
9
10class OAuthConsumer {/*{{{*/
11  public $key;
12  public $secret;
13
14  function __construct($key, $secret, $callback_url=NULL) {/*{{{*/
15    $this->key = $key;
16    $this->secret = $secret;
17    $this->callback_url = $callback_url;
18  }/*}}}*/
19}/*}}}*/
20
21class OAuthToken {/*{{{*/
22  // access tokens and request tokens
23  public $key;
24  public $secret;
25
26  /**
27   * key = the token
28   * secret = the token secret
29   */
30  function __construct($key, $secret) {/*{{{*/
31    $this->key = $key;
32    $this->secret = $secret;
33  }/*}}}*/
34
35  /**
36   * generates the basic string serialization of a token that a server
37   * would respond to request_token and access_token calls with
38   */
39  function to_string() {/*{{{*/
40    return "oauth_token=" . urlencode($this->key) . 
41        "&oauth_token_secret=" . urlencode($this->secret);
42  }/*}}}*/
43
44  function __toString() {/*{{{*/
45    return $this->to_string();
46  }/*}}}*/
47}/*}}}*/
48
49class OAuthSignatureMethod {/*{{{*/
50
51}/*}}}*/
52
53class OAuthSignatureMethod_HMAC_SHA1 extends OAuthSignatureMethod {/*{{{*/
54  function get_name() {/*{{{*/
55    return "HMAC-SHA1";
56  }/*}}}*/
57
58  public function build_signature($request, $consumer, $token) {/*{{{*/
59    $sig = array(
60      urlencode($request->get_normalized_http_method()),
61      preg_replace('/%7E/', '~', urlencode($request->get_normalized_http_url())),
62      urlencode($request->get_signable_parameters()),
63    );
64
65    $key = urlencode($consumer->secret) . "&";
66
67    if ($token) {
68      $key .= urlencode($token->secret);
69    }
70
71    $raw = implode("&", $sig);
72    // for debug purposes
73    $request->base_string = $raw;
74
75    // this is silly.
76    $hashed = base64_encode(hash_hmac("sha1", $raw, $key, TRUE));
77    return $hashed;
78  }/*}}}*/
79}/*}}}*/
80
81class OAuthSignatureMethod_PLAINTEXT extends OAuthSignatureMethod {/*{{{*/
82  public function get_name() {/*{{{*/
83    return "PLAINTEXT";
84  }/*}}}*/
85  public function build_signature($request, $consumer, $token) {/*{{{*/
86    $sig = array(
87      urlencode($consumer->secret)
88    );
89
90    if ($token) {
91      array_push($sig, urlencode($token->secret));
92    } else {
93      array_push($sig, '');
94    }
95
96    $raw = implode("&", $sig);
97    // for debug purposes
98    $request->base_string = $raw;
99
100    return urlencode($raw);
101  }/*}}}*/
102}/*}}}*/
103
104class OAuthRequest {/*{{{*/
105  private $parameters;
106  private $http_method;
107  private $http_url;
108  // for debug purposes
109  public $base_string;
110  public static $version = '1.0';
111
112  function __construct($http_method, $http_url, $parameters=NULL) {/*{{{*/
113    @$parameters or $parameters = array();
114    $this->parameters = $parameters;
115    $this->http_method = $http_method;
116    $this->http_url = $http_url;
117  }/*}}}*/
118
119
120  /**
121   * attempt to build up a request from what was passed to the server
122   */
123  public static function from_request($http_method=NULL, $http_url=NULL, $parameters=NULL) {/*{{{*/
124    @$http_url or $http_url = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
125    @$http_method or $http_method = $_SERVER['REQUEST_METHOD'];
126   
127    $request_headers = OAuthRequest::get_headers();
128
129    // let the library user override things however they'd like, if they know
130    // which parameters to use then go for it, for example XMLRPC might want to
131    // do this
132    if ($parameters) {
133      $req = new OAuthRequest($http_method, $http_url, $parameters);
134    }
135    // next check for the auth header, we need to do some extra stuff
136    // if that is the case, namely suck in the parameters from GET or POST
137    // so that we can include them in the signature
138    else if (@substr($request_headers['Authorization'], 0, 5) == "OAuth") {
139      $header_parameters = OAuthRequest::split_header($request_headers['Authorization']);
140      if ($http_method == "GET") {
141        $req_parameters = $_GET;
142      } 
143      else if ($http_method = "POST") {
144        $req_parameters = $_POST;
145      } 
146      $parameters = array_merge($header_parameters, $req_parameters);
147      $req = new OAuthRequest($http_method, $http_url, $parameters);
148    }
149    else if ($http_method == "GET") {
150      $req = new OAuthRequest($http_method, $http_url, $_GET);
151    }
152    else if ($http_method == "POST") {
153      $req = new OAuthRequest($http_method, $http_url, $_POST);
154    }
155    return $req;
156  }/*}}}*/
157
158  /**
159   * pretty much a helper function to set up the request
160   */
161  public static function from_consumer_and_token($consumer, $token, $http_method, $http_url, $parameters=NULL) {/*{{{*/
162    @$parameters or $parameters = array();
163    $defaults = array("oauth_version" => OAuthRequest::$version,
164                      "oauth_nonce" => OAuthRequest::generate_nonce(),
165                      "oauth_timestamp" => OAuthRequest::generate_timestamp(),
166                      "oauth_consumer_key" => $consumer->key);
167    $parameters = array_merge($defaults, $parameters);
168
169    if ($token) {
170      $parameters['oauth_token'] = $token->key;
171    }
172    return new OAuthRequest($http_method, $http_url, $parameters);
173  }/*}}}*/
174
175  public function set_parameter($name, $value) {
176    $this->parameters[$name] = $value;
177  }
178
179  public function get_parameter($name) {
180    return $this->parameters[$name];
181  }
182
183  public function get_parameters() {
184    return $this->parameters;
185  }
186
187  /**
188   * return a string that consists of all the parameters that need to be signed
189   */
190  public function get_signable_parameters() {/*{{{*/
191    $sorted = $this->parameters;
192    ksort($sorted);
193
194    $total = array();
195    foreach ($sorted as $k => $v) {
196      if ($k == "oauth_signature") continue;
197      //$total[] = $k . "=" . $v;
198      // andy, apparently we need to double encode or something yuck
199      $total[] = urlencode($k) . "=" . urlencode($v);
200    }
201    return implode("&", $total);
202  }/*}}}*/
203
204  /**
205   * just uppercases the http method
206   */
207  public function get_normalized_http_method() {/*{{{*/
208    return strtoupper($this->http_method);
209  }/*}}}*/
210
211  /**
212   * parses the url and rebuilds it to be
213   * scheme://host/path
214   */
215  public function get_normalized_http_url() {/*{{{*/
216    $parts = parse_url($this->http_url);
217    $port = "";
218    if( array_key_exists('port', $parts) && $parts['port'] != '80' ){
219      $port = ':' . $parts['port'];
220    }
221    ## aroth, updated to include port
222    $url_string =
223      "{$parts['scheme']}://{$parts['host']}{$port}{$parts['path']}"; 
224      return $url_string;
225  }/*}}}*/
226
227  /**
228   * builds a url usable for a GET request
229   */
230  public function to_url() {/*{{{*/
231    $out = $this->get_normalized_http_url() . "?";
232    $out .= $this->to_postdata();
233    return $out;
234  }/*}}}*/
235
236  /**
237   * builds the data one would send in a POST request
238   */
239  public function to_postdata() {/*{{{*/
240    $total = array();
241    foreach ($this->parameters as $k => $v) {
242      $total[] = urlencode($k) . "=" . urlencode($v);
243    }
244    $out = implode("&", $total);
245    return $out;
246  }/*}}}*/
247
248  /**
249   * builds the Authorization: header
250   */
251  public function to_header() {/*{{{*/
252    $out ='"Authorization: OAuth realm="",';
253    $total = array();
254    foreach ($this->parameters as $k => $v) {
255      if (substr($k, 0, 5) != "oauth") continue;
256      $total[] = urlencode($k) . '="' . urlencode($v) . '"';
257    }
258    $out = implode(",", $total);
259    return $out;
260  }/*}}}*/
261
262  public function __toString() {/*{{{*/
263    return $this->to_url();
264  }/*}}}*/
265
266
267  public function sign_request($signature_method, $consumer, $token) {/*{{{*/
268    $this->set_parameter("oauth_signature_method", $signature_method->get_name());
269    $signature = $this->build_signature($signature_method, $consumer, $token);
270    $this->set_parameter("oauth_signature", $signature);
271  }/*}}}*/
272
273  public function build_signature($signature_method, $consumer, $token) {/*{{{*/
274    $signature = $signature_method->build_signature($this, $consumer, $token);
275    return $signature;
276  }/*}}}*/
277
278  /**
279   * util function: current timestamp
280   */
281  private static function generate_timestamp() {/*{{{*/
282    return time();
283  }/*}}}*/
284
285  /**
286   * util function: current nonce
287   */
288  private static function generate_nonce() {/*{{{*/
289    $mt = microtime();
290    $rand = mt_rand();
291
292    return md5($mt . $rand); // md5s look nicer than numbers
293  }/*}}}*/
294
295  /**
296   * util function for turning the Authorization: header into
297   * parameters, has to do some unescaping
298   */
299  private static function split_header($header) {/*{{{*/
300    // this should be a regex
301    // error cases: commas in parameter values
302    $parts = explode(",", $header);
303    $out = array();
304    foreach ($parts as $param) {
305      $param = ltrim($param);
306      // skip the "realm" param, nobody ever uses it anyway
307      if (substr($param, 0, 5) != "oauth") continue;
308
309      $param_parts = explode("=", $param);
310
311      // rawurldecode() used because urldecode() will turn a "+" in the
312      // value into a space
313      $out[$param_parts[0]] = rawurldecode(substr($param_parts[1], 1, -1));
314    }
315    return $out;
316  }/*}}}*/
317
318  /**
319   * helper to try to sort out headers for people who aren't running apache
320   */
321  private static function get_headers() {
322    if (function_exists('apache_request_headers')) {
323      // we need this to get the actual Authorization: header
324      // because apache tends to tell us it doesn't exist
325      return apache_request_headers();
326    }
327    // otherwise we don't have apache and are just going to have to hope
328    // that $_SERVER actually contains what we need
329    $out = array();
330    foreach ($_SERVER as $key => $value) {
331      if (substr($key, 0, 5) == "HTTP_") {
332        // this is chaos, basically it is just there to capitalize the first
333        // letter of every word that is not an initial HTTP and strip HTTP
334        // code from przemek
335        $key = str_replace(" ", "-", ucwords(strtolower(str_replace("_", " ", substr($key, 5)))));
336        $out[$key] = $value;
337      }
338    }
339    return $out;
340  }
341}/*}}}*/
342
343class OAuthServer {/*{{{*/
344  protected $timestamp_threshold = 300; // in seconds, five minutes
345  protected $version = 1.0;             // hi blaine
346  protected $signature_methods = array();
347
348  protected $data_store;
349
350  function __construct($data_store) {/*{{{*/
351    $this->data_store = $data_store;
352  }/*}}}*/
353
354  public function add_signature_method($signature_method) {/*{{{*/
355    $this->signature_methods[$signature_method->get_name()] = 
356        $signature_method;
357  }/*}}}*/
358 
359  // high level functions
360
361  /**
362   * process a request_token request
363   * returns the request token on success
364   */
365  public function fetch_request_token(&$request) {/*{{{*/
366    $this->get_version($request);
367
368    $consumer = $this->get_consumer($request);
369
370    // no token required for the initial token request
371    $token = NULL;
372
373    $this->check_signature($request, $consumer, $token);
374
375    $new_token = $this->data_store->new_request_token($consumer);
376
377    return $new_token;
378  }/*}}}*/
379
380  /**
381   * process an access_token request
382   * returns the access token on success
383   */
384  public function fetch_access_token(&$request) {/*{{{*/
385    $this->get_version($request);
386
387    $consumer = $this->get_consumer($request);
388
389    // requires authorized request token
390    $token = $this->get_token($request, $consumer, "request");
391
392    $this->check_signature($request, $consumer, $token);
393
394    $new_token = $this->data_store->new_access_token($token, $consumer);
395
396    return $new_token;
397  }/*}}}*/
398
399  /**
400   * verify an api call, checks all the parameters
401   */
402  public function verify_request(&$request) {/*{{{*/
403    $this->get_version($request);
404    $consumer = $this->get_consumer($request);
405    $token = $this->get_token($request, $consumer, "access");
406    $this->check_signature($request, $consumer, $token);
407    return array($consumer, $token);
408  }/*}}}*/
409
410  // Internals from here
411  /**
412   * version 1
413   */
414  private function get_version(&$request) {/*{{{*/
415    $version = $request->get_parameter("oauth_version");
416    if (!$version) {
417      $version = 1.0;
418    }
419    if ($version && $version != $this->version) {
420      throw new OAuthException("OAuth version '$version' not supported");
421    }
422    return $version;
423  }/*}}}*/
424
425  /**
426   * figure out the signature with some defaults
427   */
428  private function get_signature_method(&$request) {/*{{{*/
429    $signature_method = 
430        @$request->get_parameter("oauth_signature_method");
431    if (!$signature_method) {
432      $signature_method = "PLAINTEXT";
433    }
434    if (!in_array($signature_method, 
435                  array_keys($this->signature_methods))) {
436      throw new OAuthException(
437        "Signature method '$signature_method' not supported try one of the following: " . implode(", ", array_keys($this->signature_methods))
438      );     
439    }
440    return $this->signature_methods[$signature_method];
441  }/*}}}*/
442
443  /**
444   * try to find the consumer for the provided request's consumer key
445   */
446  private function get_consumer(&$request) {/*{{{*/
447    $consumer_key = @$request->get_parameter("oauth_consumer_key");
448    if (!$consumer_key) {
449      throw new OAuthException("Invalid consumer key");
450    }
451
452    $consumer = $this->data_store->lookup_consumer($consumer_key);
453    if (!$consumer) {
454      throw new OAuthException("Invalid consumer");
455    }
456
457    return $consumer;
458  }/*}}}*/
459
460  /**
461   * try to find the token for the provided request's token key
462   */
463  private function get_token(&$request, $consumer, $token_type="access") {/*{{{*/
464    $token_field = @$request->get_parameter('oauth_token');
465    $token = $this->data_store->lookup_token(
466      $consumer, $token_type, $token_field
467    );
468    if (!$token) {
469      throw new OAuthException("Invalid $token_type token: $token_field");
470    }
471    return $token;
472  }/*}}}*/
473
474  /**
475   * all-in-one function to check the signature on a request
476   * should guess the signature method appropriately
477   */
478  private function check_signature(&$request, $consumer, $token) {/*{{{*/
479    // this should probably be in a different method
480    $timestamp = @$request->get_parameter('oauth_timestamp');
481    $nonce = @$request->get_parameter('oauth_nonce');
482
483    $this->check_timestamp($timestamp);
484    $this->check_nonce($consumer, $token, $nonce, $timestamp);
485
486    $signature_method = $this->get_signature_method($request);
487
488    $signature = $request->get_parameter('oauth_signature');   
489    $built = $signature_method->build_signature(
490      $request, $consumer, $token
491    );
492
493    if ($signature != $built) {
494      throw new OAuthException("Invalid signature");
495    }
496  }/*}}}*/
497
498  /**
499   * check that the timestamp is new enough
500   */
501  private function check_timestamp($timestamp) {/*{{{*/
502    // verify that timestamp is recentish
503    $now = time();
504    if ($now - $timestamp > $this->timestamp_threshold) {
505      throw new OAuthException("Expired timestamp, yours $timestamp, ours $now");
506    }
507  }/*}}}*/
508
509  /**
510   * check that the nonce is not repeated
511   */
512  private function check_nonce($consumer, $token, $nonce, $timestamp) {/*{{{*/
513    // verify that the nonce is uniqueish
514    $found = $this->data_store->lookup_nonce($consumer, $token, $nonce, $timestamp);
515    if ($found) {
516      throw new OAuthException("Nonce already used: $nonce");
517    }
518  }/*}}}*/
519
520
521
522}/*}}}*/
523
524class OAuthDataStore {/*{{{*/
525  function lookup_consumer($consumer_key) {/*{{{*/
526    // implement me
527  }/*}}}*/
528
529  function lookup_token($consumer, $token_type, $token) {/*{{{*/
530    // implement me
531  }/*}}}*/
532
533  function lookup_nonce($consumer, $token, $nonce, $timestamp) {/*{{{*/
534    // implement me
535  }/*}}}*/
536
537  function fetch_request_token($consumer) {/*{{{*/
538    // return a new token attached to this consumer
539  }/*}}}*/
540
541  function fetch_access_token($token, $consumer) {/*{{{*/
542    // return a new access token attached to this consumer
543    // for the user associated with this token if the request token
544    // is authorized
545    // should also invalidate the request token
546  }/*}}}*/
547
548}/*}}}*/
549
550
551/*  A very naive dbm-based oauth storage
552 */
553class SimpleOAuthDataStore extends OAuthDataStore {/*{{{*/
554  private $dbh;
555
556  function __construct($path = "oauth.gdbm") {/*{{{*/
557    $this->dbh = dba_popen($path, 'c', 'gdbm');
558  }/*}}}*/
559
560  function __destruct() {/*{{{*/
561    dba_close($this->dbh);
562  }/*}}}*/
563
564  function lookup_consumer($consumer_key) {/*{{{*/
565    $rv = dba_fetch("consumer_$consumer_key", $this->dbh);
566    if ($rv === FALSE) {
567      return NULL;
568    }
569    $obj = unserialize($rv);
570    if (!($obj instanceof OAuthConsumer)) {
571      return NULL;
572    }
573    return $obj;
574  }/*}}}*/
575
576  function lookup_token($consumer, $token_type, $token) {/*{{{*/
577    $rv = dba_fetch("${token_type}_${token}", $this->dbh);
578    if ($rv === FALSE) {
579      return NULL;
580    }
581    $obj = unserialize($rv);
582    if (!($obj instanceof OAuthToken)) {
583      return NULL;
584    }
585    return $obj;
586  }/*}}}*/
587
588  function lookup_nonce($consumer, $token, $nonce, $timestamp) {/*{{{*/
589    return dba_exists("nonce_$nonce", $this->dbh);
590  }/*}}}*/
591
592  function new_token($consumer, $type="request") {/*{{{*/
593    $key = md5(time());
594    $secret = time() + time();
595    $token = new OAuthToken($key, md5(md5($secret)));
596    if (!dba_insert("${type}_$key", serialize($token), $this->dbh)) {
597      throw new OAuthException("doooom!");
598    }
599    return $token;
600  }/*}}}*/
601
602  function new_request_token($consumer) {/*{{{*/
603    return $this->new_token($consumer, "request");
604  }/*}}}*/
605
606  function new_access_token($token, $consumer) {/*{{{*/
607
608    $token = $this->new_token($consumer, 'access');
609    dba_delete("request_" . $token->key, $this->dbh);
610    return $token;
611  }/*}}}*/
612}/*}}}*/
613
614?>
Note: See TracBrowser for help on using the browser.
Close