📈 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!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
Validate periods in DTO
Blue Mousee20ecfb44d5e
diff --git a/backend/apps/production/src/analytics/analytics.controller.ts b/backend/apps/production/src/analytics/analytics.controller.tsindex ceac7520d..81f7e16b9 100644--- a/backend/apps/production/src/analytics/analytics.controller.ts+++ b/backend/apps/production/src/analytics/analytics.controller.ts@@ -38,9 +38,9 @@ import {AnalyticsService,getHeartbeatKey,DataType,- validPeriods,getLowestPossibleTimeBucket,} from './analytics.service'+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'@@ -49,8 +49,8 @@ import { EventsDTO } from './dto/events.dto'import { GetDataDto, ChartRenderMode } from './dto/getData.dto'import { GetCustomEventMetadata } from './dto/get-custom-event-meta.dto'import { GetPagePropertyMetaDto } from './dto/get-page-property-meta.dto'-import { GetUserFlowDTO } from './dto/getUserFlow.dto'-import { GetFunnelsDTO } from './dto/getFunnels.dto'+import { GetUserFlowDto } from './dto/getUserFlow.dto'+import { GetFunnelsDto } from './dto/getFunnels.dto'import { AppLoggerService } from '../logger/logger.service'import {redis,@@ -93,6 +93,7 @@ import {ProjectViewCustomEventDto,} from '../project/dto/create-project-view.dto'import { extensions } from './utils/ua-parser'+import { GetOverallStatsDto } from './dto/get-overall-stats.dto'dayjs.extend(utc)dayjs.extend(dayjsTimezone)@@ -230,7 +231,7 @@ export class AnalyticsController {@CurrentUserId() uid: string,@Headers() headers: { 'x-password'?: string },isCaptcha = false,- ): Promise<any> {+ ) {const {pid,period,@@ -244,10 +245,6 @@ export class AnalyticsController {} = datathis.analyticsService.validatePID(pid)- if (!_isEmpty(period)) {- this.analyticsService.validatePeriod(period)- }-await this.analyticsService.checkProjectAccess(pid,uid,@@ -400,7 +397,7 @@ export class AnalyticsController {@Get('funnel')@Auth([], true, true)async getFunnel(- @Query() data: GetFunnelsDTO,+ @Query() data: GetFunnelsDto,@CurrentUserId() uid: string,@Headers() headers: { 'x-password'?: string },): Promise<IGetFunnel> {@@ -415,10 +412,6 @@ export class AnalyticsController {} = datathis.analyticsService.validatePID(pid)- if (!_isEmpty(period)) {- this.analyticsService.validatePeriod(period)- }-await this.analyticsService.checkProjectAccess(pid,uid,@@ -479,13 +472,9 @@ export class AnalyticsController {@CurrentUserId() uid: string,@Headers() headers: { 'x-password'?: string },): Promise<ReturnType<typeof this.analyticsService.getCustomEventMetadata>> {- const { pid, period } = data+ const { pid } = datathis.analyticsService.validatePID(pid)- if (!_isEmpty(period)) {- this.analyticsService.validatePeriod(period)- }-await this.analyticsService.checkProjectAccess(pid,uid,@@ -504,13 +493,9 @@ export class AnalyticsController {@CurrentUserId() uid: string,@Headers() headers: { 'x-password'?: string },): Promise<ReturnType<typeof this.analyticsService.getPagePropertyMeta>> {- const { pid, period } = data+ const { pid } = datathis.analyticsService.validatePID(pid)- if (!_isEmpty(period)) {- this.analyticsService.validatePeriod(period)- }-await this.analyticsService.checkProjectAccess(pid,uid,@@ -528,7 +513,7 @@ export class AnalyticsController {@Query() data: GetFiltersDto,@CurrentUserId() uid: string,@Headers() headers: { 'x-password'?: string },- ): Promise<any> {+ ) {const { pid, type } = datathis.analyticsService.validatePID(pid)@@ -549,7 +534,7 @@ export class AnalyticsController {@Query() data: GetFiltersDto,@CurrentUserId() uid: string,@Headers() headers: { 'x-password'?: string },- ): Promise<any> {+ ) {const { pid, type } = datathis.analyticsService.validatePID(pid)@@ -570,7 +555,7 @@ export class AnalyticsController {@Query() data: GetDataDto,@CurrentUserId() uid: string,@Headers() headers: { 'x-password'?: string },- ): Promise<any> {+ ) {const {pid,period,@@ -583,10 +568,6 @@ export class AnalyticsController {} = datathis.analyticsService.validatePID(pid)- if (!_isEmpty(period)) {- this.analyticsService.validatePeriod(period)- }-const [filtersQuery, filtersParams, appliedFilters, customEVFilterApplied] =this.analyticsService.getFiltersQuery(filters, DataType.ANALYTICS)@@ -638,7 +619,7 @@ export class AnalyticsController {@Query() data: GetDataDto & { measure: PerfMeasure },@CurrentUserId() uid: string,@Headers() headers: { 'x-password'?: string },- ): Promise<any> {+ ) {const {pid,period,@@ -653,10 +634,6 @@ export class AnalyticsController {this.analyticsService.checkIfPerfMeasureIsValid(measure)- if (!_isEmpty(period)) {- this.analyticsService.validatePeriod(period)- }-await this.analyticsService.checkProjectAccess(pid,uid,@@ -732,7 +709,7 @@ export class AnalyticsController {@Query() data: GetDataDto & { measure: PerfMeasure },@CurrentUserId() uid: string,@Headers() headers: { 'x-password'?: string },- ): Promise<any> {+ ) {const {pid,period,@@ -747,10 +724,6 @@ export class AnalyticsController {this.analyticsService.checkIfPerfMeasureIsValid(measure)- if (!_isEmpty(period)) {- this.analyticsService.validatePeriod(period)- }-const [filtersQuery, filtersParams, appliedFilters] =this.analyticsService.getFiltersQuery(filters, DataType.PERFORMANCE)@@ -800,24 +773,20 @@ export class AnalyticsController {async getCaptchaData(@Query() data: GetDataDto,@CurrentUserId() uid: string,- ): Promise<any> {+ ) {return this.getData(data, uid, {}, true)}@Get('user-flow')@Auth([], true, true)async getUserFlow(- @Query() data: GetUserFlowDTO,+ @Query() data: GetUserFlowDto,@CurrentUserId() uid: string,@Headers() headers: { 'x-password'?: string },): Promise<IUserFlow | { appliedFilters: any[] }> {const { pid, period, from, to, timezone = DEFAULT_TIMEZONE, filters } = datathis.analyticsService.validatePID(pid)- if (!_isEmpty(period)) {- this.analyticsService.validatePeriod(period)- }-await this.analyticsService.checkProjectAccess(pid,uid,@@ -870,10 +839,10 @@ export class AnalyticsController {@Auth([], true, true)// returns overall short statistics per projectasync getOverallStats(- @Query() data,+ @Query() data: GetOverallStatsDto,@CurrentUserId() uid: string,@Headers() headers: { 'x-password'?: string },- ): Promise<any> {+ ) {const {pids,pid,@@ -912,9 +881,9 @@ export class AnalyticsController {@Auth([], true, true)// returns overall short statistics per CAPTCHA projectasync getCaptchaOverallStats(- @Query() data,+ @Query() data: GetOverallStatsDto,@CurrentUserId() uid: string,- ): Promise<any> {+ ) {const {pids,pid,@@ -948,10 +917,10 @@ export class AnalyticsController {@Get('performance/birdseye')@Auth([], true, true)async getPerformanceOverallStats(- @Query() data,+ @Query() data: GetOverallStatsDto & { measure: PerfMeasure },@CurrentUserId() uid: string,@Headers() headers: { 'x-password'?: string },- ): Promise<any> {+ ) {const {pids,pid,@@ -1115,11 +1084,7 @@ export class AnalyticsController {@Post('error')@Public()- async logError(- @Body() errorDTO: ErrorDTO,- @Headers() headers,- @Ip() reqIP,- ): Promise<any> {+ async logError(@Body() errorDTO: ErrorDTO, @Headers() headers, @Ip() reqIP) {const { 'user-agent': userAgent, origin } = headersconst ip = getIPFromHeaders(headers, true) || reqIP || ''@@ -1180,7 +1145,7 @@ export class AnalyticsController {@CurrentUserId() uid: string,@Headers() headers,@Ip() reqIP,- ): Promise<any> {+ ) {const { pid, eid, eids: unprocessedEids, status } = statusDTOconst ip = getIPFromHeaders(headers) || reqIP || ''@@ -1203,7 +1168,7 @@ export class AnalyticsController {@Body() eventsDTO: EventsDTO,@Headers() headers,@Ip() reqIP,- ): Promise<any> {+ ) {const { 'user-agent': userAgent, origin } = headersconst ip = getIPFromHeaders(headers, true) || reqIP || ''@@ -1284,7 +1249,7 @@ export class AnalyticsController {@Body() logDTO: PageviewsDTO,@Headers() headers,@Ip() reqIP,- ): Promise<any> {+ ) {const { 'user-agent': userAgent, origin } = headersconst { pid } = logDTOconst ip = getIPFromHeaders(headers, true) || reqIP || ''@@ -1307,11 +1272,7 @@ export class AnalyticsController {// Log pageview event@Post()@Public()- async log(- @Body() logDTO: PageviewsDTO,- @Headers() headers,- @Ip() reqIP,- ): Promise<any> {+ async log(@Body() logDTO: PageviewsDTO, @Headers() headers, @Ip() reqIP) {const { 'user-agent': userAgent, origin } = headersconst ip = getIPFromHeaders(headers, true) || reqIP || ''@@ -1434,7 +1395,7 @@ export class AnalyticsController {@Headers() headers,@Ip() reqIP,@Response() res,- ): Promise<any> {+ ) {const { 'user-agent': userAgent, origin } = headersconst { pid } = data@@ -1512,14 +1473,10 @@ export class AnalyticsController {@Query() data: GetSessionsDto,@CurrentUserId() uid: string,@Headers() headers: { 'x-password'?: string },- ): Promise<any> {+ ) {const { pid, period, from, to, filters, timezone = DEFAULT_TIMEZONE } = datathis.analyticsService.validatePID(pid)- if (!_isEmpty(period)) {- this.analyticsService.validatePeriod(period)- }-await this.analyticsService.checkProjectAccess(pid,uid,@@ -1599,7 +1556,7 @@ export class AnalyticsController {@Query() parameters: GetUptimeBirdseyeDto,@CurrentUserId() uid: string,@Headers() headers: { 'x-password'?: string },- ): Promise<any> {+ ) {const {pid,monitorId,@@ -1659,10 +1616,6 @@ export class AnalyticsController {this.analyticsService.validatePID(pid)- if (!_isEmpty(period)) {- this.analyticsService.validatePeriod(period)- }-await this.analyticsService.checkProjectAccess(pid,userId,@@ -1738,7 +1691,7 @@ export class AnalyticsController {@Query() data: GetErrorsDto,@CurrentUserId() uid: string,@Headers() headers: { 'x-password'?: string },- ): Promise<any> {+ ) {const {pid,period,@@ -1750,10 +1703,6 @@ export class AnalyticsController {} = datathis.analyticsService.validatePID(pid)- if (!_isEmpty(period)) {- this.analyticsService.validatePeriod(period)- }-await this.analyticsService.checkProjectAccess(pid,uid,@@ -1833,7 +1782,7 @@ export class AnalyticsController {@Query() data: GetErrorDto,@CurrentUserId() uid: string,@Headers() headers: { 'x-password'?: string },- ): Promise<any> {+ ) {const {pid,timezone = DEFAULT_TIMEZONE,@@ -1845,10 +1794,6 @@ export class AnalyticsController {} = datathis.analyticsService.validatePID(pid)- if (!_isEmpty(period)) {- this.analyticsService.validatePeriod(period)- }-await this.analyticsService.checkProjectAccess(pid,uid,@@ -1902,7 +1847,7 @@ export class AnalyticsController {@Query() data: GetSessionDto,@CurrentUserId() uid: string,@Headers() headers: { 'x-password'?: string },- ): Promise<any> {+ ) {const {pid,psid,@@ -1936,7 +1881,7 @@ export class AnalyticsController {@Query() data: GetCustomEventsDto,@CurrentUserId() uid: string,@Headers() headers: { 'x-password'?: string },- ): Promise<any> {+ ) {const {pid,period,@@ -1949,10 +1894,6 @@ export class AnalyticsController {} = datathis.analyticsService.validatePID(pid)- if (!_isEmpty(period)) {- this.analyticsService.validatePeriod(period)- }-await this.analyticsService.checkProjectAccess(pid,uid,@@ -1965,7 +1906,7 @@ export class AnalyticsController {let difflet timeBucketForAllTime- if (period === validPeriods[validPeriods.length - 1]) {+ if (period === VALID_PERIODS[VALID_PERIODS.length - 1]) {const res = await this.analyticsService.getTimeBucketForAllTime(pid,period,diff --git a/backend/apps/production/src/analytics/analytics.service.ts b/backend/apps/production/src/analytics/analytics.service.tsindex a6eb9789d..f851586cf 100644--- a/backend/apps/production/src/analytics/analytics.service.ts+++ b/backend/apps/production/src/analytics/analytics.service.ts@@ -121,19 +121,6 @@ const GMT_0_TIMEZONES = [// 'Africa/Casablanca',]-export const validPeriods = [- '1h',- 'today',- 'yesterday',- '1d',- '7d',- '4w',- '3M',- '12M',- '24M',- 'all',-]-const MEASURES_MAP = {average: 'avg',median: 'median',@@ -224,10 +211,6 @@ export const getLowestPossibleTimeBucket = (to?: string,): TimeBucketType => {if (!from && !to) {- if (!_includes(validPeriods, period)) {- throw new UnprocessableEntityException('The provided period is incorrect')- }-if (period === '1h') {return TimeBucketType.MINUTE}@@ -809,12 +792,6 @@ export class AnalyticsService {}}- validatePeriod(period: string): void {- if (!_includes(validPeriods, period)) {- throw new UnprocessableEntityException('The provided period is incorrect')- }- }-async getPagesArray(rawPages?: string,funnelId?: string,@@ -1342,8 +1319,6 @@ export class AnalyticsService {_from = groupFrom_to = groupTo- } else {- this.validatePeriod(period)}const result = {}@@ -1477,8 +1452,6 @@ export class AnalyticsService {_from = groupFrom_to = groupTo- } else {- this.validatePeriod(period)}const result = {}@@ -1667,8 +1640,6 @@ export class AnalyticsService {_from = groupFrom_to = groupTo- } else {- this.validatePeriod(period)}const result = {}@@ -1861,8 +1832,6 @@ export class AnalyticsService {_from = groupFrom_to = groupTo- } else {- this.validatePeriod(period)}const result = {}diff --git a/backend/apps/production/src/analytics/decorators/validate-period.decorator.ts b/backend/apps/production/src/analytics/decorators/validate-period.decorator.tsnew file mode 100644index 000000000..917104e61--- /dev/null+++ b/backend/apps/production/src/analytics/decorators/validate-period.decorator.ts@@ -0,0 +1,40 @@+import { registerDecorator, ValidationOptions } from 'class-validator'+import { UnprocessableEntityException } from '@nestjs/common'+import _includes from 'lodash/includes'++export const VALID_PERIODS = [+ '1h',+ 'today',+ 'yesterday',+ '1d',+ '7d',+ '4w',+ '3M',+ '12M',+ '24M',+ 'all',+]++export function ValidatePeriod(validationOptions?: ValidationOptions) {+ return (object: object, propertyName: string) => {+ registerDecorator({+ name: 'validatePeriod',+ target: object.constructor,+ propertyName,+ options: validationOptions,+ validator: {+ validate(value: any) {+ if (value === undefined || value === '') {+ return true // Allow empty or undefined values+ }+ if (!_includes(VALID_PERIODS, value)) {+ throw new UnprocessableEntityException(+ `The provided period is incorrect. It should be one of: ${VALID_PERIODS.join(', ')}`,+ )+ }+ return true+ },+ },+ })+ }+}diff --git a/backend/apps/production/src/analytics/dto/get-monitor-data.dto.ts b/backend/apps/production/src/analytics/dto/get-monitor-data.dto.tsindex e66d72cf0..b69cf01b4 100644--- a/backend/apps/production/src/analytics/dto/get-monitor-data.dto.ts+++ b/backend/apps/production/src/analytics/dto/get-monitor-data.dto.ts@@ -1,7 +1,8 @@import { ApiProperty } from '@nestjs/swagger'-import { IsEnum, IsNotEmpty } from 'class-validator'+import { IsEnum, IsNotEmpty, IsOptional } from 'class-validator'import { DEFAULT_TIMEZONE } from '../../user/entities/user.entity'import { TimeBucketType } from './getData.dto'+import { ValidatePeriod } from '../decorators/validate-period.decorator'export class GetMonitorDataDto {@ApiProperty()@@ -12,8 +13,10 @@ export class GetMonitorDataDto {@IsNotEmpty()monitorId: number- @ApiProperty()- period: string+ @ApiProperty({ required: false })+ @IsOptional()+ @ValidatePeriod()+ period?: string@ApiProperty({ enum: TimeBucketType })@IsNotEmpty()diff --git a/backend/apps/production/src/analytics/dto/get-overall-stats.dto.ts b/backend/apps/production/src/analytics/dto/get-overall-stats.dto.tsnew file mode 100644index 000000000..1b644086c--- /dev/null+++ b/backend/apps/production/src/analytics/dto/get-overall-stats.dto.ts@@ -0,0 +1,49 @@+import { ApiProperty } from '@nestjs/swagger'+import { IsOptional, IsString, ValidateIf } from 'class-validator'+import { DEFAULT_TIMEZONE } from '../../user/entities/user.entity'+import { ValidatePeriod } from '../decorators/validate-period.decorator'++export class GetOverallStatsDto {+ @ApiProperty({ description: 'Array of project IDs', required: false })+ @ValidateIf(o => o.pids || !o.pid)+ @IsOptional()+ @IsString({ each: true })+ pids?: string[]++ @ApiProperty({ description: 'Single project ID', required: false })+ @ValidateIf(o => !o.pids || o.pid)+ @IsOptional()+ @IsString()+ pid?: string++ @ApiProperty({ required: false })+ @IsOptional()+ @ValidatePeriod()+ period?: string++ @ApiProperty({ required: false })+ @IsOptional()+ @IsString()+ from?: string++ @ApiProperty({ required: false })+ @IsOptional()+ @IsString()+ to?: string++ @ApiProperty({+ description: 'Timezone to display data in',+ default: DEFAULT_TIMEZONE,+ })+ @IsOptional()+ @IsString()+ timezone?: string = DEFAULT_TIMEZONE++ @ApiProperty({+ description: 'A stringified array of properties to filter',+ required: false,+ })+ @IsOptional()+ @IsString()+ filters?: string+}diff --git a/backend/apps/production/src/analytics/dto/get-uptime-birdseye.dto.ts b/backend/apps/production/src/analytics/dto/get-uptime-birdseye.dto.tsindex 69d7bc265..806ebebf9 100644--- a/backend/apps/production/src/analytics/dto/get-uptime-birdseye.dto.ts+++ b/backend/apps/production/src/analytics/dto/get-uptime-birdseye.dto.ts@@ -1,6 +1,7 @@import { ApiProperty } from '@nestjs/swagger'import { IsNotEmpty, IsOptional } from 'class-validator'import { DEFAULT_TIMEZONE } from '../../user/entities/user.entity'+import { ValidatePeriod } from '../decorators/validate-period.decorator'export class GetUptimeBirdseyeDto {@ApiProperty()@@ -15,8 +16,10 @@ export class GetUptimeBirdseyeDto {@IsOptional()monitorIds?: number[] | string[]- @ApiProperty()- period: string+ @ApiProperty({ required: false })+ @IsOptional()+ @ValidatePeriod()+ period?: string@ApiProperty({ required: false })from: stringdiff --git a/backend/apps/production/src/analytics/dto/getData.dto.ts b/backend/apps/production/src/analytics/dto/getData.dto.tsindex 3ccc5bbf2..8fa4a22da 100644--- a/backend/apps/production/src/analytics/dto/getData.dto.ts+++ b/backend/apps/production/src/analytics/dto/getData.dto.ts@@ -1,6 +1,7 @@import { ApiProperty } from '@nestjs/swagger'import { IsNotEmpty, IsOptional, IsEnum } from 'class-validator'import { DEFAULT_TIMEZONE } from '../../user/entities/user.entity'+import { ValidatePeriod } from '../decorators/validate-period.decorator'export enum TimeBucketType {MINUTE = 'minute',@@ -21,8 +22,10 @@ export class GetDataDto {@IsNotEmpty()pid: string- @ApiProperty()- period: string+ @ApiProperty({ required: false })+ @IsOptional()+ @ValidatePeriod()+ period?: string@ApiProperty({ enum: TimeBucketType })@IsNotEmpty()diff --git a/backend/apps/production/src/analytics/dto/getFunnels.dto.ts b/backend/apps/production/src/analytics/dto/getFunnels.dto.tsindex f7617cf8d..ae21a7323 100644--- a/backend/apps/production/src/analytics/dto/getFunnels.dto.ts+++ b/backend/apps/production/src/analytics/dto/getFunnels.dto.ts@@ -1,15 +1,17 @@import { ApiProperty } from '@nestjs/swagger'-import { IsNotEmpty } from 'class-validator'+import { IsNotEmpty, IsOptional } from 'class-validator'import { DEFAULT_TIMEZONE } from '../../user/entities/user.entity'+import { ValidatePeriod } from '../decorators/validate-period.decorator'-// eslint-disable-next-line @typescript-eslint/naming-convention-export class GetFunnelsDTO {+export class GetFunnelsDto {@ApiProperty()@IsNotEmpty()pid: string- @ApiProperty()- period: string+ @ApiProperty({ required: false })+ @IsOptional()+ @ValidatePeriod()+ period?: string@ApiProperty()from: stringdiff --git a/backend/apps/production/src/analytics/dto/getUserFlow.dto.ts b/backend/apps/production/src/analytics/dto/getUserFlow.dto.tsindex 63fd88641..e6e17ec74 100644--- a/backend/apps/production/src/analytics/dto/getUserFlow.dto.ts+++ b/backend/apps/production/src/analytics/dto/getUserFlow.dto.ts@@ -1,15 +1,18 @@import { ApiProperty } from '@nestjs/swagger'-import { IsNotEmpty } from 'class-validator'+import { IsNotEmpty, IsOptional } from 'class-validator'import { DEFAULT_TIMEZONE } from '../../user/entities/user.entity'+import { ValidatePeriod } from '../decorators/validate-period.decorator'// eslint-disable-next-line @typescript-eslint/naming-convention-export class GetUserFlowDTO {+export class GetUserFlowDto {@ApiProperty()@IsNotEmpty()pid: string- @ApiProperty()- period: string+ @ApiProperty({ required: false })+ @IsOptional()+ @ValidatePeriod()+ period?: string@ApiProperty()from: string