Рефакторинг. В АПИ добавлены методы в изменения: username, email, password

This commit is contained in:
iIronside 2023-10-20 15:02:59 +03:00
parent b02d0b3ddf
commit 672d0833c5
10 changed files with 385 additions and 77 deletions

View File

@ -17,10 +17,10 @@ return [
'api' => [ 'api' => [
'components' => [ 'components' => [
'user' => [ 'user' => [
'identityClass' => 'frontend\modules\api\models\User', 'identityClass' => 'frontend\modules\api\models\profile\User',
'enableAutoLogin' => true, 'enableAutoLogin' => true,
'enableSession' => false, 'enableSession' => false,
'class' => 'frontend\modules\api\models\User', 'class' => 'frontend\modules\api\models\profile\User',
//'identityCookie' => ['name' => '_identity-api', 'httpOnly' => true], //'identityCookie' => ['name' => '_identity-api', 'httpOnly' => true],
], ],
], ],

View File

@ -2,12 +2,9 @@
namespace frontend\modules\api\controllers; namespace frontend\modules\api\controllers;
use common\models\User;
use common\models\UserCard; use common\models\UserCard;
use common\services\ProfileService; use frontend\modules\api\services\ProfileService;
use yii\helpers\ArrayHelper; use yii\helpers\ArrayHelper;
use yii\web\BadRequestHttpException;
use yii\web\NotFoundHttpException;
use yii\web\ServerErrorHttpException; use yii\web\ServerErrorHttpException;
class ProfileController extends ApiController class ProfileController extends ApiController
@ -30,33 +27,55 @@ class ProfileController extends ApiController
]); ]);
} }
private ProfileService $profileService;
public function __construct(
$id,
$module,
ProfileService $profileService,
$config = []
)
{
$this->profileService = $profileService;
parent::__construct($id, $module, $config);
}
/** /**
* @throws NotFoundHttpException * @param null $id
* @return array|null
*/ */
public function actionIndex($id = null): ?array public function actionIndex($id = null): ?array
{ {
return ProfileService::getProfile($id, \Yii::$app->request->get()); return $this->profileService->getProfile($id, \Yii::$app->request->get());
} }
/** /**
* @throws BadRequestHttpException * @param $id
* @return array|null
* @throws ServerErrorHttpException
*/ */
public function actionProfileWithReportPermission($id): ?array public function actionProfileWithReportPermission($id): ?array
{ {
return ProfileService::getProfileWithReportPermission($id); return $this->profileService->getProfileWithReportPermission($id);
} }
/** /**
* @param $user_id
* @return array
* @throws ServerErrorHttpException * @throws ServerErrorHttpException
*/ */
public function actionGetMainData($user_id): array public function actionGetMainData($user_id): array
{ {
return ProfileService::getMainData($user_id); return $this->profileService->getMainData($user_id);
} }
/**
* @param $card_id
* @return array
*/
public function actionPortfolioProjects($card_id): array public function actionPortfolioProjects($card_id): array
{ {
return ProfileService::getPortfolioProjects($card_id); return $this->profileService->getPortfolioProjects($card_id);
} }
/** /**
@ -83,7 +102,7 @@ class ProfileController extends ApiController
*/ */
public function actionPositionsList(): array public function actionPositionsList(): array
{ {
return ProfileService::getPositionsList(); return $this->profileService->getPositionsList();
} }
/** /**

View File

@ -3,16 +3,13 @@
namespace frontend\modules\api\controllers; namespace frontend\modules\api\controllers;
use common\behaviors\GsCors;
use common\classes\Debug;
use common\models\User; use common\models\User;
use frontend\modules\api\models\LoginForm; use frontend\modules\api\models\profile\ProfileChangeEmailForm;
use frontend\modules\api\models\profile\ProfileChangePersonalDataForm;
use frontend\modules\api\services\UserService;
use Yii; use Yii;
use yii\filters\ContentNegotiator; use yii\base\InvalidConfigException;
use yii\helpers\ArrayHelper;
use yii\rest\ActiveController;
use yii\web\BadRequestHttpException; use yii\web\BadRequestHttpException;
use yii\web\Response;
class UserController extends ApiController class UserController extends ApiController
{ {
@ -26,28 +23,20 @@ class UserController extends ApiController
} }
return $behaviors; return $behaviors;
// return ArrayHelper::merge(parent::behaviors(), [ }
// [
// 'class' => ContentNegotiator::class,
// 'formats' => [ private UserService $userService;
// 'application/json' => Response::FORMAT_JSON,
// ], public function __construct(
// ], $id,
// 'corsFilter' => [ $module,
// 'class' => GsCors::class, UserService $userService,
// 'cors' => [ $config = []
// 'Origin' => ['*'], )
// //'Access-Control-Allow-Credentials' => true, {
// 'Access-Control-Allow-Headers' => [ $this->userService = $userService;
// 'Access-Control-Allow-Origin', parent::__construct($id, $module, $config);
// 'Content-Type',
// 'Access-Control-Allow-Headers',
// 'Authorization',
// 'X-Requested-With'
// ],
// ]
// ],
// ]);
} }
public function actions() public function actions()
@ -59,28 +48,23 @@ class UserController extends ApiController
unset($actions['delete']); unset($actions['delete']);
} }
// protected function verbs(){ public function verbs(): array
// return [
// 'login' => ['POST']
// ];
// }
public function actionLogin()
{ {
$model = new LoginForm();
if ($model->load(Yii::$app->getRequest()->getBodyParams(), '') && $model->login()) {
/** @var User $user */
$user = $model->getUser();
return [ return [
'access_token' => $model->login(), 'change-personalData' => ['put', 'patch'],
'access_token_expired_at' => $model->getUser()->getTokenExpiredAt(), 'change-email' => ['put', 'patch'],
'id' => $user->id, 'change-password' => ['put', 'patch'],
'status' => $user->userCard->status ?? null,
'card_id' => $user->userCard->id ?? null,
]; ];
} else {
throw new BadRequestHttpException(json_encode($model->errors));
} }
/**
* @return array
* @throws BadRequestHttpException
* @throws InvalidConfigException
*/
public function actionLogin(): array
{
return $this->userService->login(Yii::$app->getRequest()->getBodyParams());
} }
/** /**
@ -101,16 +85,128 @@ class UserController extends ApiController
* ), * ),
* ) * )
* *
* @return \frontend\modules\api\models\User * @return \frontend\modules\api\models\profile\User
* @throws BadRequestHttpException * @throws BadRequestHttpException
*/ */
public function actionMe(): \frontend\modules\api\models\User public function actionMe(): \frontend\modules\api\models\profile\User
{ {
$user = \frontend\modules\api\models\User::findOne(Yii::$app->user->id); return $this->userService->findCurrentUser();
if (!$user){
throw new BadRequestHttpException("User not found");
} }
return $user; /**
*
* @OA\Put(path="/user/change-email",
* summary="Изменить email адрес",
* description="Метод для изменения email адреса пользователя",
* security={
* {"bearerAuth": {}}
* },
* tags={"User"},
*
* @OA\RequestBody(
* @OA\MediaType(
* mediaType="application/x-www-form-urlencoded",
* @OA\Schema(
* required={"newEmail"},
* @OA\Property(
* property="newEmail",
* type="string",
* description="Новый email адрес",
* ),
* ),
* ),
* ),
* @OA\Response(
* response=200,
* description="Возвращает сообщение об успехе",
* ),
* )
* )
*
* @return ProfileChangeEmailForm|string[]
*/
public function actionChangeEmail()
{
return $this->userService->changeEmail(Yii::$app->request->post());
}
/**
*
* @OA\Put(path="/user/change-password",
* summary="Изменить пароль",
* description="Метод для изменения пароля пользователя",
* security={
* {"bearerAuth": {}}
* },
* tags={"User"},
*
* @OA\RequestBody(
* @OA\MediaType(
* mediaType="application/x-www-form-urlencoded",
* @OA\Schema(
* required={"password", newPassword},
* @OA\Property(
* property="password",
* type="string",
* description="Старый пароль",
* ),
* @OA\Property(
* property="newPassword",
* type="string",
* description="Новый пароль",
* ),
* ),
* ),
* ),
* @OA\Response(
* response=200,
* description="Возвращает сообщение об успехе",
* ),
* )
* )
*
* @return ProfileChangeEmailForm|string[]
*/
public function actionChangePassword()
{
return $this->userService->changePassword(Yii::$app->request->post());
}
/**
*
* @OA\Put(path="/user/change-personal-data",
* summary="Изменить логин",
* description="Метод для изменения логина пользователя",
* security={
* {"bearerAuth": {}}
* },
* tags={"User"},
*
* @OA\RequestBody(
* @OA\MediaType(
* mediaType="application/x-www-form-urlencoded",
* @OA\Schema(
* required={"newUsername"},
* @OA\Property(
* property="newUsername",
* type="string",
* description="Новый логин",
* ),
* ),
* ),
* ),
* @OA\Response(
* response=200,
* description="Возвращает сообщение об успехе",
* ),
* )
* )
*
* @return ProfileChangePersonalDataForm|string[]
* @throws \Exception
*/
public function actionChangePersonalData()
{
return $this->userService->changeChangePersonalData(Yii::$app->request->post());
} }
} }

