📈 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
add 'log out from all devices' and 'delete account' functionality to Swetrix CE
Blue Mouseac26516e04ad
diff --git a/backend/apps/community/src/auth/auth.controller.ts b/backend/apps/community/src/auth/auth.controller.tsindex c62ea0f01..fd8217000 100644--- a/backend/apps/community/src/auth/auth.controller.ts+++ b/backend/apps/community/src/auth/auth.controller.ts@@ -362,6 +362,23 @@ export class AuthController {await this.authService.logout(user.id, refreshToken)}+ @ApiOperation({ summary: 'Log out from all devices' })+ @ApiOkResponse({+ description: 'Logged out from all devices',+ })+ @UseGuards(JwtRefreshTokenGuard)+ @Post('logout-all')+ @HttpCode(200)+ public async logoutAll(@CurrentUserId() userId: string): Promise<void> {+ const user = await this.userService.findOne({ id: userId })++ if (!user) {+ throw new UnauthorizedException()+ }++ await this.authService.logoutAll(user.id)+ }+@ApiOperation({ summary: 'Initiate OIDC authentication' })@ApiOkResponse({description: 'OIDC authentication initiated',diff --git a/backend/apps/community/src/common/utils.ts b/backend/apps/community/src/common/utils.tsindex da844d398..fc64403d1 100644--- a/backend/apps/community/src/common/utils.ts+++ b/backend/apps/community/src/common/utils.ts@@ -415,6 +415,13 @@ const deleteProjectClickhouse = async (id: string) => {})}+const deleteProjectsByUserIdClickhouse = async (userId: string) => {+ await clickhouse.command({+ query: `ALTER TABLE project DELETE WHERE adminId = {userId:FixedString(36)}`,+ query_params: { userId },+ })+}+const deleteProjectSharesByProjectClickhouse = async (projectId: string) => {await clickhouse.command({query:@@ -423,6 +430,13 @@ const deleteProjectSharesByProjectClickhouse = async (projectId: string) => {})}+const deleteProjectSharesByUserIdClickhouse = async (userId: string) => {+ await clickhouse.command({+ query: `ALTER TABLE project_share DELETE WHERE userId = {userId:FixedString(36)}`,+ query_params: { userId },+ })+}+const createProjectClickhouse = async (project: Partial<Project>) => {const { id, name, adminId } = project@@ -1060,4 +1074,6 @@ export {updateProjectShareClickhouse,deleteProjectShareClickhouse,deleteProjectSharesByProjectClickhouse,+ deleteProjectSharesByUserIdClickhouse,+ deleteProjectsByUserIdClickhouse,}diff --git a/backend/apps/community/src/user/user.controller.ts b/backend/apps/community/src/user/user.controller.tsindex 05ca7b430..83a962f45 100644--- a/backend/apps/community/src/user/user.controller.ts+++ b/backend/apps/community/src/user/user.controller.ts@@ -11,11 +11,14 @@ import {ConflictException,Delete,Param,+ HttpCode,} from '@nestjs/common'import { ApiBearerAuth, ApiResponse, ApiTags } from '@nestjs/swagger'import _isEmpty from 'lodash/isEmpty'import _omit from 'lodash/omit'import _isNull from 'lodash/isNull'+import _map from 'lodash/map'+import _join from 'lodash/join'import { randomUUID } from 'crypto'import { JwtAccessTokenGuard } from '../auth/guards'@@ -27,7 +30,14 @@ import { RolesGuard } from '../auth/guards/roles.guard'import { CurrentUserId } from '../auth/decorators/current-user-id.decorator'import { AppLoggerService } from '../logger/logger.service'import { UserService } from './user.service'-import { checkRateLimit, getIPFromHeaders } from '../common/utils'+import {+ checkRateLimit,+ deleteAllRefreshTokensClickhouse,+ deleteProjectsByUserIdClickhouse,+ deleteProjectSharesByUserIdClickhouse,+ getIPFromHeaders,+ getProjectsClickhouse,+} from '../common/utils'import {findProjectShareClickhouse,findProjectSharesByUserClickhouse,@@ -41,6 +51,8 @@ import { LetterTemplate } from '../mailer/letter'import { Request } from 'express'import { Req } from '@nestjs/common'import { redis } from '../common/constants'+import { ProjectService } from '../project/project.service'+import { clickhouse } from '../common/integrations/clickhouse'@ApiTags('User')@Controller('user')@@ -51,6 +63,7 @@ export class UserController {private readonly userService: UserService,private readonly mailerService: MailerService,private readonly authService: AuthService,+ private readonly projectService: ProjectService,) {}@ApiBearerAuth()@@ -138,6 +151,57 @@ export class UserController {}}+ @ApiBearerAuth()+ @Delete('/')+ @HttpCode(204)+ @UseGuards(JwtAccessTokenGuard, RolesGuard)+ @Roles(UserType.CUSTOMER, UserType.ADMIN)+ async deleteSelf(@CurrentUserId() id: string): Promise<any> {+ this.logger.log({ id }, 'DELETE /user')++ const user = await this.userService.findOne({+ id,+ })++ if (_isEmpty(user)) {+ throw new BadRequestException('User not found')+ }++ const chResults = await getProjectsClickhouse(id)+ const projects = _map(chResults, this.projectService.formatFromClickhouse)++ try {+ if (!_isEmpty(projects)) {+ const pids = _join(+ _map(projects, el => `'${el.id}'`),+ ',',+ )+ const queries = [+ `ALTER TABLE analytics DELETE WHERE pid IN (${pids})`,+ `ALTER TABLE customEV DELETE WHERE pid IN (${pids})`,+ `ALTER TABLE performance DELETE WHERE pid IN (${pids})`,+ `ALTER TABLE errors DELETE WHERE pid IN (${pids})`,+ `ALTER TABLE error_statuses DELETE WHERE pid IN (${pids})`,+ ]+ await deleteProjectsByUserIdClickhouse(id)+ const promises = _map(queries, async query =>+ clickhouse.command({+ query,+ }),+ )+ await Promise.all(promises)+ }+ await deleteAllRefreshTokensClickhouse(id)+ await deleteProjectSharesByUserIdClickhouse(id)+ await this.userService.delete(id)+ } catch (reason) {+ this.logger.error(reason)+ throw new BadRequestException('accountDeleteError')+ }++ return 'accountDeleted'+ }+@ApiBearerAuth()@Delete('/share/:actionId')@UseGuards(JwtAccessTokenGuard, RolesGuard)diff --git a/backend/apps/community/src/user/user.module.ts b/backend/apps/community/src/user/user.module.tsindex a172b5340..29c798bd3 100644--- a/backend/apps/community/src/user/user.module.ts+++ b/backend/apps/community/src/user/user.module.ts@@ -5,9 +5,15 @@ import { UserService } from './user.service'import { AppLoggerModule } from '../logger/logger.module'import { MailerModule } from '../mailer/mailer.module'import { AuthModule } from '../auth/auth.module'+import { ProjectModule } from '../project/project.module'@Module({- imports: [AppLoggerModule, MailerModule, forwardRef(() => AuthModule)],+ imports: [+ AppLoggerModule,+ MailerModule,+ forwardRef(() => AuthModule),+ ProjectModule,+ ],providers: [UserService],exports: [UserService],controllers: [UserController],diff --git a/backend/apps/community/src/user/user.service.ts b/backend/apps/community/src/user/user.service.tsindex b18b0cd54..05f8ab896 100644--- a/backend/apps/community/src/user/user.service.ts+++ b/backend/apps/community/src/user/user.service.ts@@ -120,6 +120,13 @@ export class UserService {return this.findOne({ id: userId })}+ async delete(userId: string) {+ 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()diff --git a/web/app/pages/UserSettings/UserSettings.tsx b/web/app/pages/UserSettings/UserSettings.tsxindex 27032ff78..004f4e7b3 100644--- a/web/app/pages/UserSettings/UserSettings.tsx+++ b/web/app/pages/UserSettings/UserSettings.tsx@@ -21,7 +21,7 @@ import {confirmEmail,exportUserData,generateApiKey,- deleteApiKey, // setTheme,+ deleteApiKey,receiveLoginNotification,setShowLiveVisitorsInTitle,changeUserDetails,@@ -706,37 +706,41 @@ const UserSettings = () => {{t('profileSettings.noLink')}</div>) : null}- <div className='mt-4 flex flex-wrap justify-center gap-2 sm:justify-between'>- <Button onClick={() => setShowExportModal(true)} semiSmall primary>- <>- <DownloadIcon className='mr-1 h-5 w-5' strokeWidth={1.5} />- {t('profileSettings.requestExport')}- </>- </Button>- <div className='flex flex-wrap justify-center gap-2'>- <Button- onClick={() => {- logout(true)- }}- semiSmall- semiDanger- >- <>- {/* We need this div for the button to match the height of the button after it */}- <div className='h-5' />- {t('profileSettings.logoutAll')}- </>- </Button>- <Button onClick={() => setShowModal(true)} semiSmall semiDanger>- <>- <ExclamationTriangleIcon className='mr-1 h-5 w-5' />- {t('profileSettings.delete')}- </>- </Button>- </div>- </div></>)}+ <div className='mt-4 flex flex-wrap justify-center gap-2 sm:justify-between'>+ {isSelfhosted ? (+ <div />+ ) : (+ <Button onClick={() => setShowExportModal(true)} semiSmall primary>+ <>+ <DownloadIcon className='mr-1 h-5 w-5' strokeWidth={1.5} />+ {t('profileSettings.requestExport')}+ </>+ </Button>+ )}+ <div className='flex flex-wrap justify-center gap-2'>+ <Button+ onClick={() => {+ logout(true)+ }}+ semiSmall+ semiDanger+ >+ <>+ {/* We need this div for the button to match the height of the button after it */}+ <div className='h-5' />+ {t('profileSettings.logoutAll')}+ </>+ </Button>+ <Button onClick={() => setShowModal(true)} semiSmall semiDanger>+ <>+ <ExclamationTriangleIcon className='mr-1 h-5 w-5' />+ {t('profileSettings.delete')}+ </>+ </Button>+ </div>+ </div></>)}@@ -916,15 +920,17 @@ const UserSettings = () => {message={<>{t('profileSettings.deactivateConfirmation')}- <Textarea- classes={{- container: 'mt-4',- }}- placeholder={t('profileSettings.deletionFeedback')}- onChange={(e) => setDeletionFeedback(e.target.value)}- value={deletionFeedback}- label={t('profileSettings.deletionFeedbackLabel')}- />+ {isSelfhosted ? null : (+ <Textarea+ classes={{+ container: 'mt-4',+ }}+ placeholder={t('profileSettings.deletionFeedback')}+ onChange={(e) => setDeletionFeedback(e.target.value)}+ value={deletionFeedback}+ label={t('profileSettings.deletionFeedbackLabel')}+ />+ )}</>}isOpened={showModal}