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!

project transfers

Blue Moused12f053ed128
diff --git a/backend/apps/community/src/common/utils.ts b/backend/apps/community/src/common/utils.ts
index 13aa3d6ce..591944871 100644
--- a/backend/apps/community/src/common/utils.ts
+++ b/backend/apps/community/src/common/utils.ts
@@ -108,6 +108,8 @@ const ALLOWED_KEYS = [
'botsProtectionLevel',
]
+const CLICKHOUSE_PROJECT_UPDATABLE_KEYS = [...ALLOWED_KEYS, 'adminId']
+
const ALLOWED_FUNNEL_KEYS = ['name', 'steps']
const ALLOWED_SHARE_KEYS = ['role', 'confirmed']
@@ -311,16 +313,28 @@ const getProjectsClickhouse = async (
return data
}
-const updateProjectClickhouse = async (project: any) => {
+const updateProjectClickhouse = async (
+ project: any,
+ options: { ignoreAllowedKeys?: boolean } = {},
+) => {
+ const updatableKeys = options.ignoreAllowedKeys
+ ? CLICKHOUSE_PROJECT_UPDATABLE_KEYS
+ : ALLOWED_KEYS
+
const filtered = _reduce(
- _filter(_keys(project), key => ALLOWED_KEYS.includes(key)),
+ _filter(_keys(project), key => updatableKeys.includes(key)),
(obj, key) => {
obj[key] = project[key]
return obj
},
{},
)
+
const columns = _keys(filtered)
+ if (_isEmpty(columns)) {
+ return
+ }
+
const values = _values(filtered)
const query = `ALTER table project UPDATE ${_join(
_map(columns, (col, id) => `${col}='${values[id]}'`),
diff --git a/backend/apps/community/src/project/dto/index.ts b/backend/apps/community/src/project/dto/index.ts
index 1308d4594..3ad6d3615 100644
--- a/backend/apps/community/src/project/dto/index.ts
+++ b/backend/apps/community/src/project/dto/index.ts
@@ -4,3 +4,4 @@ export * from './update-project.dto'
export * from './project-password.dto'
export * from './funnel-create.dto'
export * from './funnel-update.dto'
+export * from './transfer-project.dto'
diff --git a/backend/apps/community/src/project/dto/transfer-project.dto.ts b/backend/apps/community/src/project/dto/transfer-project.dto.ts
new file mode 100644
index 000000000..d148c2a99
--- /dev/null
+++ b/backend/apps/community/src/project/dto/transfer-project.dto.ts
@@ -0,0 +1,9 @@
+import { IsEmail, Matches } from 'class-validator'
+
+export class TransferProjectBodyDto {
+ @Matches(/^(?!.*--)[a-zA-Z0-9-]{12}$/)
+ readonly projectId: string
+
+ @IsEmail()
+ readonly email: string
+}
diff --git a/backend/apps/community/src/project/project.controller.ts b/backend/apps/community/src/project/project.controller.ts
index 125ea782d..073f70840 100644
--- a/backend/apps/community/src/project/project.controller.ts
+++ b/backend/apps/community/src/project/project.controller.ts
@@ -16,6 +16,7 @@ import {
Patch,
HttpStatus,
ParseIntPipe,
+ ConflictException,
} from '@nestjs/common'
import { v4 as uuidv4 } from 'uuid'
import {
@@ -61,6 +62,7 @@ import {
UpdateProjectDto,
FunnelCreateDTO,
FunnelUpdateDTO,
+ TransferProjectBodyDto,
} from './dto'
import { AppLoggerService } from '../logger/logger.service'
import { isValidPID } from '../common/constants'
@@ -288,6 +290,40 @@ export class ProjectController {
}
}
+ @Post('transfer')
+ @Auth([UserType.ADMIN, UserType.CUSTOMER])
+ async transferProject(
+ @Body() body: TransferProjectBodyDto,
+ @CurrentUserId() userId: string,
+ ) {
+ // On Swetrix Cloud we send an email to verify transfer, and then transfer when user clicks on the email link
+ // Here we'll just transfer the project for now
+ this.logger.log({ body }, 'POST /project/transfer')
+
+ const project = await this.projectService.getOwnProject(
+ body.projectId,
+ userId,
+ )
+
+ const newAdmin = await this.userService.findOne({
+ email: body.email,
+ })
+
+ if (_isEmpty(newAdmin)) {
+ throw new NotFoundException('User not found.')
+ }
+
+ if (project.adminId === newAdmin.id) {
+ throw new ConflictException('You cannot transfer project to yourself.')
+ }
+
+ await this.projectService.confirmTransferProject(
+ body.projectId,
+ newAdmin.id,
+ project.adminId,
+ )
+ }
+
@ApiBearerAuth()
@Post('/:pid/share')
@HttpCode(200)
@@ -400,42 +436,6 @@ export class ProjectController {
return await findProjectShareClickhouse(shareId)
}
- @ApiBearerAuth()
- @Delete('/:pid/:shareId')
- @HttpCode(204)
- @UseGuards(JwtAccessTokenGuard, RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
- async deleteShare(
- @Param('pid') pid: string,
- @Param('shareId') shareId: string,
- @CurrentUserId() userId: string,
- ) {
- this.logger.log({ userId, pid, shareId }, 'DELETE /project/:pid/:shareId')
-
- if (!isValidPID(pid)) {
- throw new BadRequestException(
- 'The provided Project ID (pid) is incorrect',
- )
- }
-
- const share = await findProjectShareClickhouse(shareId)
-
- if (!share) {
- return
- }
-
- const project = await this.projectService.getFullProject(pid)
-
- if (_isEmpty(project)) {
- throw new NotFoundException('Project was not found in the database')
- }
-
- this.projectService.allowedToManage(project, userId)
-
- await deleteProjectShareClickhouse(shareId)
- await deleteProjectRedis(pid)
- }
-
@ApiBearerAuth()
@Post('/')
@ApiResponse({ status: 201, type: Project })
@@ -481,7 +481,7 @@ export class ProjectController {
)
}
- const project = await this.projectService.getFullProject(id)
+ const project = await this.projectService.getOwnProject(id, userId)
if (_isEmpty(project)) {
throw new NotFoundException('Project was not found in the database')
@@ -727,22 +727,22 @@ export class ProjectController {
@ApiResponse({ status: 204, description: 'Empty body' })
async delete(
@Param('id') id: string,
- @CurrentUserId() uid: string,
+ @CurrentUserId() userId: string,
): Promise<any> {
- this.logger.log({ uid, id }, 'DELETE /project/:id')
+ this.logger.log({ userId, id }, 'DELETE /project/:id')
if (!isValidPID(id)) {
throw new BadRequestException(
'The provided Project ID (pid) is incorrect',
)
}
- const project = await this.projectService.getFullProject(id)
+ const project = await this.projectService.getOwnProject(id, userId)
if (_isEmpty(project)) {
throw new NotFoundException('Project was not found in the database')
}
- this.projectService.allowedToManage(project, uid)
+ this.projectService.allowedToManage(project, userId)
await deleteProjectClickhouse(id)
@@ -1073,6 +1073,42 @@ export class ProjectController {
return this.projectService.formatViewFromClickhouse(view)
}
+ @ApiBearerAuth()
+ @Delete('/:pid/:shareId')
+ @HttpCode(204)
+ @UseGuards(JwtAccessTokenGuard, RolesGuard)
+ @Roles(UserType.CUSTOMER, UserType.ADMIN)
+ async deleteShare(
+ @Param('pid') pid: string,
+ @Param('shareId') shareId: string,
+ @CurrentUserId() userId: string,
+ ) {
+ this.logger.log({ userId, pid, shareId }, 'DELETE /project/:pid/:shareId')
+
+ if (!isValidPID(pid)) {
+ throw new BadRequestException(
+ 'The provided Project ID (pid) is incorrect',
+ )
+ }
+
+ const share = await findProjectShareClickhouse(shareId)
+
+ if (!share) {
+ return
+ }
+
+ const project = await this.projectService.getFullProject(pid)
+
+ if (_isEmpty(project)) {
+ throw new NotFoundException('Project was not found in the database')
+ }
+
+ this.projectService.allowedToManage(project, userId)
+
+ await deleteProjectShareClickhouse(shareId)
+ await deleteProjectRedis(pid)
+ }
+
@ApiOperation({ summary: 'Delete project view' })
@ApiNoContentResponse()
@ApiBearerAuth()
diff --git a/backend/apps/community/src/project/project.service.ts b/backend/apps/community/src/project/project.service.ts
index d4f1a0054..e54b81182 100644
--- a/backend/apps/community/src/project/project.service.ts
+++ b/backend/apps/community/src/project/project.service.ts
@@ -21,6 +21,7 @@ import _trim from 'lodash/trim'
import _reduce from 'lodash/reduce'
import _findIndex from 'lodash/findIndex'
import { compareSync } from 'bcrypt'
+import { v4 as uuidv4 } from 'uuid'
import { Project, ProjectWithShare, Role } from './entity/project.entity'
import { ProjectDTO } from './dto/project.dto'
@@ -36,8 +37,10 @@ import {
} from '../common/constants'
import { clickhouse } from '../common/integrations/clickhouse'
import {
+ createProjectShareClickhouse,
findProjectSharesByProjectClickhouse,
getProjectClickhouse,
+ updateProjectClickhouse,
} from '../common/utils'
import { MAX_PROJECT_PASSWORD_LENGTH, UpdateProjectDto } from './dto'
import { Funnel } from './entity/funnel.entity'
@@ -153,6 +156,40 @@ export class ProjectService {
}
}
+ async getOwnProject(projectId: string, userId: string) {
+ const project = await this.getFullProject(projectId)
+
+ if (project?.adminId !== userId) {
+ throw new ForbiddenException('You are not allowed to manage this project')
+ }
+
+ return project
+ }
+
+ async confirmTransferProject(
+ projectId: string,
+ userId: string,
+ oldAdminId: string,
+ ) {
+ await updateProjectClickhouse(
+ {
+ id: projectId,
+ adminId: userId,
+ },
+ { ignoreAllowedKeys: true },
+ )
+
+ await createProjectShareClickhouse({
+ id: uuidv4(),
+ userId: oldAdminId,
+ projectId: projectId,
+ confirmed: 1,
+ role: Role.admin,
+ })
+
+ await deleteProjectRedis(projectId)
+ }
+
allowedToManage(
project: ProjectWithShare,
uid: string,