AnhLedger commited on
Commit
bac00ce
1 Parent(s): 3d803b5

Update list of user and change roles to role in roles guard

Browse files
backend/src/modules/authentication/authorization/roles.guard.ts CHANGED
@@ -17,6 +17,6 @@ export class RolesGuard implements CanActivate {
17
  return true;
18
  }
19
  const { user } = context.switchToHttp().getRequest();
20
- return requiredRoles.some((role) => user.roles.includes(role));
21
  }
22
  }
 
17
  return true;
18
  }
19
  const { user } = context.switchToHttp().getRequest();
20
+ return requiredRoles.some((role) => user.role.includes(role));
21
  }
22
  }
backend/src/modules/user/dto/update-users.dto.ts ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { IsEmail, IsMobilePhone, IsOptional, IsString } from "class-validator";
2
+
3
+ export class UpdateUsersDto {
4
+
5
+ @IsString()
6
+ id: string;
7
+
8
+ @IsString()
9
+ @IsOptional()
10
+ full_name?: string;
11
+
12
+ @IsEmail()
13
+ @IsOptional()
14
+ email?: string;
15
+
16
+ @IsMobilePhone('vi-VN')
17
+ @IsOptional()
18
+ phone_number: string
19
+
20
+ @IsString()
21
+ @IsOptional()
22
+ password?: string;
23
+ }
24
+
backend/src/modules/user/user.controller.ts CHANGED
@@ -1,9 +1,10 @@
1
- import { Body, Controller, Get, Param, Post, Query, Request } from '@nestjs/common';
2
  import { UserService } from './user.service.js';
3
  import { UserEntity } from 'src/entities/user.entity.js';
4
  import { Roles } from '../authentication/authorization/roles.decorator.js';
5
  import { Role } from '../../common/enums/role.enum.js';
6
  import { Paginate, PaginateQuery } from 'nestjs-paginate';
 
7
 
8
  @Controller('users')
