|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace app\modules\auth\services; |
|
4
|
|
|
|
|
5
|
|
|
use Yii; |
|
6
|
|
|
use yii\base\{Exception, UserException}; |
|
7
|
|
|
use yii\web\BadRequestHttpException; |
|
8
|
|
|
use app\models\entity\User; |
|
9
|
|
|
|
|
10
|
|
|
class ConfirmEmail |
|
11
|
|
|
{ |
|
12
|
|
|
private $tokenizer; |
|
13
|
|
|
|
|
14
|
|
|
public function __construct(Tokenizer $tokenizer) |
|
15
|
|
|
{ |
|
16
|
|
|
$this->tokenizer = $tokenizer; |
|
17
|
|
|
} |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* Confirm email |
|
21
|
|
|
* |
|
22
|
|
|
* @param string $token |
|
23
|
|
|
* @throws BadRequestHttpException |
|
24
|
|
|
*/ |
|
25
|
|
|
public function setConfirmed(string $token): void |
|
26
|
|
|
{ |
|
27
|
|
|
if ($this->tokenizer->validate($token)) { |
|
28
|
|
|
$user = User::find()->emailConfirmToken($token)->one(); |
|
29
|
|
|
|
|
30
|
|
|
if ($user) { |
|
31
|
|
|
$user->setConfirmed(); |
|
32
|
|
|
if (!$user->save()) { |
|
33
|
|
|
throw new Exception(Yii::t('app', 'An error occurred while confirming')); |
|
34
|
|
|
} |
|
35
|
|
|
return; |
|
36
|
|
|
} |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
throw new BadRequestHttpException(Yii::t('app', 'Invalid token for activate account')); |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
/** |
|
43
|
|
|
* Sends an email with a link, for confirm the email |
|
44
|
|
|
* |
|
45
|
|
|
* @throws UserException |
|
46
|
|
|
*/ |
|
47
|
|
|
public function sendEmail(User $user): void |
|
48
|
|
|
{ |
|
49
|
|
|
if (!$this->tokenizer->validate($user->email_confirm_token)) { |
|
50
|
|
|
$user->setEmailConfirmToken($this->tokenizer->generate()); |
|
51
|
|
|
$user->updateAttributes([ |
|
52
|
|
|
'email_confirm_token' => $user->email_confirm_token, |
|
53
|
|
|
'date_confirm' => $user->date_confirm, |
|
54
|
|
|
]); |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
$sent = Yii::$app->mailer |
|
58
|
|
|
->compose('emailConfirmToken', ['user' => $user]) |
|
59
|
|
|
->setTo($user->email) |
|
60
|
|
|
->setSubject(Yii::t('app', 'Activate Your Account')) |
|
61
|
|
|
->send(); |
|
62
|
|
|
|
|
63
|
|
|
if (!$sent) { |
|
64
|
|
|
throw new UserException( |
|
65
|
|
|
Yii::t('app', 'An error occurred while sending a message to activate account') |
|
66
|
|
|
); |
|
67
|
|
|
} |
|
68
|
|
|
} |
|
69
|
|
|
} |
|
70
|
|
|
|