Skip to content

Commit

Permalink
GH-224 Move email change validation into utils
Browse files Browse the repository at this point in the history
  • Loading branch information
mdziekon committed Jun 9, 2022
1 parent 982c377 commit 24bf057
Show file tree
Hide file tree
Showing 4 changed files with 187 additions and 100 deletions.
2 changes: 2 additions & 0 deletions modules/settings/_includes.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@
$includePath = $_EnginePath . 'modules/settings/';

include($includePath . './utils/errorMappers/validatePasswordChange.errorMapper.php');
include($includePath . './utils/errorMappers/validateEmailChange.errorMapper.php');

include($includePath . './utils/validators/validatePasswordChange.validator.php');
include($includePath . './utils/validators/validateEmailChange.validator.php');

});

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

namespace UniEngine\Engine\Modules\Settings\Utils\ErrorMappers;

/**
* @param object $error As returned by Settings\Utils\Validators\validateEmailChange
*/
function mapValidateEmailChangeErrorToReadableMessage($error) {
global $_Lang;

$errorCode = $error['code'];

$knownErrorsByCode = [
'EMAIL_CHANGE_IN_PROGRESS' => $_Lang['Mail_alreadyInChange'],
'INVALID_EMAIL' => $_Lang['Mail_badEmail'],
'NEW_EMAIL_SAME_AS_OLD' => $_Lang['Mail_same_as_old'],
'NEW_EMAIL_CONFIRMATION_INVALID' => $_Lang['Mail_Confirm_isbad'],
'BANNED_DOMAIN_USED' => $_Lang['Mail_banned_domain'],
'NEW_EMAIL_ALREADY_IN_USE' => $_Lang['Mail_some1_hasemail'],
];

if (!isset($knownErrorsByCode[$errorCode])) {
return $_Lang['fleet_generic_errors_unknown'];
}

return $knownErrorsByCode[$errorCode];
}

?>
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
<?php

namespace UniEngine\Engine\Modules\Settings\Utils\Validators;

// TODO: Deduplicate, registration does the same thing
function _isOnDomainBanlist($emailAddress) {
global $_GameConfig;

$bannedDomains = $_GameConfig['BannedMailDomains'];
$bannedDomains = str_replace('.', '\.', $bannedDomains);

if (empty($bannedDomains)) {
return false;
}

return preg_match('#('.$bannedDomains.')+#si', $emailAddress) === 1;
}

/**
* @param array $params
* @param array $params['input']
* @param string $params['input']['newEmailAddress']
* @param string $params['input']['newEmailAddressConfirm']
* @param arrayRef $params['currentUser']
* @param boolean $params['isAlreadyChangingEmail']
*/
function validateEmailChange($params) {
$currentUser = &$params['currentUser'];
$isAlreadyChangingEmail = $params['isAlreadyChangingEmail'];

$executor = function ($input, $resultHelpers) use (&$currentUser, $isAlreadyChangingEmail) {
$newEmailAddress = $input['newEmailAddress'];
$newEmailAddressConfirm = $input['newEmailAddressConfirm'];

$currentUserEmail = $currentUser['email'];

if ($isAlreadyChangingEmail) {
return $resultHelpers['createFailure']([
'code' => 'EMAIL_CHANGE_IN_PROGRESS',
]);
}

if (!is_email($newEmailAddress)) {
return $resultHelpers['createFailure']([
'code' => 'INVALID_EMAIL',
]);
}
if ($newEmailAddress === $currentUserEmail) {
return $resultHelpers['createFailure']([
'code' => 'NEW_EMAIL_SAME_AS_OLD',
]);
}
if ($newEmailAddress !== $newEmailAddressConfirm) {
return $resultHelpers['createFailure']([
'code' => 'NEW_EMAIL_CONFIRMATION_INVALID',
]);
}
if (_isOnDomainBanlist($newEmailAddress)) {
return $resultHelpers['createFailure']([
'code' => 'BANNED_DOMAIN_USED',
]);
}

$fetchExistingEmailFromDB = doquery(
"SELECT `id` FROM {{table}} WHERE `email` = '{$newEmailAddress}' LIMIT 1;",
'users',
true
);

if ($fetchExistingEmailFromDB) {
// TODO: Verify whether we should fetch email change processes as well
return $resultHelpers['createFailure']([
'code' => 'NEW_EMAIL_ALREADY_IN_USE',
]);
}

return $resultHelpers['createSuccess']([]);
};

return createFuncWithResultHelpers($executor)($params['input']);
}

