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!

Organisations CRUD

Blue Mouse41210c7e7545
diff --git a/backend/apps/cloud/src/action-tokens/action-token.entity.ts b/backend/apps/cloud/src/action-tokens/action-token.entity.ts
index 27dd5ed1a..a57b26eee 100644
--- a/backend/apps/cloud/src/action-tokens/action-token.entity.ts
+++ b/backend/apps/cloud/src/action-tokens/action-token.entity.ts
@@ -15,6 +15,7 @@ export enum ActionTokenType {
PROJECT_SHARE,
ADDING_PROJECT_SUBSCRIBER,
TRANSFER_PROJECT,
+ ORGANISATION_INVITE,
}
@Entity()
diff --git a/backend/apps/cloud/src/app.module.ts b/backend/apps/cloud/src/app.module.ts
index 892998436..c8bcdfb6a 100644
--- a/backend/apps/cloud/src/app.module.ts
+++ b/backend/apps/cloud/src/app.module.ts
@@ -30,6 +30,7 @@ import { IntegrationsModule } from './integrations/integrations.module'
import { HealthModule } from './health/health.module'
import { AppController } from './app.controller'
import { isPrimaryNode, isPrimaryClusterNode } from './common/utils'
+import { OrganisationModule } from './organisation/organisation.module'
const modules = [
SentryModule.forRoot(),
@@ -91,6 +92,7 @@ const modules = [
CaptchaModule,
OgImageModule,
HealthModule,
+ OrganisationModule,
]
@Module({
diff --git a/backend/apps/cloud/src/common/templates/en/organization-invitation.html b/backend/apps/cloud/src/common/templates/en/organization-invitation.html
new file mode 100644
index 000000000..cd5b523af
--- /dev/null
+++ b/backend/apps/cloud/src/common/templates/en/organization-invitation.html
@@ -0,0 +1,12 @@
+
+<a href="mailto:{{email}}">{{email}}</a> has invited you to join the {{name}} organisation with the role {{role}} on Swetrix.
+<br/>
+Click the button below to accept the invitation or ignore this email if you do not want to join the organisation.
+<br/>
+The invitation will expire in {{expiration}} hours.
+<br/>
+<a href="{{url}}" target="_blank">Accept invitation</a>
+<br/>
+If you are having trouble with the button above, copy and paste the URL below directly into your web browser:
+<br/>
+{{url}}
\ No newline at end of file
diff --git a/backend/apps/cloud/src/mailer/letter.ts b/backend/apps/cloud/src/mailer/letter.ts
index 91a333395..0937c8e5b 100644
--- a/backend/apps/cloud/src/mailer/letter.ts
+++ b/backend/apps/cloud/src/mailer/letter.ts
@@ -21,4 +21,5 @@ export enum LetterTemplate {
DashboardLockedExceedingLimits = 'dashboard-locked-exceeding-limits',
DashboardLockedPaymentFailure = 'dashboard-locked-payment-failure',
UptimeMonitoringFailure = 'uptime-monitoring-failure',
+ OrganisationInvitation = 'organisation-invitation',
}
diff --git a/backend/apps/cloud/src/organisation/dto/organisation.dto.ts b/backend/apps/cloud/src/organisation/dto/organisation.dto.ts
new file mode 100644
index 000000000..95fd4efc1
--- /dev/null
+++ b/backend/apps/cloud/src/organisation/dto/organisation.dto.ts
@@ -0,0 +1,21 @@
+import { IsEmail, IsEnum, IsString, Length } from 'class-validator'
+import { OrganisationRole } from '../entity/organisation-member.entity'
+
+export class CreateOrganisationDTO {
+ @IsString()
+ @Length(1, 50)
+ name: string
+}
+
+export class InviteMemberDTO {
+ @IsEmail()
+ email: string
+
+ @IsEnum(OrganisationRole)
+ role: OrganisationRole
+}
+
+export class UpdateMemberRoleDTO {
+ @IsEnum(OrganisationRole)
+ role: OrganisationRole
+}
diff --git a/backend/apps/cloud/src/organisation/entity/organisation-member.entity.ts b/backend/apps/cloud/src/organisation/entity/organisation-member.entity.ts
new file mode 100644
index 000000000..a25b5aa0f
--- /dev/null
+++ b/backend/apps/cloud/src/organisation/entity/organisation-member.entity.ts
@@ -0,0 +1,52 @@
+import {
+ Entity,
+ Column,
+ ManyToOne,
+ BeforeUpdate,
+ PrimaryGeneratedColumn,
+} from 'typeorm'
+import { ApiProperty } from '@nestjs/swagger'
+
+import { User } from '../../user/entities/user.entity'
+import { Organisation } from './organisation.entity'
+
+export enum OrganisationRole {
+ owner = 'owner',
+ admin = 'admin',
+ viewer = 'viewer',
+}
+
+@Entity()
+export class OrganisationMember {
+ @PrimaryGeneratedColumn('uuid')
+ id: string
+
+ @ApiProperty({ type: () => User })
+ @ManyToOne(() => User, user => user.organisationMemberships)
+ user: User
+
+ @ManyToOne(() => Organisation, org => org.members)
+ organisation: Organisation
+
+ @Column({
+ type: 'enum',
+ enum: OrganisationRole,
+ })
+ role: OrganisationRole
+
+ @Column({
+ default: false,
+ })
+ confirmed: boolean
+
+ @Column({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP' })
+ created: Date
+
+ @Column({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP' })
+ updated: Date
+
+ @BeforeUpdate()
+ updateTimestamp() {
+ this.updated = new Date()
+ }
+}
diff --git a/backend/apps/cloud/src/organisation/entity/organisation.entity.ts b/backend/apps/cloud/src/organisation/entity/organisation.entity.ts
new file mode 100644
index 000000000..f6d91f257
--- /dev/null
+++ b/backend/apps/cloud/src/organisation/entity/organisation.entity.ts
@@ -0,0 +1,43 @@
+import {
+ Entity,
+ Column,
+ PrimaryGeneratedColumn,
+ ManyToOne,
+ OneToMany,
+ BeforeUpdate,
+} from 'typeorm'
+import { ApiProperty } from '@nestjs/swagger'
+
+import { User } from '../../user/entities/user.entity'
+import { Project } from '../../project/entity/project.entity'
+import { OrganisationMember } from './organisation-member.entity'
+
+@Entity()
+export class Organisation {
+ @PrimaryGeneratedColumn('uuid')
+ id: string
+
+ @Column('varchar', { length: 50 })
+ name: string
+
+ @ApiProperty({ type: () => User })
+ @ManyToOne(() => User, user => user.ownedOrganisations)
+ owner: User
+
+ @OneToMany(() => OrganisationMember, member => member.organisation)
+ members: OrganisationMember[]
+
+ @OneToMany(() => Project, project => project.organisation)
+ projects: Project[]
+
+ @Column({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP' })
+ created: Date
+
+ @Column({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP' })
+ updated: Date
+
+ @BeforeUpdate()
+ updateTimestamp() {
+ this.updated = new Date()
+ }
+}
diff --git a/backend/apps/cloud/src/organisation/organisation.controller.ts b/backend/apps/cloud/src/organisation/organisation.controller.ts
new file mode 100644
index 000000000..660d7bd12
--- /dev/null
+++ b/backend/apps/cloud/src/organisation/organisation.controller.ts
@@ -0,0 +1,242 @@
+import {
+ Controller,
+ Post,
+ Put,
+ Delete,
+ Body,
+ Param,
+ UseGuards,
+ BadRequestException,
+ NotFoundException,
+ HttpCode,
+ Headers,
+} from '@nestjs/common'
+import { ApiBearerAuth, ApiResponse } from '@nestjs/swagger'
+import { isEmpty as _isEmpty, find as _find } 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'
+import { MailerService } from '../mailer/mailer.service'
+import { ActionTokensService } from '../action-tokens/action-tokens.service'
+import { ActionTokenType } from '../action-tokens/action-token.entity'
+import {
+ CreateOrganisationDTO,
+ InviteMemberDTO,
+ UpdateMemberRoleDTO,
+} from './dto/organisation.dto'
+import { OrganisationRole } from './entity/organisation-member.entity'
+import { AppLoggerService } from '../logger/logger.service'
+import { LetterTemplate } from '../mailer/letter'
+
+const ORGANISATION_INVITE_EXPIRE = 7 * 24 // 7 days in hours
+const { PRODUCTION_ORIGIN, isDevelopment } = process.env
+
+@Controller('organisation')
+export class OrganisationController {
+ constructor(
+ private readonly organisationService: OrganisationService,
+ private readonly userService: UserService,
+ private readonly mailerService: MailerService,
+ private readonly actionTokensService: ActionTokensService,
+ private readonly logger: AppLoggerService,
+ ) {}
+
+ @ApiBearerAuth()
+ @Post('/')
+ @UseGuards(JwtAccessTokenGuard, RolesGuard)
+ @Roles(UserType.CUSTOMER, UserType.ADMIN)
+ @ApiResponse({ status: 200, type: Organisation })
+ async create(
+ @Body() createOrgDTO: CreateOrganisationDTO,
+ @CurrentUserId() uid: string,
+ ): Promise<Organisation> {
+ this.logger.log({ uid, createOrgDTO }, 'POST /organisation')
+
+ const user = await this.userService.findOne({ where: { id: uid } })
+
+ return this.organisationService.create({
+ name: createOrgDTO.name,
+ owner: user,
+ })
+ }
+
+ @ApiBearerAuth()
+ @Post('/:orgId/invite')
+ @HttpCode(200)
+ @UseGuards(JwtAccessTokenGuard, RolesGuard)
+ @Roles(UserType.CUSTOMER, UserType.ADMIN)
+ async inviteMember(
+ @Param('orgId') orgId: string,
+ @Body() inviteDTO: InviteMemberDTO,
+ @CurrentUserId() uid: string,
+ @Headers() headers,
+ ): Promise<Organisation> {
+ this.logger.log(
+ { uid, orgId, inviteDTO },
+ 'POST /organisation/:orgId/invite',
+ )
+
+ const user = await this.userService.findOne({ where: { id: uid } })
+ const organisation = await this.organisationService.findOne({
+ where: { id: orgId },
+ relations: ['owner', 'members', 'members.user'],
+ })
+
+ if (_isEmpty(organisation)) {
+ throw new NotFoundException(
+ `Organisation with ID ${orgId} does not exist`,
+ )
+ }
+
+ await this.organisationService.validateManageAccess(organisation, uid)
+
+ const invitee = await this.userService.findOne({
+ where: { email: inviteDTO.email },
+ relations: ['organisationMemberships'],
+ })
+
+ if (!invitee) {
+ throw new NotFoundException(
+ `User with email ${inviteDTO.email} is not registered`,
+ )
+ }
+
+ if (invitee.id === user.id) {
+ throw new BadRequestException('You cannot invite yourself')
+ }
+
+ const isAlreadyMember = !_isEmpty(
+ _find(organisation.members, member => member.user?.id === invitee.id),
+ )
+
+ if (isAlreadyMember) {
+ throw new BadRequestException(
+ `User ${invitee.email} is already a member of this organisation`,
+ )
+ }
+
+ try {
+ const membership = await this.organisationService.createMembership({
+ role: inviteDTO.role,
+ user: invitee,
+ organisation,
+ })
+
+ const actionToken = await this.actionTokensService.createForUser(
+ user,
+ ActionTokenType.ORGANISATION_INVITE,
+ membership.id,
+ )
+
+ const url = `${
+ isDevelopment ? headers.origin : PRODUCTION_ORIGIN
+ }/organisation/invite/${actionToken.id}`
+
+ await this.mailerService.sendEmail(
+ invitee.email,
+ LetterTemplate.OrganisationInvitation,
+ {
+ url,
+ email: user.email,
+ name: organisation.name,
+ role: membership.role,
+ expiration: ORGANISATION_INVITE_EXPIRE,
+ },
+ )
+
+ return await this.organisationService.findOne({
+ where: { id: orgId },
+ relations: ['members', 'members.user'],
+ })
+ } catch (reason) {
+ console.error(
+ `[ERROR] Could not invite to organisation (orgId: ${organisation.id}, invitee ID: ${invitee.id}): ${reason}`,
+ )
+ throw new BadRequestException(reason)
+ }
+ }
+
+ @ApiBearerAuth()
+ @Put('/member/:memberId')
+ @HttpCode(200)
+ @UseGuards(JwtAccessTokenGuard, RolesGuard)
+ @Roles(UserType.CUSTOMER, UserType.ADMIN)
+ async updateMemberRole(
+ @Param('memberId') memberId: string,
+ @Body() updateDTO: UpdateMemberRoleDTO,
+ @CurrentUserId() uid: string,
+ ) {
+ this.logger.log(
+ { uid, memberId, updateDTO },
+ 'PUT /organisation/member/:memberId',
+ )
+
+ const membership = await this.organisationService.findOneMembership({
+ where: { id: memberId },
+ relations: ['organisation', 'organisation.owner', 'user'],
+ })
+
+ if (_isEmpty(membership)) {
+ throw new NotFoundException(
+ `Membership with ID ${memberId} does not exist`,
+ )
+ }
+
+ await this.organisationService.validateManageAccess(
+ membership.organisation,
+ uid,
+ )
+
+ if (membership.user.id === uid) {
+ throw new BadRequestException('You cannot modify your own role')
+ }
+
+ if (membership.role === OrganisationRole.owner) {
+ throw new BadRequestException('Cannot modify owner role')
+ }
+
+ return this.organisationService.updateMembership(memberId, {
+ role: updateDTO.role,
+ })
+ }
+
+ @ApiBearerAuth()
+ @Delete('/member/:memberId')
+ @HttpCode(204)
+ @UseGuards(JwtAccessTokenGuard, RolesGuard)
+ @Roles(UserType.CUSTOMER, UserType.ADMIN)
+ async removeMember(
+ @Param('memberId') memberId: string,
+ @CurrentUserId() uid: string,
+ ) {
+ this.logger.log({ uid, memberId }, 'DELETE /organisation/member/:memberId')
+
+ const membership = await this.organisationService.findOneMembership({
+ where: { id: memberId },
+ relations: ['organisation', 'organisation.owner', 'user'],
+ })
+
+ if (_isEmpty(membership)) {
+ throw new NotFoundException(
+ `Membership with ID ${memberId} does not exist`,
+ )
+ }
+
+ await this.organisationService.validateManageAccess(
+ membership.organisation,
+ uid,
+ )
+
+ if (membership.role === OrganisationRole.owner) {
+ throw new BadRequestException('Cannot remove organisation owner')
+ }
+
+ await this.organisationService.deleteMembership(memberId)
+ }
+}
diff --git a/backend/apps/cloud/src/organisation/organisation.module.ts b/backend/apps/cloud/src/organisation/organisation.module.ts
new file mode 100644
index 000000000..854decf8c
--- /dev/null
+++ b/backend/apps/cloud/src/organisation/organisation.module.ts
@@ -0,0 +1,22 @@
+import { Module } from '@nestjs/common'
+import { TypeOrmModule } from '@nestjs/typeorm'
+import { Organisation } from './entity/organisation.entity'
+import { OrganisationMember } from './entity/organisation-member.entity'
+import { OrganisationController } from './organisation.controller'
+import { OrganisationService } from './organisation.service'
+import { UserModule } from '../user/user.module'
+import { MailerModule } from '../mailer/mailer.module'
+import { ActionTokensModule } from '../action-tokens/action-tokens.module'
+
+@Module({
+ imports: [
+ TypeOrmModule.forFeature([Organisation, OrganisationMember]),
+ UserModule,
+ MailerModule,
+ ActionTokensModule,
+ ],
+ controllers: [OrganisationController],
+ providers: [OrganisationService],
+ exports: [OrganisationService],
+})
+export class OrganisationModule {}
diff --git a/backend/apps/cloud/src/organisation/organisation.service.ts b/backend/apps/cloud/src/organisation/organisation.service.ts
new file mode 100644
index 000000000..bc2bf6528
--- /dev/null
+++ b/backend/apps/cloud/src/organisation/organisation.service.ts
@@ -0,0 +1,72 @@
+import { Injectable, ForbiddenException } from '@nestjs/common'
+import { InjectRepository } from '@nestjs/typeorm'
+import { Repository } from 'typeorm'
+import { find as _find } from 'lodash'
+
+import { Organisation } from './entity/organisation.entity'
+import {
+ OrganisationMember,
+ OrganisationRole,
+} from './entity/organisation-member.entity'
+
+@Injectable()
+export class OrganisationService {
+ constructor(
+ @InjectRepository(Organisation)
+ private organisationRepository: Repository<Organisation>,
+ @InjectRepository(OrganisationMember)
+ private membershipRepository: Repository<OrganisationMember>,
+ ) {}
+
+ async create(data: Partial<Organisation>): Promise<Organisation> {
+ const org = this.organisationRepository.create(data)
+ return this.organisationRepository.save(org)
+ }
+
+ async findOne(options: any): Promise<Organisation> {
+ return this.organisationRepository.findOne(options)
+ }
+
+ async createMembership(
+ data: Partial<OrganisationMember>,
+ ): Promise<OrganisationMember> {
+ const membership = this.membershipRepository.create(data)
+ return this.membershipRepository.save(membership)
+ }
+
+ async findOneMembership(options: any): Promise<OrganisationMember> {
+ return this.membershipRepository.findOne(options)
+ }
+
+ async updateMembership(
+ id: string,
+ data: Partial<OrganisationMember>,
+ ): Promise<OrganisationMember> {
+ await this.membershipRepository.update(id, data)
+ return this.findOneMembership({ where: { id } })
+ }
+
+ async deleteMembership(id: string): Promise<void> {
+ await this.membershipRepository.delete(id)
+ }
+
+ async validateManageAccess(
+ organisation: Organisation,
+ userId: string,
+ ): Promise<void> {
+ if (organisation.owner.id === userId) {
+ return
+ }
+
+ const membership = _find(
+ organisation.members,
+ member => member.user?.id === userId,
+ )
+
+ if (!membership || membership.role === OrganisationRole.viewer) {
+ throw new ForbiddenException(
+ 'You do not have permission to manage this organisation',
+ )
+ }
+ }
+}
diff --git a/backend/apps/cloud/src/project/entity/project.entity.ts b/backend/apps/cloud/src/project/entity/project.entity.ts
index 725f9fd73..819795784 100644
--- a/backend/apps/cloud/src/project/entity/project.entity.ts
+++ b/backend/apps/cloud/src/project/entity/project.entity.ts
@@ -17,6 +17,7 @@ import { Funnel } from './funnel.entity'
import { CAPTCHA_SECRET_KEY_LENGTH } from '../../common/constants'
import { ProjectViewEntity } from './project-view.entity'
import { MonitorEntity } from './monitor.entity'
+import { Organisation } from '../../organisation/entity/organisation.entity'
export enum BotsProtectionLevel {
OFF = 'off',
@@ -134,4 +135,7 @@ export class Project {
@OneToMany(() => MonitorEntity, monitor => monitor.id)
monitors: MonitorEntity[]
+
+ @ManyToOne(() => Organisation, org => org.projects, { nullable: true })
+ organisation: Organisation | null
}
diff --git a/backend/apps/cloud/src/user/entities/user.entity.ts b/backend/apps/cloud/src/user/entities/user.entity.ts
index 459feaf4a..88857fed2 100644
--- a/backend/apps/cloud/src/user/entities/user.entity.ts
+++ b/backend/apps/cloud/src/user/entities/user.entity.ts
@@ -16,6 +16,8 @@ import { Comment } from '../../marketplace/comments/entities/comment.entity'
import { CommentReply } from '../../marketplace/comments/entities/comment-reply.entity'
import { Complaint } from '../../marketplace/complaints/entities/complaint.entity'
import { RefreshToken } from './refresh-token.entity'
+import { Organisation } from '../../organisation/entity/organisation.entity'
+import { OrganisationMember } from '../../organisation/entity/organisation-member.entity'
export enum PlanCode {
none = 'none',
@@ -451,4 +453,10 @@ export class User {
@OneToMany(() => RefreshToken, refreshToken => refreshToken.user)
@JoinTable()
refreshTokens: RefreshToken[]
+
+ @OneToMany(() => Organisation, org => org.owner)
+ ownedOrganisations: Organisation[]
+
+ @OneToMany(() => OrganisationMember, membership => membership.user)
+ organisationMemberships: OrganisationMember[]
}