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,5 +1,7 @@
import {Injectable, UnauthorizedException, HttpService} from '@nestjs/common'; import {Injectable, UnauthorizedException, HttpService} from '@nestjs/common';
import {Request} from 'express'; import {Request} from 'express';
import * as jwt from 'jsonwebtoken';
import {Token} from 'src/users/types';
@Injectable() @Injectable()
export class AuthService { export class AuthService {
@ -7,7 +9,7 @@ export class AuthService {
private http: HttpService private http: HttpService
) {} ) {}
async checkRequest(request: Request): Promise<boolean> { async checkRequest(request: Request): Promise<Token> {
const {data} = await this.http.post('http://api.auth.vigdorov.ru/auth/check', { const {data} = await this.http.post('http://api.auth.vigdorov.ru/auth/check', {
access_token: request.headers.authorization, access_token: request.headers.authorization,
agent: request.headers['user-agent'] agent: request.headers['user-agent']
@ -16,6 +18,7 @@ export class AuthService {
if (!data) { if (!data) {
throw new UnauthorizedException('Доступ запрещен'); throw new UnauthorizedException('Доступ запрещен');
} }
return data;
return jwt.decode(request.headers.authorization) as Token;
} }
} }

6
src/users/types.ts Normal file
View File

@ -0,0 +1,6 @@
export interface Token {
login: string;
agent: string;
iat: number;
exp: number;
}

View File

@ -102,9 +102,9 @@ export class UsersController {
description: 'Объект для создания пользователя' description: 'Объект для создания пользователя'
}) })
async createUser(@Req() request: Request<null, CreateUserRequest>): Promise<UserResponse> { async createUser(@Req() request: Request<null, CreateUserRequest>): Promise<UserResponse> {
await this.authService.checkRequest(request); const {login} = await this.authService.checkRequest(request);
return await this.userService.create(request.body); return await this.userService.create(request.body, login);
} }
@Put() @Put()
@ -117,9 +117,9 @@ export class UsersController {
description: 'Объект обновления данных пользователя' description: 'Объект обновления данных пользователя'
}) })
async updateUser(@Req() request: Request<null, UpdateUserRequest>): Promise<UserResponse> { async updateUser(@Req() request: Request<null, UpdateUserRequest>): Promise<UserResponse> {
await this.authService.checkRequest(request); const {login} = await this.authService.checkRequest(request);
return await this.userService.update(request.body); return await this.userService.updateUser(request.body, login);
} }
@Delete(':login') @Delete(':login')
@ -131,9 +131,9 @@ export class UsersController {
description: 'Логин пользователя', description: 'Логин пользователя',
}) })
async removeUser(@Req() request: Request<{login: string}>): Promise<UpdateUserRequest> { async removeUser(@Req() request: Request<{login: string}>): Promise<UpdateUserRequest> {
await this.authService.checkRequest(request); const {login} = await this.authService.checkRequest(request);
return await this.userService.removeOne(request.params.login); return await this.userService.removeOne(request.params.login, login);
} }
@Post('change-password') @Post('change-password')

View File

@ -19,6 +19,9 @@ export class UpdateUserRequest {
@ApiProperty() @ApiProperty()
avatar: string; avatar: string;
@ApiProperty()
is_admin: boolean;
} }
export class UpdateUserSelf { export class UpdateUserSelf {

View File

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