You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
75 lines
2.0 KiB
75 lines
2.0 KiB
<?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); |
|
} |
|
}
|
|
|