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/>.
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('NO_MOODLE_COOKIES', true);
27 require_once(dirname(dirname(__FILE__
)) . '/config.php');
29 $username = required_param('username', PARAM_USERNAME
);
30 $password = required_param('password', PARAM_RAW
);
31 $serviceshortname = required_param('service', PARAM_ALPHANUMEXT
);
33 echo $OUTPUT->header();
35 if (!$CFG->enablewebservices
) {
36 throw new moodle_exception('enablewsdescription', 'webservice');
38 $username = trim(textlib
::strtolower($username));
39 if (is_restored_user($username)) {
40 throw new moodle_exception('restoredaccountresetpassword', 'webservice');
42 $user = authenticate_user_login($username, $password);
45 //Non admin can not authenticate if maintenance mode
46 $hassiteconfig = has_capability('moodle/site:config', context_system
::instance(), $user);
47 if (!empty($CFG->maintenance_enabled
) and !$hassiteconfig) {
48 throw new moodle_exception('sitemaintenance', 'admin');
51 if (isguestuser($user)) {
52 throw new moodle_exception('noguest');
54 if (empty($user->confirmed
)) {
55 throw new moodle_exception('usernotconfirmed', 'moodle', '', $user->username
);
57 // check credential expiry
58 $userauth = get_auth_plugin($user->auth
);
59 if (!empty($userauth->config
->expiration
) and $userauth->config
->expiration
== 1) {
60 $days2expire = $userauth->password_expire($user->username
);
61 if (intval($days2expire) < 0 ) {
62 throw new moodle_exception('passwordisexpired', 'webservice');
66 // let enrol plugins deal with new enrolments if necessary
67 enrol_check_plugins($user);
69 // setup user session to check capability
70 session_set_user($user);
72 //check if the service exists and is enabled
73 $service = $DB->get_record('external_services', array('shortname' => $serviceshortname, 'enabled' => 1));
74 if (empty($service)) {
75 // will throw exception if no token found
76 throw new moodle_exception('servicenotavailable', 'webservice');
79 //check if there is any required system capability
80 if ($service->requiredcapability
and !has_capability($service->requiredcapability
, context_system
::instance(), $user)) {
81 throw new moodle_exception('missingrequiredcapability', 'webservice', '', $service->requiredcapability
);
84 //specific checks related to user restricted service
85 if ($service->restrictedusers
) {
86 $authoriseduser = $DB->get_record('external_services_users',
87 array('externalserviceid' => $service->id
, 'userid' => $user->id
));
89 if (empty($authoriseduser)) {
90 throw new moodle_exception('usernotallowed', 'webservice', '', $serviceshortname);
93 if (!empty($authoriseduser->validuntil
) and $authoriseduser->validuntil
< time()) {
94 throw new moodle_exception('invalidtimedtoken', 'webservice');
97 if (!empty($authoriseduser->iprestriction
) and !address_in_subnet(getremoteaddr(), $authoriseduser->iprestriction
)) {
98 throw new moodle_exception('invalidiptoken', 'webservice');
102 //Check if a token has already been created for this user and this service
103 //Note: this could be an admin created or an user created token.
104 // It does not really matter we take the first one that is valid.
105 $tokenssql = "SELECT t.id, t.sid, t.token, t.validuntil, t.iprestriction
106 FROM {external_tokens} t
107 WHERE t.userid = ? AND t.externalserviceid = ? AND t.tokentype = ?
108 ORDER BY t.timecreated ASC";
109 $tokens = $DB->get_records_sql($tokenssql, array($user->id
, $service->id
, EXTERNAL_TOKEN_PERMANENT
));
111 //A bit of sanity checks
112 foreach ($tokens as $key=>$token) {
114 /// Checks related to a specific token. (script execution continue)
116 //if sid is set then there must be a valid associated session no matter the token type
117 if (!empty($token->sid
)) {
118 $session = session_get_instance();
119 if (!$session->session_exists($token->sid
)){
120 //this token will never be valid anymore, delete it
121 $DB->delete_records('external_tokens', array('sid'=>$token->sid
));
126 //remove token if no valid anymore
127 //Also delete this wrong token (similar logic to the web service servers
128 // /webservice/lib.php/webservice_server::authenticate_by_token())
129 if (!empty($token->validuntil
) and $token->validuntil
< time()) {
130 $DB->delete_records('external_tokens', array('token'=>$token->token
, 'tokentype'=> EXTERNAL_TOKEN_PERMANENT
));
134 // remove token if its ip not in whitelist
135 if (isset($token->iprestriction
) and !address_in_subnet(getremoteaddr(), $token->iprestriction
)) {
140 unset($tokens[$key]);
144 // if some valid tokens exist then use the most recent
145 if (count($tokens) > 0) {
146 $token = array_pop($tokens);
148 if ( ($serviceshortname == MOODLE_OFFICIAL_MOBILE_SERVICE
and has_capability('moodle/webservice:createmobiletoken', get_system_context()))
149 //Note: automatically token generation is not available to admin (they must create a token manually)
150 or (!is_siteadmin($user) && has_capability('moodle/webservice:createtoken', get_system_context()))) {
151 // if service doesn't exist, dml will throw exception
152 $service_record = $DB->get_record('external_services', array('shortname'=>$serviceshortname, 'enabled'=>1), '*', MUST_EXIST
);
153 // create a new token
154 $token = new stdClass
;
155 $token->token
= md5(uniqid(rand(), 1));
156 $token->userid
= $user->id
;
157 $token->tokentype
= EXTERNAL_TOKEN_PERMANENT
;
158 $token->contextid
= context_system
::instance()->id
;
159 $token->creatorid
= $user->id
;
160 $token->timecreated
= time();
161 $token->externalserviceid
= $service_record->id
;
162 $tokenid = $DB->insert_record('external_tokens', $token);
163 add_to_log(SITEID
, 'webservice', get_string('createtokenforuserauto', 'webservice'), '' , 'User ID: ' . $user->id
);
164 $token->id
= $tokenid;
166 throw new moodle_exception('cannotcreatetoken', 'webservice', '', $serviceshortname);
171 $DB->set_field('external_tokens', 'lastaccess', time(), array('id'=>$token->id
));
173 add_to_log(SITEID
, 'webservice', 'user request webservice token', '' , 'User ID: ' . $user->id
);
175 $usertoken = new stdClass
;
176 $usertoken->token
= $token->token
;
177 echo json_encode($usertoken);
179 throw new moodle_exception('usernamenotfound', 'moodle');