Implement functionality to view list of users by admin

master
nicekid1 2 months ago
parent 54531c1c63
commit a44695e5fd
  1. 7
      src/users/users.controller.ts
  2. 37
      src/users/users.service.ts

@ -27,10 +27,17 @@ export class UsersController {
const userId = req.user.id;
return this.usersService.getProfile(userId);
}
//edit user profile
@UseGuards(JwtAuthGuard)
@Put()
async editProfile(@Request() req, @Body() updateUserDto: UpdateUserDto): Promise<User> {
const userId = req.user.id;
return this.usersService.editProfile(userId, updateUserDto);
}
//get users list (admin)
@UseGuards(JwtAuthGuard)
@Get("users")
async findAll(): Promise<User[]> {
return this.usersService.findAll();
}
}

@ -19,10 +19,7 @@ export class UsersService {
// Register method
async register(createUserDto: CreateUserDto): Promise<User> {
try {
createUserDto.password = await bcrypt.hash(
createUserDto.password,
parseInt(process.env.BCRYPT_SALT_ROUNDS || "10", 10)
);
createUserDto.password = await bcrypt.hash(createUserDto.password, parseInt(process.env.BCRYPT_SALT_ROUNDS || "10", 10));
const userExists = await this.userModel.findOne({
where: { email: createUserDto.email },
@ -34,19 +31,14 @@ export class UsersService {
const user = await this.userModel.create(createUserDto);
return user;
} catch (error) {
throw new HttpException(
`An error occurred: ${error.message}`,
HttpStatus.INTERNAL_SERVER_ERROR
);
throw new HttpException(`An error occurred: ${error.message}`, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
// Login method
async login(loginUserDto:LoginUserDto): Promise<{ token: string }> {
async login(loginUserDto: LoginUserDto): Promise<{ token: string }> {
const user = await this.userModel.findOne({
where: { email:loginUserDto.email },
where: { email: loginUserDto.email },
});
if (!user) {
throw new UnauthorizedException("Invalid email or password");
@ -71,20 +63,21 @@ export class UsersService {
async getProfile(userId: number): Promise<User> {
const user = await this.userModel.findOne({
where: { id: userId },
attributes: { exclude: ['password'] },
attributes: { exclude: ["password"] },
});
if (!user) {
throw new Error('User not found');
throw new Error("User not found");
}
return user;
}
async editProfile(userId:number, updateUserDto:UpdateUserDto){
const user = await this.userModel.findOne({ where: { id:userId } });
//edit profile user method
async editProfile(userId: number, updateUserDto: UpdateUserDto) {
const user = await this.userModel.findOne({ where: { id: userId } });
if (!user) {
throw new NotFoundException('User not found');
throw new NotFoundException("User not found");
}
if (updateUserDto.password) {
@ -95,4 +88,12 @@ export class UsersService {
return user;
}
//get users list
async findAll(): Promise<User[]> {
try {
return await this.userModel.findAll();
} catch (error) {
throw new Error("An error occurred while fetching users");
}
}
}

Loading…
Cancel
Save