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 2FA check

Yevhenii Kulisidic2793f16c006
diff --git a/src/auth/auth.controller.ts b/src/auth/auth.controller.ts
index be2198664..67e1a661d 100644
--- a/src/auth/auth.controller.ts
+++ b/src/auth/auth.controller.ts
@@ -23,9 +23,10 @@ import {
} from '@nestjs/swagger'
import { I18nValidationExceptionFilter, I18n, I18nContext } from 'nestjs-i18n'
import { checkRateLimit } from 'src/common/utils'
+import { UserType } from 'src/user/entities/user.entity'
import { UserService } from 'src/user/user.service'
import { AuthService } from './auth.service'
-import { Public, CurrentUserId, CurrentUser } from './decorators'
+import { Public, CurrentUserId, CurrentUser, Roles } from './decorators'
import {
RegisterResponseDto,
RegisterRequestDto,
@@ -39,7 +40,7 @@ import {
ConfirmChangeEmailDto,
RequestChangeEmailDto,
} from './dtos'
-import { JwtAccessTokenGuard, JwtRefreshTokenGuard } from './guards'
+import { JwtAccessTokenGuard, JwtRefreshTokenGuard, RolesGuard } from './guards'
@ApiTags('Auth')
@Controller({ path: 'auth', version: '1' })
@@ -215,6 +216,8 @@ export class AuthController {
@ApiOkResponse({
description: 'Password changed',
})
+ @UseGuards(RolesGuard)
+ @Roles(UserType.CUSTOMER, UserType.ADMIN)
@Post('change-password')
public async changePassword(
@Body() body: ChangePasswordDto,
@@ -243,6 +246,8 @@ export class AuthController {
@ApiOkResponse({
description: 'Resend of the verification email requested',
})
+ @UseGuards(RolesGuard)
+ @Roles(UserType.CUSTOMER, UserType.ADMIN)
@Post('verify-email')
public async requestResendVerificationEmail(
@CurrentUserId() userId: string,
@@ -272,6 +277,8 @@ export class AuthController {
@ApiOkResponse({
description: 'User email changed',
})
+ @UseGuards(RolesGuard)
+ @Roles(UserType.CUSTOMER, UserType.ADMIN)
@Post('change-email')
public async requestChangeEmail(
@Body() body: RequestChangeEmailDto,
diff --git a/src/auth/decorators/index.ts b/src/auth/decorators/index.ts
index 7a764cdbf..5b4cfa3d8 100644
--- a/src/auth/decorators/index.ts
+++ b/src/auth/decorators/index.ts
@@ -2,3 +2,5 @@ export * from './validators'
export * from './current-user-id.decorator'
export * from './public.decorator'
export * from './current-user.decorator'
+export * from './two-fa-not-required.decorator'
+export * from './roles.decorator'
diff --git a/src/auth/decorators/public.decorator.ts b/src/auth/decorators/public.decorator.ts
index 93a3f77cd..91c2399b8 100644
--- a/src/auth/decorators/public.decorator.ts
+++ b/src/auth/decorators/public.decorator.ts
@@ -1,3 +1,4 @@
import { SetMetadata } from '@nestjs/common'
-export const Public = () => SetMetadata('isPublic', true)
+export const IS_PUBLIC_KEY = 'isPublic'
+export const Public = () => SetMetadata(IS_PUBLIC_KEY, true)
diff --git a/src/auth/decorators/roles.decorator.ts b/src/auth/decorators/roles.decorator.ts
new file mode 100644
index 000000000..d7cee989d
--- /dev/null
+++ b/src/auth/decorators/roles.decorator.ts
@@ -0,0 +1,5 @@
+import { SetMetadata } from '@nestjs/common'
+import { UserType } from 'src/user/entities/user.entity'
+
+export const IS_ROLES_KEY = 'roles'
+export const Roles = (...roles: UserType[]) => SetMetadata(IS_ROLES_KEY, roles)
diff --git a/src/auth/decorators/two-fa-not-required.decorator.ts b/src/auth/decorators/two-fa-not-required.decorator.ts
new file mode 100644
index 000000000..7f0839d32
--- /dev/null
+++ b/src/auth/decorators/two-fa-not-required.decorator.ts
@@ -0,0 +1,5 @@
+import { SetMetadata } from '@nestjs/common'
+
+export const IS_TWO_FA_NOT_REQUIRED_KEY = 'isTwoFaNotRequired'
+export const TwoFaNotRequired = () =>
+ SetMetadata(IS_TWO_FA_NOT_REQUIRED_KEY, true)
diff --git a/src/auth/guards/index.ts b/src/auth/guards/index.ts
index fce21343f..c7686e624 100644
--- a/src/auth/guards/index.ts
+++ b/src/auth/guards/index.ts
@@ -1,2 +1,3 @@
export * from './jwt-access-token.guard'
export * from './jwt-refresh-token.guard'
+export * from './roles.guard'
diff --git a/src/auth/guards/jwt-access-token.guard.ts b/src/auth/guards/jwt-access-token.guard.ts
index 937f8fe89..acf11ae8b 100644
--- a/src/auth/guards/jwt-access-token.guard.ts
+++ b/src/auth/guards/jwt-access-token.guard.ts
@@ -1,15 +1,16 @@
-import { ExecutionContext, Injectable } from '@nestjs/common'
+import { Injectable, ExecutionContext } from '@nestjs/common'
import { Reflector } from '@nestjs/core'
import { AuthGuard } from '@nestjs/passport'
+import { IS_PUBLIC_KEY } from '../decorators'
@Injectable()
export class JwtAccessTokenGuard extends AuthGuard('jwt-access-token') {
- constructor(private reflector: Reflector) {
+ constructor(private readonly reflector: Reflector) {
super()
}
canActivate(context: ExecutionContext) {
- const isPublic = this.reflector.getAllAndOverride('isPublic', [
+ const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
context.getHandler(),
context.getClass(),
])
diff --git a/src/auth/guards/roles.guard.ts b/src/auth/guards/roles.guard.ts
new file mode 100644
index 000000000..ce8ca7835
--- /dev/null
+++ b/src/auth/guards/roles.guard.ts
@@ -0,0 +1,47 @@
+import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common'
+import { Reflector } from '@nestjs/core'
+import { UserType } from 'src/user/entities/user.entity'
+import { UserService } from 'src/user/user.service'
+import { IS_ROLES_KEY, IS_TWO_FA_NOT_REQUIRED_KEY } from '../decorators'
+import { IJwtPayload } from '../interfaces'
+
+@Injectable()
+export class RolesGuard implements CanActivate {
+ constructor(
+ private readonly reflector: Reflector,
+ private readonly userService: UserService,
+ ) {}
+
+ async canActivate(context: ExecutionContext) {
+ const roles = this.reflector.get<UserType[]>(
+ IS_ROLES_KEY,
+ context.getHandler(),
+ )
+
+ const isTwoFaNotRequired = this.reflector.get<boolean>(
+ IS_TWO_FA_NOT_REQUIRED_KEY,
+ context.getHandler(),
+ )
+
+ if (!roles) return true
+
+ const request = context.switchToHttp().getRequest()
+ const userFromRequest = request.user as IJwtPayload
+
+ const user = await this.userService.findUserById(userFromRequest.sub)
+
+ const hasRole = user.roles.some(role => roles.includes(role))
+
+ if (!hasRole) return false
+
+ if (
+ !isTwoFaNotRequired &&
+ user.isTwoFactorAuthenticationEnabled &&
+ !userFromRequest.isSecondFactorAuthenticated
+ ) {
+ return false
+ }
+
+ return true
+ }
+}