📈 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
API to bulk add Swetrix users to multiple projects
Blue Mouse284ed219fde0
diff --git a/backend/apps/production/src/project/dto/bulk-add-users.dto.ts b/backend/apps/production/src/project/dto/bulk-add-users.dto.tsnew file mode 100644index 000000000..11d4b5bd6--- /dev/null+++ b/backend/apps/production/src/project/dto/bulk-add-users.dto.ts@@ -0,0 +1,47 @@+import { ApiProperty } from '@nestjs/swagger'+import {+ IsNotEmpty,+ IsArray,+ ValidateNested,+ ArrayMinSize,+} from 'class-validator'+import { Type } from 'class-transformer'++import { Role } from '../entity/project-share.entity'++class UserProjectAccess {+ @ApiProperty({+ example: '[email protected]',+ description: 'User you want to invite to your project',+ })+ @IsNotEmpty()+ email: string++ @ApiProperty({+ example: 'viewer',+ description: 'Users role in your project',+ })+ @IsNotEmpty()+ role: Role++ @ApiProperty({+ example: ['project-id-1', 'project-id-2'],+ description: 'Array of project IDs to add the user to',+ })+ @IsArray()+ @IsNotEmpty()+ @ArrayMinSize(1)+ projectIds: string[]+}++export class BulkAddUsersDto {+ @ApiProperty({+ type: [UserProjectAccess],+ description: 'Array of users and their project access details',+ })+ @IsArray()+ @ValidateNested({ each: true })+ @Type(() => UserProjectAccess)+ @ArrayMinSize(1)+ users: UserProjectAccess[]+}diff --git a/backend/apps/production/src/project/interfaces/bulk-add-users.ts b/backend/apps/production/src/project/interfaces/bulk-add-users.tsnew file mode 100644index 000000000..4203f649c--- /dev/null+++ b/backend/apps/production/src/project/interfaces/bulk-add-users.ts@@ -0,0 +1,9 @@+export interface BulkAddUsersResponse {+ email: string+ success: boolean+ error: string | null+ failedProjectIds?: {+ projectId: string+ reason: string+ }[]+}diff --git a/backend/apps/production/src/project/project.controller.ts b/backend/apps/production/src/project/project.controller.tsindex 060cc4795..6fd414d1a 100644--- a/backend/apps/production/src/project/project.controller.ts+++ b/backend/apps/production/src/project/project.controller.ts@@ -1,3 +1,4 @@+/* eslint-disable no-await-in-loop */import {Controller,Body,@@ -110,6 +111,8 @@ import { ProjectViewIdsDto } from './dto/project-view-ids.dto'import { CreateMonitorHttpRequestDTO } from './dto/create-monitor.dto'import { MonitorEntity } from './entity/monitor.entity'import { UpdateMonitorHttpRequestDTO } from './dto/update-monitor.dto'+import { BulkAddUsersDto } from './dto/bulk-add-users.dto'+import { BulkAddUsersResponse } from './interfaces/bulk-add-users'const PROJECTS_MAXIMUM = 50@@ -480,7 +483,6 @@ export class ProjectController {let pid = generateProjectId()- // eslint-disable-next-line no-await-in-loopwhile (!(await this.projectService.isPIDUnique(pid))) {pid = generateProjectId()}@@ -689,7 +691,7 @@ export class ProjectController {)if (!project) {- throw new NotFoundException('Project not found.')+ throw new NotFoundException('Project not found')}this.projectService.allowedToManage(project, userId)@@ -1017,6 +1019,161 @@ export class ProjectController {await this.projectService.deleteByFilters(pid, type, filters)}+ @ApiBearerAuth()+ @Post('/bulk-add-users')+ @HttpCode(200)+ @Auth([], true)+ @ApiResponse({ status: 200, type: [BulkAddUsersDto] })+ async bulkAddUsers(+ @Body() bulkAddUsersDto: BulkAddUsersDto,+ @CurrentUserId() uid: string,+ ): Promise<BulkAddUsersResponse[]> {+ this.logger.log({ uid, bulkAddUsersDto }, 'POST /project/bulk-add-users')++ const inviter = await this.userService.findOne(uid, {+ relations: ['projects', 'sharedProjects', 'sharedProjects.project'],+ })++ const results: BulkAddUsersResponse[] = []++ await Promise.all(+ bulkAddUsersDto.users.map(async invitationObject => {+ const invitee = await this.userService.findOneWhere(+ {+ email: invitationObject.email,+ },+ ['sharedProjects'],+ )++ if (!invitee) {+ this.logger.warn(+ `User with email ${invitationObject.email} is not registered`,+ )++ results.push({+ email: invitationObject.email,+ success: false,+ error: 'User with this email is not registered on Swetrix',+ failedProjectIds: [],+ })++ return null+ }++ if (invitee.id === inviter.id) {+ this.logger.warn(+ `Skipping self-share attempt for ${invitationObject.email}`,+ )++ results.push({+ email: invitationObject.email,+ success: false,+ error:+ 'User with this email is the same as the inviter initiating this request',+ failedProjectIds: [],+ })++ return null+ }++ const failedProjectIds = []++ for (const pid of invitationObject.projectIds) {+ if (!isValidPID(pid)) {+ this.logger.warn(`Invalid project ID: ${pid}`)+ failedProjectIds.push({+ projectId: pid,+ reason: 'Invalid project ID',+ })+ continue+ }++ const project = await this.projectService.findOneWhere(+ { id: pid },+ {+ relations: ['admin', 'share', 'share.user'],+ select: ['id', 'admin', 'share'],+ },+ )++ if (_isEmpty(project)) {+ this.logger.warn(`Project with ID ${pid} does not exist`)+ failedProjectIds.push({+ projectId: pid,+ reason: 'Project does not exist',+ })+ continue+ }++ try {+ this.projectService.allowedToManage(project, uid, inviter.roles)+ } catch (reason) {+ this.logger.warn(`User ${uid} not allowed to manage project ${pid}`)+ failedProjectIds.push({+ projectId: pid,+ reason: 'Inviter is not allowed to manage this project',+ })+ continue+ }++ const isSharingWithUser = !_isEmpty(+ _find(project.share, share => share.user?.id === invitee.id),+ )++ if (isSharingWithUser) {+ this.logger.warn(+ `Already sharing project ${pid} with ${invitee.email}`,+ )+ failedProjectIds.push({+ projectId: pid,+ reason: 'Already sharing project with this user',+ })+ continue+ }++ try {+ const share = new ProjectShare()+ share.role = invitationObject.role+ share.user = invitee+ share.project = project+ share.confirmed = true // Auto-confirm since we're not sending invitations++ await this.projectService.createShare(share)++ // Saving share into project+ project.share.push(share)+ await this.projectService.create(project)++ // Saving share into invitees shared projects+ invitee.sharedProjects.push(share)+ await this.userService.create(invitee)++ await deleteProjectRedis(pid)+ } catch (reason) {+ this.logger.error(+ `[ERROR] Could not share project (pid: ${pid}, invitee ID: ${invitee.id}): ${reason}`,+ )+ failedProjectIds.push({+ projectId: pid,+ reason: 'Internal error',+ })+ }+ }++ results.push({+ email: invitationObject.email,+ success: failedProjectIds.length === 0,+ failedProjectIds,+ error: null,+ })++ return null+ }),+ )++ return results+ }+@ApiBearerAuth()@Post('/:pid/share')@HttpCode(200)@@ -1074,12 +1231,7 @@ export class ProjectController {}const isSharingWithUser = !_isEmpty(- await this.projectService.findShare({- where: {- project: project.id,- user: invitee.id,- },- }),+ _find(project.share, share => share.user?.id === invitee.id),)if (isSharingWithUser) {@@ -1341,7 +1493,7 @@ export class ProjectController {})if (!project) {- throw new NotFoundException('Project not found.')+ throw new NotFoundException('Project not found')}this.projectService.allowedToManage(@@ -1357,7 +1509,7 @@ export class ProjectController {)if (!subscriber) {- throw new NotFoundException('Subscriber not found.')+ throw new NotFoundException('Subscriber not found')}await this.projectService.removeSubscriber(@@ -1381,7 +1533,7 @@ export class ProjectController {})if (!project) {- throw new NotFoundException('Project not found.')+ throw new NotFoundException('Project not found')}this.projectService.allowedToManage(@@ -1499,7 +1651,7 @@ export class ProjectController {})if (!project) {- throw new NotFoundException('Project not found.')+ throw new NotFoundException('Project not found')}this.projectService.allowedToView(project, userId)@@ -1524,7 +1676,7 @@ export class ProjectController {})if (!project) {- throw new NotFoundException('Project not found.')+ throw new NotFoundException('Project not found')}this.projectService.allowedToManage(@@ -1540,7 +1692,7 @@ export class ProjectController {)if (!subscriber) {- throw new NotFoundException('Subscriber not found.')+ throw new NotFoundException('Subscriber not found')}return this.projectService.updateSubscriber(@@ -2152,13 +2304,13 @@ export class ProjectController {])if (!project) {- throw new NotFoundException('Project not found.')+ throw new NotFoundException('Project not found')}const user = await this.userService.findUserV2(userId, ['roles'])if (!user) {- throw new NotFoundException('User not found.')+ throw new NotFoundException('User not found')}this.projectService.allowedToManage(project, userId, user.roles)diff --git a/backend/apps/production/src/project/project.service.ts b/backend/apps/production/src/project/project.service.tsindex 0ac717466..18a139d7a 100644--- a/backend/apps/production/src/project/project.service.ts+++ b/backend/apps/production/src/project/project.service.ts@@ -495,9 +495,9 @@ export class ProjectService {findOneWhere(where: Record<string, unknown>,- params: object = {},+ options: Omit<FindOneOptions<Project>, 'where'> = {},): Promise<Project> {- return this.projectsRepository.findOne({ where, ...params })+ return this.projectsRepository.findOne({ where, ...options })}allowedToView(diff --git a/backend/apps/production/src/user/user.service.ts b/backend/apps/production/src/user/user.service.tsindex 9cf9ff418..00673fbd9 100644--- a/backend/apps/production/src/user/user.service.ts+++ b/backend/apps/production/src/user/user.service.ts@@ -4,7 +4,15 @@ import {InternalServerErrorException,} from '@nestjs/common'import { InjectRepository } from '@nestjs/typeorm'-import { FindManyOptions, In, IsNull, LessThan, Not, Repository } from 'typeorm'+import {+ FindManyOptions,+ FindOneOptions,+ In,+ IsNull,+ LessThan,+ Not,+ Repository,+} from 'typeorm'import axios from 'axios'import CryptoJS from 'crypto-js'import dayjs from 'dayjs'@@ -172,7 +180,7 @@ export class UserService {return this.usersRepository.findOne({ where, relations, select })}- findOne(id: string, params: any = {}): Promise<User> {+ findOne(id: string, params: FindOneOptions<User> = {}): Promise<User> {return this.usersRepository.findOne({where: { id },...params,