The minimalistic document archiving platform.
feat(users): add user deletion usecase (#1108)
Corentin Thomasset52ca9d70415e
diff --git a/apps/papra-server/src/modules/app/database/database.test-utils.ts b/apps/papra-server/src/modules/app/database/database.test-utils.tsindex 7998a490..dfe8d409 100644--- a/apps/papra-server/src/modules/app/database/database.test-utils.ts+++ b/apps/papra-server/src/modules/app/database/database.test-utils.ts@@ -14,6 +14,7 @@ import { taggingRuleActionsTable, taggingRuleConditionsTable, taggingRulesTableimport { documentsTagsTable, tagsTable } from '../../tags/tags.table';import { usersTable } from '../../users/users.table';import { webhookDeliveriesTable, webhookEventsTable, webhooksTable } from '../../webhooks/webhooks.tables';+import { accountsTable, sessionsTable, twoFactorTable } from '../auth/auth.tables';import { setupDatabase } from './database';export { createInMemoryDatabase, seedDatabase };@@ -35,27 +36,30 @@ async function createInMemoryDatabase(seedOptions: Omit<Parameters<typeof seedDa}const seedTables = {- users: usersTable,- organizations: organizationsTable,- organizationMembers: organizationMembersTable,+ accounts: accountsTable,+ apiKeyOrganizations: apiKeyOrganizationsTable,+ apiKeys: apiKeysTable,+ customPropertyDefinitions: customPropertyDefinitionsTable,+ customPropertySelectOptions: customPropertySelectOptionsTable,+ documentCustomPropertyValues: documentCustomPropertyValuesTable,documents: documentsTable,- tags: tagsTable,documentsTags: documentsTagsTable,intakeEmails: intakeEmailsTable,+ organizationInvitations: organizationInvitationsTable,+ organizationMembers: organizationMembersTable,+ organizations: organizationsTable,organizationSubscriptions: organizationSubscriptionsTable,- taggingRules: taggingRulesTable,- taggingRuleConditions: taggingRuleConditionsTable,+ sessions: sessionsTable,taggingRuleActions: taggingRuleActionsTable,- apiKeys: apiKeysTable,- apiKeyOrganizations: apiKeyOrganizationsTable,- webhooks: webhooksTable,- webhookEvents: webhookEventsTable,- webhookDeliveries: webhookDeliveriesTable,- organizationInvitations: organizationInvitationsTable,+ taggingRuleConditions: taggingRuleConditionsTable,+ taggingRules: taggingRulesTable,+ tags: tagsTable,+ twoFactor: twoFactorTable,userRoles: userRolesTable,- customPropertyDefinitions: customPropertyDefinitionsTable,- customPropertySelectOptions: customPropertySelectOptionsTable,- documentCustomPropertyValues: documentCustomPropertyValuesTable,+ users: usersTable,+ webhookDeliveries: webhookDeliveriesTable,+ webhookEvents: webhookEventsTable,+ webhooks: webhooksTable,} as const;type SeedTablesRows = {diff --git a/apps/papra-server/src/modules/organizations/organizations.repository.ts b/apps/papra-server/src/modules/organizations/organizations.repository.tsindex b35e8c25..8a07473e 100644--- a/apps/papra-server/src/modules/organizations/organizations.repository.ts+++ b/apps/papra-server/src/modules/organizations/organizations.repository.ts@@ -24,6 +24,7 @@ export function createOrganizationsRepository({ db }: { db: Database }) {deleteOrganization,getOrganizationById,getUserOwnedOrganizationCount,+ clearUserDeletedByReferences,getOrganizationOwner,getOrganizationMembersCount,getAllOrganizationIds,@@ -117,6 +118,13 @@ async function deleteOrganization({ organizationId, db }: { organizationId: striawait db.delete(organizationsTable).where(eq(organizationsTable.id, organizationId));}+async function clearUserDeletedByReferences({ userId, db }: { userId: string; db: Database }) {+ await db+ .update(organizationsTable)+ .set({ deletedBy: null })+ .where(eq(organizationsTable.deletedBy, userId));+}+async function getOrganizationById({ organizationId, db }: { organizationId: string; db: Database }) {const [organization] = await db.select()diff --git a/apps/papra-server/src/modules/users/users.errors.ts b/apps/papra-server/src/modules/users/users.errors.tsindex b2322d6a..e7623051 100644--- a/apps/papra-server/src/modules/users/users.errors.ts+++ b/apps/papra-server/src/modules/users/users.errors.ts@@ -23,3 +23,9 @@ export const createUserAccountCreationDisabledError = createErrorFactory({code: 'users.create_account_disabled',statusCode: 403,});++export const createUserStillOwnsOrganizationsError = createErrorFactory({+ message: 'User still owns organizations',+ code: 'users.still_owns_organizations',+ statusCode: 400,+});diff --git a/apps/papra-server/src/modules/users/users.repository.ts b/apps/papra-server/src/modules/users/users.repository.tsindex 40c6bbeb..722709d1 100644--- a/apps/papra-server/src/modules/users/users.repository.ts+++ b/apps/papra-server/src/modules/users/users.repository.ts@@ -21,6 +21,7 @@ function createUsersRepository({ db }: { db: Database }) {getUserById,getUserByIdOrThrow,updateUser,+ deleteUser,getUserCount,listUsers,},@@ -78,6 +79,10 @@ async function updateUser({ userId, name, db }: { userId: string; name: string;return { user };}+async function deleteUser({ userId, db }: { userId: string; db: Database }) {+ await db.delete(usersTable).where(eq(usersTable.id, userId));+}+export async function getUserCount({ db }: { db: Database }) {const [{ userCount = 0 } = {}] = await db.select({ userCount: count() }).from(usersTable);diff --git a/apps/papra-server/src/modules/users/users.usecases.test.ts b/apps/papra-server/src/modules/users/users.usecases.test.tsnew file mode 100644index 00000000..ec87cdc5--- /dev/null+++ b/apps/papra-server/src/modules/users/users.usecases.test.ts@@ -0,0 +1,130 @@+import { eq } from 'drizzle-orm';+import { describe, expect, test } from 'vitest';+import { accountsTable, sessionsTable, twoFactorTable } from '../app/auth/auth.tables';+import { createInMemoryDatabase } from '../app/database/database.test-utils';+import { ORGANIZATION_ROLES } from '../organizations/organizations.constants';+import { createOrganizationsRepository } from '../organizations/organizations.repository';+import { organizationMembersTable, organizationsTable } from '../organizations/organizations.table';+import { createUsersNotFoundError, createUserStillOwnsOrganizationsError } from './users.errors';+import { createUsersRepository } from './users.repository';+import { deleteUser } from './users.usecases';++describe('users usecases', () => {+ describe('deleteUser', () => {+ test('deletes the user', async () => {+ const { db } = await createInMemoryDatabase({+ users: [{ id: 'user-1', email: '[email protected]' }],+ });++ const usersRepository = createUsersRepository({ db });+ const organizationsRepository = createOrganizationsRepository({ db });++ await deleteUser({ userId: 'user-1', usersRepository, organizationsRepository });++ const { user } = await usersRepository.getUserById({ userId: 'user-1' });++ expect(user).toBeUndefined();+ });++ test('cascades the user organization memberships', async () => {+ const { db } = await createInMemoryDatabase({+ users: [+ { id: 'user-1', email: '[email protected]' },+ { id: 'user-2', email: '[email protected]' },+ ],+ organizations: [{ id: 'organization-1', name: 'Organization 1' }],+ organizationMembers: [+ { organizationId: 'organization-1', userId: 'user-1', role: ORGANIZATION_ROLES.MEMBER },+ { organizationId: 'organization-1', userId: 'user-2', role: ORGANIZATION_ROLES.OWNER },+ ],+ });++ const usersRepository = createUsersRepository({ db });+ const organizationsRepository = createOrganizationsRepository({ db });++ await deleteUser({ userId: 'user-1', usersRepository, organizationsRepository });++ const members = await db.select().from(organizationMembersTable).where(eq(organizationMembersTable.userId, 'user-1'));++ expect(members).toEqual([]);+ });++ test('deleting an user cascades the authentication related data, accounts, sessions, 2fa, ...', async () => {+ const { db } = await createInMemoryDatabase({+ users: [{ id: 'user-1', email: '[email protected]' }],+ accounts: [{ id: 'account-1', accountId: 'account-1', providerId: 'email', userId: 'user-1' }],+ sessions: [{ id: 'session-1', token: 'lorem-ipsum', userId: 'user-1', expiresAt: new Date('2050-01-01') }],+ twoFactor: [{ id: '2fa-1', userId: 'user-1', secret: 'super-secret' }],+ });++ const usersRepository = createUsersRepository({ db });+ const organizationsRepository = createOrganizationsRepository({ db });++ await deleteUser({ userId: 'user-1', usersRepository, organizationsRepository });++ const [+ accounts,+ sessions,+ twoFactor,+ ] = await Promise.all([+ db.select().from(accountsTable),+ db.select().from(sessionsTable),+ db.select().from(twoFactorTable),+ ]);++ expect(accounts).toEqual([]);+ expect(sessions).toEqual([]);+ expect(twoFactor).toEqual([]);+ });++ test('nulls the organizations.deleted_by reference instead of blocking the delete', async () => {+ const { db } = await createInMemoryDatabase({+ users: [{ id: 'user-1', email: '[email protected]' }],+ // The user soft-deleted this organization, but is no longer a member of it+ organizations: [{ id: 'organization-1', name: 'Organization 1', deletedAt: new Date(), deletedBy: 'user-1' }],+ });++ const usersRepository = createUsersRepository({ db });+ const organizationsRepository = createOrganizationsRepository({ db });++ await deleteUser({ userId: 'user-1', usersRepository, organizationsRepository });++ const [organization] = await db.select().from(organizationsTable).where(eq(organizationsTable.id, 'organization-1'));++ expect(organization).toBeDefined();+ expect(organization?.deletedBy).toBeNull();+ });++ test('throws an error when the user still owns an organization', async () => {+ const { db } = await createInMemoryDatabase({+ users: [{ id: 'user-1', email: '[email protected]' }],+ organizations: [{ id: 'organization-1', name: 'Organization 1' }],+ organizationMembers: [+ { organizationId: 'organization-1', userId: 'user-1', role: ORGANIZATION_ROLES.OWNER },+ ],+ });++ const usersRepository = createUsersRepository({ db });+ const organizationsRepository = createOrganizationsRepository({ db });++ await expect(+ deleteUser({ userId: 'user-1', usersRepository, organizationsRepository }),+ ).rejects.toThrow(createUserStillOwnsOrganizationsError());++ const { user } = await usersRepository.getUserById({ userId: 'user-1' });++ expect(user).toBeDefined();+ });++ test('throws an error when the user does not exist', async () => {+ const { db } = await createInMemoryDatabase({});++ const usersRepository = createUsersRepository({ db });+ const organizationsRepository = createOrganizationsRepository({ db });++ await expect(+ deleteUser({ userId: 'unknown-user', usersRepository, organizationsRepository }),+ ).rejects.toThrow(createUsersNotFoundError());+ });+ });+});diff --git a/apps/papra-server/src/modules/users/users.usecases.ts b/apps/papra-server/src/modules/users/users.usecases.tsindex 43fd5338..4b637b11 100644--- a/apps/papra-server/src/modules/users/users.usecases.ts+++ b/apps/papra-server/src/modules/users/users.usecases.ts@@ -1,5 +1,7 @@+import type { OrganizationsRepository } from '../organizations/organizations.repository';import type { UsersRepository } from './users.repository';import type { DbInsertableUser } from './users.types';+import { createUserStillOwnsOrganizationsError } from './users.errors';export async function createUser({user: userPartials,@@ -12,3 +14,30 @@ export async function createUser({return { user };}++export async function deleteUser({+ userId,+ usersRepository,+ organizationsRepository,+}: {+ userId: string;+ usersRepository: UsersRepository;+ organizationsRepository: OrganizationsRepository;+}) {+ // Ensure the user exists (throws createUsersNotFoundError otherwise)+ await usersRepository.getUserByIdOrThrow({ userId });++ // Block deletion if the user still owns any organization+ const { organizationCount } = await organizationsRepository.getUserOwnedOrganizationCount({ userId });++ if (organizationCount > 0) {+ throw createUserStillOwnsOrganizationsError();+ }++ // Legacy: organizations.deleted_by has no ON DELETE clause in the DB,+ // so it must be nulled manually before deleting the user.+ await organizationsRepository.clearUserDeletedByReferences({ userId });++ // Hard delete the user — remaining FKs cascade / set null as configured.+ await usersRepository.deleteUser({ userId });+}