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!

Remove role-based auth

Blue Mouse59817fb458d4
diff --git a/backend/apps/cloud/src/alert/alert.controller.ts b/backend/apps/cloud/src/alert/alert.controller.ts
index 1c1ffb9c8..e2294f1ef 100644
--- a/backend/apps/cloud/src/alert/alert.controller.ts
+++ b/backend/apps/cloud/src/alert/alert.controller.ts
@@ -3,7 +3,6 @@ import {
Get,
Put,
Delete,
- UseGuards,
Query,
Param,
Body,
@@ -25,10 +24,9 @@ import _pick from 'lodash/pick'
import { UserService } from '../user/user.service'
import { ProjectService } from '../project/project.service'
import { AppLoggerService } from '../logger/logger.service'
-import { UserType, ACCOUNT_PLANS, PlanCode } from '../user/entities/user.entity'
-import { JwtAccessTokenGuard } from '../auth/guards'
+import { ACCOUNT_PLANS, PlanCode } from '../user/entities/user.entity'
+import { Auth } from '../auth/decorators'
import { CurrentUserId } from '../auth/decorators/current-user-id.decorator'
-import { Roles } from '../auth/decorators/roles.decorator'
import { Alert } from './entity/alert.entity'
import {
AlertDTO,
@@ -37,7 +35,6 @@ import {
QueryCondition,
QueryTime,
} from './dto/alert.dto'
-import { RolesGuard } from '../auth/guards/roles.guard'
import { AlertService } from './alert.service'
const ALERTS_MAXIMUM = ACCOUNT_PLANS[PlanCode.free].maxAlerts
@@ -54,8 +51,7 @@ export class AlertController {
@ApiBearerAuth()
@Get('/:alertId')
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.ADMIN, UserType.CUSTOMER)
+ @Auth()
@ApiResponse({ status: 200, type: Alert })
async getAlert(
@CurrentUserId() userId: string,
@@ -81,8 +77,7 @@ export class AlertController {
@ApiBearerAuth()
@Get('/project/:projectId')
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.ADMIN, UserType.CUSTOMER)
+ @Auth()
@ApiResponse({ status: 200, type: Alert })
async getProjectAlerts(
@CurrentUserId() userId: string,
@@ -117,8 +112,7 @@ export class AlertController {
@ApiBearerAuth()
@Post('/')
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.ADMIN, UserType.CUSTOMER)
+ @Auth()
@ApiResponse({ status: 201, type: Alert })
async createAlert(
@Body() alertDTO: CreateAlertDTO,
@@ -231,8 +225,7 @@ export class AlertController {
@ApiBearerAuth()
@Put('/:id')
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.ADMIN, UserType.CUSTOMER)
+ @Auth()
@ApiResponse({ status: 200, type: Alert })
async updateAlert(
@Param('id') id: string,
@@ -312,8 +305,7 @@ export class AlertController {
@ApiBearerAuth()
@Delete('/:id')
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.ADMIN, UserType.CUSTOMER)
+ @Auth()
@ApiResponse({ status: 204, description: 'Empty body' })
async deleteAlert(@Param('id') id: string, @CurrentUserId() uid: string) {
this.logger.log({ id, uid }, 'DELETE /alert/:id')
diff --git a/backend/apps/cloud/src/analytics/analytics.controller.ts b/backend/apps/cloud/src/analytics/analytics.controller.ts
index f4285ae76..f350e39cb 100644
--- a/backend/apps/cloud/src/analytics/analytics.controller.ts
+++ b/backend/apps/cloud/src/analytics/analytics.controller.ts
@@ -40,7 +40,7 @@ import {
import { VALID_PERIODS } from './decorators/validate-period.decorator'
import { CurrentUserId } from '../auth/decorators/current-user-id.decorator'
import { DEFAULT_TIMEZONE } from '../user/entities/user.entity'
-import { RolesGuard } from '../auth/guards/roles.guard'
+import { AuthenticationGuard } from '../auth/guards/authentication.guard'
import { PageviewsDto } from './dto/pageviews.dto'
import { EventsDto } from './dto/events.dto'
import { GetDataDto, ChartRenderMode } from './dto/getData.dto'
@@ -184,7 +184,7 @@ const TRANSPARENT_GIF_BUFFER = Buffer.from(
)
@ApiTags('Analytics')
-@UseGuards(OptionalJwtAccessTokenGuard, RolesGuard)
+@UseGuards(OptionalJwtAccessTokenGuard, AuthenticationGuard)
@UsePipes(
new ValidationPipe({
transform: true,
@@ -199,7 +199,7 @@ export class AnalyticsController {
@ApiBearerAuth()
@Get()
- @Auth([], true, true)
+ @Auth(true, true)
async getData(
@Query() data: GetDataDto,
@CurrentUserId() uid: string,
@@ -367,7 +367,7 @@ export class AnalyticsController {
}
@Get('funnel')
- @Auth([], true, true)
+ @Auth(true, true)
async getFunnel(
@Query() data: GetFunnelsDto,
@CurrentUserId() uid: string,
@@ -442,7 +442,7 @@ export class AnalyticsController {
}
@Get('meta')
- @Auth([], true, true)
+ @Auth(true, true)
async getCustomEventMetadata(
@Query() data: GetCustomEventMetadata,
@CurrentUserId() uid: string,
@@ -462,7 +462,7 @@ export class AnalyticsController {
}
@Get('property')
- @Auth([], true, true)
+ @Auth(true, true)
async getPagePropertyMetadata(
@Query() data: GetPagePropertyMetaDto,
@CurrentUserId() uid: string,
@@ -482,7 +482,7 @@ export class AnalyticsController {
}
@Get('filters')
- @Auth([], true, true)
+ @Auth(true, true)
async getFilters(
@Query() data: GetFiltersDto,
@CurrentUserId() uid: string,
@@ -502,7 +502,7 @@ export class AnalyticsController {
}
@Get('errors-filters')
- @Auth([], true, true)
+ @Auth(true, true)
async getErrorsFilters(
@Query() data: GetFiltersDto,
@CurrentUserId() uid: string,
@@ -522,7 +522,7 @@ export class AnalyticsController {
}
@Get('chart')
- @Auth([], true, true)
+ @Auth(true, true)
async getChartData(
@Query() data: GetDataDto,
@CurrentUserId() uid: string,
@@ -575,7 +575,7 @@ export class AnalyticsController {
}
@Get('performance')
- @Auth([], true, true)
+ @Auth(true, true)
async getPerfData(
@Query() data: GetDataDto & { measure: PerfMeasure },
@CurrentUserId() uid: string,
@@ -656,7 +656,7 @@ export class AnalyticsController {
}
@Get('performance/chart')
- @Auth([], true, true)
+ @Auth(true, true)
async getPerfChartData(
@Query() data: GetDataDto & { measure: PerfMeasure },
@CurrentUserId() uid: string,
@@ -710,7 +710,7 @@ export class AnalyticsController {
}
@Get('captcha')
- @Auth([], true, true)
+ @Auth(true, true)
async getCaptchaData(
@Query() data: GetDataDto,
@CurrentUserId() uid: string,
@@ -719,7 +719,7 @@ export class AnalyticsController {
}
@Get('user-flow')
- @Auth([], true, true)
+ @Auth(true, true)
async getUserFlow(
@Query() data: GetUserFlowDto,
@CurrentUserId() uid: string,
@@ -767,7 +767,7 @@ export class AnalyticsController {
}
@Get('birdseye')
- @Auth([], true, true)
+ @Auth(true, true)
// returns overall short statistics per project
async getOverallStats(
@Query() data: GetOverallStatsDto,
@@ -825,7 +825,7 @@ export class AnalyticsController {
}
@Get('captcha/birdseye')
- @Auth([], true, true)
+ @Auth(true, true)
// returns overall short statistics per CAPTCHA project
async getCaptchaOverallStats(
@Query() data: GetOverallStatsDto,
@@ -876,7 +876,7 @@ export class AnalyticsController {
}
@Get('performance/birdseye')
- @Auth([], true, true)
+ @Auth(true, true)
async getPerformanceOverallStats(
@Query() data: GetOverallStatsDto & { measure: PerfMeasure },
@CurrentUserId() uid: string,
@@ -997,7 +997,7 @@ export class AnalyticsController {
}
@Get('live-visitors')
- @Auth([], true, true)
+ @Auth(true, true)
async getLiveVisitors(
@Query() queryParams: LiveVisitorsDto,
@CurrentUserId() uid: string,
@@ -1141,7 +1141,7 @@ export class AnalyticsController {
// Update error(s) status
@Patch('error-status')
- @Auth([], true, true)
+ @Auth(true, true)
async patchStatus(
@Body() statusDTO: PatchStatusDto,
@CurrentUserId() uid: string,
@@ -1253,7 +1253,7 @@ export class AnalyticsController {
}
@Post('hb')
- @Auth([], true, true)
+ @Auth(true, true)
async heartbeat(
@Body() logDTO: PageviewsDto,
@Headers() headers,
@@ -1489,7 +1489,7 @@ export class AnalyticsController {
}
@Get('sessions')
- @Auth([], true, true)
+ @Auth(true, true)
async getSessions(
@Query() data: GetSessionsDto,
@CurrentUserId() uid: string,
@@ -1564,7 +1564,7 @@ export class AnalyticsController {
}
@Get('errors')
- @Auth([], true, true)
+ @Auth(true, true)
async getErrors(
@Query() data: GetErrorsDto,
@CurrentUserId() uid: string,
@@ -1647,7 +1647,7 @@ export class AnalyticsController {
}
@Get('get-error')
- @Auth([], true, true)
+ @Auth(true, true)
async getError(
@Query() data: GetErrorDto,
@CurrentUserId() uid: string,
@@ -1708,7 +1708,7 @@ export class AnalyticsController {
}
@Get('session')
- @Auth([], true, true)
+ @Auth(true, true)
async getSession(
@Query() data: GetSessionDto,
@CurrentUserId() uid: string,
@@ -1741,7 +1741,7 @@ export class AnalyticsController {
}
@Get('custom-events')
- @Auth([], true, true)
+ @Auth(true, true)
async getCustomEvents(
@Query() data: GetCustomEventsDto,
@CurrentUserId() uid: string,
diff --git a/backend/apps/cloud/src/auth/auth.controller.ts b/backend/apps/cloud/src/auth/auth.controller.ts
index 69f7d3af5..bc151fb0e 100644
--- a/backend/apps/cloud/src/auth/auth.controller.ts
+++ b/backend/apps/cloud/src/auth/auth.controller.ts
@@ -28,10 +28,10 @@ import { I18nValidationExceptionFilter, I18n, I18nContext } from 'nestjs-i18n'
import _pick from 'lodash/pick'
import { checkRateLimit, getIPFromHeaders } from '../common/utils'
-import { UserType, User } from '../user/entities/user.entity'
+import { User } from '../user/entities/user.entity'
import { UserService } from '../user/user.service'
import { AuthService } from './auth.service'
-import { Public, CurrentUserId, CurrentUser, Roles } from './decorators'
+import { Public, CurrentUserId, CurrentUser } from './decorators'
import {
RegisterResponseDto,
RegisterRequestDto,
@@ -50,7 +50,11 @@ import {
SSOUnlinkDto,
SSOProviders,
} from './dtos'
-import { JwtAccessTokenGuard, JwtRefreshTokenGuard, RolesGuard } from './guards'
+import {
+ JwtAccessTokenGuard,
+ JwtRefreshTokenGuard,
+ AuthenticationGuard,
+} from './guards'
import { ProjectService } from '../project/project.service'
const OAUTH_RATE_LIMIT = 15
@@ -257,8 +261,7 @@ export class AuthController {
@ApiOkResponse({
description: 'Resend of the verification email requested',
})
- @UseGuards(RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
+ @UseGuards(AuthenticationGuard)
@Post('verify-email')
public async requestResendVerificationEmail(
@CurrentUserId() userId: string,
@@ -289,8 +292,7 @@ export class AuthController {
@ApiOkResponse({
description: 'User email changed',
})
- @UseGuards(RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
+ @UseGuards(AuthenticationGuard)
@Post('change-email')
public async requestChangeEmail(
@Body() body: RequestChangeEmailDto,
@@ -496,8 +498,7 @@ export class AuthController {
@ApiOkResponse({
description: 'SSO provider linked to an existing account',
})
- @UseGuards(RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
+ @UseGuards(AuthenticationGuard)
@Post('sso/link_by_hash')
public async linkGoogleToAccount(
@Body() body: SSOLinkDto,
@@ -513,8 +514,7 @@ export class AuthController {
@ApiOkResponse({
description: 'SSO provider unlinked from an existing account',
})
- @UseGuards(RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
+ @UseGuards(AuthenticationGuard)
@Delete('sso/unlink')
public async unlinkSSOFromAccount(
@Body() body: SSOUnlinkDto,
diff --git a/backend/apps/cloud/src/auth/decorators/auth.decorator.ts b/backend/apps/cloud/src/auth/decorators/auth.decorator.ts
index 727ea2e76..07d43fa8f 100644
--- a/backend/apps/cloud/src/auth/decorators/auth.decorator.ts
+++ b/backend/apps/cloud/src/auth/decorators/auth.decorator.ts
@@ -3,22 +3,15 @@ import {
ApiKeyRateLimitGuard,
JwtAccessTokenGuard,
MultiAuthGuard,
- RolesGuard,
+ AuthenticationGuard,
} from '../guards'
-import { UserType } from '../../user/entities/user.entity'
-import { ROLES_KEY } from './roles.decorator'
export const IS_OPTIONAL_AUTH_KEY = 'isOptionalAuth'
-export function Auth(
- roles: UserType[],
- isApiKeyAuth = false,
- isOptionalAuth = false,
-) {
+export function Auth(allowApiKeyAuth = false, isOptionalAuth = false) {
return applyDecorators(
- SetMetadata(ROLES_KEY, roles),
SetMetadata(IS_OPTIONAL_AUTH_KEY, isOptionalAuth),
- isApiKeyAuth
- ? UseGuards(MultiAuthGuard, ApiKeyRateLimitGuard, RolesGuard)
- : UseGuards(JwtAccessTokenGuard, RolesGuard),
+ allowApiKeyAuth
+ ? UseGuards(MultiAuthGuard, ApiKeyRateLimitGuard, AuthenticationGuard)
+ : UseGuards(JwtAccessTokenGuard, AuthenticationGuard),
)
}
diff --git a/backend/apps/cloud/src/auth/decorators/index.ts b/backend/apps/cloud/src/auth/decorators/index.ts
index 377aac6a6..e5cfebf8b 100644
--- a/backend/apps/cloud/src/auth/decorators/index.ts
+++ b/backend/apps/cloud/src/auth/decorators/index.ts
@@ -2,5 +2,4 @@ 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'
export * from './auth.decorator'
diff --git a/backend/apps/cloud/src/auth/decorators/roles.decorator.ts b/backend/apps/cloud/src/auth/decorators/roles.decorator.ts
deleted file mode 100644
index fcbea69e4..000000000
--- a/backend/apps/cloud/src/auth/decorators/roles.decorator.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-import { SetMetadata } from '@nestjs/common'
-import { UserType } from '../../user/entities/user.entity'
-
-export const ROLES_KEY = 'roles'
-export const Roles = (...roles: UserType[]) => SetMetadata(ROLES_KEY, roles)
diff --git a/backend/apps/cloud/src/auth/guards/roles.guard.ts b/backend/apps/cloud/src/auth/guards/authentication.guard.ts
similarity index 65%
rename from backend/apps/cloud/src/auth/guards/roles.guard.ts
rename to backend/apps/cloud/src/auth/guards/authentication.guard.ts
index f1bd5d2ad..d2cce43e1 100644
--- a/backend/apps/cloud/src/auth/guards/roles.guard.ts
+++ b/backend/apps/cloud/src/auth/guards/authentication.guard.ts
@@ -3,48 +3,28 @@ import { Reflector } from '@nestjs/core'
import { ExtractJwt } from 'passport-jwt'
import { verify } from 'jsonwebtoken'
-import { UserType } from '../../user/entities/user.entity'
import { UserService } from '../../user/user.service'
import { JWT_ACCESS_TOKEN_SECRET } from '../../common/constants'
-import { IS_TWO_FA_NOT_REQUIRED_KEY, ROLES_KEY } from '../decorators'
+import { IS_TWO_FA_NOT_REQUIRED_KEY } from '../decorators'
@Injectable()
-export class RolesGuard implements CanActivate {
+export class AuthenticationGuard implements CanActivate {
constructor(
private readonly reflector: Reflector,
private readonly userService: UserService,
) {}
async canActivate(context: ExecutionContext) {
- const roles = this.reflector.get<UserType[]>(
- ROLES_KEY,
- context.getHandler(),
- )
-
const isTwoFaNotRequired = this.reflector.get<boolean>(
IS_TWO_FA_NOT_REQUIRED_KEY,
context.getHandler(),
)
- if (!roles || roles.length === 0) return true
-
const request = context.switchToHttp().getRequest()
const userFromRequest = request.user
const user = await this.userService.findUserById(userFromRequest.id)
- // this is a temp measure as well due to some fucking bug related to undefined user, will revert it when I find the cause
- let hasRole
- try {
- hasRole = user.roles.some(role => roles.includes(role))
- } catch (error) {
- console.error(`[AUTH ERROR - ROLES GUARD] ${error.message}`)
- console.error(user, roles)
- console.error(request?.path, request?.originalUrl, request?.method)
- }
-
- if (!hasRole) return false
-
let token = ''
if (request.cookies.token) {
token = request.cookies.token
@@ -53,13 +33,15 @@ export class RolesGuard implements CanActivate {
token = extract(request)
}
- if (isTwoFaNotRequired) {
+ if (isTwoFaNotRequired || !token) {
return true
}
try {
const decoded: any = verify(token, JWT_ACCESS_TOKEN_SECRET)
+ console.log('AuthenticationGuard decoded', decoded)
+
// If the token is not decoded, it means it's invalid
if (!decoded) {
return false
diff --git a/backend/apps/cloud/src/auth/guards/index.ts b/backend/apps/cloud/src/auth/guards/index.ts
index 6c37ea3a7..e049f4499 100644
--- a/backend/apps/cloud/src/auth/guards/index.ts
+++ b/backend/apps/cloud/src/auth/guards/index.ts
@@ -1,6 +1,6 @@
export * from './jwt-access-token.guard'
export * from './jwt-refresh-token.guard'
-export * from './roles.guard'
+export * from './authentication.guard'
export * from './optional-jwt-access-token.guard'
export * from './api-key-rate-limit.guard'
export * from './multi-auth.guard'
diff --git a/backend/apps/cloud/src/marketplace/categories/categories.controller.ts b/backend/apps/cloud/src/marketplace/categories/categories.controller.ts
index 5a77b6e96..2d5a016e4 100644
--- a/backend/apps/cloud/src/marketplace/categories/categories.controller.ts
+++ b/backend/apps/cloud/src/marketplace/categories/categories.controller.ts
@@ -1,33 +1,17 @@
import {
- Body,
- ConflictException,
Controller,
- Delete,
Get,
NotFoundException,
Param,
- Patch,
- Post,
Query,
- UseGuards,
UsePipes,
ValidationPipe,
} from '@nestjs/common'
-import { ApiBearerAuth, ApiParam, ApiQuery, ApiTags } from '@nestjs/swagger'
-import { JwtAccessTokenGuard } from '../../auth/guards'
-import { Roles } from '../../auth/decorators/roles.decorator'
-import { RolesGuard } from '../../auth/guards/roles.guard'
-import { UserType } from '../../user/entities/user.entity'
+import { ApiParam, ApiQuery, ApiTags } from '@nestjs/swagger'
import { CategoriesService } from './categories.service'
import { Category } from './category.entity'
-import { CreateCategory } from './dtos/create-category.dto'
-import { DeleteCategoryParams } from './dtos/delete-category-params.dto'
import { GetAllCategoriesQueries } from './dtos/get-all-categories-queries.dto'
import { GetCategoryParams } from './dtos/get-category-params.dto'
-import { UpdateCategoryParams } from './dtos/update-category-params.dto'
-import { UpdateCategory } from './dtos/update-category.dto'
-import { ISaveCategory } from './interfaces/save-category.interface'
-import { BodyValidationPipe } from '../common/pipes/body-validation.pipe'
@ApiTags('categories')
@UsePipes(
@@ -90,75 +74,4 @@ export class CategoriesController {
return category
}
-
- @ApiBearerAuth()
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.ADMIN)
- @Post()
- async createCategory(
- @Body() body: CreateCategory,
- ): Promise<ISaveCategory & Category> {
- const categoryName = await this.categoriesService.findByName(body.name)
-
- if (categoryName) {
- throw new ConflictException('A category with that name already exists.')
- }
-
- const categoryInstance = this.categoriesService.create(body)
-
- return this.categoriesService.save(categoryInstance)
- }
-
- @ApiBearerAuth()
- @ApiParam({
- name: 'categoryId',
- description: 'Category ID',
- example: 1,
- type: Number,
- })
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.ADMIN)
- @Patch(':categoryId')
- async updateCategory(
- @Param() params: UpdateCategoryParams,
- @Body(new BodyValidationPipe()) body: UpdateCategory,
- ): Promise<UpdateCategory> {
- const category = await this.categoriesService.findById(params.categoryId)
-
- if (!category) {
- throw new NotFoundException('Category not found.')
- }
-
- if (body.name) {
- const categoryName = await this.categoriesService.findByName(body.name)
-
- if (categoryName) {
- throw new ConflictException('A category with that name already exists.')
- }
- }
-
- await this.categoriesService.update(category.id, body)
-
- return body
- }
-
- @ApiBearerAuth()
- @ApiParam({
- name: 'categoryId',
- description: 'Category ID',
- example: 1,
- type: Number,
- })
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.ADMIN)
- @Delete(':categoryId')
- async deleteCategory(@Param() params: DeleteCategoryParams): Promise<void> {
- const category = await this.categoriesService.findById(params.categoryId)
-
- if (!category) {
- throw new NotFoundException('Category not found.')
- }
-
- await this.categoriesService.delete(category.id)
- }
}
diff --git a/backend/apps/cloud/src/marketplace/categories/dtos/create-category.dto.ts b/backend/apps/cloud/src/marketplace/categories/dtos/create-category.dto.ts
deleted file mode 100644
index a206c3fac..000000000
--- a/backend/apps/cloud/src/marketplace/categories/dtos/create-category.dto.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import { ApiProperty } from '@nestjs/swagger'
-import { IsString, MaxLength, MinLength } from 'class-validator'
-
-export class CreateCategory {
- @ApiProperty({
- description: 'Category name',
- example: 'Marketing',
- maxLength: 255,
- minLength: 1,
- type: String,
- })
- @IsString()
- @MinLength(1)
- @MaxLength(255)
- readonly name!: string
-}
diff --git a/backend/apps/cloud/src/marketplace/categories/dtos/delete-category-params.dto.ts b/backend/apps/cloud/src/marketplace/categories/dtos/delete-category-params.dto.ts
deleted file mode 100644
index 1e470fe4f..000000000
--- a/backend/apps/cloud/src/marketplace/categories/dtos/delete-category-params.dto.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-import { IsNumberString } from 'class-validator'
-
-export class DeleteCategoryParams {
- @IsNumberString()
- readonly categoryId!: number
-}
diff --git a/backend/apps/cloud/src/marketplace/categories/dtos/update-category-params.dto.ts b/backend/apps/cloud/src/marketplace/categories/dtos/update-category-params.dto.ts
deleted file mode 100644
index b699d4821..000000000
--- a/backend/apps/cloud/src/marketplace/categories/dtos/update-category-params.dto.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-import { IsNumberString } from 'class-validator'
-
-export class UpdateCategoryParams {
- @IsNumberString()
- readonly categoryId!: number
-}
diff --git a/backend/apps/cloud/src/marketplace/categories/dtos/update-category.dto.ts b/backend/apps/cloud/src/marketplace/categories/dtos/update-category.dto.ts
deleted file mode 100644
index 25affb003..000000000
--- a/backend/apps/cloud/src/marketplace/categories/dtos/update-category.dto.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-import { ApiProperty } from '@nestjs/swagger'
-import { IsOptional, IsString, MaxLength, MinLength } from 'class-validator'
-
-export class UpdateCategory {
- @ApiProperty({
- description: 'Category name',
- example: 'Marketing',
- maxLength: 255,
- minLength: 1,
- required: false,
- type: String,
- })
- @IsString()
- @IsOptional()
- @MinLength(1)
- @MaxLength(255)
- readonly name?: string
-}
diff --git a/backend/apps/cloud/src/marketplace/comments/comments.controller.ts b/backend/apps/cloud/src/marketplace/comments/comments.controller.ts
index 90b08fc5e..b3ad19a5a 100644
--- a/backend/apps/cloud/src/marketplace/comments/comments.controller.ts
+++ b/backend/apps/cloud/src/marketplace/comments/comments.controller.ts
@@ -41,7 +41,7 @@ export class CommentsController {
private readonly userService: UserService,
) {}
- @Auth([], true, true)
+ @Auth()
@Get()
@ApiQuery({ name: 'offset', required: false, type: String })
@ApiQuery({ name: 'limit', required: false, type: String })
@@ -61,7 +61,7 @@ export class CommentsController {
}
}
- @Auth([UserType.CUSTOMER, UserType.ADMIN])
+ @Auth()
@Post()
@ApiQuery({ name: 'userId', required: true, type: String })
async createComment(
@@ -108,7 +108,7 @@ export class CommentsController {
})
}
- @Auth([UserType.CUSTOMER, UserType.ADMIN])
+ @Auth()
@Delete(':commentId')
@ApiParam({ name: 'commentId', required: true, type: String })
async deleteComment(
@@ -133,7 +133,7 @@ export class CommentsController {
await this.commentsService.delete(params.commentId)
}
- @Auth([UserType.ADMIN, UserType.CUSTOMER])
+ @Auth()
@Post('reply')
async createCommentReply(
@Body() commentReplyDto: CreateReplyCommentBodyDto,
@@ -180,7 +180,7 @@ export class CommentsController {
}
}
- @Auth([UserType.ADMIN, UserType.CUSTOMER])
+ @Auth()
@Put('reply/:id')
async updateCommentReply(
@Param('id') id: string,
@@ -210,7 +210,7 @@ export class CommentsController {
}
}
- @Auth([UserType.ADMIN, UserType.CUSTOMER])
+ @Auth()
@Delete('reply/:id')
async deleteCommentReply(
@Param('id') id: string,
diff --git a/backend/apps/cloud/src/marketplace/common/pipes/body-validation.pipe.ts b/backend/apps/cloud/src/marketplace/common/pipes/body-validation.pipe.ts
deleted file mode 100644
index 49525325a..000000000
--- a/backend/apps/cloud/src/marketplace/common/pipes/body-validation.pipe.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-import { BadRequestException, Injectable, PipeTransform } from '@nestjs/common'
-
-@Injectable()
-export class BodyValidationPipe implements PipeTransform {
- transform(value: any) {
- if (Object.keys(value).length === 0) {
- throw new BadRequestException('The body cannot be empty.')
- }
-
- return value
- }
-}
diff --git a/backend/apps/cloud/src/marketplace/complaints/complaints.controller.ts b/backend/apps/cloud/src/marketplace/complaints/complaints.controller.ts
index fe71fdbcd..9a3d161d7 100644
--- a/backend/apps/cloud/src/marketplace/complaints/complaints.controller.ts
+++ b/backend/apps/cloud/src/marketplace/complaints/complaints.controller.ts
@@ -1,27 +1,16 @@
import {
Body,
Controller,
- Get,
NotFoundException,
- Param,
Post,
- UseGuards,
Query,
} from '@nestjs/common'
-import { ApiBearerAuth, ApiParam, ApiQuery, ApiTags } from '@nestjs/swagger'
-import { UserType } from '../../user/entities/user.entity'
-import { RolesGuard } from '../../auth/guards/roles.guard'
-import { Roles } from '../../auth/decorators/roles.decorator'
-import { JwtAccessTokenGuard } from '../../auth/guards'
+import { ApiQuery, ApiTags } from '@nestjs/swagger'
import { UserService } from '../../user/user.service'
import { ExtensionsService } from '../extensions/extensions.service'
import { ComplaintsService } from './complaints.service'
import { CreateComplaintBodyDto } from './dtos/bodies/create-complaint.dto'
-import { ResolveComplaintBodyDto } from './dtos/bodies/resolve-complaint.dto'
-import { GetComplaintParamDto } from './dtos/params/get-complaint.dto'
-import { ResolveComplaintParamDto } from './dtos/params/resolve-complaint.dto'
import { CreateComplaintQueryDto } from './dtos/queries/create-complaint.dto'
-import { GetComplaintsQueryDto } from './dtos/queries/get-complaints.dto'
import { Complaint } from './entities/complaint.entity'
@ApiTags('complaints')
@@ -33,49 +22,6 @@ export class ComplaintsController {
private readonly extensionsService: ExtensionsService,
) {}
- @ApiBearerAuth()
- @Get()
- @ApiQuery({ name: 'offset', required: false, type: String })
- @ApiQuery({ name: 'limit', required: false, type: String })
- @ApiQuery({ name: 'extensionId', required: false, type: String })
- @ApiQuery({ name: 'userId', required: false, type: String })
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.ADMIN)
- async getComplaints(@Query() queries: GetComplaintsQueryDto): Promise<{
- complaints: Complaint[]
- count: number
- }> {
- const [complaints, count] = await this.complaintsService.findAndCount({
- where: {
- ...(queries.extensionId && { extensionId: queries.extensionId }),
- ...(queries.userId && { userId: queries.userId }),
- },
- skip: queries.offset || 0,
- take: queries.limit || 25,
- })
-
- return { complaints, count }
- }
-
- @ApiBearerAuth()
- @Get(':complaintId')
- @ApiParam({ name: 'complaintId', required: true, type: String })
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.ADMIN)
- async getComplaint(
- @Param() params: GetComplaintParamDto,
- ): Promise<Complaint> {
- const complaint = await this.complaintsService.findOne({
- where: { id: parseInt(params.complaintId, 10) },
- })
-
- if (!complaint) {
- throw new NotFoundException('Complaint not found.')
- }
-
- return complaint
- }
-
@Post()
@ApiQuery({ name: 'userId', required: true, type: String })
async createComplaint(
@@ -104,32 +50,4 @@ export class ComplaintsController {
extensionId: Number(body.extensionId),
})
}
-
- @ApiBearerAuth()
- @Post(':complaintId/resolve')
- @ApiParam({ name: 'complaintId', required: true, type: String })
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.ADMIN)
- async resolveComplaint(
- @Param() params: ResolveComplaintParamDto,
- @Body() body: ResolveComplaintBodyDto,
- ) {
- const complaint = await this.complaintsService.findOne({
- where: { id: parseInt(params.complaintId, 10) },
- })
-
- if (!complaint) {
- throw new NotFoundException('Complaint not found.')
- }
-
- if (complaint.isResolved) {
- throw new NotFoundException('Complaint is already resolved.')
- }
-
- await this.complaintsService.update(Number(params.complaintId), {
- extensionId: Number(params.complaintId),
- ...body,
- isResolved: true,
- })
- }
}
diff --git a/backend/apps/cloud/src/marketplace/complaints/dtos/bodies/resolve-complaint.dto.ts b/backend/apps/cloud/src/marketplace/complaints/dtos/bodies/resolve-complaint.dto.ts
deleted file mode 100644
index f8e6d86b6..000000000
--- a/backend/apps/cloud/src/marketplace/complaints/dtos/bodies/resolve-complaint.dto.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-import { ApiProperty } from '@nestjs/swagger'
-import { IsEnum, IsString } from 'class-validator'
-import { ComplaintStatus } from '../../enums/complaint-status.enum'
-
-export class ResolveComplaintBodyDto {
- @ApiProperty()
- @IsString()
- reply: string | null
-
- @ApiProperty({
- enum: ComplaintStatus,
- })
- @IsEnum(ComplaintStatus)
- status: ComplaintStatus
-}
diff --git a/backend/apps/cloud/src/marketplace/complaints/dtos/params/get-complaint.dto.ts b/backend/apps/cloud/src/marketplace/complaints/dtos/params/get-complaint.dto.ts
deleted file mode 100644
index 167b957d0..000000000
--- a/backend/apps/cloud/src/marketplace/complaints/dtos/params/get-complaint.dto.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-import { IsNumberString } from 'class-validator'
-
-export class GetComplaintParamDto {
- @IsNumberString()
- complaintId: string
-}
diff --git a/backend/apps/cloud/src/marketplace/complaints/dtos/params/resolve-complaint.dto.ts b/backend/apps/cloud/src/marketplace/complaints/dtos/params/resolve-complaint.dto.ts
deleted file mode 100644
index 45c9aea90..000000000
--- a/backend/apps/cloud/src/marketplace/complaints/dtos/params/resolve-complaint.dto.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-import { IsNumberString } from 'class-validator'
-
-export class ResolveComplaintParamDto {
- @IsNumberString()
- complaintId: string
-}
diff --git a/backend/apps/cloud/src/marketplace/complaints/dtos/queries/get-complaints.dto.ts b/backend/apps/cloud/src/marketplace/complaints/dtos/queries/get-complaints.dto.ts
deleted file mode 100644
index 92a36a54b..000000000
--- a/backend/apps/cloud/src/marketplace/complaints/dtos/queries/get-complaints.dto.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import { IsNumberString, IsOptional } from 'class-validator'
-
-export class GetComplaintsQueryDto {
- @IsNumberString()
- @IsOptional()
- offset?: number
-
- @IsNumberString()
- @IsOptional()
- limit?: number
-
- @IsNumberString()
- @IsOptional()
- extensionId?: number
-
- @IsNumberString()
- @IsOptional()
- userId?: number
-}
diff --git a/backend/apps/cloud/src/marketplace/extensions/dtos/update-extension-params.dto.ts b/backend/apps/cloud/src/marketplace/extensions/dtos/update-extension-params.dto.ts
deleted file mode 100644
index 93493a1a3..000000000
--- a/backend/apps/cloud/src/marketplace/extensions/dtos/update-extension-params.dto.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-import { IsString } from 'class-validator'
-
-export class UpdateExtensionParams {
- @IsString()
- readonly extensionId!: string
-}
diff --git a/backend/apps/cloud/src/marketplace/extensions/extensions.controller.ts b/backend/apps/cloud/src/marketplace/extensions/extensions.controller.ts
index 8614adc88..1b584975f 100644
--- a/backend/apps/cloud/src/marketplace/extensions/extensions.controller.ts
+++ b/backend/apps/cloud/src/marketplace/extensions/extensions.controller.ts
@@ -11,17 +11,14 @@ import {
Patch,
Post,
Query,
- UseGuards,
UsePipes,
ValidationPipe,
} from '@nestjs/common'
-import { ApiBearerAuth, ApiParam, ApiQuery, ApiTags } from '@nestjs/swagger'
+import { ApiParam, ApiQuery, ApiTags } from '@nestjs/swagger'
import { FormDataRequest } from 'nestjs-form-data'
-import { Like } from 'typeorm'
import _map from 'lodash/map'
import _size from 'lodash/size'
import { CurrentUserId } from '../../auth/decorators/current-user-id.decorator'
-import { JwtAccessTokenGuard } from '../../auth/guards'
import { Auth } from '../../auth/decorators'
import { AppLoggerService } from '../../logger/logger.service'
import { DeleteExtensionParams } from './dtos/delete-extension-params.dto'
@@ -29,7 +26,6 @@ import { GetExtensionParams } from './dtos/get-extension-params.dto'
import { GetAllExtensionsQueries } from './dtos/get-all-extensions-queries.dto'
import { ExtensionsService } from './extensions.service'
import { UserService } from '../../user/user.service'
-import { UpdateExtensionParams } from './dtos/update-extension-params.dto'
import { SearchExtensionQueries } from './dtos/search-extension-queries.dto'
import { CategoriesService } from '../categories/categories.service'
import { Extension } from './entities/extension.entity'
@@ -39,10 +35,6 @@ import { UninstallExtensionParamsDto } from './dtos/params/uninstall-extension.d
import { InstallExtensionBodyDto } from './dtos/bodies/install-extension.dto'
import { UninstallExtensionBodyDto } from './dtos/bodies/uninstall-extension.dto'
import { ProjectService } from '../../project/project.service'
-import { Roles } from '../../auth/decorators/roles.decorator'
-import { RolesGuard } from '../../auth/guards/roles.guard'
-import { UserType } from '../../user/entities/user.entity'
-import { ExtensionStatus } from './enums/extension-status.enum'
import {
CreateExtensionBodyDto,
UpdateExtensionBodyDto,
@@ -69,7 +61,7 @@ export class ExtensionsController {
) {}
@Get('installed')
- @Auth([UserType.CUSTOMER, UserType.ADMIN])
+ @Auth()
async getInstalledExtensions(
@Query() queries: GetInstalledExtensionsQueriesDto,
@CurrentUserId() userId: string,
@@ -152,47 +144,6 @@ export class ExtensionsController {
return { extensions, count }
}
- @ApiQuery({
- description: 'Extension offset',
- example: '5',
- name: 'offset',
- required: false,
- type: String,
- })
- @ApiQuery({
- description: 'Extension limit',
- example: '25',
- name: 'limit',
- required: false,
- type: String,
- })
- @Auth([UserType.ADMIN])
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Get('admin')
- async getAllExtensionsAdmin(
- @Query() queries: GetAllExtensionsQueries,
- ): Promise<{
- extensions: Extension[]
- count: number
- }> {
- let [extensions, count] = await this.extensionsService.findAndCount({
- skip: queries.offset || 0,
- take: queries.limit > 100 ? 25 : queries.limit || 25,
- relations: ['owner', 'users', 'category'],
- })
-
- extensions = _map(extensions, extension => {
- // @ts-expect-error
- extension.usersQuantity = _size(extension.users)
- extension.users = undefined
- // @ts-expect-error
- extension.owner = this.extensionsService.filterOwner(extension.owner)
- return extension
- })
-
- return { extensions, count }
- }
-
@ApiQuery({
description: 'Extension term',
example: '',
@@ -235,7 +186,7 @@ export class ExtensionsController {
type: String,
})
@Get('published')
- @Auth([UserType.CUSTOMER, UserType.ADMIN])
+ @Auth()
async getAllPublishedExtensions(
@Query() queries: GetAllExtensionsQueries,
@CurrentUserId() userId: string,
@@ -321,47 +272,6 @@ export class ExtensionsController {
return { extensions, count }
}
- @ApiQuery({
- description: 'Extension term',
- example: '',
- name: 'term',
- type: String,
- })
- @ApiQuery({
- description: 'Extension offset',
- example: '5',
- name: 'offset',
- required: false,
- type: String,
- })
- @ApiQuery({
- description: 'Extension limit',
- example: '25',
- name: 'limit',
- required: false,
- type: String,
- })
- @ApiBearerAuth()
- @Roles(UserType.ADMIN)
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Get('admin/search')
- async searchExtensionAdmin(
- @Query() queries: SearchExtensionQueries,
- ): Promise<{
- extensions: Extension[]
- count: number
- }> {
- const [extensions, count] = await this.extensionsService.findAndCount({
- where: {
- name: Like(`%${queries.term}%`),
- },
- skip: queries.offset || 0,
- take: queries.limit > 100 ? 25 : queries.limit || 25,
- })
-
- return { extensions, count }
- }
-
@ApiParam({
name: 'extensionId',
description: 'Extension ID',
@@ -385,7 +295,7 @@ export class ExtensionsController {
}
@Post()
- @Auth([UserType.CUSTOMER, UserType.ADMIN])
+ @Auth()
@FormDataRequest()
async createExtension(
@Body() body: CreateExtensionBodyDto,
@@ -408,7 +318,7 @@ export class ExtensionsController {
}
@Patch(':extensionId')
- @Auth([UserType.CUSTOMER, UserType.ADMIN])
+ @Auth()
@FormDataRequest()
async updateExtension(
@Param() params: UpdateExtensionParamsDto,
@@ -464,62 +374,6 @@ export class ExtensionsController {
)
}
- @ApiBearerAuth()
- @ApiParam({
- name: 'extensionId',
- description: 'Extension ID',
- example: 'de025965-3221-4d09-ba35-a09da59793a6',
- type: String,
- })
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.ADMIN)
- @Patch(':extensionId/approve')
- async approveExtension(
- @Param() params: UpdateExtensionParams,
- ): Promise<Extension> {
- const { extensionId } = params
-
- const extension = await this.extensionsService.findOne({
- where: { id: extensionId },
- })
-
- if (!extension) {
- throw new NotFoundException('Extension not found.')
- }
-
- extension.status = ExtensionStatus.ACCEPTED
-
- return this.extensionsService.save(extension)
- }
-
- @ApiBearerAuth()
- @ApiParam({
- name: 'extensionId',
- description: 'Extension ID',
- example: 'de025965-3221-4d09-ba35-a09da59793a6',
- type: String,
- })
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.ADMIN)
- @Patch(':extensionId/reject')
- async rejectExtension(
- @Param() params: UpdateExtensionParams,
- ): Promise<Extension> {
- const { extensionId } = params
-
- const extension = await this.extensionsService.findOne({
- where: { id: extensionId },
- })
-
- if (!extension) {
- throw new NotFoundException('Extension not found.')
- }
-
- extension.status = ExtensionStatus.REJECTED
-
- return this.extensionsService.save(extension)
- }
-
@ApiParam({
name: 'extensionId',
description: 'Extension ID',
@@ -539,7 +393,7 @@ export class ExtensionsController {
}
@Post(':extensionId/install')
- @Auth([UserType.CUSTOMER, UserType.ADMIN])
+ @Auth()
async installExtension(
@Param() params: InstallExtensionParamsDto,
@Body() body: InstallExtensionBodyDto,
@@ -610,7 +464,7 @@ export class ExtensionsController {
}
@Delete(':extensionId/uninstall')
- @Auth([UserType.CUSTOMER, UserType.ADMIN])
+ @Auth()
async uninstallExtension(
@Param() params: UninstallExtensionParamsDto,
@Body() body: UninstallExtensionBodyDto,
diff --git a/backend/apps/cloud/src/organisation/organisation.controller.ts b/backend/apps/cloud/src/organisation/organisation.controller.ts
index 10fd3249f..315ef9975 100644
--- a/backend/apps/cloud/src/organisation/organisation.controller.ts
+++ b/backend/apps/cloud/src/organisation/organisation.controller.ts
@@ -4,7 +4,6 @@ import {
Delete,
Body,
Param,
- UseGuards,
BadRequestException,
NotFoundException,
HttpCode,
@@ -19,11 +18,7 @@ import {
import { ApiBearerAuth, ApiQuery, ApiResponse } from '@nestjs/swagger'
import { isEmpty as _isEmpty, find as _find, trim as _trim } from 'lodash'
-import { JwtAccessTokenGuard } from '../auth/guards/jwt-access-token.guard'
-import { RolesGuard } from '../auth/guards/roles.guard'
-import { Roles } from '../auth/decorators/roles.decorator'
import { CurrentUserId } from '../auth/decorators/current-user-id.decorator'
-import { UserType } from '../user/entities/user.entity'
import { Organisation } from './entity/organisation.entity'
import { OrganisationService } from './organisation.service'
import { UserService } from '../user/user.service'
@@ -65,7 +60,7 @@ export class OrganisationController {
@ApiQuery({ name: 'skip', required: false })
@ApiQuery({ name: 'search', required: false, type: String })
@ApiResponse({ status: 200, type: [Organisation] })
- @Auth([], true)
+ @Auth(true)
async get(
@CurrentUserId() userId: string,
@Query('take', new ParseIntPipe({ optional: true })) take?: number,
@@ -80,7 +75,7 @@ export class OrganisationController {
@ApiBearerAuth()
@Get('/:orgId')
@ApiResponse({ status: 200, type: Organisation })
- @Auth([], true)
+ @Auth(true)
async getOne(
@Param('orgId') orgId: string,
@CurrentUserId() userId: string,
@@ -126,10 +121,9 @@ export class OrganisationController {
@ApiBearerAuth()
@Post('/')
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
+ @Auth()
@ApiResponse({ status: 200, type: Organisation })
- @Auth([], true)
+ @Auth(true)
async create(
@Body() createOrgDTO: CreateOrganisationDTO,
@CurrentUserId() uid: string,
@@ -155,9 +149,8 @@ export class OrganisationController {
@ApiBearerAuth()
@Post('/:orgId/invite')
@HttpCode(200)
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
- @Auth([], true)
+ @Auth()
+ @Auth(true)
async inviteMember(
@Param('orgId') orgId: string,
@Body() inviteDTO: InviteMemberDTO,
@@ -263,9 +256,8 @@ export class OrganisationController {
@ApiBearerAuth()
@Patch('/member/:memberId')
@HttpCode(200)
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
- @Auth([], true)
+ @Auth()
+ @Auth(true)
async updateMemberRole(
@Param('memberId') memberId: string,
@Body() updateDTO: UpdateMemberRoleDTO,
@@ -313,9 +305,8 @@ export class OrganisationController {
@ApiBearerAuth()
@Delete('/member/:memberId')
@HttpCode(204)
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
- @Auth([], true)
+ @Auth()
+ @Auth(true)
async removeMember(
@Param('memberId') memberId: string,
@CurrentUserId() uid: string,
@@ -350,7 +341,7 @@ export class OrganisationController {
@ApiBearerAuth()
@Delete('/:orgId')
@ApiResponse({ status: 200, type: Organisation })
- @Auth([], true)
+ @Auth(true)
async delete(@Param('orgId') orgId: string, @CurrentUserId() userId: string) {
this.logger.log({ orgId, userId }, 'DELETE /organisation/:orgId')
@@ -382,7 +373,7 @@ export class OrganisationController {
@ApiBearerAuth()
@Patch('/:orgId')
@ApiResponse({ status: 200, type: Organisation })
- @Auth([], true)
+ @Auth(true)
async update(
@Param('orgId') orgId: string,
@Body() updateOrgDTO: UpdateOrganisationDTO,
diff --git a/backend/apps/cloud/src/project/project.controller.ts b/backend/apps/cloud/src/project/project.controller.ts
index 3684ab331..19383281f 100644
--- a/backend/apps/cloud/src/project/project.controller.ts
+++ b/backend/apps/cloud/src/project/project.controller.ts
@@ -3,7 +3,6 @@ import {
Body,
Query,
Param,
- UseGuards,
Get,
Post,
Put,
@@ -48,7 +47,6 @@ import _find from 'lodash/find'
import dayjs from 'dayjs'
import { hash } from 'bcrypt'
-import { JwtAccessTokenGuard } from '../auth/guards'
import { Auth, Public } from '../auth/decorators'
import { isValidDate } from '../analytics/analytics.service'
import {
@@ -58,13 +56,11 @@ import {
LEGAL_PID_CHARACTERS,
PID_LENGTH,
} from './project.service'
-import { UserType, PlanCode } from '../user/entities/user.entity'
+import { PlanCode } from '../user/entities/user.entity'
import { ActionTokenType } from '../action-tokens/action-token.entity'
import { ActionTokensService } from '../action-tokens/action-tokens.service'
import { MailerService } from '../mailer/mailer.service'
import { LetterTemplate } from '../mailer/letter'
-import { Roles } from '../auth/decorators/roles.decorator'
-import { RolesGuard } from '../auth/guards/roles.guard'
import { Pagination } from '../common/pagination/pagination'
import { Project } from './entity/project.entity'
import { ProjectShare, roles } from './entity/project-share.entity'
@@ -163,7 +159,7 @@ export class ProjectController {
type: String,
})
@ApiResponse({ status: 200, type: [Project] })
- @Auth([], true)
+ @Auth(true)
async get(
@CurrentUserId() userId: string,
@Query('take', new ParseIntPipe({ optional: true })) take?: number,
@@ -255,7 +251,7 @@ export class ProjectController {
@ApiQuery({ name: 'skip', required: false })
@ApiQuery({ name: 'search', required: false, type: String })
@ApiResponse({ status: 200, type: [Project] })
- @Auth([], true)
+ @Auth(true)
async getAvailableProjectsForOrganization(
@CurrentUserId() userId: string,
@Query('take', new ParseIntPipe({ optional: true })) take?: number,
@@ -276,66 +272,10 @@ export class ProjectController {
return paginated
}
- @ApiBearerAuth()
- @Post('/admin/:id')
- @ApiResponse({ status: 201, type: Project })
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.ADMIN)
- async createForAdmin(
- @Param('id') userId: string,
- @Body() projectDTO: ProjectDTO,
- ): Promise<Project> {
- this.logger.log({ userId, projectDTO }, 'POST /project/admin/:id')
-
- const user = await this.userService.findOne({
- where: { id: userId },
- relations: ['projects'],
- })
- const { maxProjects = PROJECTS_MAXIMUM } = user
-
- if (!user.isActive) {
- throw new ForbiddenException(
- "User's email address has to be verified first",
- )
- }
-
- if (_size(user.projects) >= maxProjects) {
- throw new ForbiddenException(
- `The user's plan supports maximum of ${maxProjects} projects`,
- )
- }
-
- this.projectService.validateProject(projectDTO)
- await this.projectService.checkIfIDUnique(projectDTO.id)
-
- try {
- const project = new Project()
- Object.assign(project, projectDTO)
- project.origins = _map(projectDTO.origins, _trim) as string[]
-
- const newProject = await this.projectService.create(project)
- user.projects.push(project)
-
- await this.userService.create(user)
-
- return newProject
- } catch (e) {
- if (e.code === 'ER_DUP_ENTRY') {
- if (e.sqlMessage.includes(projectDTO.id)) {
- throw new BadRequestException(
- 'Project with selected ID already exists',
- )
- }
- }
-
- throw new BadRequestException(e)
- }
- }
-
@ApiBearerAuth()
@Post('/')
@ApiResponse({ status: 201, type: Project })
- @Auth([], true)
+ @Auth(true)
async create(
@Body() projectDTO: CreateProjectDTO,
@CurrentUserId() userId: string,
@@ -468,7 +408,7 @@ export class ProjectController {
@Post('/funnel')
@ApiResponse({ status: 201 })
- @Auth([], true)
+ @Auth(true)
async createFunnel(
@Body() funnelDTO: FunnelCreateDTO,
@CurrentUserId() userId: string,
@@ -518,7 +458,7 @@ export class ProjectController {
@Patch('/funnel')
@ApiResponse({ status: 200 })
- @Auth([], true)
+ @Auth(true)
async updateFunnel(
@Body() funnelDTO: FunnelUpdateDTO,
@CurrentUserId() userId: string,
@@ -588,7 +528,7 @@ export class ProjectController {
@Delete('/funnel/:id/:pid')
@ApiResponse({ status: 200 })
- @Auth([], true)
+ @Auth(true)
async deleteFunnel(
@Param('id') id: string,
@Param('pid') pid: string,
@@ -619,7 +559,7 @@ export class ProjectController {
@Get('/funnels/:pid')
@ApiResponse({ status: 200 })
- @Auth([], true)
+ @Auth(true)
async getFunnels(
@Param('pid') pid: string,
@CurrentUserId() userId: string,
@@ -645,8 +585,7 @@ export class ProjectController {
@ApiBearerAuth()
@Delete('/reset/:id')
@HttpCode(204)
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
+ @Auth()
@ApiResponse({ status: 204, description: 'Empty body' })
async reset(
@Param('id') id: string,
@@ -695,8 +634,7 @@ export class ProjectController {
@ApiBearerAuth()
@Post('/secret-gen/:pid')
@HttpCode(200)
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
+ @Auth()
@ApiResponse({ status: 200, description: 'A regenerated CAPTCHA secret key' })
async secretGen(
@Param('pid') pid: string,
@@ -745,8 +683,8 @@ export class ProjectController {
type: 'string',
})
@ApiResponse({ status: 200 })
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Auth([UserType.ADMIN, UserType.CUSTOMER])
+ @Auth()
+ @Auth()
async deletePartially(
@Param('pid') pid: string,
@Query('from') from: string,
@@ -789,9 +727,8 @@ export class ProjectController {
@ApiBearerAuth()
@Post('organisation/:orgId')
@HttpCode(200)
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
- @Auth([], true)
+ @Auth()
+ @Auth(true)
async addProject(
@Param('orgId') orgId: string,
@Body() addProjectDTO: ProjectIdDto,
@@ -824,9 +761,8 @@ export class ProjectController {
@ApiBearerAuth()
@Delete('organisation/:orgId/:projectId')
@HttpCode(204)
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
- @Auth([], true)
+ @Auth()
+ @Auth(true)
async removeProject(
@Param('orgId') orgId: string,
@Param('projectId') projectId: string,
@@ -858,8 +794,8 @@ export class ProjectController {
@Delete('/reset-filters/:pid')
@ApiResponse({ status: 200 })
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Auth([UserType.ADMIN, UserType.CUSTOMER])
+ @Auth()
+ @Auth()
async resetFilters(
@Param('pid') pid: string,
@Query('type') type: string,
@@ -890,8 +826,7 @@ export class ProjectController {
@ApiBearerAuth()
@Post('/:pid/share')
@HttpCode(200)
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
+ @Auth()
@ApiResponse({ status: 200, type: Project })
async share(
@Param('pid') pid: string,
@@ -1012,8 +947,7 @@ export class ProjectController {
@ApiBearerAuth()
@Put('/share/:shareId')
@HttpCode(200)
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
+ @Auth()
@ApiResponse({ status: 200, type: Project })
async updateShare(
@Param('shareId') shareId: string,
@@ -1066,8 +1000,6 @@ export class ProjectController {
@ApiBearerAuth()
@HttpCode(204)
- // @UseGuards(JwtAccessTokenGuard, RolesGuard)
- // @Roles(UserType.CUSTOMER, UserType.ADMIN)
@Public()
@ApiResponse({ status: 204, description: 'Empty body' })
@Get('/share/:id')
@@ -1103,7 +1035,7 @@ export class ProjectController {
}
@Post('transfer')
- @Auth([UserType.ADMIN, UserType.CUSTOMER])
+ @Auth()
async transferProject(
@Body() body: TransferProjectBodyDto,
@CurrentUserId() userId: string,
@@ -1182,7 +1114,7 @@ export class ProjectController {
}
@Delete('transfer')
- @Auth([UserType.ADMIN, UserType.CUSTOMER])
+ @Auth()
async cancelTransferProject(
@Query() queries: CancelTransferProjectQueriesDto,
) {
@@ -1211,7 +1143,7 @@ export class ProjectController {
}
@Delete(':projectId/subscribers/:subscriberId')
- @Auth([UserType.ADMIN, UserType.CUSTOMER])
+ @Auth()
async removeSubscriber(
@Param() params: RemoveSubscriberParamsDto,
@CurrentUserId() userId: string,
@@ -1250,7 +1182,7 @@ export class ProjectController {
}
@Post(':projectId/subscribers')
- @Auth([UserType.ADMIN, UserType.CUSTOMER])
+ @Auth()
async addSubscriber(
@Param() params: AddSubscriberParamsDto,
@Body() body: AddSubscriberBodyDto,
@@ -1310,7 +1242,7 @@ export class ProjectController {
}
@Get('password/:projectId')
- @Auth([], true, true)
+ @Auth(true, true)
@ApiResponse({ status: 200, type: Project })
async checkPassword(
@Param('projectId') projectId: string,
@@ -1382,7 +1314,7 @@ export class ProjectController {
}
@Get(':projectId/subscribers')
- @Auth([UserType.ADMIN, UserType.CUSTOMER])
+ @Auth()
async getSubscribers(
@Param() params: GetSubscribersParamsDto,
@Query() queries: GetSubscribersQueriesDto,
@@ -1402,7 +1334,7 @@ export class ProjectController {
}
@Patch(':projectId/subscribers/:subscriberId')
- @Auth([UserType.ADMIN, UserType.CUSTOMER])
+ @Auth()
async updateSubscriber(
@Param() params: UpdateSubscriberParamsDto,
@Body() body: UpdateSubscriberBodyDto,
@@ -1444,7 +1376,7 @@ export class ProjectController {
@Delete('/:id')
@HttpCode(204)
- @Auth([], true)
+ @Auth(true)
@ApiResponse({ status: 204, description: 'Empty body' })
async delete(
@Param('id') id: string,
@@ -1601,7 +1533,7 @@ export class ProjectController {
@ApiBearerAuth()
@Patch('/:id/organisation')
@HttpCode(204)
- @Auth([], true)
+ @Auth(true)
async updateOrganisation(
@Param('id') id: string,
@Body() body: ProjectOrganisationDto,
@@ -1642,7 +1574,7 @@ export class ProjectController {
@ApiBearerAuth()
@Put('/:id')
@HttpCode(200)
- @Auth([], true)
+ @Auth(true)
@ApiResponse({ status: 200, type: Project })
async update(
@Param('id') id: string,
@@ -1724,8 +1656,7 @@ export class ProjectController {
@ApiBearerAuth()
@Delete('/:pid/:shareId')
@HttpCode(204)
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
+ @Auth()
@ApiResponse({ status: 204, description: 'Empty body' })
async deleteShare(
@Param('pid') pid: string,
@@ -1756,7 +1687,7 @@ export class ProjectController {
@ApiBearerAuth()
@Get('/:id')
- @Auth([], true, true)
+ @Auth(true, true)
@ApiResponse({ status: 200, type: Project })
async getOne(
@Param('id') id: string,
@@ -1847,7 +1778,7 @@ export class ProjectController {
@ApiOkResponse({ type: ProjectViewEntity })
@ApiBearerAuth()
@Get(':projectId/views/:viewId')
- @Auth([], true, true)
+ @Auth(true, true)
async getProjectView(
@Param() params: ProjectViewIdsDto,
@CurrentUserId() userId: string,
@@ -1871,8 +1802,7 @@ export class ProjectController {
@ApiOkResponse({ type: ProjectViewEntity })
@ApiBearerAuth()
@Post(':projectId/views')
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
+ @Auth()
async createProjectView(
@Param() params: ProjectIdDto,
@Body() body: CreateProjectViewDto,
@@ -1911,7 +1841,7 @@ export class ProjectController {
@ApiOkResponse({ type: ProjectViewEntity })
@ApiBearerAuth()
@Get(':projectId/views')
- @Auth([], true, true)
+ @Auth(true, true)
async getProjectViews(
@Param() params: ProjectIdDto,
@CurrentUserId() userId: string,
@@ -1932,8 +1862,7 @@ export class ProjectController {
@ApiOkResponse({ type: ProjectViewEntity })
@ApiBearerAuth()
@Patch(':projectId/views/:viewId')
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
+ @Auth()
async updateProjectView(
@Param() params: ProjectViewIdsDto,
@Body() body: UpdateProjectViewDto,
@@ -1980,8 +1909,7 @@ export class ProjectController {
@ApiBearerAuth()
@HttpCode(HttpStatus.NO_CONTENT)
@Delete(':projectId/views/:viewId')
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
+ @Auth()
async deleteProjectView(
@Param() params: ProjectViewIdsDto,
@CurrentUserId() userId: string,
diff --git a/backend/apps/cloud/src/twoFactorAuth/twoFactorAuth.controller.ts b/backend/apps/cloud/src/twoFactorAuth/twoFactorAuth.controller.ts
index 1acc2e2eb..09f34fd4c 100644
--- a/backend/apps/cloud/src/twoFactorAuth/twoFactorAuth.controller.ts
+++ b/backend/apps/cloud/src/twoFactorAuth/twoFactorAuth.controller.ts
@@ -1,7 +1,6 @@
import {
Controller,
Post,
- UseGuards,
HttpCode,
Body,
BadRequestException,
@@ -10,16 +9,14 @@ import {
} from '@nestjs/common'
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger'
-import { JwtAccessTokenGuard } from '../auth/guards'
+import { Auth } from '../auth/decorators'
import { TwoFactorAuthService } from './twoFactorAuth.service'
import { UserService } from '../user/user.service'
import { AuthService } from '../auth/auth.service'
-import { UserType } from '../user/entities/user.entity'
import { AppLoggerService } from '../logger/logger.service'
import { MailerService } from '../mailer/mailer.service'
import { LetterTemplate } from '../mailer/letter'
-import { TwoFaNotRequired, Roles, CurrentUserId } from '../auth/decorators'
-import { RolesGuard } from '../auth/guards/roles.guard'
+import { TwoFaNotRequired, CurrentUserId } from '../auth/decorators'
import { TwoFactorAuthDTO } from './dto/2fa-auth.dto'
import {
generateRecoveryCode,
@@ -40,8 +37,7 @@ export class TwoFactorAuthController {
@ApiBearerAuth()
@Post('generate')
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
+ @Auth()
@TwoFaNotRequired()
async register(@CurrentUserId() id: string) {
const user = await this.userService.findOne({ where: { id } })
@@ -51,8 +47,7 @@ export class TwoFactorAuthController {
@ApiBearerAuth()
@Post('enable')
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
+ @Auth()
@TwoFaNotRequired()
async turnOnTwoFactorAuthentication(
@Body() body: TwoFactorAuthDTO,
@@ -101,8 +96,7 @@ export class TwoFactorAuthController {
@ApiBearerAuth()
@Post('disable')
@HttpCode(200)
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
+ @Auth()
async turnOffTwoFactorAuthentication(
@Body() body: TwoFactorAuthDTO,
@CurrentUserId() id: string,
@@ -141,8 +135,7 @@ export class TwoFactorAuthController {
@ApiBearerAuth()
@Post('authenticate')
@HttpCode(200)
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
+ @Auth()
@TwoFaNotRequired()
async authenticate(
@Body() body: TwoFactorAuthDTO,
diff --git a/backend/apps/cloud/src/user/dto/admin-update-user.dto.ts b/backend/apps/cloud/src/user/dto/admin-update-user.dto.ts
deleted file mode 100644
index e9f047cd9..000000000
--- a/backend/apps/cloud/src/user/dto/admin-update-user.dto.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-import { ApiProperty } from '@nestjs/swagger'
-import { IsEmail } from 'class-validator'
-
-export class AdminUpdateUserProfileDTO {
- @ApiProperty({ example: '[email protected]', required: true })
- @IsEmail()
- email: string
-
- @ApiProperty({ example: 'your_password123' })
- password: string
-
- @ApiProperty({ example: true })
- isActive: boolean
-
- @ApiProperty({ example: 'free' })
- planCode: string
-
- @ApiProperty({ example: 'customer' })
- roles: Array<string>
-
- @ApiProperty({ example: 'date' })
- created: string
-
- @ApiProperty({ example: 'Number' })
- emailRequests: number
-
- @ApiProperty({ example: 'reportFrequency' })
- reportFrequency: string
-
- @ApiProperty({ example: 'updated' })
- updated: string
-
- @ApiProperty({ example: 'Europe/Kiev' })
- timezone: string
-
- @ApiProperty({ example: '1234567890' })
- telegramChatId: string | null
-}
diff --git a/backend/apps/cloud/src/user/user.controller.ts b/backend/apps/cloud/src/user/user.controller.ts
index f1d6aa0c1..91b642f8f 100644
--- a/backend/apps/cloud/src/user/user.controller.ts
+++ b/backend/apps/cloud/src/user/user.controller.ts
@@ -1,6 +1,5 @@
import {
Controller,
- Query,
Req,
Body,
Param,
@@ -17,10 +16,9 @@ import {
Ip,
Patch,
NotFoundException,
- ParseIntPipe,
} from '@nestjs/common'
import { Request } from 'express'
-import { ApiTags, ApiQuery, ApiResponse, ApiBearerAuth } from '@nestjs/swagger'
+import { ApiTags, ApiResponse, ApiBearerAuth } from '@nestjs/swagger'
import dayjs from 'dayjs'
import utc from 'dayjs/plugin/utc'
import _map from 'lodash/map'
@@ -36,32 +34,28 @@ import { HttpService } from '@nestjs/axios'
import { catchError, firstValueFrom, map, of } from 'rxjs'
import { Markup } from 'telegraf'
-import { JwtAccessTokenGuard } from '../auth/guards'
-import { Public, Roles, CurrentUserId, Auth } from '../auth/decorators'
+import { Public, CurrentUserId, Auth } from '../auth/decorators'
import { TelegramService } from '../integrations/telegram/telegram.service'
import { UserService } from './user.service'
import { ProjectService, deleteProjectRedis } from '../project/project.service'
import {
User,
- UserType,
MAX_EMAIL_REQUESTS,
PlanCode,
Theme,
FeatureFlag,
OnboardingStep,
} from './entities/user.entity'
-import { Pagination } from '../common/pagination/pagination'
import {
GDPR_EXPORT_TIMEFRAME,
isDevelopment,
PRODUCTION_ORIGIN,
} from '../common/constants'
import { clickhouse } from '../common/integrations/clickhouse'
-import { RolesGuard } from '../auth/guards/roles.guard'
+import { AuthenticationGuard } from '../auth/guards/authentication.guard'
import { UpdateUserProfileDTO } from './dto/update-user.dto'
import { IChangePlanDTO } from './dto/change-plan.dto'
-import { AdminUpdateUserProfileDTO } from './dto/admin-update-user.dto'
import { SetShowLiveVisitorsDTO } from './dto/set-show-live-visitors.dto'
import { ActionTokensService } from '../action-tokens/action-tokens.service'
import { MailerService } from '../mailer/mailer.service'
@@ -69,7 +63,6 @@ import { ActionTokenType } from '../action-tokens/action-token.entity'
import { AuthService } from '../auth/auth.service'
import { LetterTemplate } from '../mailer/letter'
import { AppLoggerService } from '../logger/logger.service'
-import { UserProfileDTO } from './dto/user.dto'
import { DeleteSelfDTO } from './dto/delete-self.dto'
import {
checkRateLimit,
@@ -87,7 +80,7 @@ const UNPAID_PLANS = [PlanCode.free, PlanCode.trial, PlanCode.none]
@ApiTags('User')
@Controller('user')
-@UseGuards(JwtAccessTokenGuard, RolesGuard)
+@Auth()
export class UserController {
constructor(
private readonly userService: UserService,
@@ -103,8 +96,7 @@ export class UserController {
@ApiBearerAuth()
@Get('/me')
- @UseGuards(RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
+ @UseGuards(AuthenticationGuard)
async me(@CurrentUserId() uid: string) {
this.logger.log({ uid }, 'GET /user/me')
@@ -127,24 +119,8 @@ export class UserController {
}
}
- @ApiBearerAuth()
- @Get('/')
- @ApiQuery({ name: 'take', required: false })
- @ApiQuery({ name: 'skip', required: false })
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.ADMIN)
- async get(
- @Query('take', new ParseIntPipe({ optional: true })) take?: number,
- @Query('skip', new ParseIntPipe({ optional: true })) skip?: number,
- ): Promise<Pagination<User> | User[]> {
- this.logger.log({ take, skip }, 'GET /user')
- return this.userService.paginate({ take, skip })
- }
-
@ApiBearerAuth()
@Put('/theme')
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
async setTheme(
@CurrentUserId() userId: string,
@Body('theme') theme: Theme,
@@ -154,8 +130,6 @@ export class UserController {
@ApiBearerAuth()
@Put('/feature-flags')
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
async setFeatureFlags(
@CurrentUserId() userId: string,
@Body('featureFlags') featureFlags: FeatureFlag[],
@@ -165,8 +139,6 @@ export class UserController {
@ApiBearerAuth()
@Put('/live-visitors')
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
async setShowLiveVisitors(
@CurrentUserId() userId: string,
@Body() body: SetShowLiveVisitorsDTO,
@@ -180,45 +152,8 @@ export class UserController {
}
}
- @ApiBearerAuth()
- @Get('/search')
- @ApiQuery({ name: 'query', required: false })
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.ADMIN)
- async searchUsers(
- @Query('query') query: string | undefined,
- ): Promise<User[]> {
- this.logger.log({ query }, 'GET /user/search')
- return this.userService.search(query)
- }
-
- @ApiBearerAuth()
- @Post('/')
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.ADMIN)
- async create(@Body() userDTO: UserProfileDTO): Promise<User | null> {
- this.logger.log({ userDTO }, 'POST /user')
- this.userService.validatePassword(userDTO.password)
- userDTO.password = await this.authService.hashPassword(userDTO.password)
-
- try {
- const user = await this.userService.create({ ...userDTO, isActive: true })
- return user
- } catch (e) {
- if (e.code === 'ER_DUP_ENTRY') {
- if (e.sqlMessage.includes(userDTO.email)) {
- throw new BadRequestException('User with this email already exists')
- }
- }
- }
-
- return null
- }
-
@ApiBearerAuth()
@Post('/recieve-login-notifications')
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
async receiveLoginNotifications(
@CurrentUserId() userId: string,
@Body('receiveLoginNotifications') receiveLoginNotifications: boolean,
@@ -233,8 +168,6 @@ export class UserController {
@ApiBearerAuth()
@Patch('/set-paypal-email')
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
async setPaypalEmail(
@CurrentUserId() userId: string,
@Body('paypalPaymentsEmail') paypalPaymentsEmail: string,
@@ -269,8 +202,6 @@ export class UserController {
@ApiBearerAuth()
@Post('/api-key')
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
async generateApiKey(
@CurrentUserId() userId: string,
@Headers() headers,
@@ -299,8 +230,6 @@ export class UserController {
@ApiBearerAuth()
@Delete('/api-key')
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
async deleteApiKey(@CurrentUserId() userId: string): Promise<void> {
this.logger.log({ userId }, 'DELETE /user/api-key')
@@ -313,77 +242,9 @@ export class UserController {
await this.userService.update(userId, { apiKey: null })
}
- @ApiBearerAuth()
- @Delete('/:id')
- @HttpCode(204)
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.ADMIN)
- async delete(
- @Param('id') id: string,
- @CurrentUserId() uid: string,
- ): Promise<any> {
- this.logger.log({ id, uid }, 'DELETE /user/:id')
- const user = await this.userService.findOne({
- where: { id },
- relations: ['projects'],
- select: ['id', 'planCode'],
- })
-
- if (_isEmpty(user)) {
- throw new BadRequestException(`User with id ${id} does not exist`)
- }
-
- if (!_includes(UNPAID_PLANS, user.planCode)) {
- throw new BadRequestException('cancelSubFirst')
- }
-
- try {
- if (!_isEmpty(user.projects)) {
- const pids = _join(
- _map(user.projects, el => `'${el.id}'`),
- ',',
- )
-
- const queries = [
- `ALTER TABLE analytics DELETE WHERE pid IN (${pids})`,
- `ALTER TABLE customEV DELETE WHERE pid IN (${pids})`,
- `ALTER TABLE performance DELETE WHERE pid IN (${pids})`,
- `ALTER TABLE errors DELETE WHERE pid IN (${pids})`,
- `ALTER TABLE error_statuses DELETE WHERE pid IN (${pids})`,
- `ALTER TABLE captcha DELETE WHERE pid IN (${pids})`,
- ]
-
- await this.projectService.deleteMultiple(user.projects.map(el => el.id))
-
- const promises = _map(queries, async query =>
- clickhouse.command({
- query,
- }),
- )
- await Promise.all(promises)
- }
- await this.actionTokensService.deleteMultiple(`userId="${id}"`)
- await this.userService.deleteAllRefreshTokens(id)
- await this.projectService.deleteMultipleShare(`userId="${id}"`)
- await this.organisationService.deleteMemberships({
- user: {
- id,
- },
- })
- await this.userService.delete(id)
-
- return 'accountDeleted'
- } catch (e) {
- this.logger.error(e)
- throw new BadRequestException('accountDeleteError')
- }
- }
-
@ApiBearerAuth()
@Delete('/')
@HttpCode(204)
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
async deleteSelf(
@CurrentUserId() id: string,
@Body() deleteSelfDTO: DeleteSelfDTO,
@@ -456,8 +317,6 @@ export class UserController {
@ApiBearerAuth()
@Delete('/share/:actionId')
@HttpCode(204)
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
@ApiResponse({ status: 204, description: 'Empty body' })
async deleteShare(
@Param('actionId') actionId: string,
@@ -501,8 +360,6 @@ export class UserController {
@ApiBearerAuth()
@Get('/share/:actionId')
@HttpCode(204)
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
@ApiResponse({ status: 204, description: 'Empty body' })
async acceptShare(
@Param('actionId') actionId: string,
@@ -548,8 +405,6 @@ export class UserController {
@ApiBearerAuth()
@Delete('/organisation/:actionId')
@HttpCode(204)
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
@ApiResponse({ status: 204, description: 'Empty body' })
async rejectOrganisationInvitation(
@Param('actionId') actionId: string,
@@ -598,8 +453,6 @@ export class UserController {
@ApiBearerAuth()
@Post('/organisation/:actionId')
@HttpCode(204)
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Auth([], true)
@ApiResponse({ status: 204, description: 'Empty body' })
async acceptOrganisationInvitation(
@Param('actionId') actionId: string,
@@ -656,8 +509,6 @@ export class UserController {
@ApiBearerAuth()
@Post('/confirm_email')
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
async sendEmailConfirmation(
@CurrentUserId() id: string,
@Req() request: Request,
@@ -690,46 +541,8 @@ export class UserController {
return true
}
- @ApiBearerAuth()
- @Put('/:id')
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.ADMIN)
- async update(
- @Body() userDTO: AdminUpdateUserProfileDTO,
- @Param('id') id: string,
- ): Promise<Partial<User>> {
- this.logger.log({ userDTO, id }, 'PUT /user/:id')
-
- if (userDTO.password) {
- this.userService.validatePassword(userDTO.password)
- userDTO.password = await this.authService.hashPassword(userDTO.password)
- }
-
- const user = await this.userService.findOne({ where: { id } })
-
- try {
- if (!user) {
- await this.userService.create({ ...userDTO })
- }
- await this.userService.update(id, { ...user, ...userDTO })
- // omit sensitive data before returning using this.userService.omitSensitiveData function
- return this.userService.omitSensitiveData(
- await this.userService.findOne({ where: { id } }),
- )
- } catch (e) {
- if (e.code === 'ER_DUP_ENTRY') {
- if (e.sqlMessage.includes(userDTO.email)) {
- throw new BadRequestException('User with this email already exists')
- }
- }
- throw new BadRequestException(e.message)
- }
- }
-
@ApiBearerAuth()
@Delete('/tg/:id')
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
@HttpCode(204)
async deleteTelegramConnection(
@Param('id') tgID: string,
@@ -749,8 +562,6 @@ export class UserController {
@ApiBearerAuth()
@Put('/')
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
async updateCurrentUser(
@Body() userDTO: UpdateUserProfileDTO,
@CurrentUserId() id: string,
@@ -922,8 +733,6 @@ export class UserController {
@ApiBearerAuth()
@Get('referrals')
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
async getReferralsList(@CurrentUserId() id: string): Promise<any> {
this.logger.log({ id }, 'GET /user/referrals')
@@ -938,8 +747,6 @@ export class UserController {
@ApiBearerAuth()
@Get('payouts/info')
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
async getPayoutsInfo(@CurrentUserId() id: string): Promise<any> {
this.logger.log({ id }, 'GET /user/payouts/info')
@@ -954,8 +761,6 @@ export class UserController {
@ApiBearerAuth()
@Post('generate-ref-code')
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
async generateRefCode(@CurrentUserId() id: string): Promise<any> {
this.logger.log({ id }, 'POST /user/generate-ref-code')
@@ -984,8 +789,6 @@ export class UserController {
@ApiBearerAuth()
@Get('/export')
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
async exportUserData(@CurrentUserId() user_id: string): Promise<User> {
this.logger.log({ user_id }, 'GET /user/export')
const user = await this.userService.findOne({ where: { id: user_id } })
@@ -1090,8 +893,6 @@ export class UserController {
@ApiBearerAuth()
@Post('change-plan')
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
async changePlan(
@CurrentUserId() id: string,
@Body() body: IChangePlanDTO,
@@ -1105,8 +906,6 @@ export class UserController {
@ApiBearerAuth()
@Post('preview-plan')
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
async previewPlan(
@CurrentUserId() id: string,
@Body() body: IChangePlanDTO,
@@ -1147,8 +946,6 @@ export class UserController {
@ApiBearerAuth()
@Post('onboarding/step')
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
@ApiResponse({ status: 204 })
async updateOnboardingStep(
@CurrentUserId() userId: string,
@@ -1167,8 +964,6 @@ export class UserController {
@ApiBearerAuth()
@Post('onboarding/complete')
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
@ApiResponse({ status: 204 })
async completeOnboarding(@CurrentUserId() userId: string): Promise<void> {
this.logger.log({ userId }, 'POST /user/onboarding/complete')
diff --git a/backend/apps/community/src/analytics/analytics.controller.ts b/backend/apps/community/src/analytics/analytics.controller.ts
index f92dbc76f..1beb8f056 100644
--- a/backend/apps/community/src/analytics/analytics.controller.ts
+++ b/backend/apps/community/src/analytics/analytics.controller.ts
@@ -36,7 +36,7 @@ import {
import { VALID_PERIODS } from './decorators/validate-period.decorator'
import { CurrentUserId } from '../auth/decorators/current-user-id.decorator'
import { DEFAULT_TIMEZONE } from '../user/entities/user.entity'
-import { RolesGuard } from '../auth/guards/roles.guard'
+import { AuthenticationGuard } from '../auth/guards/authentication.guard'
import { PageviewsDto } from './dto/pageviews.dto'
import { EventsDto } from './dto/events.dto'
import { GetDataDto, ChartRenderMode } from './dto/getData.dto'
@@ -171,7 +171,7 @@ const TRANSPARENT_GIF_BUFFER = Buffer.from(
)
@ApiTags('Analytics')
-@UseGuards(OptionalJwtAccessTokenGuard, RolesGuard)
+@UseGuards(OptionalJwtAccessTokenGuard, AuthenticationGuard)
@UsePipes(
new ValidationPipe({
transform: true,
@@ -185,7 +185,7 @@ export class AnalyticsController {
) {}
@Get()
- @Auth([], true, true)
+ @Auth(true, true)
async getData(
@Query() data: GetDataDto,
@CurrentUserId() uid: string,
@@ -318,7 +318,7 @@ export class AnalyticsController {
}
@Get('funnel')
- @Auth([], true, true)
+ @Auth(true, true)
async getFunnel(
@Query() data: GetFunnelsDto,
@CurrentUserId() uid: string,
@@ -391,7 +391,7 @@ export class AnalyticsController {
}
@Get('meta')
- @Auth([], true, true)
+ @Auth(true, true)
async getCustomEventMetadata(
@Query() data: GetCustomEventMetadata,
@CurrentUserId() uid: string,
@@ -409,7 +409,7 @@ export class AnalyticsController {
}
@Get('property')
- @Auth([], true, true)
+ @Auth(true, true)
async getPagePropertyMetadata(
@Query() data: GetPagePropertyMetaDto,
@CurrentUserId() uid: string,
@@ -427,7 +427,7 @@ export class AnalyticsController {
}
@Get('filters')
- @Auth([], true, true)
+ @Auth(true, true)
async getFilters(
@Query() data: GetFiltersDto,
@CurrentUserId() uid: string,
@@ -445,7 +445,7 @@ export class AnalyticsController {
}
@Get('chart')
- @Auth([], true, true)
+ @Auth(true, true)
async getChartData(
@Query() data: GetDataDto,
@CurrentUserId() uid: string,
@@ -496,7 +496,7 @@ export class AnalyticsController {
}
@Get('performance')
- @Auth([], true, true)
+ @Auth(true, true)
async getPerfData(
@Query() data: GetDataDto & { measure: PerfMeasure },
@CurrentUserId() uid: string,
@@ -575,7 +575,7 @@ export class AnalyticsController {
}
@Get('performance/chart')
- @Auth([], true, true)
+ @Auth(true, true)
async getPerfChartData(
@Query() data: GetDataDto & { measure: PerfMeasure },
@CurrentUserId() uid: string,
@@ -627,7 +627,7 @@ export class AnalyticsController {
}
@Get('user-flow')
- @Auth([], true, true)
+ @Auth(true, true)
async getUserFlow(
@Query() data: GetUserFlowDto,
@CurrentUserId() uid: string,
@@ -673,7 +673,7 @@ export class AnalyticsController {
}
@Get('birdseye')
- @Auth([], true, true)
+ @Auth(true, true)
// returns overall short statistics per project
async getOverallStats(
@Query() data: GetOverallStatsDto,
@@ -714,7 +714,7 @@ export class AnalyticsController {
}
@Get('performance/birdseye')
- @Auth([], true, true)
+ @Auth(true, true)
async getPerformanceOverallStats(
@Query() data: GetOverallStatsDto & { measure: PerfMeasure },
@CurrentUserId() uid: string,
@@ -796,7 +796,7 @@ export class AnalyticsController {
}
@Get('live-visitors')
- @Auth([], true, true)
+ @Auth(true, true)
async getLiveVisitors(
@Query() queryParams: LiveVisitorsDto,
@CurrentUserId() uid: string,
@@ -954,7 +954,7 @@ export class AnalyticsController {
}
@Post('hb')
- @Auth([], true, true)
+ @Auth(true, true)
async heartbeat(
@Body() logDTO: PageviewsDto,
@Headers() headers,
@@ -1188,7 +1188,7 @@ export class AnalyticsController {
}
@Get('sessions')
- @Auth([], true, true)
+ @Auth(true, true)
async getSessions(
@Query() data: GetSessionsDto,
@CurrentUserId() uid: string,
@@ -1261,7 +1261,7 @@ export class AnalyticsController {
}
@Get('session')
- @Auth([], true, true)
+ @Auth(true, true)
async getSession(
@Query() data: GetSessionDto,
@CurrentUserId() uid: string,
@@ -1291,7 +1291,7 @@ export class AnalyticsController {
}
@Get('custom-events')
- @Auth([], true, true)
+ @Auth(true, true)
async getCustomEvents(
@Query() data: GetCustomEventsDto,
@CurrentUserId() uid: string,
@@ -1383,7 +1383,7 @@ export class AnalyticsController {
}
@Get('errors-filters')
- @Auth([], true, true)
+ @Auth(true, true)
async getErrorsFilters(
@Query() data: GetFiltersDto,
@CurrentUserId() uid: string,
@@ -1475,7 +1475,7 @@ export class AnalyticsController {
// Update error(s) status
@Patch('error-status')
- @Auth([], true, true)
+ @Auth(true, true)
async patchStatus(
@Body() statusDTO: PatchStatusDto,
@CurrentUserId() uid: string,
@@ -1501,7 +1501,7 @@ export class AnalyticsController {
}
@Get('errors')
- @Auth([], true, true)
+ @Auth(true, true)
async getErrors(
@Query() data: GetErrorsDto,
@CurrentUserId() uid: string,
@@ -1582,7 +1582,7 @@ export class AnalyticsController {
}
@Get('get-error')
- @Auth([], true, true)
+ @Auth(true, true)
async getError(
@Query() data: GetErrorDto,
@CurrentUserId() uid: string,
diff --git a/backend/apps/community/src/auth/auth.controller.ts b/backend/apps/community/src/auth/auth.controller.ts
index fd8217000..b0d5c227a 100644
--- a/backend/apps/community/src/auth/auth.controller.ts
+++ b/backend/apps/community/src/auth/auth.controller.ts
@@ -30,7 +30,7 @@ import { Response } from 'express'
import { checkRateLimit, getIPFromHeaders } from '../common/utils'
import { AuthService } from './auth.service'
-import { Public, CurrentUserId, CurrentUser, Roles } from './decorators'
+import { Public, CurrentUserId, CurrentUser, Auth } from './decorators'
import {
LoginResponseDto,
LoginRequestDto,
@@ -45,8 +45,7 @@ import {
ConfirmResetPasswordDto,
ResetPasswordDto,
} from './dtos'
-import { JwtAccessTokenGuard, JwtRefreshTokenGuard, RolesGuard } from './guards'
-import { UserType } from '../user/entities/user.entity'
+import { JwtAccessTokenGuard, JwtRefreshTokenGuard } from './guards'
import { LetterTemplate } from '../mailer/letter'
import { MailerService } from '../mailer/mailer.service'
import { redis } from '../common/constants'
@@ -173,8 +172,7 @@ export class AuthController {
@ApiOkResponse({
description: 'Change email requested',
})
- @UseGuards(RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
+ @Auth()
@Post('change-email')
public async requestChangeEmail(
@Body() body: RequestChangeEmailDto,
diff --git a/backend/apps/community/src/auth/decorators/auth.decorator.ts b/backend/apps/community/src/auth/decorators/auth.decorator.ts
index b08e90931..62796598e 100644
--- a/backend/apps/community/src/auth/decorators/auth.decorator.ts
+++ b/backend/apps/community/src/auth/decorators/auth.decorator.ts
@@ -1,19 +1,16 @@
import { applyDecorators, SetMetadata, UseGuards } from '@nestjs/common'
-import { JwtAccessTokenGuard, MultiAuthGuard, RolesGuard } from '../guards'
-import { UserType } from '../../user/entities/user.entity'
-import { ROLES_KEY } from './roles.decorator'
+import {
+ JwtAccessTokenGuard,
+ MultiAuthGuard,
+ AuthenticationGuard,
+} from '../guards'
export const IS_OPTIONAL_AUTH_KEY = 'isOptionalAuth'
-export function Auth(
- roles: UserType[],
- isApiKeyAuth = false,
- isOptionalAuth = false,
-) {
+export function Auth(isApiKeyAuth = false, isOptionalAuth = false) {
return applyDecorators(
- SetMetadata(ROLES_KEY, roles),
SetMetadata(IS_OPTIONAL_AUTH_KEY, isOptionalAuth),
isApiKeyAuth
- ? UseGuards(MultiAuthGuard, RolesGuard)
- : UseGuards(JwtAccessTokenGuard, RolesGuard),
+ ? UseGuards(MultiAuthGuard, AuthenticationGuard)
+ : UseGuards(JwtAccessTokenGuard, AuthenticationGuard),
)
}
diff --git a/backend/apps/community/src/auth/decorators/index.ts b/backend/apps/community/src/auth/decorators/index.ts
index ad7f2c823..4d9bad96c 100644
--- a/backend/apps/community/src/auth/decorators/index.ts
+++ b/backend/apps/community/src/auth/decorators/index.ts
@@ -1,5 +1,4 @@
export * from './current-user-id.decorator'
export * from './public.decorator'
export * from './current-user.decorator'
-export * from './roles.decorator'
export * from './auth.decorator'
diff --git a/backend/apps/community/src/auth/decorators/roles.decorator.ts b/backend/apps/community/src/auth/decorators/roles.decorator.ts
deleted file mode 100644
index fcbea69e4..000000000
--- a/backend/apps/community/src/auth/decorators/roles.decorator.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-import { SetMetadata } from '@nestjs/common'
-import { UserType } from '../../user/entities/user.entity'
-
-export const ROLES_KEY = 'roles'
-export const Roles = (...roles: UserType[]) => SetMetadata(ROLES_KEY, roles)
diff --git a/backend/apps/community/src/auth/guards/roles.guard.ts b/backend/apps/community/src/auth/guards/authentication.guard.ts
similarity index 74%
rename from backend/apps/community/src/auth/guards/roles.guard.ts
rename to backend/apps/community/src/auth/guards/authentication.guard.ts
index 1a34aab68..f729570e1 100644
--- a/backend/apps/community/src/auth/guards/roles.guard.ts
+++ b/backend/apps/community/src/auth/guards/authentication.guard.ts
@@ -3,22 +3,13 @@ import { Reflector } from '@nestjs/core'
import { ExtractJwt } from 'passport-jwt'
import { verify } from 'jsonwebtoken'
-import { UserType } from '../../user/entities/user.entity'
import { JWT_ACCESS_TOKEN_SECRET } from '../../common/constants'
-import { ROLES_KEY } from '../decorators'
@Injectable()
-export class RolesGuard implements CanActivate {
+export class AuthenticationGuard implements CanActivate {
constructor(private readonly reflector: Reflector) {}
async canActivate(context: ExecutionContext) {
- const roles = this.reflector.get<UserType[]>(
- ROLES_KEY,
- context.getHandler(),
- )
-
- if (!roles || roles.length === 0) return true
-
const request = context.switchToHttp().getRequest()
let token = ''
@@ -29,6 +20,10 @@ export class RolesGuard implements CanActivate {
token = extract(request)
}
+ if (!token) {
+ return true
+ }
+
try {
const decoded: any = verify(token, JWT_ACCESS_TOKEN_SECRET)
diff --git a/backend/apps/community/src/auth/guards/index.ts b/backend/apps/community/src/auth/guards/index.ts
index aa5cbf455..b37644d33 100644
--- a/backend/apps/community/src/auth/guards/index.ts
+++ b/backend/apps/community/src/auth/guards/index.ts
@@ -1,5 +1,5 @@
export * from './jwt-access-token.guard'
export * from './jwt-refresh-token.guard'
-export * from './roles.guard'
+export * from './authentication.guard'
export * from './optional-jwt-access-token.guard'
export * from './multi-auth.guard'
diff --git a/backend/apps/community/src/project/project.controller.ts b/backend/apps/community/src/project/project.controller.ts
index c123005bd..dfd181c23 100644
--- a/backend/apps/community/src/project/project.controller.ts
+++ b/backend/apps/community/src/project/project.controller.ts
@@ -3,7 +3,6 @@ import {
Body,
Query,
Param,
- UseGuards,
Get,
Post,
Put,
@@ -43,7 +42,6 @@ import _includes from 'lodash/includes'
import dayjs from 'dayjs'
import { hash } from 'bcrypt'
-import { JwtAccessTokenGuard } from '../auth/guards'
import { Auth } from '../auth/decorators'
import { isValidDate } from '../analytics/analytics.service'
import {
@@ -52,7 +50,6 @@ import {
ProjectService,
deleteProjectRedis,
} from './project.service'
-import { RolesGuard } from '../auth/guards/roles.guard'
import { Pagination } from '../common/pagination/pagination'
import { Project } from './entity/project.entity'
import { CurrentUserId } from '../auth/decorators/current-user-id.decorator'
@@ -101,8 +98,6 @@ import { ProjectIdDto } from './dto/project-id.dto'
import { CreateProjectViewDto } from './dto/create-project-view.dto'
import { UpdateProjectViewDto } from './dto/update-project-view.dto'
import { UserService } from '../user/user.service'
-import { Roles } from '../auth/decorators/roles.decorator'
-import { UserType } from '../user/entities/user.entity'
import { MailerService } from '../mailer/mailer.service'
import { LetterTemplate } from '../mailer/letter'
@@ -126,7 +121,7 @@ export class ProjectController {
type: String,
})
@ApiResponse({ status: 200, type: [Project] })
- @Auth([], true)
+ @Auth(true)
async get(
@CurrentUserId() userId: string,
@Query('take', new ParseIntPipe({ optional: true })) take?: number,
@@ -295,7 +290,7 @@ export class ProjectController {
}
@Post('transfer')
- @Auth([UserType.ADMIN, UserType.CUSTOMER])
+ @Auth()
async transferProject(
@Body() body: TransferProjectBodyDto,
@CurrentUserId() userId: string,
@@ -331,8 +326,7 @@ export class ProjectController {
@ApiBearerAuth()
@Post('/:pid/share')
@HttpCode(200)
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
+ @Auth()
async share(
@Param('pid') pid: string,
@Body() body: { email: string; role: 'admin' | 'viewer' },
@@ -417,8 +411,7 @@ export class ProjectController {
@ApiBearerAuth()
@Put('/share/:shareId')
@HttpCode(200)
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
+ @Auth()
async updateShare(
@Param('shareId') shareId: string,
@Body() body: { role: 'admin' | 'viewer' },
@@ -453,7 +446,7 @@ export class ProjectController {
@ApiBearerAuth()
@Post('/')
@ApiResponse({ status: 201, type: Project })
- @Auth([], true)
+ @Auth(true)
async create(
@Body() projectDTO: CreateProjectDTO,
@CurrentUserId() userId: string,
@@ -482,7 +475,7 @@ export class ProjectController {
@ApiBearerAuth()
@Delete('/reset/:id')
@HttpCode(204)
- @Auth([], true)
+ @Auth(true)
@ApiResponse({ status: 204, description: 'Empty body' })
async reset(
@Param('id') id: string,
@@ -519,7 +512,7 @@ export class ProjectController {
@Post('/funnel')
@ApiResponse({ status: 201 })
- @Auth([], true)
+ @Auth(true)
async createFunnel(
@Body() funnelDTO: FunnelCreateDTO,
@CurrentUserId() userId: string,
@@ -559,7 +552,7 @@ export class ProjectController {
@Patch('/funnel')
@ApiResponse({ status: 200 })
- @Auth([], true)
+ @Auth(true)
async updateFunnel(
@Body() funnelDTO: FunnelUpdateDTO,
@CurrentUserId() userId: string,
@@ -597,7 +590,7 @@ export class ProjectController {
@Delete('/funnel/:id/:pid')
@ApiResponse({ status: 200 })
- @Auth([], true)
+ @Auth(true)
async deleteFunnel(
@Param('id') id: string,
@Param('pid') pid: string,
@@ -628,7 +621,7 @@ export class ProjectController {
@Get('/funnels/:pid')
@ApiResponse({ status: 200 })
- @Auth([], true)
+ @Auth(true)
async getFunnels(
@Param('pid') pid: string,
@CurrentUserId() userId: string,
@@ -654,7 +647,7 @@ export class ProjectController {
}
@Get('password/:projectId')
- @Auth([], true, true)
+ @Auth(true, true)
@ApiResponse({ status: 200, type: Project })
async checkPassword(
@Param('projectId') projectId: string,
@@ -694,8 +687,8 @@ export class ProjectController {
type: 'string',
})
@ApiResponse({ status: 200 })
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Auth([], true)
+ @Auth()
+ @Auth(true)
async deletePartially(
@Param('pid') pid: string,
@Query('from') from: string,
@@ -737,7 +730,7 @@ export class ProjectController {
@Delete('/:id')
@HttpCode(204)
- @Auth([], true)
+ @Auth(true)
@ApiResponse({ status: 204, description: 'Empty body' })
async delete(
@Param('id') id: string,
@@ -778,7 +771,7 @@ export class ProjectController {
@Put('/:id')
@HttpCode(200)
- @Auth([], true)
+ @Auth(true)
@ApiResponse({ status: 200, type: Project })
async update(
@Param('id') id: string,
@@ -846,7 +839,7 @@ export class ProjectController {
}
@Get('/:id')
- @Auth([], true, true)
+ @Auth(true, true)
@ApiResponse({ status: 200, type: Project })
async getOne(
@Param('id') id: string,
@@ -945,7 +938,7 @@ export class ProjectController {
@ApiOkResponse({ type: ProjectViewEntity })
@ApiBearerAuth()
@Get(':projectId/views/:viewId')
- @Auth([], true, true)
+ @Auth(true, true)
async getProjectView(
@Param() params: ProjectViewIdsDto,
@CurrentUserId() userId: string,
@@ -966,7 +959,7 @@ export class ProjectController {
@ApiOkResponse({ type: ProjectViewEntity })
@ApiBearerAuth()
@Post(':projectId/views')
- @Auth([], true)
+ @Auth(true)
async createProjectView(
@Param() params: ProjectIdDto,
@Body() body: CreateProjectViewDto,
@@ -1019,7 +1012,7 @@ export class ProjectController {
@ApiOkResponse({ type: ProjectViewEntity })
@ApiBearerAuth()
@Get(':projectId/views')
- @Auth([], true, true)
+ @Auth(true, true)
async getProjectViews(
@Param() params: ProjectIdDto,
@CurrentUserId() userId: string,
@@ -1042,7 +1035,7 @@ export class ProjectController {
@ApiOkResponse({ type: ProjectViewEntity })
@ApiBearerAuth()
@Patch(':projectId/views/:viewId')
- @Auth([], true)
+ @Auth(true)
async updateProjectView(
@Param() params: ProjectViewIdsDto,
@Body() body: UpdateProjectViewDto,
@@ -1090,8 +1083,7 @@ export class ProjectController {
@ApiBearerAuth()
@Delete('/:pid/:shareId')
@HttpCode(204)
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
+ @Auth()
async deleteShare(
@Param('pid') pid: string,
@Param('shareId') shareId: string,
@@ -1128,7 +1120,7 @@ export class ProjectController {
@ApiBearerAuth()
@HttpCode(HttpStatus.NO_CONTENT)
@Delete(':projectId/views/:viewId')
- @Auth([], true)
+ @Auth(true)
async deleteProjectView(
@Param() params: ProjectViewIdsDto,
@CurrentUserId() userId: string,
diff --git a/backend/apps/community/src/user/user.controller.ts b/backend/apps/community/src/user/user.controller.ts
index ea99d4f0f..5e33eb81a 100644
--- a/backend/apps/community/src/user/user.controller.ts
+++ b/backend/apps/community/src/user/user.controller.ts
@@ -2,7 +2,6 @@ import {
Controller,
Get,
Put,
- UseGuards,
Body,
BadRequestException,
Post,
@@ -21,12 +20,9 @@ import _map from 'lodash/map'
import _join from 'lodash/join'
import { randomUUID } from 'crypto'
-import { JwtAccessTokenGuard } from '../auth/guards'
-import { OnboardingStep, UserType } from './entities/user.entity'
+import { OnboardingStep } from './entities/user.entity'
import { UpdateUserProfileDTO } from './dto/update-user.dto'
import { SetShowLiveVisitorsDTO } from './dto/set-show-live-visitors.dto'
-import { Roles } from '../auth/decorators/roles.decorator'
-import { RolesGuard } from '../auth/guards/roles.guard'
import { CurrentUserId } from '../auth/decorators/current-user-id.decorator'
import { AppLoggerService } from '../logger/logger.service'
import { UserService } from './user.service'
@@ -53,10 +49,11 @@ import { Req } from '@nestjs/common'
import { redis } from '../common/constants'
import { ProjectService } from '../project/project.service'
import { clickhouse } from '../common/integrations/clickhouse'
+import { Auth } from '../auth/decorators'
@ApiTags('User')
@Controller('user')
-@UseGuards(JwtAccessTokenGuard, RolesGuard)
+@Auth()
export class UserController {
constructor(
private readonly logger: AppLoggerService,
@@ -68,8 +65,6 @@ export class UserController {
@ApiBearerAuth()
@Get('/me')
- @UseGuards(RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
async me(@CurrentUserId() uid: string) {
this.logger.log({ uid }, 'GET /user/me')
@@ -124,8 +119,6 @@ export class UserController {
@ApiBearerAuth()
@Put('/live-visitors')
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
async setShowLiveVisitors(
@Body() body: SetShowLiveVisitorsDTO,
@CurrentUserId() id: string,
@@ -154,8 +147,6 @@ export class UserController {
@ApiBearerAuth()
@Delete('/')
@HttpCode(204)
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
async deleteSelf(@CurrentUserId() id: string): Promise<any> {
this.logger.log({ id }, 'DELETE /user')
@@ -202,8 +193,6 @@ export class UserController {
@ApiBearerAuth()
@Delete('/share/:actionId')
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
@ApiResponse({ status: 204, description: 'Empty body' })
async deleteShare(
@CurrentUserId() uid: string,
@@ -230,8 +219,6 @@ export class UserController {
@ApiBearerAuth()
@Get('/share/:actionId')
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
@ApiResponse({ status: 204, description: 'Empty body' })
async acceptShare(
@CurrentUserId() uid: string,
@@ -258,8 +245,6 @@ export class UserController {
@ApiBearerAuth()
@Post('onboarding/step')
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
@ApiResponse({ status: 204 })
async updateOnboardingStep(
@CurrentUserId() userId: string,
@@ -278,8 +263,6 @@ export class UserController {
@ApiBearerAuth()
@Post('onboarding/complete')
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
@ApiResponse({ status: 204 })
async completeOnboarding(@CurrentUserId() userId: string): Promise<void> {
this.logger.log({ userId }, 'POST /user/onboarding/complete')
@@ -292,8 +275,6 @@ export class UserController {
@ApiBearerAuth()
@Post('api-key')
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
async generateApiKey(
@CurrentUserId() userId: string,
@Headers() headers,
@@ -324,8 +305,6 @@ export class UserController {
@ApiBearerAuth()
@Delete('/api-key')
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
async deleteApiKey(@CurrentUserId() userId: string) {
this.logger.log({ userId }, 'DELETE /user/api-key')
@@ -344,8 +323,6 @@ export class UserController {
@ApiBearerAuth()
@Put('/')
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
async updateCurrentUser(
@Body() userDTO: UpdateUserProfileDTO,
@CurrentUserId() id: string,