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!

feat: enhance organisation and project management functionality

Blue Mouse09b42cbf912e
diff --git a/backend/apps/cloud/src/organisation/organisation.controller.ts b/backend/apps/cloud/src/organisation/organisation.controller.ts
index 247245cf5..08d273dc5 100644
--- a/backend/apps/cloud/src/organisation/organisation.controller.ts
+++ b/backend/apps/cloud/src/organisation/organisation.controller.ts
@@ -15,7 +15,7 @@ import {
} from '@nestjs/common'
import { ApiBearerAuth, ApiQuery, ApiResponse } from '@nestjs/swagger'
import { isEmpty as _isEmpty, find as _find } from 'lodash'
-import { FindOptionsWhere, ILike } from 'typeorm'
+import { FindOptionsWhere, ILike, In } from 'typeorm'
import { JwtAccessTokenGuard } from '../auth/guards/jwt-access-token.guard'
import { RolesGuard } from '../auth/guards/roles.guard'
@@ -73,7 +73,7 @@ export class OrganisationController {
where = {
members: {
user: { id: userId },
- role: OrganisationRole.owner,
+ role: In([OrganisationRole.owner, OrganisationRole.admin]),
},
name: ILike(`%${search}%`),
}
@@ -81,7 +81,7 @@ export class OrganisationController {
where = {
members: {
user: { id: userId },
- role: OrganisationRole.owner,
+ role: In([OrganisationRole.owner, OrganisationRole.admin]),
},
}
}
@@ -99,6 +99,7 @@ export class OrganisationController {
@ApiResponse({ status: 200, type: Organisation })
@Auth([], true)
async getOne(@Param('orgId') orgId: string): Promise<Organisation> {
+ // todo: add access control
return this.organisationService.findOne({
where: { id: orgId },
select: {
@@ -165,7 +166,7 @@ export class OrganisationController {
const user = await this.userService.findOne({ where: { id: uid } })
const organisation = await this.organisationService.findOne({
where: { id: orgId },
- relations: ['owner', 'members', 'members.user'],
+ relations: ['members', 'members.user'],
})
if (_isEmpty(organisation)) {
diff --git a/backend/apps/cloud/src/organisation/organisation.module.ts b/backend/apps/cloud/src/organisation/organisation.module.ts
index 4a3196433..8bcbd34f2 100644
--- a/backend/apps/cloud/src/organisation/organisation.module.ts
+++ b/backend/apps/cloud/src/organisation/organisation.module.ts
@@ -1,4 +1,4 @@
-import { Module } from '@nestjs/common'
+import { Module, forwardRef } from '@nestjs/common'
import { TypeOrmModule } from '@nestjs/typeorm'
import { Organisation } from './entity/organisation.entity'
import { OrganisationMember } from './entity/organisation-member.entity'
@@ -12,7 +12,7 @@ import { AppLoggerModule } from '../logger/logger.module'
@Module({
imports: [
TypeOrmModule.forFeature([Organisation, OrganisationMember]),
- UserModule,
+ forwardRef(() => UserModule),
MailerModule,
ActionTokensModule,
AppLoggerModule,
diff --git a/backend/apps/cloud/src/organisation/organisation.service.ts b/backend/apps/cloud/src/organisation/organisation.service.ts
index 028d8c437..e9d40ae84 100644
--- a/backend/apps/cloud/src/organisation/organisation.service.ts
+++ b/backend/apps/cloud/src/organisation/organisation.service.ts
@@ -1,6 +1,11 @@
import { Injectable, ForbiddenException } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
-import { FindOneOptions, FindOptionsWhere, Repository } from 'typeorm'
+import {
+ FindManyOptions,
+ FindOneOptions,
+ FindOptionsWhere,
+ Repository,
+} from 'typeorm'
import { find as _find } from 'lodash'
import { Organisation } from './entity/organisation.entity'
@@ -28,6 +33,10 @@ export class OrganisationService {
return this.organisationRepository.findOne(options)
}
+ async find(options: FindManyOptions<Organisation>): Promise<Organisation[]> {
+ return this.organisationRepository.find(options)
+ }
+
async createMembership(
data: Partial<OrganisationMember>,
): Promise<OrganisationMember> {
@@ -69,6 +78,43 @@ export class OrganisationService {
}
}
+ async canManageOrganisation(
+ organisationId: string,
+ userId: string,
+ ): Promise<boolean> {
+ const organisation = await this.findOne({
+ where: { id: organisationId },
+ relations: ['members', 'members.user'],
+ })
+
+ if (!organisation) {
+ return false
+ }
+
+ try {
+ this.validateManageAccess(organisation, userId)
+ return true
+ } catch {
+ return false
+ }
+ }
+
+ async getOrganisationOwner(organisationId: string) {
+ const ownerMembership = await this.findOneMembership({
+ where: {
+ organisation: { id: organisationId },
+ role: OrganisationRole.owner,
+ },
+ relations: ['user'],
+ })
+
+ if (!ownerMembership) {
+ throw new ForbiddenException('Organisation owner not found')
+ }
+
+ return ownerMembership.user
+ }
+
async paginate(
options: PaginationOptionsInterface,
where?: FindOptionsWhere<Organisation> | FindOptionsWhere<Organisation>[],
@@ -80,7 +126,7 @@ export class OrganisationService {
order: {
name: 'ASC',
},
- relations: ['owner', 'members'],
+ relations: ['members'],
})
return new Pagination<Organisation>({
diff --git a/backend/apps/cloud/src/project/dto/create-project.dto.ts b/backend/apps/cloud/src/project/dto/create-project.dto.ts
index 24ba5b2ef..93a5bd8ca 100644
--- a/backend/apps/cloud/src/project/dto/create-project.dto.ts
+++ b/backend/apps/cloud/src/project/dto/create-project.dto.ts
@@ -16,6 +16,11 @@ export class CreateProjectDTO {
})
isCaptcha?: boolean
+ @ApiProperty({
+ required: false,
+ })
+ organisationId?: string
+
@ApiProperty({
required: false,
})
diff --git a/backend/apps/cloud/src/project/project.controller.ts b/backend/apps/cloud/src/project/project.controller.ts
index ee652fb59..efe9538ce 100644
--- a/backend/apps/cloud/src/project/project.controller.ts
+++ b/backend/apps/cloud/src/project/project.controller.ts
@@ -113,6 +113,8 @@ 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'
+import { OrganisationService } from '../organisation/organisation.service'
+import { Organisation } from '../organisation/entity/organisation.entity'
const PROJECTS_MAXIMUM = 50
@@ -134,6 +136,7 @@ export class ProjectController {
private readonly actionTokensService: ActionTokensService,
private readonly mailerService: MailerService,
private readonly projectsViewsRepository: ProjectsViewsRepository,
+ private readonly organisationService: OrganisationService,
) {}
@ApiBearerAuth()
@@ -409,23 +412,42 @@ export class ProjectController {
async create(
@Body() projectDTO: CreateProjectDTO,
@CurrentUserId() userId: string,
- ): Promise<Project> {
+ ): Promise<Omit<Project, 'passwordHash'>> {
this.logger.log({ projectDTO, userId }, 'POST /project')
if (!userId) {
throw new UnauthorizedException('Please auth first')
}
- const user = await this.userService.findOne({
+ const initiatingUser = await this.userService.findOne({
where: { id: userId },
relations: ['projects'],
})
- const { maxProjects = PROJECTS_MAXIMUM } = user
+ const { maxProjects = PROJECTS_MAXIMUM } = initiatingUser
- if (!user.isActive) {
+ if (!initiatingUser.isActive) {
throw new ForbiddenException('Please, verify your email address first')
}
+ let user = initiatingUser
+
+ if (projectDTO.organisationId) {
+ const canManage = await this.organisationService.canManageOrganisation(
+ projectDTO.organisationId,
+ userId,
+ )
+
+ if (!canManage) {
+ throw new ForbiddenException(
+ 'You are not allowed to add projects to the selected organisation',
+ )
+ }
+
+ user = await this.organisationService.getOrganisationOwner(
+ projectDTO.organisationId,
+ )
+ }
+
if (user.planCode === PlanCode.none) {
throw new HttpException(
'You cannot create new projects due to no active subscription. Please upgrade your account plan to continue.',
@@ -476,10 +498,16 @@ export class ProjectController {
}
try {
- const project = new Project()
- project.id = pid
- project.name = _trim(projectDTO.name)
- project.origins = []
+ const project = {
+ id: pid,
+ name: _trim(projectDTO.name),
+ origins: [],
+ active: true,
+
+ admin: {
+ id: user.id,
+ },
+ } as Project
if (projectDTO.isCaptcha) {
project.isCaptchaProject = true
@@ -490,35 +518,14 @@ export class ProjectController {
)
}
- if (projectDTO.isPasswordProtected && projectDTO.password) {
- project.isPasswordProtected = true
- project.passwordHash = await hash(projectDTO.password, 10)
- }
-
- if (projectDTO.public) {
- project.public = Boolean(projectDTO.public)
- }
-
- if (projectDTO.active) {
- project.active = Boolean(projectDTO.active)
- }
-
- if (projectDTO.origins) {
- this.projectService.validateOrigins(projectDTO)
- project.origins = projectDTO.origins
- }
-
- if (projectDTO.ipBlacklist) {
- this.projectService.validateIPBlacklist(projectDTO)
- project.ipBlacklist = projectDTO.ipBlacklist
+ if (projectDTO.organisationId) {
+ project.organisation = {
+ id: projectDTO.organisationId,
+ } as Organisation
}
const newProject = await this.projectService.create(project)
- user.projects.push(project)
- await this.userService.create(user)
-
- // @ts-expect-error
return _omit(newProject, ['passwordHash'])
} catch (reason) {
console.error('[ERROR] Failed to create a new project:')
@@ -2417,7 +2424,7 @@ export class ProjectController {
@Param('monitorId') monitorId: number,
@Body() body: UpdateMonitorHttpRequestDTO,
@CurrentUserId() userId: string,
- ): Promise<MonitorEntity> {
+ ): Promise<void> {
const project = await this.projectService.findProject(projectId, [
'admin',
'share',
diff --git a/backend/apps/cloud/src/project/project.module.ts b/backend/apps/cloud/src/project/project.module.ts
index f370df0c7..d0945a5f2 100644
--- a/backend/apps/cloud/src/project/project.module.ts
+++ b/backend/apps/cloud/src/project/project.module.ts
@@ -17,6 +17,7 @@ import { ProjectViewEntity } from './entity/project-view.entity'
import { ProjectViewCustomEventEntity } from './entity/project-view-custom-event.entity'
import { MonitorConsumer } from './consumers/monitor.consumer'
import { MonitorEntity } from './entity/monitor.entity'
+import { OrganisationModule } from '../organisation/organisation.module'
@Module({
imports: [
@@ -30,6 +31,7 @@ import { MonitorEntity } from './entity/monitor.entity'
MonitorEntity,
]),
forwardRef(() => UserModule),
+ forwardRef(() => OrganisationModule),
HttpModule.registerAsync({
imports: [ConfigModule],
inject: [ConfigService],
diff --git a/backend/apps/cloud/src/project/project.service.ts b/backend/apps/cloud/src/project/project.service.ts
index e1a580a22..1dec435db 100644
--- a/backend/apps/cloud/src/project/project.service.ts
+++ b/backend/apps/cloud/src/project/project.service.ts
@@ -14,6 +14,7 @@ import {
FindOneOptions,
FindOptionsWhere,
Repository,
+ DeepPartial,
} from 'typeorm'
import { customAlphabet } from 'nanoid'
import handlebars from 'handlebars'
@@ -459,19 +460,19 @@ export class ProjectService {
return this.projectsRepository.count()
}
- async create(project: ProjectDTO | Project): Promise<Project> {
+ async create(project: DeepPartial<Project>) {
return this.projectsRepository.save(project)
}
- async update(id: string, projectDTO: ProjectDTO | Project): Promise<any> {
+ async update(id: string, projectDTO: ProjectDTO | Project) {
return this.projectsRepository.update(id, projectDTO)
}
- async delete(id: string): Promise<any> {
+ async delete(id: string) {
return this.projectsRepository.delete(id)
}
- async deleteMultiple(pids: string[]): Promise<any> {
+ async deleteMultiple(pids: string[]) {
return this.projectsRepository
.createQueryBuilder()
.delete()
@@ -479,7 +480,7 @@ export class ProjectService {
.execute()
}
- async deleteMultipleShare(where: string): Promise<any> {
+ async deleteMultipleShare(where: string) {
return this.projectShareRepository
.createQueryBuilder()
.delete()
@@ -491,11 +492,11 @@ export class ProjectService {
return this.projectShareRepository.save(share)
}
- async deleteShare(id: string): Promise<any> {
+ async deleteShare(id: string) {
return this.projectShareRepository.delete(id)
}
- async updateShare(id: string, share: ProjectShare | object): Promise<any> {
+ async updateShare(id: string, share: ProjectShare | object) {
return this.projectShareRepository.update(id, share)
}
@@ -1367,14 +1368,14 @@ export class ProjectService {
await Promise.all([
document.fonts.ready,
...selectors.map(img => {
- // Image has already finished loading, let’s see if it worked
+ // Image has already finished loading, let's see if it worked
if (img.complete) {
// Image loaded and has presence
if (img.naturalHeight !== 0) return
// Image failed, so it has no height
throw new Error('Image failed to load')
}
- // Image hasn’t loaded yet, added an event listener to know when it does
+ // Image hasn't loaded yet, added an event listener to know when it does
// eslint-disable-next-line consistent-return
return new Promise((resolve, reject) => {
img.addEventListener('load', resolve)
@@ -1564,7 +1565,7 @@ export class ProjectService {
description,
httpOptions,
}: UpdateMonitorHttpRequestDTO,
- ): Promise<any> {
+ ): Promise<void> {
await this.monitorRepository.update(
{ id: monitorId },
{
@@ -1582,7 +1583,7 @@ export class ProjectService {
)
}
- async deleteMonitor(monitorId: number): Promise<any> {
+ async deleteMonitor(monitorId: number) {
return this.monitorRepository.delete(monitorId)
}
diff --git a/backend/apps/cloud/src/user/user.controller.ts b/backend/apps/cloud/src/user/user.controller.ts
index 7d825d965..340b3dab0 100644
--- a/backend/apps/cloud/src/user/user.controller.ts
+++ b/backend/apps/cloud/src/user/user.controller.ts
@@ -76,6 +76,7 @@ import {
} from '../common/utils'
import { IUsageInfo, IMetaInfo } from './interfaces'
import { ReportFrequency } from '../project/enums'
+import { Organisation } from '../organisation/entity/organisation.entity'
dayjs.extend(utc)
@@ -100,24 +101,31 @@ export class UserController {
@Get('/me')
@UseGuards(RolesGuard)
@Roles(UserType.CUSTOMER, UserType.ADMIN)
- async me(@CurrentUserId() uid: string): Promise<Partial<User>> {
+ async me(@CurrentUserId() uid: string) {
this.logger.log({ uid }, 'GET /user/me')
- const sharedProjects = await this.projectService.findShare({
- where: {
- user: {
- id: uid,
+ const [sharedProjects, manageableOrganisations, user] = await Promise.all([
+ this.projectService.findShare({
+ where: {
+ user: {
+ id: uid,
+ },
},
- },
- relations: ['project'],
- })
- const user = this.userService.omitSensitiveData(
- await this.userService.findOne({ where: { id: uid } }),
- )
+ relations: ['project'],
+ }),
+ this.userService.getManagableOrganisations(uid),
+ this.userService.findOne({ where: { id: uid } }),
+ ])
- user.sharedProjects = sharedProjects
+ const sanitizedUser = this.userService.omitSensitiveData(
+ user,
+ ) as Partial<User> & {
+ managableOrganisations: Organisation[]
+ }
+ sanitizedUser.sharedProjects = sharedProjects
+ sanitizedUser.managableOrganisations = manageableOrganisations
- return user
+ return sanitizedUser
}
@ApiBearerAuth()
diff --git a/backend/apps/cloud/src/user/user.module.ts b/backend/apps/cloud/src/user/user.module.ts
index b7bbd6967..8e2d8463a 100644
--- a/backend/apps/cloud/src/user/user.module.ts
+++ b/backend/apps/cloud/src/user/user.module.ts
@@ -15,6 +15,7 @@ import { ProjectModule } from '../project/project.module'
import { RefreshToken } from './entities/refresh-token.entity'
import { DeleteFeedback } from './entities/delete-feedback.entity'
import { Message } from '../integrations/telegram/entities/message.entity'
+import { OrganisationModule } from '../organisation/organisation.module'
@Module({
imports: [
@@ -24,6 +25,7 @@ import { Message } from '../integrations/telegram/entities/message.entity'
forwardRef(() => AuthModule),
AppLoggerModule,
ProjectModule,
+ OrganisationModule,
PayoutsModule,
HttpModule,
],
diff --git a/backend/apps/cloud/src/user/user.service.ts b/backend/apps/cloud/src/user/user.service.ts
index e310eea32..b655a68e9 100644
--- a/backend/apps/cloud/src/user/user.service.ts
+++ b/backend/apps/cloud/src/user/user.service.ts
@@ -40,6 +40,8 @@ import { UserGoogleDTO } from './dto/user-google.dto'
import { UserGithubDTO } from './dto/user-github.dto'
import { EMAIL_ACTION_ENCRYPTION_KEY } from '../common/constants'
import { ReportFrequency } from '../project/enums'
+import { OrganisationService } from '../organisation/organisation.service'
+import { OrganisationRole } from '../organisation/entity/organisation-member.entity'
dayjs.extend(utc)
@@ -109,6 +111,7 @@ export class UserService {
@InjectRepository(DeleteFeedback)
private readonly deleteFeedbackRepository: Repository<DeleteFeedback>,
private readonly payoutsService: PayoutsService,
+ private readonly organisationService: OrganisationService,
) {}
async create(
@@ -135,6 +138,18 @@ export class UserService {
return this.usersRepository.update({ id }, update)
}
+ async getManagableOrganisations(userId: string) {
+ return this.organisationService.find({
+ where: {
+ members: {
+ user: { id: userId },
+ role: In([OrganisationRole.owner, OrganisationRole.admin]),
+ },
+ },
+ select: ['id', 'name'],
+ })
+ }
+
async updateByEmail(
email: string,
update: Record<string, unknown>,