| 6 user.module | user_external_login_register($name, $module) |
| 7 user.module | user_external_login_register($name, $module) |
| 8 user.module | user_external_login_register($name, $module) |
Helper function for authentication modules. Either login in or registers the current user, based on username. Either way, the global $user object is populated based on $name.
File
- modules/
user/ user.module, line 1436 - Enables the user registration and login system.
Code
<?php
function user_external_login_register($name, $module) {
global $user;
$existing_user = user_load(array('name' => $name));
if (isset($existing_user->uid)) {
$user = $existing_user;
}
else {
// Register this new user.
$userinfo = array(
'name' => $name,
'pass' => user_password(),
'init' => $name,
'status' => 1,
"authname_$module" => $name,
'access' => time(),
);
$account = user_save('', $userinfo);
// Terminate if an error occured during user_save().
if (!$account) {
drupal_set_message(t("Error saving user account."), 'error');
return;
}
$user = $account;
watchdog('user', 'New external user: %name using module %module.', array('%name' => $name, '%module' => $module), WATCHDOG_NOTICE, l(t('edit'), 'user/' . $user->uid . '/edit'));
}
}
?> Login or register to post comments
Comments
Beware: hook_user login op is not invoked with this function
If you want your login hooks to fire when creating a user account with this function, this trick worked for me:
<?php
global $user;
$anonymous_user = $user; // Store the anonymous user object
// Set up variables for registration
// Set up your user object to register
user_external_login_register($new_username, 'mymodule');
$registered_user = $user;
// Reset the $user object. user_external_login() behaves strangely
// if we don't do this, even if $user->uid is set to 0. Not sure why.
$user = $anonymous_user;
user_external_login($registered_user); // This will restore $user
?>
Basically, you sidestep
user_login()redirecting you for already being logged in, and you get the hooks called in the same way that a user logging in would. Thus, you don't have to have separate logic for external registration and external authentication. Less duplication, more reuse is always good.I'm sure this can be refined. I'll edit this if someone has any suggestions.