-
Notifications
You must be signed in to change notification settings - Fork 254
Expand file tree
/
Copy pathroute.ts
More file actions
93 lines (79 loc) · 3 KB
/
route.ts
File metadata and controls
93 lines (79 loc) · 3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
'use server';
import { withAuthV2, withMinimumOrgRole } from "@/withAuthV2";
import { OrgRole } from "@sourcebot/db";
import { isServiceError } from "@/lib/utils";
import { serviceErrorResponse, missingQueryParam, notFound } from "@/lib/serviceError";
import { createLogger } from "@sourcebot/logger";
import { NextRequest } from "next/server";
import { StatusCodes } from "http-status-codes";
import { ErrorCode } from "@/lib/errorCodes";
import { getAuditService } from "@/ee/features/audit/factory";
const logger = createLogger('ee-user-api');
const auditService = getAuditService();
export const DELETE = async (request: NextRequest) => {
const url = new URL(request.url);
const userId = url.searchParams.get('userId');
if (!userId) {
return serviceErrorResponse(missingQueryParam('userId'));
}
const result = await withAuthV2(async ({ org, role, user: currentUser, prisma }) => {
return withMinimumOrgRole(role, OrgRole.OWNER, async () => {
try {
if (currentUser.id === userId) {
return {
statusCode: StatusCodes.BAD_REQUEST,
errorCode: ErrorCode.INVALID_REQUEST_BODY,
message: 'Cannot delete your own user account',
};
}
const targetUser = await prisma.user.findUnique({
where: {
id: userId,
},
select: {
id: true,
email: true,
name: true,
},
});
if (!targetUser) {
return notFound('User not found');
}
await auditService.createAudit({
action: "user.delete",
actor: {
id: currentUser.id,
type: "user"
},
target: {
id: userId,
type: "user"
},
orgId: org.id,
});
// Delete the user (cascade will handle all related records)
await prisma.user.delete({
where: {
id: userId,
},
});
logger.info('User deleted successfully', {
deletedUserId: userId,
deletedByUserId: currentUser.id,
orgId: org.id
});
return {
success: true,
message: 'User deleted successfully'
};
} catch (error) {
logger.error('Error deleting user', { error, userId });
throw error;
}
});
});
if (isServiceError(result)) {
return serviceErrorResponse(result);
}
return Response.json(result, { status: StatusCodes.OK });
};