View File

@ -0,0 +1,32 @@
<?php
namespace frontend\modules\api\models\profile;
use yii\base\Model;
class ProfileChangeEmailForm extends Model
{
public $newEmail;
/**
* @return array
*/
public function rules()
{
return [
[['newEmail'], 'string'],
[['newEmail'], 'required'],
[['newEmail'], 'email'],
['newEmail', 'unique', 'targetAttribute' => 'email', 'targetClass' => User::class],
];
}
/**
* @return string
*/
public function formName(): string
{
return '';
}
}

View File

@ -0,0 +1,30 @@
<?php
namespace frontend\modules\api\models\profile;
use yii\base\Model;
class ProfileChangePasswordForm extends Model
{
public $password;
public $newPassword;
/**
* @return array
*/
public function rules()
{
return [
[['password', 'newPassword'], 'string'],
[['password', 'newPassword'], 'required'],
];
}
/**
* @return string
*/
public function formName(): string
{
return '';
}
}

View File

@ -0,0 +1,31 @@
<?php
namespace frontend\modules\api\models\profile;
use yii\base\Model;
class ProfileChangePersonalDataForm extends Model
{
/**
* @var string
*/
public $newUsername;
/**
* @return array
*/
public function rules()
{
return [
[['newUsername'], 'string', 'max' => 255],
[['newUsername'], 'required'],
];
}
/**
* @return string
*/
public function formName(): string
{
return '';
}
}

