2016-05-31 03:33:30 +05:30
|
|
|
<?php
|
2019-08-01 14:47:12 +05:30
|
|
|
declare(strict_types=1);
|
|
|
|
|
2016-05-31 03:33:30 +05:30
|
|
|
namespace api\models\authentication;
|
|
|
|
|
2017-11-19 21:02:51 +05:30
|
|
|
use api\aop\annotations\CollectModelMetrics;
|
2016-05-31 03:33:30 +05:30
|
|
|
use api\models\base\ApiForm;
|
2016-06-17 02:02:23 +05:30
|
|
|
use common\helpers\Error as E;
|
2016-05-31 03:33:30 +05:30
|
|
|
use common\models\AccountSession;
|
2019-08-01 14:47:12 +05:30
|
|
|
use Webmozart\Assert\Assert;
|
2016-05-31 03:33:30 +05:30
|
|
|
use Yii;
|
|
|
|
|
|
|
|
class RefreshTokenForm extends ApiForm {
|
|
|
|
|
|
|
|
public $refresh_token;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @var AccountSession|null
|
|
|
|
*/
|
|
|
|
private $session;
|
|
|
|
|
2019-08-01 14:47:12 +05:30
|
|
|
public function rules(): array {
|
2016-05-31 03:33:30 +05:30
|
|
|
return [
|
2016-06-17 02:02:23 +05:30
|
|
|
['refresh_token', 'required', 'message' => E::REFRESH_TOKEN_REQUIRED],
|
2016-05-31 03:33:30 +05:30
|
|
|
['refresh_token', 'validateRefreshToken'],
|
|
|
|
];
|
|
|
|
}
|
|
|
|
|
2019-08-01 14:47:12 +05:30
|
|
|
public function validateRefreshToken(): void {
|
|
|
|
if (!$this->hasErrors() && $this->findSession() === null) {
|
|
|
|
$this->addError('refresh_token', E::REFRESH_TOKEN_NOT_EXISTS);
|
2016-05-31 03:33:30 +05:30
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2017-11-19 21:02:51 +05:30
|
|
|
* @CollectModelMetrics(prefix="authentication.renew")
|
2016-05-31 03:33:30 +05:30
|
|
|
*/
|
2019-08-01 14:47:12 +05:30
|
|
|
public function renew(): ?AuthenticationResult {
|
2016-05-31 03:33:30 +05:30
|
|
|
if (!$this->validate()) {
|
2019-08-01 14:47:12 +05:30
|
|
|
return null;
|
2016-05-31 03:33:30 +05:30
|
|
|
}
|
|
|
|
|
2019-08-01 14:47:12 +05:30
|
|
|
/** @var AccountSession $session */
|
|
|
|
$session = $this->findSession();
|
|
|
|
$account = $session->account;
|
|
|
|
|
|
|
|
$transaction = Yii::$app->db->beginTransaction();
|
|
|
|
|
2019-12-04 23:40:15 +05:30
|
|
|
$token = Yii::$app->tokensFactory->createForWebAccount($account, $session);
|
2019-08-01 14:47:12 +05:30
|
|
|
|
|
|
|
$session->setIp(Yii::$app->request->userIP);
|
|
|
|
$session->touch('last_refreshed_at');
|
|
|
|
Assert::true($session->save(), 'Cannot update session info');
|
2016-05-31 03:33:30 +05:30
|
|
|
|
2019-08-01 14:47:12 +05:30
|
|
|
$transaction->commit();
|
|
|
|
|
|
|
|
return new AuthenticationResult($token, $session->refresh_token);
|
2016-05-31 03:33:30 +05:30
|
|
|
}
|
|
|
|
|
2019-08-01 14:47:12 +05:30
|
|
|
private function findSession(): ?AccountSession {
|
2016-05-31 03:33:30 +05:30
|
|
|
if ($this->session === null) {
|
|
|
|
$this->session = AccountSession::findOne(['refresh_token' => $this->refresh_token]);
|
|
|
|
}
|
|
|
|
|
|
|
|
return $this->session;
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|