1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Library for confirmation tokens. |
4
|
|
|
* |
5
|
|
|
* @link https://github.com/hiqdev/php-confirmator |
6
|
|
|
* @package php-confirmator |
7
|
|
|
* @license BSD-3-Clause |
8
|
|
|
* @copyright Copyright (c) 2016-2017, HiQDev (http://hiqdev.com/) |
9
|
|
|
*/ |
10
|
|
|
|
11
|
|
|
namespace hiqdev\yii2\confirmator; |
12
|
|
|
|
13
|
|
|
use hiqdev\php\confirmator\ServiceInterface; |
14
|
|
|
use hiqdev\php\confirmator\ServiceTrait; |
15
|
|
|
use hiqdev\php\confirmator\StorageInterface; |
16
|
|
|
use Yii; |
17
|
|
|
use yii\helpers\Inflector; |
18
|
|
|
|
19
|
|
|
class Service extends \yii\base\Component implements ServiceInterface |
20
|
|
|
{ |
21
|
|
|
use ServiceTrait; |
22
|
|
|
|
23
|
|
|
protected $_storage; |
24
|
|
|
|
25
|
|
|
public function __construct(StorageInterface $storage, array $config = []) |
26
|
|
|
{ |
27
|
|
|
parent::__construct($config); |
28
|
|
|
$this->_storage = $storage; |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
public function setStorage($value) |
32
|
|
|
{ |
33
|
|
|
$this->_storage = $value; |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
public function getStorage() |
37
|
|
|
{ |
38
|
|
|
if (is_array($this->_storage)) { |
39
|
|
|
$config = $this->_storage; |
40
|
|
|
if (isset($config['path']) && is_string($config['path'])) { |
41
|
|
|
$config['path'] = Yii::getAlias($config['path']); |
42
|
|
|
} |
43
|
|
|
$this->_storage = Yii::createObject($config); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
return $this->_storage; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
public function mailToken($user, $action, array $data = []) |
50
|
|
|
{ |
51
|
|
|
if (!$user) { |
52
|
|
|
return false; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
if (Yii::$app->has('authManager')) { |
56
|
|
|
$auth = Yii::$app->authManager; |
57
|
|
|
if ($auth->getItem($action) && !$auth->checkAccess($user->id, $action)) { |
58
|
|
|
return false; |
59
|
|
|
} |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
$lifetime = Yii::$app->params['confirmator.mail.token.lifetime'] ?? '1 hour'; |
63
|
|
|
$token = $this->issueToken(array_merge([ |
64
|
|
|
'action' => $action, |
65
|
|
|
'id' => $user->id, |
66
|
|
|
'email' => $user->email, |
67
|
|
|
'username' => $user->username, |
68
|
|
|
'notAfter' => "+{$lifetime}", |
69
|
|
|
], $data)); |
70
|
|
|
|
71
|
|
|
$view = lcfirst(Inflector::id2camel($action . '-token')); |
72
|
|
|
|
73
|
|
|
$email_confirmed = $user->email_confirmed ?? $user->email; |
74
|
|
|
|
75
|
|
|
return Yii::$app->mailer->compose() |
76
|
|
|
->renderHtmlBody($view, compact('user', 'token')) |
77
|
|
|
->setTo([$email_confirmed => $user->username]) |
78
|
|
|
->send(); |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|