HM-98. Описаны все ошибки api для swagger'a

This commit is contained in:
vigdorov
2020-08-01 00:46:28 +03:00
parent 3711ef5f8f
commit b4e2ded4df
6 changed files with 237 additions and 66 deletions

View File

@ -1,5 +1,5 @@
import {Model, Connection, Document} from 'mongoose';
import {Injectable, NotFoundException, BadGatewayException, UnauthorizedException} from '@nestjs/common';
import {Injectable, NotFoundException, BadGatewayException, ConflictException, BadRequestException} from '@nestjs/common';
import {InjectConnection} from '@nestjs/mongoose';
import {DB_NAME, USERS_CONTROLLER, SECRET_JWT_ACCESS_KEY, SECRET_JWT_REFRESH_KEY} from 'src/consts';
import {User, UserSchema, CreateUserRequest, UserResponse, UserModel, UpdateUserRequest, TokenResponse} from './users.schema';
@ -53,7 +53,7 @@ export class UserService {
async findOne(login: string): Promise<UserResponse> {
const user = await this.userModel().findOne({login});
if (!user) {
throw new NotFoundException(`Пользователь с логином ${login} не найден`);
throw new NotFoundException(`Not found user "${login}"`);
}
return prepareUserToUserResponse(user);
}
@ -67,19 +67,29 @@ export class UserService {
const searchUser = await this.findUser(user.login);
if (searchUser) {
throw new NotFoundException(`Пользователь с логином ${user.login} уже существует`);
throw new ConflictException(`User login "${user.login}" is already in use`);
}
const Model = await this.userModel();
try {
const checkUser = new Model(user);
await validateModel(checkUser);
} catch (e) {
if (e?.message?.includes('validation failed')) {
throw new BadRequestException(e.message);
}
throw e;
}
const salt = await bcrypt.genSalt(10);
const password = await bcrypt.hash(user.password, salt);
const Model = await this.userModel();
const createUser = new Model({
...user,
salt,
password,
});
await validateModel(createUser);
const savedUser = await createUser.save();
@ -89,12 +99,24 @@ export class UserService {
async update(user: UpdateUserRequest): Promise<UserResponse> {
const searchUser = await this.userModel().findOne({login: user.login});
if (!searchUser) {
throw new NotFoundException(`Not found user login "${user.login}"`)
}
const Model = await this.userModel();
const updateUser = new Model({
...user,
password: searchUser.password,
});
await validateModel(updateUser);
try {
await validateModel(updateUser);
} catch (e) {
if (e?.message?.includes('validation failed')) {
throw new BadRequestException(e.message);
}
throw e;
}
await searchUser.updateOne({
...{
@ -108,6 +130,10 @@ export class UserService {
async removeOne(login: string): Promise<UserResponse> {
const searchUser = await this.userModel().findOne({login});
if (!searchUser) {
throw new NotFoundException(`Not found user login "${login}"`);
}
await this.userModel().deleteOne({login});
return prepareUserToUserResponse(searchUser);
@ -144,14 +170,14 @@ export class UserService {
return this.generateTokens(login, host, agent);
}
throw new UnauthorizedException('Не верный пользователь или пароль');
throw new BadRequestException('Invalid user or password');
}
verifyToken(token: string, secret: string): void {
try {
jwt.verify(token, secret);
} catch (e) {
throw new UnauthorizedException('Авторизация устарела');
throw new BadRequestException('Authorization is outdated');
}
}
@ -166,11 +192,16 @@ export class UserService {
if (searchUser && this.checkToken(token, host, agent)) {
return this.generateTokens(token.login, host, agent);
}
throw new UnauthorizedException('Не санкционированный запрос');
throw new BadRequestException('Unauthorized request');
}
async checkAccessToken(access_token: string, host: string, agent: string): Promise<boolean> {
this.verifyToken(access_token, SECRET_JWT_ACCESS_KEY);
try {
this.verifyToken(access_token, SECRET_JWT_ACCESS_KEY);
} catch (e) {
return false;
}
const token = jwt.decode(access_token) as Token;
const searchUser = await this.findUser(token.login);
return searchUser && this.checkToken(token, host, agent);