MDL-50613 webservices: Upgrade info about riskbitmask
[moodle.git] / login / token.php
blob54e9be146c775c235567a5685553af1d944e930d
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 // Allow CORS requests.
35 header('Access-Control-Allow-Origin: *');
36 echo $OUTPUT->header();
38 if (!$CFG->enablewebservices) {
39 throw new moodle_exception('enablewsdescription', 'webservice');
41 $username = trim(core_text::strtolower($username));
42 if (is_restored_user($username)) {
43 throw new moodle_exception('restoredaccountresetpassword', 'webservice');
45 $user = authenticate_user_login($username, $password);
46 if (!empty($user)) {
48 //Non admin can not authenticate if maintenance mode
49 $hassiteconfig = has_capability('moodle/site:config', context_system::instance(), $user);
50 if (!empty($CFG->maintenance_enabled) and !$hassiteconfig) {
51 throw new moodle_exception('sitemaintenance', 'admin');
54 if (isguestuser($user)) {
55 throw new moodle_exception('noguest');
57 if (empty($user->confirmed)) {
58 throw new moodle_exception('usernotconfirmed', 'moodle', '', $user->username);
60 // check credential expiry
61 $userauth = get_auth_plugin($user->auth);
62 if (!empty($userauth->config->expiration) and $userauth->config->expiration == 1) {
63 $days2expire = $userauth->password_expire($user->username);
64 if (intval($days2expire) < 0 ) {
65 throw new moodle_exception('passwordisexpired', 'webservice');
69 // Check whether the user should be changing password.
70 if (get_user_preferences('auth_forcepasswordchange', false, $user)) {
71 if ($userauth->can_change_password()) {
72 throw new moodle_exception('forcepasswordchangenotice');
73 } else {
74 throw new moodle_exception('nopasswordchangeforced', 'auth');
78 // let enrol plugins deal with new enrolments if necessary
79 enrol_check_plugins($user);
81 // setup user session to check capability
82 \core\session\manager::set_user($user);
84 //check if the service exists and is enabled
85 $service = $DB->get_record('external_services', array('shortname' => $serviceshortname, 'enabled' => 1));
86 if (empty($service)) {
87 // will throw exception if no token found
88 throw new moodle_exception('servicenotavailable', 'webservice');
91 //check if there is any required system capability
92 if ($service->requiredcapability and !has_capability($service->requiredcapability, context_system::instance(), $user)) {
93 throw new moodle_exception('missingrequiredcapability', 'webservice', '', $service->requiredcapability);
96 //specific checks related to user restricted service
97 if ($service->restrictedusers) {
98 $authoriseduser = $DB->get_record('external_services_users',
99 array('externalserviceid' => $service->id, 'userid' => $user->id));
101 if (empty($authoriseduser)) {
102 throw new moodle_exception('usernotallowed', 'webservice', '', $serviceshortname);
105 if (!empty($authoriseduser->validuntil) and $authoriseduser->validuntil < time()) {
106 throw new moodle_exception('invalidtimedtoken', 'webservice');
109 if (!empty($authoriseduser->iprestriction) and !address_in_subnet(getremoteaddr(), $authoriseduser->iprestriction)) {
110 throw new moodle_exception('invalidiptoken', 'webservice');
114 //Check if a token has already been created for this user and this service
115 //Note: this could be an admin created or an user created token.
116 // It does not really matter we take the first one that is valid.
117 $tokenssql = "SELECT t.id, t.sid, t.token, t.validuntil, t.iprestriction
118 FROM {external_tokens} t
119 WHERE t.userid = ? AND t.externalserviceid = ? AND t.tokentype = ?
120 ORDER BY t.timecreated ASC";
121 $tokens = $DB->get_records_sql($tokenssql, array($user->id, $service->id, EXTERNAL_TOKEN_PERMANENT));
123 //A bit of sanity checks
124 foreach ($tokens as $key=>$token) {
126 /// Checks related to a specific token. (script execution continue)
127 $unsettoken = false;
128 //if sid is set then there must be a valid associated session no matter the token type
129 if (!empty($token->sid)) {
130 if (!\core\session\manager::session_exists($token->sid)){
131 //this token will never be valid anymore, delete it
132 $DB->delete_records('external_tokens', array('sid'=>$token->sid));
133 $unsettoken = true;
137 //remove token if no valid anymore
138 //Also delete this wrong token (similar logic to the web service servers
139 // /webservice/lib.php/webservice_server::authenticate_by_token())
140 if (!empty($token->validuntil) and $token->validuntil < time()) {
141 $DB->delete_records('external_tokens', array('token'=>$token->token, 'tokentype'=> EXTERNAL_TOKEN_PERMANENT));
142 $unsettoken = true;
145 // remove token if its ip not in whitelist
146 if (isset($token->iprestriction) and !address_in_subnet(getremoteaddr(), $token->iprestriction)) {
147 $unsettoken = true;
150 if ($unsettoken) {
151 unset($tokens[$key]);
155 // if some valid tokens exist then use the most recent
156 if (count($tokens) > 0) {
157 $token = array_pop($tokens);
158 } else {
159 if ( ($serviceshortname == MOODLE_OFFICIAL_MOBILE_SERVICE and has_capability('moodle/webservice:createmobiletoken', context_system::instance()))
160 //Note: automatically token generation is not available to admin (they must create a token manually)
161 or (!is_siteadmin($user) && has_capability('moodle/webservice:createtoken', context_system::instance()))) {
162 // if service doesn't exist, dml will throw exception
163 $service_record = $DB->get_record('external_services', array('shortname'=>$serviceshortname, 'enabled'=>1), '*', MUST_EXIST);
165 // Create a new token.
166 $token = new stdClass;
167 $token->token = md5(uniqid(rand(), 1));
168 $token->userid = $user->id;
169 $token->tokentype = EXTERNAL_TOKEN_PERMANENT;
170 $token->contextid = context_system::instance()->id;
171 $token->creatorid = $user->id;
172 $token->timecreated = time();
173 $token->externalserviceid = $service_record->id;
174 // MDL-43119 Token valid for 3 months (12 weeks).
175 $token->validuntil = $token->timecreated + 12 * WEEKSECS;
176 $token->id = $DB->insert_record('external_tokens', $token);
178 $params = array(
179 'objectid' => $token->id,
180 'relateduserid' => $user->id,
181 'other' => array(
182 'auto' => true
185 $event = \core\event\webservice_token_created::create($params);
186 $event->add_record_snapshot('external_tokens', $token);
187 $event->trigger();
188 } else {
189 throw new moodle_exception('cannotcreatetoken', 'webservice', '', $serviceshortname);
193 // log token access
194 $DB->set_field('external_tokens', 'lastaccess', time(), array('id'=>$token->id));
196 $params = array(
197 'objectid' => $token->id,
199 $event = \core\event\webservice_token_sent::create($params);
200 $event->add_record_snapshot('external_tokens', $token);
201 $event->trigger();
203 $usertoken = new stdClass;
204 $usertoken->token = $token->token;
205 echo json_encode($usertoken);
206 } else {
207 throw new moodle_exception('usernamenotfound', 'moodle');