death-notifier/src/main/php/UserManager.php

414 lines
16 KiB
PHP

<?php
namespace php;
use Exception;
use Monolog\Logger;
use PDO;
/**
* Manages interaction with the database in the context of users.
*/
// TODO: Remove duplication in this class
class UserManager
{
/**
* The maximum length of an email address.
*/
private const MAX_EMAIL_LENGTH = 254;
/**
* The minimum length of a password;
*/
private const MIN_PASSWORD_LENGTH = 8;
/**
* The maximum length of a password.
*/
private const MAX_PASSWORD_LENGTH = 64;
/**
* @var Logger The logger to use for logging.
*/
private Logger $logger;
/**
* @var PDO The database connection to interact with.
*/
private PDO $conn;
/**
* Constructs a new user manager.
*
* @param Logger $logger the logger to use for logging
* @param PDO $conn the database connection to interact with
*/
public function __construct(Logger $logger, PDO $conn)
{
$this->logger = $logger;
$this->conn = $conn;
}
/**
* Populates the database with the necessary structures for users.
*
* @return void
*/
public function install(): void
{
$this->conn->exec("CREATE TABLE users(uuid text not null,
email text not null,
email_is_verified int not null default 0,
email_verification_token text,
password text not null,
password_update_time int not null,
PRIMARY KEY (uuid));");
}
/**
* Registers a new user.
*
* @param string $email the user-submitted email address
* @param string $password the user-submitted password
* @param string $password_confirm the user-submitted password confirmation
* @param Mailer $mailer the mailer to notify the user with
* @return Response a response with message `null` if the user was registered, or a response with a message
* explaining what went wrong otherwise
*/
public function register(string $email, string $password, string $password_confirm, Mailer $mailer): Response
{
// Generate UUID and email verification token
try {
$uuid = bin2hex(random_bytes(16));
$email_verification_token = bin2hex(random_bytes(16));
} catch (Exception $exception) {
$this->logger->emergency("Failed to generate UUID or email verification token.", [$exception]);
return new Response(
payload: ["target" => null, "message" => "Unexpected error. Please try again later."],
satisfied: false
);
}
// Validate
if (!filter_var($email, FILTER_VALIDATE_EMAIL) || strlen($email) > self::MAX_EMAIL_LENGTH)
return new Response(
payload: ["target" => "email", "message" => "Invalid email address."],
satisfied: false
);
if (strlen($password) < self::MIN_PASSWORD_LENGTH || strlen($password) > self::MAX_PASSWORD_LENGTH)
return new Response(
payload: [
"target" => "password",
"message" => "Your password should be at least 8 and at most 64 characters long."
],
satisfied: false
);
if ($password !== $password_confirm)
return new Response(
payload: ["target" => "passwordConfirm", "message" => "Passwords do not match."],
satisfied: false
);
// Begin transaction
$this->conn->beginTransaction();
// Check if email address is already in use
$stmt = $this->conn->prepare("SELECT COUNT(*) as count
FROM users
WHERE email=:email;");
$stmt->bindValue(":email", $email);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if ($result["count"] > 0) {
$this->conn->rollBack();
return new Response(
payload: ["target" => "email", "message" => "Email address already in use."],
satisfied: false
);
}
// Register user
$stmt = $this->conn->prepare("INSERT INTO users (uuid, email, email_verification_token,
password, password_update_time)
VALUES (:uuid, :email, :email_verification_token,
:password, unixepoch());");
$stmt->bindValue(":uuid", $uuid);
$stmt->bindValue(":email", $email);
$stmt->bindValue(":email_verification_token", $email_verification_token);
$stmt->bindValue(":password", password_hash($password, PASSWORD_DEFAULT));
$stmt->execute();
// Respond
$this->conn->commit();
$mailer->send_registration_email($email, $email_verification_token);
return new Response(payload: null, satisfied: true);
}
/**
* Deletes the user with the given UUID.
*
* @param string $uuid the UUID of the user to delete
* @return Response a response with message `null` if the user was deleted, or a response with a message explaining
* what went wrong otherwise
*/
public function delete(string $uuid): Response
{
$stmt = $this->conn->prepare("DELETE FROM users WHERE uuid=:uuid;");
$stmt->bindValue(":uuid", $uuid);
$stmt->execute();
$stmt = $this->conn->prepare("DELETE FROM trackings WHERE user_uuid=:uuid");
$stmt->bindValue(":uuid", $uuid);
$stmt->execute();
return new Response(payload: null, satisfied: true);
}
/**
* Validates a login attempt with the given email address and password.
*
* @param string $email the email address of the user whose password should be checked
* @param string $password the password to check against the specified user
* @return Response a response with user data if the login was successful, or a response with a message explaining
* what went wrong otherwise
*/
public function check_login(string $email, string $password): Response
{
if (!filter_var($email, FILTER_VALIDATE_EMAIL) || strlen($email) > self::MAX_EMAIL_LENGTH)
return new Response(
payload: ["target" => "email", "message" => "Invalid email address."],
satisfied: false
);
if (strlen($password) > self::MAX_PASSWORD_LENGTH)
return new Response(
payload: ["target" => "password", "message" => "Incorrect combination of email and password."],
satisfied: false
);
$stmt = $this->conn->prepare("SELECT uuid, email, email_is_verified, password, password_update_time
FROM users
WHERE email=:email;");
$stmt->bindValue(":email", $email);
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (sizeof($results) === 0 || !password_verify($password, $results[0]["password"])) {
return new Response(
payload: ["target" => "password", "message" => "Incorrect combination of email and password."],
satisfied: false
);
}
$user = $results[0];
unset($user["password"]);
return new Response(payload: $user, satisfied: true);
}
/**
* Returns the user with the given UUID.
*
* @param string $uuid the UUID of the user to return
* @return Response the user with the given UUID, or a response with an explanation what went wrong otherwise
*/
public function get_user_data(string $uuid): Response
{
$stmt = $this->conn->prepare("SELECT uuid, email, email_is_verified, password_update_time
FROM users
WHERE uuid=:uuid;");
$stmt->bindValue(":uuid", $uuid);
$stmt->execute();
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if ($user === false)
return new Response(
payload: ["target" => "uuid", "message" => "Something went wrong. Please try logging in again."],
satisfied: false
);
return new Response(payload: $user, satisfied: true);
}
/**
* Updates the indicated user's email address.
*
* @param string $uuid the UUID of the user whose email address should be updated
* @param string $email the new email address
* @param Mailer $mailer the mailer to send a notification with to the user
* @return Response a response with message `null` if the email address was updated, or a response with a message
* explaining what went wrong otherwise
*/
public function set_email(string $uuid, string $email, Mailer $mailer): Response
{
// Generate UUID and email verification token
try {
$email_verification_token = bin2hex(random_bytes(16));
} catch (Exception $exception) {
$this->logger->emergency("Failed to generate email verification token.", [$exception]);
return new Response(
payload: ["target" => null, "message" => "Unexpected error. Please try again later."],
satisfied: false
);
}
// Validate
if (!filter_var($email, FILTER_VALIDATE_EMAIL) || strlen($email) > self::MAX_EMAIL_LENGTH)
return new Response(
payload: ["target" => "email", "message" => "Invalid email address."],
satisfied: false
);
// Begin transaction
$this->conn->beginTransaction();
// Check if email address is different
$stmt = $this->conn->prepare("SELECT email FROM users WHERE uuid=:uuid;");
$stmt->bindValue(":uuid", $uuid);
$stmt->execute();
$email_old = $stmt->fetch(PDO::FETCH_ASSOC)["email"];
if ($email_old === $email)
return new Response(
payload: ["target" => "email", "message" => "That is already your email address."],
satisfied: false
);
// Check if email address is already in use
$stmt = $this->conn->prepare("SELECT COUNT(*) as count
FROM users
WHERE email=:email;");
$stmt->bindValue(":email", $email);
$stmt->execute();
if ($stmt->fetch(PDO::FETCH_ASSOC)["count"] > 0) {
$this->conn->rollBack();
return new Response(
payload: ["target" => "email", "message" => "Email address already in use."],
satisfied: false
);
}
// Update email address
$stmt = $this->conn->prepare("UPDATE users
SET email=:email,
email_is_verified=0,
email_verification_token=:email_verification_token
WHERE uuid=:uuid;");
$stmt->bindValue(":uuid", $uuid);
$stmt->bindValue(":email", $email);
$stmt->bindValue(":email_verification_token", $email_verification_token);
$stmt->execute();
// Respond
$this->conn->commit();
$mailer->send_email_verification($email_old, $email, $email_verification_token);
return new Response(payload: null, satisfied: true);
}
/**
* Verifies an email address with a token.
*
* @param string $email the email address to verify
* @param string $email_verification_token the token to verify the email address with
* @return Response the server's response to the request
*/
public function verify_email(string $email, string $email_verification_token): Response
{
if (!filter_var($email, FILTER_VALIDATE_EMAIL) || strlen($email) > self::MAX_EMAIL_LENGTH)
return new Response(
payload: ["target" => "email", "message" => "Invalid email address."],
satisfied: false
);
$this->conn->beginTransaction();
$stmt = $this->conn->prepare("SELECT email_is_verified, email_verification_token
FROM users
WHERE email=:email;");
$stmt->bindValue(":email", $email);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if ($result === false || $result["email_verification_token"] === null
|| !hash_equals($result["email_verification_token"], $email_verification_token)) {
$this->conn->rollBack();
return new Response(
payload: ["target" => "email", "message" => "Failed to verify email address."],
satisfied: false
);
}
if ($result["email_is_verified"]) {
$this->conn->commit();
return new Response(payload: null, satisfied: true);
}
$stmt = $this->conn->prepare("UPDATE users
SET email_is_verified=1, email_verification_token=null
WHERE email=:email;");
$stmt->bindValue(":email", $email);
$stmt->execute();
$this->conn->commit();
return new Response(payload: null, satisfied: true);
}
/**
* Updates the indicated user's password.
*
* @param string $uuid the UUID of the user whose password should be updated
* @param string $password_old the old password
* @param string $password_new the new password
* @param string $password_confirm the confirmation of the new password
* @return Response a response with message `null` if the password was updated, or a response with a message
* explaining what went wrong otherwise
*/
public function set_password(string $uuid, string $password_old, string $password_new,
string $password_confirm): Response
{
// Validate
if (strlen($password_old) > self::MAX_PASSWORD_LENGTH)
return new Response(
payload: ["target" => "passwordOld", "message" => "Incorrect old password."],
satisfied: false
);
if (strlen($password_new) < self::MIN_PASSWORD_LENGTH || strlen($password_new) > self::MAX_PASSWORD_LENGTH)
return new Response(
payload: [
"target" => "passwordNew",
"message" => "Your password should be at least 8 and at most 64 characters long."
],
satisfied: false
);
if ($password_new !== $password_confirm)
return new Response(
payload: ["target" => "passwordConfirm", "message" => "New passwords do not match."],
satisfied: false
);
// Begin transaction
$this->conn->beginTransaction();
// Validate old password
$stmt = $this->conn->prepare("SELECT password FROM users WHERE uuid=:uuid;");
$stmt->bindValue(":uuid", $uuid);
$stmt->execute();
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if (!password_verify($password_old, $user["password"])) {
$this->conn->rollBack();
return new Response(
payload: ["target" => "passwordOld", "message" => "Incorrect old password."],
satisfied: false
);
}
// Update password
$stmt = $this->conn->prepare("UPDATE users
SET password=:password, password_update_time=unixepoch()
WHERE uuid=:uuid;");
$stmt->bindValue(":uuid", $uuid);
$stmt->bindValue(":password", password_hash($password_new, PASSWORD_DEFAULT));
$stmt->execute();
// Respond
$this->conn->commit();
return new Response(payload: null, satisfied: true);
}
}