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!

password reset functionality

Blue Mousee38a00ff45cc
diff --git a/backend/apps/cloud/src/auth/auth.controller.ts b/backend/apps/cloud/src/auth/auth.controller.ts
index 955d3d731..69f7d3af5 100644
--- a/backend/apps/cloud/src/auth/auth.controller.ts
+++ b/backend/apps/cloud/src/auth/auth.controller.ts
@@ -41,7 +41,6 @@ import {
RequestResetPasswordDto,
ConfirmResetPasswordDto,
ResetPasswordDto,
- ChangePasswordDto,
ConfirmChangeEmailDto,
RequestChangeEmailDto,
SSOGetJWTByHashDto,
@@ -253,37 +252,6 @@ export class AuthController {
await this.authService.resetPassword(actionToken, body.newPassword)
}
- @ApiBearerAuth()
- @ApiOperation({ summary: 'Change a password' })
- @ApiOkResponse({
- description: 'Password changed',
- })
- @UseGuards(RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
- @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.getBasicUser(
- user.email,
- body.oldPassword,
- )
-
- if (!isPasswordValid) {
- throw new ConflictException(i18n.t('auth.invalidPassword'))
- }
-
- await this.authService.changePassword(user.id, body.newPassword)
- }
-
@ApiBearerAuth()
@ApiOperation({ summary: 'Request a resend of the verification email' })
@ApiOkResponse({
diff --git a/backend/apps/cloud/src/auth/dtos/index.ts b/backend/apps/cloud/src/auth/dtos/index.ts
index 7afca67e8..5f6eab085 100644
--- a/backend/apps/cloud/src/auth/dtos/index.ts
+++ b/backend/apps/cloud/src/auth/dtos/index.ts
@@ -4,7 +4,6 @@ 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'
export * from './request-change-email.dto'
export * from './confirm-change-email.dto'
export * from './process-sso-code.dto'
diff --git a/backend/apps/cloud/src/common/templates/en/mailaddress-change_confirmation.html b/backend/apps/cloud/src/common/templates/en/mailaddress-change_confirmation.html
index 34e116129..e7cc219f6 100644
--- a/backend/apps/cloud/src/common/templates/en/mailaddress-change_confirmation.html
+++ b/backend/apps/cloud/src/common/templates/en/mailaddress-change_confirmation.html
@@ -1,4 +1,4 @@
-You have changed your email address at swetrix.com
+You have requested a change of your email address at swetrix.com
<br/>
The new email will only be applied after you have confirmed this action by clicking the link below.
<br/>
diff --git a/backend/apps/community/src/auth/auth.controller.ts b/backend/apps/community/src/auth/auth.controller.ts
index 4d28ca61e..fc59393e3 100644
--- a/backend/apps/community/src/auth/auth.controller.ts
+++ b/backend/apps/community/src/auth/auth.controller.ts
@@ -40,6 +40,9 @@ import {
RegisterResponseDto,
RequestChangeEmailDto,
ConfirmChangeEmailDto,
+ RequestResetPasswordDto,
+ ConfirmResetPasswordDto,
+ ResetPasswordDto,
} from './dtos'
import { JwtAccessTokenGuard, JwtRefreshTokenGuard, RolesGuard } from './guards'
import { UserType } from '../user/entities/user.entity'
@@ -211,6 +214,53 @@ export class AuthController {
{ url },
)
}
+ @ApiOperation({ summary: 'Request a password reset' })
+ @ApiOkResponse({
+ description: 'Password reset requested',
+ })
+ @Public()
+ @Post('reset-password')
+ public async requestResetPassword(
+ @Body() body: RequestResetPasswordDto,
+ @I18n() i18n: I18nContext,
+ @Headers() headers: Record<string, string>,
+ @Ip() requestIp: string,
+ ): Promise<void> {
+ const ip = getIPFromHeaders(headers) || requestIp || ''
+
+ await checkRateLimit(ip, 'reset-password')
+ await checkRateLimit(body.email, 'reset-password')
+
+ const user = await this.userService.findOne({ email: body.email })
+
+ if (!user) {
+ throw new ConflictException(i18n.t('auth.accountNotExists'))
+ }
+
+ await this.authService.sendResetPasswordEmail(user.id, user.email, headers)
+ }
+
+ @ApiOperation({ summary: 'Reset a password' })
+ @ApiOkResponse({
+ description: 'Password reset',
+ })
+ @Public()
+ @Post('reset-password/confirm/:token')
+ @HttpCode(200)
+ public async resetPassword(
+ @Param() params: ConfirmResetPasswordDto,
+ @Body() body: ResetPasswordDto,
+ @I18n() i18n: I18nContext,
+ ): Promise<void> {
+ const userId = await redis.get(`password_reset:${params.token}`)
+
+ if (!userId) {
+ throw new ConflictException(i18n.t('auth.invalidResetPasswordToken'))
+ }
+
+ await redis.del(`password_reset:${params.token}`)
+ await this.authService.resetPassword(userId, body.newPassword)
+ }
@ApiOperation({ summary: 'Confirm a user email change (CE)' })
@ApiOkResponse({
diff --git a/backend/apps/community/src/auth/auth.module.ts b/backend/apps/community/src/auth/auth.module.ts
index 0e3beffe4..18ae84652 100644
--- a/backend/apps/community/src/auth/auth.module.ts
+++ b/backend/apps/community/src/auth/auth.module.ts
@@ -9,9 +9,10 @@ import {
JwtAccessTokenStrategy,
JwtRefreshTokenStrategy,
} from './strategies'
+import { MailerModule } from '../mailer/mailer.module'
@Module({
- imports: [JwtModule.register({}), PassportModule, UserModule],
+ imports: [JwtModule.register({}), PassportModule, UserModule, MailerModule],
controllers: [AuthController],
providers: [
AuthService,
diff --git a/backend/apps/community/src/auth/auth.service.ts b/backend/apps/community/src/auth/auth.service.ts
index 2bb8b7ae2..842c79442 100644
--- a/backend/apps/community/src/auth/auth.service.ts
+++ b/backend/apps/community/src/auth/auth.service.ts
@@ -31,6 +31,8 @@ import {
} from '../common/constants'
import { UserService } from '../user/user.service'
import { User } from '../common/types'
+import { MailerService } from '../mailer/mailer.service'
+import { LetterTemplate } from '../mailer/letter'
const REDIS_OIDC_SESSION_TIMEOUT = 60 * 5 // 5 minutes
const getOIDCRedisKey = (uuid: string) => `${REDIS_OIDC_SESSION_KEY}:${uuid}`
@@ -42,6 +44,7 @@ export class AuthService {
private readonly configService: ConfigService,
private readonly jwtService: JwtService,
private readonly userService: UserService,
+ private readonly mailerService: MailerService,
) {}
private async createSha1Hash(text: string): Promise<string> {
@@ -158,6 +161,37 @@ export class AuthService {
return assignUnassignedProjectsToUserClickhouse(userId)
}
+ public async sendResetPasswordEmail(
+ userId: string,
+ email: string,
+ headers: Record<string, string>,
+ ) {
+ const urlBase = headers.origin || ''
+
+ const token = uuidv4()
+ const url = `${urlBase}/password-reset/${token}`
+
+ await redis.set(`password_reset:${token}`, userId, 'EX', 60 * 60 * 12)
+
+ await this.mailerService.sendEmail(
+ email,
+ LetterTemplate.ConfirmPasswordChange,
+ {
+ url,
+ },
+ )
+ }
+
+ public async resetPassword(userId: string, password: string): Promise<void> {
+ const hashedPassword = await this.hashPassword(password)
+
+ await this.userService.update(userId, {
+ password: hashedPassword,
+ })
+
+ await this.logoutAll(userId)
+ }
+
async getBasicUser(email: string, password: string): Promise<User | null> {
const user = await this.userService.findOne({ email })
diff --git a/backend/apps/community/src/auth/dtos/confirm-reset-password.dto.ts b/backend/apps/community/src/auth/dtos/confirm-reset-password.dto.ts
new file mode 100644
index 000000000..4d367f1f6
--- /dev/null
+++ b/backend/apps/community/src/auth/dtos/confirm-reset-password.dto.ts
@@ -0,0 +1,11 @@
+import { ApiProperty } from '@nestjs/swagger'
+import { IsUUID } from 'class-validator'
+
+export class ConfirmResetPasswordDto {
+ @ApiProperty({
+ description: 'The token to confirm the reset password',
+ example: 'a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6',
+ })
+ @IsUUID('4', { message: 'Please enter the valid UUID.' })
+ public readonly token: string
+}
diff --git a/backend/apps/community/src/auth/dtos/index.ts b/backend/apps/community/src/auth/dtos/index.ts
index 25722d00a..8c33cb47f 100644
--- a/backend/apps/community/src/auth/dtos/index.ts
+++ b/backend/apps/community/src/auth/dtos/index.ts
@@ -3,3 +3,6 @@ export * from './oidc-auth.dto'
export * from './register.dto'
export * from './request-change-email.dto'
export * from './confirm-change-email.dto'
+export * from './request-reset-password.dto'
+export * from './reset-password.dto'
+export * from './confirm-reset-password.dto'
diff --git a/backend/apps/community/src/auth/dtos/request-reset-password.dto.ts b/backend/apps/community/src/auth/dtos/request-reset-password.dto.ts
new file mode 100644
index 000000000..a2a09a383
--- /dev/null
+++ b/backend/apps/community/src/auth/dtos/request-reset-password.dto.ts
@@ -0,0 +1,13 @@
+import { ApiProperty } from '@nestjs/swagger'
+import { IsEmail } from 'class-validator'
+
+export class RequestResetPasswordDto {
+ @ApiProperty({
+ description: 'User email',
+ example: '[email protected]',
+ maxLength: 254,
+ minLength: 6,
+ })
+ @IsEmail({}, { message: 'Please enter the valid email.' })
+ public readonly email: string
+}
diff --git a/backend/apps/cloud/src/auth/dtos/change-password.dto.ts b/backend/apps/community/src/auth/dtos/reset-password.dto.ts
similarity index 54%
rename from backend/apps/cloud/src/auth/dtos/change-password.dto.ts
rename to backend/apps/community/src/auth/dtos/reset-password.dto.ts
index 2f8e41311..14df63e68 100644
--- a/backend/apps/cloud/src/auth/dtos/change-password.dto.ts
+++ b/backend/apps/community/src/auth/dtos/reset-password.dto.ts
@@ -1,17 +1,7 @@
import { ApiProperty } from '@nestjs/swagger'
import { MaxLength, MinLength } from 'class-validator'
-export class ChangePasswordDto {
- @ApiProperty({
- description: 'User password',
- example: '%d7*c4W45p',
- maxLength: 72,
- minLength: 8,
- })
- @MaxLength(50, { message: 'Max length is $constraint1 characters' })
- @MinLength(8, { message: 'Min length is $constraint1 characters' })
- public readonly oldPassword: string
-
+export class ResetPasswordDto {
@ApiProperty({
description: 'User password',
example: '%d7*c4W45p',
diff --git a/backend/apps/community/src/common/templates/en/customer_project-invitation.html b/backend/apps/community/src/common/templates/en/customer_project-invitation.html
index 6b78b7d5d..bcf5fe809 100644
--- a/backend/apps/community/src/common/templates/en/customer_project-invitation.html
+++ b/backend/apps/community/src/common/templates/en/customer_project-invitation.html
@@ -1,4 +1,4 @@
-<a href="mailto:{{email}}">{{email}}</a> has invited you to the {{name}} website analytics dashboard with the role {{role}} on Swetrix.
+<a href="mailto:{{email}}">{{email}}</a> has invited you to the {{name}} website analytics dashboard with the role {{role}} on their Swetrix Community Edition instance.
<br/>
Click the button below to accept the invitation or ignore this email if you do not want to join the project.
<br/>
diff --git a/backend/apps/community/src/common/templates/en/mailaddress-change_confirmation.html b/backend/apps/community/src/common/templates/en/mailaddress-change_confirmation.html
index 34e116129..f89051abb 100644
--- a/backend/apps/community/src/common/templates/en/mailaddress-change_confirmation.html
+++ b/backend/apps/community/src/common/templates/en/mailaddress-change_confirmation.html
@@ -1,4 +1,4 @@
-You have changed your email address at swetrix.com
+You have requested a change of your email address at the Swetrix Community Edition instance.
<br/>
The new email will only be applied after you have confirmed this action by clicking the link below.
<br/>
@@ -6,4 +6,4 @@ The new email will only be applied after you have confirmed this action by click
<a href="{{url}}" target="_blank">Confirm email update.</a>
<br/>
<br/>
-If you have not changed your email, please ignore this email or reply to it so we could assist you in securing your account.
+If you have not changed your email, please ignore this email.
diff --git a/backend/apps/community/src/common/templates/en/mailaddress-change_information.html b/backend/apps/community/src/common/templates/en/mailaddress-change_information.html
index 821075dad..e86b0df4e 100644
--- a/backend/apps/community/src/common/templates/en/mailaddress-change_information.html
+++ b/backend/apps/community/src/common/templates/en/mailaddress-change_information.html
@@ -1,4 +1 @@
-Your email address at swetrix.com has been updated.
-<br/>
-<br/>
-If you have not done so, please reply to this email so we could assist you in securing your account.
+Your email address at the Swetrix Community Edition instance has been updated.
diff --git a/backend/apps/community/src/common/templates/en/password-change_confirmation.html b/backend/apps/community/src/common/templates/en/password-change_confirmation.html
index ed7a440e3..bb40efcbf 100644
--- a/backend/apps/community/src/common/templates/en/password-change_confirmation.html
+++ b/backend/apps/community/src/common/templates/en/password-change_confirmation.html
@@ -1,7 +1,7 @@
-You have changed your password at swetrix.com
+You have changed your password at the Swetrix Community Edition instance.
<br/>
The new password will only be applied after you have confirmed this action by clicking the link below.
<a href="{{url}}" target="_blank">Confirm password change</a>
<br/>
<br/>
-If you have not changed your password, please ignore this email or reply to it so we could assist you in securing your account.
+If you have not changed your password, please ignore this email.
diff --git a/backend/apps/community/src/common/templates/en/password-change_information.html b/backend/apps/community/src/common/templates/en/password-change_information.html
index c1a62d489..eecca25bd 100644
--- a/backend/apps/community/src/common/templates/en/password-change_information.html
+++ b/backend/apps/community/src/common/templates/en/password-change_information.html
@@ -1,4 +1 @@
-Your password at swetrix.com has been changed.
-<br/>
-<br/>
-If you have not done so, please reply to this email so we could assist you in securing your account.
+Your password at Swetrix Community Edition instance has been changed.
diff --git a/backend/apps/community/src/common/templates/en/project-transfer.html b/backend/apps/community/src/common/templates/en/project-transfer.html
index e451c151c..cc870ade1 100644
--- a/backend/apps/community/src/common/templates/en/project-transfer.html
+++ b/backend/apps/community/src/common/templates/en/project-transfer.html
@@ -1,4 +1,4 @@
-A Swetrix user wants to transfer of the {{name}} project to your account.
+A Swetrix Community Edition user wants to transfer of the {{name}} project to your account.
<br/>
If you accept the invitation, this project well be transferred to your account and the previous owner will be added as an administator (you will be able to edit project admins and viewers in the project settings).
<br />