feat: delete workspace member (#987)

* add delete user endpoint (server)

* delete user (UI)

* prevent token generation

* more checks
This commit is contained in:
Philip Okugbe
2025-04-07 19:26:03 +01:00
committed by GitHub
parent 3559358d14
commit 7431804a46
15 changed files with 250 additions and 23 deletions

View File

@ -17,6 +17,9 @@ export class AttachmentProcessor extends WorkerHost implements OnModuleDestroy {
if (job.name === QueueJob.DELETE_SPACE_ATTACHMENTS) {
await this.attachmentService.handleDeleteSpaceAttachments(job.data.id);
}
if (job.name === QueueJob.DELETE_USER_AVATARS) {
await this.attachmentService.handleDeleteUserAvatars(job.data.id);
}
} catch (err) {
throw err;
}

View File

@ -281,10 +281,42 @@ export class AttachmentService {
}),
);
if(failedDeletions.length === attachments.length){
throw new Error(`Failed to delete any attachments for spaceId: ${spaceId}`);
if (failedDeletions.length === attachments.length) {
throw new Error(
`Failed to delete any attachments for spaceId: ${spaceId}`,
);
}
} catch (err) {
throw err;
}
}
async handleDeleteUserAvatars(userId: string) {
try {
const userAvatars = await this.db
.selectFrom('attachments')
.select(['id', 'filePath'])
.where('creatorId', '=', userId)
.where('type', '=', AttachmentType.Avatar)
.execute();
if (!userAvatars || userAvatars.length === 0) {
return;
}
await Promise.all(
userAvatars.map(async (attachment) => {
try {
await this.storageService.delete(attachment.filePath);
await this.attachmentRepo.deleteAttachmentById(attachment.id);
} catch (err) {
this.logger.log(
`DeleteUserAvatar: failed to delete user avatar ${attachment.id}:`,
err,
);
}
}),
);
} catch (err) {
throw err;
}

View File

@ -43,18 +43,16 @@ export class AuthService {
) {}
async login(loginDto: LoginDto, workspaceId: string) {
const user = await this.userRepo.findByEmail(
loginDto.email,
workspaceId,
{
includePassword: true
}
const user = await this.userRepo.findByEmail(loginDto.email, workspaceId, {
includePassword: true,
});
const isPasswordMatch = await comparePasswordHash(
loginDto.password,
user.password,
);
if (
!user ||
!(await comparePasswordHash(loginDto.password, user.password))
) {
if (!user || !isPasswordMatch || user.deletedAt) {
throw new UnauthorizedException('email or password does not match');
}
@ -86,7 +84,7 @@ export class AuthService {
includePassword: true,
});
if (!user) {
if (!user || user.deletedAt) {
throw new NotFoundException('User not found');
}
@ -125,7 +123,7 @@ export class AuthService {
workspace.id,
);
if (!user) {
if (!user || user.deletedAt) {
return;
}
@ -168,7 +166,7 @@ export class AuthService {
}
const user = await this.userRepo.findById(userToken.userId, workspaceId);
if (!user) {
if (!user || user.deletedAt) {
throw new NotFoundException('User not found');
}

View File

@ -1,4 +1,8 @@
import { Injectable, UnauthorizedException } from '@nestjs/common';
import {
ForbiddenException,
Injectable,
UnauthorizedException,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { EnvironmentService } from '../../../integrations/environment/environment.service';
import {
@ -17,6 +21,10 @@ export class TokenService {
) {}
async generateAccessToken(user: User): Promise<string> {
if (user.deletedAt) {
throw new ForbiddenException();
}
const payload: JwtPayload = {
sub: user.id,
email: user.email,

View File

@ -1,9 +1,4 @@
import {
BadRequestException,
Injectable,
Logger,
UnauthorizedException,
} from '@nestjs/common';
import { Injectable, Logger, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy } from 'passport-jwt';
import { EnvironmentService } from '../../../integrations/environment/environment.service';
@ -47,7 +42,7 @@ export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
}
const user = await this.userRepo.findById(payload.sub, payload.workspaceId);
if (!user) {
if (!user || user.deletedAt) {
throw new UnauthorizedException();
}

View File

@ -84,6 +84,7 @@ export class SearchService {
.select(['id', 'name', 'avatarUrl'])
.where((eb) => eb(sql`LOWER(users.name)`, 'like', `%${query}%`))
.where('workspaceId', '=', workspaceId)
.where('deletedAt', 'is', null)
.limit(limit)
.execute();
}

View File

@ -34,6 +34,7 @@ import { addDays } from 'date-fns';
import { FastifyReply } from 'fastify';
import { EnvironmentService } from '../../../integrations/environment/environment.service';
import { CheckHostnameDto } from '../dto/check-hostname.dto';
import { RemoveWorkspaceUserDto } from '../dto/remove-workspace-user.dto';
@UseGuards(JwtAuthGuard)
@Controller('workspace')
@ -120,6 +121,22 @@ export class WorkspaceController {
}
}
@HttpCode(HttpStatus.OK)
@Post('members/delete')
async deleteWorkspaceMember(
@Body() dto: RemoveWorkspaceUserDto,
@AuthUser() user: User,
@AuthWorkspace() workspace: Workspace,
) {
const ability = this.workspaceAbility.createForUser(user, workspace);
if (
ability.cannot(WorkspaceCaslAction.Manage, WorkspaceCaslSubject.Member)
) {
throw new ForbiddenException();
}
await this.workspaceService.deleteUser(user, dto.userId, workspace.id);
}
@HttpCode(HttpStatus.OK)
@Post('members/change-role')
async updateWorkspaceMemberRole(

View File

@ -27,6 +27,8 @@ import { DomainService } from '../../../integrations/environment/domain.service'
import { jsonArrayFrom } from 'kysely/helpers/postgres';
import { addDays } from 'date-fns';
import { DISALLOWED_HOSTNAMES, WorkspaceStatus } from '../workspace.constants';
import { v4 } from 'uuid';
import { AttachmentType } from 'src/core/attachment/attachment.constants';
import { InjectQueue } from '@nestjs/bullmq';
import { QueueJob, QueueName } from '../../../integrations/queue/constants';
import { Queue } from 'bullmq';
@ -45,6 +47,7 @@ export class WorkspaceService {
private environmentService: EnvironmentService,
private domainService: DomainService,
@InjectKysely() private readonly db: KyselyDB,
@InjectQueue(QueueName.ATTACHMENT_QUEUE) private attachmentQueue: Queue,
@InjectQueue(QueueName.BILLING_QUEUE) private billingQueue: Queue,
) {}
@ -419,4 +422,66 @@ export class WorkspaceService {
}
return { hostname: this.domainService.getUrl(hostname) };
}
async deleteUser(
authUser: User,
userId: string,
workspaceId: string,
): Promise<void> {
const user = await this.userRepo.findById(userId, workspaceId);
if (!user || user.deletedAt) {
throw new BadRequestException('Workspace member not found');
}
const workspaceOwnerCount = await this.userRepo.roleCountByWorkspaceId(
UserRole.OWNER,
workspaceId,
);
if (user.role === UserRole.OWNER && workspaceOwnerCount === 1) {
throw new BadRequestException(
'There must be at least one workspace owner',
);
}
if (authUser.id === userId) {
throw new BadRequestException('You cannot delete yourself');
}
if (authUser.role === UserRole.ADMIN && user.role === UserRole.OWNER) {
throw new BadRequestException('You cannot delete a user with owner role');
}
await executeTx(this.db, async (trx) => {
await this.userRepo.updateUser(
{
name: 'Deleted user',
email: v4() + '@deleted.docmost.com',
avatarUrl: null,
settings: null,
deletedAt: new Date(),
},
userId,
workspaceId,
trx,
);
await trx.deleteFrom('groupUsers').where('userId', '=', userId).execute();
await trx
.deleteFrom('spaceMembers')
.where('userId', '=', userId)
.execute();
await trx
.deleteFrom('authAccounts')
.where('userId', '=', userId)
.execute();
});
try {
await this.attachmentQueue.add(QueueJob.DELETE_USER_AVATARS, user);
} catch (err) {
// empty
}
}
}

View File

@ -139,6 +139,7 @@ export class UserRepo {
.selectFrom('users')
.select(this.baseFields)
.where('workspaceId', '=', workspaceId)
.where('deletedAt', 'is', null)
.orderBy('createdAt', 'asc');
if (pagination.query) {

View File

@ -11,6 +11,8 @@ export enum QueueJob {
DELETE_PAGE_ATTACHMENTS = 'delete-page-attachments',
PAGE_CONTENT_UPDATE = 'page-content-update',
DELETE_USER_AVATARS = 'delete-user-avatars',
PAGE_BACKLINKS = 'page-backlinks',
STRIPE_SEATS_SYNC = 'sync-stripe-seats',