Skip to content

📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

Added a route to change the password

Yevhenii Kulisidi176dc001bf5b
diff --git a/src/auth/auth.controller.ts b/src/auth/auth.controller.ts
index 522fa034c..5f06ce968 100644
--- a/src/auth/auth.controller.ts
+++ b/src/auth/auth.controller.ts
@@ -1,18 +1,19 @@
-// FIX: I18nValidationExceptionFilter is not working
-
import {
Controller,
UseFilters,
+ UseGuards,
UsePipes,
ValidationPipe,
Post,
Body,
Ip,
ConflictException,
- Headers,
HttpCode,
- Param,
+ HttpStatus,
Get,
+ Param,
+ Headers,
+ UnauthorizedException,
} from '@nestjs/common'
import {
ApiTags,
@@ -24,6 +25,7 @@ import { I18nValidationExceptionFilter, I18n, I18nContext } from 'nestjs-i18n'
import { checkRateLimit } from 'src/common/utils'
import { UserService } from 'src/user/user.service'
import { AuthService } from './auth.service'
+import { Public, CurrentUserId } from './decorators'
import {
RegisterResponseDto,
RegisterRequestDto,
@@ -33,11 +35,14 @@ import {
RequestResetPasswordDto,
ConfirmResetPasswordDto,
ResetPasswordDto,
+ ChangePasswordDto,
} from './dtos'
+import { JwtAccessTokenGuard } from './guards'
@ApiTags('Auth')
@Controller({ path: 'auth', version: '1' })
@UseFilters(new I18nValidationExceptionFilter())
+@UseGuards(JwtAccessTokenGuard)
@UsePipes(
new ValidationPipe({
forbidNonWhitelisted: true,
@@ -57,6 +62,7 @@ export class AuthController {
description: 'User registered',
type: RegisterResponseDto,
})
+ @Public()
@Post('register')
public async register(
@Body() body: RegisterRequestDto,
@@ -100,8 +106,9 @@ export class AuthController {
description: 'User logged in',
type: LoginResponseDto,
})
+ @Public()
@Post('login')
- @HttpCode(200)
+ @HttpCode(HttpStatus.OK)
public async login(
@Body() body: LoginRequestDto,
@I18n() i18n: I18nContext,
@@ -133,6 +140,7 @@ export class AuthController {
@ApiOkResponse({
description: 'User email verified',
})
+ @Public()
@Get('verify-email/:token')
public async verifyEmail(
@Param() params: VerifyEmailDto,
@@ -153,6 +161,7 @@ export class AuthController {
@ApiOkResponse({
description: 'Password reset requested',
})
+ @Public()
@Post('reset-password')
public async requestResetPassword(
@Body() body: RequestResetPasswordDto,
@@ -179,6 +188,7 @@ export class AuthController {
@ApiOkResponse({
description: 'Password reset',
})
+ @Public()
@Post('reset-password/confirm/:token')
@HttpCode(200)
public async resetPassword(
@@ -196,4 +206,32 @@ export class AuthController {
await this.authService.resetPassword(actionToken, body.newPassword)
}
+
+ @ApiOperation({ summary: 'Change a password' })
+ @ApiOkResponse({
+ description: 'Password changed',
+ })
+ @Post('change-password')
+ public async changePassword(
+ @Body() body: ChangePasswordDto,
+ @CurrentUserId() userId: string,
+ @I18n() i18n: I18nContext,
+ ): Promise<void> {
+ const user = await this.userService.findUserById(userId)
+
+ if (!user) {
+ throw new UnauthorizedException()
+ }
+
+ const isPasswordValid = await this.authService.validateUser(
+ user.email,
+ body.oldPassword,
+ )
+
+ if (!isPasswordValid) {
+ throw new ConflictException(i18n.t('auth.invalidPassword'))
+ }
+
+ await this.authService.changePassword(user.id, body.newPassword)
+ }
}
diff --git a/src/auth/auth.service.ts b/src/auth/auth.service.ts
index 44ed1a6cd..e9e67adb0 100644
--- a/src/auth/auth.service.ts
+++ b/src/auth/auth.service.ts
@@ -258,4 +258,11 @@ export class AuthService {
})
await this.actionTokensService.deleteActionToken(actionToken.id)
}
+
+ public async changePassword(userId: string, password: string): Promise<void> {
+ const hashedPassword = await this.hashPassword(password)
+ await this.userService.updateUser(userId, {
+ password: hashedPassword,
+ })
+ }
}
diff --git a/src/auth/decorators/current-user-id.decorator.ts b/src/auth/decorators/current-user-id.decorator.ts
new file mode 100644
index 000000000..1bfee8777
--- /dev/null
+++ b/src/auth/decorators/current-user-id.decorator.ts
@@ -0,0 +1,10 @@
+import { createParamDecorator, ExecutionContext } from '@nestjs/common'
+import { IJwtPayload } from '../interfaces'
+
+export const CurrentUserId = createParamDecorator(
+ (_: unknown, context: ExecutionContext) => {
+ const request = context.switchToHttp().getRequest()
+ const user = request.user as IJwtPayload
+ return user.sub
+ },
+)
diff --git a/src/auth/decorators/index.ts b/src/auth/decorators/index.ts
index 2ec2291fc..c7ed42c34 100644
--- a/src/auth/decorators/index.ts
+++ b/src/auth/decorators/index.ts
@@ -1 +1,3 @@
export * from './validators'
+export * from './current-user-id.decorator'
+export * from './public.decorator'
diff --git a/src/auth/decorators/public.decorator.ts b/src/auth/decorators/public.decorator.ts
new file mode 100644
index 000000000..93a3f77cd
--- /dev/null
+++ b/src/auth/decorators/public.decorator.ts
@@ -0,0 +1,3 @@
+import { SetMetadata } from '@nestjs/common'
+
+export const Public = () => SetMetadata('isPublic', true)
diff --git a/src/auth/dtos/change-password.dto.ts b/src/auth/dtos/change-password.dto.ts
new file mode 100644
index 000000000..a9aace2e9
--- /dev/null
+++ b/src/auth/dtos/change-password.dto.ts
@@ -0,0 +1,22 @@
+import { ApiProperty } from '@nestjs/swagger'
+import { IsPassword } from '../decorators'
+
+export class ChangePasswordDto {
+ @ApiProperty({
+ description: 'User password',
+ example: '%d7*c4W45p',
+ maxLength: 72,
+ minLength: 8,
+ })
+ @IsPassword({ message: 'Please enter the valid password.' })
+ public readonly oldPassword: string
+
+ @ApiProperty({
+ description: 'User password',
+ example: '%d7*c4W45p',
+ maxLength: 72,
+ minLength: 8,
+ })
+ @IsPassword({ message: 'Please enter the valid password.' })
+ public readonly newPassword: string
+}
diff --git a/src/auth/dtos/index.ts b/src/auth/dtos/index.ts
index f857073ec..7b916defc 100644
--- a/src/auth/dtos/index.ts
+++ b/src/auth/dtos/index.ts
@@ -4,3 +4,4 @@ export * from './verify-email.dto'
export * from './request-reset-password.dto'
export * from './confirm-reset-password.dto'
export * from './reset-password.dto'
+export * from './change-password.dto'
diff --git a/src/auth/guards/access-token.guard.ts b/src/auth/guards/access-token.guard.ts
new file mode 100644
index 000000000..937f8fe89
--- /dev/null
+++ b/src/auth/guards/access-token.guard.ts
@@ -0,0 +1,21 @@
+import { ExecutionContext, Injectable } from '@nestjs/common'
+import { Reflector } from '@nestjs/core'
+import { AuthGuard } from '@nestjs/passport'
+
+@Injectable()
+export class JwtAccessTokenGuard extends AuthGuard('jwt-access-token') {
+ constructor(private reflector: Reflector) {
+ super()
+ }
+
+ canActivate(context: ExecutionContext) {
+ const isPublic = this.reflector.getAllAndOverride('isPublic', [
+ context.getHandler(),
+ context.getClass(),
+ ])
+
+ if (isPublic) return true
+
+ return super.canActivate(context)
+ }
+}
diff --git a/src/auth/guards/index.ts b/src/auth/guards/index.ts
new file mode 100644
index 000000000..7f84f519e
--- /dev/null
+++ b/src/auth/guards/index.ts
@@ -0,0 +1 @@
+export * from './access-token.guard'
diff --git a/src/i18n/en/auth.json b/src/i18n/en/auth.json
index 93f9842fe..0ee7d74d8 100644
--- a/src/i18n/en/auth.json
+++ b/src/i18n/en/auth.json
@@ -3,5 +3,6 @@
"invalidCredentials": "Incorrect email or password.",
"invalidVerificationToken": "Invalid verification token.",
"accountNotExists": "An account with this email does not exist.",
- "invalidResetPasswordToken": "Invalid reset password token."
+ "invalidResetPasswordToken": "Invalid reset password token.",
+ "invalidPassword": "Invalid password."
}