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 ce: Remove hardcoded login/password and allow users to sign up

Blue Mouse8f1e50a4c573
diff --git a/backend/.env.example b/backend/.env.example
index 7557d8182..c8ecb2bae 100644
--- a/backend/.env.example
+++ b/backend/.env.example
@@ -40,9 +40,7 @@ [email protected]
SMTP_MOCK=true
# Community Edition (Selfhosted) configuration
-PASSWORD=12345678
-API_KEY=
+DISABLE_REGISTRATION=true
DEBUG_MODE=
IP_GEOLOCATION_DB_PATH=
diff --git a/backend/apps/cloud/src/auth/auth.module.ts b/backend/apps/cloud/src/auth/auth.module.ts
index a9fed335a..a114d2571 100644
--- a/backend/apps/cloud/src/auth/auth.module.ts
+++ b/backend/apps/cloud/src/auth/auth.module.ts
@@ -27,7 +27,7 @@ import { OrganisationModule } from '../organisation/organisation.module'
ActionTokensModule,
ProjectModule,
TypeOrmModule.forFeature([Message]),
- OrganisationModule,
+ OrganisationModule, // todo: remove - not used
],
controllers: [AuthController],
providers: [
diff --git a/backend/apps/cloud/src/auth/auth.service.ts b/backend/apps/cloud/src/auth/auth.service.ts
index 0331a0e59..167f1d43b 100644
--- a/backend/apps/cloud/src/auth/auth.service.ts
+++ b/backend/apps/cloud/src/auth/auth.service.ts
@@ -47,7 +47,6 @@ import { TelegramService } from '../integrations/telegram/telegram.service'
import { SSOProviders } from './dtos'
import { UserGoogleDTO } from '../user/dto/user-google.dto'
import { UserGithubDTO } from '../user/dto/user-github.dto'
-import { OrganisationService } from '../organisation/organisation.service'
const REDIS_SSO_SESSION_TIMEOUT = 60 * 5 // 5 minutes
const getSSORedisKey = (uuid: string) => `${REDIS_SSO_UUID}:${uuid}`
@@ -78,7 +77,6 @@ export class AuthService {
private readonly jwtService: JwtService,
private readonly projectService: ProjectService,
private readonly telegramService: TelegramService,
- private readonly organisationService: OrganisationService,
) {
this.oauth2Client = new Auth.OAuth2Client(
this.configService.get('GOOGLE_OAUTH2_CLIENT_ID'),
diff --git a/backend/apps/cloud/src/user/user.controller.ts b/backend/apps/cloud/src/user/user.controller.ts
index 3b2a967bf..df931c027 100644
--- a/backend/apps/cloud/src/user/user.controller.ts
+++ b/backend/apps/cloud/src/user/user.controller.ts
@@ -1158,6 +1158,10 @@ export class UserController {
): Promise<void> {
this.logger.log({ userId, step }, 'POST /user/onboarding/step')
+ if (!Object.values(OnboardingStep).includes(step)) {
+ throw new BadRequestException('Invalid onboarding step')
+ }
+
await this.userService.update(userId, {
onboardingStep: step,
})
diff --git a/backend/apps/community/src/auth/auth.controller.ts b/backend/apps/community/src/auth/auth.controller.ts
index 3d4f33762..18ecc4914 100644
--- a/backend/apps/community/src/auth/auth.controller.ts
+++ b/backend/apps/community/src/auth/auth.controller.ts
@@ -15,12 +15,16 @@ import {
Res,
BadRequestException,
} from '@nestjs/common'
-import { ApiTags, ApiOperation, ApiOkResponse } from '@nestjs/swagger'
+import {
+ ApiTags,
+ ApiOperation,
+ ApiOkResponse,
+ ApiCreatedResponse,
+} from '@nestjs/swagger'
import { I18nValidationExceptionFilter, I18n, I18nContext } from 'nestjs-i18n'
import { Response } from 'express'
import { checkRateLimit, getIPFromHeaders } from '../common/utils'
-import { generateSelfhostedUser } from '../user/entities/user.entity'
import { AuthService } from './auth.service'
import { Public, CurrentUserId, CurrentUser } from './decorators'
import {
@@ -29,9 +33,12 @@ import {
OIDCInitiateDto,
OIDCProcessTokenDto,
OIDCGetJWTByHashDto,
+ RegisterRequestDto,
+ RegisterResponseDto,
} from './dtos'
import { JwtAccessTokenGuard, JwtRefreshTokenGuard } from './guards'
import { OIDC_ENABLED, OIDC_ONLY_AUTH } from '../common/constants'
+import { UserService } from '../user/user.service'
@ApiTags('Auth')
@Controller({ path: 'auth', version: '1' })
@@ -46,7 +53,64 @@ import { OIDC_ENABLED, OIDC_ONLY_AUTH } from '../common/constants'
}),
)
export class AuthController {
- constructor(private readonly authService: AuthService) {}
+ constructor(
+ private readonly authService: AuthService,
+ private readonly userService: UserService,
+ ) {}
+
+ @ApiOperation({ summary: 'Register a new user' })
+ @ApiCreatedResponse({
+ description: 'User registered',
+ type: RegisterResponseDto,
+ })
+ @Public()
+ @Post('register')
+ public async register(
+ @Body() body: RegisterRequestDto,
+ @I18n() i18n: I18nContext,
+ @Headers() headers: Record<string, string>,
+ @Ip() requestIp: string,
+ ) {
+ const ip = getIPFromHeaders(headers) || requestIp || ''
+
+ await checkRateLimit(ip, 'register', 5)
+
+ const isRegistrationDisabled =
+ await this.authService.isRegistrationDisabled()
+
+ if (isRegistrationDisabled) {
+ throw new BadRequestException('Registration is disabled')
+ }
+
+ const user = await this.userService.findOne({ email: body.email })
+
+ if (user) {
+ throw new ConflictException(i18n.t('user.emailAlreadyUsed'))
+ }
+
+ if (body.checkIfLeaked) {
+ const isLeaked = await this.authService.checkIfLeaked(body.password)
+
+ if (isLeaked) {
+ throw new ConflictException(i18n.t('auth.leakedPassword'))
+ }
+ }
+
+ if (body.email === body.password) {
+ throw new ConflictException(i18n.t('auth.passwordSameAsEmail'))
+ }
+
+ const newUser = await this.authService.createUser(body.email, body.password)
+
+ const jwtTokens = await this.authService.generateJwtTokens(newUser.id, true)
+
+ await this.authService.assignUnassignedProjectsToUser(newUser.id)
+
+ return {
+ ...jwtTokens,
+ user: this.userService.omitSensitiveData(newUser),
+ }
+ }
@ApiOperation({ summary: 'Login a user' })
@ApiOkResponse({
@@ -77,14 +141,11 @@ export class AuthController {
throw new ConflictException(i18n.t('auth.invalidCredentials'))
}
- const jwtTokens = await this.authService.generateJwtTokens(
- user.id,
- !user.isTwoFactorAuthenticationEnabled,
- )
+ const jwtTokens = await this.authService.generateJwtTokens(user.id, true)
return {
...jwtTokens,
- user,
+ user: this.userService.omitSensitiveData(user),
}
}
@@ -101,7 +162,7 @@ export class AuthController {
@CurrentUser('refreshToken') refreshToken: string,
@I18n() i18n: I18nContext,
): Promise<{ accessToken: string }> {
- const user = generateSelfhostedUser()
+ const user = await this.userService.findOne({ id: userId })
if (!user) {
throw new UnauthorizedException()
@@ -134,7 +195,7 @@ export class AuthController {
@CurrentUser('refreshToken') refreshToken: string,
@I18n() i18n: I18nContext,
): Promise<void> {
- const user = generateSelfhostedUser()
+ const user = await this.userService.findOne({ id: userId })
if (!user) {
throw new UnauthorizedException()
diff --git a/backend/apps/community/src/auth/auth.module.ts b/backend/apps/community/src/auth/auth.module.ts
index fb56a08e3..0e3beffe4 100644
--- a/backend/apps/community/src/auth/auth.module.ts
+++ b/backend/apps/community/src/auth/auth.module.ts
@@ -2,6 +2,7 @@ import { Module } from '@nestjs/common'
import { JwtModule } from '@nestjs/jwt'
import { PassportModule } from '@nestjs/passport'
import { AuthController } from './auth.controller'
+import { UserModule } from '../user/user.module'
import { AuthService } from './auth.service'
import {
ApiKeyStrategy,
@@ -10,7 +11,7 @@ import {
} from './strategies'
@Module({
- imports: [JwtModule.register({}), PassportModule],
+ imports: [JwtModule.register({}), PassportModule, UserModule],
controllers: [AuthController],
providers: [
AuthService,
diff --git a/backend/apps/community/src/auth/auth.service.ts b/backend/apps/community/src/auth/auth.service.ts
index b4186f868..74a131434 100644
--- a/backend/apps/community/src/auth/auth.service.ts
+++ b/backend/apps/community/src/auth/auth.service.ts
@@ -1,3 +1,4 @@
+import { createHash, randomBytes } from 'crypto'
import {
BadRequestException,
ConflictException,
@@ -6,7 +7,8 @@ import {
} from '@nestjs/common'
import { ConfigService } from '@nestjs/config'
import { JwtService } from '@nestjs/jwt'
-import { genSalt, hash } from 'bcrypt'
+import { genSalt, hash, compare } from 'bcrypt'
+import axios from 'axios'
import _isEmpty from 'lodash/isEmpty'
import { v4 as uuidv4 } from 'uuid'
import { decode, JwtPayload, verify } from 'jsonwebtoken'
@@ -16,19 +18,18 @@ import {
saveRefreshTokenClickhouse,
findRefreshTokenClickhouse,
deleteRefreshTokenClickhouse,
+ assignUnassignedProjectsToUserClickhouse,
} from '../common/utils'
import {
- SELFHOSTED_EMAIL,
- SELFHOSTED_PASSWORD,
JWT_ACCESS_TOKEN_SECRET,
JWT_ACCESS_TOKEN_LIFETIME,
JWT_REFRESH_TOKEN_LIFETIME,
- SELFHOSTED_API_KEY,
- SELFHOSTED_UUID,
REDIS_OIDC_SESSION_KEY,
redis,
+ IS_REGISTRATION_DISABLED,
} from '../common/constants'
-import { getSelfhostedUser, SelfhostedUser } from '../user/entities/user.entity'
+import { UserService } from '../user/user.service'
+import { ClickhouseUser } from '../common/types'
const REDIS_OIDC_SESSION_TIMEOUT = 60 * 5 // 5 minutes
const getOIDCRedisKey = (uuid: string) => `${REDIS_OIDC_SESSION_KEY}:${uuid}`
@@ -39,8 +40,42 @@ export class AuthService {
constructor(
private readonly configService: ConfigService,
private readonly jwtService: JwtService,
+ private readonly userService: UserService,
) {}
+ private async createSha1Hash(text: string): Promise<string> {
+ return new Promise(resolve => {
+ const sha1sum = createHash('sha1')
+ .update(text)
+ .digest('hex')
+ .toUpperCase()
+ resolve(sha1sum)
+ })
+ }
+
+ private getFirstFiveChars(passwordHash: string): string {
+ return passwordHash.slice(0, 5)
+ }
+
+ private async sendRequestToApi(passwordHash: string) {
+ const url = `https://api.pwnedpasswords.com/range/${passwordHash}`
+ const response = await axios.get(url)
+
+ if (response.status !== 200) {
+ throw new InternalServerErrorException()
+ }
+
+ return response.data
+ }
+
+ public async checkIfLeaked(password: string): Promise<boolean> {
+ const sha1Hash = await this.createSha1Hash(password)
+ const firstFiveChars = this.getFirstFiveChars(sha1Hash)
+ const response = await this.sendRequestToApi(firstFiveChars)
+
+ return response.includes(firstFiveChars)
+ }
+
public async hashPassword(password: string): Promise<string> {
const salt = await genSalt(10)
return hash(password, salt)
@@ -63,15 +98,83 @@ export class AuthService {
)
}
+ public async createUser(email: string, password: string) {
+ const hashedPassword = await this.hashPassword(password)
+
+ return this.userService.create({
+ email,
+ password: hashedPassword, // Using the password field is incorrect.
+ })
+ }
+
+ private generateRandomPassword(length = 48): string {
+ return randomBytes(64).toString('hex').slice(0, length)
+ }
+
+ private async getOrCreateUserByEmail(email: string): Promise<ClickhouseUser> {
+ const existingUser = await this.userService.findOne({ email })
+
+ if (existingUser && existingUser.id) {
+ return existingUser
+ }
+
+ // Treat as registration attempt; respect registration-disabled setting
+ const isRegistrationDisabled = await this.isRegistrationDisabled()
+
+ if (isRegistrationDisabled) {
+ throw new BadRequestException('Registration is disabled')
+ }
+
+ const randomPassword = this.generateRandomPassword(48)
+ const hashedPassword = await this.hashPassword(randomPassword)
+
+ const createdUser = await this.userService.create({
+ email,
+ password: hashedPassword,
+ })
+
+ // Assign any pre-v4 unassigned projects to the newly registered user
+ await this.assignUnassignedProjectsToUser(createdUser.id)
+
+ return createdUser
+ }
+
+ async isRegistrationDisabled() {
+ const usersCount = await this.userService.count()
+
+ if (usersCount === 0) {
+ return false
+ }
+
+ return IS_REGISTRATION_DISABLED
+ }
+
+ // Before Swetrix CE v4 there could only be a single user, with login / password set in .env file
+ // Because of that, projects were stored without an adminId as it was not needed
+ // Unassigned projects are only possible when migrating from Swetrix CE v3 to v4, so people who migrated are
+ // going to create an account anyway, so it's safe to assign them to the user
+ async assignUnassignedProjectsToUser(userId: string) {
+ return assignUnassignedProjectsToUserClickhouse(userId)
+ }
+
async getBasicUser(
email: string,
password: string,
- ): Promise<SelfhostedUser | null> {
- if (email !== SELFHOSTED_EMAIL || password !== SELFHOSTED_PASSWORD) {
- return null
+ ): Promise<ClickhouseUser | null> {
+ const user = await this.userService.findOne({ email })
+
+ if (user && (await this.comparePassword(password, user.password))) {
+ return user
}
- return getSelfhostedUser()
+ return null
+ }
+
+ private async comparePassword(
+ password: string,
+ hashedPassword: string,
+ ): Promise<boolean> {
+ return compare(password, hashedPassword)
}
private async generateJwtRefreshToken(
@@ -128,10 +231,6 @@ export class AuthService {
await deleteRefreshTokenClickhouse(userId, refreshToken)
}
- isApiKeyValid(apiKey: string): boolean {
- return apiKey === SELFHOSTED_API_KEY
- }
-
getOidcConfig() {
return {
discoveryURL: this.configService.get('OIDC_DISCOVERY_URL'),
@@ -263,6 +362,16 @@ export class AuthService {
const discovery = await this.getOidcDiscovery()
+ // Ensure the state corresponds to an initiated session
+ const oidcRedisKey = getOIDCRedisKey(state)
+ const sessionExists = await redis.exists(oidcRedisKey)
+
+ if (!sessionExists) {
+ throw new BadRequestException(
+ 'No authentication session opened for the provided state',
+ )
+ }
+
const tokenResponse = await fetch(discovery.token_endpoint, {
method: 'POST',
headers: {
@@ -286,17 +395,24 @@ export class AuthService {
)
}
- // Ideally we want to use id/email from this id token, but for now we only support one user in the system
- await this.getIdToken(tokenData, discovery)
+ // Extract and validate ID token claims
+ const idToken = await this.getIdToken(tokenData, discovery)
- const dataToStore = JSON.stringify({ id: SELFHOSTED_UUID })
+ const emailClaimRaw = (idToken as any).email
- await redis.set(
- getOIDCRedisKey(state),
- dataToStore,
- 'EX',
- REDIS_OIDC_SESSION_TIMEOUT,
- )
+ if (!emailClaimRaw || typeof emailClaimRaw !== 'string') {
+ throw new BadRequestException('Email claim missing in ID token')
+ }
+
+ const email = emailClaimRaw.trim().toLowerCase()
+
+ // Find or create user by email
+ const user = await this.getOrCreateUserByEmail(email)
+
+ // Store resolved user id in the existing OIDC session
+ const dataToStore = JSON.stringify({ id: user.id })
+
+ await redis.set(oidcRedisKey, dataToStore, 'EX', REDIS_OIDC_SESSION_TIMEOUT)
}
async processHash(state: string) {
@@ -343,7 +459,9 @@ export class AuthService {
const { id } = await this.processHash(state)
try {
- if (id !== SELFHOSTED_UUID) {
+ const user = await this.userService.findOne({ id })
+
+ if (!user) {
throw new BadRequestException('Invalid user ID')
}
@@ -351,7 +469,7 @@ export class AuthService {
return {
...tokens,
- user: getSelfhostedUser(),
+ user: this.userService.omitSensitiveData(user),
}
} catch (error) {
console.error(`[ERROR][AuthService -> authenticateOidc]: ${error}`)
diff --git a/backend/apps/community/src/auth/dtos/index.ts b/backend/apps/community/src/auth/dtos/index.ts
index e0e1003d5..a49558cd1 100644
--- a/backend/apps/community/src/auth/dtos/index.ts
+++ b/backend/apps/community/src/auth/dtos/index.ts
@@ -1,2 +1,3 @@
export * from './login.dto'
export * from './oidc-auth.dto'
+export * from './register.dto'
diff --git a/backend/apps/community/src/auth/dtos/register.dto.ts b/backend/apps/community/src/auth/dtos/register.dto.ts
new file mode 100644
index 000000000..05c4d0e39
--- /dev/null
+++ b/backend/apps/community/src/auth/dtos/register.dto.ts
@@ -0,0 +1,54 @@
+import { ApiProperty } from '@nestjs/swagger'
+import {
+ IsEmail,
+ IsNotEmpty,
+ IsBoolean,
+ MaxLength,
+ MinLength,
+} from 'class-validator'
+
+export class RegisterRequestDto {
+ @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
+}
+
+export class RegisterResponseDto {
+ @ApiProperty({
+ description: 'Access token (JWT)',
+ })
+ public readonly accessToken: string
+
+ @ApiProperty({
+ description: 'Refresh token (JWT)',
+ })
+ public readonly refreshToken: string
+
+ @ApiProperty({
+ description: 'User entity',
+ })
+ user: object
+}
diff --git a/backend/apps/community/src/auth/strategies/api-key.strategy.ts b/backend/apps/community/src/auth/strategies/api-key.strategy.ts
index c754d2694..83dacf5e2 100644
--- a/backend/apps/community/src/auth/strategies/api-key.strategy.ts
+++ b/backend/apps/community/src/auth/strategies/api-key.strategy.ts
@@ -1,15 +1,14 @@
import { Injectable, UnauthorizedException } from '@nestjs/common'
import { PassportStrategy } from '@nestjs/passport'
import { HeaderAPIKeyStrategy } from 'passport-headerapikey'
-import { AuthService } from '../auth.service'
-import { getSelfhostedUser } from '../../user/entities/user.entity'
+import { UserService } from '../../user/user.service'
@Injectable()
export class ApiKeyStrategy extends PassportStrategy(
HeaderAPIKeyStrategy,
'api-key',
) {
- constructor(private readonly authService: AuthService) {
+ constructor(private readonly userService: UserService) {
super(
{ header: 'X-Api-Key', prefix: '' },
true,
@@ -23,10 +22,9 @@ export class ApiKeyStrategy extends PassportStrategy(
}
async validate(apiKey: string, done: (err: any, user: any) => void) {
- const isValid = this.authService.isApiKeyValid(apiKey)
- if (!isValid) return done(new UnauthorizedException(), false)
+ const user = await this.userService.findOne({ apiKey })
+ if (!user) return done(new UnauthorizedException(), false)
- const user = await getSelfhostedUser()
return done(null, user)
}
}
diff --git a/backend/apps/community/src/auth/strategies/jwt-access-token.strategy.ts b/backend/apps/community/src/auth/strategies/jwt-access-token.strategy.ts
index fdbf73b6f..8bf8723ad 100644
--- a/backend/apps/community/src/auth/strategies/jwt-access-token.strategy.ts
+++ b/backend/apps/community/src/auth/strategies/jwt-access-token.strategy.ts
@@ -3,19 +3,19 @@ import { ConfigService } from '@nestjs/config'
import { PassportStrategy } from '@nestjs/passport'
import { Strategy, ExtractJwt } from 'passport-jwt'
-import {
- SELFHOSTED_UUID,
- JWT_ACCESS_TOKEN_SECRET,
-} from '../../common/constants'
-import { getSelfhostedUser } from '../../user/entities/user.entity'
+import { JWT_ACCESS_TOKEN_SECRET } from '../../common/constants'
import { IJwtPayload } from '../interfaces'
+import { UserService } from '../../user/user.service'
@Injectable()
export class JwtAccessTokenStrategy extends PassportStrategy(
Strategy,
'jwt-access-token',
) {
- constructor(public readonly configService: ConfigService) {
+ constructor(
+ public readonly configService: ConfigService,
+ private readonly userService: UserService,
+ ) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
@@ -24,10 +24,12 @@ export class JwtAccessTokenStrategy extends PassportStrategy(
}
public async validate(payload: IJwtPayload) {
- if (payload.sub !== SELFHOSTED_UUID) {
+ const user = await this.userService.findOne({ id: payload.sub })
+
+ if (!user) {
throw new UnauthorizedException()
}
- return getSelfhostedUser()
+ return user
}
}
diff --git a/backend/apps/community/src/common/constants.ts b/backend/apps/community/src/common/constants.ts
index 951ede643..e98be07ff 100644
--- a/backend/apps/community/src/common/constants.ts
+++ b/backend/apps/community/src/common/constants.ts
@@ -1,7 +1,6 @@
import Redis from 'ioredis'
import _toNumber from 'lodash/toNumber'
-import { getSelfhostedUUID } from './utils'
import 'dotenv/config'
const redis = new Redis(
@@ -29,20 +28,16 @@ const {
const isProxiedByCloudflare = process.env.CLOUDFLARE_PROXY_ENABLED === 'true'
const isDevelopment = process.env.NODE_ENV === 'development'
-const SELFHOSTED_EMAIL = process.env.EMAIL
-const SELFHOSTED_PASSWORD = process.env.PASSWORD
-const SELFHOSTED_API_KEY = process.env.API_KEY
-const SELFHOSTED_API_AUTH_ENABLED = !!SELFHOSTED_API_KEY
+export const IS_REGISTRATION_DISABLED =
+ process.env.DISABLE_REGISTRATION === 'true' ||
+ !process.env.DISABLE_REGISTRATION
+
const SELFHOSTED_GEOIP_DB_PATH = process.env.IP_GEOLOCATION_DB_PATH
-const UUIDV5_NAMESPACE = '912c64c1-73fd-42b6-859f-785f839a9f68'
-const DEFAULT_SELFHOSTED_UUID = 'deadbeef-dead-beef-dead-beefdeadbeef'
// OIDC configuration
const OIDC_ENABLED = process.env.OIDC_ENABLED === 'true'
const OIDC_ONLY_AUTH = process.env.OIDC_ONLY_AUTH === 'true'
-const SELFHOSTED_UUID = getSelfhostedUUID()
-
const ORIGINS_REGEX =
/^(?=.{1,255}$)([0-9A-Za-z*:](?:(?:[0-9A-Za-z*:]|-){0,61}[0-9A-Za-z*:])?(?:\.[0-9A-Za-z*:](?:(?:[0-9A-Za-z*-]|-){0,61}[0-9A-Za-z*:])?)*)?$/
const IP_REGEX =
@@ -119,18 +114,11 @@ export {
UNIQUE_SESSION_LIFE_TIME,
TRAFFIC_METAKEY_COLUMNS,
REDIS_SESSION_SALT_KEY,
- UUIDV5_NAMESPACE,
- SELFHOSTED_EMAIL,
- SELFHOSTED_PASSWORD,
- SELFHOSTED_API_KEY,
- SELFHOSTED_API_AUTH_ENABLED,
- SELFHOSTED_UUID,
REDIS_USERS_COUNT_KEY,
REDIS_PROJECTS_COUNT_KEY,
IP_REGEX,
ORIGINS_REGEX,
isDevelopment,
- DEFAULT_SELFHOSTED_UUID,
JWT_ACCESS_TOKEN_SECRET,
NUMBER_JWT_REFRESH_TOKEN_LIFETIME as JWT_REFRESH_TOKEN_LIFETIME,
NUMBER_JWT_ACCESS_TOKEN_LIFETIME as JWT_ACCESS_TOKEN_LIFETIME,
diff --git a/backend/apps/community/src/common/types.ts b/backend/apps/community/src/common/types.ts
index 61e2e9a49..59b1b2764 100644
--- a/backend/apps/community/src/common/types.ts
+++ b/backend/apps/community/src/common/types.ts
@@ -1,8 +1,15 @@
-export interface ClickhouseSFUser {
+import { OnboardingStep } from '../user/entities/user.entity'
+
+export interface ClickhouseUser {
id: string
- timezone: string | null
- timeFormat: string | null
- showLiveVisitorsInTitle: number | null
+ email: string
+ password: string
+ timezone: string
+ timeFormat: string
+ showLiveVisitorsInTitle: number
+ onboardingStep: OnboardingStep
+ hasCompletedOnboarding: number
+ apiKey: string | null
}
export interface ClickhouseProject {
diff --git a/backend/apps/community/src/common/utils.ts b/backend/apps/community/src/common/utils.ts
index 4cb6d5a31..749b96a42 100644
--- a/backend/apps/community/src/common/utils.ts
+++ b/backend/apps/community/src/common/utils.ts
@@ -4,7 +4,6 @@ import fs from 'fs'
import crypto from 'crypto'
import { CityResponse, Reader } from 'maxmind'
import timezones from 'countries-and-timezones'
-import { v5 as uuidv5 } from 'uuid'
import _join from 'lodash/join'
import _filter from 'lodash/filter'
import _values from 'lodash/values'
@@ -23,19 +22,15 @@ import _map from 'lodash/map'
import {
redis,
- DEFAULT_SELFHOSTED_UUID,
- SELFHOSTED_EMAIL,
- UUIDV5_NAMESPACE,
isDevelopment,
isProxiedByCloudflare,
SELFHOSTED_GEOIP_DB_PATH,
} from './constants'
import { clickhouse } from './integrations/clickhouse'
-import { DEFAULT_TIMEZONE, TimeFormat } from '../user/entities/user.entity'
import { BotsProtectionLevel, Project } from '../project/entity/project.entity'
import { ProjectViewEntity } from '../project/entity/project-view.entity'
-import { ClickhouseFunnel, ClickhouseSFUser } from './types'
+import { ClickhouseFunnel } from './types'
dayjs.extend(utc)
@@ -294,6 +289,17 @@ const updateProjectClickhouse = async (project: any) => {
})
}
+const assignUnassignedProjectsToUserClickhouse = async (userId: string) => {
+ const query = `ALTER TABLE project UPDATE adminId = {userId:FixedString(36)} WHERE adminId IS NULL`
+
+ await clickhouse.command({
+ query,
+ query_params: {
+ userId,
+ },
+ })
+}
+
/**
* Checking the % change in one number relative to the other
* @param oldVal The initial value
@@ -401,107 +407,6 @@ const deleteRefreshTokenClickhouse = async (
})
}
-interface IClickhouseUser {
- timezone?: string
- timeFormat?: string
- showLiveVisitorsInTitle?: number
-}
-
-const CLICKHOUSE_SETTINGS_ID = 'sfuser'
-
-const createUserClickhouse = async (user: IClickhouseUser) => {
- const { timezone, timeFormat, showLiveVisitorsInTitle } = user
-
- await clickhouse.insert({
- table: 'sfuser',
- format: 'JSONEachRow',
- values: [
- {
- id: CLICKHOUSE_SETTINGS_ID,
- timezone,
- timeFormat,
- showLiveVisitorsInTitle,
- },
- ],
- })
-}
-
-const getUserClickhouse = async () => {
- const query = `SELECT * FROM sfuser WHERE id = {id:String}`
-
- try {
- const { data } = await clickhouse
- .query({
- query,
- query_params: {
- id: CLICKHOUSE_SETTINGS_ID,
- },
- })
- .then(resultSet => resultSet.json<ClickhouseSFUser>())
-
- return data[0] || ({} as ClickhouseSFUser)
- } catch {
- return {}
- }
-}
-
-const userClickhouseExists = async () => {
- const query = `SELECT * FROM sfuser WHERE id = '${CLICKHOUSE_SETTINGS_ID}'`
-
- try {
- const { data } = await clickhouse
- .query({
- query,
- })
- .then(resultSet => resultSet.json())
-
- return !_isEmpty(data)
- } catch {
- return false
- }
-}
-
-const updateUserClickhouse = async (user: IClickhouseUser) => {
- const userExists = await userClickhouseExists()
-
- if (!userExists) {
- await createUserClickhouse({
- timezone: DEFAULT_TIMEZONE,
- timeFormat: TimeFormat['12-hour'],
- showLiveVisitorsInTitle: 0,
- ...user,
- })
- }
-
- let query = 'ALTER table sfuser UPDATE '
- let separator = ''
-
- if (!_isNil(user.timezone)) {
- query += `${separator}timezone={timezone:String}`
- separator = ', '
- }
-
- if (!_isNil(user.timeFormat)) {
- query += `${separator}timeFormat={timeFormat:String}`
- separator = ', '
- }
-
- if (!_isNil(user.showLiveVisitorsInTitle)) {
- query += `${separator}showLiveVisitorsInTitle={showLiveVisitorsInTitle:Int8}`
- separator = ', '
- }
-
- query += ` WHERE id={id:String}`
-
- await clickhouse.command({
- query,
- query_params: {
- ...user,
- id: CLICKHOUSE_SETTINGS_ID,
- },
- })
-}
-
const findProjectViewCustomEventsClickhouse = async (viewId: string) => {
try {
const { data } = await clickhouse
@@ -719,14 +624,6 @@ export const isPrimaryNode = () => {
return process.env.IS_PRIMARY_NODE === 'true'
}
-const getSelfhostedUUID = (): string => {
- try {
- return uuidv5(SELFHOSTED_EMAIL, UUIDV5_NAMESPACE)
- } catch {
- return DEFAULT_SELFHOSTED_UUID
- }
-}
-
const dummyLookup = () => ({
country: {
names: {
@@ -848,16 +745,13 @@ export {
deleteProjectClickhouse,
calculateRelativePercentage,
millisecondsToSeconds,
- getSelfhostedUUID,
saveRefreshTokenClickhouse,
findRefreshTokenClickhouse,
deleteRefreshTokenClickhouse,
- updateUserClickhouse,
- getUserClickhouse,
- createUserClickhouse,
getGeoDetails,
getIPFromHeaders,
sumArrays,
+ assignUnassignedProjectsToUserClickhouse,
getFunnelClickhouse,
getFunnelsClickhouse,
updateFunnelClickhouse,
diff --git a/backend/apps/community/src/project/entity/project.entity.ts b/backend/apps/community/src/project/entity/project.entity.ts
index b160a1acf..baad80f65 100644
--- a/backend/apps/community/src/project/entity/project.entity.ts
+++ b/backend/apps/community/src/project/entity/project.entity.ts
@@ -5,22 +5,14 @@ export enum BotsProtectionLevel {
export class Project {
id: string
-
name: string
-
origins: string[]
-
ipBlacklist: string[]
-
active: boolean
-
public: boolean
-
isPasswordProtected: boolean
-
botsProtectionLevel: BotsProtectionLevel
-
passwordHash?: string
-
created: Date
+ adminId: string | null
}
diff --git a/backend/apps/community/src/user/entities/user.entity.ts b/backend/apps/community/src/user/entities/user.entity.ts
index 0484d8247..3be468868 100644
--- a/backend/apps/community/src/user/entities/user.entity.ts
+++ b/backend/apps/community/src/user/entities/user.entity.ts
@@ -1,10 +1,4 @@
import _omit from 'lodash/omit'
-import {
- SELFHOSTED_API_KEY,
- SELFHOSTED_EMAIL,
- SELFHOSTED_UUID,
-} from '../../common/constants'
-import { getUserClickhouse } from '../../common/utils'
export enum UserType {
CUSTOMER = 'customer',
@@ -18,44 +12,9 @@ export enum TimeFormat {
export const DEFAULT_TIMEZONE = 'Etc/GMT'
-export interface SelfhostedUser {
- id: string
- email: string
- isTwoFactorAuthenticationEnabled: boolean
- planCode: 'enterprise'
- roles: UserType[]
- isActive: boolean
- timezone: string
- timeFormat: TimeFormat
- showLiveVisitorsInTitle: boolean
- apiKey?: string
-}
-
-export const generateSelfhostedUser = (): SelfhostedUser => ({
- id: SELFHOSTED_UUID,
- email: SELFHOSTED_EMAIL,
- isTwoFactorAuthenticationEnabled: false,
- planCode: 'enterprise',
- roles: [UserType.ADMIN, UserType.CUSTOMER],
- isActive: true,
- timezone: DEFAULT_TIMEZONE,
- timeFormat: TimeFormat['12-hour'],
- showLiveVisitorsInTitle: false,
- apiKey: SELFHOSTED_API_KEY,
-})
-
-export const getSelfhostedUser = async (): Promise<SelfhostedUser> => {
- const user = generateSelfhostedUser()
- let settings = {}
-
- try {
- settings = _omit(await getUserClickhouse(), ['id'])
- } catch (reason) {
- console.error('[ERROR] getSelfhostedUser: ', reason)
- }
-
- return {
- ...user,
- ...settings,
- }
+export enum OnboardingStep {
+ CREATE_PROJECT = 'create_project',
+ SETUP_TRACKING = 'setup_tracking',
+ WAITING_FOR_EVENTS = 'waiting_for_events',
+ COMPLETED = 'completed',
}
diff --git a/backend/apps/community/src/user/user.controller.ts b/backend/apps/community/src/user/user.controller.ts
index 684f06ff7..030792927 100644
--- a/backend/apps/community/src/user/user.controller.ts
+++ b/backend/apps/community/src/user/user.controller.ts
@@ -5,42 +5,44 @@ import {
UseGuards,
Body,
BadRequestException,
+ Post,
} from '@nestjs/common'
-import { ApiBearerAuth, ApiTags } from '@nestjs/swagger'
+import { ApiBearerAuth, ApiResponse, ApiTags } from '@nestjs/swagger'
import _omit from 'lodash/omit'
import { JwtAccessTokenGuard } from '../auth/guards'
-import {
- UserType,
- SelfhostedUser,
- generateSelfhostedUser,
- getSelfhostedUser,
-} from './entities/user.entity'
+import { OnboardingStep, UserType } from './entities/user.entity'
import { UpdateUserProfileDTO } from './dto/update-user.dto'
import { SetShowLiveVisitorsDTO } from './dto/set-show-live-visitors.dto'
import { Roles } from '../auth/decorators/roles.decorator'
import { RolesGuard } from '../auth/guards/roles.guard'
import { CurrentUserId } from '../auth/decorators/current-user-id.decorator'
import { AppLoggerService } from '../logger/logger.service'
-import { updateUserClickhouse, getUserClickhouse } from '../common/utils'
+import { UserService } from './user.service'
+import { ClickhouseUser } from '../common/types'
@ApiTags('User')
@Controller('user')
@UseGuards(JwtAccessTokenGuard, RolesGuard)
export class UserController {
- constructor(private readonly logger: AppLoggerService) {}
+ constructor(
+ private readonly logger: AppLoggerService,
+ private readonly userService: UserService,
+ ) {}
@ApiBearerAuth()
@Get('/me')
@UseGuards(RolesGuard)
@Roles(UserType.CUSTOMER, UserType.ADMIN)
async me(
- @CurrentUserId() user_id: string,
- ): Promise<{ user: SelfhostedUser }> {
- this.logger.log({ user_id }, 'GET /user/me')
+ @CurrentUserId() uid: string,
+ ): Promise<{ user: Partial<ClickhouseUser> }> {
+ this.logger.log({ uid }, 'GET /user/me')
+
+ const user = await this.userService.findOne({ id: uid })
return {
- user: await getSelfhostedUser(),
+ user: this.userService.omitSensitiveData(user),
}
}
@@ -50,11 +52,12 @@ export class UserController {
@Roles(UserType.CUSTOMER, UserType.ADMIN)
async setShowLiveVisitors(
@Body() body: SetShowLiveVisitorsDTO,
- ): Promise<Partial<SelfhostedUser>> {
+ @CurrentUserId() id: string,
+ ) {
const { show } = body
try {
- await updateUserClickhouse({
+ await this.userService.update(id, {
showLiveVisitorsInTitle: Number(show),
})
} catch (reason) {
@@ -72,6 +75,40 @@ export class UserController {
}
}
+ @ApiBearerAuth()
+ @Post('onboarding/step')
+ @UseGuards(JwtAccessTokenGuard, RolesGuard)
+ @Roles(UserType.CUSTOMER, UserType.ADMIN)
+ @ApiResponse({ status: 204 })
+ async updateOnboardingStep(
+ @CurrentUserId() userId: string,
+ @Body('step') step: OnboardingStep,
+ ): Promise<void> {
+ this.logger.log({ userId, step }, 'POST /user/onboarding/step')
+
+ if (!Object.values(OnboardingStep).includes(step)) {
+ throw new BadRequestException('Invalid onboarding step')
+ }
+
+ await this.userService.update(userId, {
+ onboardingStep: step,
+ })
+ }
+
+ @ApiBearerAuth()
+ @Post('onboarding/complete')
+ @UseGuards(JwtAccessTokenGuard, RolesGuard)
+ @Roles(UserType.CUSTOMER, UserType.ADMIN)
+ @ApiResponse({ status: 204 })
+ async completeOnboarding(@CurrentUserId() userId: string): Promise<void> {
+ this.logger.log({ userId }, 'POST /user/onboarding/complete')
+
+ await this.userService.update(userId, {
+ onboardingStep: OnboardingStep.COMPLETED,
+ hasCompletedOnboarding: 1,
+ })
+ }
+
@ApiBearerAuth()
@Put('/')
@UseGuards(JwtAccessTokenGuard, RolesGuard)
@@ -79,21 +116,23 @@ export class UserController {
async updateCurrentUser(
@Body() userDTO: UpdateUserProfileDTO,
@CurrentUserId() id: string,
- ): Promise<SelfhostedUser> {
+ ) {
this.logger.log({ userDTO, id }, 'PUT /user')
+ const originalUser = await this.userService.findOne({ id })
+
+ if (!originalUser) {
+ throw new BadRequestException('User not found')
+ }
+
try {
- await updateUserClickhouse({
+ const user = await this.userService.update(id, {
timeFormat: userDTO.timeFormat,
timezone: userDTO.timezone,
})
- const user = generateSelfhostedUser()
- const settings = _omit(await getUserClickhouse(), ['id'])
-
return {
- ...user,
- ...settings,
+ ...this.userService.omitSensitiveData(user),
}
} catch (reason) {
console.error(
diff --git a/backend/apps/community/src/user/user.service.ts b/backend/apps/community/src/user/user.service.ts
index 5e34520ed..a10583316 100644
--- a/backend/apps/community/src/user/user.service.ts
+++ b/backend/apps/community/src/user/user.service.ts
@@ -1,4 +1,161 @@
import { Injectable } from '@nestjs/common'
+import { v4 as uuidv4 } from 'uuid'
+import _omit from 'lodash/omit'
+import { clickhouse } from '../common/integrations/clickhouse'
+import { type ClickhouseUser } from '../common/types'
+import {
+ DEFAULT_TIMEZONE,
+ OnboardingStep,
+ TimeFormat,
+} from './entities/user.entity'
@Injectable()
-export class UserService {}
+export class UserService {
+ async findOne(
+ options: Partial<ClickhouseUser>,
+ ): Promise<ClickhouseUser | undefined> {
+ const paramTypes: Record<keyof ClickhouseUser, string> = {
+ id: 'FixedString(36)',
+ email: 'String',
+ password: 'String',
+ timezone: 'String',
+ timeFormat: 'String',
+ showLiveVisitorsInTitle: 'Int8',
+ onboardingStep: 'String',
+ hasCompletedOnboarding: 'Int8',
+ apiKey: 'String',
+ }
+
+ const entries = Object.entries(options).filter(
+ ([key, value]) => key in paramTypes && value !== undefined,
+ ) as [keyof ClickhouseUser, unknown][]
+
+ const conditions: string[] = []
+ const queryParams: Record<string, unknown> = {}
+
+ for (const [key, value] of entries) {
+ if (value === null) {
+ conditions.push(`${String(key)} IS NULL`)
+ } else {
+ conditions.push(`${String(key)} = {${String(key)}:${paramTypes[key]}}`)
+ queryParams[String(key)] = value
+ }
+ }
+
+ const where = conditions.length > 0 ? conditions.join(' AND ') : '1'
+
+ const { data } = await clickhouse
+ .query({
+ query: `SELECT * FROM user WHERE ${where}`,
+ query_params: queryParams,
+ })
+ .then(resultSet => resultSet.json<ClickhouseUser>())
+
+ return data[0]
+ }
+
+ async update(userId: string, update: Partial<ClickhouseUser>) {
+ const allowedKeys: Array<keyof ClickhouseUser> = [
+ 'email',
+ 'password',
+ 'timezone',
+ 'timeFormat',
+ 'showLiveVisitorsInTitle',
+ 'onboardingStep',
+ 'hasCompletedOnboarding',
+ 'apiKey',
+ ]
+
+ const rawEntries = Object.entries(update) as [
+ keyof ClickhouseUser,
+ unknown,
+ ][]
+ const entries = rawEntries.filter(
+ ([key, value]) => allowedKeys.includes(key) && value !== undefined,
+ )
+
+ if (entries.length === 0) {
+ return this.findOne({ id: userId })
+ }
+
+ const assignments: string[] = []
+ const queryParams: Record<string, unknown> = {}
+
+ for (const [key, value] of entries) {
+ // Support explicit clearing of the nullable apiKey column
+ if (value === null) {
+ if (key === 'apiKey') {
+ assignments.push('apiKey = NULL')
+ }
+ continue
+ }
+
+ const type = [
+ 'showLiveVisitorsInTitle',
+ 'hasCompletedOnboarding',
+ ].includes(key)
+ ? 'Int8'
+ : 'String'
+
+ assignments.push(`${String(key)} = {${String(key)}:${type}}`)
+ queryParams[String(key)] = value
+ }
+
+ if (assignments.length === 0) {
+ return this.findOne({ id: userId })
+ }
+
+ const query = `ALTER TABLE user UPDATE ${assignments.join(
+ ', ',
+ )} WHERE id = {id:FixedString(36)}`
+
+ await clickhouse.command({
+ query,
+ query_params: {
+ ...queryParams,
+ id: userId,
+ },
+ })
+
+ return this.findOne({ id: userId })
+ }
+
+ async create(user: Pick<ClickhouseUser, 'email' | 'password'>) {
+ const id = uuidv4()
+
+ await clickhouse.insert({
+ table: 'user',
+ format: 'JSONEachRow',
+ values: [
+ {
+ id,
+ email: user.email || '',
+ password: user.password || '',
+ timezone: DEFAULT_TIMEZONE,
+ timeFormat: TimeFormat['24-hour'],
+ showLiveVisitorsInTitle: 0,
+ onboardingStep: OnboardingStep.CREATE_PROJECT,
+ hasCompletedOnboarding: 0,
+ apiKey: null,
+ },
+ ],
+ })
+
+ return this.findOne({ id })
+ }
+
+ async count() {
+ const { data } = await clickhouse
+ .query({
+ query: 'SELECT count() as total FROM user',
+ })
+ .then(resultSet => resultSet.json<{ total: number }>())
+
+ const total = Array.isArray(data) && data.length > 0 ? data[0].total : 0
+ return Number(total) || 0
+ }
+
+ omitSensitiveData(user: Partial<ClickhouseUser>): Partial<ClickhouseUser> {
+ return _omit(user, ['password'])
+ }
+}
diff --git a/backend/migrations/clickhouse/initialise_selfhosted.js b/backend/migrations/clickhouse/initialise_selfhosted.js
index 805f02e71..1a613d6d0 100644
--- a/backend/migrations/clickhouse/initialise_selfhosted.js
+++ b/backend/migrations/clickhouse/initialise_selfhosted.js
@@ -3,6 +3,21 @@ const { queriesRunner, dbName } = require('./setup')
const { initialiseDatabase } = require('./initialise_database')
const CLICKHOUSE_INIT_QUERIES = [
+ `CREATE TABLE IF NOT EXISTS ${dbName}.user
+ (
+ id FixedString(36),
+ email String,
+ password String,
+ timezone String,
+ timeFormat String,
+ showLiveVisitorsInTitle Int8,
+ onboardingStep String,
+ hasCompletedOnboarding Int8,
+ apiKey Nullable(String)
+ )
+ ENGINE = MergeTree()
+ PRIMARY KEY id;`,
+
`CREATE TABLE IF NOT EXISTS ${dbName}.project
(
id FixedString(12),
@@ -14,6 +29,7 @@ const CLICKHOUSE_INIT_QUERIES = [
isPasswordProtected Int8,
botsProtectionLevel String DEFAULT 'basic',
passwordHash Nullable(String),
+ adminId Nullable(String),
created DateTime
)
ENGINE = MergeTree()
@@ -28,16 +44,6 @@ const CLICKHOUSE_INIT_QUERIES = [
ENGINE = MergeTree()
ORDER BY userId;`,
- `CREATE TABLE IF NOT EXISTS ${dbName}.sfuser
- (
- id String,
- timezone Nullable(String),
- timeFormat Nullable(String),
- showLiveVisitorsInTitle Nullable(Int8)
- )
- ENGINE = MergeTree()
- PRIMARY KEY id;`,
-
`CREATE TABLE IF NOT EXISTS ${dbName}.funnel
(
id String,
diff --git a/backend/migrations/clickhouse/selfhosted_v3_to_v4.js b/backend/migrations/clickhouse/selfhosted_v3_to_v4.js
new file mode 100644
index 000000000..ea730fdd0
--- /dev/null
+++ b/backend/migrations/clickhouse/selfhosted_v3_to_v4.js
@@ -0,0 +1,33 @@
+const { queriesRunner, dbName } = require('./setup')
+
+const queries = [
+ `CREATE TABLE IF NOT EXISTS ${dbName}.user
+ (
+ id FixedString(36),
+ email String,
+ password String,
+ timezone String,
+ timeFormat String,
+ showLiveVisitorsInTitle Int8,
+ onboardingStep String,
+ hasCompletedOnboarding Int8,
+ apiKey Nullable(String)
+ )
+ ENGINE = MergeTree()
+ PRIMARY KEY id;`,
+
+ `DROP TABLE IF EXISTS ${dbName}.sfuser`,
+
+ `ALTER TABLE ${dbName}.project ADD COLUMN adminId Nullable(String) AFTER passwordHash`,
+]
+
+async function runMigrations() {
+ try {
+ await queriesRunner(queries)
+ console.log('[INFO] SWETRIX CE V4 - MIGRATIONS FINISHED')
+ } catch (reason) {
+ console.error('Error running migration:', reason)
+ }
+}
+
+runMigrations()
diff --git a/web/app/components/Footer/index.tsx b/web/app/components/Footer/index.tsx
index 765b6b12d..7834dd875 100644
--- a/web/app/components/Footer/index.tsx
+++ b/web/app/components/Footer/index.tsx
@@ -32,7 +32,7 @@ import SwetrixLogo from '~/ui/icons/SwetrixLogo'
import { cn } from '~/utils/generic'
import routesPath from '~/utils/routes'
-const CONTACT_US_URL = `https://swetrix.com${routesPath.contact}`
+export const CONTACT_US_URL = `https://swetrix.com${routesPath.contact}`
const ABOUT_US_URL = `https://swetrix.com${routesPath.about}`
const navigation = {
diff --git a/web/app/components/Header/index.tsx b/web/app/components/Header/index.tsx
index 8a3a474a3..300bb9324 100644
--- a/web/app/components/Header/index.tsx
+++ b/web/app/components/Header/index.tsx
@@ -576,7 +576,7 @@ const NotAuthedHeader = ({
to={routes.signup}
className='flex items-center text-base leading-6 font-semibold text-slate-800 hover:text-slate-700 dark:text-slate-200 dark:hover:text-white'
>
- {t('header.startForFree')}
+ {isSelfhosted ? t('header.signUp') : t('header.startForFree')}
<ArrowRightIcon className='mt-[1px] ml-1 h-4 w-4 stroke-2' />
</Link>
</>
@@ -885,7 +885,7 @@ const Header = ({ refPage, transparent }: HeaderProps) => {
className='-mx-3 block rounded-lg px-3 py-2 text-base leading-7 font-semibold text-gray-900 hover:bg-gray-300/50 dark:text-gray-50 dark:hover:bg-slate-700/80'
aria-label={t('titles.signup')}
>
- {t('header.startForFree')}
+ {isSelfhosted ? t('header.signUp') : t('header.startForFree')}
</Link>
</>
)}
diff --git a/web/app/lib/constants/index.ts b/web/app/lib/constants/index.ts
index 48a4809e9..923f84fd0 100644
--- a/web/app/lib/constants/index.ts
+++ b/web/app/lib/constants/index.ts
@@ -324,8 +324,6 @@ export const GDPR_EXPORT_TIMEFRAME = 14 // days
export const SHOW_BANNER_AT_PERC = 85 // show banner when 85% of events in tier are used
-export const TITLE_SUFFIX = '| Swetrix'
-
export const LS_THEME_SETTING = 'colour-theme'
export const LS_VIEW_PREFS_SETTING = 'proj-view-preferences'
export const LS_CAPTCHA_VIEW_PREFS_SETTING = 'captcha-view-preferences'
@@ -394,6 +392,8 @@ export const isDisableMarketingPages =
export const apiUrlUnprocessed = isSelfhosted || !isStaging ? PRODUCTION_API_URL : STAGING_API_URL
const cdnUrlUnprocessed = isBrowser ? window.REMIX_ENV?.CDN_URL : process.env.CDN_URL
+export const TITLE_SUFFIX = isSelfhosted ? '| Swetrix Community Edition' : '| Swetrix'
+
export const API_URL = _endsWith(apiUrlUnprocessed, '/') ? apiUrlUnprocessed : `${apiUrlUnprocessed}/`
export const CDN_URL = _endsWith(cdnUrlUnprocessed, '/') ? cdnUrlUnprocessed : `${cdnUrlUnprocessed}/`
const NODE_ENV = isBrowser ? window.REMIX_ENV?.NODE_ENV : process.env.NODE_ENV
diff --git a/web/app/pages/Auth/CreateNewPassword/CreateNewPassword.tsx b/web/app/pages/Auth/CreateNewPassword/CreateNewPassword.tsx
index c924089de..fc01c5638 100644
--- a/web/app/pages/Auth/CreateNewPassword/CreateNewPassword.tsx
+++ b/web/app/pages/Auth/CreateNewPassword/CreateNewPassword.tsx
@@ -100,7 +100,7 @@ const CreateNewPassword = () => {
return (
<div>
- <div className='min-h-min-footer flex flex-col bg-gray-50 px-4 py-6 sm:px-6 lg:px-8 dark:bg-slate-900'>
+ <div className='min-h-min-footer flex flex-col bg-gray-50 px-4 py-10 sm:px-6 lg:px-8 dark:bg-slate-900'>
<div className='sm:mx-auto sm:w-full sm:max-w-md'>
<h2 className='text-center text-2xl leading-9 font-bold text-gray-900 dark:text-gray-50'>
{t('auth.recovery.title')}
diff --git a/web/app/pages/Auth/ForgotPassword/ForgotPassword.tsx b/web/app/pages/Auth/ForgotPassword/ForgotPassword.tsx
index 7f7fc891e..0644c83be 100644
--- a/web/app/pages/Auth/ForgotPassword/ForgotPassword.tsx
+++ b/web/app/pages/Auth/ForgotPassword/ForgotPassword.tsx
@@ -85,7 +85,7 @@ const ForgotPassword = () => {
return (
<div>
- <div className='min-h-min-footer flex flex-col bg-gray-50 px-4 py-6 sm:px-6 lg:px-8 dark:bg-slate-900'>
+ <div className='min-h-min-footer flex flex-col bg-gray-50 px-4 py-10 sm:px-6 lg:px-8 dark:bg-slate-900'>
<div className='sm:mx-auto sm:w-full sm:max-w-md'>
<h2 className='text-center text-2xl leading-9 font-bold text-gray-900 dark:text-gray-50'>
{t('titles.recovery')}
diff --git a/web/app/pages/Auth/Signin/Signin.tsx b/web/app/pages/Auth/Signin/Signin.tsx
index f31a29fb8..15becf609 100644
--- a/web/app/pages/Auth/Signin/Signin.tsx
+++ b/web/app/pages/Auth/Signin/Signin.tsx
@@ -249,7 +249,7 @@ const Signin = () => {
if (isTwoFARequired) {
return (
- <div className='min-h-page flex flex-col bg-gray-50 px-4 py-6 sm:px-6 lg:px-8 dark:bg-slate-900'>
+ <div className='min-h-page flex flex-col bg-gray-50 px-4 py-10 sm:px-6 lg:px-8 dark:bg-slate-900'>
<form className='mx-auto max-w-prose' onSubmit={_submit2FA}>
<h2 className='mt-2 text-3xl font-bold text-gray-900 dark:text-gray-50'>{t('auth.signin.2fa')}</h2>
<p className='mt-4 text-base whitespace-pre-line text-gray-900 dark:text-gray-50'>
@@ -288,7 +288,7 @@ const Signin = () => {
}
return (
- <div className='min-h-min-footer flex flex-col bg-gray-50 px-4 py-6 sm:px-6 lg:px-8 dark:bg-slate-900'>
+ <div className='min-h-min-footer flex flex-col bg-gray-50 px-4 py-10 sm:px-6 lg:px-8 dark:bg-slate-900'>
<div className='sm:mx-auto sm:w-full sm:max-w-md'>
<h2 className='text-center text-2xl leading-9 font-bold text-gray-900 dark:text-gray-50'>
{t('auth.signin.title')}
diff --git a/web/app/pages/Auth/Signup/Signup.tsx b/web/app/pages/Auth/Signup/Signup.tsx
index 488749045..412829461 100644
--- a/web/app/pages/Auth/Signup/Signup.tsx
+++ b/web/app/pages/Auth/Signup/Signup.tsx
@@ -9,7 +9,8 @@ import { toast } from 'sonner'
import { generateSSOAuthURL, getJWTBySSOHash, signup } from '~/api'
import GithubAuth from '~/components/GithubAuth'
import GoogleAuth from '~/components/GoogleAuth'
-import { HAVE_I_BEEN_PWNED_URL, REFERRAL_COOKIE, TRIAL_DAYS } from '~/lib/constants'
+import OIDCAuth from '~/components/OIDCAuth'
+import { HAVE_I_BEEN_PWNED_URL, isSelfhosted, REFERRAL_COOKIE, TRIAL_DAYS } from '~/lib/constants'
import { SSOProvider } from '~/lib/models/Auth'
import { useAuth } from '~/providers/AuthProvider'
import Button from '~/ui/Button'
@@ -19,7 +20,7 @@ import Tooltip from '~/ui/Tooltip'
import { setAccessToken } from '~/utils/accessToken'
import { trackCustom } from '~/utils/analytics'
import { deleteCookie, getCookie } from '~/utils/cookie'
-import { delay, openBrowserWindow } from '~/utils/generic'
+import { cn, delay, openBrowserWindow } from '~/utils/generic'
import { setRefreshToken } from '~/utils/refreshToken'
import routes from '~/utils/routes'
import { isValidEmail, isValidPassword, MIN_PASSWORD_CHARS, MAX_PASSWORD_CHARS } from '~/utils/validator'
@@ -81,7 +82,7 @@ const Signup = () => {
allErrors.password = t('auth.common.passwordTooLong', { amount: MAX_PASSWORD_CHARS })
}
- if (!form.tos) {
+ if (!form.tos && !isSelfhosted) {
allErrors.tos = t('auth.common.tosError')
}
@@ -136,7 +137,7 @@ const Signup = () => {
})
navigate(routes.onboarding)
} catch (reason) {
- toast.error(typeof reason === 'string' ? reason : t('apiNotifications.somethingWentWrong'))
+ toast.error((reason as { message?: string })?.message || t('apiNotifications.somethingWentWrong'))
setIsLoading(false)
}
}
@@ -204,7 +205,7 @@ const Signup = () => {
}
}
} catch (reason) {
- toast.error(typeof reason === 'string' ? reason : t('apiNotifications.socialisationGenericError'))
+ toast.error((reason as { message?: string })?.message || t('apiNotifications.socialisationGenericError'))
setIsLoading(false)
return
}
@@ -231,44 +232,48 @@ const Signup = () => {
return (
<div>
- <div className='min-h-min-footer flex flex-col bg-gray-50 px-4 py-6 sm:px-6 lg:px-8 dark:bg-slate-900'>
- <div className='flex min-h-full flex-1 flex-col justify-center py-6 sm:px-6 lg:px-8'>
- <div className='sm:mx-auto sm:w-full sm:max-w-md'>
- <h2 className='text-center text-2xl leading-9 font-bold text-gray-900 dark:text-gray-50'>
- {t('auth.signup.trial', {
- amount: TRIAL_DAYS,
- })}
- </h2>
+ <div className='min-h-min-footer flex flex-col bg-gray-50 px-4 py-10 sm:px-6 lg:px-8 dark:bg-slate-900'>
+ <div className='sm:mx-auto sm:w-full sm:max-w-md'>
+ <h2 className='text-center text-2xl leading-9 font-bold text-gray-900 dark:text-gray-50'>
+ {isSelfhosted
+ ? t('auth.signup.createAnAccount')
+ : t('auth.signup.trial', {
+ amount: TRIAL_DAYS,
+ })}
+ </h2>
+ {isSelfhosted ? null : (
<p className='text-center text-base text-gray-900 dark:text-gray-50'>{t('auth.signup.noCC')}</p>
- </div>
- <div className='mt-10 sm:mx-auto sm:w-full sm:max-w-[480px]'>
- <div className='bg-white px-6 py-12 shadow-xs ring-1 ring-gray-200 sm:rounded-lg sm:px-12 dark:bg-slate-900 dark:ring-slate-800'>
- <form className='space-y-6' onSubmit={handleSubmit}>
- <Input
- name='email'
- type='email'
- label={t('auth.common.email')}
- value={form.email}
- onChange={handleInput}
- error={beenSubmitted ? errors.email : ''}
- />
- <Input
- name='password'
- type='password'
- label={t('auth.common.password')}
- hint={t('auth.common.hint', { amount: MIN_PASSWORD_CHARS })}
- value={form.password}
- onChange={handleInput}
- error={beenSubmitted ? errors.password : ''}
- />
- <Input
- name='repeat'
- type='password'
- label={t('auth.common.repeat')}
- value={form.repeat}
- onChange={handleInput}
- error={beenSubmitted ? errors.repeat : ''}
- />
+ )}
+ </div>
+ <div className='mt-10 sm:mx-auto sm:w-full sm:max-w-[480px]'>
+ <div className='bg-white px-6 py-12 shadow-xs ring-1 ring-gray-200 sm:rounded-lg sm:px-12 dark:bg-slate-900 dark:ring-slate-800'>
+ <form className='space-y-6' onSubmit={handleSubmit}>
+ <Input
+ name='email'
+ type='email'
+ label={t('auth.common.email')}
+ value={form.email}
+ onChange={handleInput}
+ error={beenSubmitted ? errors.email : ''}
+ />
+ <Input
+ name='password'
+ type='password'
+ label={t('auth.common.password')}
+ hint={t('auth.common.hint', { amount: MIN_PASSWORD_CHARS })}
+ value={form.password}
+ onChange={handleInput}
+ error={beenSubmitted ? errors.password : ''}
+ />
+ <Input
+ name='repeat'
+ type='password'
+ label={t('auth.common.repeat')}
+ value={form.repeat}
+ onChange={handleInput}
+ error={beenSubmitted ? errors.repeat : ''}
+ />
+ {isSelfhosted ? null : (
<Checkbox
checked={form.tos}
onChange={(checked) =>
@@ -308,80 +313,86 @@ const Signup = () => {
}}
hint={beenSubmitted ? errors.tos : ''}
/>
- <div className='flex'>
- <Checkbox
- checked={form.checkIfLeaked}
- onChange={(checked) =>
- setForm((prev) => ({
- ...prev,
- checkIfLeaked: checked,
- }))
- }
- name='checkIfLeaked'
- label={t('auth.common.checkLeakedPassword')}
- />
- <Tooltip
- className='ml-2'
- text={
- <Trans
- t={t}
- i18nKey='auth.common.checkLeakedPasswordDesc'
- components={{
- db: (
- <a
- href={HAVE_I_BEEN_PWNED_URL}
- className='font-medium text-indigo-400 hover:text-indigo-500 hover:underline dark:text-indigo-400 dark:hover:text-indigo-500'
- target='_blank'
- rel='noreferrer noopener'
- />
- ),
- }}
- values={{
- database: 'haveibeenpwned.com',
- }}
- />
- }
- />
- </div>
- <Button className='w-full justify-center' type='submit' loading={isLoading} primary giant>
- {t('auth.signup.button')}
- </Button>
- </form>
-
- <div>
- <div className='relative mt-10'>
- <div className='absolute inset-0 flex items-center' aria-hidden='true'>
- <div className='w-full border-t border-gray-200 dark:border-gray-600' />
- </div>
- <div className='relative flex justify-center text-sm leading-6 font-medium'>
- <span className='bg-white px-6 text-gray-900 dark:bg-slate-900 dark:text-gray-50'>
- {t('auth.common.orContinueWith')}
- </span>
- </div>
+ )}
+ <div className='flex'>
+ <Checkbox
+ checked={form.checkIfLeaked}
+ onChange={(checked) =>
+ setForm((prev) => ({
+ ...prev,
+ checkIfLeaked: checked,
+ }))
+ }
+ name='checkIfLeaked'
+ label={t('auth.common.checkLeakedPassword')}
+ />
+ <Tooltip
+ className='ml-2'
+ text={
+ <Trans
+ t={t}
+ i18nKey='auth.common.checkLeakedPasswordDesc'
+ components={{
+ db: (
+ <a
+ href={HAVE_I_BEEN_PWNED_URL}
+ className='font-medium text-indigo-400 hover:text-indigo-500 hover:underline dark:text-indigo-400 dark:hover:text-indigo-500'
+ target='_blank'
+ rel='noreferrer noopener'
+ />
+ ),
+ }}
+ values={{
+ database: 'haveibeenpwned.com',
+ }}
+ />
+ }
+ />
+ </div>
+ <Button className='w-full justify-center' type='submit' loading={isLoading} primary giant>
+ {t('auth.signup.button')}
+ </Button>
+ </form>
+
+ <div>
+ <div className='relative mt-10'>
+ <div className='absolute inset-0 flex items-center' aria-hidden='true'>
+ <div className='w-full border-t border-gray-200 dark:border-gray-600' />
</div>
- <div className='mt-6 grid grid-cols-2 gap-4'>
- <GoogleAuth onClick={() => onSsoLogin('google')} disabled={isLoading} />
- <GithubAuth onClick={() => onSsoLogin('github')} disabled={isLoading} />
+ <div className='relative flex justify-center text-sm leading-6 font-medium'>
+ <span className='bg-white px-6 text-gray-900 dark:bg-slate-900 dark:text-gray-50'>
+ {t('auth.common.orContinueWith')}
+ </span>
</div>
</div>
+ <div className={cn('mt-6 grid gap-4', isSelfhosted ? 'grid-cols-1' : 'grid-cols-2')}>
+ {isSelfhosted ? (
+ <OIDCAuth onClick={() => onSsoLogin('openid-connect')} disabled={isLoading} className='w-full' />
+ ) : (
+ <>
+ <GoogleAuth onClick={() => onSsoLogin('google')} disabled={isLoading} />
+ <GithubAuth onClick={() => onSsoLogin('github')} disabled={isLoading} />
+ </>
+ )}
+ </div>
</div>
-
- <p className='mt-10 text-center text-sm text-gray-500 dark:text-gray-200'>
- <Trans
- t={t}
- i18nKey='auth.signup.alreadyAMember'
- components={{
- url: (
- <Link
- to={routes.signin}
- className='leading-6 font-semibold text-indigo-600 hover:underline dark:text-indigo-400'
- aria-label={t('titles.signin')}
- />
- ),
- }}
- />
- </p>
</div>
+
+ <p className='mt-10 text-center text-sm text-gray-500 dark:text-gray-200'>
+ <Trans
+ t={t}
+ i18nKey='auth.signup.alreadyAMember'
+ components={{
+ url: (
+ <Link
+ to={routes.signin}
+ className='leading-6 font-semibold text-indigo-600 hover:underline dark:text-indigo-400'
+ aria-label={t('titles.signin')}
+ />
+ ),
+ }}
+ />
+ </p>
</div>
</div>
</div>
diff --git a/web/app/pages/Onboarding/Onboarding.tsx b/web/app/pages/Onboarding/Onboarding.tsx
index 4f200c6ed..5b113d16a 100644
--- a/web/app/pages/Onboarding/Onboarding.tsx
+++ b/web/app/pages/Onboarding/Onboarding.tsx
@@ -9,8 +9,9 @@ import { Link, useNavigate } from 'react-router'
import { toast } from 'sonner'
import { updateOnboardingStep, completeOnboarding, createProject, authMe, getProjects } from '~/api'
+import { CONTACT_US_URL } from '~/components/Footer'
import { withAuthentication, auth } from '~/hoc/protected'
-import { DOCS_URL, INTEGRATIONS_URL } from '~/lib/constants'
+import { DOCS_URL, INTEGRATIONS_URL, isSelfhosted } from '~/lib/constants'
import { getSnippet } from '~/modals/TrackingSnippet'
import { useAuth } from '~/providers/AuthProvider'
import { Badge } from '~/ui/Badge'
@@ -31,6 +32,7 @@ const getOnboardingSteps = (t: TFunction) => [
title: t('onboarding.confirm.navTitle'),
description: t('onboarding.confirm.navDesc'),
completed: false,
+ uiHidden: isSelfhosted,
},
{
id: 'create_project',
@@ -80,7 +82,7 @@ const Onboarding = () => {
}
const determineCurrentStep = async () => {
- if (!user?.isActive) {
+ if (!user?.isActive && !isSelfhosted) {
setCurrentStep(0)
return
}
@@ -236,6 +238,8 @@ const Onboarding = () => {
<nav aria-label='Progress'>
<ol className='overflow-hidden'>
{steps.map((step, stepIdx) => {
+ if (step.uiHidden) return null
+
const status = step.completed ? 'complete' : step.current ? 'current' : 'upcoming'
return (
@@ -570,7 +574,9 @@ const Onboarding = () => {
components={{
url: (
<Link
- to={routes.contact}
+ to={isSelfhosted ? CONTACT_US_URL : routes.contact}
+ target='_blank'
+ rel='noopener noreferrer'
className='font-medium text-indigo-600 hover:underline dark:text-indigo-400'
/>
),
diff --git a/web/app/routes/privacy.tsx b/web/app/routes/privacy.tsx
index 49eb29221..914a0ddf6 100644
--- a/web/app/routes/privacy.tsx
+++ b/web/app/routes/privacy.tsx
@@ -1,12 +1,23 @@
+import { redirect } from 'react-router'
import type { SitemapFunction } from 'remix-sitemap'
+import { isSelfhosted } from '~/lib/constants'
import Privacy from '~/pages/Privacy'
export const sitemap: SitemapFunction = () => ({
priority: 0.9,
changefreq: 'monthly',
+ exclude: isSelfhosted,
})
-export default function Index() {
+export async function loader() {
+ if (isSelfhosted) {
+ return redirect('/login', 302)
+ }
+
+ return null
+}
+
+export default function PrivacyPage() {
return <Privacy />
}
diff --git a/web/app/routes/signup.tsx b/web/app/routes/signup.tsx
index 8c0fd39b5..6f284c1d7 100644
--- a/web/app/routes/signup.tsx
+++ b/web/app/routes/signup.tsx
@@ -1,5 +1,4 @@
import type { HeadersFunction } from 'react-router'
-import { redirect } from 'react-router'
import type { SitemapFunction } from 'remix-sitemap'
import { isSelfhosted } from '~/lib/constants'
@@ -10,19 +9,11 @@ export const headers: HeadersFunction = ({ parentHeaders }) => {
return parentHeaders
}
-export async function loader() {
- if (isSelfhosted) {
- return redirect('/login', 302)
- }
-
- return null
-}
-
export const sitemap: SitemapFunction = () => ({
priority: 0.9,
exclude: isSelfhosted,
})
-export default function Index() {
+export default function SignupPage() {
return <Singup />
}
diff --git a/web/app/routes/terms.tsx b/web/app/routes/terms.tsx
index 6437c71a5..2693ed1e6 100644
--- a/web/app/routes/terms.tsx
+++ b/web/app/routes/terms.tsx
@@ -1,12 +1,23 @@
+import { redirect } from 'react-router'
import type { SitemapFunction } from 'remix-sitemap'
+import { isSelfhosted } from '~/lib/constants'
import Terms from '~/pages/Terms'
export const sitemap: SitemapFunction = () => ({
priority: 0.9,
changefreq: 'monthly',
+ exclude: isSelfhosted,
})
-export default function Index() {
+export async function loader() {
+ if (isSelfhosted) {
+ return redirect('/login', 302)
+ }
+
+ return null
+}
+
+export default function TermsPage() {
return <Terms />
}
diff --git a/web/app/routes/tools._index.tsx b/web/app/routes/tools._index.tsx
index 7478a39ca..fba0458cb 100644
--- a/web/app/routes/tools._index.tsx
+++ b/web/app/routes/tools._index.tsx
@@ -1,13 +1,23 @@
import { ArrowRightIcon, SparklesIcon, CheckIcon } from 'lucide-react'
-import { Link } from 'react-router'
+import { Link, redirect } from 'react-router'
import type { SitemapFunction } from 'remix-sitemap'
import { DitchGoogle } from '~/components/marketing/DitchGoogle'
+import { isSelfhosted } from '~/lib/constants'
export const sitemap: SitemapFunction = () => ({
priority: 0.9,
+ exclude: isSelfhosted,
})
+export async function loader() {
+ if (isSelfhosted) {
+ return redirect('/login', 302)
+ }
+
+ return null
+}
+
const TOOLS = [
{
title: 'ROI Calculator',
diff --git a/web/app/routes/tools.ctr-calculator.tsx b/web/app/routes/tools.ctr-calculator.tsx
index 3fcd22f0d..f1134e652 100644
--- a/web/app/routes/tools.ctr-calculator.tsx
+++ b/web/app/routes/tools.ctr-calculator.tsx
@@ -1,15 +1,26 @@
import { TrendingUpIcon } from 'lucide-react'
import { useState } from 'react'
+import { redirect } from 'react-router'
import type { SitemapFunction } from 'remix-sitemap'
import { DitchGoogle } from '~/components/marketing/DitchGoogle'
+import { isSelfhosted } from '~/lib/constants'
import Button from '~/ui/Button'
import Input from '~/ui/Input'
export const sitemap: SitemapFunction = () => ({
priority: 0.8,
+ exclude: isSelfhosted,
})
+export async function loader() {
+ if (isSelfhosted) {
+ return redirect('/login', 302)
+ }
+
+ return null
+}
+
const FAQ_ITEMS = [
{
question: 'What is CTR (Click-Through Rate)?',
diff --git a/web/app/routes/tools.roi-calculator.tsx b/web/app/routes/tools.roi-calculator.tsx
index ffca0b43e..bc5dd543d 100644
--- a/web/app/routes/tools.roi-calculator.tsx
+++ b/web/app/routes/tools.roi-calculator.tsx
@@ -1,15 +1,26 @@
import { TrendingUpIcon, DollarSignIcon, ShoppingCartIcon, ChevronDownIcon } from 'lucide-react'
import { useState, useEffect } from 'react'
+import { redirect } from 'react-router'
import type { SitemapFunction } from 'remix-sitemap'
import { DitchGoogle } from '~/components/marketing/DitchGoogle'
+import { isSelfhosted } from '~/lib/constants'
import Input from '~/ui/Input'
import Tooltip from '~/ui/Tooltip'
export const sitemap: SitemapFunction = () => ({
priority: 0.8,
+ exclude: isSelfhosted,
})
+export async function loader() {
+ if (isSelfhosted) {
+ return redirect('/login', 302)
+ }
+
+ return null
+}
+
interface CampaignMetrics {
campaignName: string
adSpend: number
diff --git a/web/app/routes/tools.utm-generator.tsx b/web/app/routes/tools.utm-generator.tsx
index cc85f68b6..4e9e99430 100644
--- a/web/app/routes/tools.utm-generator.tsx
+++ b/web/app/routes/tools.utm-generator.tsx
@@ -1,16 +1,27 @@
import { CopyIcon, ChevronDownIcon } from 'lucide-react'
import { useState } from 'react'
+import { redirect } from 'react-router'
import type { SitemapFunction } from 'remix-sitemap'
import { DitchGoogle } from '~/components/marketing/DitchGoogle'
+import { isSelfhosted } from '~/lib/constants'
import Button from '~/ui/Button'
import Input from '~/ui/Input'
import Tooltip from '~/ui/Tooltip'
export const sitemap: SitemapFunction = () => ({
priority: 0.8,
+ exclude: isSelfhosted,
})
+export async function loader() {
+ if (isSelfhosted) {
+ return redirect('/login', 302)
+ }
+
+ return null
+}
+
interface UTMParams {
url: string
utm_source: string
diff --git a/web/app/routes/user-settings.tsx b/web/app/routes/user-settings.tsx
index fde2163c8..732ff9a6a 100644
--- a/web/app/routes/user-settings.tsx
+++ b/web/app/routes/user-settings.tsx
@@ -6,6 +6,6 @@ export const sitemap: SitemapFunction = () => ({
exclude: true,
})
-export default function Index() {
+export default function UserSettingsPage() {
return <UserSettings />
}
diff --git a/web/public/locales/en.json b/web/public/locales/en.json
index f5a7faae2..e5775e035 100644
--- a/web/public/locales/en.json
+++ b/web/public/locales/en.json
@@ -486,7 +486,8 @@
"create": "Create your account",
"trial": "Start your free {{amount}} day trial",
"noCC": "No credit card required.",
- "alreadyAMember": "Already a member? <url>Sign in</url>"
+ "alreadyAMember": "Already a member? <url>Sign in</url>",
+ "createAnAccount": "Create an account"
},
"verification": {
"success": "Your email has been successfully verified!",
@@ -1379,6 +1380,7 @@
},
"header": {
"startForFree": "Start for free",
+ "signUp": "Sign up",
"switchTheme": "Switch theme",
"dark": "Dark",
"light": "Light",