2 // This file is part of Moodle - http://moodle.org/
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.
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 * Configurable oauth2 client class.
21 * @copyright 2017 Damyon Wiese
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 namespace core\oauth2;
26 defined('MOODLE_INTERNAL') || die();
28 require_once($CFG->libdir . '/oauthlib.php');
29 require_once($CFG->libdir . '/filelib.php');
36 * Configurable oauth2 client class where the urls come from DB.
38 * @copyright 2017 Damyon Wiese
39 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
41 class client extends \oauth2_client {
43 /** @var \core\oauth2\issuer $issuer */
46 /** @var bool $system */
47 protected $system = false;
52 * @param issuer $issuer
53 * @param moodle_url|null $returnurl
54 * @param string $scopesrequired
55 * @param boolean $system
57 public function __construct(issuer $issuer, $returnurl, $scopesrequired, $system = false) {
58 $this->issuer = $issuer;
59 $this->system = $system;
60 $scopes = $this->get_login_scopes();
61 $additionalscopes = explode(' ', $scopesrequired);
63 foreach ($additionalscopes as $scope) {
65 if (strpos(' ' . $scopes . ' ', ' ' . $scope . ' ') === false) {
66 $scopes .= ' ' . $scope;
70 if (empty($returnurl)) {
71 $returnurl = new moodle_url('/');
73 parent::__construct($issuer->get('clientid'), $issuer->get('clientsecret'), $returnurl, $scopes);
77 * Returns the auth url for OAuth 2.0 request
78 * @return string the auth url
80 protected function auth_url() {
81 return $this->issuer->get_endpoint_url('authorization');
85 * Get the oauth2 issuer for this client.
87 * @return \core\oauth2\issuer Issuer
89 public function get_issuer() {
94 * Override to append additional params to a authentication request.
96 * @return array (name value pairs).
98 public function get_additional_login_parameters() {
101 if (!empty($this->issuer->get('loginparamsoffline'))) {
102 $params = $this->issuer->get('loginparamsoffline');
105 if (!empty($this->issuer->get('loginparams'))) {
106 $params = $this->issuer->get('loginparams');
109 if (empty($params)) {
113 parse_str($params, $result);
118 * Override to change the scopes requested with an authentiction request.
122 protected function get_login_scopes() {
124 return $this->issuer->get('loginscopesoffline');
126 return $this->issuer->get('loginscopes');
131 * Returns the token url for OAuth 2.0 request
133 * We are overriding the parent function so we get this from the configured endpoint.
135 * @return string the auth url
137 protected function token_url() {
138 return $this->issuer->get_endpoint_url('token');
142 * We want a unique key for each issuer / and a different key for system vs user oauth.
144 * @return string The unique key for the session value.
146 protected function get_tokenname() {
147 $name = 'oauth2-state-' . $this->issuer->get('id');
155 * Get a list of the mapping user fields in an associative array.
159 protected function get_userinfo_mapping() {
160 $fields = user_field_mapping::get_records(['issuerid' => $this->issuer->get('id')]);
163 foreach ($fields as $field) {
164 $map[$field->get('externalfield')] = $field->get('internalfield');
170 * Upgrade a refresh token from oauth 2.0 to an access token
172 * @param \core\oauth2\system_account $systemaccount
173 * @return boolean true if token is upgraded succesfully
175 public function upgrade_refresh_token(system_account $systemaccount) {
176 $refreshtoken = $systemaccount->get('refreshtoken');
178 $params = array('refresh_token' => $refreshtoken,
179 'client_id' => $this->issuer->get('clientid'),
180 'client_secret' => $this->issuer->get('clientsecret'),
181 'grant_type' => 'refresh_token'
184 // Requests can either use http GET or POST.
185 if ($this->use_http_get()) {
186 $response = $this->get($this->token_url(), $params);
188 $response = $this->post($this->token_url(), $this->build_post_data($params));
191 if ($this->info['http_code'] !== 200) {
192 throw new moodle_exception('Could not upgrade oauth token');
195 $r = json_decode($response);
197 if (!empty($r->error)) {
198 throw new moodle_exception($r->error . ' ' . $r->error_description);
201 if (!isset($r->access_token)) {
205 if (isset($r->refresh_token)) {
206 $systemaccount->set('refreshtoken', $r->refresh_token);
207 $systemaccount->update();
208 $this->refreshtoken = $r->refresh_token;
211 // Store the token an expiry time.
212 $accesstoken = new stdClass;
213 $accesstoken->token = $r->access_token;
214 if (isset($r->expires_in)) {
215 // Expires 10 seconds before actual expiry.
216 $accesstoken->expires = (time() + ($r->expires_in - 10));
218 if (isset($r->scope)) {
219 $accesstoken->scope = $r->scope;
221 $accesstoken->scope = $this->scope;
223 // Also add the scopes.
224 $this->store_token($accesstoken);
230 * Fetch the user info from the user info endpoint and map all
231 * the fields back into moodle fields.
233 * @return array (Moodle user fields for the logged in user).
235 public function get_userinfo() {
236 $url = $this->get_issuer()->get_endpoint_url('userinfo');
237 $response = $this->get($url);
241 $userinfo = new stdClass();
243 $userinfo = json_decode($response);
244 } catch (Exception $e) {
248 $map = $this->get_userinfo_mapping();
250 $user = new stdClass();
251 foreach ($map as $openidproperty => $moodleproperty) {
252 // We support nested objects via a-b-c syntax.
253 $getfunc = function($obj, $prop) use (&$getfunc) {
254 $proplist = explode('-', $prop, 2);
255 if (empty($proplist[0]) || empty($obj->{$proplist[0]})) {
258 $obj = $obj->{$proplist[0]};
260 if (count($proplist) > 1) {
261 return $getfunc($obj, $proplist[1]);
266 $resolved = $getfunc($userinfo, $openidproperty);
267 if (!empty($resolved)) {
268 $user->$moodleproperty = $resolved;
272 if (empty($user->username) && !empty($user->email)) {
273 $user->username = $user->email;
276 if (!empty($user->picture)) {
277 $user->picture = download_file_content($user->picture, null, null, false, 10, 10, true, null, false);
279 $pictureurl = $this->issuer->get_endpoint_url('userpicture');
280 if (!empty($pictureurl)) {
281 $user->picture = $this->get($pictureurl);
285 if (!empty($user->picture)) {
286 // If it doesn't look like a picture lets unset it.
287 if (function_exists('imagecreatefromstring')) {
288 $img = @imagecreatefromstring($user->picture);
290 unset($user->picture);