9
  export class UsersController {
@@ -31,6 +32,14 @@ export class UsersController {
31
  return this.usersService.updateUserById(userId, updateUserDto);
32
  }
33
 
 
 
 
 
 
 
 
 
34
  @Get('getAll')
35
  @Roles(Role.ADMIN, Role.AREA_MANAGER, Role.BRANCH_MANAGER)
36
  async findAllUser(@Paginate() query: PaginateQuery) {
 
1
+ import { Body, Controller, Get, Post, Put, Query, Request } from '@nestjs/common';
2
  import { UserService } from './user.service.js';
3
  import { UserEntity } from 'src/entities/user.entity.js';
4
  import { Roles } from '../authentication/authorization/roles.decorator.js';
5
  import { Role } from '../../common/enums/role.enum.js';
6
  import { Paginate, PaginateQuery } from 'nestjs-paginate';
7
+ import { UpdateUsersDto } from './dto/update-users.dto.js';
8
 
9
  @Controller('users')
10
  export class UsersController {
 
32
  return this.usersService.updateUserById(userId, updateUserDto);
33
  }
34
 
35
+ @Put('updateList')
36
+ @Roles(Role.ADMIN)
37
+ async updateUsers(
38
+ @Body() updateUsersDto: UpdateUsersDto[],
39
+ ) {
40
+ return this.usersService.updateUsers(updateUsersDto);
41
+ }
42
+
43
  @Get('getAll')
44
  @Roles(Role.ADMIN, Role.AREA_MANAGER, Role.BRANCH_MANAGER)
45
  async findAllUser(@Paginate() query: PaginateQuery) {
backend/src/modules/user/user.service.ts CHANGED
@@ -1,22 +1,13 @@
1
- import {
2
- Body,
3
- forwardRef,
4
- Inject,
5
- Injectable,
6
- NotFoundException,
7
- } from '@nestjs/common';
8
  import { UserEntity } from '../../entities/user.entity.js';
9
  import { SignUpDto } from '../authentication/dto/sign-up.dto.js';
10
  import { UpdateUserDto } from './dto/update-user-dto.js';
11
  import { ValidateService } from '../../validate/validate.service.js';
12
  import * as bcrypt from 'bcrypt';
13
  import { JwtService } from '@nestjs/jwt';
14
- import {
15
- FilterOperator,
16
- paginate,
17
- PaginateConfig,
18
- PaginateQuery,
19
- } from 'nestjs-paginate';
20
 
21
  export type User = any;
22
 
@@ -27,37 +18,32 @@ export class UserService {
27
  private jwtService: JwtService,
28
  ) {}
29
 
30
- async create(signUpDto: SignUpDto): Promise<UserEntity | undefined> {
31
  return UserEntity.create({
32
  full_name: signUpDto.full_name,
33
  phone_number: signUpDto.phone_number,
34
  email: signUpDto.email,
35
- hash_password: signUpDto.password,
36
- });
37
  }
38
 
39
- async save(userEntity: UserEntity): Promise<UserEntity | undefined> {
40
  return UserEntity.save(userEntity);
41
  }
42
 
43
- async findOneByField(
44
- field: string,
45
- value: any,
46
- ): Promise<UserEntity | undefined> {
47
- return UserEntity.findOne({
48
- where: { [field]: value },
49
  });
50
  }
51
 
52
- async updateUserById(userId: string, updateUserDto: UpdateUserDto) {
 
53
  await this.validateService.checkExistField('email', updateUserDto.email);
54
- await this.validateService.checkExistField(
55
- 'phone_number',
56
- updateUserDto.phone_number,
57
- );
58
 
59
  const user = await UserEntity.findOne({
60
- where: { id: userId },
61
  });
62
  if (!user) {
63
  throw new NotFoundException(`User with ID ${userId} not found`);
@@ -66,17 +52,14 @@ export class UserService {
66
  Object.assign(user, updateUserDto);
67
  if (updateUserDto.hash_password) {
68
  const saltRounds = 10;
69
- user.hash_password = await bcrypt.hash(
70
- updateUserDto.hash_password,
71
- saltRounds,
72
- ); // Mã hóa mật khẩu
73
  }
74
  await UserEntity.save(user);
75
 
76
- const payload = { sub: user.id, username: user.full_name, role: user.role };
77
- const token = await this.jwtService.signAsync(payload);
78
  return {
79
- access_token: token,
80
  };
81
  }
82
 
@@ -93,17 +76,15 @@ export class UserService {
93
  FilterOperator.GT,
94
  FilterOperator.GTE,
95
  ],
96
- item_type: [FilterOperator.EQ],
97
  },
98
  };
99
  return paginate(query, UserEntity.createQueryBuilder(), paginateConfig);
100
  }
101
 
102
  async findAllByName(fullName: string, query: PaginateQuery) {
103
- const queryBuilder = UserEntity.createQueryBuilder('users').where(
104
- 'users.full_name = :fullName',
105
- { fullName },
106
- );
107
  const paginateConfig: PaginateConfig<UserEntity> = {
108
  sortableColumns: ['id', 'full_name', 'phone_number', 'email'],
109
  nullSort: 'last',
@@ -116,17 +97,15 @@ export class UserService {
116
  FilterOperator.GT,
117
  FilterOperator.GTE,
118
  ],
119
- item_type: [FilterOperator.EQ],
120
  },
121
  };
122
  return paginate(query, queryBuilder, paginateConfig);
123
  }
124
 
125
  async findAllByRole(role: string, query: PaginateQuery) {
126
- const queryBuilder = UserEntity.createQueryBuilder('users').where(
127
- 'users.role = :role',
128
- { role },
129
- );
130
  const paginateConfig: PaginateConfig<UserEntity> = {
131
  sortableColumns: ['id', 'full_name', 'phone_number', 'email'],
132
  nullSort: 'last',
@@ -139,9 +118,46 @@ export class UserService {
139
  FilterOperator.GT,
140
  FilterOperator.GTE,
141
  ],
142
- item_type: [FilterOperator.EQ],
143
  },
144
  };
145
  return paginate(query, queryBuilder, paginateConfig);
146
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
147
  }
 
1
+ import { Body, forwardRef, HttpStatus, Inject, Injectable, NotFoundException } from '@nestjs/common';
 
 
 
 
 
 
2
  import { UserEntity } from '../../entities/user.entity.js';
3
  import { SignUpDto } from '../authentication/dto/sign-up.dto.js';
4
  import { UpdateUserDto } from './dto/update-user-dto.js';
5
  import { ValidateService } from '../../validate/validate.service.js';
6
  import * as bcrypt from 'bcrypt';
7
  import { JwtService } from '@nestjs/jwt';
8
+ import { FilterOperator, paginate, PaginateConfig, PaginateQuery } from 'nestjs-paginate';
9
+ import { UpdateUsersDto } from './dto/update-users.dto.js';
10
+ import { In } from 'typeorm';
 
 
 
11
 
12
  export type User = any;
13
 
 
18
  private jwtService: JwtService,
19
  ) {}
20
 
21
+ async create(signUpDto: SignUpDto): Promise<UserEntity | undefined>{
22
  return UserEntity.create({
23
  full_name: signUpDto.full_name,
24
  phone_number: signUpDto.phone_number,
25
  email: signUpDto.email,
26
+ hash_password: signUpDto.password
27
+ })
28
  }
