Merge pull request #1354 from Infisical/daniel/readd-workspaces-endpoint

(Feat): Re-add missing V2 workspaces endpoint
This commit is contained in:
Akhil Mohan
2024-01-30 21:26:33 +05:30
committed by GitHub
5 changed files with 140 additions and 2 deletions
+1
View File
@@ -236,6 +236,7 @@ export const registerRoutes = async (
orgDAL, orgDAL,
incidentContactDAL, incidentContactDAL,
tokenService, tokenService,
projectDAL,
smtpService, smtpService,
userDAL, userDAL,
orgBotDAL orgBotDAL
@@ -46,6 +46,42 @@ export const registerOrgRouter = async (server: FastifyZodProvider) => {
} }
}); });
server.route({
method: "GET",
url: "/:organizationId/workspaces",
schema: {
params: z.object({
organizationId: z.string().trim()
}),
response: {
200: z.object({
workspaces: z
.object({
name: z.string(),
organization: z.string(),
environments: z
.object({
name: z.string(),
slug: z.string()
})
.array()
})
.array()
})
}
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.API_KEY, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
const workspaces = await server.services.org.findAllWorkspaces({
actor: req.permission.type,
actorId: req.permission.id,
orgId: req.params.organizationId
});
return { workspaces };
}
});
server.route({ server.route({
method: "PATCH", method: "PATCH",
url: "/:organizationId/memberships/:membershipId", url: "/:organizationId/memberships/:membershipId",
+38 -1
View File
@@ -3,6 +3,7 @@ import slugify from "@sindresorhus/slugify";
import jwt from "jsonwebtoken"; import jwt from "jsonwebtoken";
import { OrgMembershipRole, OrgMembershipStatus } from "@app/db/schemas"; import { OrgMembershipRole, OrgMembershipStatus } from "@app/db/schemas";
import { TProjects } from "@app/db/schemas/projects";
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service"; import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
import { import {
OrgPermissionActions, OrgPermissionActions,
@@ -17,9 +18,10 @@ import { BadRequestError, UnauthorizedError } from "@app/lib/errors";
import { alphaNumericNanoId } from "@app/lib/nanoid"; import { alphaNumericNanoId } from "@app/lib/nanoid";
import { isDisposableEmail } from "@app/lib/validator"; import { isDisposableEmail } from "@app/lib/validator";
import { AuthMethod, AuthTokenType } from "../auth/auth-type"; import { ActorType, AuthMethod, AuthTokenType } from "../auth/auth-type";
import { TAuthTokenServiceFactory } from "../auth-token/auth-token-service"; import { TAuthTokenServiceFactory } from "../auth-token/auth-token-service";
import { TokenType } from "../auth-token/auth-token-types"; import { TokenType } from "../auth-token/auth-token-types";
import { TProjectDALFactory } from "../project/project-dal";
import { SmtpTemplates, TSmtpService } from "../smtp/smtp-service"; import { SmtpTemplates, TSmtpService } from "../smtp/smtp-service";
import { TUserDALFactory } from "../user/user-dal"; import { TUserDALFactory } from "../user/user-dal";
import { TIncidentContactsDALFactory } from "./incident-contacts-dal"; import { TIncidentContactsDALFactory } from "./incident-contacts-dal";
@@ -28,6 +30,7 @@ import { TOrgDALFactory } from "./org-dal";
import { TOrgRoleDALFactory } from "./org-role-dal"; import { TOrgRoleDALFactory } from "./org-role-dal";
import { import {
TDeleteOrgMembershipDTO, TDeleteOrgMembershipDTO,
TFindAllWorkspacesDTO,
TInviteUserToOrgDTO, TInviteUserToOrgDTO,
TUpdateOrgMembershipDTO, TUpdateOrgMembershipDTO,
TVerifyUserToOrgDTO TVerifyUserToOrgDTO
@@ -38,6 +41,7 @@ type TOrgServiceFactoryDep = {
orgBotDAL: TOrgBotDALFactory; orgBotDAL: TOrgBotDALFactory;
orgRoleDAL: TOrgRoleDALFactory; orgRoleDAL: TOrgRoleDALFactory;
userDAL: TUserDALFactory; userDAL: TUserDALFactory;
projectDAL: TProjectDALFactory;
incidentContactDAL: TIncidentContactsDALFactory; incidentContactDAL: TIncidentContactsDALFactory;
samlConfigDAL: Pick<TSamlConfigDALFactory, "findOne">; samlConfigDAL: Pick<TSamlConfigDALFactory, "findOne">;
smtpService: TSmtpService; smtpService: TSmtpService;
@@ -58,6 +62,7 @@ export const orgServiceFactory = ({
incidentContactDAL, incidentContactDAL,
permissionService, permissionService,
smtpService, smtpService,
projectDAL,
tokenService, tokenService,
orgBotDAL, orgBotDAL,
licenseService, licenseService,
@@ -93,6 +98,37 @@ export const orgServiceFactory = ({
const members = await orgDAL.findAllOrgMembers(orgId); const members = await orgDAL.findAllOrgMembers(orgId);
return members; return members;
}; };
const findAllWorkspaces = async ({ actor, actorId, orgId }: TFindAllWorkspacesDTO) => {
const { permission } = await permissionService.getOrgPermission(actor, actorId, orgId);
ForbiddenError.from(permission).throwUnlessCan(
OrgPermissionActions.Read,
OrgPermissionSubjects.Workspace
);
const organizationWorkspaceIds = new Set(
(await projectDAL.find({ orgId })).map((workspace) => workspace.id)
);
let workspaces: (TProjects & { organization: string } & {
environments: {
id: string;
slug: string;
name: string;
}[];
})[];
if (actor === ActorType.USER) {
workspaces = await projectDAL.findAllProjects(actorId);
} else if (actor === ActorType.IDENTITY) {
workspaces = await projectDAL.findAllProjectsByIdentity(actorId);
} else {
throw new BadRequestError({ message: "Invalid actor type" });
}
return workspaces.filter((workspace) => organizationWorkspaceIds.has(workspace.id));
};
/* /*
* Update organization settings * Update organization settings
* */ * */
@@ -459,6 +495,7 @@ export const orgServiceFactory = ({
createOrganization, createOrganization,
deleteOrganizationById, deleteOrganizationById,
deleteOrgMembership, deleteOrgMembership,
findAllWorkspaces,
updateOrgMembership, updateOrgMembership,
// incident contacts // incident contacts
findIncidentContacts, findIncidentContacts,
+8
View File
@@ -1,3 +1,5 @@
import { ActorType } from "../auth/auth-type";
export type TUpdateOrgMembershipDTO = { export type TUpdateOrgMembershipDTO = {
userId: string; userId: string;
orgId: string; orgId: string;
@@ -22,3 +24,9 @@ export type TVerifyUserToOrgDTO = {
orgId: string; orgId: string;
code: string; code: string;
}; };
export type TFindAllWorkspacesDTO = {
actor: ActorType;
actorId: string;
orgId: string;
};
+57 -1
View File
@@ -30,7 +30,7 @@ export const projectDALFactory = (db: TDbClient) => {
db.ref("name").withSchema(TableName.Environment).as("envName") db.ref("name").withSchema(TableName.Environment).as("envName")
) )
.orderBy("createdAt", "asc", "last"); .orderBy("createdAt", "asc", "last");
return sqlNestRelationships({ const nestedWorkspaces = sqlNestRelationships({
data: workspaces, data: workspaces,
key: "id", key: "id",
parentMapper: ({ _id, ...el }) => ({ _id, ...ProjectsSchema.parse(el) }), parentMapper: ({ _id, ...el }) => ({ _id, ...ProjectsSchema.parse(el) }),
@@ -46,11 +46,66 @@ export const projectDALFactory = (db: TDbClient) => {
} }
] ]
}); });
return nestedWorkspaces.map((workspace) => ({
...workspace,
organization: workspace.id
}));
} catch (error) { } catch (error) {
throw new DatabaseError({ error, name: "Find all projects" }); throw new DatabaseError({ error, name: "Find all projects" });
} }
}; };
const findAllProjectsByIdentity = async (identityId: string) => {
try {
const workspaces = await db(TableName.IdentityProjectMembership)
.where({ identityId })
.join(
TableName.Project,
`${TableName.IdentityProjectMembership}.projectId`,
`${TableName.Project}.id`
)
.leftJoin(
TableName.Environment,
`${TableName.Environment}.projectId`,
`${TableName.Project}.id`
)
.select(
selectAllTableCols(TableName.Project),
db.ref("id").withSchema(TableName.Project).as("_id"),
db.ref("id").withSchema(TableName.Environment).as("envId"),
db.ref("slug").withSchema(TableName.Environment).as("envSlug"),
db.ref("name").withSchema(TableName.Environment).as("envName")
)
.orderBy("createdAt", "asc", "last");
const nestedWorkspaces = sqlNestRelationships({
data: workspaces,
key: "id",
parentMapper: ({ _id, ...el }) => ({ _id, ...ProjectsSchema.parse(el) }),
childrenMapper: [
{
key: "envId",
label: "environments" as const,
mapper: ({ envId: id, envSlug: slug, envName: name }) => ({
id,
slug,
name
})
}
]
});
// We need to add the organization field, as it's required for one of our API endpoint responses.
return nestedWorkspaces.map((workspace) => ({
...workspace,
organization: workspace.id
}));
} catch (error) {
throw new DatabaseError({ error, name: "Find all projects by identity" });
}
};
const findProjectById = async (id: string) => { const findProjectById = async (id: string) => {
try { try {
const workspaces = await db(TableName.ProjectMembership) const workspaces = await db(TableName.ProjectMembership)
@@ -96,6 +151,7 @@ export const projectDALFactory = (db: TDbClient) => {
return { return {
...projectOrm, ...projectOrm,
findAllProjects, findAllProjects,
findAllProjectsByIdentity,
findProjectById findProjectById
}; };
}; };