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!

added timezone & time notation selfhosted user settings

Blue Mousee2090f790644
diff --git a/apps/selfhosted/src/auth/auth.controller.ts b/apps/selfhosted/src/auth/auth.controller.ts
index 42d617a6a..105b70dfa 100644
--- a/apps/selfhosted/src/auth/auth.controller.ts
+++ b/apps/selfhosted/src/auth/auth.controller.ts
@@ -16,8 +16,8 @@ import {
import { ApiTags, ApiOperation, ApiOkResponse } from '@nestjs/swagger'
import { I18nValidationExceptionFilter, I18n, I18nContext } from 'nestjs-i18n'
-import { checkRateLimit } from 'src/common/utils'
-import { generateSelfhostedUser } from 'src/user/entities/user.entity'
+import { getUserClickhouse, checkRateLimit } from '../common/utils'
+import { generateSelfhostedUser } from '../user/entities/user.entity'
import { AuthService } from './auth.service'
import { Public, CurrentUserId, CurrentUser } from './decorators'
import { LoginResponseDto, LoginRequestDto } from './dtos'
@@ -104,7 +104,6 @@ export class AuthController {
const accessToken = await this.authService.generateJwtAccessToken(
user.id,
- user.isTwoFactorAuthenticationEnabled,
)
return { accessToken }
diff --git a/apps/selfhosted/src/auth/auth.service.ts b/apps/selfhosted/src/auth/auth.service.ts
index 5009c5442..cc80d3401 100644
--- a/apps/selfhosted/src/auth/auth.service.ts
+++ b/apps/selfhosted/src/auth/auth.service.ts
@@ -4,20 +4,19 @@ import { JwtService } from '@nestjs/jwt'
import { genSalt, hash } from 'bcrypt'
import * as _isEmpty from 'lodash/isEmpty'
-import {
- SelfhostedUser,
- generateSelfhostedUser,
-} from 'src/user/entities/user.entity'
import {
saveRefreshTokenClickhouse,
findRefreshTokenClickhouse,
deleteRefreshTokenClickhouse,
-} from 'src/common/utils'
+} from '../common/utils'
import {
SELFHOSTED_EMAIL,
SELFHOSTED_PASSWORD,
JWT_ACCESS_TOKEN_SECRET,
-} from 'src/common/constants'
+} from '../common/constants'
+import {
+ getSelfhostedUser, SelfhostedUser,
+} from '../user/entities/user.entity'
@Injectable()
export class AuthService {
@@ -56,7 +55,7 @@ export class AuthService {
return null
}
- return generateSelfhostedUser()
+ return await getSelfhostedUser()
}
private async generateJwtRefreshToken(
diff --git a/apps/selfhosted/src/auth/strategies/jwt-access-token.strategy.ts b/apps/selfhosted/src/auth/strategies/jwt-access-token.strategy.ts
index c601d8530..31bde65f0 100644
--- a/apps/selfhosted/src/auth/strategies/jwt-access-token.strategy.ts
+++ b/apps/selfhosted/src/auth/strategies/jwt-access-token.strategy.ts
@@ -3,8 +3,8 @@ import { ConfigService } from '@nestjs/config'
import { PassportStrategy } from '@nestjs/passport'
import { Strategy, ExtractJwt } from 'passport-jwt'
-import { SELFHOSTED_UUID, JWT_ACCESS_TOKEN_SECRET } from 'src/common/constants'
-import { generateSelfhostedUser } from 'src/user/entities/user.entity'
+import { SELFHOSTED_UUID, JWT_ACCESS_TOKEN_SECRET } from '../../common/constants'
+import { getSelfhostedUser } from '../../user/entities/user.entity'
import { IJwtPayload } from '../interfaces'
@Injectable()
@@ -25,6 +25,6 @@ export class JwtAccessTokenStrategy extends PassportStrategy(
throw new UnauthorizedException()
}
- return generateSelfhostedUser()
+ return await getSelfhostedUser()
}
}
diff --git a/apps/selfhosted/src/common/utils.ts b/apps/selfhosted/src/common/utils.ts
index d64a27bcc..8939e0a86 100644
--- a/apps/selfhosted/src/common/utils.ts
+++ b/apps/selfhosted/src/common/utils.ts
@@ -186,6 +186,89 @@ const deleteRefreshTokenClickhouse = async (
return clickhouse.query(query, paramsData).toPromise()
}
+interface IClickhouseUser {
+ timezone?: string
+ timeFormat?: string
+}
+
+const CLICKHOUSE_SETTINGS_ID = 'sfuser'
+
+const createUserClickhouse = async (user: IClickhouseUser) => {
+ const paramsData = {
+ params: {
+ ...user,
+ id: CLICKHOUSE_SETTINGS_ID,
+ },
+ }
+
+ const query = `INSERT INTO sfuser (*) VALUES ({id:String},{timezone:String},{timeFormat:String})`
+
+ return clickhouse.query(query, paramsData).toPromise()
+}
+
+const getUserClickhouse = async () => {
+ const paramsData = {
+ params: {
+ id: CLICKHOUSE_SETTINGS_ID,
+ },
+ }
+
+ const query = `SELECT * FROM sfuser WHERE id = {id:String}`
+
+ try {
+ return ((await clickhouse.query(query, paramsData).toPromise())[0] || {})
+ } catch {
+ return {}
+ }
+}
+
+const userClickhouseExists = async () => {
+ const query = `SELECT * FROM sfuser WHERE id = '${CLICKHOUSE_SETTINGS_ID}'`
+
+ try {
+ const result = await clickhouse.query(query).toPromise()
+ return !_isEmpty(result)
+ } catch {
+ return false
+ }
+}
+
+const updateUserClickhouse = async (user: IClickhouseUser) => {
+ console.log(user)
+ const userExists = await userClickhouseExists()
+
+ if (!userExists) {
+ await createUserClickhouse(user)
+ }
+
+ const paramsData = {
+ params: {
+ ...user,
+ id: CLICKHOUSE_SETTINGS_ID,
+ },
+ }
+
+ let query = 'ALTER table sfuser UPDATE '
+
+ if (user.timezone) {
+ query += `timezone={timezone:String}`
+ }
+
+ if (user.timeFormat) {
+ if (user.timezone) {
+ query += ', '
+ }
+
+ query += `timeFormat={timeFormat:String}`
+ }
+
+ query += ` WHERE id={id:String}`
+
+ console.log(query, paramsData)
+
+ return clickhouse.query(query, paramsData).toPromise()
+}
+
const millisecondsToSeconds = (milliseconds: number) => milliseconds / 1000
const getSelfhostedUUID = (): string => {
@@ -208,4 +291,7 @@ export {
saveRefreshTokenClickhouse,
findRefreshTokenClickhouse,
deleteRefreshTokenClickhouse,
+ updateUserClickhouse,
+ getUserClickhouse,
+ createUserClickhouse,
}
diff --git a/apps/selfhosted/src/user/dto/update-user.dto.ts b/apps/selfhosted/src/user/dto/update-user.dto.ts
new file mode 100644
index 000000000..edee5c092
--- /dev/null
+++ b/apps/selfhosted/src/user/dto/update-user.dto.ts
@@ -0,0 +1,10 @@
+import { ApiProperty } from '@nestjs/swagger'
+import { TimeFormat } from '../entities/user.entity'
+
+export class UpdateUserProfileDTO {
+ @ApiProperty({ example: 'Europe/Kiev' })
+ timezone: string
+
+ @ApiProperty({ example: '24-hour', enum: TimeFormat })
+ timeFormat: string
+}
diff --git a/apps/selfhosted/src/user/entities/user.entity.ts b/apps/selfhosted/src/user/entities/user.entity.ts
index 01daf3b8c..4c0390b7a 100644
--- a/apps/selfhosted/src/user/entities/user.entity.ts
+++ b/apps/selfhosted/src/user/entities/user.entity.ts
@@ -1,4 +1,6 @@
+import * as _omit from 'lodash/omit'
import { SELFHOSTED_EMAIL, SELFHOSTED_UUID } from '../../common/constants'
+import { getUserClickhouse } from '../../common/utils'
export enum UserType {
CUSTOMER = 'customer',
@@ -19,6 +21,8 @@ export interface SelfhostedUser {
planCode: 'enterprise'
roles: UserType[]
isActive: boolean
+ timezone: string
+ timeFormat: TimeFormat
}
export const generateSelfhostedUser = (): SelfhostedUser => ({
@@ -28,4 +32,22 @@ export const generateSelfhostedUser = (): SelfhostedUser => ({
planCode: 'enterprise',
roles: [UserType.ADMIN, UserType.CUSTOMER],
isActive: true,
+ timezone: DEFAULT_TIMEZONE,
+ timeFormat: TimeFormat['12-hour'],
})
+
+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,
+ }
+}
\ No newline at end of file
diff --git a/apps/selfhosted/src/user/user.controller.ts b/apps/selfhosted/src/user/user.controller.ts
index 70de626d1..9edf4b077 100644
--- a/apps/selfhosted/src/user/user.controller.ts
+++ b/apps/selfhosted/src/user/user.controller.ts
@@ -1,16 +1,20 @@
-import { Controller, Get, UseGuards } from '@nestjs/common'
+import { Controller, Get, Put, UseGuards, Body, BadRequestException} from '@nestjs/common'
import { ApiTags } from '@nestjs/swagger'
+import * as _omit from 'lodash/omit'
-import { JwtAccessTokenGuard } from 'src/auth/guards'
+import { JwtAccessTokenGuard } from '../auth/guards'
import {
UserType,
SelfhostedUser,
generateSelfhostedUser,
+ getSelfhostedUser,
} from './entities/user.entity'
+import { UpdateUserProfileDTO } from './dto/update-user.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'
@ApiTags('User')
@Controller('user')
@@ -24,6 +28,33 @@ export class UserController {
async me(@CurrentUserId() user_id: string): Promise<SelfhostedUser> {
this.logger.log({ user_id }, 'GET /user/me')
- return generateSelfhostedUser()
+ return await getSelfhostedUser()
+ }
+
+ @Put('/')
+ @UseGuards(JwtAccessTokenGuard, RolesGuard)
+ @Roles(UserType.CUSTOMER, UserType.ADMIN)
+ async updateCurrentUser(
+ @Body() userDTO: UpdateUserProfileDTO,
+ @CurrentUserId() id: string,
+ ): Promise<SelfhostedUser> {
+ this.logger.log({ userDTO, id }, 'PUT /user')
+
+ try {
+ await updateUserClickhouse({
+ timeFormat: userDTO.timeFormat,
+ timezone: userDTO.timezone,
+ })
+
+ const user = generateSelfhostedUser()
+ const settings = _omit((await getUserClickhouse() || {}), ['id'])
+
+ return {
+ ...user,
+ ...settings,
+ }
+ } catch (_) {
+ throw new BadRequestException('An error occurred while updating user')
+ }
}
}
diff --git a/migrations/clickhouse/selfhosted_2023_05_15.js b/migrations/clickhouse/selfhosted_2023_05_15.js
new file mode 100644
index 000000000..058389420
--- /dev/null
+++ b/migrations/clickhouse/selfhosted_2023_05_15.js
@@ -0,0 +1,14 @@
+const { queriesRunner, dbName } = require('./setup')
+
+const queries = [
+ `CREATE TABLE IF NOT EXISTS ${dbName}.sfuser
+ (
+ id String,
+ timezone Nullable(String),
+ timeFormat Nullable(String)
+ )
+ ENGINE = MergeTree()
+ PRIMARY KEY id;`,
+]
+
+queriesRunner(queries)
diff --git a/migrations/clickhouse/selfhosted_v1_to_v2.js b/migrations/clickhouse/selfhosted_v1_to_v2.js
index 742d1e053..4a44b676c 100644
--- a/migrations/clickhouse/selfhosted_v1_to_v2.js
+++ b/migrations/clickhouse/selfhosted_v1_to_v2.js
@@ -36,7 +36,9 @@ async function runMigrations() {
await runScript('./2023_03_20.js')
await runScript('./2023_04_25.js')
await runScript('./2023_04_26.js')
+ await runScript('./2023_05_07.js')
await runScript('./selfhosted_2023_04_29.js')
+ await runScript('./selfhosted_2023_05_15.js')
console.log('[INFO] SELFHOSTED MIGRATIONS FINISHED')
} catch (err) {