|
|
|
<?php
|
|
|
|
|
|
|
|
namespace core\services\auth;
|
|
|
|
|
|
|
|
use core\forms\auth\PasswordResetRequestForm;
|
|
|
|
use core\forms\auth\ResetPasswordForm;
|
|
|
|
use core\repositories\user\UserRepository;
|
|
|
|
use DomainException;
|
|
|
|
use RuntimeException;
|
|
|
|
use Yii;
|
|
|
|
use yii\base\Exception;
|
|
|
|
use yii\mail\MailerInterface;
|
|
|
|
|
|
|
|
class PasswordResetService
|
|
|
|
{
|
|
|
|
private MailerInterface $mailer;
|
|
|
|
private UserRepository $users;
|
|
|
|
|
|
|
|
public function __construct(UserRepository $users, MailerInterface $mailer)
|
|
|
|
{
|
|
|
|
$this->mailer = $mailer;
|
|
|
|
$this->users = $users;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param PasswordResetRequestForm $form
|
|
|
|
* @throws Exception
|
|
|
|
*/
|
|
|
|
public function request(PasswordResetRequestForm $form): void
|
|
|
|
{
|
|
|
|
$user = $this->users->getByEmail($form->email);
|
|
|
|
|
|
|
|
if (!$user->isActive()) {
|
|
|
|
throw new DomainException(Yii::t('auth', 'User is not active.'));
|
|
|
|
}
|
|
|
|
|
|
|
|
$user->requestPasswordReset();
|
|
|
|
$this->users->save($user);
|
|
|
|
|
|
|
|
$sent = $this->mailer
|
|
|
|
->compose(
|
|
|
|
['html' => 'auth/reset/confirm-html', 'text' => 'auth/reset/confirm-text'],
|
|
|
|
['user' => $user]
|
|
|
|
)
|
|
|
|
->setTo($user->email)
|
|
|
|
->setSubject('Password reset for ' . Yii::$app->name)
|
|
|
|
->send();
|
|
|
|
|
|
|
|
if (!$sent) {
|
|
|
|
throw new RuntimeException('Sending error.');
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public function validateToken($token): void
|
|
|
|
{
|
|
|
|
if (empty($token) || !is_string($token)) {
|
|
|
|
throw new DomainException('Password reset token cannot be blank.');
|
|
|
|
}
|
|
|
|
if (!$this->users->existsByPasswordResetToken($token)) {
|
|
|
|
throw new DomainException('Wrong password reset token.');
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param string $token
|
|
|
|
* @param ResetPasswordForm $form
|
|
|
|
* @throws Exception
|
|
|
|
*/
|
|
|
|
public function reset(string $token, ResetPasswordForm $form): void
|
|
|
|
{
|
|
|
|
$user = $this->users->getByPasswordResetToken($token);
|
|
|
|
$user->resetPassword($form->password);
|
|
|
|
$this->users->save($user);
|
|
|
|
}
|
|
|
|
}
|