Created
February 13, 2024 22:09
-
-
Save denrad/e9fb057dc0979bdc386515d3ac6a0f64 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| namespace app\modules\api\controllers; | |
| use app\modules\admin\models\forms\LoginForm; | |
| use OpenApi\Attributes as OA; | |
| use Yii; | |
| use yii\filters\auth\HttpBearerAuth; | |
| use yii\rest\Controller; | |
| use yii\web\Response; | |
| class UserController extends Controller | |
| { | |
| public function behaviors(): array | |
| { | |
| return [ | |
| 'authenticator' => [ | |
| 'class' => HttpBearerAuth::class, | |
| 'except' => ['login'], | |
| ], | |
| ]; | |
| } | |
| #[OA\Post( | |
| path: '/user/login', | |
| summary: 'Авторизация', | |
| requestBody: new OA\RequestBody( | |
| description: 'Данные для авторизации', | |
| required: true, | |
| content: new OA\JsonContent( | |
| ref: '#/components/schemas/LoginRequest', | |
| type: 'object', | |
| ) | |
| ), | |
| tags: ['User'], | |
| responses: [ | |
| new OA\Response( | |
| response: 200, description: 'OK', content: new OA\JsonContent(ref: '#/components/schemas/LoginResponse') | |
| ), | |
| new OA\Response(response: 401, description: 'Not allowed'), | |
| ], | |
| )] | |
| public function actionLogin(): Response | |
| { | |
| $model = new LoginForm(); | |
| $model->load($this->request->bodyParams, ''); | |
| if ($auth = $model->auth()) { | |
| return $this->asJson($auth); | |
| } | |
| $this->response->setStatusCode(401); | |
| return $this->asJson(['success' => false, 'error' => $model->getFirstError('password')]); | |
| } | |
| #[OA\Post(path: '/user/logout', summary: 'Выход из системы', tags: ['User'])] | |
| #[OA\Response( | |
| response: 200, | |
| description: 'Успешный выход' | |
| )] | |
| public function actionLogout(): Response | |
| { | |
| Yii::$app->user->logout(); | |
| return $this->asJson(['success' => true]); | |
| } | |
| protected function verbs(): array | |
| { | |
| return [ | |
| 'login' => ['post'], | |
| 'logout' => ['post'], | |
| ]; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment