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!

6.0 KB
Raw Blame
import { BadRequestException, Injectable } from '@nestjs/common'
import { randomUUID } from 'crypto'
import _omit from 'lodash/omit'
import _isEmpty from 'lodash/isEmpty'
import _size from 'lodash/size'
import { clickhouse } from '../common/integrations/clickhouse'
import { User, type ClickhouseInputUser } from '../common/types'
import {
  DEFAULT_TIMEZONE,
  OnboardingStep,
  TimeFormat,
} from './entities/user.entity'

@Injectable()
export class UserService {
  async findOne(options: Partial<ClickhouseInputUser>) {
    const paramTypes: Record<keyof ClickhouseInputUser, string> = {
      id: 'FixedString(36)',
      email: 'String',
      password: 'String',
      timezone: 'String',
      timeFormat: 'String',
      showLiveVisitorsInTitle: 'Int8',
      onboardingStep: 'String',
      hasCompletedOnboarding: 'Int8',
      apiKey: 'String',
      twoFactorAuthenticationSecret: 'String',
      twoFactorRecoveryCode: 'String',
      isTwoFactorAuthenticationEnabled: 'Int8',
    }

    const entries = Object.entries(options).filter(
      ([key, value]) => key in paramTypes && value !== undefined,
    ) as [keyof ClickhouseInputUser, 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<ClickhouseInputUser>())

    return this.formatUser(data[0])
  }

  async update(userId: string, update: Partial<ClickhouseInputUser>) {
    const allowedKeys: Array<keyof ClickhouseInputUser> = [
      'email',
      'password',
      'timezone',
      'timeFormat',
      'showLiveVisitorsInTitle',
      'onboardingStep',
      'hasCompletedOnboarding',
      'apiKey',
      'twoFactorAuthenticationSecret',
      'twoFactorRecoveryCode',
      'isTwoFactorAuthenticationEnabled',
    ]

    const rawEntries = Object.entries(update) as [
      keyof ClickhouseInputUser,
      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) {
        const nullableKeys: Array<keyof ClickhouseInputUser> = [
          'apiKey',
          'twoFactorAuthenticationSecret',
          'twoFactorRecoveryCode',
        ]
        if (nullableKeys.includes(key)) {
          assignments.push(`${String(key)} = NULL`)
        }
        continue
      }

      const type = [
        'showLiveVisitorsInTitle',
        'hasCompletedOnboarding',
        'isTwoFactorAuthenticationEnabled',
      ].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 delete(userId: string) {
    await clickhouse.command({
      query: 'ALTER TABLE api_key DELETE WHERE userId = {userId:String}',
      query_params: { userId },
      clickhouse_settings: { mutations_sync: '2' },
    })
    await clickhouse.command({
      query: `ALTER TABLE user DELETE WHERE id = {id:FixedString(36)}`,
      query_params: { id: userId },
    })
  }

  async create(user: Pick<ClickhouseInputUser, 'email' | 'password'>) {
    const id = randomUUID()

    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.LANGUAGE,
          hasCompletedOnboarding: 0,
          apiKey: null,
          twoFactorAuthenticationSecret: null,
          twoFactorRecoveryCode: null,
          isTwoFactorAuthenticationEnabled: 0,
        },
      ],
    })

    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<User>): Partial<User> {
    return _omit(user, [
      'password',
      'apiKey',
      'apiKeyAccess',
      'twoFactorAuthenticationSecret',
      'twoFactorRecoveryCode',
    ])
  }

  validatePassword(pass: string): void {
    const err = []
    if (_isEmpty(pass)) {
      err.push('Password cannot be empty')
    }

    if (_size(pass) > 50) {
      err.push('Maximum password length is 50 letters')
    }

    if (_size(pass) < 8) {
      err.push('at least 8 characters')
    }

    if (!_isEmpty(err)) {
      throw new BadRequestException(err)
    }
  }

  formatUser(user?: ClickhouseInputUser): User {
    if (!user) {
      return undefined
    }

    return {
      ...user,
      showLiveVisitorsInTitle: Boolean(user.showLiveVisitorsInTitle),
      hasCompletedOnboarding: Boolean(user.hasCompletedOnboarding),
      isTwoFactorAuthenticationEnabled: Boolean(
        user.isTwoFactorAuthenticationEnabled,
      ),
    }
  }
}