Merge pull request #4054 from MrPetovan/bug/4041-fix-register

Fix registration
This commit is contained in:
Michael Vogel 2017-12-13 20:01:03 +01:00 committed by GitHub
commit f58167b000
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 139 additions and 177 deletions

View file

@ -1068,17 +1068,14 @@ function search($s, $id = 'search-box', $url = 'search', $save = false, $aside =
} }
/** /**
* Check if $x is a valid email string * @brief Check for a valid email string
* *
* @param string $x * @param string $email_address
* @return boolean * @return boolean
*/ */
function valid_email($x){ function valid_email($email_address)
{
/// @TODO Removed because Fabio told me so. return preg_match('/^[_a-zA-Z0-9\-\+]+(\.[_a-zA-Z0-9\-\+]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/', $email_address);
//if (Config::get('system','disable_email_validation'))
// return true;
return preg_match('/^[_a-zA-Z0-9\-\+]+(\.[_a-zA-Z0-9\-\+]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/', $x);
} }

View file

@ -1466,13 +1466,20 @@ function admin_page_users_post(App $a)
check_form_security_token_redirectOnErr('/admin/users', 'admin_users'); check_form_security_token_redirectOnErr('/admin/users', 'admin_users');
if (!($nu_name === "") && !($nu_email === "") && !($nu_nickname === "")) { if (!($nu_name === "") && !($nu_email === "") && !($nu_nickname === "")) {
$result = User::create(array('username' => $nu_name, 'email' => $nu_email, try {
'nickname' => $nu_nickname, 'verified' => 1, 'language' => $nu_language)); $result = User::create([
if (!$result['success']) { 'username' => $nu_name,
notice($result['message']); 'email' => $nu_email,
'nickname' => $nu_nickname,
'verified' => 1,
'language' => $nu_language
]);
} catch (Exception $ex) {
notice($ex->getMessage());
return; return;
} }
$nu = $result['user'];
$user = $result['user'];
$preamble = deindent(t(' $preamble = deindent(t('
Dear %1$s, Dear %1$s,
the administrator of %2$s has set up an account for you.')); the administrator of %2$s has set up an account for you.'));
@ -1502,12 +1509,12 @@ function admin_page_users_post(App $a)
Thank you and welcome to %4$s.')); Thank you and welcome to %4$s.'));
$preamble = sprintf($preamble, $nu['username'], $a->config['sitename']); $preamble = sprintf($preamble, $user['username'], $a->config['sitename']);
$body = sprintf($body, System::baseUrl(), $nu['email'], $result['password'], $a->config['sitename']); $body = sprintf($body, System::baseUrl(), $user['email'], $result['password'], $a->config['sitename']);
notification(array( notification(array(
'type' => SYSTEM_EMAIL, 'type' => SYSTEM_EMAIL,
'to_email' => $nu['email'], 'to_email' => $user['email'],
'subject' => sprintf(t('Registration details for %s'), $a->config['sitename']), 'subject' => sprintf(t('Registration details for %s'), $a->config['sitename']),
'preamble' => $preamble, 'preamble' => $preamble,
'body' => $body)); 'body' => $body));
@ -1587,8 +1594,8 @@ function admin_page_users(App $a)
/* get pending */ /* get pending */
$pending = q("SELECT `register`.*, `contact`.`name`, `user`.`email` $pending = q("SELECT `register`.*, `contact`.`name`, `user`.`email`
FROM `register` FROM `register`
LEFT JOIN `contact` ON `register`.`uid` = `contact`.`uid` INNER JOIN `contact` ON `register`.`uid` = `contact`.`uid`
LEFT JOIN `user` ON `register`.`uid` = `user`.`uid`;"); INNER JOIN `user` ON `register`.`uid` = `user`.`uid`;");
/* get users */ /* get users */

View file

@ -59,10 +59,10 @@ function register_post(App $a)
$arr['verified'] = $verified; $arr['verified'] = $verified;
$arr['language'] = get_browser_language(); $arr['language'] = get_browser_language();
try {
$result = User::create($arr); $result = User::create($arr);
} catch (Exception $e) {
if (!$result['success']) { notice($e->getMessage());
notice($result['message']);
return; return;
} }

View file

