Automatically generated installer lang files
[moodle.git] / login / token.php
CommitLineData
13ea96c4
DC
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 * 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
22 */
23
24define('AJAX_SCRIPT', true);
22e9de0f 25define('REQUIRE_CORRECT_ACCESS', true);
13ea96c4
DC
26define('NO_MOODLE_COOKIES', true);
27
28require_once(dirname(dirname(__FILE__)) . '/config.php');
29
9b9d7a60 30$username = required_param('username', PARAM_USERNAME);
13ea96c4 31$password = required_param('password', PARAM_RAW);
5b9735b9 32$serviceshortname = required_param('service', PARAM_ALPHANUMEXT);
13ea96c4
DC
33
34echo $OUTPUT->header();
35
36if (!$CFG->enablewebservices) {
37 throw new moodle_exception('enablewsdescription', 'webservice');
38}
6f3451e5 39$username = trim(textlib::strtolower($username));
13ea96c4
DC
40if (is_restored_user($username)) {
41 throw new moodle_exception('restoredaccountresetpassword', 'webservice');
42}
43$user = authenticate_user_login($username, $password);
44if (!empty($user)) {
07a90ec3
JM
45
46 //Non admin can not authenticate if maintenance mode
47 $hassiteconfig = has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM), $user);
48 if (!empty($CFG->maintenance_enabled) and !$hassiteconfig) {
49 throw new moodle_exception('sitemaintenance', 'admin');
50 }
51
13ea96c4
DC
52 if (isguestuser($user)) {
53 throw new moodle_exception('noguest');
54 }
55 if (empty($user->confirmed)) {
56 throw new moodle_exception('usernotconfirmed', 'moodle', '', $user->username);
57 }
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');
64 }
65 }
66
e922fe23
PS
67 // let enrol plugins deal with new enrolments if necessary
68 enrol_check_plugins($user);
69
13ea96c4
DC
70 // setup user session to check capability
71 session_set_user($user);
72
5b9735b9
JM
73 //check if the service exists and is enabled
74 $service = $DB->get_record('external_services', array('shortname' => $serviceshortname, 'enabled' => 1));
75 if (empty($service)) {
76 // will throw exception if no token found
77 throw new moodle_exception('servicenotavailable', 'webservice');
78 }
79
80 //check if there is any required system capability
81 if ($service->requiredcapability and !has_capability($service->requiredcapability, get_context_instance(CONTEXT_SYSTEM), $user)) {
82 throw new moodle_exception('missingrequiredcapability', 'webservice', '', $service->requiredcapability);
83 }
84
85 //specific checks related to user restricted service
86 if ($service->restrictedusers) {
87 $authoriseduser = $DB->get_record('external_services_users',
88 array('externalserviceid' => $service->id, 'userid' => $user->id));
89
90 if (empty($authoriseduser)) {
91 throw new moodle_exception('usernotallowed', 'webservice', '', $serviceshortname);
92 }
93
94 if (!empty($authoriseduser->validuntil) and $authoriseduser->validuntil < time()) {
95 throw new moodle_exception('invalidtimedtoken', 'webservice');
96 }
97
98 if (!empty($authoriseduser->iprestriction) and !address_in_subnet(getremoteaddr(), $authoriseduser->iprestriction)) {
99 throw new moodle_exception('invalidiptoken', 'webservice');
100 }
101 }
102
103 //Check if a token has already been created for this user and this service
104 //Note: this could be an admin created or an user created token.
105 // It does not really matter we take the first one that is valid.
dab3977a 106 $tokenssql = "SELECT t.id, t.sid, t.token, t.validuntil, t.iprestriction
13ea96c4 107 FROM {external_tokens} t
2b8fe35b 108 WHERE t.userid = ? AND t.externalserviceid = ? AND t.tokentype = ?
13ea96c4 109 ORDER BY t.timecreated ASC";
2b8fe35b 110 $tokens = $DB->get_records_sql($tokenssql, array($user->id, $service->id, EXTERNAL_TOKEN_PERMANENT));
5b9735b9
JM
111
112 //A bit of sanity checks
113 foreach ($tokens as $key=>$token) {
114
115 /// Checks related to a specific token. (script execution continue)
116 $unsettoken = false;
117 //if sid is set then there must be a valid associated session no matter the token type
118 if (!empty($token->sid)) {
119 $session = session_get_instance();
120 if (!$session->session_exists($token->sid)){
121 //this token will never be valid anymore, delete it
122 $DB->delete_records('external_tokens', array('sid'=>$token->sid));
123 $unsettoken = true;
124 }
125 }
126
127 //remove token if no valid anymore
128 //Also delete this wrong token (similar logic to the web service servers
129 // /webservice/lib.php/webservice_server::authenticate_by_token())
130 if (!empty($token->validuntil) and $token->validuntil < time()) {
131 $DB->delete_records('external_tokens', array('token'=>$token->token, 'tokentype'=> EXTERNAL_TOKEN_PERMANENT));
132 $unsettoken = true;
133 }
134
13ea96c4 135 // remove token if its ip not in whitelist
5b9735b9
JM
136 if (isset($token->iprestriction) and !address_in_subnet(getremoteaddr(), $token->iprestriction)) {
137 $unsettoken = true;
138 }
139
140 if ($unsettoken) {
13ea96c4
DC
141 unset($tokens[$key]);
142 }
143 }
5b9735b9
JM
144
145 // if some valid tokens exist then use the most recent
13ea96c4
DC
146 if (count($tokens) > 0) {
147 $token = array_pop($tokens);
148 } else {
5b9735b9
JM
149 if ( ($serviceshortname == MOODLE_OFFICIAL_MOBILE_SERVICE and has_capability('moodle/webservice:createmobiletoken', get_system_context()))
150 //Note: automatically token generation is not available to admin (they must create a token manually)
151 or (!is_siteadmin($user) && has_capability('moodle/webservice:createtoken', get_system_context()))) {
152 // if service doesn't exist, dml will throw exception
153 $service_record = $DB->get_record('external_services', array('shortname'=>$serviceshortname, 'enabled'=>1), '*', MUST_EXIST);
154 // create a new token
155 $token = new stdClass;
156 $token->token = md5(uniqid(rand(), 1));
157 $token->userid = $user->id;
158 $token->tokentype = EXTERNAL_TOKEN_PERMANENT;
159 $token->contextid = get_context_instance(CONTEXT_SYSTEM)->id;
160 $token->creatorid = $user->id;
161 $token->timecreated = time();
162 $token->externalserviceid = $service_record->id;
163 $tokenid = $DB->insert_record('external_tokens', $token);
aa578540 164 add_to_log(SITEID, 'webservice', 'automatically create user token', '' , 'User ID: ' . $user->id);
5b9735b9
JM
165 $token->id = $tokenid;
166 } else {
167 throw new moodle_exception('cannotcreatetoken', 'webservice', '', $serviceshortname);
13ea96c4
DC
168 }
169 }
170
171 // log token access
172 $DB->set_field('external_tokens', 'lastaccess', time(), array('id'=>$token->id));
173
13ea96c4 174 add_to_log(SITEID, 'webservice', 'user request webservice token', '' , 'User ID: ' . $user->id);
d8f85b6e
SH
175
176 $usertoken = new stdClass;
13ea96c4
DC
177 $usertoken->token = $token->token;
178 echo json_encode($usertoken);
179} else {
180 throw new moodle_exception('usernamenotfound', 'moodle');
9b9d7a60 181}