View File

@ -1,11 +1,10 @@
<?php <?php
namespace frontend\modules\api\models; namespace frontend\modules\api\models\profile;
use backend\modules\card\models\UserCard; use backend\modules\card\models\UserCard;
use common\classes\Debug;
use yii\base\Model; use yii\base\Model;
/** /**

View File

@ -1,9 +1,8 @@
<?php <?php
namespace frontend\modules\api\models; namespace frontend\modules\api\models\profile;
use backend\modules\card\models\UserCardSearch; use frontend\modules\api\services\ProfileService;
use common\services\ProfileService;
class User extends \common\models\User class User extends \common\models\User
{ {

View File

@ -1,13 +1,13 @@
<?php <?php
namespace common\services; namespace frontend\modules\api\services;
use common\models\Manager; use common\models\Manager;
use common\models\ManagerEmployee; use common\models\ManagerEmployee;
use common\models\Position; use common\models\Position;
use common\models\UserCard; use common\models\UserCard;
use common\models\UserCardPortfolioProjects; use common\models\UserCardPortfolioProjects;
use frontend\modules\api\models\ProfileSearchForm; use frontend\modules\api\models\profile\ProfileSearchForm;
use Yii; use Yii;
use yii\web\ServerErrorHttpException; use yii\web\ServerErrorHttpException;

View File

@ -0,0 +1,102 @@
<?php
namespace frontend\modules\api\services;
use Exception;
use frontend\modules\api\models\LoginForm;
use frontend\modules\api\models\profile\ProfileChangeEmailForm;
use frontend\modules\api\models\profile\ProfileChangePasswordForm;
use frontend\modules\api\models\profile\ProfileChangePersonalDataForm;
use frontend\modules\api\models\profile\User;
use Yii;
use yii\web\BadRequestHttpException;
class UserService
{
public function login(array $params)
{
$model = new LoginForm();
$model->load($params, '');
if ($model->load($params, '') && $model->login()) {
/** @var User $user */
$user = $model->getUser();
return [
'access_token' => $model->login(),
'access_token_expired_at' => $model->getUser()->getTokenExpiredAt(),
'id' => $user->id,
'status' => $user->userCard->status ?? null,
'card_id' => $user->userCard->id ?? null,
];
} else {
throw new BadRequestHttpException(json_encode($model->errors));
}
}
public function findCurrentUser(): User
{
$user = User::findOne(Yii::$app->user->id);
if (!$user){
throw new BadRequestHttpException("User not found");
}
return $user;
}
/**
* @throws Exception
*/
public function changeChangePersonalData(array $params)
{
$form = new ProfileChangePersonalDataForm();
$form->load($params);
if (!$form->validate()){
return $form;
}
$user = User::findOne(['id' => Yii::$app->user->identity->getId()]);;
$user->username = $form->newUsername;
if (!$user->save()) {
throw new Exception('User dont save');
}
return ['status' => 'success'];
}
public function changeEmail(array $params)
{
$form = new ProfileChangeEmailForm();
$form->load($params);
if (!$form->validate()) {
return $form;
}
$user = User::findOne(Yii::$app->user->identity->getId());
$user->email = $form->newEmail;
$user->save();
return ['status' => 'success'];
}
public function changePassword(array $params)
{
$form = new ProfileChangePasswordForm();
$form->load($params);
if (!$form->validate()){
return $form;
}
$user = User::findOne(Yii::$app->user->identity->getId());
if ($user->validatePassword($form->password)) {
$user->password_hash = Yii::$app->security->generatePasswordHash($form->newPassword);
$user->save();
return ['status' => 'success'];
}
return ['error' => 'Wrong password!'];
}
}