MDL-58489 core: Fix unreachable HTTP error handling
[moodle.git] / lib / classes / oauth2 / client.php
CommitLineData
60237253
DW
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.
13//
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/>.
16
17/**
18 * Configurable oauth2 client class.
19 *
72fd103a 20 * @package core
60237253
DW
21 * @copyright 2017 Damyon Wiese
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 */
24namespace core\oauth2;
25
26defined('MOODLE_INTERNAL') || die();
27
28require_once($CFG->libdir . '/oauthlib.php');
29require_once($CFG->libdir . '/filelib.php');
30
31use moodle_url;
32use curl;
8445556b 33use stdClass;
60237253
DW
34
35/**
36 * Configurable oauth2 client class where the urls come from DB.
37 *
38 * @copyright 2017 Damyon Wiese
39 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
40 */
485a22fc 41class client extends \oauth2_client {
60237253
DW
42
43 /** @var \core\oauth2\issuer $issuer */
44 private $issuer;
45
46 /** @var bool $system */
47 protected $system = false;
48
49 /**
50 * Constructor.
51 *
52 * @param issuer $issuer
931c0234
DW
53 * @param moodle_url|null $returnurl
54 * @param string $scopesrequired
55 * @param boolean $system
60237253 56 */
931c0234 57 public function __construct(issuer $issuer, $returnurl, $scopesrequired, $system = false) {
60237253
DW
58 $this->issuer = $issuer;
59 $this->system = $system;
60 $scopes = $this->get_login_scopes();
61 $additionalscopes = explode(' ', $scopesrequired);
62
63 foreach ($additionalscopes as $scope) {
485a22fc
DW
64 if (!empty($scope)) {
65 if (strpos(' ' . $scopes . ' ', ' ' . $scope . ' ') === false) {
66 $scopes .= ' ' . $scope;
67 }
60237253
DW
68 }
69 }
931c0234
DW
70 if (empty($returnurl)) {
71 $returnurl = new moodle_url('/');
72 }
60237253
DW
73 parent::__construct($issuer->get('clientid'), $issuer->get('clientsecret'), $returnurl, $scopes);
74 }
75
60237253
DW
76 /**
77 * Returns the auth url for OAuth 2.0 request
78 * @return string the auth url
79 */
80 protected function auth_url() {
81 return $this->issuer->get_endpoint_url('authorization');
82 }
83
8445556b
DW
84 /**
85 * Get the oauth2 issuer for this client.
86 *
87 * @return \core\oauth2\issuer Issuer
88 */
89 public function get_issuer() {
60237253
DW
90 return $this->issuer;
91 }
92
8445556b
DW
93 /**
94 * Override to append additional params to a authentication request.
95 *
96 * @return array (name value pairs).
97 */
60237253 98 public function get_additional_login_parameters() {
485a22fc
DW
99 $params = '';
100 if ($this->system) {
101 if (!empty($this->issuer->get('loginparamsoffline'))) {
102 $params = $this->issuer->get('loginparamsoffline');
103 }
104 } else {
105 if (!empty($this->issuer->get('loginparams'))) {
106 $params = $this->issuer->get('loginparams');
107 }
108 }
109 if (empty($params)) {
110 return [];
111 }
112 $result = [];
113 parse_str($params, $result);
114 return $result;
60237253
DW
115 }
116
8445556b
DW
117 /**
118 * Override to change the scopes requested with an authentiction request.
119 *
120 * @return string
121 */
60237253 122 protected function get_login_scopes() {
485a22fc
DW
123 if ($this->system) {
124 return $this->issuer->get('loginscopesoffline');
125 } else {
126 return $this->issuer->get('loginscopes');
127 }
60237253
DW
128 }
129
130 /**
131 * Returns the token url for OAuth 2.0 request
8445556b
DW
132 *
133 * We are overriding the parent function so we get this from the configured endpoint.
134 *
60237253
DW
135 * @return string the auth url
136 */
137 protected function token_url() {
138 return $this->issuer->get_endpoint_url('token');
139 }
140
8445556b
DW
141 /**
142 * We want a unique key for each issuer / and a different key for system vs user oauth.
143 *
144 * @return string The unique key for the session value.
145 */
60237253 146 protected function get_tokenname() {
8445556b 147 $name = 'oauth2-state-' . $this->issuer->get('id');
60237253
DW
148 if ($this->system) {
149 $name .= '-system';
150 }
151 return $name;
152 }
153
f9f243f9
DW
154 /**
155 * Get a list of the mapping user fields in an associative array.
156 *
157 * @return array
158 */
8445556b
DW
159 protected function get_userinfo_mapping() {
160 $fields = user_field_mapping::get_records(['issuerid' => $this->issuer->get('id')]);
161
162 $map = [];
163 foreach ($fields as $field) {
164 $map[$field->get('externalfield')] = $field->get('internalfield');
165 }
166 return $map;
167 }
168
237fd80c
DW
169 /**
170 * Upgrade a refresh token from oauth 2.0 to an access token
171 *
29911249 172 * @param \core\oauth2\system_account $systemaccount
237fd80c
DW
173 * @return boolean true if token is upgraded succesfully
174 */
175 public function upgrade_refresh_token(system_account $systemaccount) {
176 $refreshtoken = $systemaccount->get('refreshtoken');
177
178 $params = array('refresh_token' => $refreshtoken,
931c0234
DW
179 'client_id' => $this->issuer->get('clientid'),
180 'client_secret' => $this->issuer->get('clientsecret'),
237fd80c
DW
181 'grant_type' => 'refresh_token'
182 );
183
184 // Requests can either use http GET or POST.
185 if ($this->use_http_get()) {
186 $response = $this->get($this->token_url(), $params);
187 } else {
188 $response = $this->post($this->token_url(), $this->build_post_data($params));
189 }
190
eb4ab7c4 191 if ($this->info['http_code'] !== 200) {
237fd80c
DW
192 throw new moodle_exception('Could not upgrade oauth token');
193 }
194
195 $r = json_decode($response);
196
197 if (!empty($r->error)) {
198 throw new moodle_exception($r->error . ' ' . $r->error_description);
199 }
200
201 if (!isset($r->access_token)) {
202 return false;
203 }
204
205 if (isset($r->refresh_token)) {
206 $systemaccount->set('refreshtoken', $r->refresh_token);
207 $systemaccount->update();
208 $this->refreshtoken = $r->refresh_token;
209 }
210
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));
217 }
218 if (isset($r->scope)) {
219 $accesstoken->scope = $r->scope;
220 } else {
221 $accesstoken->scope = $this->scope;
222 }
223 // Also add the scopes.
224 $this->store_token($accesstoken);
225
226 return true;
227 }
228
f9f243f9
DW
229 /**
230 * Fetch the user info from the user info endpoint and map all
231 * the fields back into moodle fields.
232 *
233 * @return array (Moodle user fields for the logged in user).
234 */
8445556b
DW
235 public function get_userinfo() {
236 $url = $this->get_issuer()->get_endpoint_url('userinfo');
237 $response = $this->get($url);
238 if (!$response) {
239 return false;
240 }
241 $userinfo = new stdClass();
242 try {
243 $userinfo = json_decode($response);
244 } catch (Exception $e) {
245 return false;
246 }
247
248 $map = $this->get_userinfo_mapping();
249
250 $user = new stdClass();
251 foreach ($map as $openidproperty => $moodleproperty) {
485a22fc
DW
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]})) {
256 return false;
257 }
258 $obj = $obj->{$proplist[0]};
259
260 if (count($proplist) > 1) {
261 return $getfunc($obj, $proplist[1]);
262 }
263 return $obj;
264 };
265
266 $resolved = $getfunc($userinfo, $openidproperty);
267 if (!empty($resolved)) {
268 $user->$moodleproperty = $resolved;
8445556b
DW
269 }
270 }
271
7f158660
DW
272 if (empty($user->username) && !empty($user->email)) {
273 $user->username = $user->email;
274 }
275
8445556b
DW
276 if (!empty($user->picture)) {
277 $user->picture = download_file_content($user->picture, null, null, false, 10, 10, true, null, false);
278 } else {
279 $pictureurl = $this->issuer->get_endpoint_url('userpicture');
280 if (!empty($pictureurl)) {
281 $user->picture = $this->get($pictureurl);
282 }
283 }
284
14cfd280
DW
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);
289 if (empty($img)) {
290 unset($user->picture);
291 } else {
292 imagedestroy($img);
293 }
294 }
295 }
296
8445556b
DW
297 return (array)$user;
298 }
60237253 299}