📈 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!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
added ability to disable 2fa
Blue Mouse2a84888043a6
diff --git a/package.json b/package.jsonindex 45abb1daf..fa184b3c0 100644--- a/package.json+++ b/package.json@@ -56,7 +56,7 @@"passport-jwt": "^4.0.0","php-serialize": "^4.0.2","postmark": "^3.0.1",- "qrcode": "^1.5.0",+ "randomstring": "^1.2.2","reflect-metadata": "^0.1.13","rimraf": "^3.0.2","rxjs": "^7.5.5",diff --git a/src/auth/auth.service.ts b/src/auth/auth.service.tsindex 0672b5e16..3a8e3544b 100644--- a/src/auth/auth.service.ts+++ b/src/auth/auth.service.ts@@ -104,6 +104,7 @@ export class AuthService {// @ts-ignore...user,password: undefined,+ twoFactorRecoveryCode: undefined,maxEventsCount,}diff --git a/src/common/utils.ts b/src/common/utils.tsindex ae966f454..0c2d65d5b 100644--- a/src/common/utils.ts+++ b/src/common/utils.ts@@ -1,5 +1,6 @@import { ForbiddenException, NotFoundException } from '@nestjs/common'import { hash } from 'blake3'+import * as randomstring from 'randomstring'import * as _sample from 'lodash/sample'import * as _join from 'lodash/join'import * as _filter from 'lodash/filter'@@ -113,6 +114,13 @@ const createProjectClickhouse = async (project: Project) => {return await clickhouse.query(query, paramsData).toPromise()}+const generateRecoveryCode = () => randomstring.generate({+ length: 30,+ charset: 'alphabetic',+ capitalization: 'uppercase',+})+export {- getRandomTip, checkRateLimit, createProjectClickhouse, getProjectsClickhouse, updateProjectClickhouse, deleteProjectClickhouse, splitAt,+ getRandomTip, checkRateLimit, createProjectClickhouse, getProjectsClickhouse, updateProjectClickhouse,+ deleteProjectClickhouse, splitAt, generateRecoveryCode,}diff --git a/src/twoFactorAuth/twoFactorAuth.controller.ts b/src/twoFactorAuth/twoFactorAuth.controller.tsindex ec291cd21..894a7757c 100644--- a/src/twoFactorAuth/twoFactorAuth.controller.ts+++ b/src/twoFactorAuth/twoFactorAuth.controller.ts@@ -1,8 +1,7 @@import {- Controller, Post, Res, UseGuards, HttpCode, Body, UnauthorizedException,+ Controller, Post, UseGuards, HttpCode, Body, BadRequestException,} from '@nestjs/common'import { ApiTags } from '@nestjs/swagger'-import { Response } from 'express'import { TwoFactorAuthService } from './twoFactorAuth.service'import { UserService } from '../user/user.service'@@ -16,9 +15,7 @@ import { Roles } from '../common/decorators/roles.decorator'import { TwoFaNotRequired } from '../common/decorators/2fa-disabled.decorator'import { RolesGuard } from 'src/common/guards/roles.guard'import { TwoFactorAuthDTO } from './dto/2fa-auth.dto'-import {- isSelfhosted, SELFHOSTED_EMAIL, SELFHOSTED_PASSWORD, SELFHOSTED_UUID,-} from 'src/common/constants'+import { generateRecoveryCode } from 'src/common/utils'@ApiTags('2fa')@Controller('2fa')@@ -36,16 +33,13 @@ export class TwoFactorAuthController {@UseGuards(SelfhostedGuard) // temporary this feature is not available for selfhosted@Roles(UserType.CUSTOMER, UserType.ADMIN)@TwoFaNotRequired()- async register(@Res() response: Response, @CurrentUserId() id: string) {+ async register(@CurrentUserId() id: string) {const user = await this.userService.findOneWhere({ id })- const { otpauthUrl } = await this.twoFactorAuthService.generateTwoFactorAuthenticationSecret(user)-- return this.twoFactorAuthService.pipeQrCodeStream(response, otpauthUrl)+ return await this.twoFactorAuthService.generateTwoFactorAuthenticationSecret(user)}@Post('enable')- @HttpCode(200)@UseGuards(RolesGuard)@UseGuards(SelfhostedGuard) // temporary this feature is not available for selfhosted@Roles(UserType.CUSTOMER, UserType.ADMIN)@@ -60,11 +54,46 @@ export class TwoFactorAuthController {)if (!isCodeValid) {- throw new UnauthorizedException('Wrong authentication code')+ throw new BadRequestException('Wrong authentication code')}+ const twoFactorRecoveryCode = generateRecoveryCode()+await this.userService.update(user.id, {isTwoFactorAuthenticationEnabled: true,+ twoFactorRecoveryCode,+ })++ const authData = this.authService.login(user, true)++ return {+ twoFactorRecoveryCode,+ ...authData,+ }+ }++ @Post('disable')+ @HttpCode(200)+ @UseGuards(RolesGuard)+ @UseGuards(SelfhostedGuard) // temporary this feature is not available for selfhosted+ @Roles(UserType.CUSTOMER, UserType.ADMIN)+ async turnOffTwoFactorAuthentication(@Body() body: TwoFactorAuthDTO, @CurrentUserId() id: string) {+ this.logger.log({ body }, 'POST /2fa/disable')+ const user = await this.userService.findOneWhere({ id })+ const { twoFactorAuthenticationCode } = body++ const isCodeValid = this.twoFactorAuthService.isTwoFactorAuthenticationCodeValid(+ twoFactorAuthenticationCode, user,+ )++ if (!isCodeValid) {+ throw new BadRequestException('Wrong authentication code')+ }++ await this.userService.update(user.id, {+ isTwoFactorAuthenticationEnabled: false,+ twoFactorRecoveryCode: null,+ twoFactorAuthenticationSecret: null,})}@@ -84,7 +113,7 @@ export class TwoFactorAuthController {)if (!isCodeValid) {- throw new UnauthorizedException('Wrong authentication code')+ throw new BadRequestException('Wrong authentication code')}return this.authService.login(user, true)diff --git a/src/twoFactorAuth/twoFactorAuth.service.ts b/src/twoFactorAuth/twoFactorAuth.service.tsindex cf45ab45c..df60d1766 100644--- a/src/twoFactorAuth/twoFactorAuth.service.ts+++ b/src/twoFactorAuth/twoFactorAuth.service.ts@@ -1,7 +1,5 @@import { Injectable } from '@nestjs/common'import { authenticator } from 'otplib'-import { toFileStream } from 'qrcode'-import { Response } from 'express'import { UserService } from '../user/user.service'import { User } from '../user/entities/user.entity'@@ -31,10 +29,6 @@ export class TwoFactorAuthService {}}- async pipeQrCodeStream(stream: Response, otpauthUrl: string) {- return toFileStream(stream, otpauthUrl)- }-isTwoFactorAuthenticationCodeValid(twoFactorAuthenticationCode: string, user: User) {return authenticator.verify({token: twoFactorAuthenticationCode,diff --git a/src/user/entities/user.entity.ts b/src/user/entities/user.entity.tsindex adada4351..40e192b67 100644--- a/src/user/entities/user.entity.ts+++ b/src/user/entities/user.entity.ts@@ -129,6 +129,9 @@ export class User {@Column('varchar', { length: 32, nullable: true })twoFactorAuthenticationSecret: string+ @Column('varchar', { length: 30, nullable: true })+ twoFactorRecoveryCode: string+@Column({ default: false })isTwoFactorAuthenticationEnabled: booleandiff --git a/src/user/user.controller.ts b/src/user/user.controller.tsindex ecf069b91..a32e2e2e3 100644--- a/src/user/user.controller.ts+++ b/src/user/user.controller.ts@@ -307,7 +307,7 @@ export class UserController {}// delete internal properties from userDTO before updating it// todo: use _pick instead of _omit- const userToUpdate = _omit(userDTO, ['id', 'sharedProjects', 'isActive', 'evWarningSentOn', 'exportedAt', 'subID', 'subUpdateURL', 'subCancelURL', 'projects', 'actionTokens', 'roles', 'created', 'updated', 'planCode', 'billingFrequency', 'nextBillDate'])+ const userToUpdate = _omit(userDTO, ['id', 'sharedProjects', 'isActive', 'evWarningSentOn', 'exportedAt', 'subID', 'subUpdateURL', 'subCancelURL', 'projects', 'actionTokens', 'roles', 'created', 'updated', 'planCode', 'billingFrequency', 'nextBillDate', 'twoFactorRecoveryCode', 'twoFactorAuthenticationSecret', 'isTwoFactorAuthenticationEnabled'])await this.userService.update(id, userToUpdate)const updatedUser = await this.userService.findOneWhere({ id })diff --git a/src/user/user.service.ts b/src/user/user.service.tsindex 5cc3d501d..5477ad68b 100644--- a/src/user/user.service.ts+++ b/src/user/user.service.ts@@ -53,7 +53,7 @@ export class UserService {}omitSensitiveData(user: User): User {- return _omit(user, ['password'])+ return _omit(user, ['password', 'twoFactorRecoveryCode'])}findOneWhere(where: Record<string, unknown>, relations: string[] = []): Promise<User> {