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.
		
		
		
		
			
				
					63 lines
				
				1.7 KiB
			
		
		
			
		
	
	
					63 lines
				
				1.7 KiB
			| 
											8 years ago
										 | <?php
 | ||
|  | 
 | ||
|  | namespace core\services\auth;
 | ||
|  | 
 | ||
|  | use core\forms\auth\PasswordResetRequestForm;
 | ||
|  | use core\forms\auth\ResetPasswordForm;
 | ||
|  | use core\repositories\user\UserRepository;
 | ||
|  | use Yii;
 | ||
|  | use yii\mail\MailerInterface;
 | ||
|  | 
 | ||
|  | class PasswordResetService
 | ||
|  | {
 | ||
|  |     private $mailer;
 | ||
|  |     private $users;
 | ||
|  | 
 | ||
|  |     public function __construct(UserRepository $users, MailerInterface $mailer)
 | ||
|  |     {
 | ||
|  |         $this->mailer = $mailer;
 | ||
|  |         $this->users = $users;
 | ||
|  |     }
 | ||
|  | 
 | ||
|  |     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.');
 | ||
|  |         }
 | ||
|  |     }
 | ||
|  | 
 | ||
|  |     public function reset(string $token, ResetPasswordForm $form): void
 | ||
|  |     {
 | ||
|  |         $user = $this->users->getByPasswordResetToken($token);
 | ||
|  |         $user->resetPassword($form->password);
 | ||
|  |         $this->users->save($user);
 | ||
|  |     }
 | ||
|  | }
 |