Merge branch 'MDL-62026-master' of git://github.com/junpataleta/moodle
[moodle.git] / lib / oauthlib.php
blobc933decedbf249cd9c7bec76648438ae7754bac1
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 defined('MOODLE_INTERNAL') || die();
20 require_once($CFG->libdir.'/filelib.php');
22 /**
23 * OAuth helper class
25 * 1. You can extends oauth_helper to add specific functions, such as twitter extends oauth_helper
26 * 2. Call request_token method to get oauth_token and oauth_token_secret, and redirect user to authorize_url,
27 * developer needs to store oauth_token and oauth_token_secret somewhere, we will use them to request
28 * access token later on
29 * 3. User approved the request, and get back to moodle
30 * 4. Call get_access_token, it takes previous oauth_token and oauth_token_secret as arguments, oauth_token
31 * will be used in OAuth request, oauth_token_secret will be used to bulid signature, this method will
32 * return access_token and access_secret, store these two values in database or session
33 * 5. Now you can access oauth protected resources by access_token and access_secret using oauth_helper::request
34 * method (or get() post())
36 * Note:
37 * 1. This class only support HMAC-SHA1
38 * 2. oauth_helper class don't store tokens and secrets, you must store them manually
39 * 3. Some functions are based on http://code.google.com/p/oauth/
41 * @package moodlecore
42 * @copyright 2010 Dongsheng Cai <dongsheng@moodle.com>
43 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
46 class oauth_helper {
47 /** @var string consumer key, issued by oauth provider*/
48 protected $consumer_key;
49 /** @var string consumer secret, issued by oauth provider*/
50 protected $consumer_secret;
51 /** @var string oauth root*/
52 protected $api_root;
53 /** @var string request token url*/
54 protected $request_token_api;
55 /** @var string authorize url*/
56 protected $authorize_url;
57 protected $http_method;
58 /** @var string */
59 protected $access_token_api;
60 /** @var curl */
61 protected $http;
62 /** @var array options to pass to the next curl request */
63 protected $http_options;
65 /**
66 * Contructor for oauth_helper.
67 * Subclass can override construct to build its own $this->http
69 * @param array $args requires at least three keys, oauth_consumer_key
70 * oauth_consumer_secret and api_root, oauth_helper will
71 * guess request_token_api, authrize_url and access_token_api
72 * based on api_root, but it not always works
74 function __construct($args) {
75 if (!empty($args['api_root'])) {
76 $this->api_root = $args['api_root'];
77 } else {
78 $this->api_root = '';
80 $this->consumer_key = $args['oauth_consumer_key'];
81 $this->consumer_secret = $args['oauth_consumer_secret'];
83 if (empty($args['request_token_api'])) {
84 $this->request_token_api = $this->api_root . '/request_token';
85 } else {
86 $this->request_token_api = $args['request_token_api'];
89 if (empty($args['authorize_url'])) {
90 $this->authorize_url = $this->api_root . '/authorize';
91 } else {
92 $this->authorize_url = $args['authorize_url'];
95 if (empty($args['access_token_api'])) {
96 $this->access_token_api = $this->api_root . '/access_token';
97 } else {
98 $this->access_token_api = $args['access_token_api'];
101 if (!empty($args['oauth_callback'])) {
102 $this->oauth_callback = new moodle_url($args['oauth_callback']);
104 if (!empty($args['access_token'])) {
105 $this->access_token = $args['access_token'];
107 if (!empty($args['access_token_secret'])) {
108 $this->access_token_secret = $args['access_token_secret'];
110 $this->http = new curl(array('debug'=>false));
111 $this->http_options = array();
115 * Build parameters list:
116 * oauth_consumer_key="0685bd9184jfhq22",
117 * oauth_nonce="4572616e48616d6d65724c61686176",
118 * oauth_token="ad180jjd733klru7",
119 * oauth_signature_method="HMAC-SHA1",
120 * oauth_signature="wOJIO9A2W5mFwDgiDvZbTSMK%2FPY%3D",
121 * oauth_timestamp="137131200",
122 * oauth_version="1.0"
123 * oauth_verifier="1.0"
124 * @param array $param
125 * @return string
127 function get_signable_parameters($params){
128 $sorted = $params;
129 ksort($sorted);
131 $total = array();
132 foreach ($sorted as $k => $v) {
133 if ($k == 'oauth_signature') {
134 continue;
137 $total[] = rawurlencode($k) . '=' . rawurlencode($v);
139 return implode('&', $total);
143 * Create signature for oauth request
144 * @param string $url
145 * @param string $secret
146 * @param array $params
147 * @return string
149 public function sign($http_method, $url, $params, $secret) {
150 $sig = array(
151 strtoupper($http_method),
152 preg_replace('/%7E/', '~', rawurlencode($url)),
153 rawurlencode($this->get_signable_parameters($params)),
156 $base_string = implode('&', $sig);
157 $sig = base64_encode(hash_hmac('sha1', $base_string, $secret, true));
158 return $sig;
162 * Initilize oauth request parameters, including:
163 * oauth_consumer_key="0685bd9184jfhq22",
164 * oauth_token="ad180jjd733klru7",
165 * oauth_signature_method="HMAC-SHA1",
166 * oauth_signature="wOJIO9A2W5mFwDgiDvZbTSMK%2FPY%3D",
167 * oauth_timestamp="137131200",
168 * oauth_nonce="4572616e48616d6d65724c61686176",
169 * oauth_version="1.0"
170 * To access protected resources, oauth_token should be defined
172 * @param string $url
173 * @param string $token
174 * @param string $http_method
175 * @return array
177 public function prepare_oauth_parameters($url, $params, $http_method = 'POST') {
178 if (is_array($params)) {
179 $oauth_params = $params;
180 } else {
181 $oauth_params = array();
183 $oauth_params['oauth_version'] = '1.0';
184 $oauth_params['oauth_nonce'] = $this->get_nonce();
185 $oauth_params['oauth_timestamp'] = $this->get_timestamp();
186 $oauth_params['oauth_consumer_key'] = $this->consumer_key;
187 $oauth_params['oauth_signature_method'] = 'HMAC-SHA1';
188 $oauth_params['oauth_signature'] = $this->sign($http_method, $url, $oauth_params, $this->sign_secret);
189 return $oauth_params;
192 public function setup_oauth_http_header($params) {
194 $total = array();
195 ksort($params);
196 foreach ($params as $k => $v) {
197 $total[] = rawurlencode($k) . '="' . rawurlencode($v).'"';
199 $str = implode(', ', $total);
200 $str = 'Authorization: OAuth '.$str;
201 $this->http->setHeader('Expect:');
202 $this->http->setHeader($str);
206 * Sets the options for the next curl request
208 * @param array $options
210 public function setup_oauth_http_options($options) {
211 $this->http_options = $options;
215 * Request token for authentication
216 * This is the first step to use OAuth, it will return oauth_token and oauth_token_secret
217 * @return array
219 public function request_token() {
220 $this->sign_secret = $this->consumer_secret.'&';
222 if (empty($this->oauth_callback)) {
223 $params = [];
224 } else {
225 $params = ['oauth_callback' => $this->oauth_callback->out(false)];
228 $params = $this->prepare_oauth_parameters($this->request_token_api, $params, 'GET');
229 $content = $this->http->get($this->request_token_api, $params, $this->http_options);
230 // Including:
231 // oauth_token
232 // oauth_token_secret
233 $result = $this->parse_result($content);
234 if (empty($result['oauth_token'])) {
235 throw new moodle_exception('oauth1requesttoken', 'core_error', '', null, $content);
237 // Build oauth authorize url.
238 $result['authorize_url'] = $this->authorize_url . '?oauth_token='.$result['oauth_token'];
240 return $result;
244 * Set oauth access token for oauth request
245 * @param string $token
246 * @param string $secret
248 public function set_access_token($token, $secret) {
249 $this->access_token = $token;
250 $this->access_token_secret = $secret;
254 * Request oauth access token from server
255 * @param string $method
256 * @param string $url
257 * @param string $token
258 * @param string $secret
260 public function get_access_token($token, $secret, $verifier='') {
261 $this->sign_secret = $this->consumer_secret.'&'.$secret;
262 $params = $this->prepare_oauth_parameters($this->access_token_api, array('oauth_token'=>$token, 'oauth_verifier'=>$verifier), 'POST');
263 $this->setup_oauth_http_header($params);
264 // Should never send the callback in this request.
265 unset($params['oauth_callback']);
266 $content = $this->http->post($this->access_token_api, $params, $this->http_options);
267 $keys = $this->parse_result($content);
269 if (empty($keys['oauth_token']) || empty($keys['oauth_token_secret'])) {
270 throw new moodle_exception('oauth1accesstoken', 'core_error', '', null, $content);
273 $this->set_access_token($keys['oauth_token'], $keys['oauth_token_secret']);
274 return $keys;
278 * Request oauth protected resources
279 * @param string $method
280 * @param string $url
281 * @param string $token
282 * @param string $secret
284 public function request($method, $url, $params=array(), $token='', $secret='') {
285 if (empty($token)) {
286 $token = $this->access_token;
288 if (empty($secret)) {
289 $secret = $this->access_token_secret;
291 // to access protected resource, sign_secret will alwasy be consumer_secret+token_secret
292 $this->sign_secret = $this->consumer_secret.'&'.$secret;
293 if (strtolower($method) === 'post' && !empty($params)) {
294 $oauth_params = $this->prepare_oauth_parameters($url, array('oauth_token'=>$token) + $params, $method);
295 } else {
296 $oauth_params = $this->prepare_oauth_parameters($url, array('oauth_token'=>$token), $method);
298 $this->setup_oauth_http_header($oauth_params);
299 $content = call_user_func_array(array($this->http, strtolower($method)), array($url, $params, $this->http_options));
300 // reset http header and options to prepare for the next request
301 $this->http->resetHeader();
302 // return request return value
303 return $content;
307 * shortcut to start http get request
309 public function get($url, $params=array(), $token='', $secret='') {
310 return $this->request('GET', $url, $params, $token, $secret);
314 * shortcut to start http post request
316 public function post($url, $params=array(), $token='', $secret='') {
317 return $this->request('POST', $url, $params, $token, $secret);
321 * A method to parse oauth response to get oauth_token and oauth_token_secret
322 * @param string $str
323 * @return array
325 public function parse_result($str) {
326 if (empty($str)) {
327 throw new moodle_exception('error');
329 $parts = explode('&', $str);
330 $result = array();
331 foreach ($parts as $part){
332 list($k, $v) = explode('=', $part, 2);
333 $result[urldecode($k)] = urldecode($v);
335 if (empty($result)) {
336 throw new moodle_exception('error');
338 return $result;
342 * Set nonce
344 function set_nonce($str) {
345 $this->nonce = $str;
348 * Set timestamp
350 function set_timestamp($time) {
351 $this->timestamp = $time;
354 * Generate timestamp
356 function get_timestamp() {
357 if (!empty($this->timestamp)) {
358 $timestamp = $this->timestamp;
359 unset($this->timestamp);
360 return $timestamp;
362 return time();
365 * Generate nonce for oauth request
367 function get_nonce() {
368 if (!empty($this->nonce)) {
369 $nonce = $this->nonce;
370 unset($this->nonce);
371 return $nonce;
373 $mt = microtime();
374 $rand = mt_rand();
376 return md5($mt . $rand);
381 * OAuth 2.0 Client for using web access tokens.
383 * http://tools.ietf.org/html/draft-ietf-oauth-v2-22
385 * @package core
386 * @copyright Dan Poltawski <talktodan@gmail.com>
387 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
389 abstract class oauth2_client extends curl {
390 /** @var string $clientid client identifier issued to the client */
391 private $clientid = '';
392 /** @var string $clientsecret The client secret. */
393 private $clientsecret = '';
394 /** @var moodle_url $returnurl URL to return to after authenticating */
395 private $returnurl = null;
396 /** @var string $scope of the authentication request */
397 protected $scope = '';
398 /** @var stdClass $accesstoken access token object */
399 private $accesstoken = null;
400 /** @var string $refreshtoken refresh token string */
401 protected $refreshtoken = '';
402 /** @var string $mocknextresponse string */
403 private $mocknextresponse = '';
404 /** @var array $upgradedcodes list of upgraded codes in this request */
405 private static $upgradedcodes = [];
406 /** @var bool basicauth */
407 protected $basicauth = false;
410 * Returns the auth url for OAuth 2.0 request
411 * @return string the auth url
413 abstract protected function auth_url();
416 * Returns the token url for OAuth 2.0 request
417 * @return string the auth url
419 abstract protected function token_url();
422 * Constructor.
424 * @param string $clientid
425 * @param string $clientsecret
426 * @param moodle_url $returnurl
427 * @param string $scope
429 public function __construct($clientid, $clientsecret, moodle_url $returnurl, $scope) {
430 parent::__construct();
431 $this->clientid = $clientid;
432 $this->clientsecret = $clientsecret;
433 $this->returnurl = $returnurl;
434 $this->scope = $scope;
435 $this->accesstoken = $this->get_stored_token();
439 * Is the user logged in? Note that if this is called
440 * after the first part of the authorisation flow the token
441 * is upgraded to an accesstoken.
443 * @return boolean true if logged in
445 public function is_logged_in() {
446 // Has the token expired?
447 if (isset($this->accesstoken->expires) && time() >= $this->accesstoken->expires) {
448 $this->log_out();
449 return false;
452 // We have a token so we are logged in.
453 if (isset($this->accesstoken->token)) {
454 // Check that the access token has all the requested scopes.
455 $scopemissing = false;
456 $scopecheck = ' ' . $this->accesstoken->scope . ' ';
458 $requiredscopes = explode(' ', $this->scope);
459 foreach ($requiredscopes as $requiredscope) {
460 if (strpos($scopecheck, ' ' . $requiredscope . ' ') === false) {
461 $scopemissing = true;
462 break;
465 if (!$scopemissing) {
466 return true;
470 // If we've been passed then authorization code generated by the
471 // authorization server try and upgrade the token to an access token.
472 $code = optional_param('oauth2code', null, PARAM_RAW);
473 // Note - sometimes we may call is_logged_in twice in the same request - we don't want to attempt
474 // to upgrade the same token twice.
475 if ($code && !in_array($code, self::$upgradedcodes) && $this->upgrade_token($code)) {
476 return true;
479 return false;
483 * Callback url where the request is returned to.
485 * @return moodle_url url of callback
487 public static function callback_url() {
488 global $CFG;
490 return new moodle_url('/admin/oauth2callback.php');
494 * An additional array of url params to pass with a login request.
496 * @return array of name value pairs.
498 public function get_additional_login_parameters() {
499 return [];
503 * Returns the login link for this oauth request
505 * @return moodle_url login url
507 public function get_login_url() {
509 $callbackurl = self::callback_url();
510 $params = array_merge(
512 'client_id' => $this->clientid,
513 'response_type' => 'code',
514 'redirect_uri' => $callbackurl->out(false),
515 'state' => $this->returnurl->out_as_local_url(false),
516 'scope' => $this->scope,
518 $this->get_additional_login_parameters()
521 return new moodle_url($this->auth_url(), $params);
525 * Given an array of name value pairs - build a valid HTTP POST application/x-www-form-urlencoded string.
527 * @param array $params Name / value pairs.
528 * @return string POST data.
530 public function build_post_data($params) {
531 $result = [];
532 foreach ($params as $name => $value) {
533 $result[] = urlencode($name) . '=' . urlencode($value);
535 return implode('&', $result);
539 * Upgrade a authorization token from oauth 2.0 to an access token
541 * @param string $code the code returned from the oauth authenticaiton
542 * @return boolean true if token is upgraded succesfully
544 public function upgrade_token($code) {
545 $callbackurl = self::callback_url();
546 $params = array('code' => $code,
547 'grant_type' => 'authorization_code',
548 'redirect_uri' => $callbackurl->out(false),
551 if ($this->basicauth) {
552 $idsecret = urlencode($this->clientid) . ':' . urlencode($this->clientsecret);
553 $this->setHeader('Authorization: Basic ' . base64_encode($idsecret));
554 } else {
555 $params['client_id'] = $this->clientid;
556 $params['client_secret'] = $this->clientsecret;
559 // Requests can either use http GET or POST.
560 if ($this->use_http_get()) {
561 $response = $this->get($this->token_url(), $params);
562 } else {
563 $response = $this->post($this->token_url(), $this->build_post_data($params));
566 if ($this->info['http_code'] !== 200) {
567 throw new moodle_exception('Could not upgrade oauth token');
570 $r = json_decode($response);
572 if (is_null($r)) {
573 throw new moodle_exception("Could not decode JSON token response");
576 if (!empty($r->error)) {
577 throw new moodle_exception($r->error . ' ' . $r->error_description);
580 if (!isset($r->access_token)) {
581 return false;
584 if (isset($r->refresh_token)) {
585 $this->refreshtoken = $r->refresh_token;
588 // Store the token an expiry time.
589 $accesstoken = new stdClass;
590 $accesstoken->token = $r->access_token;
591 if (isset($r->expires_in)) {
592 // Expires 10 seconds before actual expiry.
593 $accesstoken->expires = (time() + ($r->expires_in - 10));
595 $accesstoken->scope = $this->scope;
596 // Also add the scopes.
597 self::$upgradedcodes[] = $code;
598 $this->store_token($accesstoken);
600 return true;
604 * Logs out of a oauth request, clearing any stored tokens
606 public function log_out() {
607 $this->store_token(null);
611 * Make a HTTP request, adding the access token we have
613 * @param string $url The URL to request
614 * @param array $options
615 * @param mixed $acceptheader mimetype (as string) or false to skip sending an accept header.
616 * @return bool
618 protected function request($url, $options = array(), $acceptheader = 'application/json') {
619 $murl = new moodle_url($url);
621 if ($this->accesstoken) {
622 if ($this->use_http_get()) {
623 // If using HTTP GET add as a parameter.
624 $murl->param('access_token', $this->accesstoken->token);
625 } else {
626 $this->setHeader('Authorization: Bearer '.$this->accesstoken->token);
630 if ($acceptheader) {
631 $this->setHeader('Accept: ' . $acceptheader);
634 $response = parent::request($murl->out(false), $options);
636 $this->resetHeader();
638 return $response;
642 * Multiple HTTP Requests
643 * This function could run multi-requests in parallel.
645 * @param array $requests An array of files to request
646 * @param array $options An array of options to set
647 * @return array An array of results
649 protected function multi($requests, $options = array()) {
650 if ($this->accesstoken) {
651 $this->setHeader('Authorization: Bearer '.$this->accesstoken->token);
653 return parent::multi($requests, $options);
657 * Returns the tokenname for the access_token to be stored
658 * through multiple requests.
660 * The default implentation is to use the classname combiend
661 * with the scope.
663 * @return string tokenname for prefernce storage
665 protected function get_tokenname() {
666 // This is unusual but should work for most purposes.
667 return get_class($this).'-'.md5($this->scope);
671 * Store a token between requests. Currently uses
672 * session named by get_tokenname
674 * @param stdClass|null $token token object to store or null to clear
676 protected function store_token($token) {
677 global $SESSION;
679 $this->accesstoken = $token;
680 $name = $this->get_tokenname();
682 if ($token !== null) {
683 $SESSION->{$name} = $token;
684 } else {
685 unset($SESSION->{$name});
690 * Get a refresh token!!!
692 * @return string
694 public function get_refresh_token() {
695 return $this->refreshtoken;
699 * Retrieve a token stored.
701 * @return stdClass|null token object
703 protected function get_stored_token() {
704 global $SESSION;
706 $name = $this->get_tokenname();
708 if (isset($SESSION->{$name})) {
709 return $SESSION->{$name};
712 return null;
716 * Get access token.
718 * This is just a getter to read the private property.
720 * @return string
722 public function get_accesstoken() {
723 return $this->accesstoken;
727 * Get the client ID.
729 * This is just a getter to read the private property.
731 * @return string
733 public function get_clientid() {
734 return $this->clientid;
738 * Get the client secret.
740 * This is just a getter to read the private property.
742 * @return string
744 public function get_clientsecret() {
745 return $this->clientsecret;
749 * Should HTTP GET be used instead of POST?
750 * Some APIs do not support POST and want oauth to use
751 * GET instead (with the auth_token passed as a GET param).
753 * @return bool true if GET should be used
755 protected function use_http_get() {
756 return false;