@ -96,11 +96,11 @@ class Contact extends BaseObject
public static function createSelfFromUserId($uid) public static function createSelfFromUserId($uid)
{ {
// Only create the entry if it doesn't exist yet // Only create the entry if it doesn't exist yet
if (dba::exists('contact', ['uid' => intval($uid), 'self'])) { if (dba::exists('contact', ['uid' => $uid, 'self' => true])) {
return true; return true;
} }
$user = dba::select('user', ['uid', 'username', 'nickname'], ['uid' => intval($uid)], ['limit' => 1]); $user = dba::select('user', ['uid', 'username', 'nickname'], ['uid' => $uid], ['limit' => 1]);
if (!DBM::is_result($user)) { if (!DBM::is_result($user)) {
return false; return false;
} }

View file

@ -47,6 +47,9 @@ class Group extends BaseObject
} }
$return = dba::insert('group', ['uid' => $uid, 'name' => $name]); $return = dba::insert('group', ['uid' => $uid, 'name' => $name]);
if ($return) {
$return = dba::lastInsertId();
}
} }
return $return; return $return;
} }

View file

@ -17,6 +17,7 @@ use Friendica\Model\Group;
use Friendica\Model\Photo; use Friendica\Model\Photo;
use Friendica\Object\Image; use Friendica\Object\Image;
use dba; use dba;
use Exception;
require_once 'boot.php'; require_once 'boot.php';
require_once 'include/crypto.php'; require_once 'include/crypto.php';
@ -134,11 +135,12 @@ class User
* *
* @param array $data * @param array $data
* @return string * @return string
* @throw Exception
*/ */
public static function create(array $data) public static function create(array $data)
{ {
$a = get_app(); $a = get_app();
$result = array('success' => false, 'user' => null, 'password' => '', 'message' => ''); $return = ['user' => null, 'password' => ''];
$using_invites = Config::get('system', 'invitation_only'); $using_invites = Config::get('system', 'invitation_only');
$num_invites = Config::get('system', 'number_invites'); $num_invites = Config::get('system', 'number_invites');
@ -159,9 +161,8 @@ class User
$netpublish = strlen(Config::get('system', 'directory')) ? $publish : 0; $netpublish = strlen(Config::get('system', 'directory')) ? $publish : 0;
if ($password1 != $confirm) { if ($password1 != $confirm) {
$result['message'] .= t('Passwords do not match. Password unchanged.') . EOL; throw new Exception(t('Passwords do not match. Password unchanged.'));
return $result; } elseif ($password1 != '') {
} elseif ($password1 != "") {
$password = $password1; $password = $password1;
} }
@ -169,21 +170,18 @@ class User
if ($using_invites) { if ($using_invites) {
if (!$invite_id) { if (!$invite_id) {
$result['message'] .= t('An invitation is required.') . EOL; throw new Exception(t('An invitation is required.'));
return $result;
} }
$r = q("SELECT * FROM `register` WHERE `hash` = '%s' LIMIT 1", dbesc($invite_id));
if (!results($r)) { if (!dba::exists('register', ['hash' => $invite_id])) {
$result['message'] .= t('Invitation could not be verified.') . EOL; throw new Exception(t('Invitation could not be verified.'));
return $result;
} }
} }
if (!x($username) || !x($email) || !x($nickname)) { if (!x($username) || !x($email) || !x($nickname)) {
if ($openid_url) { if ($openid_url) {
if (!validate_url($tmp_str)) { if (!validate_url($tmp_str)) {
$result['message'] .= t('Invalid OpenID url') . EOL; throw new Exception(t('Invalid OpenID url'));
return $result;
} }
$_SESSION['register'] = 1; $_SESSION['register'] = 1;
$_SESSION['openid'] = $openid_url; $_SESSION['openid'] = $openid_url;
@ -196,15 +194,13 @@ class User
try { try {
$authurl = $openid->authUrl(); $authurl = $openid->authUrl();
} catch (Exception $e) { } catch (Exception $e) {
$result['message'] .= t("We encountered a problem while logging in with the OpenID you provided. Please check the correct spelling of the ID.") . EOL . EOL . t("The error message was:") . $e->getMessage() . EOL; throw new Exception(t('We encountered a problem while logging in with the OpenID you provided. Please check the correct spelling of the ID.') . EOL . EOL . t('The error message was:') . $e->getMessage(), 0, $e);
return $result;
} }
goaway($authurl); goaway($authurl);
// NOTREACHED // NOTREACHED
} }
notice(t('Please enter the required information.') . EOL); throw new Exception(t('Please enter the required information.'));
return;
} }
if (!validate_url($tmp_str)) { if (!validate_url($tmp_str)) {
@ -217,10 +213,10 @@ class User
$username = preg_replace('/ +/', ' ', $username); $username = preg_replace('/ +/', ' ', $username);
if (mb_strlen($username) > 48) { if (mb_strlen($username) > 48) {
$result['message'] .= t('Please use a shorter name.') . EOL; throw new Exception(t('Please use a shorter name.'));
} }
if (mb_strlen($username) < 3) { if (mb_strlen($username) < 3) {
$result['message'] .= t('Name too short.') . EOL; throw new Exception(t('Name too short.'));
} }
// So now we are just looking for a space in the full name. // So now we are just looking for a space in the full name.
@ -228,72 +224,52 @@ class User
if (!$loose_reg) { if (!$loose_reg) {
$username = mb_convert_case($username, MB_CASE_TITLE, 'UTF-8'); $username = mb_convert_case($username, MB_CASE_TITLE, 'UTF-8');
if (!strpos($username, ' ')) { if (!strpos($username, ' ')) {
$result['message'] .= t("That doesn't appear to be your full \x28First Last\x29 name.") . EOL; throw new Exception(t("That doesn't appear to be your full \x28First Last\x29 name."));
} }
} }
if (!allowed_email($email)) { if (!allowed_email($email)) {
$result['message'] .= t('Your email domain is not among those allowed on this site.') . EOL; throw new Exception(t('Your email domain is not among those allowed on this site.'));
} }
if (!valid_email($email) || !validate_email($email)) { if (!valid_email($email) || !validate_email($email)) {
$result['message'] .= t('Not a valid email address.') . EOL; throw new Exception(t('Not a valid email address.'));
}
if (dba::exists('user', ['email' => $email])) {
throw new Exception(t('Cannot use that email.'));
} }
// Disallow somebody creating an account using openid that uses the admin email address, // Disallow somebody creating an account using openid that uses the admin email address,
// since openid bypasses email verification. We'll allow it if there is not yet an admin account. // since openid bypasses email verification. We'll allow it if there is not yet an admin account.
if (x($a->config, 'admin_email') && strlen($openid_url)) {
$adminlist = explode(",", str_replace(" ", "", strtolower($a->config['admin_email']))); $adminlist = explode(',', str_replace(' ', '', strtolower($a->config['admin_email'])));
if (in_array(strtolower($email), $adminlist)) {
//if((x($a->config,'admin_email')) && (strcasecmp($email,$a->config['admin_email']) == 0) && strlen($openid_url)) { throw new Exception(t('Cannot use that email.'));
if (x($a->config, 'admin_email') && in_array(strtolower($email), $adminlist) && strlen($openid_url)) {
$r = q("SELECT * FROM `user` WHERE `email` = '%s' LIMIT 1",
dbesc($email)
);
if (DBM::is_result($r)) {
$result['message'] .= t('Cannot use that email.') . EOL;
} }
} }
$nickname = $data['nickname'] = strtolower($nickname); $nickname = $data['nickname'] = strtolower($nickname);
if (!preg_match("/^[a-z0-9][a-z0-9\_]*$/", $nickname)) { if (!preg_match('/^[a-z0-9][a-z0-9\_]*$/', $nickname)) {
$result['message'] .= t('Your "nickname" can only contain "a-z", "0-9" and "_".') . EOL; throw new Exception(t('Your "nickname" can only contain "a-z", "0-9" and "_".'));
} }
$r = q("SELECT `uid` FROM `user` // Check existing and deleted accounts for this nickname.
WHERE `nickname` = '%s' LIMIT 1", if (dba::exists('user', ['nickname' => $nickname])
dbesc($nickname) || dba::exists('userd', ['username' => $nickname])
); ) {
if (DBM::is_result($r)) { throw new Exception(t('Nickname is already registered. Please choose another.'));
$result['message'] .= t('Nickname is already registered. Please choose another.') . EOL;
}
// Check deleted accounts that had this nickname. Doesn't matter to us,
// but could be a security issue for federated platforms.
$r = q("SELECT * FROM `userd`
WHERE `username` = '%s' LIMIT 1",
dbesc($nickname)
);
if (DBM::is_result($r)) {
$result['message'] .= t('Nickname was once registered here and may not be re-used. Please choose another.') . EOL;
}
if (strlen($result['message'])) {
return $result;
} }
$new_password = strlen($password) ? $password : autoname(6) . mt_rand(100, 9999); $new_password = strlen($password) ? $password : autoname(6) . mt_rand(100, 9999);
$new_password_encoded = hash('whirlpool', $new_password); $new_password_encoded = hash('whirlpool', $new_password);
$result['password'] = $new_password; $return['password'] = $new_password;
$keys = new_keypair(4096); $keys = new_keypair(4096);
if ($keys === false) { if ($keys === false) {
$result['message'] .= t('SERIOUS ERROR: Generation of security keys failed.') . EOL; throw new Exception(t('SERIOUS ERROR: Generation of security keys failed.'));
return $result;
} }
$prvkey = $keys['prvkey']; $prvkey = $keys['prvkey'];
@ -304,100 +280,83 @@ class User
$sprvkey = $sres['prvkey']; $sprvkey = $sres['prvkey'];
$spubkey = $sres['pubkey']; $spubkey = $sres['pubkey'];
$r = q("INSERT INTO `user` (`guid`, `username`, `password`, `email`, `openid`, `nickname`, $insert_result = dba::insert('user', [
`pubkey`, `prvkey`, `spubkey`, `sprvkey`, `register_date`, `verified`, `blocked`, `timezone`, `default-location`) 'guid' => generate_user_guid(),
VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, 'UTC', '')", 'username' => $username,
dbesc(generate_user_guid()), 'password' => $new_password_encoded,
dbesc($username), 'email' => $email,
dbesc($new_password_encoded), 'openid' => $openid_url,
dbesc($email), 'nickname' => $nickname,
dbesc($openid_url), 'pubkey' => $pubkey,
dbesc($nickname), 'prvkey' => $prvkey,
dbesc($pubkey), 'spubkey' => $spubkey,
dbesc($prvkey), 'sprvkey' => $sprvkey,
dbesc($spubkey), 'verified' => $verified,
dbesc($sprvkey), 'blocked' => $blocked,
dbesc(datetime_convert()), 'timezone' => 'UTC',
intval($verified), 'register_date' => datetime_convert(),
intval($blocked) 'default-location' => ''
); ]);
if ($r) { if ($insert_result) {
$r = q("SELECT * FROM `user` $uid = dba::lastInsertId();
WHERE `username` = '%s' AND `password` = '%s' LIMIT 1", $user = dba::select('user', [], ['uid' => $uid], ['limit' => 1]);
dbesc($username),
dbesc($new_password_encoded)
);
if (DBM::is_result($r)) {
$u = $r[0];
$newuid = intval($r[0]['uid']);
}
} else { } else {
$result['message'] .= t('An error occurred during registration. Please try again.') . EOL; throw new Exception(t('An error occurred during registration. Please try again.'));
return $result;
} }
/** if (!$uid) {
* if somebody clicked submit twice very quickly, they could end up with two accounts throw new Exception(t('An error occurred during registration. Please try again.'));
* due to race condition. Remove this one.
*/
$r = q("SELECT `uid` FROM `user`
WHERE `nickname` = '%s' ",
dbesc($nickname)
);
if (DBM::is_result($r) && count($r) > 1 && $newuid) {
$result['message'] .= t('Nickname is already registered. Please choose another.') . EOL;
dba::delete('user', array('uid' => $newuid));
return $result;
} }
if (x($newuid) !== false) { // if somebody clicked submit twice very quickly, they could end up with two accounts
$r = q("INSERT INTO `profile` ( `uid`, `profile-name`, `is-default`, `name`, `photo`, `thumb`, `publish`, `net-publish` ) // due to race condition. Remove this one.
VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, %d ) ", $user_count = dba::count('user', ['nickname' => $nickname]);
intval($newuid), if ($user_count > 1) {
t('default'), dba::delete('user', ['uid' => $uid]);
1,
dbesc($username), throw new Exception(t('Nickname is already registered. Please choose another.'));
dbesc(System::baseUrl() . "/photo/profile/{$newuid}.jpg"), }
dbesc(System::baseUrl() . "/photo/avatar/{$newuid}.jpg"),
intval($publish), $insert_result = dba::insert('profile', [
intval($netpublish) 'uid' => $uid,
); 'name' => $username,
if ($r === false) { 'photo' => System::baseUrl() . "/photo/profile/{$uid}.jpg",
$result['message'] .= t('An error occurred creating your default profile. Please try again.') . EOL; 'thumb' => System::baseUrl() . "/photo/avatar/{$uid}.jpg",
// Start fresh next time. 'publish' => $publish,
dba::delete('user', array('uid' => $newuid)); 'is-default' => 1,
return $result; 'net-publish' => $netpublish,
'profile-name' => t('default')
]);
if (!$insert_result) {
dba::delete('user', ['uid' => $uid]);
throw new Exception(t('An error occurred creating your default profile. Please try again.'));
} }
// Create the self contact // Create the self contact
Contact::createSelfFromUserId($newuid); if (!Contact::createSelfFromUserId($uid)) {
dba::delete('user', ['uid' => $uid]);
throw new Exception(t('An error occurred creating your self contact. Please try again.'));
}
// Create a group with no members. This allows somebody to use it // Create a group with no members. This allows somebody to use it
// right away as a default group for new contacts. // right away as a default group for new contacts.
Group::create($newuid, t('Friends')); $def_gid = Group::create($uid, t('Friends'));
if (!$def_gid) {
dba::delete('user', ['uid' => $uid]);
$r = q("SELECT `id` FROM `group` WHERE `uid` = %d AND `name` = '%s'", throw new Exception(t('An error occurred creating your default contact group. Please try again.'));
intval($newuid),
dbesc(t('Friends'))
);
if (DBM::is_result($r)) {
$def_gid = $r[0]['id'];
q("UPDATE `user` SET `def_gid` = %d WHERE `uid` = %d",
intval($r[0]['id']),
intval($newuid)
);
} }
$fields = ['def_gid' => $def_gid];
if (Config::get('system', 'newuser_private') && $def_gid) { if (Config::get('system', 'newuser_private') && $def_gid) {
q("UPDATE `user` SET `allow_gid` = '%s' WHERE `uid` = %d", $fields['allow_gid'] = '<' . $def_gid . '>';
dbesc("<" . $def_gid . ">"),
intval($newuid)
);
}
} }
dba::update('user', $fields, ['uid' => $uid]);
// if we have no OpenID photo try to look up an avatar // if we have no OpenID photo try to look up an avatar
if (!strlen($photo)) { if (!strlen($photo)) {
$photo = avatar_img($email); $photo = avatar_img($email);
@ -412,14 +371,13 @@ class User
// guess mimetype from headers or filename // guess mimetype from headers or filename
$type = Image::guessType($photo, true); $type = Image::guessType($photo, true);
$Image = new Image($img_str, $type); $Image = new Image($img_str, $type);
if ($Image->isValid()) { if ($Image->isValid()) {
$Image->scaleToSquare(175); $Image->scaleToSquare(175);
$hash = photo_new_resource(); $hash = photo_new_resource();
$r = Photo::store($Image, $newuid, 0, $hash, $filename, t('Profile Photos'), 4); $r = Photo::store($Image, $uid, 0, $hash, $filename, t('Profile Photos'), 4);
if ($r === false) { if ($r === false) {
$photo_failure = true; $photo_failure = true;
@ -427,7 +385,7 @@ class User
$Image->scaleDown(80); $Image->scaleDown(80);
$r = Photo::store($Image, $newuid, 0, $hash, $filename, t('Profile Photos'), 5); $r = Photo::store($Image, $uid, 0, $hash, $filename, t('Profile Photos'), 5);
if ($r === false) { if ($r === false) {
$photo_failure = true; $photo_failure = true;
@ -435,24 +393,21 @@ class User
$Image->scaleDown(48); $Image->scaleDown(48);
$r = Photo::store($Image, $newuid, 0, $hash, $filename, t('Profile Photos'), 6); $r = Photo::store($Image, $uid, 0, $hash, $filename, t('Profile Photos'), 6);
if ($r === false) { if ($r === false) {
$photo_failure = true; $photo_failure = true;
} }
if (!$photo_failure) { if (!$photo_failure) {
q("UPDATE `photo` SET `profile` = 1 WHERE `resource-id` = '%s' ", dba::update('photo', ['profile' => 1], ['resource-id' => $hash]);
dbesc($hash)
);
} }
} }
} }
call_hooks('register_account', $newuid); call_hooks('register_account', $uid);
$result['success'] = true; $result['user'] = $user;
$result['user'] = $u;
return $result; return $result;
} }