MDL-46963 environment: add check for antelope row format
[moodle.git] / login / token.php
blobee4d6cacc5ded2bfa88e69ce4d1511110444371c
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/>.
17 /**
18 * Return token
19 * @package moodlecore
20 * @copyright 2011 Dongsheng Cai <dongsheng@moodle.com>
21 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 define('AJAX_SCRIPT', true);
25 define('REQUIRE_CORRECT_ACCESS', true);
26 define('NO_MOODLE_COOKIES', true);
28 require_once(dirname(dirname(__FILE__)) . '/config.php');
30 $username = required_param('username', PARAM_USERNAME);
31 $password = required_param('password', PARAM_RAW);
32 $serviceshortname = required_param('service', PARAM_ALPHANUMEXT);
34 echo $OUTPUT->header();
36 if (!$CFG->enablewebservices) {
37 throw new moodle_exception('enablewsdescription', 'webservice');
39 $username = trim(core_text::strtolower($username));
40 if (is_restored_user($username)) {
41 throw new moodle_exception('restoredaccountresetpassword', 'webservice');
43 $user = authenticate_user_login($username, $password);
44 if (!empty($user)) {
46 //Non admin can not authenticate if maintenance mode
47 $hassiteconfig = has_capability('moodle/site:config', context_system::instance(), $user);
48 if (!empty($CFG->maintenance_enabled) and !$hassiteconfig) {
49 throw new moodle_exception('sitemaintenance', 'admin');
52 if (isguestuser($user)) {
53 throw new moodle_exception('noguest');
55 if (empty($user->confirmed)) {
56 throw new moodle_exception('usernotconfirmed', 'moodle', '', $user->username);
58 // check credential expiry
59 $userauth = get_auth_plugin($user->auth);
60 if (!empty($userauth->config->expiration) and $userauth->config->expiration == 1) {
61 $days2expire = $userauth->password_expire($user->username);
62 if (intval($days2expire) < 0 ) {
63 throw new moodle_exception('passwordisexpired', 'webservice');
67 // Check whether the user should be changing password.
68 if (get_user_preferences('auth_forcepasswordchange', false, $user)) {
69 if ($userauth->can_change_password()) {
70 throw new moodle_exception('forcepasswordchangenotice');
71 } else {
72 throw new moodle_exception('nopasswordchangeforced', 'auth');
76 // let enrol plugins deal with new enrolments if necessary
77 enrol_check_plugins($user);
79 // setup user session to check capability
80 \core\session\manager::set_user($user);
82 //check if the service exists and is enabled
83 $service = $DB->get_record('external_services', array('shortname' => $serviceshortname, 'enabled' => 1));
84 if (empty($service)) {
85 // will throw exception if no token found
86 throw new moodle_exception('servicenotavailable', 'webservice');
89 //check if there is any required system capability
90 if ($service->requiredcapability and !has_capability($service->requiredcapability, context_system::instance(), $user)) {
91 throw new moodle_exception('missingrequiredcapability', 'webservice', '', $service->requiredcapability);
94 //specific checks related to user restricted service
95 if ($service->restrictedusers) {
96 $authoriseduser = $DB->get_record('external_services_users',
97 array('externalserviceid' => $service->id, 'userid' => $user->id));
99 if (empty($authoriseduser)) {
100 throw new moodle_exception('usernotallowed', 'webservice', '', $serviceshortname);
103 if (!empty($authoriseduser->validuntil) and $authoriseduser->validuntil < time()) {
104 throw new moodle_exception('invalidtimedtoken', 'webservice');
107 if (!empty($authoriseduser->iprestriction) and !address_in_subnet(getremoteaddr(), $authoriseduser->iprestriction)) {
108 throw new moodle_exception('invalidiptoken', 'webservice');
112 //Check if a token has already been created for this user and this service
113 //Note: this could be an admin created or an user created token.
114 // It does not really matter we take the first one that is valid.
115 $tokenssql = "SELECT t.id, t.sid, t.token, t.validuntil, t.iprestriction
116 FROM {external_tokens} t
117 WHERE t.userid = ? AND t.externalserviceid = ? AND t.tokentype = ?
118 ORDER BY t.timecreated ASC";
119 $tokens = $DB->get_records_sql($tokenssql, array($user->id, $service->id, EXTERNAL_TOKEN_PERMANENT));
121 //A bit of sanity checks
122 foreach ($tokens as $key=>$token) {
124 /// Checks related to a specific token. (script execution continue)
125 $unsettoken = false;
126 //if sid is set then there must be a valid associated session no matter the token type
127 if (!empty($token->sid)) {
128 if (!\core\session\manager::session_exists($token->sid)){
129 //this token will never be valid anymore, delete it
130 $DB->delete_records('external_tokens', array('sid'=>$token->sid));
131 $unsettoken = true;
135 //remove token if no valid anymore
136 //Also delete this wrong token (similar logic to the web service servers
137 // /webservice/lib.php/webservice_server::authenticate_by_token())
138 if (!empty($token->validuntil) and $token->validuntil < time()) {
139 $DB->delete_records('external_tokens', array('token'=>$token->token, 'tokentype'=> EXTERNAL_TOKEN_PERMANENT));
140 $unsettoken = true;
143 // remove token if its ip not in whitelist
144 if (isset($token->iprestriction) and !address_in_subnet(getremoteaddr(), $token->iprestriction)) {
145 $unsettoken = true;
148 if ($unsettoken) {
149 unset($tokens[$key]);
153 // if some valid tokens exist then use the most recent
154 if (count($tokens) > 0) {
155 $token = array_pop($tokens);
156 } else {
157 if ( ($serviceshortname == MOODLE_OFFICIAL_MOBILE_SERVICE and has_capability('moodle/webservice:createmobiletoken', context_system::instance()))
158 //Note: automatically token generation is not available to admin (they must create a token manually)
159 or (!is_siteadmin($user) && has_capability('moodle/webservice:createtoken', context_system::instance()))) {
160 // if service doesn't exist, dml will throw exception
161 $service_record = $DB->get_record('external_services', array('shortname'=>$serviceshortname, 'enabled'=>1), '*', MUST_EXIST);
163 // Create a new token.
164 $token = new stdClass;
165 $token->token = md5(uniqid(rand(), 1));
166 $token->userid = $user->id;
167 $token->tokentype = EXTERNAL_TOKEN_PERMANENT;
168 $token->contextid = context_system::instance()->id;
169 $token->creatorid = $user->id;
170 $token->timecreated = time();
171 $token->externalserviceid = $service_record->id;
172 // MDL-43119 Token valid for 3 months (12 weeks).
173 $token->validuntil = $token->timecreated + 12 * WEEKSECS;
174 $token->id = $DB->insert_record('external_tokens', $token);
176 $params = array(
177 'objectid' => $token->id,
178 'relateduserid' => $user->id,
179 'other' => array(
180 'auto' => true
183 $event = \core\event\webservice_token_created::create($params);
184 $event->add_record_snapshot('external_tokens', $token);
185 $event->trigger();
186 } else {
187 throw new moodle_exception('cannotcreatetoken', 'webservice', '', $serviceshortname);
191 // log token access
192 $DB->set_field('external_tokens', 'lastaccess', time(), array('id'=>$token->id));
194 $params = array(
195 'objectid' => $token->id,
197 $event = \core\event\webservice_token_sent::create($params);
198 $event->add_record_snapshot('external_tokens', $token);
199 $event->trigger();
201 $usertoken = new stdClass;
202 $usertoken->token = $token->token;
203 echo json_encode($usertoken);
204 } else {
205 throw new moodle_exception('usernamenotfound', 'moodle');