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: SSO account linking for existing users

Blue Mousee96ff4c3dfb2
diff --git a/backend/apps/cloud/src/auth/auth.controller.ts b/backend/apps/cloud/src/auth/auth.controller.ts
index a1327fc7d..2ce0e04b0 100644
--- a/backend/apps/cloud/src/auth/auth.controller.ts
+++ b/backend/apps/cloud/src/auth/auth.controller.ts
@@ -49,6 +49,7 @@ import {
SSOLinkDto,
SSOUnlinkDto,
SSOProviders,
+ SSOLinkWithPasswordDto,
} from './dtos'
import {
JwtAccessTokenGuard,
@@ -523,4 +524,35 @@ export class AuthController {
await this.authService.unlinkSSOAccount(userId, provider)
}
+
+ @ApiOperation({
+ summary: 'Link SSO provider during login with password verification',
+ })
+ @ApiOkResponse({
+ description: 'SSO provider linked and user authenticated',
+ type: LoginResponseDto,
+ })
+ @Public()
+ @Post('sso/link_with_password')
+ @HttpCode(HttpStatus.OK)
+ public async linkSSOWithPassword(
+ @Body() body: SSOLinkWithPasswordDto,
+ @Headers() headers: Record<string, string>,
+ @Ip() requestIp: string,
+ ): Promise<LoginResponseDto> {
+ const ip = getIPFromHeaders(headers) || requestIp || ''
+
+ await checkRateLimit(ip, 'sso-link-password', 10, 1800)
+
+ const { email, password, provider, ssoId, twoFactorAuthenticationCode } =
+ body
+
+ return this.authService.linkSSOAccountWithPassword(
+ email,
+ password,
+ provider,
+ ssoId,
+ twoFactorAuthenticationCode,
+ )
+ }
}
diff --git a/backend/apps/cloud/src/auth/auth.module.ts b/backend/apps/cloud/src/auth/auth.module.ts
index ce4477b9c..d7834331c 100644
--- a/backend/apps/cloud/src/auth/auth.module.ts
+++ b/backend/apps/cloud/src/auth/auth.module.ts
@@ -7,6 +7,7 @@ import { MailerModule } from '../mailer/mailer.module'
import { UserModule } from '../user/user.module'
import { ProjectModule } from '../project/project.module'
import { TelegramService } from '../integrations/telegram/telegram.service'
+import { TwoFactorAuthModule } from '../twoFactorAuth/twoFactorAuth.module'
import { AuthController } from './auth.controller'
import { AuthService } from './auth.service'
import {
@@ -25,6 +26,7 @@ import { Message } from '../integrations/telegram/entities/message.entity'
MailerModule,
ActionTokensModule,
ProjectModule,
+ forwardRef(() => TwoFactorAuthModule),
TypeOrmModule.forFeature([Message]),
],
controllers: [AuthController],
diff --git a/backend/apps/cloud/src/auth/auth.service.ts b/backend/apps/cloud/src/auth/auth.service.ts
index ac395c0cd..8f5b93ee6 100644
--- a/backend/apps/cloud/src/auth/auth.service.ts
+++ b/backend/apps/cloud/src/auth/auth.service.ts
@@ -4,6 +4,8 @@ import {
InternalServerErrorException,
BadRequestException,
ConflictException,
+ Inject,
+ forwardRef,
} from '@nestjs/common'
import { ConfigService } from '@nestjs/config'
import { JwtService } from '@nestjs/jwt'
@@ -44,6 +46,7 @@ import {
} from '../common/constants'
import { getGeoDetails } from '../common/utils'
import { TelegramService } from '../integrations/telegram/telegram.service'
+import { TwoFactorAuthService } from '../twoFactorAuth/twoFactorAuth.service'
import { SSOProviders } from './dtos'
import { UserGoogleDTO } from '../user/dto/user-google.dto'
import { UserGithubDTO } from '../user/dto/user-github.dto'
@@ -84,6 +87,8 @@ export class AuthService {
private readonly jwtService: JwtService,
private readonly projectService: ProjectService,
private readonly telegramService: TelegramService,
+ @Inject(forwardRef(() => TwoFactorAuthService))
+ private readonly twoFactorAuthService: TwoFactorAuthService,
) {
this.oauth2Client = new OAuth2Client(
this.configService.get('GOOGLE_OAUTH2_CLIENT_ID'),
@@ -583,12 +588,14 @@ export class AuthService {
})
if (userWithSameEmail) {
- console.error(
- `[ERROR][AuthService -> registerUserGoogle] User with email ${email} already exists`,
- )
- throw new BadRequestException(
- 'There is already an account associated with this email address',
- )
+ return {
+ linkingRequired: true,
+ email,
+ provider: SSOProviders.GOOGLE,
+ ssoId: sub,
+ isTwoFactorAuthenticationEnabled:
+ userWithSameEmail.isTwoFactorAuthenticationEnabled,
+ }
}
const user = await this.userService.create(query)
@@ -831,6 +838,8 @@ export class AuthService {
await this.userService.updateUser(userId, {
googleId: sub,
})
+
+ await this.sendSocialIdentityLinkedEmail(user.email, 'Google')
}
async unlinkSSOAccount(userId: string, provider: SSOProviders) {
@@ -983,12 +992,14 @@ export class AuthService {
})
if (userWithSameEmail) {
- console.error(
- `[ERROR][AuthService -> registerUserGithub] User with email ${email} already exists`,
- )
- throw new BadRequestException(
- 'There is already an account associated with this email address',
- )
+ return {
+ linkingRequired: true,
+ email,
+ provider: SSOProviders.GITHUB,
+ ssoId: id,
+ isTwoFactorAuthenticationEnabled:
+ userWithSameEmail.isTwoFactorAuthenticationEnabled,
+ }
}
const user = await this.userService.create(query)
@@ -1089,6 +1100,8 @@ export class AuthService {
await this.userService.updateUser(userId, {
githubId: id,
})
+
+ await this.sendSocialIdentityLinkedEmail(user.email, 'Github')
}
async authenticateGithub(
@@ -1129,4 +1142,120 @@ export class AuthService {
throw new InternalServerErrorException(error)
}
}
+
+ async sendSocialIdentityLinkedEmail(email: string, providerName: string) {
+ try {
+ await this.mailerService.sendEmail(
+ email,
+ LetterTemplate.SocialIdentityLinked,
+ { provider: providerName },
+ )
+ } catch (error) {
+ console.error(
+ `[ERROR][AuthService -> sendSocialIdentityLinkedEmail]: ${error}`,
+ )
+ }
+ }
+
+ async linkSSOAccountWithPassword(
+ email: string,
+ password: string,
+ provider: SSOProviders,
+ ssoId: string | number,
+ twoFactorAuthenticationCode?: string,
+ ) {
+ const user = await this.getBasicUser(email, password)
+
+ if (!user) {
+ throw new BadRequestException('Invalid email or password')
+ }
+
+ if (user.isTwoFactorAuthenticationEnabled) {
+ if (!twoFactorAuthenticationCode) {
+ throw new BadRequestException(
+ 'Two-factor authentication code is required',
+ )
+ }
+
+ const isRecoveryCodeValid =
+ !!user.twoFactorRecoveryCode &&
+ user.twoFactorRecoveryCode === twoFactorAuthenticationCode
+ const isTotpValid =
+ this.twoFactorAuthService.isTwoFactorAuthenticationCodeValid(
+ twoFactorAuthenticationCode,
+ user,
+ )
+ const isCodeValid = isRecoveryCodeValid || isTotpValid
+
+ if (!isCodeValid) {
+ throw new BadRequestException('Invalid two-factor authentication code')
+ }
+ }
+
+ if (provider === SSOProviders.GOOGLE) {
+ if (user.googleId) {
+ throw new BadRequestException(
+ 'This account already has a Google account linked',
+ )
+ }
+
+ const existingUser = await this.userService.findOne({
+ where: { googleId: ssoId as string },
+ })
+
+ if (existingUser) {
+ throw new BadRequestException(
+ 'This Google account is already linked to another user',
+ )
+ }
+
+ await this.userService.updateUser(user.id, {
+ googleId: ssoId as string,
+ })
+
+ await this.sendSocialIdentityLinkedEmail(user.email, 'Google')
+ }
+
+ if (provider === SSOProviders.GITHUB) {
+ if (user.githubId) {
+ throw new BadRequestException(
+ 'This account already has a Github account linked',
+ )
+ }
+
+ const existingUser = await this.userService.findOne({
+ where: { githubId: ssoId as number },
+ })
+
+ if (existingUser) {
+ throw new BadRequestException(
+ 'This Github account is already linked to another user',
+ )
+ }
+
+ await this.userService.updateUser(user.id, {
+ githubId: ssoId as number,
+ })
+
+ await this.sendSocialIdentityLinkedEmail(user.email, 'Github')
+ }
+
+ const jwtTokens = await this.generateJwtTokens(user.id, true)
+
+ const [sharedProjects, organisationMemberships] = await Promise.all([
+ this.getSharedProjectsForUser(user.id),
+ this.userService.getOrganisationsForUser(user.id),
+ ])
+
+ user.sharedProjects = sharedProjects
+ user.organisationMemberships = organisationMemberships
+
+ const totalMonthlyEvents = await this.projectService.getRedisCount(user.id)
+
+ return {
+ ...jwtTokens,
+ user: this.userService.omitSensitiveData(user),
+ totalMonthlyEvents,
+ }
+ }
}
diff --git a/backend/apps/cloud/src/auth/dtos/index.ts b/backend/apps/cloud/src/auth/dtos/index.ts
index 5f6eab085..4424503d2 100644
--- a/backend/apps/cloud/src/auth/dtos/index.ts
+++ b/backend/apps/cloud/src/auth/dtos/index.ts
@@ -11,3 +11,4 @@ export * from './sso-generate.dto'
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'
diff --git a/backend/apps/cloud/src/auth/dtos/sso-link-with-password.dto.ts b/backend/apps/cloud/src/auth/dtos/sso-link-with-password.dto.ts
new file mode 100644
index 000000000..8ee46abab
--- /dev/null
+++ b/backend/apps/cloud/src/auth/dtos/sso-link-with-password.dto.ts
@@ -0,0 +1,44 @@
+import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'
+import { IsEnum, IsString, IsOptional, Length } from 'class-validator'
+
+import { SSOProviders } from './sso-generate.dto'
+
+export class SSOLinkWithPasswordDto {
+ @ApiProperty({
+ description: 'User email',
+ example: '[email protected]',
+ })
+ @IsString()
+ email: string
+
+ @ApiProperty({
+ description: 'User password',
+ example: 'password123',
+ })
+ @IsString()
+ password: string
+
+ @ApiPropertyOptional({
+ description:
+ 'Two-factor authentication code (required if 2FA is enabled on the account)',
+ example: '123456',
+ })
+ @IsOptional()
+ @IsString()
+ @Length(6, 20)
+ twoFactorAuthenticationCode?: string
+
+ @ApiProperty({
+ description: 'SSO provider name',
+ enum: SSOProviders,
+ })
+ @IsEnum(SSOProviders)
+ provider: SSOProviders
+
+ @ApiProperty({
+ description: 'SSO ID from the provider (Google sub or GitHub id)',
+ example: '123456789',
+ })
+ @IsString()
+ ssoId: string
+}
diff --git a/backend/apps/cloud/src/common/templates/en/social-identity-linked.html b/backend/apps/cloud/src/common/templates/en/social-identity-linked.html
new file mode 100644
index 000000000..057af7fea
--- /dev/null
+++ b/backend/apps/cloud/src/common/templates/en/social-identity-linked.html
@@ -0,0 +1,8 @@
+A new <b>{{provider}}</b> social identity was just linked to your Swetrix
+account. <br /><br />
+This means you can now sign in to Swetrix using the {{provider}} account
+associated with this email address.
+<br /><br />
+If you did not initiate this action or believe your account has been
+compromised, please reply to this email immediately so we can assist you in
+securing your account.
diff --git a/backend/apps/cloud/src/mailer/letter.ts b/backend/apps/cloud/src/mailer/letter.ts
index ae0b59577..c804de7d4 100644
--- a/backend/apps/cloud/src/mailer/letter.ts
+++ b/backend/apps/cloud/src/mailer/letter.ts
@@ -18,4 +18,5 @@ export enum LetterTemplate {
DashboardLockedExceedingLimits = 'dashboard-locked-exceeding-limits',
DashboardLockedPaymentFailure = 'dashboard-locked-payment-failure',
OrganisationInvitation = 'organisation-invitation',
+ SocialIdentityLinked = 'social-identity-linked',
}
diff --git a/backend/apps/cloud/src/twoFactorAuth/twoFactorAuth.module.ts b/backend/apps/cloud/src/twoFactorAuth/twoFactorAuth.module.ts
index ab13390ec..d086fdf6c 100644
--- a/backend/apps/cloud/src/twoFactorAuth/twoFactorAuth.module.ts
+++ b/backend/apps/cloud/src/twoFactorAuth/twoFactorAuth.module.ts
@@ -1,4 +1,4 @@
-import { Module } from '@nestjs/common'
+import { forwardRef, Module } from '@nestjs/common'
import { TwoFactorAuthService } from './twoFactorAuth.service'
import { UserModule } from '../user/user.module'
import { AuthModule } from '../auth/auth.module'
@@ -7,7 +7,12 @@ import { AppLoggerModule } from '../logger/logger.module'
import { MailerModule } from '../mailer/mailer.module'
@Module({
- imports: [UserModule, AppLoggerModule, AuthModule, MailerModule],
+ imports: [
+ UserModule,
+ AppLoggerModule,
+ forwardRef(() => AuthModule),
+ MailerModule,
+ ],
controllers: [TwoFactorAuthController],
providers: [TwoFactorAuthService],
exports: [TwoFactorAuthService],
diff --git a/web/app/api/api.server.ts b/web/app/api/api.server.ts
index 51cb3e177..2adc5bcaf 100644
--- a/web/app/api/api.server.ts
+++ b/web/app/api/api.server.ts
@@ -2050,12 +2050,13 @@ export async function generateSSOAuthURLServer(
})
}
-export interface SSOHashResponse {
- accessToken: string
- refreshToken: string
- user: User
- totalMonthlyEvents: number
-}
+export type {
+ SSOHashSuccessResponse,
+ SSOHashLinkingRequiredResponse,
+ SSOHashResponse,
+} from '~/lib/models/Auth'
+
+import type { SSOHashSuccessResponse, SSOHashResponse } from '~/lib/models/Auth'
export async function getJWTBySSOHashServer(
request: Request,
@@ -2097,6 +2098,29 @@ export async function linkBySSOHashServer(
})
}
+export interface LinkSSOWithPasswordParams {
+ email: string
+ password: string
+ provider: SSOProvider
+ ssoId: string | number
+ twoFactorAuthenticationCode?: string
+}
+
+export async function linkSSOWithPasswordServer(
+ request: Request,
+ params: LinkSSOWithPasswordParams,
+): Promise<ServerFetchResult<SSOHashResponse>> {
+ return serverFetch<SSOHashResponse>(
+ request,
+ 'v1/auth/sso/link_with_password',
+ {
+ method: 'POST',
+ body: { ...params },
+ skipAuth: true,
+ },
+ )
+}
+
export async function processSSOTokenServer(
request: Request,
token: string,
diff --git a/web/app/hooks/useAuthProxy.ts b/web/app/hooks/useAuthProxy.ts
index 6ac972d6d..bb7c2c738 100644
--- a/web/app/hooks/useAuthProxy.ts
+++ b/web/app/hooks/useAuthProxy.ts
@@ -2,10 +2,10 @@ import { useCallback } from 'react'
import type {
SSOProvider,
- SSOAuthURLResponse,
SSOHashResponse,
- AuthMeResponse,
-} from '~/api/api.server'
+ SSOHashSuccessResponse,
+} from '~/lib/models/Auth'
+import type { SSOAuthURLResponse, AuthMeResponse } from '~/api/api.server'
interface ProxyResponse<T> {
data: T | null
@@ -152,6 +152,38 @@ export function useAuthProxy() {
[],
)
+ const linkSSOWithPassword = useCallback(
+ async (
+ email: string,
+ password: string,
+ provider: SSOProvider,
+ ssoId: string | number,
+ twoFactorAuthenticationCode?: string,
+ remember = false,
+ ): Promise<SSOHashSuccessResponse> => {
+ const response = await fetch('/api/auth', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ action: 'linkSSOWithPassword',
+ email,
+ password,
+ provider,
+ ssoId,
+ twoFactorAuthenticationCode,
+ remember,
+ }),
+ })
+ const result =
+ (await response.json()) as ProxyResponse<SSOHashSuccessResponse>
+ if (result.error || !result.data) {
+ throw new Error(result.error || 'Failed to link SSO account')
+ }
+ return result.data
+ },
+ [],
+ )
+
return {
generateSSOAuthURL,
getJWTBySSOHash,
@@ -160,5 +192,6 @@ export function useAuthProxy() {
processSSOToken,
processGSCToken,
authMe,
+ linkSSOWithPassword,
}
}
diff --git a/web/app/lib/models/Auth.ts b/web/app/lib/models/Auth.ts
index 72780b239..ef86568d7 100644
--- a/web/app/lib/models/Auth.ts
+++ b/web/app/lib/models/Auth.ts
@@ -8,3 +8,28 @@ export interface Auth {
}
export type SSOProvider = 'google' | 'github' | 'openid-connect'
+
+export interface SSOAuthURLResponse {
+ uuid: string
+ auth_url: string
+ expires_in: number
+}
+
+export interface SSOHashSuccessResponse {
+ accessToken: string
+ refreshToken: string
+ user: User
+ totalMonthlyEvents: number
+}
+
+export interface SSOHashLinkingRequiredResponse {
+ linkingRequired: true
+ email: string
+ provider: SSOProvider
+ ssoId: string | number
+ isTwoFactorAuthenticationEnabled: boolean
+}
+
+export type SSOHashResponse =
+ | SSOHashSuccessResponse
+ | SSOHashLinkingRequiredResponse
diff --git a/web/app/pages/Auth/Signin/Signin.tsx b/web/app/pages/Auth/Signin/Signin.tsx
index 2fc1e2cc5..801234753 100644
--- a/web/app/pages/Auth/Signin/Signin.tsx
+++ b/web/app/pages/Auth/Signin/Signin.tsx
@@ -16,7 +16,7 @@ import GoogleAuth from '~/components/GoogleAuth'
import OIDCAuth from '~/components/OIDCAuth'
import { useAuthProxy } from '~/hooks/useAuthProxy'
import { isSelfhosted, TRIAL_DAYS } from '~/lib/constants'
-import { SSOProvider } from '~/lib/models/Auth'
+import { SSOProvider, SSOHashSuccessResponse } from '~/lib/models/Auth'
import { useAuth } from '~/providers/AuthProvider'
import { useTheme } from '~/providers/ThemeProvider'
import type { LoginActionData } from '~/routes/login'
@@ -31,6 +31,13 @@ import { MIN_PASSWORD_CHARS } from '~/utils/validator'
const HASH_CHECK_FREQUENCY = 1000
+interface LinkingData {
+ email: string
+ provider: SSOProvider
+ ssoId: string | number
+ isTwoFactorAuthenticationEnabled: boolean
+}
+
const Signin = () => {
const navigate = useNavigate()
const navigation = useNavigation()
@@ -50,12 +57,21 @@ const Signin = () => {
const [clearedErrors, setClearedErrors] = useState<Set<string>>(new Set())
+ // State for SSO account linking flow
+ const [linkingData, setLinkingData] = useState<LinkingData | null>(null)
+ const [linkingPassword, setLinkingPassword] = useState('')
+ const [linking2FACode, setLinking2FACode] = useState('')
+ const [isLinkingLoading, setIsLinkingLoading] = useState(false)
+ const [linkingError, setLinkingError] = useState<string | null>(null)
+
const { setUser, setTotalMonthlyEvents, setIsAuthenticated } = useAuth()
- const { generateSSOAuthURL, getJWTBySSOHash } = useAuthProxy()
+ const { generateSSOAuthURL, getJWTBySSOHash, linkSSOWithPassword } =
+ useAuthProxy()
const isFormSubmitting = navigation.state === 'submitting'
const is2FALoading = twoFAFetcher.state === 'submitting'
- const isLoading = isFormSubmitting || isSsoLoading || is2FALoading
+ const isLoading =
+ isFormSubmitting || isSsoLoading || is2FALoading || isLinkingLoading
// 2FA is required from URL params, action data, or SSO flow
const isTwoFARequired =
@@ -63,6 +79,9 @@ const Signin = () => {
actionData?.requires2FA === true ||
sso2FARequired
+ // Check if we're in the linking flow
+ const isLinkingRequired = linkingData !== null
+
// Derive 2FA error from fetcher data
const twoFACodeError = twoFAFetcher.data?.fieldErrors?.twoFACode || null
@@ -175,13 +194,26 @@ const Signin = () => {
await delay(HASH_CHECK_FREQUENCY)
try {
- const { user, totalMonthlyEvents } = await getJWTBySSOHash(
- uuid,
- provider,
- !dontRemember,
- )
+ const response = await getJWTBySSOHash(uuid, provider, !dontRemember)
authWindow.close()
+ // Check if linking is required
+ if ('linkingRequired' in response && response.linkingRequired) {
+ setLinkingData({
+ email: response.email,
+ provider: response.provider as SSOProvider,
+ ssoId: response.ssoId,
+ isTwoFactorAuthenticationEnabled:
+ response.isTwoFactorAuthenticationEnabled,
+ })
+ setIsSsoLoading(false)
+ return
+ }
+
+ // Normal SSO login flow - type is narrowed to SSOHashSuccessResponse
+ const { user, totalMonthlyEvents } =
+ response as SSOHashSuccessResponse
+
if (user.isTwoFactorAuthenticationEnabled) {
setUser(user)
setSso2FARequired(true)
@@ -237,11 +269,145 @@ const Signin = () => {
twoFAFetcher.submit(formData, { method: 'post' })
}
+ const handleLinkAccount = async (e: React.FormEvent<HTMLFormElement>) => {
+ e.preventDefault()
+ e.stopPropagation()
+
+ if (!linkingData || isLinkingLoading) {
+ return
+ }
+
+ setIsLinkingLoading(true)
+ setLinkingError(null)
+
+ try {
+ const { user, totalMonthlyEvents } = await linkSSOWithPassword(
+ linkingData.email,
+ linkingPassword,
+ linkingData.provider,
+ linkingData.ssoId,
+ linkingData.isTwoFactorAuthenticationEnabled
+ ? linking2FACode
+ : undefined,
+ !dontRemember,
+ )
+
+ setUser(user)
+ setIsAuthenticated(true)
+ setTotalMonthlyEvents(totalMonthlyEvents)
+
+ toast.success(
+ t('auth.linkAccount.linkSuccess', {
+ provider: linkingData.provider === 'google' ? 'Google' : 'Github',
+ }),
+ )
+
+ if (!user.hasCompletedOnboarding) {
+ navigate(routes.onboarding)
+ } else {
+ navigate(routes.dashboard)
+ }
+ } catch (error) {
+ setLinkingError(
+ error instanceof Error
+ ? error.message
+ : t('auth.linkAccount.invalidCredentials'),
+ )
+ } finally {
+ setIsLinkingLoading(false)
+ }
+ }
+
+ const handleCancelLinking = () => {
+ setLinkingData(null)
+ setLinkingPassword('')
+ setLinking2FACode('')
+ setLinkingError(null)
+ }
+
+ const getProviderDisplayName = (provider: SSOProvider) => {
+ if (provider === 'google') return 'Google'
+ if (provider === 'github') return 'Github'
+ return provider
+ }
+
return (
<div className='flex min-h-min-footer bg-gray-50 dark:bg-slate-900'>
<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-900'>
<div className='mx-auto w-full max-w-md'>
- {isTwoFARequired ? (
+ {isLinkingRequired && linkingData ? (
+ <>
+ <div className='mb-8'>
+ <Text
+ as='h1'
+ size='3xl'
+ weight='bold'
+ className='tracking-tight'
+ >
+ {t('auth.linkAccount.title')}
+ </Text>
+ <Text as='p' colour='muted' className='mt-2'>
+ {t('auth.linkAccount.description', {
+ email: linkingData.email,
+ provider: getProviderDisplayName(linkingData.provider),
+ })}
+ </Text>
+ </div>
+
+ <form onSubmit={handleLinkAccount} className='space-y-4'>
+ <Input
+ label={t('auth.linkAccount.enterPassword')}
+ type='password'
+ value={linkingPassword}
+ onChange={(e) => setLinkingPassword(e.target.value)}
+ disabled={isLinkingLoading}
+ error={linkingError || undefined}
+ />
+
+ {linkingData.isTwoFactorAuthenticationEnabled && (
+ <>
+ <Text as='p' colour='muted' size='sm' className='mt-2'>
+ {t('auth.linkAccount.2FARequired')}
+ </Text>
+ <Input
+ label={t('auth.linkAccount.enter2FA')}
+ value={linking2FACode}
+ placeholder={t('auth.signin.6digitCode')}
+ onChange={(e) => setLinking2FACode(e.target.value)}
+ disabled={isLinkingLoading}
+ />
+ </>
+ )}
+
+ <div className='flex flex-col gap-3 pt-2'>
+ <Button
+ type='submit'
+ loading={isLinkingLoading}
+ primary
+ giant
+ className='w-full justify-center'
+ >
+ {t('auth.linkAccount.linkButton')}
+ </Button>
+ <Button
+ type='button'
+ onClick={handleCancelLinking}
+ disabled={isLinkingLoading}
+ giant
+ className='w-full justify-center'
+ >
+ {t('auth.linkAccount.returnToSignIn')}
+ </Button>
+ </div>
+
+ <div className='mt-6 border-t border-gray-200 pt-4 dark:border-gray-700'>
+ <Text as='p' colour='muted' size='sm'>
+ {t('auth.linkAccount.unlinkHint')}
+ </Text>
+ </div>
+ </form>
+ </>
+ ) : isTwoFARequired ? (
<>
<div className='mb-8'>
<Text
diff --git a/web/app/pages/Auth/Signup/Signup.tsx b/web/app/pages/Auth/Signup/Signup.tsx
index 025a02f00..8c8e7ba5e 100644
--- a/web/app/pages/Auth/Signup/Signup.tsx
+++ b/web/app/pages/Auth/Signup/Signup.tsx
@@ -24,7 +24,7 @@ import {
isSelfhosted,
TRIAL_DAYS,
} from '~/lib/constants'
-import { SSOProvider } from '~/lib/models/Auth'
+import { SSOProvider, SSOHashSuccessResponse } from '~/lib/models/Auth'
import { useAuth } from '~/providers/AuthProvider'
import { useTheme } from '~/providers/ThemeProvider'
import type { SignupActionData } from '~/routes/signup'
@@ -172,13 +172,22 @@ const Signup = () => {
await delay(HASH_CHECK_FREQUENCY)
try {
- const { user, totalMonthlyEvents } = await getJWTBySSOHash(
- uuid,
- provider,
- true,
- )
+ const response = await getJWTBySSOHash(uuid, provider, true)
authWindow.close()
+ // Check if linking is required - redirect to sign in
+ if ('linkingRequired' in response && response.linkingRequired) {
+ toast.error(
+ 'An account with this email already exists. Please sign in to link your account.',
+ )
+ setIsSsoLoading(false)
+ navigate(routes.signin)
+ return
+ }
+
+ const { user, totalMonthlyEvents } =
+ response as SSOHashSuccessResponse
+
if (user.isTwoFactorAuthenticationEnabled) {
setUser(user)
navigate(`${routes.signin}?show_2fa_screen=true`)
diff --git a/web/app/pages/Project/View/ViewProject.tsx b/web/app/pages/Project/View/ViewProject.tsx
index 53879be6a..1d962f877 100644
--- a/web/app/pages/Project/View/ViewProject.tsx
+++ b/web/app/pages/Project/View/ViewProject.tsx
@@ -76,7 +76,6 @@ import { ProjectViewActionData } from '~/routes/projects.$id'
import Dropdown from '~/ui/Dropdown'
import Flag from '~/ui/Flag'
import Loader from '~/ui/Loader'
-import { trackCustom } from '~/utils/analytics'
import { getItem, setItem } from '~/utils/localstorage'
import routes from '~/utils/routes'
diff --git a/web/app/routes/api.auth.ts b/web/app/routes/api.auth.ts
index 9e824c3e1..796a488a2 100644
--- a/web/app/routes/api.auth.ts
+++ b/web/app/routes/api.auth.ts
@@ -12,10 +12,13 @@ import {
processSSOTokenServer,
processGSCTokenServer,
authMeServer,
+ linkSSOWithPasswordServer,
type SSOProvider,
type SSOAuthURLResponse,
type SSOHashResponse,
+ type SSOHashSuccessResponse,
type AuthMeResponse,
+ type LinkSSOWithPasswordParams,
} from '~/api/api.server'
import { createAuthCookies } from '~/utils/session.server'
@@ -28,6 +31,7 @@ interface ProxyRequest {
| 'processSSOToken'
| 'processGSCToken'
| 'authMe'
+ | 'linkSSOWithPassword'
provider?: SSOProvider
redirectUrl?: string
hash?: string
@@ -35,6 +39,10 @@ interface ProxyRequest {
code?: string
state?: string
remember?: boolean
+ email?: string
+ password?: string
+ ssoId?: string | number
+ twoFactorAuthenticationCode?: string
}
interface ProxyResponse<T> {
@@ -84,24 +92,33 @@ export async function action({ request }: ActionFunctionArgs) {
)
if (result.data) {
- const { accessToken, refreshToken } = result.data
- const cookies = createAuthCookies(
- { accessToken, refreshToken },
- body.remember ?? false,
- )
+ // Only set cookies if this is a success response (not linking required)
+ if ('accessToken' in result.data) {
+ const { accessToken, refreshToken } = result.data
+ const cookies = createAuthCookies(
+ { accessToken, refreshToken },
+ body.remember ?? false,
+ )
- return data<ProxyResponse<SSOHashResponse>>(
- {
- data: result.data,
- error: null,
- },
- {
- headers: cookies.map((cookie) => ['Set-Cookie', cookie]) as [
- string,
- string,
- ][],
- },
- )
+ return data<ProxyResponse<SSOHashResponse>>(
+ {
+ data: result.data,
+ error: null,
+ },
+ {
+ headers: cookies.map((cookie) => ['Set-Cookie', cookie]) as [
+ string,
+ string,
+ ][],
+ },
+ )
+ }
+
+ // Return linking required response without cookies
+ return data<ProxyResponse<SSOHashResponse>>({
+ data: result.data,
+ error: null,
+ })
}
return data<ProxyResponse<SSOHashResponse>>({
@@ -215,6 +232,57 @@ export async function action({ request }: ActionFunctionArgs) {
})
}
+ case 'linkSSOWithPassword': {
+ if (!body.email || !body.password || !body.provider || !body.ssoId) {
+ return data<ProxyResponse<null>>(
+ {
+ data: null,
+ error: 'email, password, provider, and ssoId are required',
+ },
+ { status: 400 },
+ )
+ }
+ const params: LinkSSOWithPasswordParams = {
+ email: body.email,
+ password: body.password,
+ provider: body.provider,
+ ssoId: body.ssoId,
+ twoFactorAuthenticationCode: body.twoFactorAuthenticationCode,
+ }
+ const result = await linkSSOWithPasswordServer(request, params)
+
+ if (result.data && 'accessToken' in result.data) {
+ const { accessToken, refreshToken } =
+ result.data as SSOHashSuccessResponse
+ const cookies = createAuthCookies(
+ { accessToken, refreshToken },
+ body.remember ?? false,
+ )
+
+ return data<ProxyResponse<SSOHashResponse>>(
+ {
+ data: result.data,
+ error: null,
+ },
+ {
+ headers: cookies.map((cookie) => ['Set-Cookie', cookie]) as [
+ string,
+ string,
+ ][],
+ },
+ )
+ }
+
+ return data<ProxyResponse<SSOHashResponse>>({
+ data: result.data,
+ error: result.error
+ ? Array.isArray(result.error)
+ ? result.error.join(', ')
+ : result.error
+ : null,
+ })
+ }
+
default:
return data<ProxyResponse<null>>(
{ data: null, error: `Unknown action: ${action}` },
diff --git a/web/public/locales/en.json b/web/public/locales/en.json
index b64456916..0a3dd1e4e 100644
--- a/web/public/locales/en.json
+++ b/web/public/locales/en.json
@@ -768,6 +768,18 @@
"failedDesc": "An error has occurred while authenticating through a third party service, please try again or contact support.",
"successDesc": "You are now authenticated through a 3rd party service and can safely close this page if it didn't close automatically."
},
+ "linkAccount": {
+ "title": "Link your account",
+ "description": "{{email}} is already registered with Swetrix. Would you like to link your {{provider}} account for easier sign-in?",
+ "linkButton": "Link account",
+ "returnToSignIn": "Return to sign in",
+ "unlinkHint": "If you want to use this email with a different account, sign into your existing account to remove it or use the email unlink feature if you don't have access.",
+ "enterPassword": "Enter your password to confirm",
+ "enter2FA": "Enter your 2FA code",
+ "2FARequired": "Your account has two-factor authentication enabled. Please enter your code to continue.",
+ "invalidCredentials": "Invalid password or 2FA code",
+ "linkSuccess": "Account linked successfully! You can now sign in with {{provider}}."
+ },
"common": {
"password": "Password",
"noRemember": "Don't remember me.",