Skip to content

Commit

Permalink
Add change email of user api
Browse files Browse the repository at this point in the history
  • Loading branch information
Benau committed Aug 25, 2021
1 parent e8bcc58 commit 2018f6e
Show file tree
Hide file tree
Showing 2 changed files with 87 additions and 0 deletions.
27 changes: 27 additions & 0 deletions api/user.php
Original file line number Diff line number Diff line change
Expand Up @@ -639,6 +639,33 @@
}
break;

case 'change-email':
$userid = isset($_POST['userid']) ? (int)$_POST['userid'] : 0;
$token = isset($_POST['token']) ? $_POST['token'] : "";
$new_email = isset($_POST['new-email']) ? $_POST['new-email'] : "";

try
{
$session = ClientSession::get($token, $userid);
$session->getUser()->changeEmail($new_email);

$output->startElement('change-email');
$output->writeAttribute('success', 'yes');
$output->writeAttribute('info', '');
$output->endElement();
}
catch(Exception $e)
{
$output->startElement('change-email');
$output->writeAttribute('success', 'no');
$output->writeAttribute(
'info',
h($e->getMessage())
);
$output->endElement();
}
break;

default:
$output->addErrorElement('request', 'Invalid action. Action = ' . h($_POST['action']));
break;
Expand Down
60 changes: 60 additions & 0 deletions include/User.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,66 @@ public function asXML($tag = 'user')
return $user_xml->asString();
}

/**
* Change the email of an existing user
*
* @param string $new_email Must be unique
*
* @throws UserException
*/
public function changeEmail($new_email)
{
// validate
static::validateEmail($new_email);

$db = DBConnection::get();
$db->beginTransaction();
// Make sure the email address is unique
try
{
$result = $db->query(
"SELECT `email`
FROM `{DB_VERSION}_users`
WHERE `email` LIKE :new_email",
DBConnection::FETCH_FIRST,
[':new_email' => $new_email]
);
}
catch (DBException $e)
{
throw new UserException(
exception_message_db(_('validate your email address')),
ErrorType::VALIDATE_EMAIL_NOT_EXISTS
);
}
if ($result)
{
throw new UserException(_h('This email address is already taken.'), ErrorType::VALIDATE_EMAIL_TAKEN);
}

// No exception occurred - continue with changing email
try
{
DBConnection::get()->update(
"users",
"`id` = :id",
[
":id" => $this->getID(),
":email" => $new_email,
],
[
":id" => DBConnection::PARAM_INT,
":email" => DBConnection::PARAM_STR
]
);
$db->commit();
}
catch (DBException $e)
{
throw new UserException(exception_message_db(_('change your email')), ErrorType::USER_DB_EXCEPTION);
}
}

/**
* @return UserException
*/
Expand Down

0 comments on commit 2018f6e

Please sign in to comment.