add tg bot auth method
This commit is contained in:
@ -4,6 +4,7 @@ namespace frontend\modules\api\models\tg_bot;
|
||||
|
||||
|
||||
use frontend\modules\api\models\profile\User;
|
||||
use Yii;
|
||||
use yii\db\ActiveQuery;
|
||||
|
||||
/**
|
||||
@ -43,6 +44,8 @@ use yii\db\ActiveQuery;
|
||||
*/
|
||||
class UserTgBotToken extends \common\models\UserTgBotToken
|
||||
{
|
||||
const EXPIRE_TIME = 604800; // token expiration time, valid for 7 days
|
||||
|
||||
public function fields(): array
|
||||
{
|
||||
return [
|
||||
@ -59,6 +62,16 @@ class UserTgBotToken extends \common\models\UserTgBotToken
|
||||
return [];
|
||||
}
|
||||
|
||||
public function updateToken()
|
||||
{
|
||||
$access_token = $this->user->generateAccessToken();
|
||||
$this->user->access_token_expired_at = date('Y-m-d', time() + static::EXPIRE_TIME);
|
||||
$this->user->save(false);
|
||||
|
||||
Yii::$app->user->login($this->user, static::EXPIRE_TIME);
|
||||
return $access_token;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return ActiveQuery
|
||||
*/
|
||||
|
@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
namespace frontend\modules\api\models\tg_bot\forms;
|
||||
use DateTime;
|
||||
use frontend\modules\api\models\profile\User;
|
||||
use frontend\modules\api\models\tg_bot\UserTgBotToken;
|
||||
use yii\base\Model;
|
||||
|
||||
class UserTgBotLoginForm extends Model
|
||||
{
|
||||
public $token;
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function rules()
|
||||
{
|
||||
return [
|
||||
[['token'], 'string'],
|
||||
[['token'], 'required'],
|
||||
['token', 'validateToken'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws \Exception
|
||||
*/
|
||||
public function validateToken()
|
||||
{
|
||||
$model = UserTgBotToken::findOne(['token' => $this->token]);
|
||||
|
||||
if (!empty($model)) {
|
||||
|
||||
$currentTime = new DateTime();
|
||||
|
||||
if ($currentTime > new DateTime($model->expired_at)) {
|
||||
$this->addError('token', 'Токен не действителен!');
|
||||
}
|
||||
} else {
|
||||
$this->addError('token', 'Пользователь с соответствующим токеном не найден!');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function formName(): string
|
||||
{
|
||||
return '';
|
||||
}
|
||||
|
||||
public function getUser()
|
||||
{
|
||||
return User::findOne($this->userId);
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user