Skip to content

Commit

Permalink
Merge pull request #9 from andrewhancox/master
Browse files Browse the repository at this point in the history
Add user provisioning and test client code. Close #9
  • Loading branch information
dmitriim authored Apr 10, 2017
2 parents 1632d88 + 9ec87b0 commit c12c521
Show file tree
Hide file tree
Showing 9 changed files with 430 additions and 19 deletions.
67 changes: 64 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,9 +94,70 @@ You can set URL to redirect users before they see Moodle login page. For example
to your web application to login page. You can use "enrolkey_skipsso" URL parameter to bypass this option.
E.g. http://yourmoodle.com/login/index.php?enrolkey_skipsso=1

**Example client**

The code below defines a function that can be used to obtain a login url.
You will need to add/remove parameters depending on whether you have iprestriction or update/create user enabled and which mapping field you are using.

The required library curl.php can be obtained from https://github.com/dongsheng/cURL
```
/**
* @param string $useremail Email address of user to create token for.
* @param string $firstname First name of user (used to update/create user).
* @param string $lastname Last name of user (used to update/create user).
* @param string $username Username of user (used to update/create user).
* @param string $ipaddress IP address of end user that login request will come from (probably $_SERVER['REMOTE_ADDR']).
* @param int $courseid Course id to send logged in users to, defaults to site home.
* @param int $modname Name of course module to send users to, defaults to none.
* @param int $activityid cmid to send logged in users to, defaults to site home.
* @return bool|string
*/
function getloginurl($useremail, $firstname, $lastname, $username, $ipaddress, $courseid = null, $modname = null, $activityid = null) {
require_once('./curl.php');
$token = 'YOUR_TOKEN';
$domainname = 'http://MOODLE_WWW_ROOT';
$functionname = 'auth_userkey_request_login_url';
$param = [
'user' => [
'firstname' => $firstname,
'lastname' => $lastname,
'username' => $username,
'email' => $useremail,
'ip' => $ipaddress
]
];
$serverurl = $domainname . '/webservice/rest/server.php' . '?wstoken=' . $token . '&wsfunction=' . $functionname . '&moodlewsrestformat=json';
$curl = new curl;
try {
$resp = $curl->post($serverurl, $param);
$resp = json_decode($resp);
$loginurl = $resp->loginurl;
} catch (Exception $ex) {
return false;
}
if (!isset($loginurl)) {
return false;
}
$path = '';
if (isset($courseid)) {
$path = '&wantsurl=' . urlencode("$domainname/course/view.php?id=$courseid");
}
if (isset($modname) && isset($activityid)) {
$path = '&wantsurl=' . urlencode("$domainname/mod/$modname/view.php?id=$activityid");
}
return $loginurl . $path;
}
echo getloginurl('[email protected]', 'barry', 'white', 'barrywhite', '127.0.0.1', 2, 'certificate', 8);
```

TODO:
-----
1. Add users provisioning.
2. Implement logout webservice to be able to call it from external application.
3. Add a test client code to README.
1. Implement logout webservice to be able to call it from external application.
118 changes: 112 additions & 6 deletions auth.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@

require_once($CFG->libdir . "/externallib.php");
require_once($CFG->libdir.'/authlib.php');
require_once($CFG->dirroot . '/user/lib.php');

/**
* User key authentication plugin.
Expand Down Expand Up @@ -58,7 +59,8 @@ class auth_plugin_userkey extends auth_plugin_base {
'iprestriction' => 0,
'redirecturl' => '',
'ssourl' => '',
// TODO: use this field when implementing user creation. 'createuser' => 0.
'createuser' => false,
'updateuser' => false,
);

/**
Expand Down Expand Up @@ -302,6 +304,19 @@ protected function should_create_user() {
return false;
}

/**
* Check if we need to update users.
*
* @return bool
*/
protected function should_update_user() {
if (isset($this->config->updateuser) && $this->config->updateuser == true) {
return true;
}

return false;
}

