misc: moved the rest of project group methods to IDs

This commit is contained in:
Sheen Capadngan
2024-09-23 17:59:10 +08:00
parent 2352e29902
commit 839f0c7e1c
13 changed files with 175 additions and 192 deletions
+7 -7
View File
@@ -410,21 +410,21 @@ export const PROJECTS = {
secretSnapshotId: "The ID of the snapshot to rollback to." secretSnapshotId: "The ID of the snapshot to rollback to."
}, },
ADD_GROUP_TO_PROJECT: { ADD_GROUP_TO_PROJECT: {
projectSlug: "The slug of the project to add the group to.", projectId: "The ID of the project to add the group to.",
groupSlug: "The slug of the group to add to the project.", groupId: "The ID of the group to add to the project.",
role: "The role for the group to assume in the project." role: "The role for the group to assume in the project."
}, },
UPDATE_GROUP_IN_PROJECT: { UPDATE_GROUP_IN_PROJECT: {
projectSlug: "The slug of the project to update the group in.", projectId: "The ID of the project to update the group in.",
groupSlug: "The slug of the group to update in the project.", groupId: "The ID of the group to update in the project.",
roles: "A list of roles to update the group to." roles: "A list of roles to update the group to."
}, },
REMOVE_GROUP_FROM_PROJECT: { REMOVE_GROUP_FROM_PROJECT: {
projectSlug: "The slug of the project to delete the group from.", projectId: "The ID of the project to delete the group from.",
groupSlug: "The slug of the group to delete from the project." groupId: "The ID of the group to delete from the project."
}, },
LIST_GROUPS_IN_PROJECT: { LIST_GROUPS_IN_PROJECT: {
projectSlug: "The slug of the project to list groups for." projectId: "The ID of the project to list groups for."
}, },
LIST_INTEGRATION: { LIST_INTEGRATION: {
workspaceId: "The ID of the project to list integrations for." workspaceId: "The ID of the project to list integrations for."
@@ -16,7 +16,7 @@ import { ProjectUserMembershipTemporaryMode } from "@app/services/project-member
export const registerGroupProjectRouter = async (server: FastifyZodProvider) => { export const registerGroupProjectRouter = async (server: FastifyZodProvider) => {
server.route({ server.route({
method: "POST", method: "POST",
url: "/:projectSlug/groups/:groupSlug", url: "/:projectId/groups/:groupId",
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]), onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
config: { config: {
rateLimit: writeLimit rateLimit: writeLimit
@@ -29,8 +29,8 @@ export const registerGroupProjectRouter = async (server: FastifyZodProvider) =>
} }
], ],
params: z.object({ params: z.object({
projectSlug: z.string().trim().describe(PROJECTS.ADD_GROUP_TO_PROJECT.projectSlug), projectId: z.string().trim().describe(PROJECTS.ADD_GROUP_TO_PROJECT.projectId),
groupSlug: z.string().trim().describe(PROJECTS.ADD_GROUP_TO_PROJECT.groupSlug) groupId: z.string().trim().describe(PROJECTS.ADD_GROUP_TO_PROJECT.groupId)
}), }),
body: z body: z
.object({ .object({
@@ -74,9 +74,9 @@ export const registerGroupProjectRouter = async (server: FastifyZodProvider) =>
actorId: req.permission.id, actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod, actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId, actorOrgId: req.permission.orgId,
groupSlug: req.params.groupSlug, roles: req.body.roles || [{ role: req.body.role }],
projectSlug: req.params.projectSlug, projectId: req.params.projectId,
roles: req.body.roles || [{ role: req.body.role }] groupId: req.params.groupId
}); });
return { groupMembership }; return { groupMembership };
@@ -85,7 +85,7 @@ export const registerGroupProjectRouter = async (server: FastifyZodProvider) =>
server.route({ server.route({
method: "PATCH", method: "PATCH",
url: "/:projectSlug/groups/:groupSlug", url: "/:projectId/groups/:groupId",
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]), onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
schema: { schema: {
description: "Update group in project", description: "Update group in project",
@@ -95,8 +95,8 @@ export const registerGroupProjectRouter = async (server: FastifyZodProvider) =>
} }
], ],
params: z.object({ params: z.object({
projectSlug: z.string().trim().describe(PROJECTS.UPDATE_GROUP_IN_PROJECT.projectSlug), projectId: z.string().trim().describe(PROJECTS.UPDATE_GROUP_IN_PROJECT.projectId),
groupSlug: z.string().trim().describe(PROJECTS.UPDATE_GROUP_IN_PROJECT.groupSlug) groupId: z.string().trim().describe(PROJECTS.UPDATE_GROUP_IN_PROJECT.groupId)
}), }),
body: z.object({ body: z.object({
roles: z roles: z
@@ -130,17 +130,18 @@ export const registerGroupProjectRouter = async (server: FastifyZodProvider) =>
actorId: req.permission.id, actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod, actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId, actorOrgId: req.permission.orgId,
groupSlug: req.params.groupSlug, projectId: req.params.projectId,
projectSlug: req.params.projectSlug, groupId: req.params.groupId,
roles: req.body.roles roles: req.body.roles
}); });
return { roles }; return { roles };
} }
}); });
server.route({ server.route({
method: "DELETE", method: "DELETE",
url: "/:projectSlug/groups/:groupSlug", url: "/:projectId/groups/:groupId",
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]), onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
config: { config: {
rateLimit: writeLimit rateLimit: writeLimit
@@ -153,8 +154,8 @@ export const registerGroupProjectRouter = async (server: FastifyZodProvider) =>
} }
], ],
params: z.object({ params: z.object({
projectSlug: z.string().trim().describe(PROJECTS.REMOVE_GROUP_FROM_PROJECT.projectSlug), projectId: z.string().trim().describe(PROJECTS.REMOVE_GROUP_FROM_PROJECT.projectId),
groupSlug: z.string().trim().describe(PROJECTS.REMOVE_GROUP_FROM_PROJECT.groupSlug) groupId: z.string().trim().describe(PROJECTS.REMOVE_GROUP_FROM_PROJECT.groupId)
}), }),
response: { response: {
200: z.object({ 200: z.object({
@@ -168,16 +169,17 @@ export const registerGroupProjectRouter = async (server: FastifyZodProvider) =>
actorId: req.permission.id, actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod, actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId, actorOrgId: req.permission.orgId,
groupSlug: req.params.groupSlug, groupId: req.params.groupId,
projectSlug: req.params.projectSlug projectId: req.params.projectId
}); });
return { groupMembership }; return { groupMembership };
} }
}); });
server.route({ server.route({
method: "GET", method: "GET",
url: "/:projectSlug/groups", url: "/:projectId/groups",
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]), onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
config: { config: {
rateLimit: readLimit rateLimit: readLimit
@@ -190,7 +192,7 @@ export const registerGroupProjectRouter = async (server: FastifyZodProvider) =>
} }
], ],
params: z.object({ params: z.object({
projectSlug: z.string().trim().describe(PROJECTS.LIST_GROUPS_IN_PROJECT.projectSlug) projectId: z.string().trim().describe(PROJECTS.LIST_GROUPS_IN_PROJECT.projectId)
}), }),
response: { response: {
200: z.object({ 200: z.object({
@@ -226,9 +228,67 @@ export const registerGroupProjectRouter = async (server: FastifyZodProvider) =>
actorId: req.permission.id, actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod, actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId, actorOrgId: req.permission.orgId,
projectSlug: req.params.projectSlug projectId: req.params.projectId
}); });
return { groupMemberships }; return { groupMemberships };
} }
}); });
server.route({
method: "GET",
url: "/:projectId/groups/:groupId",
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
config: {
rateLimit: readLimit
},
schema: {
description: "Return project group",
security: [
{
bearerAuth: []
}
],
params: z.object({
projectId: z.string().trim(),
groupId: z.string().trim()
}),
response: {
200: z.object({
groupMembership: z.object({
id: z.string(),
groupId: z.string(),
createdAt: z.date(),
updatedAt: z.date(),
roles: z.array(
z.object({
id: z.string(),
role: z.string(),
customRoleId: z.string().optional().nullable(),
customRoleName: z.string().optional().nullable(),
customRoleSlug: z.string().optional().nullable(),
isTemporary: z.boolean(),
temporaryMode: z.string().optional().nullable(),
temporaryRange: z.string().nullable().optional(),
temporaryAccessStartTime: z.date().nullable().optional(),
temporaryAccessEndTime: z.date().nullable().optional()
})
),
group: GroupsSchema.pick({ name: true, id: true, slug: true })
})
})
}
},
handler: async (req) => {
const groupMembership = await server.services.groupProject.getGroupInProject({
actor: req.permission.type,
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
...req.params
});
return { groupMembership };
}
});
}; };
@@ -1,65 +0,0 @@
import { z } from "zod";
import { GroupsSchema } from "@app/db/schemas";
import { readLimit } from "@app/server/config/rateLimiter";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { AuthMode } from "@app/services/auth/auth-type";
export const registerGroupProjectRouter = async (server: FastifyZodProvider) => {
server.route({
method: "GET",
url: "/:projectId/groups/:groupId",
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
config: {
rateLimit: readLimit
},
schema: {
description: "Return project group",
security: [
{
bearerAuth: []
}
],
params: z.object({
projectId: z.string().trim(),
groupId: z.string().trim()
}),
response: {
200: z.object({
groupMembership: z.object({
id: z.string(),
groupId: z.string(),
createdAt: z.date(),
updatedAt: z.date(),
roles: z.array(
z.object({
id: z.string(),
role: z.string(),
customRoleId: z.string().optional().nullable(),
customRoleName: z.string().optional().nullable(),
customRoleSlug: z.string().optional().nullable(),
isTemporary: z.boolean(),
temporaryMode: z.string().optional().nullable(),
temporaryRange: z.string().nullable().optional(),
temporaryAccessStartTime: z.date().nullable().optional(),
temporaryAccessEndTime: z.date().nullable().optional()
})
),
group: GroupsSchema.pick({ name: true, id: true, slug: true })
})
})
}
},
handler: async (req) => {
const groupMembership = await server.services.groupProject.getGroupInProject({
actor: req.permission.type,
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
...req.params
});
return { groupMembership };
}
});
};
+1 -8
View File
@@ -1,5 +1,4 @@
import { registerDashboardRouter } from "./dashboard-router"; import { registerDashboardRouter } from "./dashboard-router";
import { registerGroupProjectRouter } from "./group-project-router";
import { registerLoginRouter } from "./login-router"; import { registerLoginRouter } from "./login-router";
import { registerSecretBlindIndexRouter } from "./secret-blind-index-router"; import { registerSecretBlindIndexRouter } from "./secret-blind-index-router";
import { registerSecretRouter } from "./secret-router"; import { registerSecretRouter } from "./secret-router";
@@ -11,12 +10,6 @@ export const registerV3Routes = async (server: FastifyZodProvider) => {
await server.register(registerLoginRouter, { prefix: "/auth" }); await server.register(registerLoginRouter, { prefix: "/auth" });
await server.register(registerUserRouter, { prefix: "/users" }); await server.register(registerUserRouter, { prefix: "/users" });
await server.register(registerSecretRouter, { prefix: "/secrets" }); await server.register(registerSecretRouter, { prefix: "/secrets" });
await server.register( await server.register(registerSecretBlindIndexRouter, { prefix: "/workspaces" });
async (projectServer) => {
await projectServer.register(registerSecretBlindIndexRouter);
await projectServer.register(registerGroupProjectRouter);
},
{ prefix: "/workspaces" }
);
await server.register(registerDashboardRouter, { prefix: "/dashboard" }); await server.register(registerDashboardRouter, { prefix: "/dashboard" });
}; };
@@ -56,19 +56,17 @@ export const groupProjectServiceFactory = ({
permissionService permissionService
}: TGroupProjectServiceFactoryDep) => { }: TGroupProjectServiceFactoryDep) => {
const addGroupToProject = async ({ const addGroupToProject = async ({
groupSlug,
actor, actor,
actorId, actorId,
actorOrgId, actorOrgId,
actorAuthMethod, actorAuthMethod,
projectSlug, roles,
roles projectId,
groupId
}: TCreateProjectGroupDTO) => { }: TCreateProjectGroupDTO) => {
const project = await projectDAL.findOne({ const project = await projectDAL.findById(projectId);
slug: projectSlug
});
if (!project) throw new BadRequestError({ message: `Failed to find project with slug ${projectSlug}` }); if (!project) throw new BadRequestError({ message: `Failed to find project with ID ${projectId}` });
if (project.version < 2) throw new BadRequestError({ message: `Failed to add group to E2EE project` }); if (project.version < 2) throw new BadRequestError({ message: `Failed to add group to E2EE project` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
@@ -80,13 +78,13 @@ export const groupProjectServiceFactory = ({
); );
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Create, ProjectPermissionSub.Groups); ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Create, ProjectPermissionSub.Groups);
const group = await groupDAL.findOne({ orgId: actorOrgId, slug: groupSlug }); const group = await groupDAL.findOne({ orgId: actorOrgId, id: groupId });
if (!group) throw new BadRequestError({ message: `Failed to find group with slug ${groupSlug}` }); if (!group) throw new BadRequestError({ message: `Failed to find group with ID ${groupId}` });
const existingGroup = await groupProjectDAL.findOne({ groupId: group.id, projectId: project.id }); const existingGroup = await groupProjectDAL.findOne({ groupId: group.id, projectId: project.id });
if (existingGroup) if (existingGroup)
throw new BadRequestError({ throw new BadRequestError({
message: `Group with slug ${groupSlug} already exists in project with id ${project.id}` message: `Group with ID ${groupId} already exists in project with id ${project.id}`
}); });
for await (const { role: requestedRoleChange } of roles) { for await (const { role: requestedRoleChange } of roles) {
@@ -227,19 +225,17 @@ export const groupProjectServiceFactory = ({
}; };
const updateGroupInProject = async ({ const updateGroupInProject = async ({
projectSlug, projectId,
groupSlug, groupId,
roles, roles,
actor, actor,
actorId, actorId,
actorAuthMethod, actorAuthMethod,
actorOrgId actorOrgId
}: TUpdateProjectGroupDTO) => { }: TUpdateProjectGroupDTO) => {
const project = await projectDAL.findOne({ const project = await projectDAL.findById(projectId);
slug: projectSlug
});
if (!project) throw new BadRequestError({ message: `Failed to find project with slug ${projectSlug}` }); if (!project) throw new BadRequestError({ message: `Failed to find project with ID ${projectId}` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@@ -250,11 +246,11 @@ export const groupProjectServiceFactory = ({
); );
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Edit, ProjectPermissionSub.Groups); ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Edit, ProjectPermissionSub.Groups);
const group = await groupDAL.findOne({ orgId: actorOrgId, slug: groupSlug }); const group = await groupDAL.findOne({ orgId: actorOrgId, id: groupId });
if (!group) throw new BadRequestError({ message: `Failed to find group with slug ${groupSlug}` }); if (!group) throw new BadRequestError({ message: `Failed to find group with ID ${groupId}` });
const projectGroup = await groupProjectDAL.findOne({ groupId: group.id, projectId: project.id }); const projectGroup = await groupProjectDAL.findOne({ groupId: group.id, projectId: project.id });
if (!projectGroup) throw new BadRequestError({ message: `Failed to find group with slug ${groupSlug}` }); if (!projectGroup) throw new BadRequestError({ message: `Failed to find group with ID ${groupId}` });
for await (const { role: requestedRoleChange } of roles) { for await (const { role: requestedRoleChange } of roles) {
const { permission: rolePermission } = await permissionService.getProjectPermissionByRole( const { permission: rolePermission } = await permissionService.getProjectPermissionByRole(
@@ -326,24 +322,22 @@ export const groupProjectServiceFactory = ({
}; };
const removeGroupFromProject = async ({ const removeGroupFromProject = async ({
projectSlug, projectId,
groupSlug, groupId,
actorId, actorId,
actor, actor,
actorOrgId, actorOrgId,
actorAuthMethod actorAuthMethod
}: TDeleteProjectGroupDTO) => { }: TDeleteProjectGroupDTO) => {
const project = await projectDAL.findOne({ const project = await projectDAL.findById(projectId);
slug: projectSlug
});
if (!project) throw new BadRequestError({ message: `Failed to find project with slug ${projectSlug}` }); if (!project) throw new BadRequestError({ message: `Failed to find project with ID ${projectId}` });
const group = await groupDAL.findOne({ orgId: actorOrgId, slug: groupSlug }); const group = await groupDAL.findOne({ orgId: actorOrgId, id: groupId });
if (!group) throw new BadRequestError({ message: `Failed to find group with slug ${groupSlug}` }); if (!group) throw new BadRequestError({ message: `Failed to find group with ID ${groupId}` });
const groupProjectMembership = await groupProjectDAL.findOne({ groupId: group.id, projectId: project.id }); const groupProjectMembership = await groupProjectDAL.findOne({ groupId: group.id, projectId: project.id });
if (!groupProjectMembership) throw new BadRequestError({ message: `Failed to find group with slug ${groupSlug}` }); if (!groupProjectMembership) throw new BadRequestError({ message: `Failed to find group with ID ${groupId}` });
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@@ -377,17 +371,17 @@ export const groupProjectServiceFactory = ({
}; };
const listGroupsInProject = async ({ const listGroupsInProject = async ({
projectSlug, projectId,
actor, actor,
actorId, actorId,
actorAuthMethod, actorAuthMethod,
actorOrgId actorOrgId
}: TListProjectGroupDTO) => { }: TListProjectGroupDTO) => {
const project = await projectDAL.findOne({ const project = await projectDAL.findById(projectId);
slug: projectSlug
});
if (!project) throw new BadRequestError({ message: `Failed to find project with slug ${projectSlug}` }); if (!project) {
throw new BadRequestError({ message: `Failed to find project with ID ${projectId}` });
}
const { permission } = await permissionService.getProjectPermission( const { permission } = await permissionService.getProjectPermission(
actor, actor,
@@ -1,9 +1,9 @@
import { TProjectPermission, TProjectSlugPermission } from "@app/lib/types"; import { TProjectPermission } from "@app/lib/types";
import { ProjectUserMembershipTemporaryMode } from "../project-membership/project-membership-types"; import { ProjectUserMembershipTemporaryMode } from "../project-membership/project-membership-types";
export type TCreateProjectGroupDTO = { export type TCreateProjectGroupDTO = {
groupSlug: string; groupId: string;
roles: ( roles: (
| { | {
role: string; role: string;
@@ -17,7 +17,7 @@ export type TCreateProjectGroupDTO = {
temporaryAccessStartTime: string; temporaryAccessStartTime: string;
} }
)[]; )[];
} & TProjectSlugPermission; } & TProjectPermission;
export type TUpdateProjectGroupDTO = { export type TUpdateProjectGroupDTO = {
roles: ( roles: (
@@ -33,13 +33,13 @@ export type TUpdateProjectGroupDTO = {
temporaryAccessStartTime: string; temporaryAccessStartTime: string;
} }
)[]; )[];
groupSlug: string; groupId: string;
} & TProjectSlugPermission; } & TProjectPermission;
export type TDeleteProjectGroupDTO = { export type TDeleteProjectGroupDTO = {
groupSlug: string; groupId: string;
} & TProjectSlugPermission; } & TProjectPermission;
export type TListProjectGroupDTO = TProjectSlugPermission; export type TListProjectGroupDTO = TProjectPermission;
export type TGetGroupInProjectDTO = TProjectPermission & { groupId: string }; export type TGetGroupInProjectDTO = TProjectPermission & { groupId: string };
+19 -18
View File
@@ -10,23 +10,24 @@ export const useAddGroupToWorkspace = () => {
const queryClient = useQueryClient(); const queryClient = useQueryClient();
return useMutation({ return useMutation({
mutationFn: async ({ mutationFn: async ({
groupSlug, groupId,
projectSlug, projectId,
role role
}: { }: {
groupSlug: string; groupId: string;
projectSlug: string; projectId: string;
role?: string; role?: string;
}) => { }) => {
const { const {
data: { groupMembership } data: { groupMembership }
} = await apiRequest.post(`/api/v2/workspace/${projectSlug}/groups/${groupSlug}`, { } = await apiRequest.post(`/api/v2/workspace/${projectId}/groups/${groupId}`, {
role role
}); });
return groupMembership; return groupMembership;
}, },
onSuccess: (_, { projectSlug }) => { onSuccess: (_, { projectId }) => {
queryClient.invalidateQueries(workspaceKeys.getWorkspaceGroupMemberships(projectSlug)); queryClient.invalidateQueries(workspaceKeys.getWorkspaceGroupMemberships(projectId));
} }
}); });
}; };
@@ -34,17 +35,17 @@ export const useAddGroupToWorkspace = () => {
export const useUpdateGroupWorkspaceRole = () => { export const useUpdateGroupWorkspaceRole = () => {
const queryClient = useQueryClient(); const queryClient = useQueryClient();
return useMutation({ return useMutation({
mutationFn: async ({ groupSlug, projectSlug, roles }: TUpdateWorkspaceGroupRoleDTO) => { mutationFn: async ({ groupId, projectId, roles }: TUpdateWorkspaceGroupRoleDTO) => {
const { const {
data: { groupMembership } data: { groupMembership }
} = await apiRequest.patch(`/api/v2/workspace/${projectSlug}/groups/${groupSlug}`, { } = await apiRequest.patch(`/api/v2/workspace/${projectId}/groups/${groupId}`, {
roles roles
}); });
return groupMembership; return groupMembership;
}, },
onSuccess: (_, { projectSlug }) => { onSuccess: (_, { projectId }) => {
queryClient.invalidateQueries(workspaceKeys.getWorkspaceGroupMemberships(projectSlug)); queryClient.invalidateQueries(workspaceKeys.getWorkspaceGroupMemberships(projectId));
} }
}); });
}; };
@@ -53,20 +54,20 @@ export const useDeleteGroupFromWorkspace = () => {
const queryClient = useQueryClient(); const queryClient = useQueryClient();
return useMutation({ return useMutation({
mutationFn: async ({ mutationFn: async ({
groupSlug, groupId,
projectSlug projectId
}: { }: {
groupSlug: string; groupId: string;
projectSlug: string; projectId: string;
username?: string; username?: string;
}) => { }) => {
const { const {
data: { groupMembership } data: { groupMembership }
} = await apiRequest.delete(`/api/v2/workspace/${projectSlug}/groups/${groupSlug}`); } = await apiRequest.delete(`/api/v2/workspace/${projectId}/groups/${groupId}`);
return groupMembership; return groupMembership;
}, },
onSuccess: (_, { projectSlug, username }) => { onSuccess: (_, { projectId, username }) => {
queryClient.invalidateQueries(workspaceKeys.getWorkspaceGroupMemberships(projectSlug)); queryClient.invalidateQueries(workspaceKeys.getWorkspaceGroupMemberships(projectId));
if (username) { if (username) {
queryClient.invalidateQueries(userKeys.listUserGroupMemberships(username)); queryClient.invalidateQueries(userKeys.listUserGroupMemberships(username));
+3 -3
View File
@@ -535,14 +535,14 @@ export const useGetWorkspaceIdentityMemberships = (
}); });
}; };
export const useListWorkspaceGroups = (projectSlug: string) => { export const useListWorkspaceGroups = (projectId: string) => {
return useQuery({ return useQuery({
queryKey: workspaceKeys.getWorkspaceGroupMemberships(projectSlug), queryKey: workspaceKeys.getWorkspaceGroupMemberships(projectId),
queryFn: async () => { queryFn: async () => {
const { const {
data: { groupMemberships } data: { groupMemberships }
} = await apiRequest.get<{ groupMemberships: TGroupMembership[] }>( } = await apiRequest.get<{ groupMemberships: TGroupMembership[] }>(
`/api/v2/workspace/${projectSlug}/groups` `/api/v2/workspace/${projectId}/groups`
); );
return groupMemberships; return groupMemberships;
}, },
+2 -2
View File
@@ -127,8 +127,8 @@ export type TUpdateWorkspaceIdentityRoleDTO = {
}; };
export type TUpdateWorkspaceGroupRoleDTO = { export type TUpdateWorkspaceGroupRoleDTO = {
groupSlug: string; groupId: string;
projectSlug: string; projectId: string;
roles: ( roles: (
| { | {
role: string; role: string;
@@ -16,7 +16,7 @@ import {
import { UsePopUpState } from "@app/hooks/usePopUp"; import { UsePopUpState } from "@app/hooks/usePopUp";
const schema = z.object({ const schema = z.object({
slug: z.string(), id: z.string(),
role: z.string() role: z.string()
}); });
@@ -35,7 +35,7 @@ export const GroupModal = ({ popUp, handlePopUpToggle }: Props) => {
const projectSlug = currentWorkspace?.slug || ""; const projectSlug = currentWorkspace?.slug || "";
const { data: groups } = useGetOrganizationGroups(orgId); const { data: groups } = useGetOrganizationGroups(orgId);
const { data: groupMemberships } = useListWorkspaceGroups(currentWorkspace?.slug || ""); const { data: groupMemberships } = useListWorkspaceGroups(currentWorkspace?.id || "");
const { data: roles } = useGetProjectRoles(projectSlug); const { data: roles } = useGetProjectRoles(projectSlug);
@@ -60,11 +60,11 @@ export const GroupModal = ({ popUp, handlePopUpToggle }: Props) => {
resolver: zodResolver(schema) resolver: zodResolver(schema)
}); });
const onFormSubmit = async ({ slug, role }: FormData) => { const onFormSubmit = async ({ id, role }: FormData) => {
try { try {
await addGroupToWorkspaceMutateAsync({ await addGroupToWorkspaceMutateAsync({
projectSlug: currentWorkspace?.slug || "", projectId: currentWorkspace?.id || "",
groupSlug: slug, groupId: id,
role: role || undefined role: role || undefined
}); });
@@ -96,7 +96,7 @@ export const GroupModal = ({ popUp, handlePopUpToggle }: Props) => {
<form onSubmit={handleSubmit(onFormSubmit)}> <form onSubmit={handleSubmit(onFormSubmit)}>
<Controller <Controller
control={control} control={control}
name="slug" name="id"
defaultValue={filteredGroupMembershipOrgs?.[0]?.id} defaultValue={filteredGroupMembershipOrgs?.[0]?.id}
render={({ field: { onChange, ...field }, fieldState: { error } }) => ( render={({ field: { onChange, ...field }, fieldState: { error } }) => (
<FormControl label="Group" errorText={error?.message} isError={Boolean(error)}> <FormControl label="Group" errorText={error?.message} isError={Boolean(error)}>
@@ -107,8 +107,8 @@ export const GroupModal = ({ popUp, handlePopUpToggle }: Props) => {
className="w-full border border-mineshaft-600" className="w-full border border-mineshaft-600"
placeholder="Select group..." placeholder="Select group..."
> >
{filteredGroupMembershipOrgs.map(({ name, slug, id }) => ( {filteredGroupMembershipOrgs.map(({ name, id }) => (
<SelectItem value={slug} key={`org-group-${id}`} > <SelectItem value={id} key={`org-group-${id}`}>
{name} {name}
</SelectItem> </SelectItem>
))} ))}
@@ -143,7 +143,7 @@ export const GroupModal = ({ popUp, handlePopUpToggle }: Props) => {
</FormControl> </FormControl>
)} )}
/> />
<div className="flex items-center mt-6"> <div className="mt-6 flex items-center">
<Button <Button
className="mr-4" className="mr-4"
size="sm" size="sm"
@@ -195,13 +195,13 @@ type TForm = z.infer<typeof formSchema>;
export type TMemberRolesProp = { export type TMemberRolesProp = {
disableEdit?: boolean; disableEdit?: boolean;
groupSlug: string; groupId: string;
roles: TGroupMembership["roles"]; roles: TGroupMembership["roles"];
}; };
const MAX_ROLES_TO_BE_SHOWN_IN_TABLE = 2; const MAX_ROLES_TO_BE_SHOWN_IN_TABLE = 2;
export const GroupRoles = ({ roles = [], disableEdit = false, groupSlug }: TMemberRolesProp) => { export const GroupRoles = ({ roles = [], disableEdit = false, groupId }: TMemberRolesProp) => {
const { currentWorkspace } = useWorkspace(); const { currentWorkspace } = useWorkspace();
const { popUp, handlePopUpToggle } = usePopUp(["editRole"] as const); const { popUp, handlePopUpToggle } = usePopUp(["editRole"] as const);
const [searchRoles, setSearchRoles] = useState(""); const [searchRoles, setSearchRoles] = useState("");
@@ -248,8 +248,8 @@ export const GroupRoles = ({ roles = [], disableEdit = false, groupSlug }: TMemb
try { try {
await updateGroupWorkspaceRole.mutateAsync({ await updateGroupWorkspaceRole.mutateAsync({
projectSlug: currentWorkspace?.slug || "", projectId: currentWorkspace?.id || "",
groupSlug, groupId,
roles: selectedRoles roles: selectedRoles
}); });
createNotification({ text: "Successfully updated group role", type: "success" }); createNotification({ text: "Successfully updated group role", type: "success" });
@@ -39,11 +39,11 @@ export const GroupsSection = () => {
} }
}; };
const onRemoveGroupSubmit = async (groupSlug: string) => { const onRemoveGroupSubmit = async (groupId: string) => {
try { try {
await deleteMutateAsync({ await deleteMutateAsync({
groupSlug, groupId,
projectSlug: currentWorkspace?.slug || "" projectId: currentWorkspace?.id || ""
}); });
createNotification({ createNotification({
@@ -92,7 +92,7 @@ export const GroupsSection = () => {
onChange={(isOpen) => handlePopUpToggle("deleteGroup", isOpen)} onChange={(isOpen) => handlePopUpToggle("deleteGroup", isOpen)}
deleteKey="confirm" deleteKey="confirm"
onDeleteApproved={() => onDeleteApproved={() =>
onRemoveGroupSubmit((popUp?.deleteGroup?.data as { slug: string })?.slug) onRemoveGroupSubmit((popUp?.deleteGroup?.data as { id: string })?.id)
} }
/> />
<UpgradePlanModal <UpgradePlanModal
@@ -26,7 +26,7 @@ type Props = {
handlePopUpOpen: ( handlePopUpOpen: (
popUpName: keyof UsePopUpState<["deleteGroup", "group"]>, popUpName: keyof UsePopUpState<["deleteGroup", "group"]>,
data?: { data?: {
slug?: string; id?: string;
name?: string; name?: string;
} }
) => void; ) => void;
@@ -34,7 +34,7 @@ type Props = {
export const GroupTable = ({ handlePopUpOpen }: Props) => { export const GroupTable = ({ handlePopUpOpen }: Props) => {
const { currentWorkspace } = useWorkspace(); const { currentWorkspace } = useWorkspace();
const { data, isLoading } = useListWorkspaceGroups(currentWorkspace?.slug || ""); const { data, isLoading } = useListWorkspaceGroups(currentWorkspace?.id || "");
return ( return (
<TableContainer> <TableContainer>
<Table> <Table>
@@ -51,7 +51,7 @@ export const GroupTable = ({ handlePopUpOpen }: Props) => {
{!isLoading && {!isLoading &&
data && data &&
data.length > 0 && data.length > 0 &&
data.map(({ group: { id, name, slug }, roles, createdAt }) => { data.map(({ group: { id, name }, roles, createdAt }) => {
return ( return (
<Tr className="group h-10" key={`st-v3-${id}`}> <Tr className="group h-10" key={`st-v3-${id}`}>
<Td>{name}</Td> <Td>{name}</Td>
@@ -61,7 +61,7 @@ export const GroupTable = ({ handlePopUpOpen }: Props) => {
a={ProjectPermissionSub.Groups} a={ProjectPermissionSub.Groups}
> >
{(isAllowed) => ( {(isAllowed) => (
<GroupRoles roles={roles} disableEdit={!isAllowed} groupSlug={slug} /> <GroupRoles roles={roles} disableEdit={!isAllowed} groupId={id} />
)} )}
</ProjectPermissionCan> </ProjectPermissionCan>
</Td> </Td>
@@ -77,7 +77,7 @@ export const GroupTable = ({ handlePopUpOpen }: Props) => {
<IconButton <IconButton
onClick={() => { onClick={() => {
handlePopUpOpen("deleteGroup", { handlePopUpOpen("deleteGroup", {
slug, id,
name name
}); });
}} }}