Skip to content

Commit

Permalink
6.30. Добавит метод login в UserController.
Browse files Browse the repository at this point in the history
Добавим в контроллер `UserController` метод `login`. Он будет
использоваться для авторизации пользователя в системе. Авторизацию мы реализуем позже, а пока опишем одну проверку (существует пользователь или нет) и вернём в качестве результата «Not implemented».

При реализации нам потребуется DTO — `LoginUserDto`. Поэтому создадим новый класс для DTO по аналогии с ранее созданными.

Для тестирования обработчика сразу добавим  запрос в `user.http`.
  • Loading branch information
AntonovIgor committed Sep 10, 2024
1 parent cc55800 commit 25a27d2
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/shared/modules/user/dto/login-user.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export class LoginUserDto {
public email: string;
public password: string;
}
6 changes: 6 additions & 0 deletions src/shared/modules/user/login-user-request.type.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { Request } from 'express';

import { RequestBody, RequestParams } from '../../libs/rest/index.js';
import { LoginUserDto } from './dto/login-user.dto.js';

export type LoginUserRequest = Request<RequestParams, RequestBody, LoginUserDto>;
23 changes: 23 additions & 0 deletions src/shared/modules/user/user.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { UserService } from './user-service.interface.js';
import { Config, RestSchema } from '../../libs/config/index.js';
import { fillDTO } from '../../helpers/index.js';
import { UserRdo } from './rdo/user.rdo.js';
import { LoginUserRequest } from './login-user-request.type.js';

@injectable()
export class UserController extends BaseController {
Expand All @@ -22,6 +23,7 @@ export class UserController extends BaseController {
this.logger.info('Register routes for UserController…');

this.addRoute({ path: '/register', method: HttpMethod.Post, handler: this.create });
this.addRoute({ path: '/login', method: HttpMethod.Post, handler: this.login });
}

public async create(
Expand All @@ -41,4 +43,25 @@ export class UserController extends BaseController {
const result = await this.userService.create(body, this.configService.get('SALT'));
this.created(res, fillDTO(UserRdo, result));
}

public async login(
{ body }: LoginUserRequest,
_res: Response,
): Promise<void> {
const existsUser = await this.userService.findByEmail(body.email);

if (! existsUser) {
throw new HttpError(
StatusCodes.UNAUTHORIZED,
`User with email ${body.email} not found.`,
'UserController',
);
}

throw new HttpError(
StatusCodes.NOT_IMPLEMENTED,
'Not implemented',
'UserController',
);
}
}
12 changes: 12 additions & 0 deletions src/shared/modules/user/user.http
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,15 @@ Content-Type: application/json
}

###

## Авторизовать пользователя

POST http://localhost:4000/users/login HTTP/1.1
Content-Type: application/json

{
"email": "[email protected]",
"password": "shining"
}

###

0 comments on commit 25a27d2

Please sign in to comment.