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 * This file allows for testing of login via configured oauth2 IDP poviders.
20 * @package auth_oauth2
21 * @copyright 2021 Matt Porritt <mattp@catalyst-au.net>
22 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
25 // Require_login is not needed here.
26 // phpcs:disable moodle.Files.RequireLogin.Missing
27 require_once('../../config.php');
31 $issuerid = required_param('id', PARAM_INT
);
32 $url = new moodle_url('/auth/oauth2/test.php', ['id' => $issuerid, 'sesskey' => sesskey()]);
34 $PAGE->set_context(context_system
::instance());
36 $PAGE->set_pagelayout('admin');
38 if (!\auth_oauth
2\api
::is_enabled()) {
39 throw new \
moodle_exception('notenabled', 'auth_oauth2');
42 $issuer = new \core\oauth2\
issuer($issuerid);
43 if (!$issuer->is_available_for_login()) {
44 throw new \
moodle_exception('issuernologin', 'auth_oauth2');
47 $client = \core\oauth2\api
::get_user_oauth_client($issuer, $url);
50 // We have a valid client, now lets see if we can log into the IDP.
51 if (!$client->is_logged_in()) {
52 redirect($client->get_login_url());
55 echo $OUTPUT->header();
57 // We were successful logging into the IDP.
58 echo $OUTPUT->notification(get_string('loggedin', 'auth_oauth2'), 'notifysuccess');
60 // Try getting user info from the IDP.
61 $endpointurl = $client->get_issuer()->get_endpoint_url('userinfo');
62 $response = $client->get($endpointurl);
63 $userinfo = json_decode($response, true);
66 foreach ($userinfo as $key => $value) {
67 // We are just displaying the data from the IdP for testing purposes,
68 // so we are more interested in displaying it to the admin than
70 if (is_array($value)) {
71 $value = json_encode($value);
73 $templateinfo[] = ['name' => $key, 'value' => $value];
77 if (!empty($templateinfo)) {
78 echo $OUTPUT->render_from_template('auth_oauth2/idpresponse', ['pairs' => $templateinfo]);
82 throw new moodle_exception('Could not get an OAuth client.');
85 echo $OUTPUT->footer();