?>
173 changes: 73 additions & 100 deletions settings.php
Original file line number Diff line number Diff line change
Expand Up @@ -147,110 +147,83 @@
}
}

if(isset($_POST['change_mail']) && $_POST['change_mail'] == 'on')
{
if($CheckMailChange['ID'] <= 0)
{
$_POST['give_newemail'] = getDBLink()->escape_string(
strip_tags(trim($_POST['give_newemail']))
);
if (
isset($_POST['change_mail']) &&
$_POST['change_mail'] == 'on'
) {
$inputNewEmailAddress = $_POST['give_newemail'];
$inputNewEmailAddressConfirm = $_POST['give_confirmemail'];
$normalizedInputNewEmailAddress = getDBLink()->escape_string(
strip_tags(trim($inputNewEmailAddress))
);

$CheckMail = $_POST['give_newemail'];
$banned_domain_list = $_GameConfig['BannedMailDomains'];
$banned_domain_list = str_replace('.', '\.', $banned_domain_list);
$emailChangeValidationResult = Settings\Utils\Validators\validateEmailChange([
'input' => [
'newEmailAddress' => $normalizedInputNewEmailAddress,
'newEmailAddressConfirm' => $inputNewEmailAddressConfirm,
],
'currentUser' => &$_User,
'isAlreadyChangingEmail' => ($CheckMailChange['ID'] > 0),
]);

if(is_email($CheckMail))
{
if($CheckMail !== $_User['email'])
{
if($CheckMail === $_POST['give_confirmemail'])
{
if(empty($banned_domain_list) || !preg_match('#('.$banned_domain_list.')+#si', $CheckMail))
{
$CheckMailinDB = doquery("SELECT `id` FROM {{table}} WHERE `email` = '{$CheckMail}' LIMIT 1;", 'users', true);
if($CheckMailinDB['id'] <= 0)
{
$RandomHash = md5($_User['id'].$_User['username'].mt_rand(0, 999999999));
$RandomHashNew = md5($_User['id'].$_User['username'].mt_rand(0, 999999999));
$ThisTime = $Now;

$EmailParse = array
(
'EP_User' => $_User['username'],
'EP_GameLink' => GAMEURL_STRICT,
'EP_Link' => GAMEURL."email_change.php?hash=old&amp;key={$RandomHash}",
'EP_Text' => $_Lang['Email_MailOld'],
'EP_OldMail' => $_User['email'],
'EP_NewMail' => $CheckMail,
'EP_Date' => date('d.m.Y - H:i:s', $ThisTime),
'EP_IP' => $_User['user_lastip'],
'EP_ContactLink' => GAMEURL_STRICT.'/contact.php',
'EP_Text2' => $_Lang['Email_WarnOld']
);
$EmailParseNew = array
(
'EP_User' => $_User['username'],
'EP_GameLink' => GAMEURL_STRICT,
'EP_Link' => GAMEURL."email_change.php?hash=new&amp;key={$RandomHashNew}",
'EP_Text' => $_Lang['Email_MailNew'],
'EP_OldMail' => $_User['email'],
'EP_NewMail' => $CheckMail,
'EP_Date' => date('d.m.Y - H:i:s', $ThisTime),
'EP_IP' => $_User['user_lastip'],
'EP_ContactLink' => GAMEURL_STRICT.'/contact.php',
'EP_Text2' => $_Lang['Email_WarnNew']
);

include($_EnginePath.'includes/functions/SendMail.php');
$EmailBody = parsetemplate($_Lang['Email_Body'], $EmailParse);
$EmailBodyNew = parsetemplate($_Lang['Email_Body'], $EmailParseNew);
$SendResult = SendMail($_User['email'], $_Lang['Email_Title'], $EmailBody, '', true);
$SendResult2 = SendMail($CheckMail, $_Lang['Email_Title'], $EmailBodyNew);
CloseMailConnection();

if($SendResult === TRUE AND $SendResult2 === TRUE)
{
$ChangeSet['email_2'] = $CheckMail;
$ChangeSetTypes['email_2'] = 's';

doquery("INSERT INTO {{table}} VALUES (NULL, {$ThisTime}, {$_User['id']}, '{$_User['email']}', '{$CheckMail}', 0, 0, '{$RandomHash}', '{$RandomHashNew}');", 'mailchange');
$CheckMailChange = array('ID' => 1, 'Date' => $ThisTime);
$InfoMsgs[] = sprintf($_Lang['Mail_MailChange'], $_User['email']);
}
else
{
$WarningMsgs[] = sprintf($_Lang['Mail_SendMailError'], urlencode(str_pad(mt_rand(0,999), 3, 'a', STR_PAD_RIGHT).base64_encode($SendResult).'||'.base64_encode($SendResult2)));
}
}
else
{
$WarningMsgs[] = $_Lang['Mail_some1_hasemail'];
}
}
else
{
$WarningMsgs[] = $_Lang['Mail_banned_domain'];
}
}
else
{
$WarningMsgs[] = $_Lang['Mail_Confirm_isbad'];
}
}
else
{
$WarningMsgs[] = $_Lang['Mail_same_as_old'];
}
}
else
{
$WarningMsgs[] = $_Lang['Mail_badEmail'];
if (!$emailChangeValidationResult['isSuccess']) {
$WarningMsgs[] = Settings\Utils\ErrorMappers\mapValidateEmailChangeErrorToReadableMessage(
$emailChangeValidationResult['error']
);
} else {
$RandomHash = md5($_User['id'].$_User['username'].mt_rand(0, 999999999));
$RandomHashNew = md5($_User['id'].$_User['username'].mt_rand(0, 999999999));
$ThisTime = $Now;

$EmailParse = array
(
'EP_User' => $_User['username'],
'EP_GameLink' => GAMEURL_STRICT,
'EP_Link' => GAMEURL."email_change.php?hash=old&amp;key={$RandomHash}",
'EP_Text' => $_Lang['Email_MailOld'],
'EP_OldMail' => $_User['email'],
'EP_NewMail' => $normalizedInputNewEmailAddress,
'EP_Date' => date('d.m.Y - H:i:s', $ThisTime),
'EP_IP' => $_User['user_lastip'],
'EP_ContactLink' => GAMEURL_STRICT.'/contact.php',
'EP_Text2' => $_Lang['Email_WarnOld']
);
$EmailParseNew = array
(
'EP_User' => $_User['username'],
'EP_GameLink' => GAMEURL_STRICT,
'EP_Link' => GAMEURL."email_change.php?hash=new&amp;key={$RandomHashNew}",
'EP_Text' => $_Lang['Email_MailNew'],
'EP_OldMail' => $_User['email'],
'EP_NewMail' => $normalizedInputNewEmailAddress,
'EP_Date' => date('d.m.Y - H:i:s', $ThisTime),
'EP_IP' => $_User['user_lastip'],
'EP_ContactLink' => GAMEURL_STRICT.'/contact.php',
'EP_Text2' => $_Lang['Email_WarnNew']
);

include($_EnginePath.'includes/functions/SendMail.php');
$EmailBody = parsetemplate($_Lang['Email_Body'], $EmailParse);
$EmailBodyNew = parsetemplate($_Lang['Email_Body'], $EmailParseNew);
$SendResult = SendMail($_User['email'], $_Lang['Email_Title'], $EmailBody, '', true);
$SendResult2 = SendMail($normalizedInputNewEmailAddress, $_Lang['Email_Title'], $EmailBodyNew);
CloseMailConnection();

if (
// true
$SendResult === true &&
$SendResult2 === true
) {
$ChangeSet['email_2'] = $normalizedInputNewEmailAddress;
$ChangeSetTypes['email_2'] = 's';

doquery("INSERT INTO {{table}} VALUES (NULL, {$ThisTime}, {$_User['id']}, '{$_User['email']}', '{$normalizedInputNewEmailAddress}', 0, 0, '{$RandomHash}', '{$RandomHashNew}');", 'mailchange');
$CheckMailChange = array('ID' => 1, 'Date' => $ThisTime);
$InfoMsgs[] = sprintf($_Lang['Mail_MailChange'], $_User['email']);
} else {
$WarningMsgs[] = sprintf($_Lang['Mail_SendMailError'], urlencode(str_pad(mt_rand(0,999), 3, 'a', STR_PAD_RIGHT).base64_encode($SendResult).'||'.base64_encode($SendResult2)));
}
}
else
{
$WarningMsgs[] = $_Lang['Mail_alreadyInChange'];
}
}

if(isset($_POST['stop_email_change']) && $_POST['stop_email_change'] == 'on')
Expand Down

0 comments on commit 24bf057

Please sign in to comment.