/**
* Check if restriction by IP is enabled.
*
Expand All @@ -323,10 +338,88 @@ protected function is_ip_restriction_enabled() {
* @return object User object.
*/
protected function create_user(array $data) {
// TODO:
// 1. Validate user
// 2. Create user.
// 3. Throw exception if something went wrong.
global $DB, $CFG;

$user = $data;
unset($user['ip']);
$user['auth'] = 'userkey';
$user['mnethostid'] = $CFG->mnet_localhost_id;

$requiredfieds = ['username', 'email', 'firstname', 'lastname'];
$missingfields = [];
foreach ($requiredfieds as $requiredfied) {
if (empty($user[$requiredfied])) {
$missingfields[] = $requiredfied;
}
}
if (!empty($missingfields)) {
throw new invalid_parameter_exception('Unable to create user, missing value(s): ' . implode(',', $missingfields));
}

if ($DB->record_exists('user', array('username' => $user['username'], 'mnethostid' => $CFG->mnet_localhost_id))) {
throw new invalid_parameter_exception('Username already exists: '.$user['username']);
}
if (!validate_email($user['email'])) {
throw new invalid_parameter_exception('Email address is invalid: '.$user['email']);
} else if (empty($CFG->allowaccountssameemail) &&
$DB->record_exists('user', array('email' => $user['email'], 'mnethostid' => $user['mnethostid']))) {
throw new invalid_parameter_exception('Email address already exists: '.$user['email']);
}

$userid = user_create_user($user);
return $DB->get_record('user', ['id' => $userid]);
}

/**
* Update an existing user.
*
* @param stdClass $user Existing user record.
* @param array $data Validated user data from web service.
*
* @return object User object.
*/
protected function update_user(\stdClass $user, array $data) {
global $DB, $CFG;

$userdata = $data;
unset($userdata['ip']);
$userdata['auth'] = 'userkey';

$changed = false;
foreach ($userdata as $key => $value) {
if ($user->$key != $value) {
$changed = true;
break;
}
}

if (!$changed) {
return $user;
}

if (
$user->username != $userdata['username']
&&
$DB->record_exists('user', array('username' => $userdata['username'], 'mnethostid' => $CFG->mnet_localhost_id))
) {
throw new invalid_parameter_exception('Username already exists: '.$userdata['username']);
}
if (!validate_email($userdata['email'])) {
throw new invalid_parameter_exception('Email address is invalid: '.$userdata['email']);
} else if (
empty($CFG->allowaccountssameemail)
&&
$user->email != $userdata['email']
&&
$DB->record_exists('user', array('email' => $userdata['email'], 'mnethostid' => $CFG->mnet_localhost_id))
) {
throw new invalid_parameter_exception('Email address already exists: '.$userdata['email']);
}
$userdata['id'] = $user->id;

$userdata = (object) $userdata;
user_update_user($userdata, false);
return $DB->get_record('user', ['id' => $user->id]);
}

