Skip to content

Commit

Permalink
Finished lost/reset password feature by adding the email functionality.
Browse files Browse the repository at this point in the history
Obviously this needs any, and possibly per-node configuration based on deployment details, so I have added configuration fields for sending mail.
I left in some sample values to help give an idea of what may be used for each, along with others already filled in with their actual value for the project that is less likely to change.
I also cleaned up some of the other fields in the same way.
The body of the message could be large, so I moved this to be loaded from a file instead.

Used SwiftMailer based on recommendation over PHP's built-in mail function.  PHPMailer was also a recommendation.  So this needs a dependency install.
Heard we use PHP 7 in production and/or stage.  Not sure how I got started with 5.  Maybe a nice common denominator.  Also thinking that's the version of php/php-fpm that came with my Mac too.

Added more layers to the API between success and fails.  There must be a better way instead of so many nested if statements!! :P  but we'll wait until a back-end API refactor for that..

Having the mail code in a separate file keeps it nice and clean too, plus keeps a lot of related code together in case you need to modify it in the future.

So far we're just using Google's Gmail servers in production, so I'll leave SSL ((START)TLS?) hard-coded enabled on for now, and that seems good to be secure by default too! :)
  • Loading branch information
Pysis868 committed Feb 4, 2018
1 parent 1c571ed commit 12e01c4
Show file tree
Hide file tree
Showing 7 changed files with 164 additions and 18 deletions.
14 changes: 11 additions & 3 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,18 @@
DBMS=mysql
DBHOST=localhost
DBPORT=
DBNAME=zmap_v2
DBUSER=root
DBPASSWD="<password>"
DBNAME=zeldamaps
DBUSER=
DBPASSWD=""
# Quotes at least around the password to allow for special characters.
PREFIX=
[SECURITY]
LOST_PASSWORD_RANDOM_GENERATOR_STRENGTH=MEDIUM
[MAIL]
server="smtp.server.com"
port=465
username="[email protected]"
password=""
replyToAddress="[email protected]"
lostPasswordSubject="Zelda Maps - Password Reset"
lostPasswordBodyTemplateFilePath="content/lostPasswordEmailBodyTemplate.txt"
25 changes: 17 additions & 8 deletions ajax/lost_password.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,19 +17,28 @@
$randomPassword = $generator->generateString(32, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/`~!@#$%^&*()-_=+[{]}\|;:\'",<.>/?');
$hash = password_hash($randomPassword, PASSWORD_DEFAULT, ['cost' => 13]);

$query = "SELECT `id` FROM `{$map_prefix}user` WHERE `email` = '$email'";
$result = $mysqli->query($query);
$row = $result->fetch_assoc();
$querySelectUser = "SELECT `id`, `name` FROM `{$map_prefix}user` WHERE `email` = '$email'";
$resultSelectUser = $mysqli->query($querySelectUser);
$rowSelectUser = $resultSelectUser->fetch_assoc();

if($row) {
if($rowSelectUser) {
$query = "UPDATE `{$map_prefix}user` SET `password` = '$hash' WHERE `email` = '$email'";
//echo $query;
$result = $mysqli->query($query);

if ($result) {
commit();
# TODO: Remove and put password in email instead!!
echo json_encode(array("success"=>true, "msg"=>"Password reset."));
$commitResult = commit();

if($commitResult) {
include_once("$path/lib/zmailer.php");
$mailResult = sendMail(createResetPasswordEmail($email, $rowSelectUser['name'], $randomPassword));
if($mailResult) {
echo json_encode(array("success"=>true, "msg"=>"Password reset. Email sent."));
} else {
echo json_encode(array("success"=>false, "msg"=>"Password reset. Email not sent."));
}
} else {
echo json_encode(array("success"=>false, "msg"=>"Password not reset. Database error."));
}
} else {
rollback();
echo json_encode(array("success"=>false, "msg"=>"Password not reset."));
Expand Down
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
{
"require": {
"ircmaxell/random-lib": "^1.2"
"ircmaxell/random-lib": "^1.2",
"swiftmailer/swiftmailer": "^5.4"
}
}
56 changes: 55 additions & 1 deletion composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

22 changes: 17 additions & 5 deletions config.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,18 @@
}
$lostPasswordRandomGeneratorStrengthConstant = new SecurityLib\Strength((new SecurityLib\Strength)->getConstList()[$lostPasswordRandomGeneratorStrengthString]);

$mailServer = $ENV['server'];
$mailPort = $ENV['port'];
$mailUsername = $ENV['username'];
$mailPassword = $ENV['password'];
$mailReplyToAddress = $ENV['replyToAddress'];

$lostPasswordSubject = $ENV["lostPasswordSubject"];
if(isset($ENV["lostPasswordBodyTemplateFilePath"])) $lostPasswordBodyTemplateFilePath = $ENV["lostPasswordBodyTemplateFilePath"];
if(isset($lostPasswordBodyTemplateFilePath) && !empty($lostPasswordBodyTemplateFilePath)) {
$lostPasswordBodyTemplate = file_get_contents($lostPasswordBodyTemplateFilePath);
}

$_ENV = array_merge($ENV,$_ENV);
}

Expand All @@ -62,25 +74,25 @@

function begin() {
global $mysqli;
@$mysqli->query("BEGIN");
return $mysqli->query("BEGIN");
}

function commit() {
global $mysqli;
@$mysqli->query("COMMIT");
return $mysqli->query("COMMIT");
}

function rollback() {
global $mysqli;
@$mysqli->query("ROLLBACK");
return $mysqli->query("ROLLBACK");
}

function start_session($name="zmap") {
if(!defined("PHP_MAJOR_VERSION") || PHP_MAJOR_VERSION<7) {
session_start($name);
return session_start($name);
} else {
$opts = ["name"=>$name];
session_start($opts);
return session_start($opts);
}
}
?>
5 changes: 5 additions & 0 deletions content/lostPasswordEmailBodyTemplate.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
Hello {{name}},

You have recently requested to have your password reset.

Your new password will be: {{newPassword}}
57 changes: 57 additions & 0 deletions lib/zmailer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<?php

$path = DIRNAME(__FILE__);
include_once("$path/../config.php");

function prepareMailTransport() {
global $mailServer, $mailPort, $mailUsername, $mailPassword;

// Debug
// error_log("Creating mail transport with the following parameters:\n" .
// "mailServer: $mailServer\n" .
// "mailPort: $mailPort\n" .
// "mailUsername: $mailUsername\n" .
// "mailPassword: $mailPassword\n" .
// "ssl"
// );

return (new Swift_SmtpTransport($mailServer, $mailPort, 'ssl'))
->setUsername($mailUsername)
->setPassword($mailPassword)
;
}

function createResetPasswordEmail($toAddress, $toName, $newPassword) {
global $lostPasswordBodyTemplate, $mailReplyToAddress, $lostPasswordSubject;
$body = "";
if(isset($lostPasswordBodyTemplate)) {
$body = $lostPasswordBodyTemplate;
$body = str_replace("{{name}}", $toName, $body);
$body = str_replace("{{newPassword}}", $newPassword, $body);
} else {
error_log("Error: No lost password mail body message template available; exiting...");
exit;
}

// Debug
// error_log("Generating reset password email with the following parameters:\n" .
// "reply-to: $mailReplyToAddress\n" .
// "to: $toName <$toAddress>\n" .
// "subject: $lostPasswordSubject\n" .
// "body: $body"
// );

return (new Swift_Message($lostPasswordSubject))
->setFrom([$mailReplyToAddress])
->setTo([$toAddress => $toName])
->setBody($body)
;
}

function sendMail($message) {
global $mailer;
return ($mailer->send($message));
}

$mailer = new Swift_Mailer(prepareMailTransport());
?>

0 comments on commit 12e01c4

Please sign in to comment.