1 | <?php |
||
2 | namespace App\Http\Api\Backend\Form; |
||
3 | |||
4 | use App\Model\Session; |
||
5 | use App\Factory\SessionFactory; |
||
6 | use Yii; |
||
7 | |||
8 | class SessionRefreshForm extends UserForm |
||
9 | { |
||
10 | public $refresh_token; |
||
11 | |||
12 | public function rules() |
||
13 | { |
||
14 | return array_merge(parent::rules(), [ |
||
15 | [['refresh_token'], 'trim'], |
||
16 | [['refresh_token'], 'string'], |
||
17 | [['refresh_token'], 'required'], |
||
18 | ['refresh_token', 'validateRefreshToken'], |
||
19 | ]); |
||
20 | } |
||
21 | |||
22 | public function validateRefreshToken($attribute) |
||
23 | { |
||
24 | if ($this->hasErrors()) { |
||
25 | return; |
||
26 | } |
||
27 | |||
28 | $session = $this->getSession(); |
||
29 | if (!$session || $this->$attribute !== $session->refresh_token) { |
||
30 | $this->addError($attribute, Yii::t('app', '{attribute} is invalid')); |
||
31 | } |
||
32 | if ($session->isRefreshTokenExpired()) { |
||
33 | $this->addError($attribute, Yii::t('app', '{attribute} is expired')); |
||
34 | } |
||
35 | } |
||
36 | |||
37 | protected function handleInternal() |
||
38 | { |
||
39 | $user = $this->getUser(); |
||
40 | $transaction = Yii::$app->getDb()->beginTransaction(); |
||
41 | try { |
||
42 | // creates new session |
||
43 | $newSession = SessionFactory::create( |
||
44 | $user->id, |
||
45 | Yii::$app->params['user.session.duration'], |
||
46 | Yii::$app->params['user.session.refreshTokenDuration'], |
||
47 | Yii::$app->getRequest() |
||
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
48 | ); |
||
49 | if (!$newSession->save()) { |
||
50 | Yii::error($newSession->getErrors()); |
||
51 | throw new \RuntimeException('Unable to create new session'); |
||
52 | } |
||
53 | |||
54 | // makes old session expires in a few time |
||
55 | $oldSession = $this->getSession(); |
||
56 | $now = time(); |
||
57 | $oldSession->expire_time = $now + Yii::$app->params['user.session.durationAfterRefresh']; |
||
58 | $oldSession->refresh_token_expire_time = $now - 1; // expire old refresh token right now |
||
59 | if (!$newSession->save()) { |
||
60 | Yii::error($newSession->getErrors()); |
||
61 | throw new \RuntimeException('Unable to update old session'); |
||
62 | } |
||
63 | |||
64 | $transaction->commit(); |
||
65 | |||
66 | return [ |
||
67 | 'token' => $newSession->token, |
||
68 | 'expires_in' => $newSession->getExpiresIn(), |
||
69 | 'refresh_token' => $newSession->refresh_token, |
||
70 | 'refresh_token_expire_in' => $newSession->getRefreshTokenExpiresIn(), |
||
71 | ]; |
||
72 | } catch (\Throwable $e) { |
||
73 | $transaction->rollBack(); |
||
74 | throw $e; |
||
75 | } |
||
76 | } |
||
77 | |||
78 | protected function getSession(): ?Session |
||
79 | { |
||
80 | $user = $this->getUser(); |
||
81 | return $user->session; |
||
82 | } |
||
83 | } |
||
84 |