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!

swetrix ce: remove hardcoded api keys

Blue Mousecccca4de31fe
diff --git a/backend/apps/community/src/user/user.controller.ts b/backend/apps/community/src/user/user.controller.ts
index 030792927..0f22cea14 100644
--- a/backend/apps/community/src/user/user.controller.ts
+++ b/backend/apps/community/src/user/user.controller.ts
@@ -6,9 +6,15 @@ import {
Body,
BadRequestException,
Post,
+ Headers,
+ Ip,
+ ConflictException,
+ Delete,
} from '@nestjs/common'
import { ApiBearerAuth, ApiResponse, ApiTags } from '@nestjs/swagger'
import _omit from 'lodash/omit'
+import _isNull from 'lodash/isNull'
+import { v4 as uuidv4 } from 'uuid'
import { JwtAccessTokenGuard } from '../auth/guards'
import { OnboardingStep, UserType } from './entities/user.entity'
@@ -20,6 +26,7 @@ import { CurrentUserId } from '../auth/decorators/current-user-id.decorator'
import { AppLoggerService } from '../logger/logger.service'
import { UserService } from './user.service'
import { ClickhouseUser } from '../common/types'
+import { checkRateLimit, getIPFromHeaders } from '../common/utils'
@ApiTags('User')
@Controller('user')
@@ -109,6 +116,58 @@ export class UserController {
})
}
+ @ApiBearerAuth()
+ @Post('api-key')
+ @UseGuards(JwtAccessTokenGuard, RolesGuard)
+ @Roles(UserType.CUSTOMER, UserType.ADMIN)
+ async generateApiKey(
+ @CurrentUserId() userId: string,
+ @Headers() headers,
+ @Ip() reqIP,
+ ) {
+ this.logger.log({ userId }, 'POST /user/api-key')
+
+ const ip = getIPFromHeaders(headers) || reqIP || ''
+
+ await checkRateLimit(ip, 'generate-api-key', 5, 3600)
+
+ const user = await this.userService.findOne({ id: userId })
+
+ if (!user) {
+ throw new BadRequestException('User not found')
+ }
+
+ if (!_isNull(user.apiKey)) {
+ throw new ConflictException('You already have an API key')
+ }
+
+ const apiKey: string = uuidv4()
+
+ await this.userService.update(userId, { apiKey })
+
+ return { apiKey }
+ }
+
+ @ApiBearerAuth()
+ @Delete('/api-key')
+ @UseGuards(JwtAccessTokenGuard, RolesGuard)
+ @Roles(UserType.CUSTOMER, UserType.ADMIN)
+ async deleteApiKey(@CurrentUserId() userId: string) {
+ this.logger.log({ userId }, 'DELETE /user/api-key')
+
+ const user = await this.userService.findOne({ id: userId })
+
+ if (!user) {
+ throw new BadRequestException('User not found')
+ }
+
+ if (_isNull(user.apiKey)) {
+ throw new ConflictException("You don't have an API key")
+ }
+
+ await this.userService.update(userId, { apiKey: null })
+ }
+
@ApiBearerAuth()
@Put('/')
@UseGuards(JwtAccessTokenGuard, RolesGuard)
diff --git a/web/app/pages/UserSettings/UserSettings.tsx b/web/app/pages/UserSettings/UserSettings.tsx
index 9a6f7fbc5..41f00d737 100644
--- a/web/app/pages/UserSettings/UserSettings.tsx
+++ b/web/app/pages/UserSettings/UserSettings.tsx
@@ -499,7 +499,6 @@ const UserSettings = () => {
<>
<hr className='mt-5 border-gray-200 dark:border-gray-600' />
- {/* API access setup */}
<h3 className='mt-2 flex items-center text-lg font-bold text-gray-900 dark:text-gray-50'>
{t('profileSettings.apiKey')}
</h3>
@@ -520,9 +519,18 @@ const UserSettings = () => {
</>
) : (
<p className='max-w-prose text-base text-gray-900 dark:text-gray-50'>
- {t('profileSettings.selfhostedNoApiKey')}
+ {t('profileSettings.noApiKey')}
</p>
)}
+ {user?.apiKey ? (
+ <Button className='mt-4' onClick={() => setShowAPIDeleteModal(true)} danger large>
+ {t('profileSettings.deleteApiKeyBtn')}
+ </Button>
+ ) : (
+ <Button className='mt-4' onClick={onApiKeyGenerate} primary large>
+ {t('profileSettings.addApiKeyBtn')}
+ </Button>
+ )}
</>
) : (
<>
diff --git a/web/public/locales/en.json b/web/public/locales/en.json
index e5775e035..bfad038f3 100644
--- a/web/public/locales/en.json
+++ b/web/public/locales/en.json
@@ -591,7 +591,6 @@
"2faDisableHint": "To disable two-factor authentication, please enter your 6-digit code or one of your recovery codes below.",
"apiKey": "API Key",
"noApiKey": "You haven't created any API keys yet.",
- "selfhostedNoApiKey": "You haven't created any API keys yet. You can do this in your docker compose file by modifying the API_KEY environment variable.",
"apiKeyWarning": "Treat your API Key like a password and keep it secret. Never hardcode it into your programs, or share it with anyone.",
"addApiKeyBtn": "Generate API Key",
"deleteApiKeyBtn": "Delete API Key",