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!

fix: Claim pending invitation if user sign ups through a regular flow

Blue Mouse562a380a9fca
diff --git a/backend/apps/cloud/src/auth/auth.controller.ts b/backend/apps/cloud/src/auth/auth.controller.ts
index d0ac49762..982953cd8 100644
--- a/backend/apps/cloud/src/auth/auth.controller.ts
+++ b/backend/apps/cloud/src/auth/auth.controller.ts
@@ -60,11 +60,10 @@ import {
JwtRefreshTokenGuard,
AuthenticationGuard,
} from './guards'
-import { ProjectService, deleteProjectRedis } from '../project/project.service'
+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
@@ -133,6 +132,16 @@ export class AuthController {
body.password,
)
+ const hadPendingInvitations =
+ await this.authService.redeemPendingInvitations(newUser)
+
+ if (hadPendingInvitations) {
+ await this.userService.updateUser(newUser.id, {
+ registeredViaInvitation: true,
+ hasCompletedOnboarding: true,
+ })
+ }
+
await trackCustom(ip, headers['user-agent'], {
ev: 'SIGNUP',
meta: {
@@ -142,9 +151,23 @@ export class AuthController {
const jwtTokens = await this.authService.generateJwtTokens(newUser.id, true)
+ const updatedUser = hadPendingInvitations
+ ? await this.userService.findUserById(newUser.id)
+ : newUser
+
+ if (hadPendingInvitations) {
+ 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(newUser),
+ user: this.userService.omitSensitiveData(updatedUser),
totalMonthlyEvents: 0,
}
}
@@ -488,6 +511,42 @@ export class AuthController {
}
}
+ @ApiBearerAuth()
+ @ApiOperation({
+ summary: 'Claim a pending invitation for an authenticated user',
+ })
+ @ApiOkResponse({ description: 'Invitation claimed' })
+ @UseGuards(AuthenticationGuard)
+ @Post('invitation/:id/claim')
+ public async claimInvitation(
+ @Param('id') id: string,
+ @CurrentUserId() userId: string,
+ ) {
+ const invitation = await this.pendingInvitationService.findById(id)
+
+ if (!invitation) {
+ throw new NotFoundException('Invitation not found or has expired')
+ }
+
+ const user = await this.userService.findOne({
+ where: { id: userId },
+ })
+
+ if (!user) {
+ throw new UnauthorizedException()
+ }
+
+ if (invitation.email !== user.email) {
+ throw new BadRequestException(
+ 'This invitation was sent to a different email address',
+ )
+ }
+
+ await this.authService.redeemPendingInvitations(user)
+
+ return { success: true }
+ }
+
@ApiOperation({ summary: 'Register a new user via invitation' })
@ApiCreatedResponse({
description: 'User registered via invitation',
@@ -547,52 +606,7 @@ export class AuthController {
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)
- await deleteProjectRedis(project.id)
- }
- } 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.organisationService.deleteOrganisationProjectsFromRedis(
- organisation.id,
- )
- }
- }
- }
-
- await this.pendingInvitationService.deleteAllByEmail(body.email)
+ await this.authService.redeemPendingInvitations(newUser)
await trackCustom(ip, headers['user-agent'], {
ev: 'SIGNUP',
diff --git a/backend/apps/cloud/src/auth/auth.service.ts b/backend/apps/cloud/src/auth/auth.service.ts
index 53666aa3b..043b2af3f 100644
--- a/backend/apps/cloud/src/auth/auth.service.ts
+++ b/backend/apps/cloud/src/auth/auth.service.ts
@@ -47,6 +47,11 @@ import { SSOProviders } from './dtos'
import { UserGoogleDTO } from '../user/dto/user-google.dto'
import { UserGithubDTO } from '../user/dto/user-github.dto'
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 { deleteProjectRedis } from '../project/project.service'
+import { OrganisationService } from '../organisation/organisation.service'
const REDIS_SSO_SESSION_TIMEOUT = 60 * 5 // 5 minutes
const getSSORedisKey = (uuid: string) => `${REDIS_SSO_UUID}:${uuid}`
@@ -85,6 +90,9 @@ export class AuthService {
private readonly telegramService: TelegramService,
@Inject(forwardRef(() => TwoFactorAuthService))
private readonly twoFactorAuthService: TwoFactorAuthService,
+ private readonly pendingInvitationService: PendingInvitationService,
+ @Inject(forwardRef(() => OrganisationService))
+ private readonly organisationService: OrganisationService,
) {
this.oauth2Client = new OAuth2Client(
this.configService.get('GOOGLE_OAUTH2_CLIENT_ID'),
@@ -181,6 +189,75 @@ export class AuthService {
return user
}
+ public async redeemPendingInvitations(user: User): Promise<boolean> {
+ const pendingInvitations = await this.pendingInvitationService.findByEmail(
+ user.email,
+ )
+
+ if (!pendingInvitations.length) {
+ return false
+ }
+
+ for (const pending of pendingInvitations) {
+ if (
+ pending.type === PendingInvitationType.PROJECT_SHARE &&
+ pending.projectId
+ ) {
+ const project = await this.projectService.findOne({
+ where: { id: pending.projectId },
+ relations: ['share'],
+ })
+
+ if (project) {
+ const alreadyShared = project.share?.some(
+ (s) => s.user?.id === user.id,
+ )
+
+ if (!alreadyShared) {
+ const share = new ProjectShare()
+ share.role = pending.role as any
+ share.user = user
+ share.project = project
+ share.confirmed = true
+
+ await this.projectService.createShare(share)
+ await deleteProjectRedis(project.id)
+ }
+ }
+ } else if (
+ pending.type === PendingInvitationType.ORGANISATION_MEMBER &&
+ pending.organisationId
+ ) {
+ const organisation = await this.organisationService.findOne({
+ where: { id: pending.organisationId },
+ relations: ['members', 'members.user'],
+ })
+
+ if (organisation) {
+ const alreadyMember = organisation.members?.some(
+ (m) => m.user?.id === user.id,
+ )
+
+ if (!alreadyMember) {
+ await this.organisationService.createMembership({
+ role: pending.role as any,
+ user,
+ organisation,
+ confirmed: true,
+ })
+ await this.organisationService.deleteOrganisationProjectsFromRedis(
+ organisation.id,
+ )
+ }
+ }
+ }
+ }
+
+ await this.pendingInvitationService.deleteAllByEmail(user.email)
+
+ return true
+ }
+
public async generateJwtAccessToken(
userId: string,
isSecondFactorAuthenticated = false,
@@ -590,11 +667,24 @@ export class AuthService {
const user = await this.userService.create(query)
+ const hadPendingInvitations = await this.redeemPendingInvitations(user)
+
+ if (hadPendingInvitations) {
+ await this.userService.updateUser(user.id, {
+ registeredViaInvitation: true,
+ hasCompletedOnboarding: true,
+ })
+ }
+
const jwtTokens = await this.generateJwtTokens(user.id, true)
+ const finalUser = hadPendingInvitations
+ ? await this.userService.findUserById(user.id)
+ : user
+
return {
...jwtTokens,
- user: this.userService.omitSensitiveData(user),
+ user: this.userService.omitSensitiveData(finalUser),
totalMonthlyEvents: 0,
}
}
@@ -990,11 +1080,24 @@ export class AuthService {
const user = await this.userService.create(query)
+ const hadPendingInvitations = await this.redeemPendingInvitations(user)
+
+ if (hadPendingInvitations) {
+ await this.userService.updateUser(user.id, {
+ registeredViaInvitation: true,
+ hasCompletedOnboarding: true,
+ })
+ }
+
const jwtTokens = await this.generateJwtTokens(user.id, true)
+ const finalUser = hadPendingInvitations
+ ? await this.userService.findUserById(user.id)
+ : user
+
return {
...jwtTokens,
- user: this.userService.omitSensitiveData(user),
+ user: this.userService.omitSensitiveData(finalUser),
totalMonthlyEvents: 0,
}
}
diff --git a/web/app/api/api.server.ts b/web/app/api/api.server.ts
index 69a269511..5af9073b8 100644
--- a/web/app/api/api.server.ts
+++ b/web/app/api/api.server.ts
@@ -483,6 +483,26 @@ export async function getInvitationDetails(
}
}
+export async function claimInvitation(
+ request: Request,
+ invitationId: string,
+): Promise<{ success: boolean; error?: string }> {
+ const result = await serverFetch<{ success: boolean }>(
+ request,
+ `v1/auth/invitation/${invitationId}/claim`,
+ { method: 'POST' },
+ )
+
+ if (result.error) {
+ return {
+ success: false,
+ error: Array.isArray(result.error) ? result.error[0] : result.error,
+ }
+ }
+
+ return { success: true }
+}
+
export async function registerViaInvitation(
request: Request,
data: {
diff --git a/web/app/routes/signup_.invitation.$id.tsx b/web/app/routes/signup_.invitation.$id.tsx
index 8022534c9..b5e00cc71 100644
--- a/web/app/routes/signup_.invitation.$id.tsx
+++ b/web/app/routes/signup_.invitation.$id.tsx
@@ -11,6 +11,7 @@ import {
getAuthenticatedUser,
getInvitationDetails,
registerViaInvitation,
+ claimInvitation,
} from '~/api/api.server'
import { getOgImageUrl } from '~/lib/constants'
import InvitationSignup from '~/pages/Auth/Signup/InvitationSignup'
@@ -66,12 +67,27 @@ export async function loader({
const authResult = await getAuthenticatedUser(request)
if (authResult) {
+ const { id: invId } = params
+
+ if (invId) {
+ await claimInvitation(request, invId)
+ }
+
const user = authResult.user.user
+ const cookies = authResult.cookies || []
+ const redirectHeaders = cookies.length
+ ? createHeadersWithCookies(cookies)
+ : undefined
if (!user.hasCompletedOnboarding) {
- throw redirect('/onboarding')
+ throw redirect('/onboarding', {
+ headers: redirectHeaders,
+ })
}
- throw redirect('/dashboard')
+
+ throw redirect('/dashboard', {
+ headers: redirectHeaders,
+ })
}
const { id } = params