Merge branch 'MDL-27834' of git://github.com/kordan/moodle
[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);
25define('NO_MOODLE_COOKIES', true);
26
27require_once(dirname(dirname(__FILE__)) . '/config.php');
28
29$username = required_param('username', PARAM_USERNAME);
30$password = required_param('password', PARAM_RAW);
31$service = required_param('service', PARAM_ALPHANUMEXT);
32
33echo $OUTPUT->header();
34
35if (!$CFG->enablewebservices) {
36 throw new moodle_exception('enablewsdescription', 'webservice');
37}
38$username = trim(moodle_strtolower($username));
39if (is_restored_user($username)) {
40 throw new moodle_exception('restoredaccountresetpassword', 'webservice');
41}
42$user = authenticate_user_login($username, $password);
43if (!empty($user)) {
44 if (isguestuser($user)) {
45 throw new moodle_exception('noguest');
46 }
47 if (empty($user->confirmed)) {
48 throw new moodle_exception('usernotconfirmed', 'moodle', '', $user->username);
49 }
50 // check credential expiry
51 $userauth = get_auth_plugin($user->auth);
52 if (!empty($userauth->config->expiration) and $userauth->config->expiration == 1) {
53 $days2expire = $userauth->password_expire($user->username);
54 if (intval($days2expire) < 0 ) {
55 throw new moodle_exception('passwordisexpired', 'webservice');
56 }
57 }
58
59 // setup user session to check capability
60 session_set_user($user);
61
62 $admintokenssql = "SELECT t.*
63 FROM {external_tokens} t
64 JOIN {external_services} s
65 ON t.externalserviceid = s.id
66 WHERE s.shortname = ?
67 AND s.enabled = 1
68 AND t.userid = ?
69 AND (t.validuntil = 0 OR t.validuntil IS NULL OR t.validuntil > ?)
70 AND t.userid != t.creatorid
71 ORDER BY t.timecreated ASC";
72 $tokens = $DB->get_records_sql($admintokenssql, array($service, $user->id, time()));
73 foreach ($tokens as $key=>$admin_token) {
74 // remove token if its ip not in whitelist
75 if (isset($admin_token->iprestriction) and !address_in_subnet(getremoteaddr(), $admin_token->iprestriction)) {
76 unset($tokens[$key]);
77 }
78 }
79 // if admin created token then use the most recent created one over user created token
80 if (count($tokens) > 0) {
81 $token = array_pop($tokens);
82 } else {
83 // if no admin created tokens, try to use user created token
84 // NOTE user created token doesn't have valid date and ip limits
85 $usertokensql = "SELECT t.*
86 FROM {external_tokens} t
87 JOIN {external_services} s
88 ON t.externalserviceid = s.id
89 WHERE s.shortname = ?
90 AND s.enabled = 1
91 AND t.userid = ?
92 AND t.userid = t.creatorid";
93
94 $token = $DB->get_record_sql($usertokensql, array($service, $user->id));
95 // create token if not exists
96 if (!$token) {
97 // This is an exception for Moodle Mobiel App
98 // if user doesn't have token, we will create one on the fly
99 // even user doesn't have createtoken permission
100 if ($service == MOODLE_OFFICIAL_MOBILE_SERVICE) {
13ea96c4
DC
101 if (has_capability('moodle/webservice:createmobiletoken', get_system_context())) {
102 // if service doesn't exist, dml will throw exception
103 $service_record = $DB->get_record('external_services', array('shortname'=>$service, 'enabled'=>1), '*', MUST_EXIST);
104 // create a new token
d8f85b6e 105 $token = new stdClass;
13ea96c4
DC
106 $token->token = md5(uniqid(rand(), 1));
107 $token->userid = $user->id;
108 $token->tokentype = EXTERNAL_TOKEN_PERMANENT;
109 $token->contextid = get_context_instance(CONTEXT_SYSTEM)->id;
110 $token->creatorid = $user->id;
111 $token->timecreated = time();
112 $token->externalserviceid = $service_record->id;
113 $tokenid = $DB->insert_record('external_tokens', $token);
114 add_to_log(SITEID, 'webservice', get_string('createtokenforuserauto', 'webservice'), '' , 'User ID: ' . $user->id);
115 $token->id = $tokenid;
116 } else {
117 throw new moodle_exception('cannotcreatemobiletoken', 'webservice');
118 }
119 } else {
120 // will throw exception if no token found
121 throw new moodle_exception('invalidtoken', 'webservice');
122 }
123 }
124 }
125
126 // log token access
127 $DB->set_field('external_tokens', 'lastaccess', time(), array('id'=>$token->id));
128
13ea96c4 129 add_to_log(SITEID, 'webservice', 'user request webservice token', '' , 'User ID: ' . $user->id);
d8f85b6e
SH
130
131 $usertoken = new stdClass;
13ea96c4
DC
132 $usertoken->token = $token->token;
133 echo json_encode($usertoken);
134} else {
135 throw new moodle_exception('usernamenotfound', 'moodle');
d8f85b6e 136}