HM-127. Доработки ручек авторизаций

This commit is contained in:
vigdorov
2020-09-10 22:05:09 +03:00
parent a33d901c39
commit 6e3f003cd4
5 changed files with 50 additions and 21 deletions

View File

@ -1,17 +1,11 @@
import {Model, Connection, Document} from 'mongoose';
import {Injectable, NotFoundException, BadGatewayException, ConflictException, BadRequestException} from '@nestjs/common';
import {Injectable, NotFoundException, BadGatewayException, ConflictException, BadRequestException, NotAcceptableException} 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, UpdateUserSelf} from './users.schema';
import * as bcrypt from 'bcrypt';
import * as jwt from 'jsonwebtoken';
interface Token {
login: string;
agent: string;
iat: number;
exp: number;
}
import {Token} from './types';
const validateModel = async (user: Document) => {
try {
@ -62,7 +56,13 @@ export class UserService {
return users.map(prepareUserToUserResponse);
}
async create(user: CreateUserRequest): Promise<UserResponse> {
async create(user: CreateUserRequest, requesterLogin: string): Promise<UserResponse> {
const requester = await this.findUser(requesterLogin);
if (!requester.is_admin) {
throw new NotAcceptableException(`Действие запрещено`);
}
const searchUser = await this.findUser(user.login);
if (searchUser) {
@ -122,15 +122,20 @@ export class UserService {
}
await searchUser.updateOne({
...{
avatar: user.avatar,
},
is_admin: user.is_admin,
avatar: user.avatar,
});
return prepareUserToUserResponse(updateUser);
}
async removeOne(login: string): Promise<UserResponse> {
async removeOne(login: string, requesterLogin: string): Promise<UserResponse> {
const requester = await this.findUser(requesterLogin);
if (!requester.is_admin) {
throw new NotAcceptableException(`Действие запрещено`);
}
if (login === 'admin') {
throw new BadRequestException('Запрещено удалять пользователя admin');
}
@ -217,11 +222,23 @@ export class UserService {
return await this.findOne(token.login);
}
async updateUser(user: UpdateUserRequest, requesterLogin: string): Promise<UserResponse> {
const requester = await this.findUser(requesterLogin);
if (!requester.is_admin) {
throw new NotAcceptableException(`Действие запрещено`);
}
return await this.update(user);
}
async updateSelf(access_token: string, {avatar}: UpdateUserSelf): Promise<UserResponse> {
const {login} = jwt.decode(access_token) as Token;
const requester = await this.findUser(login);
return await this.update({
avatar,
login,
is_admin: requester.is_admin,
});
}