mirror of
https://github.com/awatertrevi/infisical.git
synced 2026-09-22 13:39:35 +00:00
Added pki collection table, pki alert modal
This commit is contained in:
2
backend/src/@types/fastify.d.ts
vendored
2
backend/src/@types/fastify.d.ts
vendored
@@ -52,6 +52,7 @@ import { TIntegrationAuthServiceFactory } from "@app/services/integration-auth/i
|
||||
import { TOrgRoleServiceFactory } from "@app/services/org/org-role-service";
|
||||
import { TOrgServiceFactory } from "@app/services/org/org-service";
|
||||
import { TOrgAdminServiceFactory } from "@app/services/org-admin/org-admin-service";
|
||||
import { TPkiCollectionServiceFactory } from "@app/services/pki-collection/pki-collection-service";
|
||||
import { TProjectServiceFactory } from "@app/services/project/project-service";
|
||||
import { TProjectBotServiceFactory } from "@app/services/project-bot/project-bot-service";
|
||||
import { TProjectEnvServiceFactory } from "@app/services/project-env/project-env-service";
|
||||
@@ -155,6 +156,7 @@ declare module "fastify" {
|
||||
certificate: TCertificateServiceFactory;
|
||||
certificateAuthority: TCertificateAuthorityServiceFactory;
|
||||
certificateAuthorityCrl: TCertificateAuthorityCrlServiceFactory;
|
||||
pkiCollection: TPkiCollectionServiceFactory;
|
||||
secretScanning: TSecretScanningServiceFactory;
|
||||
license: TLicenseServiceFactory;
|
||||
trustedIp: TTrustedIpServiceFactory;
|
||||
|
||||
8
backend/src/@types/knex.d.ts
vendored
8
backend/src/@types/knex.d.ts
vendored
@@ -164,6 +164,9 @@ import {
|
||||
TOrgRoles,
|
||||
TOrgRolesInsert,
|
||||
TOrgRolesUpdate,
|
||||
TPkiCollections,
|
||||
TPkiCollectionsInsert,
|
||||
TPkiCollectionsUpdate,
|
||||
TProjectBots,
|
||||
TProjectBotsInsert,
|
||||
TProjectBotsUpdate,
|
||||
@@ -368,6 +371,11 @@ declare module "knex/types/tables" {
|
||||
TCertificateSecretsInsert,
|
||||
TCertificateSecretsUpdate
|
||||
>;
|
||||
[TableName.PkiCollection]: KnexOriginal.CompositeTableType<
|
||||
TPkiCollections,
|
||||
TPkiCollectionsInsert,
|
||||
TPkiCollectionsUpdate
|
||||
>;
|
||||
[TableName.UserGroupMembership]: KnexOriginal.CompositeTableType<
|
||||
TUserGroupMembership,
|
||||
TUserGroupMembershipInsert,
|
||||
|
||||
@@ -22,7 +22,7 @@ export async function up(knex: Knex): Promise<void> {
|
||||
if (!hasVersionColumn) {
|
||||
await knex.schema.alterTable(TableName.CertificateAuthorityCert, (t) => {
|
||||
t.integer("version").nullable();
|
||||
t.dropUnique(["caId"]);
|
||||
// t.dropUnique(["caId"]);
|
||||
});
|
||||
|
||||
await knex(TableName.CertificateAuthorityCert).update({ version: 1 }).whereNull("version");
|
||||
@@ -54,11 +54,11 @@ export async function up(knex: Knex): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
if (await knex.schema.hasTable(TableName.CertificateAuthoritySecret)) {
|
||||
await knex.schema.alterTable(TableName.CertificateAuthoritySecret, (t) => {
|
||||
t.dropUnique(["caId"]);
|
||||
});
|
||||
}
|
||||
// if (await knex.schema.hasTable(TableName.CertificateAuthoritySecret)) {
|
||||
// await knex.schema.alterTable(TableName.CertificateAuthoritySecret, (t) => {
|
||||
// t.dropUnique(["caId"]);
|
||||
// });
|
||||
// }
|
||||
}
|
||||
|
||||
export async function down(knex: Knex): Promise<void> {
|
||||
|
||||
@@ -4,23 +4,39 @@ import { TableName } from "../schemas";
|
||||
import { createOnUpdateTrigger, dropOnUpdateTrigger } from "../utils";
|
||||
|
||||
export async function up(knex: Knex): Promise<void> {
|
||||
if (!(await knex.schema.hasTable(TableName.PkiCollection))) {
|
||||
await knex.schema.createTable(TableName.PkiCollection, (t) => {
|
||||
t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
|
||||
t.timestamps(true, true, true);
|
||||
t.string("projectId").notNullable();
|
||||
t.foreign("projectId").references("id").inTable(TableName.Project).onDelete("CASCADE");
|
||||
t.string("name").notNullable();
|
||||
});
|
||||
}
|
||||
|
||||
if (!(await knex.schema.hasTable(TableName.Alert))) {
|
||||
// TODO: rename to pki alert
|
||||
await knex.schema.createTable(TableName.Alert, (t) => {
|
||||
t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
|
||||
t.timestamps(true, true, true);
|
||||
t.string("projectId").notNullable();
|
||||
t.foreign("projectId").references("id").inTable(TableName.Project).onDelete("CASCADE");
|
||||
t.uuid("pkiCollectionId").notNullable();
|
||||
t.foreign("pkiCollectionId").references("id").inTable(TableName.PkiCollection).onDelete("CASCADE");
|
||||
t.string("name").notNullable();
|
||||
t.integer("alertBeforeDays").notNullable();
|
||||
t.string("recipientEmails").notNullable();
|
||||
});
|
||||
}
|
||||
|
||||
await createOnUpdateTrigger(knex, TableName.PkiCollection);
|
||||
await createOnUpdateTrigger(knex, TableName.Alert);
|
||||
}
|
||||
|
||||
export async function down(knex: Knex): Promise<void> {
|
||||
// certificates
|
||||
await knex.schema.dropTableIfExists(TableName.PkiCollection);
|
||||
await dropOnUpdateTrigger(knex, TableName.PkiCollection);
|
||||
|
||||
await knex.schema.dropTableIfExists(TableName.Alert);
|
||||
await dropOnUpdateTrigger(knex, TableName.Alert);
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ export const AlertsSchema = z.object({
|
||||
createdAt: z.date(),
|
||||
updatedAt: z.date(),
|
||||
projectId: z.string(),
|
||||
pkiCollectionId: z.string().uuid(),
|
||||
name: z.string(),
|
||||
alertBeforeDays: z.number(),
|
||||
recipientEmails: z.string()
|
||||
|
||||
@@ -53,6 +53,7 @@ export * from "./org-bots";
|
||||
export * from "./org-memberships";
|
||||
export * from "./org-roles";
|
||||
export * from "./organizations";
|
||||
export * from "./pki-collections";
|
||||
export * from "./project-bots";
|
||||
export * from "./project-environments";
|
||||
export * from "./project-keys";
|
||||
|
||||
@@ -9,7 +9,8 @@ export enum TableName {
|
||||
Certificate = "certificates",
|
||||
CertificateBody = "certificate_bodies",
|
||||
CertificateSecret = "certificate_secrets",
|
||||
Alert = "alerts",
|
||||
Alert = "alerts", // TODO: rename
|
||||
PkiCollection = "pki_collections",
|
||||
Groups = "groups",
|
||||
GroupProjectMembership = "group_project_memberships",
|
||||
GroupProjectMembershipRole = "group_project_membership_roles",
|
||||
|
||||
20
backend/src/db/schemas/pki-collections.ts
Normal file
20
backend/src/db/schemas/pki-collections.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
// Code generated by automation script, DO NOT EDIT.
|
||||
// Automated by pulling database and generating zod schema
|
||||
// To update. Just run npm run generate:schema
|
||||
// Written by akhilmhdh.
|
||||
|
||||
import { z } from "zod";
|
||||
|
||||
import { TImmutableDBKeys } from "./models";
|
||||
|
||||
export const PkiCollectionsSchema = z.object({
|
||||
id: z.string().uuid(),
|
||||
createdAt: z.date(),
|
||||
updatedAt: z.date(),
|
||||
projectId: z.string(),
|
||||
name: z.string()
|
||||
});
|
||||
|
||||
export type TPkiCollections = z.infer<typeof PkiCollectionsSchema>;
|
||||
export type TPkiCollectionsInsert = Omit<z.input<typeof PkiCollectionsSchema>, TImmutableDBKeys>;
|
||||
export type TPkiCollectionsUpdate = Partial<Omit<z.input<typeof PkiCollectionsSchema>, TImmutableDBKeys>>;
|
||||
@@ -10,7 +10,6 @@ export enum ProjectPermissionActions {
|
||||
}
|
||||
|
||||
export enum ProjectPermissionSub {
|
||||
Alerts = "alerts",
|
||||
Role = "role",
|
||||
Member = "member",
|
||||
Groups = "groups",
|
||||
@@ -31,6 +30,8 @@ export enum ProjectPermissionSub {
|
||||
Identity = "identity",
|
||||
CertificateAuthorities = "certificate-authorities",
|
||||
Certificates = "certificates",
|
||||
PkiAlerts = "pki-alerts",
|
||||
PkiCollections = "pki-collections",
|
||||
Kms = "kms"
|
||||
}
|
||||
|
||||
@@ -64,7 +65,8 @@ export type ProjectPermissionSet =
|
||||
| [ProjectPermissionActions, ProjectPermissionSub.Identity]
|
||||
| [ProjectPermissionActions, ProjectPermissionSub.CertificateAuthorities]
|
||||
| [ProjectPermissionActions, ProjectPermissionSub.Certificates]
|
||||
| [ProjectPermissionActions, ProjectPermissionSub.Alerts]
|
||||
| [ProjectPermissionActions, ProjectPermissionSub.PkiAlerts]
|
||||
| [ProjectPermissionActions, ProjectPermissionSub.PkiCollections]
|
||||
| [ProjectPermissionActions.Delete, ProjectPermissionSub.Project]
|
||||
| [ProjectPermissionActions.Edit, ProjectPermissionSub.Project]
|
||||
| [ProjectPermissionActions.Read, ProjectPermissionSub.SecretRollback]
|
||||
@@ -74,11 +76,6 @@ export type ProjectPermissionSet =
|
||||
const buildAdminPermissionRules = () => {
|
||||
const { can, rules } = new AbilityBuilder<MongoAbility<ProjectPermissionSet>>(createMongoAbility);
|
||||
|
||||
can(ProjectPermissionActions.Read, ProjectPermissionSub.Alerts);
|
||||
can(ProjectPermissionActions.Create, ProjectPermissionSub.Alerts);
|
||||
can(ProjectPermissionActions.Edit, ProjectPermissionSub.Alerts);
|
||||
can(ProjectPermissionActions.Delete, ProjectPermissionSub.Alerts);
|
||||
|
||||
can(ProjectPermissionActions.Read, ProjectPermissionSub.Secrets);
|
||||
can(ProjectPermissionActions.Create, ProjectPermissionSub.Secrets);
|
||||
can(ProjectPermissionActions.Edit, ProjectPermissionSub.Secrets);
|
||||
@@ -168,6 +165,16 @@ const buildAdminPermissionRules = () => {
|
||||
can(ProjectPermissionActions.Edit, ProjectPermissionSub.Certificates);
|
||||
can(ProjectPermissionActions.Delete, ProjectPermissionSub.Certificates);
|
||||
|
||||
can(ProjectPermissionActions.Read, ProjectPermissionSub.PkiAlerts);
|
||||
can(ProjectPermissionActions.Create, ProjectPermissionSub.PkiAlerts);
|
||||
can(ProjectPermissionActions.Edit, ProjectPermissionSub.PkiAlerts);
|
||||
can(ProjectPermissionActions.Delete, ProjectPermissionSub.PkiAlerts);
|
||||
|
||||
can(ProjectPermissionActions.Read, ProjectPermissionSub.PkiCollections);
|
||||
can(ProjectPermissionActions.Create, ProjectPermissionSub.PkiCollections);
|
||||
can(ProjectPermissionActions.Edit, ProjectPermissionSub.PkiCollections);
|
||||
can(ProjectPermissionActions.Delete, ProjectPermissionSub.PkiCollections);
|
||||
|
||||
can(ProjectPermissionActions.Edit, ProjectPermissionSub.Project);
|
||||
can(ProjectPermissionActions.Delete, ProjectPermissionSub.Project);
|
||||
|
||||
@@ -244,7 +251,8 @@ const buildMemberPermissionRules = () => {
|
||||
can(ProjectPermissionActions.Edit, ProjectPermissionSub.Certificates);
|
||||
can(ProjectPermissionActions.Delete, ProjectPermissionSub.Certificates);
|
||||
|
||||
can(ProjectPermissionActions.Read, ProjectPermissionSub.Alerts);
|
||||
can(ProjectPermissionActions.Read, ProjectPermissionSub.PkiAlerts);
|
||||
can(ProjectPermissionActions.Read, ProjectPermissionSub.PkiCollections);
|
||||
|
||||
return rules;
|
||||
};
|
||||
|
||||
@@ -133,6 +133,8 @@ import { orgRoleServiceFactory } from "@app/services/org/org-role-service";
|
||||
import { orgServiceFactory } from "@app/services/org/org-service";
|
||||
import { orgAdminServiceFactory } from "@app/services/org-admin/org-admin-service";
|
||||
import { orgMembershipDALFactory } from "@app/services/org-membership/org-membership-dal";
|
||||
import { pkiCollectionDALFactory } from "@app/services/pki-collection/pki-collection-dal";
|
||||
import { pkiCollectionServiceFactory } from "@app/services/pki-collection/pki-collection-service";
|
||||
import { projectDALFactory } from "@app/services/project/project-dal";
|
||||
import { projectQueueFactory } from "@app/services/project/project-queue";
|
||||
import { projectServiceFactory } from "@app/services/project/project-service";
|
||||
@@ -517,10 +519,6 @@ export const registerRoutes = async (
|
||||
licenseService
|
||||
});
|
||||
const apiKeyService = apiKeyServiceFactory({ apiKeyDAL, userDAL });
|
||||
const alertService = alertServiceFactory({
|
||||
alertDAL,
|
||||
permissionService
|
||||
});
|
||||
|
||||
const secretScanningQueue = secretScanningQueueFactory({
|
||||
telemetryService,
|
||||
@@ -590,6 +588,8 @@ export const registerRoutes = async (
|
||||
const certificateDAL = certificateDALFactory(db);
|
||||
const certificateBodyDAL = certificateBodyDALFactory(db);
|
||||
|
||||
const pkiCollectionDAL = pkiCollectionDALFactory(db);
|
||||
|
||||
const certificateService = certificateServiceFactory({
|
||||
certificateDAL,
|
||||
certificateBodyDAL,
|
||||
@@ -634,6 +634,17 @@ export const registerRoutes = async (
|
||||
licenseService
|
||||
});
|
||||
|
||||
const alertService = alertServiceFactory({
|
||||
alertDAL,
|
||||
pkiCollectionDAL,
|
||||
permissionService
|
||||
});
|
||||
|
||||
const pkiCollectionService = pkiCollectionServiceFactory({
|
||||
pkiCollectionDAL,
|
||||
permissionService
|
||||
});
|
||||
|
||||
const projectService = projectServiceFactory({
|
||||
permissionService,
|
||||
projectDAL,
|
||||
@@ -651,6 +662,7 @@ export const registerRoutes = async (
|
||||
certificateAuthorityDAL,
|
||||
certificateDAL,
|
||||
alertDAL,
|
||||
pkiCollectionDAL,
|
||||
projectUserMembershipRoleDAL,
|
||||
identityProjectMembershipRoleDAL,
|
||||
keyStore,
|
||||
@@ -1123,6 +1135,7 @@ export const registerRoutes = async (
|
||||
certificate: certificateService,
|
||||
certificateAuthority: certificateAuthorityService,
|
||||
certificateAuthorityCrl: certificateAuthorityCrlService,
|
||||
pkiCollection: pkiCollectionService,
|
||||
secretScanning: secretScanningService,
|
||||
license: licenseService,
|
||||
trustedIp: trustedIpService,
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { registerAdminRouter } from "./admin-router";
|
||||
import { registerAlertRouter } from "./alert-router";
|
||||
import { registerAuthRoutes } from "./auth-router";
|
||||
import { registerProjectBotRouter } from "./bot-router";
|
||||
import { registerCaRouter } from "./certificate-authority-router";
|
||||
@@ -19,6 +18,8 @@ import { registerInviteOrgRouter } from "./invite-org-router";
|
||||
import { registerOrgAdminRouter } from "./org-admin-router";
|
||||
import { registerOrgRouter } from "./organization-router";
|
||||
import { registerPasswordRouter } from "./password-router";
|
||||
import { registerPkiAlertRouter } from "./pki-alert-router";
|
||||
import { registerPkiCollectionRouter } from "./pki-collection-router";
|
||||
import { registerProjectEnvRouter } from "./project-env-router";
|
||||
import { registerProjectKeyRouter } from "./project-key-router";
|
||||
import { registerProjectMembershipRouter } from "./project-membership-router";
|
||||
@@ -49,7 +50,6 @@ export const registerV1Routes = async (server: FastifyZodProvider) => {
|
||||
},
|
||||
{ prefix: "/auth" }
|
||||
);
|
||||
await server.register(registerAlertRouter, { prefix: "/alerts" });
|
||||
await server.register(registerPasswordRouter, { prefix: "/password" });
|
||||
await server.register(registerOrgRouter, { prefix: "/organization" });
|
||||
await server.register(registerAdminRouter, { prefix: "/admin" });
|
||||
@@ -76,6 +76,8 @@ export const registerV1Routes = async (server: FastifyZodProvider) => {
|
||||
async (pkiRouter) => {
|
||||
await pkiRouter.register(registerCaRouter, { prefix: "/ca" });
|
||||
await pkiRouter.register(registerCertRouter, { prefix: "/certificates" });
|
||||
await server.register(registerPkiAlertRouter, { prefix: "/alerts" });
|
||||
await server.register(registerPkiCollectionRouter, { prefix: "/collections" });
|
||||
},
|
||||
{ prefix: "/pki" }
|
||||
);
|
||||
|
||||
@@ -5,7 +5,7 @@ import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
|
||||
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
|
||||
import { AuthMode } from "@app/services/auth/auth-type";
|
||||
|
||||
export const registerAlertRouter = async (server: FastifyZodProvider) => {
|
||||
export const registerPkiAlertRouter = async (server: FastifyZodProvider) => {
|
||||
server.route({
|
||||
method: "POST",
|
||||
url: "/",
|
||||
@@ -14,9 +14,10 @@ export const registerAlertRouter = async (server: FastifyZodProvider) => {
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||
schema: {
|
||||
description: "Create alert",
|
||||
description: "Create PKI alert",
|
||||
body: z.object({
|
||||
projectId: z.string().trim(),
|
||||
pkiCollectionId: z.string().trim(),
|
||||
name: z.string().trim(),
|
||||
alertBeforeDays: z.number(),
|
||||
emails: z.array(z.string())
|
||||
@@ -26,7 +27,7 @@ export const registerAlertRouter = async (server: FastifyZodProvider) => {
|
||||
}
|
||||
},
|
||||
handler: async (req) => {
|
||||
const alert = await server.services.alert.createAlert({
|
||||
const alert = await server.services.alert.createPkiAlert({
|
||||
actor: req.permission.type,
|
||||
actorId: req.permission.id,
|
||||
actorAuthMethod: req.permission.authMethod,
|
||||
@@ -61,7 +62,7 @@ export const registerAlertRouter = async (server: FastifyZodProvider) => {
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||
schema: {
|
||||
description: "Get alert",
|
||||
description: "Get PKI alert",
|
||||
params: z.object({
|
||||
alertId: z.string().trim()
|
||||
}),
|
||||
@@ -70,7 +71,7 @@ export const registerAlertRouter = async (server: FastifyZodProvider) => {
|
||||
}
|
||||
},
|
||||
handler: async (req) => {
|
||||
const alert = await server.services.alert.getAlertById({
|
||||
const alert = await server.services.alert.getPkiAlertById({
|
||||
alertId: req.params.alertId,
|
||||
actor: req.permission.type,
|
||||
actorId: req.permission.id,
|
||||
@@ -104,13 +105,14 @@ export const registerAlertRouter = async (server: FastifyZodProvider) => {
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||
schema: {
|
||||
description: "Update alert",
|
||||
description: "Update PKI alert",
|
||||
params: z.object({
|
||||
alertId: z.string().trim()
|
||||
}),
|
||||
body: z.object({
|
||||
name: z.string().trim().optional(),
|
||||
alertBeforeDays: z.number().optional(),
|
||||
pkiCollectionId: z.string().trim().optional(),
|
||||
emails: z.array(z.string()).optional()
|
||||
}),
|
||||
response: {
|
||||
@@ -118,7 +120,7 @@ export const registerAlertRouter = async (server: FastifyZodProvider) => {
|
||||
}
|
||||
},
|
||||
handler: async (req) => {
|
||||
const alert = await server.services.alert.updateAlert({
|
||||
const alert = await server.services.alert.updatePkiAlert({
|
||||
alertId: req.params.alertId,
|
||||
actor: req.permission.type,
|
||||
actorId: req.permission.id,
|
||||
@@ -153,7 +155,7 @@ export const registerAlertRouter = async (server: FastifyZodProvider) => {
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||
schema: {
|
||||
description: "Delete alert",
|
||||
description: "Delete PKI alert",
|
||||
params: z.object({
|
||||
alertId: z.string().trim()
|
||||
}),
|
||||
@@ -162,7 +164,7 @@ export const registerAlertRouter = async (server: FastifyZodProvider) => {
|
||||
}
|
||||
},
|
||||
handler: async (req) => {
|
||||
const alert = await server.services.alert.deleteAlert({
|
||||
const alert = await server.services.alert.deletePkiAlert({
|
||||
alertId: req.params.alertId,
|
||||
actor: req.permission.type,
|
||||
actorId: req.permission.id,
|
||||
187
backend/src/server/routes/v1/pki-collection-router.ts
Normal file
187
backend/src/server/routes/v1/pki-collection-router.ts
Normal file
@@ -0,0 +1,187 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { PkiCollectionsSchema } from "@app/db/schemas";
|
||||
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
|
||||
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
|
||||
import { AuthMode } from "@app/services/auth/auth-type";
|
||||
|
||||
export const registerPkiCollectionRouter = async (server: FastifyZodProvider) => {
|
||||
server.route({
|
||||
method: "POST",
|
||||
url: "/",
|
||||
config: {
|
||||
rateLimit: writeLimit
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||
schema: {
|
||||
description: "Create PKI collection",
|
||||
body: z.object({
|
||||
projectId: z.string().trim(),
|
||||
name: z.string().trim()
|
||||
}),
|
||||
response: {
|
||||
200: PkiCollectionsSchema
|
||||
}
|
||||
},
|
||||
handler: async (req) => {
|
||||
const pkiCollection = await server.services.pkiCollection.createPkiCollection({
|
||||
actor: req.permission.type,
|
||||
actorId: req.permission.id,
|
||||
actorAuthMethod: req.permission.authMethod,
|
||||
actorOrgId: req.permission.orgId,
|
||||
...req.body
|
||||
});
|
||||
|
||||
// TODO: audit logging
|
||||
|
||||
// await server.services.auditLog.createAuditLog({
|
||||
// ...req.auditLogInfo,
|
||||
// projectId: ca.projectId,
|
||||
// event: {
|
||||
// type: EventType.REVOKE_CERT,
|
||||
// metadata: {
|
||||
// certId: cert.id,
|
||||
// cn: cert.commonName,
|
||||
// serialNumber: cert.serialNumber
|
||||
// }
|
||||
// }
|
||||
// });
|
||||
|
||||
return pkiCollection;
|
||||
}
|
||||
});
|
||||
|
||||
server.route({
|
||||
method: "GET",
|
||||
url: "/:collectionId",
|
||||
config: {
|
||||
rateLimit: readLimit
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||
schema: {
|
||||
description: "Get PKI collection",
|
||||
params: z.object({
|
||||
collectionId: z.string().trim()
|
||||
}),
|
||||
response: {
|
||||
200: PkiCollectionsSchema
|
||||
}
|
||||
},
|
||||
handler: async (req) => {
|
||||
const pkiCollection = await server.services.pkiCollection.getPkiCollectionById({
|
||||
collectionId: req.params.collectionId,
|
||||
actor: req.permission.type,
|
||||
actorId: req.permission.id,
|
||||
actorAuthMethod: req.permission.authMethod,
|
||||
actorOrgId: req.permission.orgId
|
||||
});
|
||||
|
||||
// TODO: audit logging
|
||||
|
||||
// await server.services.auditLog.createAuditLog({
|
||||
// ...req.auditLogInfo,
|
||||
// projectId: ca.projectId,
|
||||
// event: {
|
||||
// type: EventType.GET_CA,
|
||||
// metadata: {
|
||||
// caId: ca.id,
|
||||
// dn: ca.dn
|
||||
// }
|
||||
// }
|
||||
// });
|
||||
|
||||
return pkiCollection;
|
||||
}
|
||||
});
|
||||
|
||||
server.route({
|
||||
method: "PATCH",
|
||||
url: "/:collectionId",
|
||||
config: {
|
||||
rateLimit: writeLimit
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||
schema: {
|
||||
description: "Update PKI collection",
|
||||
params: z.object({
|
||||
collectionId: z.string().trim()
|
||||
}),
|
||||
body: z.object({
|
||||
name: z.string().trim().optional()
|
||||
}),
|
||||
response: {
|
||||
200: PkiCollectionsSchema
|
||||
}
|
||||
},
|
||||
handler: async (req) => {
|
||||
const pkiCollection = await server.services.pkiCollection.updatePkiCollection({
|
||||
collectionId: req.params.collectionId,
|
||||
actor: req.permission.type,
|
||||
actorId: req.permission.id,
|
||||
actorAuthMethod: req.permission.authMethod,
|
||||
actorOrgId: req.permission.orgId,
|
||||
...req.body
|
||||
});
|
||||
|
||||
// TODO: audit logging
|
||||
|
||||
// await server.services.auditLog.createAuditLog({
|
||||
// ...req.auditLogInfo,
|
||||
// projectId: ca.projectId,
|
||||
// event: {
|
||||
// type: EventType.GET_CA,
|
||||
// metadata: {
|
||||
// caId: ca.id,
|
||||
// dn: ca.dn
|
||||
// }
|
||||
// }
|
||||
// });
|
||||
|
||||
return pkiCollection;
|
||||
}
|
||||
});
|
||||
|
||||
server.route({
|
||||
method: "DELETE",
|
||||
url: "/:collectionId",
|
||||
config: {
|
||||
rateLimit: writeLimit
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||
schema: {
|
||||
description: "Delete PKI collection",
|
||||
params: z.object({
|
||||
collectionId: z.string().trim()
|
||||
}),
|
||||
response: {
|
||||
200: PkiCollectionsSchema
|
||||
}
|
||||
},
|
||||
handler: async (req) => {
|
||||
const pkiCollection = await server.services.pkiCollection.deletePkiCollection({
|
||||
collectionId: req.params.collectionId,
|
||||
actor: req.permission.type,
|
||||
actorId: req.permission.id,
|
||||
actorAuthMethod: req.permission.authMethod,
|
||||
actorOrgId: req.permission.orgId
|
||||
});
|
||||
|
||||
// TODO: audit logging
|
||||
|
||||
// await server.services.auditLog.createAuditLog({
|
||||
// ...req.auditLogInfo,
|
||||
// projectId: ca.projectId,
|
||||
// event: {
|
||||
// type: EventType.DELETE_CERT,
|
||||
// metadata: {
|
||||
// certId: deletedCert.id,
|
||||
// cn: deletedCert.commonName,
|
||||
// serialNumber: deletedCert.serialNumber
|
||||
// }
|
||||
// }
|
||||
// });
|
||||
|
||||
return pkiCollection;
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -1,7 +1,13 @@
|
||||
import slugify from "@sindresorhus/slugify";
|
||||
import { z } from "zod";
|
||||
|
||||
import { AlertsSchema, CertificateAuthoritiesSchema, CertificatesSchema, ProjectKeysSchema } from "@app/db/schemas";
|
||||
import {
|
||||
AlertsSchema,
|
||||
CertificateAuthoritiesSchema,
|
||||
CertificatesSchema,
|
||||
PkiCollectionsSchema,
|
||||
ProjectKeysSchema
|
||||
} from "@app/db/schemas";
|
||||
import { EventType } from "@app/ee/services/audit-log/audit-log-types";
|
||||
import { PROJECTS } from "@app/lib/api-docs";
|
||||
import { creationLimit, readLimit, writeLimit } from "@app/server/config/rateLimiter";
|
||||
@@ -395,7 +401,7 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
|
||||
|
||||
server.route({
|
||||
method: "GET",
|
||||
url: "/:projectId/alerts",
|
||||
url: "/:projectId/pki-alerts",
|
||||
config: {
|
||||
rateLimit: readLimit
|
||||
},
|
||||
@@ -422,4 +428,34 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
|
||||
return { alerts };
|
||||
}
|
||||
});
|
||||
|
||||
server.route({
|
||||
method: "GET",
|
||||
url: "/:projectId/pki-collections",
|
||||
config: {
|
||||
rateLimit: readLimit
|
||||
},
|
||||
schema: {
|
||||
params: z.object({
|
||||
projectId: z.string().trim()
|
||||
}),
|
||||
response: {
|
||||
200: z.object({
|
||||
collections: z.array(PkiCollectionsSchema)
|
||||
})
|
||||
}
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||
handler: async (req) => {
|
||||
const { pkiCollections } = await server.services.project.listProjectPkiCollections({
|
||||
projectId: req.params.projectId,
|
||||
actorId: req.permission.id,
|
||||
actorOrgId: req.permission.orgId,
|
||||
actorAuthMethod: req.permission.authMethod,
|
||||
actor: req.permission.type
|
||||
});
|
||||
|
||||
return { collections: pkiCollections };
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
@@ -2,22 +2,25 @@ import { ForbiddenError } from "@casl/ability";
|
||||
|
||||
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service";
|
||||
import { ProjectPermissionActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";
|
||||
import { NotFoundError } from "@app/lib/errors";
|
||||
import { NotFoundError, UnauthorizedError } from "@app/lib/errors";
|
||||
import { TPkiCollectionDALFactory } from "@app/services/pki-collection/pki-collection-dal";
|
||||
|
||||
import { TAlertDALFactory } from "./alert-dal";
|
||||
import { TCreateAlertDTO, TDeleteAlertDTO, TGetAlertByIdDTO, TUpdateAlertDTO } from "./alert-types";
|
||||
|
||||
type TAlertServiceFactoryDep = {
|
||||
alertDAL: TAlertDALFactory;
|
||||
pkiCollectionDAL: TPkiCollectionDALFactory;
|
||||
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
|
||||
};
|
||||
|
||||
export type TAlertServiceFactory = ReturnType<typeof alertServiceFactory>;
|
||||
|
||||
export const alertServiceFactory = ({ alertDAL, permissionService }: TAlertServiceFactoryDep) => {
|
||||
const createAlert = async ({
|
||||
export const alertServiceFactory = ({ alertDAL, pkiCollectionDAL, permissionService }: TAlertServiceFactoryDep) => {
|
||||
const createPkiAlert = async ({
|
||||
projectId,
|
||||
name,
|
||||
pkiCollectionId,
|
||||
alertBeforeDays,
|
||||
emails,
|
||||
actorId,
|
||||
@@ -33,10 +36,16 @@ export const alertServiceFactory = ({ alertDAL, permissionService }: TAlertServi
|
||||
actorOrgId
|
||||
);
|
||||
|
||||
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Create, ProjectPermissionSub.Alerts);
|
||||
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Create, ProjectPermissionSub.PkiAlerts);
|
||||
|
||||
const pkiCollection = await pkiCollectionDAL.findById(pkiCollectionId);
|
||||
if (!pkiCollection) throw new NotFoundError({ message: "PKI collection not found" });
|
||||
if (pkiCollection.projectId !== projectId)
|
||||
throw new UnauthorizedError({ message: "PKI collection not found in project" });
|
||||
|
||||
const alert = await alertDAL.create({
|
||||
projectId,
|
||||
pkiCollectionId,
|
||||
name,
|
||||
alertBeforeDays,
|
||||
recipientEmails: emails.join(",")
|
||||
@@ -44,7 +53,7 @@ export const alertServiceFactory = ({ alertDAL, permissionService }: TAlertServi
|
||||
return alert;
|
||||
};
|
||||
|
||||
const getAlertById = async ({ alertId, actorId, actorAuthMethod, actor, actorOrgId }: TGetAlertByIdDTO) => {
|
||||
const getPkiAlertById = async ({ alertId, actorId, actorAuthMethod, actor, actorOrgId }: TGetAlertByIdDTO) => {
|
||||
const alert = await alertDAL.findById(alertId);
|
||||
if (!alert) throw new NotFoundError({ message: "Alert not found" });
|
||||
|
||||
@@ -56,13 +65,14 @@ export const alertServiceFactory = ({ alertDAL, permissionService }: TAlertServi
|
||||
actorOrgId
|
||||
);
|
||||
|
||||
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.Alerts);
|
||||
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.PkiAlerts);
|
||||
return alert;
|
||||
};
|
||||
|
||||
const updateAlert = async ({
|
||||
const updatePkiAlert = async ({
|
||||
alertId,
|
||||
name,
|
||||
pkiCollectionId,
|
||||
alertBeforeDays,
|
||||
emails,
|
||||
actorId,
|
||||
@@ -81,17 +91,26 @@ export const alertServiceFactory = ({ alertDAL, permissionService }: TAlertServi
|
||||
actorOrgId
|
||||
);
|
||||
|
||||
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Create, ProjectPermissionSub.Alerts);
|
||||
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Edit, ProjectPermissionSub.PkiAlerts);
|
||||
|
||||
if (pkiCollectionId) {
|
||||
const pkiCollection = await pkiCollectionDAL.findById(pkiCollectionId);
|
||||
if (!pkiCollection) throw new NotFoundError({ message: "PKI collection not found" });
|
||||
if (pkiCollection.projectId !== alert.projectId)
|
||||
throw new UnauthorizedError({ message: "PKI collection not found in project" });
|
||||
}
|
||||
|
||||
alert = await alertDAL.updateById(alertId, {
|
||||
name,
|
||||
alertBeforeDays,
|
||||
recipientEmails: emails ? emails.join(",") : undefined
|
||||
...(pkiCollectionId && { pkiCollectionId }),
|
||||
...(emails && { recipientEmails: emails.join(",") }) // TODO: standardize recipient emails
|
||||
});
|
||||
|
||||
return alert;
|
||||
};
|
||||
|
||||
const deleteAlert = async ({ alertId, actorId, actorAuthMethod, actor, actorOrgId }: TDeleteAlertDTO) => {
|
||||
const deletePkiAlert = async ({ alertId, actorId, actorAuthMethod, actor, actorOrgId }: TDeleteAlertDTO) => {
|
||||
let alert = await alertDAL.findById(alertId);
|
||||
if (!alert) throw new NotFoundError({ message: "Alert not found" });
|
||||
|
||||
@@ -103,15 +122,15 @@ export const alertServiceFactory = ({ alertDAL, permissionService }: TAlertServi
|
||||
actorOrgId
|
||||
);
|
||||
|
||||
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Create, ProjectPermissionSub.Alerts);
|
||||
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Delete, ProjectPermissionSub.PkiAlerts);
|
||||
alert = await alertDAL.deleteById(alertId);
|
||||
return alert;
|
||||
};
|
||||
|
||||
return {
|
||||
createAlert,
|
||||
getAlertById,
|
||||
updateAlert,
|
||||
deleteAlert
|
||||
createPkiAlert,
|
||||
getPkiAlertById,
|
||||
updatePkiAlert,
|
||||
deletePkiAlert
|
||||
};
|
||||
};
|
||||
|
||||
@@ -2,6 +2,7 @@ import { TProjectPermission } from "@app/lib/types";
|
||||
|
||||
export type TCreateAlertDTO = {
|
||||
name: string;
|
||||
pkiCollectionId: string;
|
||||
alertBeforeDays: number;
|
||||
emails: string[];
|
||||
} & TProjectPermission;
|
||||
@@ -13,6 +14,7 @@ export type TGetAlertByIdDTO = {
|
||||
export type TUpdateAlertDTO = {
|
||||
alertId: string;
|
||||
name?: string;
|
||||
pkiCollectionId?: string;
|
||||
alertBeforeDays?: number;
|
||||
emails?: string[];
|
||||
} & Omit<TProjectPermission, "projectId">;
|
||||
|
||||
13
backend/src/services/pki-collection/pki-collection-dal.ts
Normal file
13
backend/src/services/pki-collection/pki-collection-dal.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import { TDbClient } from "@app/db";
|
||||
import { TableName } from "@app/db/schemas";
|
||||
import { ormify } from "@app/lib/knex";
|
||||
|
||||
export type TPkiCollectionDALFactory = ReturnType<typeof pkiCollectionDALFactory>;
|
||||
|
||||
export const pkiCollectionDALFactory = (db: TDbClient) => {
|
||||
const pkiCollectionOrm = ormify(db, TableName.PkiCollection);
|
||||
|
||||
return {
|
||||
...pkiCollectionOrm
|
||||
};
|
||||
};
|
||||
138
backend/src/services/pki-collection/pki-collection-service.ts
Normal file
138
backend/src/services/pki-collection/pki-collection-service.ts
Normal file
@@ -0,0 +1,138 @@
|
||||
import { ForbiddenError } from "@casl/ability";
|
||||
|
||||
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service";
|
||||
import { ProjectPermissionActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";
|
||||
import { NotFoundError } from "@app/lib/errors";
|
||||
|
||||
import { TPkiCollectionDALFactory } from "./pki-collection-dal";
|
||||
import {
|
||||
TCreatePkiCollectionDTO,
|
||||
TDeletePkiCollectionDTO,
|
||||
TGetPkiCollectionByIdDTO,
|
||||
TUpdatePkiCollectionDTO
|
||||
} from "./pki-collection-types";
|
||||
|
||||
type TPkiCollectionServiceFactoryDep = {
|
||||
pkiCollectionDAL: TPkiCollectionDALFactory;
|
||||
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
|
||||
};
|
||||
|
||||
export type TPkiCollectionServiceFactory = ReturnType<typeof pkiCollectionServiceFactory>;
|
||||
|
||||
export const pkiCollectionServiceFactory = ({
|
||||
pkiCollectionDAL,
|
||||
permissionService
|
||||
}: TPkiCollectionServiceFactoryDep) => {
|
||||
const createPkiCollection = async ({
|
||||
name,
|
||||
projectId,
|
||||
actorId,
|
||||
actorAuthMethod,
|
||||
actor,
|
||||
actorOrgId
|
||||
}: TCreatePkiCollectionDTO) => {
|
||||
const { permission } = await permissionService.getProjectPermission(
|
||||
actor,
|
||||
actorId,
|
||||
projectId,
|
||||
actorAuthMethod,
|
||||
actorOrgId
|
||||
);
|
||||
|
||||
ForbiddenError.from(permission).throwUnlessCan(
|
||||
ProjectPermissionActions.Create,
|
||||
ProjectPermissionSub.PkiCollections
|
||||
);
|
||||
|
||||
const pkiCollection = await pkiCollectionDAL.create({
|
||||
projectId,
|
||||
name
|
||||
});
|
||||
|
||||
return pkiCollection;
|
||||
};
|
||||
|
||||
const getPkiCollectionById = async ({
|
||||
collectionId,
|
||||
actorId,
|
||||
actorAuthMethod,
|
||||
actor,
|
||||
actorOrgId
|
||||
}: TGetPkiCollectionByIdDTO) => {
|
||||
const pkiCollection = await pkiCollectionDAL.findById(collectionId);
|
||||
if (!pkiCollection) throw new NotFoundError({ message: "PKI collection not found" });
|
||||
|
||||
const { permission } = await permissionService.getProjectPermission(
|
||||
actor,
|
||||
actorId,
|
||||
pkiCollection.projectId,
|
||||
actorAuthMethod,
|
||||
actorOrgId
|
||||
);
|
||||
|
||||
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.PkiCollections);
|
||||
return pkiCollection;
|
||||
};
|
||||
|
||||
const updatePkiCollection = async ({
|
||||
collectionId,
|
||||
name,
|
||||
actorId,
|
||||
actorAuthMethod,
|
||||
actor,
|
||||
actorOrgId
|
||||
}: TUpdatePkiCollectionDTO) => {
|
||||
let pkiCollection = await pkiCollectionDAL.findById(collectionId);
|
||||
if (!pkiCollection) throw new NotFoundError({ message: "PKI collection not found" });
|
||||
|
||||
const { permission } = await permissionService.getProjectPermission(
|
||||
actor,
|
||||
actorId,
|
||||
pkiCollection.projectId,
|
||||
actorAuthMethod,
|
||||
actorOrgId
|
||||
);
|
||||
|
||||
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Edit, ProjectPermissionSub.PkiCollections);
|
||||
pkiCollection = await pkiCollectionDAL.updateById(collectionId, {
|
||||
name
|
||||
});
|
||||
|
||||
return pkiCollection;
|
||||
};
|
||||
|
||||
const deletePkiCollection = async ({
|
||||
collectionId,
|
||||
actorId,
|
||||
actorAuthMethod,
|
||||
actor,
|
||||
actorOrgId
|
||||
}: TDeletePkiCollectionDTO) => {
|
||||
let pkiCollection = await pkiCollectionDAL.findById(collectionId);
|
||||
if (!pkiCollection) throw new NotFoundError({ message: "PKI collection not found" });
|
||||
|
||||
const { permission } = await permissionService.getProjectPermission(
|
||||
actor,
|
||||
actorId,
|
||||
pkiCollection.projectId,
|
||||
actorAuthMethod,
|
||||
actorOrgId
|
||||
);
|
||||
|
||||
ForbiddenError.from(permission).throwUnlessCan(
|
||||
ProjectPermissionActions.Create,
|
||||
ProjectPermissionSub.PkiCollections
|
||||
);
|
||||
pkiCollection = await pkiCollectionDAL.deleteById(collectionId);
|
||||
return pkiCollection;
|
||||
};
|
||||
|
||||
// TODO: add/remove pki collection items
|
||||
|
||||
return {
|
||||
createPkiCollection,
|
||||
getPkiCollectionById,
|
||||
updatePkiCollection,
|
||||
deletePkiCollection
|
||||
};
|
||||
};
|
||||
18
backend/src/services/pki-collection/pki-collection-types.ts
Normal file
18
backend/src/services/pki-collection/pki-collection-types.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { TProjectPermission } from "@app/lib/types";
|
||||
|
||||
export type TCreatePkiCollectionDTO = {
|
||||
name: string;
|
||||
} & TProjectPermission;
|
||||
|
||||
export type TGetPkiCollectionByIdDTO = {
|
||||
collectionId: string;
|
||||
} & Omit<TProjectPermission, "projectId">;
|
||||
|
||||
export type TUpdatePkiCollectionDTO = {
|
||||
collectionId: string;
|
||||
name?: string;
|
||||
} & Omit<TProjectPermission, "projectId">;
|
||||
|
||||
export type TDeletePkiCollectionDTO = {
|
||||
collectionId: string;
|
||||
} & Omit<TProjectPermission, "projectId">;
|
||||
@@ -23,6 +23,7 @@ import { TIdentityProjectMembershipRoleDALFactory } from "../identity-project/id
|
||||
import { TKmsServiceFactory } from "../kms/kms-service";
|
||||
import { TOrgDALFactory } from "../org/org-dal";
|
||||
import { TOrgServiceFactory } from "../org/org-service";
|
||||
import { TPkiCollectionDALFactory } from "../pki-collection/pki-collection-dal";
|
||||
import { TProjectBotDALFactory } from "../project-bot/project-bot-dal";
|
||||
import { TProjectEnvDALFactory } from "../project-env/project-env-dal";
|
||||
import { TProjectKeyDALFactory } from "../project-key/project-key-dal";
|
||||
@@ -73,6 +74,7 @@ type TProjectServiceFactoryDep = {
|
||||
certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "find">;
|
||||
certificateDAL: Pick<TCertificateDALFactory, "find" | "countCertificatesInProject">;
|
||||
alertDAL: Pick<TAlertDALFactory, "find">;
|
||||
pkiCollectionDAL: Pick<TPkiCollectionDALFactory, "find">;
|
||||
permissionService: TPermissionServiceFactory;
|
||||
orgService: Pick<TOrgServiceFactory, "addGhostUser">;
|
||||
licenseService: Pick<TLicenseServiceFactory, "getPlan">;
|
||||
@@ -110,6 +112,7 @@ export const projectServiceFactory = ({
|
||||
identityProjectMembershipRoleDAL,
|
||||
certificateAuthorityDAL,
|
||||
certificateDAL,
|
||||
pkiCollectionDAL,
|
||||
alertDAL,
|
||||
keyStore,
|
||||
kmsService,
|
||||
@@ -698,7 +701,7 @@ export const projectServiceFactory = ({
|
||||
actorOrgId
|
||||
);
|
||||
|
||||
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.Alerts);
|
||||
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.PkiAlerts);
|
||||
|
||||
const alerts = await alertDAL.find({ projectId });
|
||||
|
||||
@@ -707,6 +710,33 @@ export const projectServiceFactory = ({
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Return list of PKI collections for project
|
||||
*/
|
||||
const listProjectPkiCollections = async ({
|
||||
projectId,
|
||||
actor,
|
||||
actorId,
|
||||
actorAuthMethod,
|
||||
actorOrgId
|
||||
}: TListProjectAlertsDTO) => {
|
||||
const { permission } = await permissionService.getProjectPermission(
|
||||
actor,
|
||||
actorId,
|
||||
projectId,
|
||||
actorAuthMethod,
|
||||
actorOrgId
|
||||
);
|
||||
|
||||
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.PkiCollections);
|
||||
|
||||
const pkiCollections = await pkiCollectionDAL.find({ projectId });
|
||||
|
||||
return {
|
||||
pkiCollections
|
||||
};
|
||||
};
|
||||
|
||||
const updateProjectKmsKey = async ({
|
||||
projectId,
|
||||
kms,
|
||||
@@ -826,6 +856,7 @@ export const projectServiceFactory = ({
|
||||
listProjectCas,
|
||||
listProjectCertificates,
|
||||
listProjectAlerts,
|
||||
listProjectPkiCollections,
|
||||
updateVersionLimit,
|
||||
updateAuditLogsRetention,
|
||||
updateProjectKmsKey,
|
||||
|
||||
@@ -8,7 +8,6 @@ export enum ProjectPermissionActions {
|
||||
}
|
||||
|
||||
export enum ProjectPermissionSub {
|
||||
Alerts = "alerts",
|
||||
Role = "role",
|
||||
Member = "member",
|
||||
Groups = "groups",
|
||||
@@ -29,6 +28,8 @@ export enum ProjectPermissionSub {
|
||||
Identity = "identity",
|
||||
CertificateAuthorities = "certificate-authorities",
|
||||
Certificates = "certificates",
|
||||
PkiAlerts = "pki-alerts",
|
||||
PkiCollections = "pki-collections",
|
||||
Kms = "kms"
|
||||
}
|
||||
|
||||
@@ -42,7 +43,7 @@ export type ProjectPermissionSet =
|
||||
ProjectPermissionActions,
|
||||
ProjectPermissionSub.Secrets | (ForcedSubject<ProjectPermissionSub.Secrets> & SubjectFields)
|
||||
]
|
||||
| [ProjectPermissionActions, ProjectPermissionSub.Alerts]
|
||||
| [ProjectPermissionActions, ProjectPermissionSub.PkiAlerts]
|
||||
| [ProjectPermissionActions, ProjectPermissionSub.Role]
|
||||
| [ProjectPermissionActions, ProjectPermissionSub.Tags]
|
||||
| [ProjectPermissionActions, ProjectPermissionSub.Member]
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
|
||||
import { apiRequest } from "@app/config/request";
|
||||
|
||||
import { workspaceKeys } from "../workspace/queries";
|
||||
import { alertKeys } from "./queries";
|
||||
import { TAlert, TCreateAlertDTO, TDeleteAlertDTO,TUpdateAlertDTO } from "./types";
|
||||
|
||||
export const useCreateAlert = () => {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation<TAlert, {}, TCreateAlertDTO>({
|
||||
mutationFn: async (body) => {
|
||||
const { data: alert } = await apiRequest.post<TAlert>("/api/v1/alerts", body);
|
||||
return alert;
|
||||
},
|
||||
onSuccess: (_, { projectId }) => {
|
||||
queryClient.invalidateQueries(workspaceKeys.getWorkspaceAlerts(projectId));
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
export const useUpdateAlert = () => {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation<TAlert, {}, TUpdateAlertDTO>({
|
||||
mutationFn: async ({ alertId, ...body }) => {
|
||||
const { data: alert } = await apiRequest.patch<TAlert>(`/api/v1/alerts/${alertId}`, body);
|
||||
return alert;
|
||||
},
|
||||
onSuccess: (_, { projectId, alertId }) => {
|
||||
queryClient.invalidateQueries(workspaceKeys.getWorkspaceAlerts(projectId));
|
||||
queryClient.invalidateQueries(alertKeys.getAlertById(alertId));
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
export const useDeleteAlert = () => {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation<TAlert, {}, TDeleteAlertDTO>({
|
||||
mutationFn: async ({ alertId }) => {
|
||||
const { data: alert } = await apiRequest.delete<TAlert>(`/api/v1/alerts/${alertId}`);
|
||||
return alert;
|
||||
},
|
||||
onSuccess: (_, { projectId, alertId }) => {
|
||||
queryClient.invalidateQueries(workspaceKeys.getWorkspaceAlerts(projectId));
|
||||
queryClient.invalidateQueries(alertKeys.getAlertById(alertId));
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -1,20 +0,0 @@
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
|
||||
import { apiRequest } from "@app/config/request";
|
||||
|
||||
import { TAlert } from "./types";
|
||||
|
||||
export const alertKeys = {
|
||||
getAlertById: (alertId: string) => [{ alertId }, "alert"]
|
||||
};
|
||||
|
||||
export const useGetAlertById = (alertId: string) => {
|
||||
return useQuery({
|
||||
queryKey: alertKeys.getAlertById(alertId),
|
||||
queryFn: async () => {
|
||||
const { data: alert } = await apiRequest.get<TAlert>(`/api/v1/alerts/${alertId}`);
|
||||
return alert;
|
||||
},
|
||||
enabled: Boolean(alertId)
|
||||
});
|
||||
};
|
||||
@@ -1,6 +1,5 @@
|
||||
export * from "./accessApproval";
|
||||
export * from "./admin";
|
||||
export * from "./alerts";
|
||||
export * from "./apiKeys";
|
||||
export * from "./auditLogs";
|
||||
export * from "./auditLogStreams";
|
||||
@@ -22,6 +21,8 @@ export * from "./ldapConfig";
|
||||
export * from "./oidcConfig";
|
||||
export * from "./orgAdmin";
|
||||
export * from "./organization";
|
||||
export * from "./pkiAlerts";
|
||||
export * from "./pkiCollections";
|
||||
export * from "./projectUserAdditionalPrivilege";
|
||||
export * from "./rateLimit";
|
||||
export * from "./roles";
|
||||
|
||||
51
frontend/src/hooks/api/pkiAlerts/mutations.tsx
Normal file
51
frontend/src/hooks/api/pkiAlerts/mutations.tsx
Normal file
@@ -0,0 +1,51 @@
|
||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
|
||||
import { apiRequest } from "@app/config/request";
|
||||
|
||||
import { workspaceKeys } from "../workspace/queries";
|
||||
import { pkiAlertKeys } from "./queries";
|
||||
import { TCreatePkiAlertDTO, TDeletePkiAlertDTO, TPkiAlert, TUpdatePkiAlertDTO } from "./types";
|
||||
|
||||
export const useCreateAlert = () => {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation<TPkiAlert, {}, TCreatePkiAlertDTO>({
|
||||
mutationFn: async (body) => {
|
||||
const { data: alert } = await apiRequest.post<TPkiAlert>("/api/v1/pki/alerts", body);
|
||||
return alert;
|
||||
},
|
||||
onSuccess: (_, { projectId }) => {
|
||||
queryClient.invalidateQueries(workspaceKeys.getWorkspacePkiAlerts(projectId));
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
export const useUpdateAlert = () => {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation<TPkiAlert, {}, TUpdatePkiAlertDTO>({
|
||||
mutationFn: async ({ alertId, ...body }) => {
|
||||
const { data: alert } = await apiRequest.patch<TPkiAlert>(
|
||||
`/api/v1/pki/alerts/${alertId}`,
|
||||
body
|
||||
);
|
||||
return alert;
|
||||
},
|
||||
onSuccess: (_, { projectId, alertId }) => {
|
||||
queryClient.invalidateQueries(workspaceKeys.getWorkspacePkiAlerts(projectId));
|
||||
queryClient.invalidateQueries(pkiAlertKeys.getPkiAlertById(alertId));
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
export const useDeleteAlert = () => {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation<TPkiAlert, {}, TDeletePkiAlertDTO>({
|
||||
mutationFn: async ({ alertId }) => {
|
||||
const { data: alert } = await apiRequest.delete<TPkiAlert>(`/api/v1/pki/alerts/${alertId}`);
|
||||
return alert;
|
||||
},
|
||||
onSuccess: (_, { projectId, alertId }) => {
|
||||
queryClient.invalidateQueries(workspaceKeys.getWorkspacePkiAlerts(projectId));
|
||||
queryClient.invalidateQueries(pkiAlertKeys.getPkiAlertById(alertId));
|
||||
}
|
||||
});
|
||||
};
|
||||
20
frontend/src/hooks/api/pkiAlerts/queries.tsx
Normal file
20
frontend/src/hooks/api/pkiAlerts/queries.tsx
Normal file
@@ -0,0 +1,20 @@
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
|
||||
import { apiRequest } from "@app/config/request";
|
||||
|
||||
import { TPkiAlert } from "./types";
|
||||
|
||||
export const pkiAlertKeys = {
|
||||
getPkiAlertById: (alertId: string) => [{ alertId }, "alert"]
|
||||
};
|
||||
|
||||
export const useGetAlertById = (alertId: string) => {
|
||||
return useQuery({
|
||||
queryKey: pkiAlertKeys.getPkiAlertById(alertId),
|
||||
queryFn: async () => {
|
||||
const { data: alert } = await apiRequest.get<TPkiAlert>(`/api/v1/pki/alerts/${alertId}`);
|
||||
return alert;
|
||||
},
|
||||
enabled: Boolean(alertId)
|
||||
});
|
||||
};
|
||||
@@ -1,29 +1,32 @@
|
||||
export type TAlert = {
|
||||
export type TPkiAlert = {
|
||||
id: string;
|
||||
name: string;
|
||||
projectId: string;
|
||||
pkiCollectionId: string;
|
||||
alertBeforeDays: number;
|
||||
recipientEmails: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
};
|
||||
|
||||
export type TCreateAlertDTO = {
|
||||
export type TCreatePkiAlertDTO = {
|
||||
projectId: string;
|
||||
name: string;
|
||||
pkiCollectionId: string;
|
||||
alertBeforeDays: number;
|
||||
emails: string[];
|
||||
};
|
||||
|
||||
export type TUpdateAlertDTO = {
|
||||
export type TUpdatePkiAlertDTO = {
|
||||
alertId: string;
|
||||
projectId: string;
|
||||
pkiCollectionId?: string;
|
||||
name?: string;
|
||||
alertBeforeDays?: number;
|
||||
emails?: string[];
|
||||
};
|
||||
|
||||
export type TDeleteAlertDTO = {
|
||||
export type TDeletePkiAlertDTO = {
|
||||
alertId: string;
|
||||
projectId: string;
|
||||
};
|
||||
5
frontend/src/hooks/api/pkiCollections/index.tsx
Normal file
5
frontend/src/hooks/api/pkiCollections/index.tsx
Normal file
@@ -0,0 +1,5 @@
|
||||
export {
|
||||
useCreatePkiCollection,
|
||||
useDeletePkiCollection,
|
||||
useUpdatePkiCollection} from "./mutations";
|
||||
export { useGetPkiCollectionById } from "./queries";
|
||||
64
frontend/src/hooks/api/pkiCollections/mutations.tsx
Normal file
64
frontend/src/hooks/api/pkiCollections/mutations.tsx
Normal file
@@ -0,0 +1,64 @@
|
||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
|
||||
import { apiRequest } from "@app/config/request";
|
||||
|
||||
import { workspaceKeys } from "../workspace/queries";
|
||||
// import { alertKeys } from "./queries";
|
||||
// import { TAlert, TCreateAlertDTO, TDeleteAlertDTO, TUpdateAlertDTO } from "./types";
|
||||
import { pkiCollectionKeys } from "./queries";
|
||||
import {
|
||||
TCreatePkiCollectionDTO,
|
||||
TDeletePkiCollectionDTO,
|
||||
TPkiCollection,
|
||||
TUpdatePkiCollectionTO} from "./types";
|
||||
|
||||
export const useCreatePkiCollection = () => {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation<TPkiCollection, {}, TCreatePkiCollectionDTO>({
|
||||
mutationFn: async (body) => {
|
||||
const { data: pkiCollection } = await apiRequest.post<TPkiCollection>(
|
||||
"/api/v1/pki/collections",
|
||||
body
|
||||
);
|
||||
return pkiCollection;
|
||||
},
|
||||
onSuccess: (_, { projectId }) => {
|
||||
queryClient.invalidateQueries(workspaceKeys.getWorkspacePkiCollections(projectId));
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
export const useUpdatePkiCollection = () => {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation<TPkiCollection, {}, TUpdatePkiCollectionTO>({
|
||||
mutationFn: async ({ collectionId, ...body }) => {
|
||||
const { data: pkiCollection } = await apiRequest.patch<TPkiCollection>(
|
||||
`/api/v1/pki/collections/${collectionId}`,
|
||||
body
|
||||
);
|
||||
return pkiCollection;
|
||||
},
|
||||
onSuccess: (_, { projectId, collectionId }) => {
|
||||
queryClient.invalidateQueries(workspaceKeys.getWorkspacePkiCollections(projectId));
|
||||
queryClient.invalidateQueries(pkiCollectionKeys.getPkiCollectionById(collectionId));
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
export const useDeletePkiCollection = () => {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation<TPkiCollection, {}, TDeletePkiCollectionDTO>({
|
||||
mutationFn: async ({ collectionId }) => {
|
||||
const { data: pkiCollection } = await apiRequest.delete<TPkiCollection>(
|
||||
`/api/v1/pki/collections/${collectionId}`
|
||||
);
|
||||
return pkiCollection;
|
||||
},
|
||||
onSuccess: (_, { projectId, collectionId }) => {
|
||||
queryClient.invalidateQueries(workspaceKeys.getWorkspacePkiCollections(projectId));
|
||||
queryClient.invalidateQueries(pkiCollectionKeys.getPkiCollectionById(collectionId));
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
// TODO: add PKI Collection Item
|
||||
22
frontend/src/hooks/api/pkiCollections/queries.tsx
Normal file
22
frontend/src/hooks/api/pkiCollections/queries.tsx
Normal file
@@ -0,0 +1,22 @@
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
|
||||
import { apiRequest } from "@app/config/request";
|
||||
|
||||
import { TPkiCollection } from "./types";
|
||||
|
||||
export const pkiCollectionKeys = {
|
||||
getPkiCollectionById: (collectionId: string) => [{ collectionId }, "pki-collection"]
|
||||
};
|
||||
|
||||
export const useGetPkiCollectionById = (collectionId: string) => {
|
||||
return useQuery({
|
||||
queryKey: pkiCollectionKeys.getPkiCollectionById(collectionId),
|
||||
queryFn: async () => {
|
||||
const { data: pkiCollection } = await apiRequest.get<TPkiCollection>(
|
||||
`/api/v1/pki/collections/${collectionId}`
|
||||
);
|
||||
return pkiCollection;
|
||||
},
|
||||
enabled: Boolean(collectionId)
|
||||
});
|
||||
};
|
||||
23
frontend/src/hooks/api/pkiCollections/types.ts
Normal file
23
frontend/src/hooks/api/pkiCollections/types.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
export type TPkiCollection = {
|
||||
id: string;
|
||||
name: string;
|
||||
projectId: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
};
|
||||
|
||||
export type TCreatePkiCollectionDTO = {
|
||||
projectId: string;
|
||||
name: string;
|
||||
};
|
||||
|
||||
export type TUpdatePkiCollectionTO = {
|
||||
collectionId: string;
|
||||
projectId: string;
|
||||
name?: string;
|
||||
};
|
||||
|
||||
export type TDeletePkiCollectionDTO = {
|
||||
collectionId: string;
|
||||
projectId: string;
|
||||
};
|
||||
@@ -27,10 +27,12 @@ export {
|
||||
useListWorkspaceCas,
|
||||
useListWorkspaceCertificates,
|
||||
useListWorkspaceGroups,
|
||||
useListWorkspacePkiCollections,
|
||||
useNameWorkspaceSecrets,
|
||||
useRenameWorkspace,
|
||||
useToggleAutoCapitalization,
|
||||
useUpdateIdentityWorkspaceRole,
|
||||
useUpdateUserWorkspaceRole,
|
||||
useUpdateWsEnvironment,
|
||||
useUpgradeProject} from "./queries";
|
||||
useUpgradeProject
|
||||
} from "./queries";
|
||||
|
||||
@@ -2,7 +2,6 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
|
||||
import { apiRequest } from "@app/config/request";
|
||||
|
||||
import { TAlert } from "../alerts/types";
|
||||
import { CaStatus } from "../ca/enums";
|
||||
import { TCertificateAuthority } from "../ca/types";
|
||||
import { TCertificate } from "../certificates/types";
|
||||
@@ -11,6 +10,8 @@ import { identitiesKeys } from "../identities/queries";
|
||||
import { IdentityMembership } from "../identities/types";
|
||||
import { IntegrationAuth } from "../integrationAuth/types";
|
||||
import { TIntegration } from "../integrations/types";
|
||||
import { TPkiAlert } from "../pkiAlerts/types";
|
||||
import { TPkiCollection } from "../pkiCollections/types";
|
||||
import { EncryptedSecret } from "../secrets/types";
|
||||
import { userKeys } from "../users/queries";
|
||||
import { TWorkspaceUser } from "../users/types";
|
||||
@@ -64,7 +65,9 @@ export const workspaceKeys = {
|
||||
offset: number;
|
||||
limit: number;
|
||||
}) => [...workspaceKeys.forWorkspaceCertificates(slug), { offset, limit }] as const,
|
||||
getWorkspaceAlerts: (workspaceId: string) => [{ workspaceId }, "workspace-alerts"] as const
|
||||
getWorkspacePkiAlerts: (workspaceId: string) => [{ workspaceId }, "workspace-alerts"] as const,
|
||||
getWorkspacePkiCollections: (workspaceId: string) =>
|
||||
[{ workspaceId }, "workspace-pki-collections"] as const
|
||||
};
|
||||
|
||||
const fetchWorkspaceById = async (workspaceId: string) => {
|
||||
@@ -606,14 +609,32 @@ export const useListWorkspaceCertificates = ({
|
||||
|
||||
export const useListWorkspaceAlerts = ({ workspaceId }: { workspaceId: string }) => {
|
||||
return useQuery({
|
||||
queryKey: workspaceKeys.getWorkspaceAlerts(workspaceId),
|
||||
queryKey: workspaceKeys.getWorkspacePkiAlerts(workspaceId),
|
||||
queryFn: async () => {
|
||||
const {
|
||||
data: { alerts }
|
||||
} = await apiRequest.get<{ alerts: TAlert[] }>(`/api/v2/workspace/${workspaceId}/alerts`);
|
||||
} = await apiRequest.get<{ alerts: TPkiAlert[] }>(
|
||||
`/api/v2/workspace/${workspaceId}/pki-alerts`
|
||||
);
|
||||
|
||||
return { alerts };
|
||||
},
|
||||
enabled: Boolean(workspaceId)
|
||||
});
|
||||
};
|
||||
|
||||
export const useListWorkspacePkiCollections = ({ workspaceId }: { workspaceId: string }) => {
|
||||
return useQuery({
|
||||
queryKey: workspaceKeys.getWorkspacePkiCollections(workspaceId),
|
||||
queryFn: async () => {
|
||||
const {
|
||||
data: { collections }
|
||||
} = await apiRequest.get<{ collections: TPkiCollection[] }>(
|
||||
`/api/v2/workspace/${workspaceId}/pki-collections`
|
||||
);
|
||||
|
||||
return { collections };
|
||||
},
|
||||
enabled: Boolean(workspaceId)
|
||||
});
|
||||
};
|
||||
|
||||
@@ -2,12 +2,12 @@ import { Tab, TabList, TabPanel, Tabs } from "@app/components/v2";
|
||||
import { ProjectPermissionActions, ProjectPermissionSub } from "@app/context";
|
||||
import { withProjectPermission } from "@app/hoc";
|
||||
|
||||
import { AlertsTab,CaTab, CertificatesTab } from "./components";
|
||||
import { AlertsTab, CaTab, CertificatesTab } from "./components";
|
||||
|
||||
enum TabSections {
|
||||
Ca = "certificate-authorities",
|
||||
Certificates = "certificates",
|
||||
Alerts = "alerts"
|
||||
Alerting = "alerting"
|
||||
}
|
||||
|
||||
export const CertificatesPage = withProjectPermission(
|
||||
@@ -20,7 +20,7 @@ export const CertificatesPage = withProjectPermission(
|
||||
<TabList>
|
||||
<Tab value={TabSections.Certificates}>Certificates</Tab>
|
||||
<Tab value={TabSections.Ca}>Certificate Authorities</Tab>
|
||||
<Tab value={TabSections.Alerts}>Alerting</Tab>
|
||||
<Tab value={TabSections.Alerting}>Alerting</Tab>
|
||||
</TabList>
|
||||
<TabPanel value={TabSections.Certificates}>
|
||||
<CertificatesTab />
|
||||
@@ -28,7 +28,7 @@ export const CertificatesPage = withProjectPermission(
|
||||
<TabPanel value={TabSections.Ca}>
|
||||
<CaTab />
|
||||
</TabPanel>
|
||||
<TabPanel value={TabSections.Alerts}>
|
||||
<TabPanel value={TabSections.Alerting}>
|
||||
<AlertsTab />
|
||||
</TabPanel>
|
||||
</Tabs>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { motion } from "framer-motion";
|
||||
|
||||
import { AlertsSection } from "./components";
|
||||
import { AlertsSection,PkiCollectionSection } from "./components";
|
||||
|
||||
export const AlertsTab = () => {
|
||||
return (
|
||||
@@ -11,6 +11,7 @@ export const AlertsTab = () => {
|
||||
animate={{ opacity: 1, translateX: 0 }}
|
||||
exit={{ opacity: 0, translateX: 30 }}
|
||||
>
|
||||
<PkiCollectionSection />
|
||||
<AlertsSection />
|
||||
</motion.div>
|
||||
);
|
||||
|
||||
@@ -4,15 +4,53 @@ import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { z } from "zod";
|
||||
|
||||
import { createNotification } from "@app/components/notifications";
|
||||
import { Button, FormControl, Input, Modal, ModalContent } from "@app/components/v2";
|
||||
import {
|
||||
Button,
|
||||
FormControl,
|
||||
Input,
|
||||
Modal,
|
||||
ModalContent,
|
||||
Select,
|
||||
SelectItem,
|
||||
TextArea} from "@app/components/v2";
|
||||
import { useWorkspace } from "@app/context";
|
||||
import { useCreateAlert, useGetAlertById,useUpdateAlert } from "@app/hooks/api";
|
||||
import {
|
||||
useCreateAlert,
|
||||
useGetAlertById,
|
||||
useListWorkspacePkiCollections,
|
||||
useUpdateAlert} from "@app/hooks/api";
|
||||
import { UsePopUpState } from "@app/hooks/usePopUp";
|
||||
|
||||
enum TimeUnit {
|
||||
DAY = "days",
|
||||
WEEK = "weeks",
|
||||
MONTH = "months",
|
||||
YEAR = "years"
|
||||
}
|
||||
|
||||
const schema = z.object({
|
||||
name: z.string().trim().min(1)
|
||||
name: z.string().trim().min(1),
|
||||
pkiCollectionId: z.string(),
|
||||
alertBefore: z.string(),
|
||||
alertUnit: z.nativeEnum(TimeUnit),
|
||||
emails: z.string().trim()
|
||||
});
|
||||
|
||||
const convertToDays = (unit: TimeUnit, value: number) => {
|
||||
switch (unit) {
|
||||
case TimeUnit.DAY:
|
||||
return value;
|
||||
case TimeUnit.WEEK:
|
||||
return value * 7;
|
||||
case TimeUnit.MONTH:
|
||||
return value * 30;
|
||||
case TimeUnit.YEAR:
|
||||
return value * 365;
|
||||
default:
|
||||
throw new Error(`Unknown time unit: ${unit}`);
|
||||
}
|
||||
};
|
||||
|
||||
export type FormData = z.infer<typeof schema>;
|
||||
|
||||
type Props = {
|
||||
@@ -28,6 +66,10 @@ export const AlertModal = ({ popUp, handlePopUpToggle }: Props) => {
|
||||
(popUp?.alert?.data as { alertId: string })?.alertId || ""
|
||||
);
|
||||
|
||||
const { data: pkiCollections } = useListWorkspacePkiCollections({
|
||||
workspaceId: projectId
|
||||
});
|
||||
|
||||
const { mutateAsync: createAlert } = useCreateAlert();
|
||||
const { mutateAsync: updateAlert } = useUpdateAlert();
|
||||
|
||||
@@ -37,13 +79,20 @@ export const AlertModal = ({ popUp, handlePopUpToggle }: Props) => {
|
||||
reset,
|
||||
formState: { isSubmitting }
|
||||
} = useForm<FormData>({
|
||||
resolver: zodResolver(schema)
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: {
|
||||
alertUnit: TimeUnit.DAY
|
||||
}
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (alert) {
|
||||
reset({
|
||||
name: alert.name
|
||||
name: alert.name,
|
||||
pkiCollectionId: alert.pkiCollectionId,
|
||||
alertBefore: alert.alertBeforeDays.toString(),
|
||||
alertUnit: TimeUnit.DAY,
|
||||
emails: alert.recipientEmails
|
||||
});
|
||||
} else {
|
||||
reset({
|
||||
@@ -52,26 +101,41 @@ export const AlertModal = ({ popUp, handlePopUpToggle }: Props) => {
|
||||
}
|
||||
}, [alert]);
|
||||
|
||||
const onFormSubmit = async ({ name }: FormData) => {
|
||||
const onFormSubmit = async ({
|
||||
name,
|
||||
pkiCollectionId,
|
||||
alertBefore,
|
||||
alertUnit,
|
||||
emails
|
||||
}: FormData) => {
|
||||
try {
|
||||
if (!projectId) return;
|
||||
|
||||
const emailArray = emails
|
||||
.split(",")
|
||||
.map((email) => email.trim())
|
||||
.filter((email) => email.length > 0);
|
||||
|
||||
const alertBeforeDays = convertToDays(alertUnit, Number(alertBefore));
|
||||
|
||||
if (alert) {
|
||||
// update
|
||||
await updateAlert({
|
||||
alertId: alert.id,
|
||||
pkiCollectionId,
|
||||
name,
|
||||
projectId,
|
||||
alertBeforeDays: 3,
|
||||
emails: ["test"]
|
||||
alertBeforeDays,
|
||||
emails: emailArray
|
||||
});
|
||||
} else {
|
||||
// create
|
||||
await createAlert({
|
||||
name,
|
||||
projectId,
|
||||
alertBeforeDays: 3,
|
||||
emails: ["test"]
|
||||
pkiCollectionId,
|
||||
alertBeforeDays,
|
||||
emails: emailArray
|
||||
});
|
||||
}
|
||||
|
||||
@@ -107,11 +171,104 @@ export const AlertModal = ({ popUp, handlePopUpToggle }: Props) => {
|
||||
defaultValue=""
|
||||
name="name"
|
||||
render={({ field, fieldState: { error } }) => (
|
||||
<FormControl label="Name" isError={Boolean(error)} errorText={error?.message}>
|
||||
<FormControl
|
||||
label="Name"
|
||||
isError={Boolean(error)}
|
||||
errorText={error?.message}
|
||||
isRequired
|
||||
>
|
||||
<Input {...field} placeholder="My Alert" />
|
||||
</FormControl>
|
||||
)}
|
||||
/>
|
||||
<Controller
|
||||
control={control}
|
||||
name="pkiCollectionId"
|
||||
defaultValue=""
|
||||
render={({ field: { onChange, ...field }, fieldState: { error } }) => (
|
||||
<FormControl
|
||||
label="PKI Collection"
|
||||
errorText={error?.message}
|
||||
isError={Boolean(error)}
|
||||
isRequired
|
||||
>
|
||||
<Select
|
||||
defaultValue={field.value}
|
||||
{...field}
|
||||
onValueChange={(e) => onChange(e)}
|
||||
className="w-full"
|
||||
>
|
||||
{(pkiCollections?.collections || []).map(({ id, name }) => (
|
||||
<SelectItem value={id} key={`project-${id}`}>
|
||||
{name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</Select>
|
||||
</FormControl>
|
||||
)}
|
||||
/>
|
||||
<div className="flex items-center">
|
||||
<Controller
|
||||
control={control}
|
||||
defaultValue=""
|
||||
name="alertBefore"
|
||||
render={({ field, fieldState: { error } }) => (
|
||||
<FormControl
|
||||
label="Alert Before"
|
||||
isError={Boolean(error)}
|
||||
errorText={error?.message}
|
||||
className="w-full"
|
||||
isRequired
|
||||
>
|
||||
<Input {...field} placeholder="5" type="number" min={1} />
|
||||
</FormControl>
|
||||
)}
|
||||
/>
|
||||
<Controller
|
||||
control={control}
|
||||
name="alertUnit"
|
||||
defaultValue={TimeUnit.YEAR}
|
||||
render={({ field: { onChange, ...field }, fieldState: { error } }) => (
|
||||
<FormControl
|
||||
className="ml-4"
|
||||
label="Alert Unit"
|
||||
errorText={error?.message}
|
||||
isError={Boolean(error)}
|
||||
>
|
||||
<Select
|
||||
defaultValue={field.value}
|
||||
{...field}
|
||||
onValueChange={(e) => onChange(e)}
|
||||
className="w-48"
|
||||
>
|
||||
<SelectItem value={TimeUnit.DAY}>Days</SelectItem>
|
||||
<SelectItem value={TimeUnit.WEEK}>Weeks</SelectItem>
|
||||
<SelectItem value={TimeUnit.MONTH}>Months</SelectItem>
|
||||
<SelectItem value={TimeUnit.YEAR}>Years</SelectItem>
|
||||
</Select>
|
||||
</FormControl>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
<Controller
|
||||
control={control}
|
||||
defaultValue=""
|
||||
name="emails"
|
||||
render={({ field, fieldState: { error } }) => (
|
||||
<FormControl
|
||||
label="Recipient Email(s)"
|
||||
isError={Boolean(error)}
|
||||
errorText={error?.message}
|
||||
isRequired
|
||||
>
|
||||
<TextArea
|
||||
{...field}
|
||||
placeholder="aturing@gmail.com, alovelace@gmail.com, ..."
|
||||
reSize="none"
|
||||
/>
|
||||
</FormControl>
|
||||
)}
|
||||
/>
|
||||
<div className="flex items-center">
|
||||
<Button
|
||||
className="mr-4"
|
||||
@@ -120,7 +277,7 @@ export const AlertModal = ({ popUp, handlePopUpToggle }: Props) => {
|
||||
isLoading={isSubmitting}
|
||||
isDisabled={isSubmitting}
|
||||
>
|
||||
Create
|
||||
{alert ? "Update" : "Create"}
|
||||
</Button>
|
||||
<Button colorSchema="secondary" variant="plain">
|
||||
Cancel
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
import { faEllipsis } from "@fortawesome/free-solid-svg-icons";
|
||||
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
|
||||
import { ProjectPermissionCan } from "@app/components/permissions";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
Td,
|
||||
Tr
|
||||
} from "@app/components/v2";
|
||||
import { ProjectPermissionActions, ProjectPermissionSub } from "@app/context";
|
||||
import { useGetPkiCollectionById } from "@app/hooks/api";
|
||||
import { TPkiAlert } from "@app/hooks/api/pkiAlerts/types";
|
||||
import { UsePopUpState } from "@app/hooks/usePopUp";
|
||||
|
||||
type Props = {
|
||||
alert: TPkiAlert;
|
||||
handlePopUpOpen: (popUpName: keyof UsePopUpState<["alert", "deleteAlert"]>, data?: {}) => void;
|
||||
};
|
||||
|
||||
export const AlertRow = ({ alert, handlePopUpOpen }: Props) => {
|
||||
const { data: pkiCollection } = useGetPkiCollectionById(alert.pkiCollectionId || "");
|
||||
return (
|
||||
<Tr className="h-10" key={`alert-${alert.id}`}>
|
||||
<Td>{alert.name}</Td>
|
||||
<Td>{alert.alertBeforeDays}</Td>
|
||||
<Td>{pkiCollection ? pkiCollection.name : "-"}</Td>
|
||||
<Td>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild className="rounded-lg">
|
||||
<div className="hover:text-primary-400 data-[state=open]:text-primary-400">
|
||||
<FontAwesomeIcon size="sm" icon={faEllipsis} />
|
||||
</div>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="start" className="p-1">
|
||||
<ProjectPermissionCan
|
||||
I={ProjectPermissionActions.Edit}
|
||||
a={ProjectPermissionSub.PkiAlerts}
|
||||
>
|
||||
{(isAllowed) => (
|
||||
<DropdownMenuItem
|
||||
className={twMerge(
|
||||
!isAllowed && "pointer-events-none cursor-not-allowed opacity-50"
|
||||
)}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
handlePopUpOpen("alert", {
|
||||
alertId: alert.id
|
||||
});
|
||||
}}
|
||||
disabled={!isAllowed}
|
||||
>
|
||||
Edit Alert
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
</ProjectPermissionCan>
|
||||
<ProjectPermissionCan
|
||||
I={ProjectPermissionActions.Delete}
|
||||
a={ProjectPermissionSub.PkiAlerts}
|
||||
>
|
||||
{(isAllowed) => (
|
||||
<DropdownMenuItem
|
||||
className={twMerge(
|
||||
isAllowed
|
||||
? "hover:!bg-red-500 hover:!text-white"
|
||||
: "pointer-events-none cursor-not-allowed opacity-50"
|
||||
)}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
handlePopUpOpen("deleteAlert", {
|
||||
alertId: alert.id,
|
||||
name: alert.name
|
||||
});
|
||||
}}
|
||||
disabled={!isAllowed}
|
||||
>
|
||||
Delete Alert
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
</ProjectPermissionCan>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</Td>
|
||||
</Tr>
|
||||
);
|
||||
};
|
||||
@@ -49,7 +49,10 @@ export const AlertsSection = () => {
|
||||
<div className="mb-6 rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4">
|
||||
<div className="mb-4 flex justify-between">
|
||||
<p className="text-xl font-semibold text-mineshaft-100">Alerts</p>
|
||||
<ProjectPermissionCan I={ProjectPermissionActions.Create} a={ProjectPermissionSub.Alerts}>
|
||||
<ProjectPermissionCan
|
||||
I={ProjectPermissionActions.Create}
|
||||
a={ProjectPermissionSub.PkiAlerts}
|
||||
>
|
||||
{(isAllowed) => (
|
||||
<Button
|
||||
colorSchema="primary"
|
||||
@@ -58,7 +61,7 @@ export const AlertsSection = () => {
|
||||
onClick={() => handlePopUpOpen("alert")}
|
||||
isDisabled={!isAllowed}
|
||||
>
|
||||
Create Alert
|
||||
Create
|
||||
</Button>
|
||||
)}
|
||||
</ProjectPermissionCan>
|
||||
|
||||
@@ -1,27 +1,21 @@
|
||||
import { faEllipsis, faExclamationCircle } from "@fortawesome/free-solid-svg-icons";
|
||||
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
import { faExclamationCircle } from "@fortawesome/free-solid-svg-icons";
|
||||
|
||||
import { ProjectPermissionCan } from "@app/components/permissions";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
EmptyState,
|
||||
Table,
|
||||
TableContainer,
|
||||
TableSkeleton,
|
||||
TBody,
|
||||
Td,
|
||||
Th,
|
||||
THead,
|
||||
Tr
|
||||
} from "@app/components/v2";
|
||||
import { ProjectPermissionActions, ProjectPermissionSub , useWorkspace } from "@app/context";
|
||||
import { useWorkspace } from "@app/context";
|
||||
import { useListWorkspaceAlerts } from "@app/hooks/api";
|
||||
import { UsePopUpState } from "@app/hooks/usePopUp";
|
||||
|
||||
import { AlertRow } from "./AlertRow";
|
||||
|
||||
type Props = {
|
||||
handlePopUpOpen: (popUpName: keyof UsePopUpState<["alert", "deleteAlert"]>, data?: {}) => void;
|
||||
};
|
||||
@@ -35,91 +29,33 @@ export const AlertsTable = ({ handlePopUpOpen }: Props) => {
|
||||
});
|
||||
|
||||
return (
|
||||
<div>
|
||||
<TableContainer>
|
||||
<Table>
|
||||
<THead>
|
||||
<Tr>
|
||||
<Th>Name</Th>
|
||||
<Th>Status</Th>
|
||||
<Th>Valid Until</Th>
|
||||
<Th className="w-5" />
|
||||
</Tr>
|
||||
</THead>
|
||||
<TBody>
|
||||
{isLoading && <TableSkeleton columns={4} innerKey="project-alerts" />}
|
||||
{!isLoading &&
|
||||
data?.alerts.map((alert) => {
|
||||
return (
|
||||
<Tr className="h-10" key={`alert-${alert.id}`}>
|
||||
<Td>{alert.name}</Td>
|
||||
<Td>Test 2</Td>
|
||||
<Td>Test 3</Td>
|
||||
<Td>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild className="rounded-lg">
|
||||
<div className="hover:text-primary-400 data-[state=open]:text-primary-400">
|
||||
<FontAwesomeIcon size="sm" icon={faEllipsis} />
|
||||
</div>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="start" className="p-1">
|
||||
<ProjectPermissionCan
|
||||
I={ProjectPermissionActions.Edit}
|
||||
a={ProjectPermissionSub.Alerts}
|
||||
>
|
||||
{(isAllowed) => (
|
||||
<DropdownMenuItem
|
||||
className={twMerge(
|
||||
!isAllowed && "pointer-events-none cursor-not-allowed opacity-50"
|
||||
)}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
handlePopUpOpen("alert", {
|
||||
alertId: alert.id
|
||||
});
|
||||
}}
|
||||
disabled={!isAllowed}
|
||||
>
|
||||
Edit Alert
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
</ProjectPermissionCan>
|
||||
<ProjectPermissionCan
|
||||
I={ProjectPermissionActions.Delete}
|
||||
a={ProjectPermissionSub.Alerts}
|
||||
>
|
||||
{(isAllowed) => (
|
||||
<DropdownMenuItem
|
||||
className={twMerge(
|
||||
isAllowed
|
||||
? "hover:!bg-red-500 hover:!text-white"
|
||||
: "pointer-events-none cursor-not-allowed opacity-50"
|
||||
)}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
handlePopUpOpen("deleteAlert", {
|
||||
alertId: alert.id,
|
||||
name: alert.name
|
||||
});
|
||||
}}
|
||||
disabled={!isAllowed}
|
||||
>
|
||||
Delete Alert
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
</ProjectPermissionCan>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</Td>
|
||||
</Tr>
|
||||
);
|
||||
})}
|
||||
</TBody>
|
||||
</Table>
|
||||
{!isLoading && !data?.alerts?.length && (
|
||||
<EmptyState title="No alerts have been created" icon={faExclamationCircle} />
|
||||
)}
|
||||
</TableContainer>
|
||||
</div>
|
||||
<TableContainer>
|
||||
<Table>
|
||||
<THead>
|
||||
<Tr>
|
||||
<Th>Alert Name</Th>
|
||||
<Th>Alert Before Days</Th>
|
||||
<Th>Bound PKI Collection</Th>
|
||||
<Th className="w-5" />
|
||||
</Tr>
|
||||
</THead>
|
||||
<TBody>
|
||||
{isLoading && <TableSkeleton columns={4} innerKey="project-alerts" />}
|
||||
{!isLoading &&
|
||||
data?.alerts.map((alert) => {
|
||||
return (
|
||||
<AlertRow
|
||||
key={`alert-${alert.id}`}
|
||||
alert={alert}
|
||||
handlePopUpOpen={handlePopUpOpen}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</TBody>
|
||||
</Table>
|
||||
{!isLoading && !data?.alerts?.length && (
|
||||
<EmptyState title="No alerts have been created" icon={faExclamationCircle} />
|
||||
)}
|
||||
</TableContainer>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
import { useEffect } from "react";
|
||||
import { Controller, useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { z } from "zod";
|
||||
|
||||
import { createNotification } from "@app/components/notifications";
|
||||
import { Button, FormControl, Input, Modal, ModalContent } from "@app/components/v2";
|
||||
import { useWorkspace } from "@app/context";
|
||||
import {
|
||||
useCreatePkiCollection,
|
||||
useGetPkiCollectionById,
|
||||
useUpdatePkiCollection
|
||||
} from "@app/hooks/api";
|
||||
import { UsePopUpState } from "@app/hooks/usePopUp";
|
||||
|
||||
const schema = z.object({
|
||||
name: z.string().trim().min(1)
|
||||
});
|
||||
|
||||
export type FormData = z.infer<typeof schema>;
|
||||
|
||||
type Props = {
|
||||
popUp: UsePopUpState<["pkiCollection"]>;
|
||||
handlePopUpToggle: (popUpName: keyof UsePopUpState<["pkiCollection"]>, state?: boolean) => void;
|
||||
};
|
||||
|
||||
export const PkiCollectionModal = ({ popUp, handlePopUpToggle }: Props) => {
|
||||
const { currentWorkspace } = useWorkspace();
|
||||
const projectId = currentWorkspace?.id || "";
|
||||
|
||||
const { data: pkiCollection } = useGetPkiCollectionById(
|
||||
(popUp?.pkiCollection?.data as { collectionId: string })?.collectionId || ""
|
||||
);
|
||||
|
||||
const { mutateAsync: createPkiCollection } = useCreatePkiCollection();
|
||||
const { mutateAsync: updatePkiCollection } = useUpdatePkiCollection();
|
||||
|
||||
const {
|
||||
control,
|
||||
handleSubmit,
|
||||
reset,
|
||||
formState: { isSubmitting }
|
||||
} = useForm<FormData>({
|
||||
resolver: zodResolver(schema)
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (pkiCollection) {
|
||||
reset({
|
||||
name: pkiCollection.name
|
||||
});
|
||||
} else {
|
||||
reset({
|
||||
name: ""
|
||||
});
|
||||
}
|
||||
}, [pkiCollection]);
|
||||
|
||||
const onFormSubmit = async ({ name }: FormData) => {
|
||||
try {
|
||||
if (!projectId) return;
|
||||
|
||||
if (pkiCollection) {
|
||||
// update
|
||||
await updatePkiCollection({
|
||||
collectionId: pkiCollection.id,
|
||||
name,
|
||||
projectId
|
||||
});
|
||||
} else {
|
||||
// create
|
||||
await createPkiCollection({
|
||||
name,
|
||||
projectId
|
||||
});
|
||||
}
|
||||
|
||||
handlePopUpToggle("pkiCollection", false);
|
||||
|
||||
reset();
|
||||
|
||||
createNotification({
|
||||
text: `Successfully ${pkiCollection ? "updated" : "created"} PKI collection`,
|
||||
type: "success"
|
||||
});
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
createNotification({
|
||||
text: `Failed to ${pkiCollection ? "updated" : "created"} PKI collection`,
|
||||
type: "error"
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal
|
||||
isOpen={popUp?.pkiCollection?.isOpen}
|
||||
onOpenChange={(isOpen) => {
|
||||
handlePopUpToggle("pkiCollection", isOpen);
|
||||
reset();
|
||||
}}
|
||||
>
|
||||
<ModalContent title={`${pkiCollection ? "Edit" : "Create"} PKI Collection`}>
|
||||
<form onSubmit={handleSubmit(onFormSubmit)}>
|
||||
<Controller
|
||||
control={control}
|
||||
defaultValue=""
|
||||
name="name"
|
||||
render={({ field, fieldState: { error } }) => (
|
||||
<FormControl
|
||||
label="Name"
|
||||
isError={Boolean(error)}
|
||||
errorText={error?.message}
|
||||
isRequired
|
||||
>
|
||||
<Input {...field} placeholder="My Certificate Collection" />
|
||||
</FormControl>
|
||||
)}
|
||||
/>
|
||||
<div className="flex items-center">
|
||||
<Button
|
||||
className="mr-4"
|
||||
size="sm"
|
||||
type="submit"
|
||||
isLoading={isSubmitting}
|
||||
isDisabled={isSubmitting}
|
||||
>
|
||||
Create
|
||||
</Button>
|
||||
<Button colorSchema="secondary" variant="plain">
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</ModalContent>
|
||||
</Modal>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,86 @@
|
||||
import { faPlus } from "@fortawesome/free-solid-svg-icons";
|
||||
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
||||
|
||||
import { createNotification } from "@app/components/notifications";
|
||||
import { ProjectPermissionCan } from "@app/components/permissions";
|
||||
import { Button, DeleteActionModal } from "@app/components/v2";
|
||||
import { ProjectPermissionActions, ProjectPermissionSub, useWorkspace } from "@app/context";
|
||||
import { useDeletePkiCollection } from "@app/hooks/api";
|
||||
import { usePopUp } from "@app/hooks/usePopUp";
|
||||
|
||||
import { PkiCollectionModal } from "./PkiCollectionModal";
|
||||
import { PkiCollectionTable } from "./PkiCollectionTable";
|
||||
|
||||
export const PkiCollectionSection = () => {
|
||||
const { currentWorkspace } = useWorkspace();
|
||||
const projectId = currentWorkspace?.id || "";
|
||||
const { mutateAsync: deletePkiCollection } = useDeletePkiCollection();
|
||||
|
||||
const { popUp, handlePopUpOpen, handlePopUpClose, handlePopUpToggle } = usePopUp([
|
||||
"pkiCollection",
|
||||
"deletePkiCollection"
|
||||
] as const);
|
||||
|
||||
const onRemovePkiCollectionSubmit = async (collectionId: string) => {
|
||||
try {
|
||||
if (!projectId) return;
|
||||
|
||||
await deletePkiCollection({
|
||||
collectionId,
|
||||
projectId
|
||||
});
|
||||
|
||||
await createNotification({
|
||||
text: "Successfully deleted PKI collection",
|
||||
type: "success"
|
||||
});
|
||||
|
||||
handlePopUpClose("deletePkiCollection");
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
createNotification({
|
||||
text: "Failed to delete PKI collection",
|
||||
type: "error"
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="mb-6 rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4">
|
||||
<div className="mb-4 flex justify-between">
|
||||
<p className="text-xl font-semibold text-mineshaft-100">PKI Collection</p>
|
||||
<ProjectPermissionCan
|
||||
I={ProjectPermissionActions.Create}
|
||||
a={ProjectPermissionSub.PkiCollections}
|
||||
>
|
||||
{(isAllowed) => (
|
||||
<Button
|
||||
colorSchema="primary"
|
||||
type="submit"
|
||||
leftIcon={<FontAwesomeIcon icon={faPlus} />}
|
||||
onClick={() => handlePopUpOpen("pkiCollection")}
|
||||
isDisabled={!isAllowed}
|
||||
>
|
||||
Create
|
||||
</Button>
|
||||
)}
|
||||
</ProjectPermissionCan>
|
||||
</div>
|
||||
<PkiCollectionTable handlePopUpOpen={handlePopUpOpen} />
|
||||
<PkiCollectionModal popUp={popUp} handlePopUpToggle={handlePopUpToggle} />
|
||||
<DeleteActionModal
|
||||
isOpen={popUp.deletePkiCollection.isOpen}
|
||||
title={`Are you sure want to remove the alert ${
|
||||
(popUp?.deletePkiCollection?.data as { name: string })?.name || ""
|
||||
} from the project?`}
|
||||
onChange={(isOpen) => handlePopUpToggle("deletePkiCollection", isOpen)}
|
||||
deleteKey="confirm"
|
||||
onDeleteApproved={() =>
|
||||
onRemovePkiCollectionSubmit(
|
||||
(popUp?.deletePkiCollection?.data as { collectionId: string })?.collectionId
|
||||
)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,124 @@
|
||||
import { faBoxesStacked, faEllipsis } from "@fortawesome/free-solid-svg-icons";
|
||||
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
|
||||
import { ProjectPermissionCan } from "@app/components/permissions";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
EmptyState,
|
||||
Table,
|
||||
TableContainer,
|
||||
TableSkeleton,
|
||||
TBody,
|
||||
Td,
|
||||
Th,
|
||||
THead,
|
||||
Tr
|
||||
} from "@app/components/v2";
|
||||
import { ProjectPermissionActions, ProjectPermissionSub, useWorkspace } from "@app/context";
|
||||
import { useListWorkspacePkiCollections } from "@app/hooks/api";
|
||||
import { UsePopUpState } from "@app/hooks/usePopUp";
|
||||
|
||||
type Props = {
|
||||
handlePopUpOpen: (
|
||||
popUpName: keyof UsePopUpState<["pkiCollection", "deletePkiCollection"]>,
|
||||
data?: {}
|
||||
) => void;
|
||||
};
|
||||
|
||||
export const PkiCollectionTable = ({ handlePopUpOpen }: Props) => {
|
||||
const { currentWorkspace } = useWorkspace();
|
||||
const projectId = currentWorkspace?.id || "";
|
||||
|
||||
const { data, isLoading } = useListWorkspacePkiCollections({
|
||||
workspaceId: projectId
|
||||
});
|
||||
|
||||
return (
|
||||
<div>
|
||||
<TableContainer>
|
||||
<Table>
|
||||
<THead>
|
||||
<Tr>
|
||||
<Th>Name</Th>
|
||||
<Th className="w-5" />
|
||||
</Tr>
|
||||
</THead>
|
||||
<TBody>
|
||||
{isLoading && <TableSkeleton columns={2} innerKey="pki-collections" />}
|
||||
{!isLoading &&
|
||||
data?.collections.map((pkiCollection) => {
|
||||
return (
|
||||
<Tr className="h-10" key={`pki-collection-${pkiCollection.id}`}>
|
||||
<Td>{pkiCollection.name}</Td>
|
||||
<Td>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild className="rounded-lg">
|
||||
<div className="hover:text-primary-400 data-[state=open]:text-primary-400">
|
||||
<FontAwesomeIcon size="sm" icon={faEllipsis} />
|
||||
</div>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="start" className="p-1">
|
||||
<ProjectPermissionCan
|
||||
I={ProjectPermissionActions.Edit}
|
||||
a={ProjectPermissionSub.PkiCollections}
|
||||
>
|
||||
{(isAllowed) => (
|
||||
<DropdownMenuItem
|
||||
className={twMerge(
|
||||
!isAllowed && "pointer-events-none cursor-not-allowed opacity-50"
|
||||
)}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
handlePopUpOpen("pkiCollection", {
|
||||
collectionId: pkiCollection.id
|
||||
});
|
||||
}}
|
||||
disabled={!isAllowed}
|
||||
>
|
||||
Edit PKI Collection
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
</ProjectPermissionCan>
|
||||
<ProjectPermissionCan
|
||||
I={ProjectPermissionActions.Delete}
|
||||
a={ProjectPermissionSub.PkiCollections}
|
||||
>
|
||||
{(isAllowed) => (
|
||||
<DropdownMenuItem
|
||||
className={twMerge(
|
||||
isAllowed
|
||||
? "hover:!bg-red-500 hover:!text-white"
|
||||
: "pointer-events-none cursor-not-allowed opacity-50"
|
||||
)}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
handlePopUpOpen("deletePkiCollection", {
|
||||
collectionId: pkiCollection.id,
|
||||
name: pkiCollection.name
|
||||
});
|
||||
}}
|
||||
disabled={!isAllowed}
|
||||
>
|
||||
Delete PKI Collection
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
</ProjectPermissionCan>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</Td>
|
||||
</Tr>
|
||||
);
|
||||
})}
|
||||
</TBody>
|
||||
</Table>
|
||||
{!isLoading && !data?.collections?.length && (
|
||||
<EmptyState title="No collections have been created" icon={faBoxesStacked} />
|
||||
)}
|
||||
</TableContainer>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -1 +1,2 @@
|
||||
export { AlertsSection } from "./AlertsSection";
|
||||
export { PkiCollectionSection } from "./PkiCollectionSection";
|
||||
|
||||
Reference in New Issue
Block a user