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: Allow inviting people to projects / orgs who are not signed up on Swetrix

Blue Mouse50b81186cd4f
diff --git a/backend/apps/cloud/src/app.module.ts b/backend/apps/cloud/src/app.module.ts
index fb04ce0d4..6068b9f0d 100644
--- a/backend/apps/cloud/src/app.module.ts
+++ b/backend/apps/cloud/src/app.module.ts
@@ -33,6 +33,7 @@ import { isPrimaryNode, isPrimaryClusterNode } from './common/utils'
import { OrganisationModule } from './organisation/organisation.module'
import { RevenueModule } from './revenue/revenue.module'
import { ToolsModule } from './tools/tools.module'
+import { PendingInvitationModule } from './pending-invitation/pending-invitation.module'
const modules = [
SentryModule.forRoot(),
@@ -90,6 +91,7 @@ const modules = [
OrganisationModule,
RevenueModule,
ToolsModule,
+ PendingInvitationModule,
]
@Module({
diff --git a/backend/apps/cloud/src/auth/auth.controller.ts b/backend/apps/cloud/src/auth/auth.controller.ts
index 2ce0e04b0..66ec516d7 100644
--- a/backend/apps/cloud/src/auth/auth.controller.ts
+++ b/backend/apps/cloud/src/auth/auth.controller.ts
@@ -8,6 +8,8 @@ import {
Delete,
Body,
Ip,
+ Inject,
+ forwardRef,
ConflictException,
HttpCode,
HttpStatus,
@@ -15,6 +17,7 @@ import {
Param,
UnauthorizedException,
BadRequestException,
+ NotFoundException,
Headers,
} from '@nestjs/common'
import {
@@ -50,6 +53,7 @@ import {
SSOUnlinkDto,
SSOProviders,
SSOLinkWithPasswordDto,
+ RegisterInvitationRequestDto,
} from './dtos'
import {
JwtAccessTokenGuard,
@@ -58,6 +62,10 @@ import {
} from './guards'
import { ProjectService } from '../project/project.service'
import { trackCustom } from '../common/analytics'
+import { PendingInvitationService } from '../pending-invitation/pending-invitation.service'
+import { PendingInvitationType } from '../pending-invitation/pending-invitation.entity'
+import { ProjectShare } from '../project/entity/project-share.entity'
+import { OrganisationService } from '../organisation/organisation.service'
const OAUTH_RATE_LIMIT = 15
@@ -78,6 +86,9 @@ export class AuthController {
private readonly userService: UserService,
private readonly authService: AuthService,
private readonly projectService: ProjectService,
+ private readonly pendingInvitationService: PendingInvitationService,
+ @Inject(forwardRef(() => OrganisationService))
+ private readonly organisationService: OrganisationService,
) {}
@ApiOperation({ summary: 'Register a new user' })
@@ -434,6 +445,177 @@ export class AuthController {
await this.authService.logoutAll(user.id)
}
+ @ApiOperation({ summary: 'Get pending invitation details' })
+ @ApiOkResponse({ description: 'Invitation details returned' })
+ @Public()
+ @Get('invitation/:id')
+ public async getInvitationDetails(@Param('id') id: string) {
+ const invitation = await this.pendingInvitationService.findById(id)
+
+ if (!invitation) {
+ throw new NotFoundException('Invitation not found or has expired')
+ }
+
+ const inviter = await this.userService.findUserById(invitation.inviterId)
+
+ let targetName = ''
+
+ if (
+ invitation.type === PendingInvitationType.PROJECT_SHARE &&
+ invitation.projectId
+ ) {
+ const project = await this.projectService.findOne({
+ where: { id: invitation.projectId },
+ })
+ targetName = project?.name || ''
+ } else if (
+ invitation.type === PendingInvitationType.ORGANISATION_MEMBER &&
+ invitation.organisationId
+ ) {
+ const organisation = await this.organisationService.findOne({
+ where: { id: invitation.organisationId },
+ })
+ targetName = organisation?.name || ''
+ }
+
+ return {
+ id: invitation.id,
+ email: invitation.email,
+ type: invitation.type,
+ role: invitation.role,
+ inviterEmail: inviter?.email || '',
+ targetName,
+ }
+ }
+
+ @ApiOperation({ summary: 'Register a new user via invitation' })
+ @ApiCreatedResponse({
+ description: 'User registered via invitation',
+ type: RegisterResponseDto,
+ })
+ @Public()
+ @Post('register/invitation')
+ public async registerViaInvitation(
+ @Body() body: RegisterInvitationRequestDto,
+ @I18n() i18n: I18nContext,
+ @Headers() headers: Record<string, string>,
+ @Ip() requestIp: string,
+ ) {
+ const ip = getIPFromHeaders(headers) || requestIp || ''
+
+ await checkRateLimit(ip, 'register', 5)
+
+ const invitation = await this.pendingInvitationService.findById(
+ body.pendingInvitationId,
+ )
+
+ if (!invitation) {
+ throw new NotFoundException('Invitation not found or has expired')
+ }
+
+ if (invitation.email !== body.email) {
+ throw new BadRequestException('Email does not match the invitation')
+ }
+
+ const existingUser = await this.userService.findUser(body.email)
+
+ if (existingUser) {
+ throw new ConflictException(i18n.t('user.emailAlreadyUsed'))
+ }
+
+ if (body.checkIfLeaked) {
+ const isLeaked = await this.authService.checkIfLeaked(body.password)
+
+ if (isLeaked) {
+ throw new ConflictException(
+ 'The provided password is leaked, please use another one',
+ )
+ }
+ }
+
+ if (body.email === body.password) {
+ throw new ConflictException(i18n.t('auth.passwordSameAsEmail'))
+ }
+
+ const newUser = await this.authService.createUnverifiedUser(
+ body.email,
+ body.password,
+ )
+
+ await this.userService.updateUser(newUser.id, {
+ hasCompletedOnboarding: true,
+ registeredViaInvitation: true,
+ })
+
+ const allPendingInvitations =
+ await this.pendingInvitationService.findByEmail(body.email)
+
+ for (const pending of allPendingInvitations) {
+ if (
+ pending.type === PendingInvitationType.PROJECT_SHARE &&
+ pending.projectId
+ ) {
+ const project = await this.projectService.findOne({
+ where: { id: pending.projectId },
+ relations: ['share'],
+ })
+
+ if (project) {
+ const share = new ProjectShare()
+ share.role = pending.role as any
+ share.user = newUser
+ share.project = project
+ share.confirmed = true
+
+ await this.projectService.createShare(share)
+ }
+ } else if (
+ pending.type === PendingInvitationType.ORGANISATION_MEMBER &&
+ pending.organisationId
+ ) {
+ const organisation = await this.organisationService.findOne({
+ where: { id: pending.organisationId },
+ })
+
+ if (organisation) {
+ await this.organisationService.createMembership({
+ role: pending.role as any,
+ user: newUser,
+ organisation,
+ confirmed: true,
+ })
+ }
+ }
+ }
+
+ await this.pendingInvitationService.deleteAllByEmail(body.email)
+
+ await trackCustom(ip, headers['user-agent'], {
+ ev: 'SIGNUP',
+ meta: {
+ method: 'invitation',
+ },
+ })
+
+ const jwtTokens = await this.authService.generateJwtTokens(newUser.id, true)
+
+ const updatedUser = await this.userService.findUserById(newUser.id)
+
+ const [sharedProjects, organisationMemberships] = await Promise.all([
+ this.authService.getSharedProjectsForUser(newUser.id),
+ this.userService.getOrganisationsForUser(newUser.id),
+ ])
+
+ updatedUser.sharedProjects = sharedProjects
+ updatedUser.organisationMemberships = organisationMemberships
+
+ return {
+ ...jwtTokens,
+ user: this.userService.omitSensitiveData(updatedUser),
+ totalMonthlyEvents: 0,
+ }
+ }
+
// SSO section
@ApiOperation({ summary: 'Generate SSO authentication URL' })
@Post('sso/generate')
diff --git a/backend/apps/cloud/src/auth/auth.module.ts b/backend/apps/cloud/src/auth/auth.module.ts
index d7834331c..3ec6f6c34 100644
--- a/backend/apps/cloud/src/auth/auth.module.ts
+++ b/backend/apps/cloud/src/auth/auth.module.ts
@@ -16,6 +16,8 @@ import {
JwtRefreshTokenStrategy,
} from './strategies'
import { Message } from '../integrations/telegram/entities/message.entity'
+import { PendingInvitationModule } from '../pending-invitation/pending-invitation.module'
+import { OrganisationModule } from '../organisation/organisation.module'
@Module({
imports: [
@@ -28,6 +30,8 @@ import { Message } from '../integrations/telegram/entities/message.entity'
ProjectModule,
forwardRef(() => TwoFactorAuthModule),
TypeOrmModule.forFeature([Message]),
+ PendingInvitationModule,
+ forwardRef(() => OrganisationModule),
],
controllers: [AuthController],
providers: [
diff --git a/backend/apps/cloud/src/auth/dtos/index.ts b/backend/apps/cloud/src/auth/dtos/index.ts
index 4424503d2..7e1cd40ad 100644
--- a/backend/apps/cloud/src/auth/dtos/index.ts
+++ b/backend/apps/cloud/src/auth/dtos/index.ts
@@ -12,3 +12,4 @@ export * from './sso-get-jwt-by-hash.dto'
export * from './sso-link.dto'
export * from './sso-unlink.dto'
export * from './sso-link-with-password.dto'
+export * from './register-invitation.dto'
diff --git a/backend/apps/cloud/src/auth/dtos/register-invitation.dto.ts b/backend/apps/cloud/src/auth/dtos/register-invitation.dto.ts
new file mode 100644
index 000000000..fffaf03f2
--- /dev/null
+++ b/backend/apps/cloud/src/auth/dtos/register-invitation.dto.ts
@@ -0,0 +1,45 @@
+import { ApiProperty } from '@nestjs/swagger'
+import {
+ IsEmail,
+ IsNotEmpty,
+ IsBoolean,
+ IsUUID,
+ MaxLength,
+ MinLength,
+} from 'class-validator'
+
+export class RegisterInvitationRequestDto {
+ @ApiProperty({
+ description: 'Pending invitation ID',
+ })
+ @IsNotEmpty()
+ @IsUUID('4')
+ public readonly pendingInvitationId: string
+
+ @ApiProperty({
+ description: 'User email',
+ example: '[email protected]',
+ maxLength: 254,
+ minLength: 6,
+ })
+ @IsEmail({}, { message: 'Please enter the valid email.' })
+ public readonly email: string
+
+ @ApiProperty({
+ description: 'User password',
+ example: '%d7*c4W45p',
+ maxLength: 72,
+ minLength: 8,
+ })
+ @MaxLength(50, { message: 'Max length is $constraint1 characters' })
+ @MinLength(8, { message: 'Min length is $constraint1 characters' })
+ public readonly password: string
+
+ @ApiProperty({
+ description: 'Check if password is leaked',
+ example: true,
+ })
+ @IsNotEmpty({ message: 'This field is required.' })
+ @IsBoolean({ message: 'Please enter the valid value (true or false).' })
+ public readonly checkIfLeaked: boolean
+}
diff --git a/backend/apps/cloud/src/common/templates/en/organisation-invitation-unregistered.html b/backend/apps/cloud/src/common/templates/en/organisation-invitation-unregistered.html
new file mode 100644
index 000000000..fe04b1705
--- /dev/null
+++ b/backend/apps/cloud/src/common/templates/en/organisation-invitation-unregistered.html
@@ -0,0 +1,14 @@
+<a href="mailto:{{email}}">{{email}}</a> has invited you to join the {{name}}
+organisation with the role {{role}} on Swetrix.
+<br />
+You don't have a Swetrix account yet, but you can create one to accept the
+invitation.
+<br />
+Click the button below to create your account and join the organisation.
+<br />
+<a href="{{url}}" target="_blank">Create account & 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}}
diff --git a/backend/apps/cloud/src/common/templates/en/project-invitation-unregistered.html b/backend/apps/cloud/src/common/templates/en/project-invitation-unregistered.html
new file mode 100644
index 000000000..329c0a5de
--- /dev/null
+++ b/backend/apps/cloud/src/common/templates/en/project-invitation-unregistered.html
@@ -0,0 +1,14 @@
+<a href="mailto:{{email}}">{{email}}</a> has invited you to the {{name}} website
+analytics dashboard with the role {{role}} on Swetrix.
+<br />
+You don't have a Swetrix account yet, but you can create one to accept the
+invitation.
+<br />
+Click the button below to create your account and join the project.
+<br />
+<a href="{{url}}" target="_blank">Create account & 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}}
diff --git a/backend/apps/cloud/src/mailer/letter.ts b/backend/apps/cloud/src/mailer/letter.ts
index 374bb474a..d7c8cafe1 100644
--- a/backend/apps/cloud/src/mailer/letter.ts
+++ b/backend/apps/cloud/src/mailer/letter.ts
@@ -19,6 +19,8 @@ export enum LetterTemplate {
DashboardLockedExceedingLimits = 'dashboard-locked-exceeding-limits',
DashboardLockedPaymentFailure = 'dashboard-locked-payment-failure',
OrganisationInvitation = 'organisation-invitation',
+ ProjectInvitationUnregistered = 'project-invitation-unregistered',
+ OrganisationInvitationUnregistered = 'organisation-invitation-unregistered',
SocialIdentityLinked = 'social-identity-linked',
NoEventsAfterSignup = 'no-events-after-signup',
}
diff --git a/backend/apps/cloud/src/mailer/mailer.service.ts b/backend/apps/cloud/src/mailer/mailer.service.ts
index f05d6f9b1..fd8824528 100644
--- a/backend/apps/cloud/src/mailer/mailer.service.ts
+++ b/backend/apps/cloud/src/mailer/mailer.service.ts
@@ -61,6 +61,16 @@ const metaInfoJson = {
en: () => 'You have been invited to join the organisation',
},
},
+ [LetterTemplate.ProjectInvitationUnregistered]: {
+ subject: {
+ en: () => 'You have been invited to join a project on Swetrix',
+ },
+ },
+ [LetterTemplate.OrganisationInvitationUnregistered]: {
+ subject: {
+ en: () => 'You have been invited to join an organisation on Swetrix',
+ },
+ },
[LetterTemplate.TwoFAOn]: {
subject: {
en: () => '2FA has been enabled on your Swetrix account',
diff --git a/backend/apps/cloud/src/organisation/organisation.controller.ts b/backend/apps/cloud/src/organisation/organisation.controller.ts
index a32943b4f..253ea07a2 100644
--- a/backend/apps/cloud/src/organisation/organisation.controller.ts
+++ b/backend/apps/cloud/src/organisation/organisation.controller.ts
@@ -41,6 +41,8 @@ import { Project } from '../project/entity'
import { isDevelopment, PRODUCTION_ORIGIN } from '../common/constants'
import { checkRateLimit, getIPFromHeaders } from '../common/utils'
import { trackCustom } from '../common/analytics'
+import { PendingInvitationService } from '../pending-invitation/pending-invitation.service'
+import { PendingInvitationType } from '../pending-invitation/pending-invitation.entity'
const ORGANISATION_INVITE_EXPIRE = 7 * 24 // 7 days in hours
@@ -53,6 +55,7 @@ export class OrganisationController {
private readonly actionTokensService: ActionTokensService,
private readonly logger: AppLoggerService,
private readonly projectService: ProjectService,
+ private readonly pendingInvitationService: PendingInvitationService,
) {}
@ApiBearerAuth()
@@ -200,21 +203,61 @@ export class OrganisationController {
})
if (!invitee) {
- throw new NotFoundException(
- `User with email ${inviteDTO.email} is not registered`,
- )
+ const existingPending =
+ await this.pendingInvitationService.findByEmailAndOrganisation(
+ inviteDTO.email,
+ orgId,
+ )
+
+ if (existingPending) {
+ throw new BadRequestException(
+ `An invitation has already been sent to ${inviteDTO.email}`,
+ )
+ }
+
+ try {
+ const pendingInvitation = await this.pendingInvitationService.create({
+ email: inviteDTO.email,
+ type: PendingInvitationType.ORGANISATION_MEMBER,
+ organisationId: orgId,
+ role: inviteDTO.role,
+ inviterId: userId,
+ })
+
+ const origin =
+ isDevelopment && typeof headers?.origin === 'string'
+ ? headers.origin
+ : PRODUCTION_ORIGIN
+ const url = `${origin}/signup/invitation/${pendingInvitation.id}?email=${encodeURIComponent(inviteDTO.email)}`
+
+ await this.mailerService.sendEmail(
+ inviteDTO.email,
+ LetterTemplate.OrganisationInvitationUnregistered,
+ {
+ url,
+ email: user.email,
+ name: organisation.name,
+ role: inviteDTO.role,
+ },
+ )
+
+ return await this.organisationService.findOne({
+ where: { id: orgId },
+ relations: ['members', 'members.user'],
+ })
+ } catch (reason) {
+ this.logger.error(
+ { orgId: organisation?.id, email: inviteDTO.email, reason },
+ 'Could not create pending invitation for organisation',
+ )
+ throw new BadRequestException('Failed to invite member to organisation')
+ }
}
if (invitee.id === user.id) {
throw new BadRequestException('You cannot invite yourself')
}
- // if (!this.userService.isPaidTier(invitee)) {
- // throw new BadRequestException(
- // 'You must be a paid tier subscriber to use this feature.',
- // )
- // }
-
const isAlreadyMember = !_isEmpty(
_find(organisation.members, (member) => member.user?.id === invitee.id),
)
diff --git a/backend/apps/cloud/src/organisation/organisation.module.ts b/backend/apps/cloud/src/organisation/organisation.module.ts
index a67f76ce7..ce0645f91 100644
--- a/backend/apps/cloud/src/organisation/organisation.module.ts
+++ b/backend/apps/cloud/src/organisation/organisation.module.ts
@@ -9,6 +9,7 @@ import { MailerModule } from '../mailer/mailer.module'
import { ActionTokensModule } from '../action-tokens/action-tokens.module'
import { AppLoggerModule } from '../logger/logger.module'
import { ProjectModule } from '../project/project.module'
+import { PendingInvitationModule } from '../pending-invitation/pending-invitation.module'
@Module({
imports: [
@@ -18,6 +19,7 @@ import { ProjectModule } from '../project/project.module'
MailerModule,
ActionTokensModule,
AppLoggerModule,
+ PendingInvitationModule,
],
controllers: [OrganisationController],
providers: [OrganisationService],
diff --git a/backend/apps/cloud/src/pending-invitation/pending-invitation.entity.ts b/backend/apps/cloud/src/pending-invitation/pending-invitation.entity.ts
new file mode 100644
index 000000000..b93336bcb
--- /dev/null
+++ b/backend/apps/cloud/src/pending-invitation/pending-invitation.entity.ts
@@ -0,0 +1,41 @@
+import {
+ Entity,
+ Column,
+ PrimaryGeneratedColumn,
+ CreateDateColumn,
+} from 'typeorm'
+
+export enum PendingInvitationType {
+ PROJECT_SHARE = 'project_share',
+ ORGANISATION_MEMBER = 'organisation_member',
+}
+
+@Entity()
+export class PendingInvitation {
+ @PrimaryGeneratedColumn('uuid')
+ id: string
+
+ @Column('varchar', { length: 254 })
+ email: string
+
+ @Column({
+ type: 'enum',
+ enum: PendingInvitationType,
+ })
+ type: PendingInvitationType
+
+ @Column('varchar', { nullable: true })
+ projectId: string | null
+
+ @Column('varchar', { nullable: true })
+ organisationId: string | null
+
+ @Column('varchar')
+ role: string
+
+ @Column('varchar')
+ inviterId: string
+
+ @CreateDateColumn()
+ created: Date
+}
diff --git a/backend/apps/cloud/src/pending-invitation/pending-invitation.module.ts b/backend/apps/cloud/src/pending-invitation/pending-invitation.module.ts
new file mode 100644
index 000000000..05f098606
--- /dev/null
+++ b/backend/apps/cloud/src/pending-invitation/pending-invitation.module.ts
@@ -0,0 +1,12 @@
+import { Module } from '@nestjs/common'
+import { TypeOrmModule } from '@nestjs/typeorm'
+
+import { PendingInvitation } from './pending-invitation.entity'
+import { PendingInvitationService } from './pending-invitation.service'
+
+@Module({
+ imports: [TypeOrmModule.forFeature([PendingInvitation])],
+ providers: [PendingInvitationService],
+ exports: [PendingInvitationService],
+})
+export class PendingInvitationModule {}
diff --git a/backend/apps/cloud/src/pending-invitation/pending-invitation.service.ts b/backend/apps/cloud/src/pending-invitation/pending-invitation.service.ts
new file mode 100644
index 000000000..610bcd543
--- /dev/null
+++ b/backend/apps/cloud/src/pending-invitation/pending-invitation.service.ts
@@ -0,0 +1,47 @@
+import { Injectable } from '@nestjs/common'
+import { InjectRepository } from '@nestjs/typeorm'
+import { Repository } from 'typeorm'
+
+import { PendingInvitation } from './pending-invitation.entity'
+
+@Injectable()
+export class PendingInvitationService {
+ constructor(
+ @InjectRepository(PendingInvitation)
+ private readonly repository: Repository<PendingInvitation>,
+ ) {}
+
+ async create(data: Partial<PendingInvitation>): Promise<PendingInvitation> {
+ return this.repository.save(data)
+ }
+
+ async findById(id: string): Promise<PendingInvitation | null> {
+ return this.repository.findOne({ where: { id } })
+ }
+
+ async findByEmail(email: string): Promise<PendingInvitation[]> {
+ return this.repository.find({ where: { email } })
+ }
+
+ async findByEmailAndProject(
+ email: string,
+ projectId: string,
+ ): Promise<PendingInvitation | null> {
+ return this.repository.findOne({ where: { email, projectId } })
+ }
+
+ async findByEmailAndOrganisation(
+ email: string,
+ organisationId: string,
+ ): Promise<PendingInvitation | null> {
+ return this.repository.findOne({ where: { email, organisationId } })
+ }
+
+ async delete(id: string): Promise<void> {
+ await this.repository.delete(id)
+ }
+
+ async deleteAllByEmail(email: string): Promise<void> {
+ await this.repository.delete({ email })
+ }
+}
diff --git a/backend/apps/cloud/src/project/project.controller.ts b/backend/apps/cloud/src/project/project.controller.ts
index 9a0d18b60..8042631e6 100644
--- a/backend/apps/cloud/src/project/project.controller.ts
+++ b/backend/apps/cloud/src/project/project.controller.ts
@@ -111,6 +111,9 @@ import { OrganisationService } from '../organisation/organisation.service'
import { Organisation } from '../organisation/entity/organisation.entity'
import { ProjectOrganisationDto } from './dto/project-organisation.dto'
import { trackCustom } from '../common/analytics'
+import { PendingInvitationService } from '../pending-invitation/pending-invitation.service'
+import { PendingInvitationType } from '../pending-invitation/pending-invitation.entity'
+import { PlanCode } from '../user/entities/user.entity'
const PROJECTS_MAXIMUM = 50
@@ -133,6 +136,7 @@ export class ProjectController {
private readonly mailerService: MailerService,
private readonly projectsViewsRepository: ProjectsViewsRepository,
private readonly organisationService: OrganisationService,
+ private readonly pendingInvitationService: PendingInvitationService,
) {}
@ApiBearerAuth()
@@ -330,6 +334,17 @@ export class ProjectController {
)
}
+ if (
+ initiatingUser.planCode === PlanCode.none &&
+ initiatingUser.hasCompletedOnboarding &&
+ !projectDTO.organisationId
+ ) {
+ throw new HttpException(
+ 'You need an active subscription to create personal projects. Please start a free trial or subscribe to a plan.',
+ HttpStatus.PAYMENT_REQUIRED,
+ )
+ }
+
if (user.isAccountBillingSuspended) {
throw new HttpException(
'This account is currently suspended, this is because of a billing issue. Please resolve the issue to continue.',
@@ -1030,9 +1045,53 @@ export class ProjectController {
})
if (!invitee) {
- throw new NotFoundException(
- `User with email ${shareDTO.email} is not registered on Swetrix`,
- )
+ const existingPending =
+ await this.pendingInvitationService.findByEmailAndProject(
+ shareDTO.email,
+ pid,
+ )
+
+ if (existingPending) {
+ throw new BadRequestException(
+ `An invitation has already been sent to ${shareDTO.email}`,
+ )
+ }
+
+ try {
+ const pendingInvitation = await this.pendingInvitationService.create({
+ email: shareDTO.email,
+ type: PendingInvitationType.PROJECT_SHARE,
+ projectId: pid,
+ role: shareDTO.role,
+ inviterId: userId,
+ })
+
+ const origin = isDevelopment ? headers.origin : PRODUCTION_ORIGIN
+ const url = `${origin}/signup/invitation/${pendingInvitation.id}?email=${encodeURIComponent(shareDTO.email)}`
+
+ await this.mailerService.sendEmail(
+ shareDTO.email,
+ LetterTemplate.ProjectInvitationUnregistered,
+ {
+ url,
+ email: user.email,
+ name: project.name,
+ role: shareDTO.role,
+ },
+ )
+
+ const updatedProject = await this.projectService.findOne({
+ where: { id: pid },
+ relations: ['share', 'share.user'],
+ })
+
+ return processProjectUser(updatedProject)
+ } catch (reason) {
+ console.error(
+ `[ERROR] Could not create pending invitation for project (pid: ${project.id}, email: ${shareDTO.email}): ${reason}`,
+ )
+ throw new BadRequestException(reason)
+ }
}
if (invitee.id === user.id) {
diff --git a/backend/apps/cloud/src/project/project.module.ts b/backend/apps/cloud/src/project/project.module.ts
index 7647e850a..b4fb53d18 100644
--- a/backend/apps/cloud/src/project/project.module.ts
+++ b/backend/apps/cloud/src/project/project.module.ts
@@ -21,6 +21,7 @@ import { ProjectsViewsRepository } from './repositories/projects-views.repositor
import { ProjectViewEntity } from './entity/project-view.entity'
import { ProjectViewCustomEventEntity } from './entity/project-view-custom-event.entity'
import { OrganisationModule } from '../organisation/organisation.module'
+import { PendingInvitationModule } from '../pending-invitation/pending-invitation.module'
@Module({
imports: [
@@ -39,6 +40,7 @@ import { OrganisationModule } from '../organisation/organisation.module'
AppLoggerModule,
ActionTokensModule,
MailerModule,
+ PendingInvitationModule,
],
providers: [ProjectService, ProjectsViewsRepository, GSCService],
exports: [ProjectService, ProjectsViewsRepository, GSCService],
diff --git a/backend/apps/cloud/src/user/entities/user.entity.ts b/backend/apps/cloud/src/user/entities/user.entity.ts
index 22d7d0185..4d3a4d9d1 100644
--- a/backend/apps/cloud/src/user/entities/user.entity.ts
+++ b/backend/apps/cloud/src/user/entities/user.entity.ts
@@ -408,6 +408,9 @@ export class User {
@Column({ default: false })
hasCompletedOnboarding: boolean
+ @Column({ default: false })
+ registeredViaInvitation: boolean
+
// Google SSO
@Column({
type: 'varchar',
diff --git a/backend/migrations/mysql/2026_03_09_pending_invitations.sql b/backend/migrations/mysql/2026_03_09_pending_invitations.sql
new file mode 100644
index 000000000..388f15bee
--- /dev/null
+++ b/backend/migrations/mysql/2026_03_09_pending_invitations.sql
@@ -0,0 +1,18 @@
+-- Pending invitations table for inviting unregistered users
+CREATE TABLE IF NOT EXISTS `pending_invitation` (
+ `id` varchar(36) NOT NULL,
+ `email` varchar(254) NOT NULL,
+ `type` enum('project_share', 'organisation_member') NOT NULL,
+ `projectId` varchar(255) DEFAULT NULL,
+ `organisationId` varchar(255) DEFAULT NULL,
+ `role` varchar(255) NOT NULL,
+ `inviterId` varchar(255) NOT NULL,
+ `created` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
+ PRIMARY KEY (`id`),
+ KEY `IDX_pending_invitation_email` (`email`),
+ KEY `IDX_pending_invitation_project` (`projectId`),
+ KEY `IDX_pending_invitation_organisation` (`organisationId`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
+
+-- Add registeredViaInvitation flag to user table
+ALTER TABLE `user` ADD COLUMN `registeredViaInvitation` tinyint(1) NOT NULL DEFAULT 0;
diff --git a/docs/content/docs/sitesettings/how-to-invite-users-to-your-website.mdx b/docs/content/docs/sitesettings/how-to-invite-users-to-your-website.mdx
index 430dd463e..f11f23d70 100644
--- a/docs/content/docs/sitesettings/how-to-invite-users-to-your-website.mdx
+++ b/docs/content/docs/sitesettings/how-to-invite-users-to-your-website.mdx
@@ -5,7 +5,7 @@ slug: /how-to-invite-users-to-your-website
Swetrix allows you to invite other people to your website. This is useful if you want to give access to your team, clients or other people without sharing your login credentials.
-You can invite any person to your website, but they need to have a Swetrix account. At the same time, they don't necessarily need to have a paid subscription to be invited to and access your website.
+You can invite any person to your website using their email address. If they already have a Swetrix account, they'll receive an invitation notification in their dashboard and via email. If they don't have an account yet, they'll receive an email with a link to create one — no paid subscription or credit card is required for invited users.
<Callout type="info">
If you want to share your dashboard without requiring the other person to have a Swetrix account, you can password-protect your dashboard and share the password with them.
@@ -16,13 +16,21 @@ If you want to share your dashboard without requiring the other person to have a
1. Go to your [site settings](/how-to-access-site-settings) page.
2. Scroll down to the "People" section and click the "Invite a user" button.
-3. Enter the email address of the person you want to invite. Please note that the person needs to have a Swetrix account with the same email address.
+3. Enter the email address of the person you want to invite.
4. Select a role for the person you're inviting. You can choose between "Admin" and "Viewer" roles.
- **Admin**: Admins have full access to your website. They can view and edit all settings, add and remove other users, and view all analytics data.
- **Viewer**: Viewers can only view your website's analytics data. They can't edit any settings or invite other users.
-5. Click the "Invite" button to send the invitation. The person will receive an email with a link to accept the invitation. Once they accept it, they will be able to access your website. We'll also display a notification in their Dashboard page to let them know they've been invited to your website and they can accept the invitation from there as well.
+5. Click the "Invite" button to send the invitation.
+
+### If the invitee already has a Swetrix account
+
+They will receive an email with a link to accept the invitation. Once they accept it, they will be able to access your website. We'll also display a notification in their Dashboard page to let them know they've been invited to your website and they can accept the invitation from there as well.
+
+### If the invitee does not have a Swetrix account
+
+They will receive an email with a link to create their account. After signing up through that link, the invitation is automatically accepted and they'll have immediate access to your website's analytics dashboard. These users do not need to start a trial or enter a credit card.
<img alt="Invite user" src="/docs/img/sitesettings/invite_user.png" />
@@ -32,6 +40,8 @@ The owner of the website is responsible for billing and needs to have a paid sub
However, if you transfer ownership of your website to someone else, they will become responsible for billing.
+If an invited user wants to create their own personal projects later on, they will need to start a free trial and subscribe to a plan.
+
## How to modify user permissions
You can modify the permissions of any user at any time. To do this, go to your [site settings](/how-to-access-site-settings) page and scroll down to the "People" section. Here you can see a list of all users who have access to your website.
diff --git a/web/app/api/api.server.ts b/web/app/api/api.server.ts
index 632cd1cc8..69a269511 100644
--- a/web/app/api/api.server.ts
+++ b/web/app/api/api.server.ts
@@ -442,6 +442,90 @@ export async function registerUser(
}
}
+export async function getInvitationDetails(
+ request: Request,
+ invitationId: string,
+): Promise<{
+ success: boolean
+ data?: {
+ id: string
+ email: string
+ type: string
+ role: string
+ inviterEmail: string
+ targetName: string
+ }
+ error?: string
+}> {
+ const result = await serverFetch<{
+ id: string
+ email: string
+ type: string
+ role: string
+ inviterEmail: string
+ targetName: string
+ }>(request, `v1/auth/invitation/${invitationId}`, {
+ skipAuth: true,
+ })
+
+ if (result.error || !result.data) {
+ return {
+ success: false,
+ error: Array.isArray(result.error)
+ ? result.error[0]
+ : result.error || 'Invitation not found',
+ }
+ }
+
+ return {
+ success: true,
+ data: result.data,
+ }
+}
+
+export async function registerViaInvitation(
+ request: Request,
+ data: {
+ pendingInvitationId: string
+ email: string
+ password: string
+ checkIfLeaked: boolean
+ },
+): Promise<{
+ success: boolean
+ data?: Auth
+ error?: string | string[]
+ cookies: string[]
+}> {
+ const result = await serverFetch<Auth>(
+ request,
+ 'v1/auth/register/invitation',
+ {
+ method: 'POST',
+ body: data,
+ skipAuth: true,
+ },
+ )
+
+ if (result.error || !result.data) {
+ return {
+ success: false,
+ error: result.error || 'Registration failed',
+ cookies: [],
+ }
+ }
+
+ const { accessToken, refreshToken } = result.data
+
+ const cookies = createAuthCookies({ accessToken, refreshToken }, true)
+
+ return {
+ success: true,
+ data: result.data,
+ cookies,
+ }
+}
+
export async function logoutUser(
request: Request,
options: { logoutAll?: boolean } = {},
diff --git a/web/app/lib/models/User.ts b/web/app/lib/models/User.ts
index b72f4558e..999c0b29c 100644
--- a/web/app/lib/models/User.ts
+++ b/web/app/lib/models/User.ts
@@ -77,4 +77,5 @@ export interface User {
organisationMemberships: OrganisationMembership[]
onboardingStep: OnboardingStep
hasCompletedOnboarding: boolean
+ registeredViaInvitation: boolean
}
diff --git a/web/app/pages/Auth/Signup/InvitationSignup.tsx b/web/app/pages/Auth/Signup/InvitationSignup.tsx
new file mode 100644
index 000000000..83d664f8f
--- /dev/null
+++ b/web/app/pages/Auth/Signup/InvitationSignup.tsx
@@ -0,0 +1,301 @@
+import { ArrowRightIcon, EnvelopeIcon } from '@phosphor-icons/react'
+import React, { useState, useEffect, memo } from 'react'
+import { useTranslation, Trans } from 'react-i18next'
+import {
+ Link,
+ Form,
+ useActionData,
+ useNavigation,
+ useLoaderData,
+} from 'react-router'
+import { toast } from 'sonner'
+
+import { HAVE_I_BEEN_PWNED_URL } from '~/lib/constants'
+import type {
+ InvitationSignupLoaderData,
+ InvitationSignupActionData,
+} from '~/routes/signup.invitation.$id'
+import Button from '~/ui/Button'
+import Checkbox from '~/ui/Checkbox'
+import Input from '~/ui/Input'
+import { Text } from '~/ui/Text'
+import Tooltip from '~/ui/Tooltip'
+import routes from '~/utils/routes'
+import { MIN_PASSWORD_CHARS } from '~/utils/validator'
+
+const InvitationSignup = () => {
+ const { t } = useTranslation('common')
+ const navigation = useNavigation()
+ const actionData = useActionData<InvitationSignupActionData>()
+ const loaderData = useLoaderData<InvitationSignupLoaderData>()
+
+ const [tos, setTos] = useState(false)
+ const [checkIfLeaked, setCheckIfLeaked] = useState(true)
+ const [clearedErrors, setClearedErrors] = useState<Set<string>>(new Set())
+
+ const isFormSubmitting = navigation.state === 'submitting'
+ const invitation = loaderData?.invitation
+
+ useEffect(() => {
+ if (actionData?.error && !actionData?.fieldErrors) {
+ const errorMessage = Array.isArray(actionData.error)
+ ? actionData.error[0]
+ : actionData.error
+ toast.error(errorMessage)
+ }
+ }, [actionData?.error, actionData?.fieldErrors, actionData?.timestamp])
+
+ const clearFieldError = (fieldName: string) => {
+ if (
+ actionData?.fieldErrors?.[
+ fieldName as keyof typeof actionData.fieldErrors
+ ]
+ ) {
+ setClearedErrors((prev) => new Set(prev).add(fieldName))
+ }
+ }
+
+ const getFieldError = (fieldName: string) => {
+ if (clearedErrors.has(fieldName)) {
+ return undefined
+ }
+ return actionData?.fieldErrors?.[
+ fieldName as keyof typeof actionData.fieldErrors
+ ]
+ }
+
+ const handleFormSubmit = () => {
+ setClearedErrors(new Set())
+ }
+
+ if (loaderData?.error || !invitation) {
+ return (
+ <div className='flex min-h-min-footer items-center justify-center bg-gray-50 dark:bg-slate-950'>
+ <div className='mx-auto max-w-md px-4 text-center'>
+ <Text as='h1' size='2xl' weight='bold' className='mb-4'>
+ {t('common.error')}
+ </Text>
+ <Text colour='muted' className='mb-6'>
+ {loaderData?.error || t('auth.invitation.invalidLink')}
+ </Text>
+ <Link
+ to={routes.signup}
+ className='font-medium text-gray-900 underline decoration-dashed hover:decoration-solid dark:text-gray-300'
+ >
+ {t('auth.signup.createAnAccount')}
+ </Link>
+ </div>
+ </div>
+ )
+ }
+
+ const typeLabel =
+ invitation.type === 'project_share'
+ ? t('auth.invitation.project')
+ : t('auth.invitation.organisation')
+
+ return (
+ <div className='flex min-h-min-footer bg-gray-50 dark:bg-slate-950'>
+ <div className='flex w-full flex-col justify-center bg-gray-50 px-4 py-12 sm:px-6 lg:w-3/5 lg:px-12 xl:px-24 dark:bg-slate-950'>
+ <div className='mx-auto w-full max-w-md'>
+ <div className='mb-6'>
+ <Text as='h1' size='3xl' weight='bold' className='tracking-tight'>
+ {t('auth.signup.createAnAccount')}
+ </Text>
+ </div>
+
+ <div className='mb-6 rounded-xl bg-indigo-50 p-4 ring-1 ring-indigo-200 dark:bg-slate-900 dark:ring-slate-700/80'>
+ <div className='flex items-start gap-3'>
+ <div className='flex size-9 shrink-0 items-center justify-center rounded-lg bg-indigo-100 dark:bg-slate-800'>
+ <EnvelopeIcon
+ weight='duotone'
+ className='size-5 text-indigo-600 dark:text-slate-200'
+ />
+ </div>
+ <div>
+ <Text size='sm' weight='semibold'>
+ <Trans
+ t={t}
+ i18nKey='auth.invitation.invitedToJoin'
+ values={{ targetName: invitation.targetName }}
+ components={{
+ target: (
+ <span className='text-indigo-600 dark:text-white' />
+ ),
+ }}
+ />
+ </Text>
+ <Text size='sm' colour='muted' className='mt-0.5'>
+ <Trans
+ t={t}
+ i18nKey='auth.invitation.invitedByAs'
+ values={{
+ inviterEmail: invitation.inviterEmail,
+ role: invitation.role,
+ type: typeLabel,
+ }}
+ components={{
+ role: <span className='font-medium' />,
+ }}
+ />
+ </Text>
+ </div>
+ </div>
+ </div>
+
+ <Form method='post' className='space-y-4' onSubmit={handleFormSubmit}>
+ <Input
+ name='email'
+ type='email'
+ label={t('auth.common.email')}
+ error={getFieldError('email')}
+ placeholder='[email protected]'
+ disabled
+ defaultValue={invitation.email}
+ />
+ <Input
+ name='password'
+ type='password'
+ label={t('auth.common.password')}
+ hint={t('auth.common.hint', { amount: MIN_PASSWORD_CHARS })}
+ error={getFieldError('password')}
+ disabled={isFormSubmitting}
+ onChange={() => clearFieldError('password')}
+ />
+ <input type='hidden' name='tos' value={tos ? 'true' : 'false'} />
+ <input
+ type='hidden'
+ name='checkIfLeaked'
+ value={checkIfLeaked ? 'true' : 'false'}
+ />
+
+ <Checkbox
+ checked={tos}
+ onChange={(checked) => {
+ setTos(checked)
+ clearFieldError('tos')
+ }}
+ disabled={isFormSubmitting}
+ label={
+ <Text as='span' size='sm'>
+ <Trans
+ t={t}
+ i18nKey='auth.signup.tos'
+ components={{
+ tos: (
+ <Link
+ to={routes.terms}
+ className='font-medium text-gray-900 underline decoration-dashed hover:decoration-solid dark:text-gray-300'
+ aria-label={t('footer.tos')}
+ />
+ ),
+ pp: (
+ <Link
+ to={routes.privacy}
+ className='font-medium text-gray-900 underline decoration-dashed hover:decoration-solid dark:text-gray-300'
+ aria-label={t('footer.pp')}
+ />
+ ),
+ }}
+ />
+ </Text>
+ }
+ classes={{
+ hint: '!text-red-600 dark:!text-red-500',
+ }}
+ hint={getFieldError('tos')}
+ />
+
+ <div className='flex items-center'>
+ <Checkbox
+ checked={checkIfLeaked}
+ onChange={setCheckIfLeaked}
+ disabled={isFormSubmitting}
+ label={
+ <Text size='sm'>{t('auth.common.checkLeakedPassword')}</Text>
+ }
+ />
+ <Tooltip
+ className='ml-2'
+ text={
+ <Trans
+ t={t}
+ i18nKey='auth.common.checkLeakedPasswordDesc'
+ components={{
+ db: (
+ <a
+ href={HAVE_I_BEEN_PWNED_URL}
+ className='font-medium underline decoration-dashed hover:decoration-solid'
+ target='_blank'
+ rel='noreferrer noopener'
+ />
+ ),
+ }}
+ values={{
+ database: 'haveibeenpwned.com',
+ }}
+ />
+ }
+ />
+ </div>
+
+ <Button
+ className='mt-6 flex w-full items-center justify-center gap-1'
+ type='submit'
+ loading={isFormSubmitting}
+ primary
+ giant
+ >
+ <span>
+ {t('auth.invitation.createAndJoin', { type: typeLabel })}
+ </span>
+ <ArrowRightIcon className='size-4 translate-y-px' />
+ </Button>
+ </Form>
+
+ <Text as='p' size='sm' colour='muted' className='mt-6 text-center'>
+ <Trans
+ t={t}
+ i18nKey='auth.signup.alreadyAMember'
+ components={{
+ url: (
+ <Link
+ to={routes.signin}
+ className='font-medium text-gray-900 underline decoration-dashed hover:decoration-solid dark:text-gray-300'
+ aria-label={t('titles.signin')}
+ />
+ ),
+ }}
+ />
+ </Text>
+ </div>
+ </div>
+
+ <div className='relative m-3 hidden overflow-hidden rounded-lg bg-linear-to-br from-slate-800 via-slate-900 to-slate-950 lg:flex lg:w-2/5 lg:flex-col lg:items-center lg:justify-center dark:from-slate-900 dark:to-slate-950'>
+ <div className='absolute -top-24 -right-24 size-96 rounded-full bg-indigo-500/20 blur-3xl' />
+ <div className='absolute -bottom-24 -left-24 size-96 rounded-full bg-slate-500/20 blur-3xl' />
+
+ <div className='relative z-10 max-w-sm px-10 text-center'>
+ <div className='mx-auto mb-6 flex size-16 items-center justify-center rounded-2xl bg-white/10'>
+ <EnvelopeIcon weight='duotone' className='size-8 text-white' />
+ </div>
+ <Text as='h2' size='xl' weight='bold' className='mb-3 text-white'>
+ {t('auth.invitation.youreInvited')}
+ </Text>
+ <Text size='sm' className='text-slate-400'>
+ <Trans
+ t={t}
+ i18nKey='auth.invitation.sidebarDesc'
+ values={{ targetName: invitation.targetName }}
+ components={{
+ target: <span className='font-medium text-white' />,
+ }}
+ />
+ </Text>
+ </div>
+ </div>
+ </div>
+ )
+}
+
+export default memo(InvitationSignup)
diff --git a/web/app/pages/Dashboard/Dashboard.tsx b/web/app/pages/Dashboard/Dashboard.tsx
index 4bd63285c..078df7c97 100644
--- a/web/app/pages/Dashboard/Dashboard.tsx
+++ b/web/app/pages/Dashboard/Dashboard.tsx
@@ -245,6 +245,15 @@ const Dashboard = () => {
return
}
+ if (
+ !isSelfhosted &&
+ user?.planCode === 'none' &&
+ !newProjectOrganisationId
+ ) {
+ toast.error(t('project.settings.subscriptionRequired'))
+ return
+ }
+
const formData = new FormData()
formData.set('intent', 'create-project')
formData.set('name', newProjectName || DEFAULT_PROJECT_NAME)
diff --git a/web/app/routes/dashboard.tsx b/web/app/routes/dashboard.tsx
index 0af61c5bc..ee2b3d436 100644
--- a/web/app/routes/dashboard.tsx
+++ b/web/app/routes/dashboard.tsx
@@ -210,11 +210,11 @@ export async function loader({ request }: LoaderFunctionArgs) {
return redirect('/onboarding')
}
- // If user is not subscribed (trial or real sub), and they're not past subscription (none tier, but have blocked dashboard), redirect to checkout
if (
!isSelfhosted &&
user?.planCode === 'none' &&
- !user?.dashboardBlockReason
+ !user?.dashboardBlockReason &&
+ !user?.registeredViaInvitation
) {
if (authCookies.length > 0) {
return redirect('/subscribe', {
diff --git a/web/app/routes/login.tsx b/web/app/routes/login.tsx
index 0d52876bc..a78937be5 100644
--- a/web/app/routes/login.tsx
+++ b/web/app/routes/login.tsx
@@ -83,7 +83,11 @@ export async function action({ request }: ActionFunctionArgs) {
const result = await serverFetch<{
accessToken: string
refreshToken: string
- user: { hasCompletedOnboarding: boolean; planCode?: string }
+ user: {
+ hasCompletedOnboarding: boolean
+ planCode?: string
+ registeredViaInvitation?: boolean
+ }
}>(request, '2fa/authenticate', {
method: 'POST',
body: { twoFactorAuthenticationCode },
diff --git a/web/app/routes/signup.invitation.$id.tsx b/web/app/routes/signup.invitation.$id.tsx
new file mode 100644
index 000000000..f46eac496
--- /dev/null
+++ b/web/app/routes/signup.invitation.$id.tsx
@@ -0,0 +1,124 @@
+import type {
+ ActionFunctionArgs,
+ HeadersFunction,
+ LoaderFunctionArgs,
+} from 'react-router'
+import { redirect, data } from 'react-router'
+
+import {
+ getAuthenticatedUser,
+ getInvitationDetails,
+ registerViaInvitation,
+} from '~/api/api.server'
+import InvitationSignup from '~/pages/Auth/Signup/InvitationSignup'
+import { createHeadersWithCookies } from '~/utils/session.server'
+
+export const headers: HeadersFunction = ({ parentHeaders }) => {
+ parentHeaders.set('X-Frame-Options', 'DENY')
+ return parentHeaders
+}
+
+export interface InvitationDetails {
+ id: string
+ email: string
+ type: string
+ role: string
+ inviterEmail: string
+ targetName: string
+}
+
+export interface InvitationSignupLoaderData {
+ invitation?: InvitationDetails
+ error?: string
+}
+
+export interface InvitationSignupActionData {
+ error?: string | string[]
+ fieldErrors?: {
+ email?: string
+ password?: string
+ tos?: string
+ }
+ timestamp?: number
+}
+
+export async function loader({
+ request,
+ params,
+}: LoaderFunctionArgs): Promise<InvitationSignupLoaderData> {
+ const authResult = await getAuthenticatedUser(request)
+
+ if (authResult) {
+ const user = authResult.user.user
+
+ if (!user.hasCompletedOnboarding) {
+ throw redirect('/onboarding')
+ }
+ throw redirect('/dashboard')
+ }
+
+ const { id } = params
+
+ if (!id) {
+ return { error: 'Invalid invitation link' }
+ }
+
+ const result = await getInvitationDetails(request, id)
+
+ if (!result.success || !result.data) {
+ return { error: result.error || 'Invitation not found or has expired' }
+ }
+
+ return { invitation: result.data }
+}
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ const { id } = params
+ const formData = await request.formData()
+
+ const email = formData.get('email')?.toString() || ''
+ const password = formData.get('password')?.toString() || ''
+ const tos = formData.get('tos') === 'true'
+ const checkIfLeaked = formData.get('checkIfLeaked') === 'true'
+
+ const fieldErrors: InvitationSignupActionData['fieldErrors'] = {}
+
+ if (!email || !email.includes('@')) {
+ fieldErrors.email = 'Please enter a valid email address'
+ }
+
+ if (!password || password.length < 8) {
+ fieldErrors.password = 'Password must be at least 8 characters'
+ }
+
+ if (password.length > 50) {
+ fieldErrors.password = 'Password must be at most 50 characters'
+ }
+
+ if (!tos) {
+ fieldErrors.tos = 'You must accept the Terms of Service'
+ }
+
+ if (fieldErrors.email || fieldErrors.password || fieldErrors.tos) {
+ return data({ fieldErrors, timestamp: Date.now() }, { status: 400 })
+ }
+
+ const result = await registerViaInvitation(request, {
+ pendingInvitationId: id!,
+ email,
+ password,
+ checkIfLeaked,
+ })
+
+ if (!result.success) {
+ return data({ error: result.error, timestamp: Date.now() }, { status: 400 })
+ }
+
+ return redirect('/dashboard', {
+ headers: createHeadersWithCookies(result.cookies),
+ })
+}
+
+export default function InvitationSignupPage() {
+ return <InvitationSignup />
+}
diff --git a/web/app/routes/subscribe.tsx b/web/app/routes/subscribe.tsx
index 875eeb104..61ab9b3f6 100644
--- a/web/app/routes/subscribe.tsx
+++ b/web/app/routes/subscribe.tsx
@@ -55,8 +55,10 @@ export async function loader({ request }: LoaderFunctionArgs) {
return redirect('/onboarding')
}
- // If the user already has an active subscription or legacy trial, skip checkout
- if (user?.planCode && user.planCode !== 'none') {
+ if (
+ (user?.planCode && user.planCode !== 'none') ||
+ user?.registeredViaInvitation
+ ) {
if (cookies.length > 0) {
return redirect('/dashboard', {
headers: createHeadersWithCookies(cookies),
diff --git a/web/app/utils/auth.ts b/web/app/utils/auth.ts
index bfee99c38..8ce00f33d 100644
--- a/web/app/utils/auth.ts
+++ b/web/app/utils/auth.ts
@@ -12,6 +12,7 @@ import routes from './routes'
export const decidePostAuthRedirect = (user: {
hasCompletedOnboarding: boolean
planCode?: string
+ registeredViaInvitation?: boolean
}): string => {
if (!user.hasCompletedOnboarding) {
return routes.onboarding
diff --git a/web/app/utils/routes.ts b/web/app/utils/routes.ts
index cdf21e1d5..325d34f61 100644
--- a/web/app/utils/routes.ts
+++ b/web/app/utils/routes.ts
@@ -1,6 +1,7 @@
const routes = Object.freeze({
signin: '/login',
signup: '/signup',
+ signup_invitation: '/signup/invitation/:id',
performance: '/performance',
errorTracking: '/error-tracking',
captchaLanding: '/captcha',
diff --git a/web/public/locales/en.json b/web/public/locales/en.json
index 54014bf30..dd9fe3a05 100644
--- a/web/public/locales/en.json
+++ b/web/public/locales/en.json
@@ -726,6 +726,16 @@
"intuitiveDesc": "Easy to use, no need to be a data scientist."
}
},
+ "invitation": {
+ "invalidLink": "This invitation link is invalid or has expired.",
+ "invitedToJoin": "You've been invited to join <target>{{targetName}}</target>",
+ "invitedByAs": "{{inviterEmail}} invited you as <role>{{role}}</role> to this {{type}}. Create your account to get started.",
+ "createAndJoin": "Create account & join {{type}}",
+ "youreInvited": "You're invited",
+ "sidebarDesc": "Create your free account to access the analytics for <target>{{targetName}}</target>. No credit card required.",
+ "project": "project",
+ "organisation": "organisation"
+ },
"verification": {
"success": "Your email has been successfully verified!",
"continueToOnboarding": "Continue to onboarding"
@@ -1771,6 +1781,7 @@
"pxCharsError": "Project name cannot be longer than {{amount}} characters.",
"oxCharsError": "A list of allowed origins has to be smaller than {{amount}} symbols.",
"noNameError": "Please enter a project name.",
+ "subscriptionRequired": "You need an active subscription to create personal projects. Please start a free trial or subscribe to a plan.",
"create": "Create a new project",
"settings": "Settings of",
"name": "Project name",