add tg bot auth method

This commit is contained in:
iIronside 2023-11-01 16:59:02 +03:00
parent 8ca7bef498
commit 52f8cb312f
5 changed files with 206 additions and 59 deletions

View File

@ -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());
}
}

View File

@ -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
*/

View File

@ -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);
}
}

View File

@ -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 */

View File

@ -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];
}
}