π¨ The ultimate agentic social media scheduling tool π€
TypeScript nextjsopen-sourceopen-source-social-media-scheduling-toolosspostiz-cloudpostiz-hostedredisscheduling-toolsocial-media-scheduling-tooltypescript
feat: delete account
Nevo Davidafd034b266cd
diff --git a/apps/backend/src/api/routes/users.controller.ts b/apps/backend/src/api/routes/users.controller.tsindex 26f3441e3..896cc03b1 100644--- a/apps/backend/src/api/routes/users.controller.ts+++ b/apps/backend/src/api/routes/users.controller.ts@@ -328,6 +328,48 @@ export class UsersController {response.status(200).send();}+ @Post('/delete-account')+ async deleteAccount(+ @GetUserFromRequest() user: User,+ @Req() req: Request,+ @Res({ passthrough: true }) response: Response+ ) {+ const impersonate = req.cookies.impersonate || req.headers.impersonate;+ if (impersonate) {+ throw new HttpException(+ 'Account cannot be deleted while impersonating',+ 400+ );+ }++ // Cancel billing before scrubbing the account β once the account is+ // deleted there is no way to retry a failed cancellation+ const ownedOrgs = await this._userService.getOrgsToDeleteForAccount(+ user.id+ );++ if (process.env.STRIPE_PUBLISHABLE_KEY) {+ for (const org of ownedOrgs) {+ if (!org.paymentId) {+ continue;+ }+ try {+ await this._stripeService.cancelAllSubscriptions(org.id);+ } catch (err) {+ console.log(err);+ throw new HttpException(+ 'Could not cancel your subscription, please try again or contact support',+ 400+ );+ }+ }+ }++ await this._userService.deleteAccount(user.id);++ return this.logout(response);+ }+@Post('/logout')logout(@Res({ passthrough: true }) response: Response) {response.header('logout', 'true');diff --git a/apps/frontend/src/components/settings/delete-account.component.tsx b/apps/frontend/src/components/settings/delete-account.component.tsxnew file mode 100644index 000000000..f90ea05df--- /dev/null+++ b/apps/frontend/src/components/settings/delete-account.component.tsx@@ -0,0 +1,100 @@+'use client';++import React, { useCallback, useState } from 'react';+import { useFetch } from '@gitroom/helpers/utils/custom.fetch';+import { deleteDialog } from '@gitroom/react/helpers/delete.dialog';+import { Button } from '@gitroom/react/form/button';+import { useVariables } from '@gitroom/react/helpers/variable.context';+import { setCookie } from '@gitroom/frontend/components/layout/layout.context';+import { useToaster } from '@gitroom/react/toaster/toaster';+import { useT } from '@gitroom/react/translation/get.transation.service.client';++const DeleteAccountComponent = () => {+ const t = useT();+ const fetch = useFetch();+ const toaster = useToaster();+ const { isSecured } = useVariables();+ const [loading, setLoading] = useState(false);++ const deleteAccount = useCallback(async () => {+ if (+ !(await deleteDialog(+ t(+ 'delete_account_confirm',+ 'Your account, organizations, channels and posts will be deleted. This action cannot be undone, are you sure?'+ ),+ t('yes_delete_my_account', 'Yes, delete my account')+ ))+ ) {+ return;+ }++ setLoading(true);+ try {+ const response = await fetch('/user/delete-account', {+ method: 'POST',+ });++ if (response.status !== 200 && response.status !== 201) {+ const { message } = await response.json().catch(() => ({+ message: '',+ }));+ toaster.show(+ message ||+ t('could_not_delete_account', 'Could not delete your account'),+ 'warning'+ );+ return;+ }++ if (!isSecured) {+ setCookie('auth', '', -10);+ }+ window.location.href = '/';+ } finally {+ setLoading(false);+ }+ }, [isSecured]);++ return (+ <div className="my-[16px] mt-[16px] bg-sixth border-fifth border rounded-[4px] p-[24px] flex flex-col gap-[24px]">+ {loading && (+ <div className="text-textColor fixed start-0 top-0 bg-primary/80 z-[500] w-full h-full animate-fade flex flex-col items-center justify-center gap-[24px]">+ <div className="w-[48px] h-[48px] border-[3px] border-forth border-t-transparent rounded-full animate-spin" />+ <div className="text-[20px] font-semibold">+ {t('deleting_your_account', 'Deleting your account...')}+ </div>+ <div className="text-[14px] text-textItemBlur">+ {t(+ 'deleting_your_account_description',+ 'We are removing your channels and posts, this can take a while. Please donβt close this window.'+ )}+ </div>+ </div>+ )}+ <div className="mt-[4px]">{t('delete_account', 'Delete Account')}</div>+ <div className="flex items-center justify-between">+ <div className="flex flex-col">+ <div className="text-[14px]">+ {t('delete_your_account', 'Delete your account')}+ </div>+ <div className="text-[12px] text-textItemBlur">+ {t(+ 'delete_account_description',+ 'Your account, organizations and channels will be deleted permanently'+ )}+ </div>+ </div>+ <Button+ className="!bg-red-800"+ loading={loading}+ onClick={deleteAccount}+ >+ {t('delete_account', 'Delete Account')}+ </Button>+ </div>+ </div>+ );+};++export default DeleteAccountComponent;diff --git a/apps/frontend/src/components/settings/global.settings.tsx b/apps/frontend/src/components/settings/global.settings.tsxindex 6fc56cd88..ddb4fa679 100644--- a/apps/frontend/src/components/settings/global.settings.tsx+++ b/apps/frontend/src/components/settings/global.settings.tsx@@ -5,6 +5,7 @@ import { useT } from '@gitroom/react/translation/get.transation.service.client';import dynamic from 'next/dynamic';import EmailNotificationsComponent from '@gitroom/frontend/components/settings/email-notifications.component';import ShortlinkPreferenceComponent from '@gitroom/frontend/components/settings/shortlink-preference.component';+import DeleteAccountComponent from '@gitroom/frontend/components/settings/delete-account.component';const MetricComponent = dynamic(() => import('@gitroom/frontend/components/settings/metric.component'),@@ -21,6 +22,7 @@ export const GlobalSettings = () => {<MetricComponent /><EmailNotificationsComponent /><ShortlinkPreferenceComponent />+ <DeleteAccountComponent /></div>);};diff --git a/libraries/nestjs-libraries/src/database/prisma/integrations/integration.repository.ts b/libraries/nestjs-libraries/src/database/prisma/integrations/integration.repository.tsindex 15434d6c8..f03a6b5d8 100644--- a/libraries/nestjs-libraries/src/database/prisma/integrations/integration.repository.ts+++ b/libraries/nestjs-libraries/src/database/prisma/integrations/integration.repository.ts@@ -1,5 +1,6 @@import { PrismaRepository } from '@gitroom/nestjs-libraries/database/prisma/prisma.service';import { Injectable } from '@nestjs/common';+import { createHash } from 'crypto';import dayjs from 'dayjs';import { Integration } from '@prisma/client';import { makeId } from '@gitroom/nestjs-libraries/services/make.is';@@ -69,9 +70,14 @@ export class IntegrationRepository {}async checkPreviousConnections(org: string, id: string) {+ // Deleted accounts keep their integrations with an md5 hashed+ // rootInternalId, so match both the raw id and its hash to still catch+ // channels that were connected by a deleted account.const findIt = await this._integration.model.integration.findMany({where: {- rootInternalId: id,+ rootInternalId: {+ in: [id, createHash('md5').update(id).digest('hex')],+ },},select: {organizationId: true,@@ -542,6 +548,55 @@ export class IntegrationRepository {});}+ async deleteIntegrationsForAccount(org: string) {+ const hash = (value: string) =>+ createHash('md5').update(value).digest('hex');++ await this._posts.model.post.updateMany({+ where: {+ organizationId: org,+ deletedAt: null,+ },+ data: {+ deletedAt: new Date(),+ },+ });++ const integrations = await this._integration.model.integration.findMany({+ where: {+ organizationId: org,+ },+ });++ // md5 is deterministic, so a hashed rootInternalId can still be matched+ // by checkPreviousConnections when the same channel is connected again+ // from a new account.+ for (const integration of integrations) {+ await this._integration.model.integration.update({+ where: {+ id: integration.id,+ },+ data: {+ name: hash(integration.name),+ internalId: hash(integration.internalId),+ rootInternalId: integration.rootInternalId+ ? hash(integration.rootInternalId)+ : null,+ token: hash(integration.token),+ refreshToken: integration.refreshToken+ ? hash(integration.refreshToken)+ : null,+ profile: integration.profile ? hash(integration.profile) : null,+ customInstanceDetails: integration.customInstanceDetails+ ? hash(integration.customInstanceDetails)+ : null,+ picture: null,+ deletedAt: integration.deletedAt || new Date(),+ },+ });+ }+ }+async checkForDeletedOnceAndUpdate(org: string, page: string) {return this._integration.model.integration.updateMany({where: {diff --git a/libraries/nestjs-libraries/src/database/prisma/organizations/organization.repository.ts b/libraries/nestjs-libraries/src/database/prisma/organizations/organization.repository.tsindex 1114051b9..60e4dd8d1 100644--- a/libraries/nestjs-libraries/src/database/prisma/organizations/organization.repository.ts+++ b/libraries/nestjs-libraries/src/database/prisma/organizations/organization.repository.ts@@ -56,6 +56,7 @@ export class OrganizationRepository {return this._organization.model.organization.findFirst({where: {apiKey: api,+ deletedAt: null,},include: {subscription: {@@ -176,6 +177,7 @@ export class OrganizationRepository {async getOrgsByUserId(userId: string) {return this._organization.model.organization.findMany({where: {+ deletedAt: null,users: {some: {userId,@@ -390,6 +392,17 @@ export class OrganizationRepository {});}+ deleteOrganization(orgId: string) {+ return this._organization.model.organization.update({+ where: {+ id: orgId,+ },+ data: {+ deletedAt: new Date(),+ },+ });+ }+async deleteTeamMember(orgId: string, userId: string) {return this._userOrg.model.userOrganization.delete({where: {diff --git a/libraries/nestjs-libraries/src/database/prisma/schema.prisma b/libraries/nestjs-libraries/src/database/prisma/schema.prismaindex 1c1f21d8e..629637450 100644--- a/libraries/nestjs-libraries/src/database/prisma/schema.prisma+++ b/libraries/nestjs-libraries/src/database/prisma/schema.prisma@@ -17,6 +17,7 @@ model Organization {streakSince DateTime?createdAt DateTime @default(now())updatedAt DateTime @updatedAt+ deletedAt DateTime?allowTrial Boolean @default(false)isTrailing Boolean @default(false)shortlink ShortLinkPreference @default(ASK)@@ -47,6 +48,7 @@ model Organization {@@index([apiKey])@@index([streakSince])@@index([paymentId])+ @@index([deletedAt])}model Tags {@@ -99,6 +101,7 @@ model User {lastOnline DateTime @default(now())ip String?agent String?+ deletedAt DateTime?comments Comments[]items ItemUser[]groupBuyer MessagesGroup[] @relation("groupBuyer")@@ -120,6 +123,7 @@ model User {@@index([account])@@index([lastOnline])@@index([pictureId])+ @@index([deletedAt])}model UsedCodes {diff --git a/libraries/nestjs-libraries/src/database/prisma/users/users.repository.ts b/libraries/nestjs-libraries/src/database/prisma/users/users.repository.tsindex 71d6dedc1..da2b18d13 100644--- a/libraries/nestjs-libraries/src/database/prisma/users/users.repository.ts+++ b/libraries/nestjs-libraries/src/database/prisma/users/users.repository.ts@@ -3,6 +3,7 @@ import {PrismaTransaction,} from '@gitroom/nestjs-libraries/database/prisma/prisma.service';import { Injectable } from '@nestjs/common';+import { createHash } from 'crypto';import { Provider, Role } from '@prisma/client';import { AuthService } from '@gitroom/helpers/auth/auth.service';import { UserDetailDto } from '@gitroom/nestjs-libraries/dtos/users/user.details.dto';@@ -73,6 +74,7 @@ export class UsersRepository {getImpersonateUser(name: string) {return this._user.model.user.findMany({where: {+ deletedAt: null,OR: [{name: {@@ -104,6 +106,7 @@ export class UsersRepository {return this._user.model.user.findFirst({where: {id,+ deletedAt: null,},});}@@ -116,6 +119,7 @@ export class UsersRepository {mode: 'insensitive',},providerName: Provider.LOCAL,+ deletedAt: null,},include: {picture: {@@ -133,6 +137,7 @@ export class UsersRepository {where: {email,id: { not: excludeUserId },+ deletedAt: null,organizations: {some: {role: Role.SUPERADMIN,@@ -162,6 +167,44 @@ export class UsersRepository {where: {providerId,providerName: provider,+ deletedAt: null,+ },+ });+ }++ async deleteAccount(userId: string) {+ const user = await this._user.model.user.findUnique({+ where: {+ id: userId,+ },+ });++ if (!user || user.deletedAt) {+ return;+ }++ const hash = (value: string) =>+ createHash('md5').update(value).digest('hex');++ // Hash the identifying fields instead of removing the row, the random+ // suffix keeps [email, providerName] unique if the same email is deleted+ // more than once+ return this._user.model.user.update({+ where: {+ id: userId,+ },+ data: {+ email: `deleted_${hash(user.email.toLowerCase())}_${makeId(5)}`,+ password: null,+ name: user.name ? hash(user.name) : null,+ lastName: user.lastName ? hash(user.lastName) : null,+ providerId: user.providerId ? hash(user.providerId) : null,+ bio: null,+ ip: null,+ agent: null,+ account: null,+ pictureId: null,+ deletedAt: new Date(),},});}diff --git a/libraries/nestjs-libraries/src/database/prisma/users/users.service.ts b/libraries/nestjs-libraries/src/database/prisma/users/users.service.tsindex b0bf65726..decb2c6a3 100644--- a/libraries/nestjs-libraries/src/database/prisma/users/users.service.ts+++ b/libraries/nestjs-libraries/src/database/prisma/users/users.service.ts@@ -1,9 +1,10 @@-import { Injectable, Logger } from '@nestjs/common';+import { HttpException, Injectable, Logger } from '@nestjs/common';import { UsersRepository } from '@gitroom/nestjs-libraries/database/prisma/users/users.repository';-import { Provider } from '@prisma/client';+import { Provider, Role } from '@prisma/client';import { UserDetailDto } from '@gitroom/nestjs-libraries/dtos/users/user.details.dto';import { EmailNotificationsDto } from '@gitroom/nestjs-libraries/dtos/users/email-notifications.dto';import { OrganizationRepository } from '@gitroom/nestjs-libraries/database/prisma/organizations/organization.repository';+import { IntegrationRepository } from '@gitroom/nestjs-libraries/database/prisma/integrations/integration.repository';import { NotificationService } from '@gitroom/nestjs-libraries/database/prisma/notifications/notification.service';@Injectable()@@ -11,6 +12,7 @@ export class UsersService {constructor(private _usersRepository: UsersRepository,private _organizationRepository: OrganizationRepository,+ private _integrationRepository: IntegrationRepository,private _notificationService: NotificationService) {}@@ -82,6 +84,49 @@ export class UsersService {return { kept, switched };}+ async getOrgsToDeleteForAccount(userId: string) {+ const orgs = await this._organizationRepository.getOrgsByUserId(userId);+ const ownedOrgs = orgs.filter(+ (org) => org.users[0].role === Role.SUPERADMIN+ );++ for (const org of ownedOrgs) {+ const team = await this._organizationRepository.getTeam(org.id);+ if (team?.users?.some((member) => member.user.id !== userId)) {+ throw new HttpException(+ 'Please remove your team members before deleting your account',+ 400+ );+ }+ }++ return ownedOrgs;+ }++ async deleteAccount(userId: string) {+ const deletedOrgs = await this.getOrgsToDeleteForAccount(userId);+ const orgs = await this._organizationRepository.getOrgsByUserId(userId);++ for (const org of orgs) {+ if (org.users[0].role === Role.SUPERADMIN) {+ await this._integrationRepository.deleteIntegrationsForAccount(org.id);+ await this._organizationRepository.deleteOrganization(org.id);+ } else {+ await this._organizationRepository.deleteTeamMember(org.id, userId);+ }+ }++ await this._usersRepository.deleteAccount(userId);++ this._logger.log(+ `Account ${userId} deleted, organizations removed: ${deletedOrgs+ .map((org) => org.id)+ .join(', ')}`+ );++ return { deletedOrgs };+ }+activateUser(id: string) {return this._usersRepository.activateUser(id);}diff --git a/libraries/nestjs-libraries/src/services/stripe.service.ts b/libraries/nestjs-libraries/src/services/stripe.service.tsindex c781c18de..06c6559a2 100644--- a/libraries/nestjs-libraries/src/services/stripe.service.ts+++ b/libraries/nestjs-libraries/src/services/stripe.service.ts@@ -390,6 +390,29 @@ export class StripeService {};}+ async cancelAllSubscriptions(organizationId: string) {+ // getOrgById must not filter deletedAt, this can run for an organization+ // that was already soft deleted by an account deletion+ const org = await this._organizationService.getOrgById(organizationId);+ if (!org?.paymentId) {+ return;+ }++ const subscriptions = await stripe.subscriptions.list({+ customer: org.paymentId,+ status: 'all',+ limit: 100,+ });++ for (const subscription of subscriptions.data.filter(+ (f) => f.status !== 'canceled'+ )) {+ await stripe.subscriptions.cancel(subscription.id);+ }++ await this._subscriptionService.deleteSubscription(org.paymentId);+ }+async getCustomerByOrganizationId(organizationId: string) {const org = (await this._organizationService.getOrgById(organizationId))!;return org.paymentId;