29
 
30
+ async save(userEntity: UserEntity): Promise<UserEntity | undefined>{
31
  return UserEntity.save(userEntity);
32
  }
33
 
34
+ async findOneByField(field: string, value: any): Promise<UserEntity | undefined> {
35
+ return UserEntity.findOne({
36
+ where: { [field]: value }
 
 
 
37
  });
38
  }
39
 
40
+ async updateUserById(userId: string, updateUserDto: UpdateUserDto){
41
+
42
  await this.validateService.checkExistField('email', updateUserDto.email);
43
+ await this.validateService.checkExistField('phone_number', updateUserDto.phone_number);
 
 
 
44
 
45
  const user = await UserEntity.findOne({
46
+ where: { id: userId }
47
  });
48
  if (!user) {
49
  throw new NotFoundException(`User with ID ${userId} not found`);
 
52
  Object.assign(user, updateUserDto);
53
  if (updateUserDto.hash_password) {
54
  const saltRounds = 10;
55
+ user.hash_password = await bcrypt.hash(updateUserDto.hash_password, saltRounds); // Mã hóa mật khẩu
 
 
 
56
  }
57
  await UserEntity.save(user);
58
 
59
+ const payload = { sub: user.id, username: user.full_name, roles: user.role };
60
+ const token = await this.jwtService.signAsync(payload)
61
  return {
62
+ access_token: token
63
  };
64
  }
65
 
 
76
  FilterOperator.GT,
77
  FilterOperator.GTE,
78
  ],
79
+ item_type: [FilterOperator.EQ]
80
  },
81
  };
82
  return paginate(query, UserEntity.createQueryBuilder(), paginateConfig);
83
  }
84
 
85
  async findAllByName(fullName: string, query: PaginateQuery) {
86
+ const queryBuilder = UserEntity.createQueryBuilder('users')
87
+ .where('users.full_name = :fullName', { fullName });
 
 
88
  const paginateConfig: PaginateConfig<UserEntity> = {
89
  sortableColumns: ['id', 'full_name', 'phone_number', 'email'],
90
  nullSort: 'last',
 
97
  FilterOperator.GT,
98
  FilterOperator.GTE,
99
  ],
100
+ item_type: [FilterOperator.EQ]
101
  },
102
  };
103
  return paginate(query, queryBuilder, paginateConfig);
104
  }
105
 
106
  async findAllByRole(role: string, query: PaginateQuery) {
107
+ const queryBuilder = UserEntity.createQueryBuilder('users')
108
+ .where('users.role = :role', { role });
 
 
109
  const paginateConfig: PaginateConfig<UserEntity> = {
110
  sortableColumns: ['id', 'full_name', 'phone_number', 'email'],
111
  nullSort: 'last',
 
118
  FilterOperator.GT,
119
  FilterOperator.GTE,
120
  ],
121
+ item_type: [FilterOperator.EQ]
122
  },
123
  };
124
  return paginate(query, queryBuilder, paginateConfig);
125
  }
126
+
127
+ async updateUsers(updateUsersDto: UpdateUsersDto[]) {
128
+ try {
129
+ //Lấy ra id trong updateUsersDto
130
+ const userIds = updateUsersDto.map(user => user.id).filter(id => id !== undefined);
131
+
132
+ //Lấy ra các user tồn tại trong db
133
+ const existingUsers = await UserEntity.find({
134
+ where: { id: In(userIds) },
135
+ });
136
+
137
+ // Bước 2: Kết hợp dữ liệu từ yêu cầu với dữ liệu hiện có
138
+ const mergedData = updateUsersDto.map(userData => {
139
+ const existingUser = existingUsers.find(user => user.id === userData.id);
140
+
141
+ if (existingUser) {
142
+ // Kết hợp: giữ nguyên giá trị hiện có cho các trường không có trong userData
143
+ return { ...existingUser, ...userData };
144
+ } else {
145
+ // Đối với user mới (không có trong DB), sử dụng dữ liệu từ request
146
+ return userData;
147
+ }
148
+ });
149
+
150
+ console.log(updateUsersDto)
151
+ UserEntity.upsert(mergedData, ['id'])
152
+ return {
153
+ statusCode: HttpStatus.OK,
154
+ message: "Thành công"
155
+ }
156
+ } catch (error) {
157
+ return {
158
+ statusCode: HttpStatus.OK,
159
+ message: "Thất bại"
160
+ }
161
+ }
162
+ }
163
  }