/**
Expand Down Expand Up @@ -381,6 +474,8 @@ protected function get_user(array $data) {
} else {
throw new invalid_parameter_exception('User is not exist');
}
} else if ($this->should_update_user()) {
$user = $this->update_user($user, $data);
}

return $user;
Expand Down Expand Up @@ -506,7 +601,18 @@ protected function get_user_fields_parameters() {
);
}

// TODO: add more fields here when we implement user creation.
$mappingfield = $this->get_mapping_field();
if ($this->should_create_user() || $this->should_update_user()) {
$parameters['firstname'] = new external_value(PARAM_NOTAGS, 'The first name(s) of the user', VALUE_OPTIONAL);
$parameters['lastname'] = new external_value(PARAM_NOTAGS, 'The family name of the user', VALUE_OPTIONAL);

if ($mappingfield != 'email') {
$parameters['email'] = new external_value(PARAM_RAW_TRIMMED, 'A valid and unique email address', VALUE_OPTIONAL);
}
if ($mappingfield != 'username') {
$parameters['username'] = new external_value(PARAM_USERNAME, 'A valid and unique username', VALUE_OPTIONAL);
}
}

return $parameters;
}
Expand Down
2 changes: 2 additions & 0 deletions classes/userkey_manager_interface.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@

namespace auth_userkey;

defined('MOODLE_INTERNAL') || die();

/**
* Interface userkey_manager_interface describes key manager behaviour.
*
Expand Down
2 changes: 2 additions & 0 deletions externallib.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/

defined('MOODLE_INTERNAL') || die();

require_once($CFG->libdir . "/externallib.php");
require_once($CFG->dirroot . "/webservice/lib.php");
require_once($CFG->dirroot . "/auth/userkey/auth.php");
Expand Down
5 changes: 4 additions & 1 deletion lang/en/auth_userkey.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,10 @@
$string['keylifetime'] = 'User key life time';
$string['keylifetime_desc'] = 'Life time in seconds of the each user login key.';
$string['incorrectkeylifetime'] = 'User key life time should be a number';
$string['createuser'] = 'Crete user?';
$string['createuser'] = 'Create user?';
$string['createuser_desc'] = 'If enabled, a new user will be created if fail to find one in LMS.';
$string['updateuser'] = 'Update user?';
$string['updateuser_desc'] = 'If enabled, users will be updated with the properties supplied when the webservice is called.';
$string['redirecturl'] = 'Logout redirect URL';
$string['redirecturl_desc'] = 'Optionally you can redirect users to this URL after they logged out from LMS.';
$string['incorrectredirecturl'] = 'You should provide valid URL';
Expand All @@ -43,3 +45,4 @@
$string['ssourl'] = 'URL of SSO host';
$string['ssourl_desc'] = 'URL of the SSO host to redirect users to. If defined users will be redirected here on login instead of the Moodle Login page';
$string['redirecterrordetected'] = 'Unsupported redirect to {$a} detected, execution terminated.';
$string['noip'] = 'Unable to fetch IP address of client.';
22 changes: 14 additions & 8 deletions settings.html
Original file line number Diff line number Diff line change
Expand Up @@ -63,13 +63,19 @@
<?php if (isset($err[$field])) { echo $OUTPUT->notification($err[$field], 'notifyfailure'); } ?>
<?php print_string($field.'_desc', 'auth_userkey') ?></td>
</tr>
<!--UNCOMMENT FOLLOWING WHEN IMPLEMENT USER CREATION.-->
<!--<tr valign="top">-->
<!--<?php $field = 'createuser' ?>-->
<!--<td align="right"><label for="<?php echo $field ?>"><?php print_string($field, 'auth_userkey') ?></label></td>-->
<!--<td><?php echo html_writer::select($yesno, $field, $config->$field, false) ?>-->
<!--<?php if (isset($err[$field])) { echo $OUTPUT->notification($err[$field], 'notifyfailure'); } ?>-->
<!--<?php print_string($field.'_desc', 'auth_userkey')?></td>-->
<!--</tr>-->
<tr valign="top">
<?php $field = 'createuser' ?>
<td align="right"><label for="<?php echo $field ?>"><?php print_string($field, 'auth_userkey') ?></label></td>
<td><?php echo html_writer::select($yesno, $field, $config->$field, false) ?>
<?php if (isset($err[$field])) { echo $OUTPUT->notification($err[$field], 'notifyfailure'); } ?>
<?php print_string($field.'_desc', 'auth_userkey')?></td>
</tr>
<tr valign="top">
<?php $field = 'updateuser' ?>
<td align="right"><label for="<?php echo $field ?>"><?php print_string($field, 'auth_userkey') ?></label></td>
<td><?php echo html_writer::select($yesno, $field, $config->$field, false) ?>
<?php if (isset($err[$field])) { echo $OUTPUT->notification($err[$field], 'notifyfailure'); } ?>
<?php print_string($field.'_desc', 'auth_userkey')?></td>
</tr>
</table>

Loading

0 comments on commit c12c521

Please sign in to comment.