68 lines
2.3 KiB
PHP
68 lines
2.3 KiB
PHP
<?php
|
|
|
|
namespace com\fwdekker\deathnotifier\user;
|
|
|
|
use com\fwdekker\deathnotifier\Action;
|
|
use com\fwdekker\deathnotifier\validation\InvalidTypeException;
|
|
use com\fwdekker\deathnotifier\validation\InvalidValueException;
|
|
use com\fwdekker\deathnotifier\validation\IsEmailRule;
|
|
use com\fwdekker\deathnotifier\validation\IsStringRule;
|
|
use com\fwdekker\deathnotifier\validation\IsValidCsrfTokenRule;
|
|
use com\fwdekker\deathnotifier\validation\RuleSet;
|
|
use com\fwdekker\deathnotifier\validation\LoginValidator;
|
|
|
|
|
|
/**
|
|
* Logs in the user if the credentials are correct.
|
|
*/
|
|
class LoginAction extends Action
|
|
{
|
|
/**
|
|
* @var UserList the list of users to check credentials in
|
|
*/
|
|
private readonly UserList $user_list;
|
|
|
|
|
|
/**
|
|
* Constructs a new `LoginAction`.
|
|
*
|
|
* @param UserList $user_list the list of users to check credentials in
|
|
*/
|
|
public function __construct(UserList $user_list)
|
|
{
|
|
$this->user_list = $user_list;
|
|
}
|
|
|
|
|
|
/**
|
|
* Logs in the user if the credentials are correct.
|
|
*
|
|
* Requires that the user is logged out and that a valid CSRF token is present.
|
|
*
|
|
* @param array<int|string, mixed> $inputs `"token": string`: a valid CSRF token, `"email": string`: the email to
|
|
* log in with, `"password": string`: the password to log in with
|
|
* @return null
|
|
* @throws InvalidTypeException if any of the inputs has the incorrect type
|
|
* @throws InvalidValueException if the user is logged in, if no account with the given email address exists, if the
|
|
* password is wrong, or if no valid CSRF token is present
|
|
*/
|
|
public function handle(array $inputs): mixed
|
|
{
|
|
(new LoginValidator(validate_logged_out: true))->check($_SESSION);
|
|
(new RuleSet([
|
|
"token" => [new IsValidCsrfTokenRule()],
|
|
"email" => [new IsEmailRule()],
|
|
"password" => [new IsStringRule()],
|
|
]))->check($inputs);
|
|
|
|
$user_data = $this->user_list->get_user_by_email($inputs["email"]);
|
|
if ($user_data === null)
|
|
throw new InvalidValueException("No user with that email address has been registered.", "email");
|
|
if (!password_verify($inputs["password"], $user_data["password"]))
|
|
throw new InvalidValueException("Incorrect password.", "password");
|
|
|
|
$_SESSION["uuid"] = $user_data["uuid"];
|
|
return null;
|
|
}
|
|
}
|