Skip to content
Snippets Groups Projects
Commit cead66ea authored by Hugo SUBTIL's avatar Hugo SUBTIL
Browse files

feat: add password cahnge endpoint

parent 01878083
No related branches found
No related tags found
3 merge requests!27Recette,!26Dev,!6Feat/change password
import { IsNotEmpty } from 'class-validator';
export class PasswordChangeDto {
@IsNotEmpty() readonly newPassword: string;
@IsNotEmpty() readonly oldPassword: string;
}
import { Body, Controller, Get, Param, Post, Query, Req, Request, UseGuards } from '@nestjs/common';
import { ApiOperation, ApiParam, ApiResponse } from '@nestjs/swagger';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { PasswordChangeDto } from './change-password.dto';
import { CreateUserDto } from './create-user.dto';
import { UsersService } from './users.service';
......@@ -30,4 +31,17 @@ export class UsersController {
public async validateUser(@Param() params, @Query('token') token: string) {
return this.usersService.validateUser(params.id, token);
}
@UseGuards(JwtAuthGuard)
@Post('change-password')
@ApiResponse({ status: 201, description: 'Password changed' })
@ApiResponse({ status: 401, description: 'Invalid password' })
@ApiResponse({ status: 422, description: 'Weak password' })
public async changePassword(@Request() req, @Body() passwordChangeDto: PasswordChangeDto) {
return this.usersService.changeUserPassword(
req.user._id,
passwordChangeDto.oldPassword,
passwordChangeDto.newPassword
);
}
}
......@@ -66,7 +66,10 @@ export class UsersService {
return this.userModel.findOne({ email: mail }).select('-password').exec();
}
public async findById(id: string): Promise<IUser | undefined> {
public async findById(id: string, passwordQuery?: boolean): Promise<IUser | undefined> {
if (passwordQuery) {
return this.userModel.findById(id).exec();
}
return this.userModel.findById(id).select('-password').exec();
}
......@@ -130,4 +133,20 @@ export class UsersService {
throw new HttpException('Invalid token', HttpStatus.UNAUTHORIZED);
}
}
public async changeUserPassword(userId: string, oldPassword: string, newPassword: string) {
const user = await this.findById(userId, true);
const arePasswordEqual = await this.comparePassword(oldPassword, user.password);
if (!arePasswordEqual) {
throw new HttpException('Invalid credentials', HttpStatus.UNAUTHORIZED);
}
if (!this.isStrongPassword(newPassword)) {
throw new HttpException(
'Weak password, it must contain ne lowercase alphabetical character, one uppercase alphabetical character, one numeric character, one special character and be eight characters or longer',
HttpStatus.UNPROCESSABLE_ENTITY
);
}
user.password = await this.hashPassword(newPassword);
user.save();
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment