📈 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
import { ApiKeyService } from '../api-key/api-key.service'
import {
Controller,
Req,
Body,
Param,
Get,
Post,
Put,
Delete,
HttpCode,
BadRequestException,
FileTypeValidator,
UseGuards,
UseInterceptors,
Headers,
Ip,
NotFoundException,
ParseFilePipe,
UploadedFiles,
} from '@nestjs/common'
import { FilesInterceptor } from '@nestjs/platform-express'
import { Request } from 'express'
import {
ApiTags,
ApiResponse,
ApiBearerAuth,
ApiBody,
ApiConsumes,
} from '@nestjs/swagger'
import dayjs from 'dayjs'
import utc from 'dayjs/plugin/utc'
import _map from 'lodash/map'
import _join from 'lodash/join'
import _isEmpty from 'lodash/isEmpty'
import _includes from 'lodash/includes'
import _isString from 'lodash/isString'
import _pick from 'lodash/pick'
import _round from 'lodash/round'
import { Markup } from 'telegraf'
import { Public, CurrentUserId, Auth } from '../auth/decorators'
import { TelegramService } from '../integrations/telegram/telegram.service'
import { UserService, UserPayment } from './user.service'
import { ProjectService, deleteProjectRedis } from '../project/project.service'
import {
User,
MAX_EMAIL_REQUESTS,
PlanCode,
OnboardingStep,
} from './entities/user.entity'
import { isDevelopment, PRODUCTION_ORIGIN } from '../common/constants'
import { AuthenticationGuard } from '../auth/guards/authentication.guard'
import { UpdateUserProfileDTO } from './dto/update-user.dto'
import { IChangePlanDTO } from './dto/change-plan.dto'
import { SetShowLiveVisitorsDTO } from './dto/set-show-live-visitors.dto'
import { ActionTokensService } from '../action-tokens/action-tokens.service'
import { MailerService } from '../mailer/mailer.service'
import { ActionTokenType } from '../action-tokens/action-token.entity'
import { AuthService } from '../auth/auth.service'
import { LetterTemplate } from '../mailer/letter'
import { AppLoggerService } from '../logger/logger.service'
import { DeleteSelfDTO } from './dto/delete-self.dto'
import { CancelSubscriptionDTO } from './dto/cancel-subscription.dto'
import { CreateFeedbackDTO } from './dto/create-feedback.dto'
import {
UpdateSessionReplayAddonDTO,
UpdateWebsiteAddonDTO,
} from './dto/update-website-addon.dto'
import { checkRateLimit, getIPDetails, getIPFromHeaders } from '../common/utils'
import {
IUsageInfo,
IUsageInfoBreakdown,
IUsageInfoRedis,
IMetaInfo,
} from './interfaces'
import { ReportFrequency } from '../project/enums'
import { OrganisationService } from '../organisation/organisation.service'
import { trackCustom } from '../common/analytics'
dayjs.extend(utc)
const UNPAID_PLANS = [PlanCode.free, PlanCode.trial, PlanCode.none]
const ORGANISATION_INVITE_EXPIRE_HOURS = 7 * 24 // 7 days
const FEEDBACK_ATTACHMENTS_LIMIT = 7
const FEEDBACK_ATTACHMENT_MAX_SIZE = 5 * 1024 * 1024
const EMPTY_USAGE_INFO: IUsageInfoRedis = {
total: 0,
traffic: 0,
customEvents: 0,
captcha: 0,
errors: 0,
}
const formatUsageInfo = (
rawInfo?: IUsageInfoRedis | null,
): IUsageInfoBreakdown => {
const usage = rawInfo || EMPTY_USAGE_INFO
return {
...usage,
outboundLinks: usage.outboundLinks || 0,
outboundLinksPerc: usage.total
? _round(((usage.outboundLinks || 0) / usage.total) * 100, 2)
: 0,
trafficPerc: usage.total
? _round((usage.traffic / usage.total) * 100, 2)
: 0,
customEventsPerc: usage.total
? _round((usage.customEvents / usage.total) * 100, 2)
: 0,
captchaPerc: usage.total
? _round((usage.captcha / usage.total) * 100, 2)
: 0,
errorsPerc: usage.total ? _round((usage.errors / usage.total) * 100, 2) : 0,
}
}
@ApiTags('User')
@Controller('user')
@Auth()
export class UserController {
constructor(
private readonly apiKeys: ApiKeyService,
private readonly userService: UserService,
private readonly authService: AuthService,
private readonly projectService: ProjectService,
private readonly actionTokensService: ActionTokensService,
private readonly mailerService: MailerService,
private readonly logger: AppLoggerService,
private readonly telegramService: TelegramService,
private readonly organisationService: OrganisationService,
) {}
@ApiBearerAuth()
@Get('/me')
@UseGuards(AuthenticationGuard)
async me(@CurrentUserId() uid: string) {
this.logger.log({ uid }, 'GET /user/me')
const [sharedProjects, organisationMemberships, user, totalMonthlyEvents] =
await Promise.all([
this.authService.getSharedProjectsForUser(uid),
this.userService.getOrganisationsForUser(uid),
this.userService.findOne({ where: { id: uid } }),
this.projectService.getRedisCount(uid),
])
const sanitizedUser = this.userService.omitSensitiveData(
user,
) as Partial<User> & {
websiteAddon?: unknown
sessionReplayAddon?: unknown
}
sanitizedUser.sharedProjects = sharedProjects
sanitizedUser.organisationMemberships = organisationMemberships
sanitizedUser.websiteAddon = await this.userService.getWebsiteAddonSummary(
uid,
user,
)
sanitizedUser.sessionReplayAddon =
await this.userService.getSessionReplayAddonSummary(uid, user)
return {
user: sanitizedUser,
totalMonthlyEvents,
}
}
@ApiBearerAuth()
@Put('/live-visitors')
async setShowLiveVisitors(
@CurrentUserId() userId: string,
@Body() body: SetShowLiveVisitorsDTO,
): Promise<Partial<User>> {
const { show } = body
await this.userService.update(userId, { showLiveVisitorsInTitle: show })
return {
showLiveVisitorsInTitle: show,
}
}
@ApiBearerAuth()
@Post('/recieve-login-notifications')
async receiveLoginNotifications(
@CurrentUserId() userId: string,
@Body('receiveLoginNotifications') receiveLoginNotifications: boolean,
): Promise<User> {
this.logger.log(
{ userId, receiveLoginNotifications },
'POST /user/recieve-login-notifications',
)
return this.userService.update(userId, { receiveLoginNotifications })
}
@ApiBearerAuth()
@Post('/api-key')
async generateApiKey() {
throw new BadRequestException(
'Create scoped API keys through /user/api-keys',
)
}
@ApiBearerAuth()
@Delete('/api-key')
async deleteApiKey(
@CurrentUserId() userId: string,
@Headers() headers: Record<string, string>,
@Ip() requestIp: string,
): Promise<void> {
this.logger.log({ userId }, 'DELETE /user/api-key')
const ip = getIPFromHeaders(headers) || requestIp || ''
await trackCustom(ip, headers['user-agent'], {
ev: 'API_KEY_DELETED',
})
await this.apiKeys.remove(userId, 'legacy')
}
@ApiBearerAuth()
@Post('/feedback')
@ApiConsumes('multipart/form-data')
@ApiBody({
schema: {
type: 'object',
properties: {
message: { type: 'string' },
attachments: {
type: 'array',
items: { type: 'string', format: 'binary' },
},
},
required: ['message'],
},
})
@UseInterceptors(
FilesInterceptor('attachments', FEEDBACK_ATTACHMENTS_LIMIT, {
limits: { fileSize: FEEDBACK_ATTACHMENT_MAX_SIZE },
}),
)
async createFeedback(
@CurrentUserId() userId: string,
@Body() body: CreateFeedbackDTO,
@UploadedFiles(
new ParseFilePipe({
fileIsRequired: false,
validators: [
new FileTypeValidator({
fileType: /^image\//,
errorMessage: 'Only image attachments are allowed',
}),
],
}),
)
files: Express.Multer.File[],
@Headers() headers: Record<string, string>,
@Ip() requestIp: string,
) {
this.logger.log({ userId }, 'POST /user/feedback')
const ip = getIPFromHeaders(headers) || requestIp || ''
const userAgent = headers['user-agent'] || ''
await checkRateLimit(userId, 'user-feedback', 5, 3600)
const message = body.message.trim()
if (!message) {
throw new BadRequestException('Feedback cannot be empty')
}
const feedback = await this.userService.saveUserFeedback(
userId,
message,
files,
)
await trackCustom(ip, userAgent, {
ev: 'FEEDBACK_LEFT',
meta: {
attachment_count: feedback.attachmentUrls.length,
},
})
return {
id: feedback.id,
}
}
@ApiBearerAuth()
@Delete('/')
@HttpCode(204)
async deleteSelf(
@CurrentUserId() id: string,
@Body() deleteSelfDTO: DeleteSelfDTO,
@Headers() headers: Record<string, string>,
@Ip() requestIp: string,
): Promise<any> {
this.logger.log({ id }, 'DELETE /user')
const ip = getIPFromHeaders(headers) || requestIp || ''
const user = await this.userService.findOne({
where: { id },
select: ['id', 'planCode', 'password'],
})
if (_isEmpty(user)) {
throw new BadRequestException('User not found')
}
const isPasswordValid = await this.authService.comparePassword(
deleteSelfDTO.password,
user.password,
)
if (!isPasswordValid) {
throw new BadRequestException('incorrectPassword')
}
if (!_includes(UNPAID_PLANS, user.planCode)) {
throw new BadRequestException('cancelSubFirst')
}
try {
const hasProjects = (await this.projectService.countByAdminId(id)) > 0
if (hasProjects) {
await this.projectService.deleteProjectsForUser(id)
}
await this.actionTokensService.deleteMultiple({ user: { id } })
await this.userService.deleteAllRefreshTokens(id)
await this.projectService.deleteMultipleShare({ user: { id } })
await this.organisationService.deleteMemberships({
user: {
id,
},
})
await this.userService.delete(id)
} catch (reason) {
this.logger.error(reason)
throw new BadRequestException('accountDeleteError')
}
const feedback = deleteSelfDTO?.feedback
try {
if (feedback) {
await this.userService.saveDeleteFeedback(feedback)
}
} catch (reason) {
this.logger.error(
'[ERROR] Failed to save account deletion feedback:',
reason,
)
this.logger.error('DeleteSelfDTO: ', deleteSelfDTO)
}
await trackCustom(ip, headers['user-agent'], {
ev: 'ACCOUNT_DELETED',
meta: {
reason_stated: !!feedback,
},
})
return 'accountDeleted'
}
@ApiBearerAuth()
@Delete('/share/:actionId')
@HttpCode(204)
@ApiResponse({ status: 204, description: 'Empty body' })
async deleteShare(
@Param('actionId') actionId: string,
@CurrentUserId() uid: string,
) {
this.logger.log({ uid, actionId }, 'DELETE /user/share/:actionId')
let isActionToken = false
const actionToken = await this.actionTokensService.getActionToken(actionId)
if (actionToken) {
isActionToken = true
}
const share = await this.projectService.findOneShare({
where: { id: actionToken?.newValue || actionId },
relations: ['user', 'project'],
})
if (_isEmpty(share)) {
throw new BadRequestException(
'This invitation does not exist or is no longer valid',
)
}
if (share.user?.id !== uid) {
throw new BadRequestException(
'You are not allowed to reject this invitation',
)
}
await this.projectService.deleteShare(share.id)
await deleteProjectRedis(share.project.id)
if (isActionToken) {
await this.actionTokensService.delete(actionId)
}
}
@ApiBearerAuth()
@Get('/share/:actionId')
@HttpCode(204)
@ApiResponse({ status: 204, description: 'Empty body' })
async acceptShare(
@Param('actionId') actionId: string,
@CurrentUserId() uid: string,
) {
this.logger.log({ uid, actionId }, 'GET /user/share/:actionId')
let isActionToken = false
const actionToken = await this.actionTokensService.getActionToken(actionId)
if (actionToken) {
isActionToken = true
}
const share = await this.projectService.findOneShare({
where: { id: actionToken?.newValue || actionId },
relations: ['user', 'project'],
})
if (_isEmpty(share)) {
throw new BadRequestException(
'This invitation does not exist or is no longer valid',
)
}
if (share.user?.id !== uid) {
throw new BadRequestException(
'You are not allowed to accept this invitation',
)
}
await this.projectService.updateShare(share.id, {
confirmed: true,
})
await deleteProjectRedis(share.project.id)
if (isActionToken) {
await this.actionTokensService.delete(actionId)
}
}
@ApiBearerAuth()
@Delete('/organisation/:actionId')
@HttpCode(204)
@ApiResponse({ status: 204, description: 'Empty body' })
async rejectOrganisationInvitation(
@Param('actionId') actionId: string,
@CurrentUserId() uid: string,
) {
this.logger.log({ uid, actionId }, 'DELETE /user/organisation/:actionId')
const actionToken = await this.actionTokensService.getActionToken(actionId)
if (
!actionToken ||
actionToken.action !== ActionTokenType.ORGANISATION_INVITE ||
!actionToken.newValue
) {
throw new BadRequestException(
'This invitation does not exist or is no longer valid',
)
}
const tokenAgeMs =
Date.now() - new Date(actionToken.created as any).getTime()
if (tokenAgeMs > ORGANISATION_INVITE_EXPIRE_HOURS * 60 * 60 * 1000) {
await this.actionTokensService.delete(actionId)
throw new BadRequestException(
'This invitation does not exist or is no longer valid',
)
}
const membership = await this.organisationService.findOneMembership({
where: { id: actionToken.newValue },
relations: ['user'],
select: {
id: true,
user: {
id: true,
},
},
})
if (_isEmpty(membership)) {
throw new BadRequestException(
'This invitation does not exist or is no longer valid',
)
}
if (membership.user?.id !== uid) {
throw new BadRequestException(
'You are not allowed to reject this invitation from this account',
)
}
if (actionToken.user?.id && actionToken.user.id !== membership.user.id) {
throw new BadRequestException(
'This invitation does not exist or is no longer valid',
)
}
await this.organisationService.deleteMembership(membership.id)
await this.actionTokensService.delete(actionId)
}
@ApiBearerAuth()
@Post('/organisation/:actionId')
@HttpCode(204)
@ApiResponse({ status: 204, description: 'Empty body' })
async acceptOrganisationInvitation(
@Param('actionId') actionId: string,
@CurrentUserId() uid: string,
): Promise<any> {
this.logger.log({ uid, actionId }, 'POST /user/organisation/:actionId')
const actionToken = await this.actionTokensService.getActionToken(actionId)
if (
!actionToken ||
actionToken.action !== ActionTokenType.ORGANISATION_INVITE ||
!actionToken.newValue
) {
throw new BadRequestException(
'This invitation does not exist or is no longer valid',
)
}
const tokenAgeMs =
Date.now() - new Date(actionToken.created as any).getTime()
if (tokenAgeMs > ORGANISATION_INVITE_EXPIRE_HOURS * 60 * 60 * 1000) {
await this.actionTokensService.delete(actionId)
throw new BadRequestException(
'This invitation does not exist or is no longer valid',
)
}
const membership = await this.organisationService.findOneMembership({
where: { id: actionToken.newValue },
relations: ['user', 'organisation'],
select: {
id: true,
user: {
id: true,
},
organisation: {
id: true,
},
},
})
if (_isEmpty(membership)) {
throw new BadRequestException(
'This invitation does not exist or is no longer valid',
)
}
if (membership.user?.id !== uid) {
throw new BadRequestException(
'You are not allowed to accept this invitation from this account',
)
}
if (actionToken.user?.id && actionToken.user.id !== membership.user.id) {
throw new BadRequestException(
'This invitation does not exist or is no longer valid',
)
}
await this.organisationService.updateMembership(membership.id, {
confirmed: true,
})
await this.actionTokensService.delete(actionId)
await this.organisationService.deleteOrganisationProjectsFromRedis(
membership.organisation.id,
)
}
@ApiBearerAuth()
@Post('/confirm_email')
async sendEmailConfirmation(
@CurrentUserId() id: string,
@Req() request: Request,
): Promise<boolean> {
this.logger.log({ id }, 'POST /user/confirm_email')
const user = await this.userService.findOne({ where: { id } })
if (
!user ||
!user.email ||
user.isActive ||
user.emailRequests >= MAX_EMAIL_REQUESTS
)
return false
const token = await this.actionTokensService.createForUser(
user,
ActionTokenType.EMAIL_VERIFICATION,
user.email,
)
const url = `${isDevelopment ? request.headers.origin : PRODUCTION_ORIGIN}/verify/${token.id}`
await this.userService.update(id, {
emailRequests: 1 + user.emailRequests,
})
await this.mailerService.sendEmail(user.email, LetterTemplate.SignUp, {
url,
})
return true
}
@ApiBearerAuth()
@Delete('/tg/:id')
@HttpCode(204)
async deleteTelegramConnection(
@Param('id') tgID: string,
@CurrentUserId() id: string,
): Promise<any> {
this.logger.log({ tgID, id }, 'DELETE /user/tg/:id')
const user = await this.userService.findOne({ where: { id } })
if (tgID && user.telegramChatId === tgID) {
await this.userService.update(id, {
telegramChatId: null,
isTelegramChatIdConfirmed: false,
})
}
}
@ApiBearerAuth()
@Put('/')
async updateCurrentUser(
@Body() userDTO: UpdateUserProfileDTO,
@CurrentUserId() id: string,
@Req() request: Request,
): Promise<Partial<User>> {
this.logger.log({ id }, 'PUT /user')
const user = await this.userService.findOne({ where: { id } })
const shouldUpdatePassword =
!_isEmpty(userDTO.password) && _isString(userDTO.password)
if (shouldUpdatePassword) {
const currentPassword = userDTO.currentPassword
if (_isEmpty(currentPassword) || !_isString(currentPassword)) {
throw new BadRequestException('incorrectPassword')
}
const isPasswordValid = await this.authService.comparePassword(
currentPassword,
user.password,
)
if (!isPasswordValid) {
throw new BadRequestException('incorrectPassword')
}
this.userService.validatePassword(userDTO.password)
userDTO.password = await this.authService.hashPassword(userDTO.password)
}
try {
if (userDTO.email && user.email !== userDTO.email) {
const userWithByEmail = await this.userService.findOne({
where: { email: userDTO.email },
})
if (userWithByEmail) {
throw new BadRequestException('User with this email already exists')
}
await checkRateLimit(user.id, 'change-email', 5)
const token = await this.actionTokensService.createForUser(
user,
ActionTokenType.EMAIL_CHANGE,
userDTO.email,
)
const url = `${
isDevelopment ? request.headers.origin : PRODUCTION_ORIGIN
}/change-email/${token.id}`
await this.mailerService.sendEmail(
user.email,
LetterTemplate.MailAddressChangeConfirmation,
{ url },
)
}
if (
userDTO.telegramChatId &&
user.telegramChatId !== userDTO.telegramChatId
) {
const userWithByTelegramChatId = await this.userService.findOne({
where: { telegramChatId: userDTO.telegramChatId },
})
if (userWithByTelegramChatId) {
throw new BadRequestException(
'User with this Telegram chat ID already exists',
)
}
await this.userService.update(id, {
isTelegramChatIdConfirmed: false,
})
await this.telegramService.addMessage(
userDTO.telegramChatId,
'Please confirm your Telegram chat ID',
Markup.inlineKeyboard([
[
Markup.button.callback(
'✅ Confirm',
`link-account:confirm:${id}`,
),
Markup.button.callback('❌ Cancel', `link-account:cancel:${id}`),
],
]),
)
}
if (userDTO.timeFormat && user.timeFormat !== userDTO.timeFormat) {
await this.userService.update(id, {
timeFormat: userDTO.timeFormat,
})
}
const userToUpdate = _pick(userDTO, [
'password',
'reportFrequency',
'timezone',
'showLiveVisitorsInTitle',
'telegramChatId',
'receiveLoginNotifications',
'timeFormat',
])
await this.userService.update(id, userToUpdate)
if (shouldUpdatePassword) {
await Promise.all([
this.mailerService.sendEmail(
user.email,
LetterTemplate.PasswordChanged,
),
this.authService.logoutAll(id),
this.actionTokensService.deleteMultiple({
user: { id },
action: ActionTokenType.PASSWORD_RESET,
}),
])
}
const updatedUser = await this.userService.findOne({ where: { id } })
return this.userService.omitSensitiveData(updatedUser)
} catch (reason) {
throw new BadRequestException(reason.message)
}
}
@Get('metainfo')
@Public()
async getMetaInfo(
@Headers() headers,
@Ip() reqIP: string,
): Promise<IMetaInfo> {
const ip = getIPFromHeaders(headers) || reqIP || ''
const { country, city, region } = getIPDetails(ip)
return {
country,
city,
region,
...this.userService.getCurrencyByCountry(country),
}
}
@Get('usageinfo')
async getUsageInfo(@CurrentUserId() uid: string): Promise<IUsageInfo> {
const [rawInfo, rawLast30DaysInfo, projects, sessionReplays] =
await Promise.all([
this.projectService.getRedisUsageInfo(uid),
this.projectService.getRedisUsageInfo(uid, 'last30Days'),
this.projectService.countByAdminId(uid),
this.projectService.getMonthlySessionReplayUsage(uid),
])
return {
...formatUsageInfo(rawInfo),
projects,
sessionReplays,
last30Days: formatUsageInfo(rawLast30DaysInfo),
}
}
@ApiBearerAuth()
@Get('payments')
async getPayments(@CurrentUserId() uid: string): Promise<UserPayment[]> {
return this.userService.getPayments(uid)
}
@ApiBearerAuth()
@Post('change-plan')
async changePlan(
@CurrentUserId() id: string,
@Body() body: IChangePlanDTO,
): Promise<void> {
const { planId, planType, swetrixProfileId, swetrixSessionId } = body
this.logger.log(
{
id,
planId,
planType,
hasSwetrixProfileId: !!swetrixProfileId,
hasSwetrixSessionId: !!swetrixSessionId,
},
'POST /change-plan',
)
await this.userService.updateSubscription(id, planId, planType, {
swetrixProfileId,
swetrixSessionId,
})
await this.projectService.clearProjectsRedisCache(id)
}
@ApiBearerAuth()
@Post('generate-pay-link')
async generatePayLink(
@CurrentUserId() id: string,
@Body() body: IChangePlanDTO,
): Promise<any> {
const { planId, planType, eventTier, swetrixProfileId, swetrixSessionId } =
body
this.logger.log(
{
id,
planId,
planType,
eventTier,
hasSwetrixProfileId: !!swetrixProfileId,
hasSwetrixSessionId: !!swetrixSessionId,
},
'POST /generate-pay-link',
)
return this.userService.generatePayLink(id, planId, {
planType,
eventTier,
swetrixProfileId,
swetrixSessionId,
})
}
@ApiBearerAuth()
@Post('preview-plan')
async previewPlan(
@CurrentUserId() id: string,
@Body() body: IChangePlanDTO,
): Promise<any> {
this.logger.log({ body, id }, 'POST /preview-plan')
const { planId, planType } = body
return this.userService.previewSubscription(id, planId, planType)
}
@ApiBearerAuth()
@Post('addons/websites/preview')
async previewWebsiteAddon(
@CurrentUserId() id: string,
@Body() body: UpdateWebsiteAddonDTO,
): Promise<any> {
this.logger.log({ body, id }, 'POST /addons/websites/preview')
return this.userService.previewWebsiteAddon(
id,
body.quantity,
body.billingInterval,
)
}
@ApiBearerAuth()
@Put('addons/websites')
async updateWebsiteAddon(
@CurrentUserId() id: string,
@Body() body: UpdateWebsiteAddonDTO,
): Promise<Partial<User>> {
this.logger.log({ body, id }, 'PUT /addons/websites')
const user = await this.userService.updateWebsiteAddon(
id,
body.quantity,
body.billingInterval,
)
await this.projectService.clearProjectsRedisCache(id)
return user
}
@ApiBearerAuth()
@Post('addons/session-replays/preview')
async previewSessionReplayAddon(
@CurrentUserId() id: string,
@Body() body: UpdateSessionReplayAddonDTO,
): Promise<any> {
this.logger.log({ body, id }, 'POST /addons/session-replays/preview')
return this.userService.previewSessionReplayAddon(
id,
body.quantity,
body.billingInterval,
)
}
@ApiBearerAuth()
@Put('addons/session-replays')
async updateSessionReplayAddon(
@CurrentUserId() id: string,
@Body() body: UpdateSessionReplayAddonDTO,
): Promise<Partial<User>> {
this.logger.log({ body, id }, 'PUT /addons/session-replays')
const user = await this.userService.updateSessionReplayAddon(
id,
body.quantity,
body.billingInterval,
)
await this.projectService.clearProjectsRedisCache(id)
return user
}
@ApiBearerAuth()
@Post('subscription/cancel')
async cancelSubscription(
@CurrentUserId() id: string,
@Body() body: CancelSubscriptionDTO,
@Headers() headers: Record<string, string>,
@Ip() requestIp: string,
): Promise<void> {
this.logger.log({ id }, 'POST /subscription/cancel')
const ip = getIPFromHeaders(headers) || requestIp || ''
const user = await this.userService.findOne({ where: { id } })
if (!user) {
throw new BadRequestException('User not found')
}
if (_includes(UNPAID_PLANS, user.planCode)) {
throw new BadRequestException('No paid subscription to cancel')
}
if (!user.subID) {
throw new BadRequestException('No active subscription found')
}
await this.userService.cancelSubscription(user.subID)
if (body.feedback) {
try {
await this.userService.saveCancellationFeedback(
user.email,
user.planCode,
body.feedback,
)
} catch (reason) {
this.logger.error(
'[ERROR] Failed to save cancellation feedback:',
reason,
)
}
}
await trackCustom(ip, headers['user-agent'], {
ev: 'SUBSCRIPTION_CANCELLED',
meta: {
plan: user.planCode,
feedback_given: !!body.feedback,
},
})
}
// Used to unsubscribe from email reports
@Get('/unsubscribe/:token')
@Public()
@ApiResponse({ status: 204 })
async unsubscribeFromEmailReports(
@Param('token') token: string,
): Promise<void> {
this.logger.log({ token }, 'GET /project/unsubscribe/:token')
let userId
try {
userId = this.userService.decryptUnsubscribeKey(token)
} catch {
throw new NotFoundException('Unsubscribe token is invalid')
}
const user = await this.userService.findOne({ where: { id: userId } })
if (!user) {
throw new NotFoundException('Unsubscribe token is invalid')
}
await this.userService.update(userId, {
reportFrequency: ReportFrequency.NEVER,
})
}
@ApiBearerAuth()
@Post('onboarding/step')
@ApiResponse({ status: 204 })
async updateOnboardingStep(
@CurrentUserId() userId: string,
@Body('step') step: OnboardingStep,
): Promise<void> {
this.logger.log({ userId, step }, 'POST /user/onboarding/step')
if (!Object.values(OnboardingStep).includes(step)) {
throw new BadRequestException('Invalid onboarding step')
}
await this.userService.update(userId, {
onboardingStep: step,
})
}
@ApiBearerAuth()
@Post('onboarding/complete')
@ApiResponse({ status: 204 })
async completeOnboarding(@CurrentUserId() userId: string): Promise<void> {
this.logger.log({ userId }, 'POST /user/onboarding/complete')
await this.userService.update(userId, {
onboardingStep: OnboardingStep.COMPLETED,
hasCompletedOnboarding: true,
})
}
}