From 52f8cb312f2570a3b6b53250b9d02b62eee4f1c7 Mon Sep 17 00:00:00 2001 From: iIronside Date: Wed, 1 Nov 2023 16:59:02 +0300 Subject: [PATCH] add tg bot auth method --- .../api/controllers/UserTgBotController.php | 55 +++++++ .../api/models/tg_bot/UserTgBotToken.php | 13 ++ .../tg_bot/forms/UserTgBotLoginForm.php | 56 +++++++ frontend/modules/api/services/UserService.php | 1 - .../api/services/UserTgBotTokenService.php | 140 ++++++++++-------- 5 files changed, 206 insertions(+), 59 deletions(-) create mode 100644 frontend/modules/api/models/tg_bot/forms/UserTgBotLoginForm.php diff --git a/frontend/modules/api/controllers/UserTgBotController.php b/frontend/modules/api/controllers/UserTgBotController.php index 7ab2b31..927ccd5 100644 --- a/frontend/modules/api/controllers/UserTgBotController.php +++ b/frontend/modules/api/controllers/UserTgBotController.php @@ -17,6 +17,16 @@ class UserTgBotController extends ApiController */ private UserTgBotTokenService $userTgBotTokenService; + public function behaviors() + { + $behaviors = parent::behaviors(); + if($this->action->id == "auth"){ + unset($behaviors['authenticator']); + } + + return $behaviors; + } + public function __construct( $id, $module, @@ -210,4 +220,49 @@ class UserTgBotController extends ApiController { return $this->userTgBotTokenService->getUserIdByDialogId($dialogId); } + + /** + * + * @OA\Post(path="/user-tg-bot/auth", + * summary="Аутентификация", + * description="Метод производит аутентификацию пользователя по токену ТГ бта", + * security={ + * {"bearerAuth": {}} + * }, + * tags={"TgBot"}, + * @OA\Parameter( + * name="token", + * in="query", + * example="1", + * required=true, + * description="токен пользователя", + * @OA\Schema( + * type="integer", + * ) + * ), + * @OA\Response( + * response=200, + * description="Возвращает сообщение об успехе", + * @OA\MediaType( + * mediaType="application/json", + * * @OA\Schema( + * schema="schemae_5cfb24156100e_category", + * @OA\Property(property="access_token",type="string",description="Category ID",example="HclquHysW2Y6LecQfM_ZZTjL4kBz-jOi"), + * @OA\Property(property="access_token_expired_at",type="dateTime",description="Expired at",example="2023-11-08"), + * @OA\Property(property="id",type="integer",description="ID",example=1), + * @OA\Property(property="status",type="integer",description="status",example=1), + * @OA\Property(property="card_id",type="integer",description="Card ID",example=1), + * ), + * ), + + * ), + * ) + * + * @return array + * @throws \yii\web\BadRequestHttpException + */ + public function actionAuth() + { + return $this->userTgBotTokenService->auth(Yii::$app->request->post()); + } } diff --git a/frontend/modules/api/models/tg_bot/UserTgBotToken.php b/frontend/modules/api/models/tg_bot/UserTgBotToken.php index 14c0fed..e4e273e 100644 --- a/frontend/modules/api/models/tg_bot/UserTgBotToken.php +++ b/frontend/modules/api/models/tg_bot/UserTgBotToken.php @@ -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 */ diff --git a/frontend/modules/api/models/tg_bot/forms/UserTgBotLoginForm.php b/frontend/modules/api/models/tg_bot/forms/UserTgBotLoginForm.php new file mode 100644 index 0000000..0138cd4 --- /dev/null +++ b/frontend/modules/api/models/tg_bot/forms/UserTgBotLoginForm.php @@ -0,0 +1,56 @@ + $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); + } +} diff --git a/frontend/modules/api/services/UserService.php b/frontend/modules/api/services/UserService.php index e8cd5df..1512210 100644 --- a/frontend/modules/api/services/UserService.php +++ b/frontend/modules/api/services/UserService.php @@ -16,7 +16,6 @@ class UserService public function login(array $params) { $model = new LoginForm(); - $model->load($params, ''); if ($model->load($params, '') && $model->login()) { /** @var User $user */ diff --git a/frontend/modules/api/services/UserTgBotTokenService.php b/frontend/modules/api/services/UserTgBotTokenService.php index 3c9cb21..e6ca60f 100644 --- a/frontend/modules/api/services/UserTgBotTokenService.php +++ b/frontend/modules/api/services/UserTgBotTokenService.php @@ -5,16 +5,97 @@ namespace frontend\modules\api\services; use DateTime; use Exception; -use frontend\modules\api\models\tg_bot\forms\TgBotDialogForm; use frontend\modules\api\models\profile\User; +use frontend\modules\api\models\tg_bot\forms\TgBotDialogForm; +use frontend\modules\api\models\tg_bot\forms\UserTgBotLoginForm; use frontend\modules\api\models\tg_bot\UserTgBotDialog; use frontend\modules\api\models\tg_bot\UserTgBotToken; use Yii; +use yii\web\BadRequestHttpException; class UserTgBotTokenService { const CHARACTERS = '0123456789'; + + public function auth(array $params) + { + /** @var UserTgBotToken $model */ + $model = new UserTgBotLoginForm; + + if ($model->load($params, '') && $model->validate()) { + + $userTgBotToken = UserTgBotToken::findOne(['token' => $model->token]); + $user = $userTgBotToken->user; + return [ + 'access_token' => $userTgBotToken->updateToken(), + 'access_token_expired_at' => $userTgBotToken->user->getTokenExpiredAt(), + 'id' => $user->id, + 'status' => $user->userCard->status ?? null, + 'card_id' => $user->userCard->id ?? null, + ]; + } else { + throw new BadRequestHttpException(json_encode($model->errors)); + } + } + + /** + * @param array $params + * @return TgBotDialogForm|string[] + * @throws Exception + */ + public function createDialog(array $params) + { + $form = new TgBotDialogForm(); + $form->load($params); + + if (!$form->validate()){ + return $form; + } + + $dialog = new UserTgBotDialog(); + $dialog->user_id = $form->userId; + $dialog->dialog_id = $form->dialogId; + + if (!$dialog->save()) { + throw new Exception('User dont save'); + } + + return ['status' => 'success']; + } + + /** + * @param string $userId + * @return array + * @throws Exception + */ + public function getDialogIdByUserId(string $userId) + { + $model = UserTgBotDialog::findOne(['user_id' => $userId]); + + if (!$model) { + throw new \Exception('dialog_id не найден!'); + } + + return ['dialog_id' => $model->dialog_id]; + } + + /** + * @param string $dialogId + * @return array + * @throws Exception + */ + public function getUserIdByDialogId(string $dialogId) + { + $model = UserTgBotDialog::findOne(['dialog_id' => $dialogId]); + + if (!$model) { + throw new \Exception('user_id не найден!'); + } + + return ['user_id' => $model->user_id]; + } + /** * @param int $userId * @return UserTgBotToken @@ -130,61 +211,4 @@ class UserTgBotTokenService return $model; } - - /** - * @param array $params - * @return TgBotDialogForm|string[] - * @throws Exception - */ - public function createDialog(array $params) - { - $form = new TgBotDialogForm(); - $form->load($params); - - if (!$form->validate()){ - return $form; - } - - $dialog = new UserTgBotDialog(); - $dialog->user_id = $form->userId; - $dialog->dialog_id = $form->dialogId; - - if (!$dialog->save()) { - throw new Exception('User dont save'); - } - - return ['status' => 'success']; - } - - /** - * @param string $userId - * @return array - * @throws Exception - */ - public function getDialogIdByUserId(string $userId) - { - $model = UserTgBotDialog::findOne(['user_id' => $userId]); - - if (!$model) { - throw new \Exception('dialog_id не найден!'); - } - - return ['dialog_id' => $model->dialog_id]; - } - - /** - * @param string $dialogId - * @return array - * @throws Exception - */ - public function getUserIdByDialogId(string $dialogId) - { - $model = UserTgBotDialog::findOne(['dialog_id' => $dialogId]); - - if (!$model) { - throw new \Exception('user_id не найден!'); - } - - return ['user_id' => $model->user_id]; - } } \ No newline at end of file