refactor: streamline async logic and notification handling across various settings and integration components

This commit is contained in:
Victor Santos
2025-11-03 15:11:10 -03:00
parent 3aeee8d552
commit c005f8a0fe
33 changed files with 709 additions and 1061 deletions

View File

@@ -39,40 +39,33 @@ export const AuditLogsRetentionSection = () => {
if (!currentProject) return null;
const handleAuditLogsRetentionSubmit = async ({ auditLogsRetentionDays }: TForm) => {
try {
if (!subscription?.auditLogs) {
handlePopUpOpen("upgradePlan", {
description:
"You can only configure audit logs retention if you switch to Infisical's Pro plan."
});
return;
}
if (subscription && auditLogsRetentionDays > subscription?.auditLogsRetentionDays) {
handlePopUpOpen("upgradePlan", {
description:
"To update your audit logs retention period to a higher value, switch to Infisical's Pro plan."
});
return;
}
await updateAuditLogsRetention({
auditLogsRetentionDays,
projectSlug: currentProject.slug
if (!subscription?.auditLogs) {
handlePopUpOpen("upgradePlan", {
description:
"You can only configure audit logs retention if you switch to Infisical's Pro plan."
});
createNotification({
text: "Successfully updated audit logs retention period",
type: "success"
});
} catch {
createNotification({
text: "Failed updating audit logs retention period",
type: "error"
});
return;
}
if (subscription && auditLogsRetentionDays > subscription?.auditLogsRetentionDays) {
handlePopUpOpen("upgradePlan", {
description:
"To update your audit logs retention period to a higher value, switch to Infisical's Pro plan."
});
return;
}
await updateAuditLogsRetention({
auditLogsRetentionDays,
projectSlug: currentProject.slug
});
createNotification({
text: "Successfully updated audit logs retention period",
type: "success"
});
};
// render only for dedicated/self-hosted instances of Infisical

View File

@@ -2,7 +2,6 @@ import { faHome } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { Link, useNavigate, useParams } from "@tanstack/react-router";
import { createNotification } from "@app/components/notifications";
import { OrgPermissionCan } from "@app/components/permissions";
import { RequestProjectAccessModal } from "@app/components/projects";
import { AccessRestrictedBanner, Button } from "@app/components/v2";
@@ -35,19 +34,12 @@ export const ProjectAccessError = () => {
const handleAccessProject = async () => {
if (!project) return;
try {
await orgAdminAccessProject.mutateAsync({
projectId: project.id
});
await navigate({
to: "."
});
} catch {
createNotification({
text: "Failed to access project",
type: "error"
});
}
await orgAdminAccessProject.mutateAsync({
projectId: project.id
});
await navigate({
to: "."
});
};
return (

View File

@@ -131,52 +131,44 @@ export const ShareSecretForm = ({
emails,
shouldLimitView
}: FormData) => {
try {
const expiresAt = new Date(new Date().getTime() + Number(expiresIn));
const expiresAt = new Date(new Date().getTime() + Number(expiresIn));
const processedEmails = emails ? emails.split(",").map((e) => e.trim()) : undefined;
const processedEmails = emails ? emails.split(",").map((e) => e.trim()) : undefined;
const { id } = await createSharedSecret.mutateAsync({
name,
password,
secretValue: secret,
expiresAt,
expiresAfterViews: shouldLimitView ? Number(viewLimit) : undefined,
accessType,
emails: processedEmails
const { id } = await createSharedSecret.mutateAsync({
name,
password,
secretValue: secret,
expiresAt,
expiresAfterViews: shouldLimitView ? Number(viewLimit) : undefined,
accessType,
emails: processedEmails
});
if (processedEmails && processedEmails.length > 0) {
setSecretLink("");
createNotification({
text: `Shared secret link emailed to ${processedEmails.length} user(s).`,
type: "success"
});
if (processedEmails && processedEmails.length > 0) {
setSecretLink("");
createNotification({
text: `Shared secret link emailed to ${processedEmails.length} user(s).`,
type: "success"
});
} else {
const link = new URL(`${window.location.origin}/shared/secret/${id}`);
if (subOrganization) {
link.searchParams.set("subOrganization", subOrganization);
}
setSecretLink(link.toString());
navigator.clipboard.writeText(link.toString());
setCopyTextSecret("secret");
createNotification({
text: "Shared secret link copied to clipboard.",
type: "success"
});
} else {
const link = new URL(`${window.location.origin}/shared/secret/${id}`);
if (subOrganization) {
link.searchParams.set("subOrganization", subOrganization);
}
reset();
} catch (error) {
console.error(error);
setSecretLink(link.toString());
navigator.clipboard.writeText(link.toString());
setCopyTextSecret("secret");
createNotification({
text: "Failed to create a shared secret.",
type: "error"
text: "Shared secret link copied to clipboard.",
type: "success"
});
}
reset();
};
if (secretLink === null)

View File

@@ -140,22 +140,15 @@ export const RollbackPreviewTab = (): JSX.Element => {
);
const handleRollback = async (): Promise<void> => {
try {
await rollback(message);
await rollback(message);
createNotification({
type: "success",
text: "Rollback completed successfully"
});
createNotification({
type: "success",
text: "Rollback completed successfully"
});
handlePopUpClose("rollbackConfirm");
goBackToHistory();
} catch (error) {
createNotification({
type: "error",
text: error instanceof Error ? error.message : "Failed to rollback changes"
});
}
handlePopUpClose("rollbackConfirm");
goBackToHistory();
};
const folderChanges: FolderChanges[] = rollbackChangesNested || [];

View File

@@ -53,28 +53,20 @@ export const IntegrationDetailsByIDPage = () => {
const navigate = useNavigate();
const handleIntegrationDelete = async (shouldDeleteIntegrationSecrets: boolean) => {
try {
await deleteIntegration({
id: integrationId,
workspaceId: currentProject.id,
shouldDeleteIntegrationSecrets
});
await deleteIntegration({
id: integrationId,
workspaceId: currentProject.id,
shouldDeleteIntegrationSecrets
});
createNotification({
type: "success",
text: "Deleted integration"
});
createNotification({
type: "success",
text: "Deleted integration"
});
await navigate({
to: `/${ProjectType.SecretManager}/${projectId}/integrations`
});
} catch (err) {
console.log(err);
createNotification({
type: "error",
text: "Failed to delete integration"
});
}
await navigate({
to: `/${ProjectType.SecretManager}/${projectId}/integrations`
});
};
const { popUp, handlePopUpOpen, handlePopUpClose, handlePopUpToggle } = usePopUp([

View File

@@ -488,55 +488,47 @@ export const OverviewPage = () => {
};
const handleSecretCreate = async (env: string, key: string, value: string) => {
try {
// create folder if not existing
if (secretPath !== "/") {
// /hello/world -> [hello","world"]
const pathSegment = secretPath.split("/").filter(Boolean);
const parentPath = `/${pathSegment.slice(0, -1).join("/")}`;
const folderName = pathSegment.at(-1);
const canCreateFolder = permission.can(
ProjectPermissionActions.Create,
subject(ProjectPermissionSub.SecretFolders, {
environment: env,
secretPath: parentPath
})
);
if (folderName && parentPath && canCreateFolder) {
await getOrCreateFolder({
projectId,
path: parentPath,
environment: env,
name: folderName
});
}
// create folder if not existing
if (secretPath !== "/") {
// /hello/world -> [hello","world"]
const pathSegment = secretPath.split("/").filter(Boolean);
const parentPath = `/${pathSegment.slice(0, -1).join("/")}`;
const folderName = pathSegment.at(-1);
const canCreateFolder = permission.can(
ProjectPermissionActions.Create,
subject(ProjectPermissionSub.SecretFolders, {
environment: env,
secretPath: parentPath
})
);
if (folderName && parentPath && canCreateFolder) {
await getOrCreateFolder({
projectId,
path: parentPath,
environment: env,
name: folderName
});
}
const result = await createSecretV3({
environment: env,
projectId,
secretPath,
secretKey: key,
secretValue: value,
secretComment: "",
type: SecretType.Shared
});
}
const result = await createSecretV3({
environment: env,
projectId,
secretPath,
secretKey: key,
secretValue: value,
secretComment: "",
type: SecretType.Shared
});
if ("approval" in result) {
createNotification({
type: "info",
text: "Requested change has been sent for review"
});
} else {
createNotification({
type: "success",
text: "Successfully created secret"
});
}
} catch (error) {
console.log(error);
if ("approval" in result) {
createNotification({
type: "error",
text: "Failed to create secret"
type: "info",
text: "Requested change has been sent for review"
});
} else {
createNotification({
type: "success",
text: "Successfully created secret"
});
}
};
@@ -565,63 +557,47 @@ export const OverviewPage = () => {
secretValue = undefined;
}
try {
const result = await updateSecretV3({
environment: env,
projectId,
secretPath,
secretKey: key,
secretValue,
type
});
const result = await updateSecretV3({
environment: env,
projectId,
secretPath,
secretKey: key,
secretValue,
type
});
if ("approval" in result) {
createNotification({
type: "info",
text: "Requested change has been sent for review"
});
} else {
createNotification({
type: "success",
text: "Successfully updated secret"
});
}
} catch (error) {
console.log(error);
if ("approval" in result) {
createNotification({
type: "error",
text: "Failed to update secret"
type: "info",
text: "Requested change has been sent for review"
});
} else {
createNotification({
type: "success",
text: "Successfully updated secret"
});
}
};
const handleSecretDelete = async (env: string, key: string, secretId?: string) => {
try {
const result = await deleteSecretV3({
environment: env,
projectId,
secretPath,
secretKey: key,
secretId,
type: SecretType.Shared
});
const result = await deleteSecretV3({
environment: env,
projectId,
secretPath,
secretKey: key,
secretId,
type: SecretType.Shared
});
if ("approval" in result) {
createNotification({
type: "info",
text: "Requested change has been sent for review"
});
} else {
createNotification({
type: "success",
text: "Successfully deleted secret"
});
}
} catch (error) {
console.log(error);
if ("approval" in result) {
createNotification({
type: "error",
text: "Failed to delete secret"
type: "info",
text: "Requested change has been sent for review"
});
} else {
createNotification({
type: "success",
text: "Successfully deleted secret"
});
}
};

View File

@@ -193,19 +193,12 @@ export const CreateSecretForm = ({ secretPath = "/", onClose }: Props) => {
const slugSchema = z.string().trim().toLowerCase().min(1);
const createNewTag = async (slug: string) => {
// TODO: Replace with slugSchema generic
try {
const parsedSlug = slugSchema.parse(slug);
await createWsTag.mutateAsync({
projectId,
tagSlug: parsedSlug,
tagColor: ""
});
} catch {
createNotification({
type: "error",
text: "Failed to create new tag"
});
}
const parsedSlug = slugSchema.parse(slug);
await createWsTag.mutateAsync({
projectId,
tagSlug: parsedSlug,
tagColor: ""
});
};
return (

View File

@@ -77,70 +77,55 @@ export const CreateSecretForm = ({
const slugSchema = z.string().trim().toLowerCase().min(1);
const createNewTag = async (slug: string) => {
// TODO: Replace with slugSchema generic
try {
const parsedSlug = slugSchema.parse(slug);
await createWsTag.mutateAsync({
projectId,
tagSlug: parsedSlug,
tagColor: ""
});
} catch {
createNotification({
type: "error",
text: "Failed to create new tag"
});
}
const parsedSlug = slugSchema.parse(slug);
await createWsTag.mutateAsync({
projectId,
tagSlug: parsedSlug,
tagColor: ""
});
};
const handleFormSubmit = async ({ key, value, tags }: TFormSchema) => {
try {
if (isBatchMode) {
const pendingSecretCreate: PendingSecretCreate = {
id: key,
type: PendingAction.Create,
secretKey: key,
secretValue: value || "",
secretComment: "",
tags: tags?.map((el) => ({ id: el.value, slug: el.label })),
timestamp: Date.now(),
resourceType: "secret"
};
addPendingChange(pendingSecretCreate, {
projectId,
environment,
secretPath
});
closePopUp(PopUpNames.CreateSecretForm);
reset();
return;
}
await createSecretV3({
environment,
projectId,
secretPath,
if (isBatchMode) {
const pendingSecretCreate: PendingSecretCreate = {
id: key,
type: PendingAction.Create,
secretKey: key,
secretValue: value || "",
secretComment: "",
type: SecretType.Shared,
tagIds: tags?.map((el) => el.value)
tags: tags?.map((el) => ({ id: el.value, slug: el.label })),
timestamp: Date.now(),
resourceType: "secret"
};
addPendingChange(pendingSecretCreate, {
projectId,
environment,
secretPath
});
closePopUp(PopUpNames.CreateSecretForm);
reset();
createNotification({
type: isProtectedBranch ? "info" : "success",
text: isProtectedBranch
? "Requested changes have been sent for review"
: "Successfully created secret"
});
} catch (error) {
console.log(error);
createNotification({
type: "error",
text: "Failed to create secret"
});
return;
}
await createSecretV3({
environment,
projectId,
secretPath,
secretKey: key,
secretValue: value || "",
secretComment: "",
type: SecretType.Shared,
tagIds: tags?.map((el) => el.value)
});
closePopUp(PopUpNames.CreateSecretForm);
reset();
createNotification({
type: isProtectedBranch ? "info" : "success",
text: isProtectedBranch
? "Requested changes have been sent for review"
: "Successfully created secret"
});
};
const handlePaste = (e: ClipboardEvent<HTMLInputElement>) => {

View File

@@ -293,174 +293,166 @@ export const SecretListView = ({
isSameTags &&
isSameRecipients;
try {
// personal secret change
let personalAction = false;
if (overrideAction === "deleted") {
await handleSecretOperation("delete", SecretType.Personal, oldKey, {
secretId: orgSecret.idOverride
});
personalAction = true;
} else if (overrideAction && idOverride) {
await handleSecretOperation("update", SecretType.Personal, oldKey, {
value: valueOverride,
newKey: hasKeyChanged ? key : undefined,
secretId: orgSecret.idOverride,
skipMultilineEncoding: modSecret.skipMultilineEncoding
});
personalAction = true;
} else if (overrideAction) {
await handleSecretOperation("create", SecretType.Personal, oldKey, {
value: valueOverride
});
personalAction = true;
}
// personal secret change
let personalAction = false;
if (overrideAction === "deleted") {
await handleSecretOperation("delete", SecretType.Personal, oldKey, {
secretId: orgSecret.idOverride
});
personalAction = true;
} else if (overrideAction && idOverride) {
await handleSecretOperation("update", SecretType.Personal, oldKey, {
value: valueOverride,
newKey: hasKeyChanged ? key : undefined,
secretId: orgSecret.idOverride,
skipMultilineEncoding: modSecret.skipMultilineEncoding
});
personalAction = true;
} else if (overrideAction) {
await handleSecretOperation("create", SecretType.Personal, oldKey, {
value: valueOverride
});
personalAction = true;
}
// shared secret change
if (!isSharedSecUnchanged && !personalAction) {
if (isBatchMode) {
const isEditingPendingCreation = isPending && pendingAction === PendingAction.Create;
// shared secret change
if (!isSharedSecUnchanged && !personalAction) {
if (isBatchMode) {
const isEditingPendingCreation = isPending && pendingAction === PendingAction.Create;
if (isEditingPendingCreation) {
const updatedCreate: PendingSecretCreate = {
id: orgSecret.id,
type: PendingAction.Create,
secretKey: key,
secretValue: value || "",
secretComment: comment || "",
skipMultilineEncoding: modSecret.skipMultilineEncoding || false,
tags: tags?.map((tag) => ({ id: tag.id, slug: tag.name || tag.slug || "" })) || [],
secretMetadata: secretMetadata || [],
timestamp: Date.now(),
resourceType: "secret",
originalKey: oldKey
};
if (isEditingPendingCreation) {
const updatedCreate: PendingSecretCreate = {
id: orgSecret.id,
type: PendingAction.Create,
secretKey: key,
secretValue: value || "",
secretComment: comment || "",
skipMultilineEncoding: modSecret.skipMultilineEncoding || false,
tags: tags?.map((tag) => ({ id: tag.id, slug: tag.name || tag.slug || "" })) || [],
secretMetadata: secretMetadata || [],
timestamp: Date.now(),
resourceType: "secret",
originalKey: oldKey
};
addPendingChange(updatedCreate, {
projectId,
environment,
secretPath
});
} else {
const trueOriginalSecret = getTrueOriginalSecret(
orgSecret,
pendingChangesRef.current.secrets
);
addPendingChange(updatedCreate, {
projectId,
environment,
secretPath
});
} else {
const trueOriginalSecret = getTrueOriginalSecret(
orgSecret,
pendingChangesRef.current.secrets
);
const updateChange: PendingSecretUpdate = {
id: orgSecret.id,
type: PendingAction.Update,
secretKey: trueOriginalSecret.key,
newSecretName: key,
originalValue: trueOriginalSecret.value,
secretValue: value,
originalComment: trueOriginalSecret.comment,
secretComment: comment,
originalSkipMultilineEncoding: trueOriginalSecret.skipMultilineEncoding,
skipMultilineEncoding: modSecret.skipMultilineEncoding,
originalTags:
trueOriginalSecret.tags?.map((tag) => ({ id: tag.id, slug: tag.slug })) || [],
tags: tags?.map((tag) => ({ id: tag.id, slug: tag.name || tag.slug || "" })) || [],
originalSecretMetadata: trueOriginalSecret.secretMetadata || [],
secretMetadata: secretMetadata || [],
timestamp: Date.now(),
resourceType: "secret",
existingSecret: orgSecret
};
const updateChange: PendingSecretUpdate = {
id: orgSecret.id,
type: PendingAction.Update,
secretKey: trueOriginalSecret.key,
newSecretName: key,
originalValue: trueOriginalSecret.value,
secretValue: value,
originalComment: trueOriginalSecret.comment,
secretComment: comment,
originalSkipMultilineEncoding: trueOriginalSecret.skipMultilineEncoding,
skipMultilineEncoding: modSecret.skipMultilineEncoding,
originalTags:
trueOriginalSecret.tags?.map((tag) => ({ id: tag.id, slug: tag.slug })) || [],
tags: tags?.map((tag) => ({ id: tag.id, slug: tag.name || tag.slug || "" })) || [],
originalSecretMetadata: trueOriginalSecret.secretMetadata || [],
secretMetadata: secretMetadata || [],
timestamp: Date.now(),
resourceType: "secret",
existingSecret: orgSecret
};
addPendingChange(updateChange, {
projectId,
environment,
secretPath
});
}
if (!isReminderEvent) {
handlePopUpClose("secretDetail");
}
if (cb) cb();
return;
addPendingChange(updateChange, {
projectId,
environment,
secretPath
});
}
await handleSecretOperation("update", SecretType.Shared, oldKey, {
value,
tags: tagIds,
comment,
reminderRepeatDays,
reminderNote,
reminderRecipients,
secretId: orgSecret.id,
newKey: hasKeyChanged ? key : undefined,
skipMultilineEncoding: modSecret.skipMultilineEncoding,
secretMetadata,
isRotatedSecret: orgSecret.isRotatedSecret,
secretValueHidden
});
if (!isReminderEvent) {
handlePopUpClose("secretDetail");
}
if (cb) cb();
}
queryClient.invalidateQueries({
queryKey: dashboardKeys.getDashboardSecrets({
projectId,
secretPath
})
});
queryClient.invalidateQueries({
queryKey: secretKeys.getProjectSecret({ projectId, environment, secretPath })
});
queryClient.invalidateQueries({
queryKey: secretSnapshotKeys.list({
projectId,
environment,
directory: secretPath
})
});
queryClient.invalidateQueries({
queryKey: secretSnapshotKeys.count({
projectId,
environment,
directory: secretPath
})
});
queryClient.invalidateQueries({
queryKey: commitKeys.count({ projectId, environment, directory: secretPath })
});
queryClient.invalidateQueries({
queryKey: commitKeys.history({
projectId,
environment,
directory: secretPath
})
});
queryClient.invalidateQueries({
queryKey: secretApprovalRequestKeys.count({ projectId })
});
if (!isReminderEvent) {
handlePopUpClose("secretDetail");
return;
}
let successMessage;
if (isReminderEvent) {
successMessage = reminderRepeatDays
? "Successfully saved secret reminder"
: "Successfully deleted secret reminder";
} else {
successMessage = "Successfully saved secrets";
}
createNotification({
type: isProtectedBranch && !personalAction ? "info" : "success",
text:
isProtectedBranch && !personalAction
? "Requested changes have been sent for review"
: successMessage
});
} catch (error) {
console.log(error);
createNotification({
type: "error",
text: "Failed to save secret"
await handleSecretOperation("update", SecretType.Shared, oldKey, {
value,
tags: tagIds,
comment,
reminderRepeatDays,
reminderNote,
reminderRecipients,
secretId: orgSecret.id,
newKey: hasKeyChanged ? key : undefined,
skipMultilineEncoding: modSecret.skipMultilineEncoding,
secretMetadata,
isRotatedSecret: orgSecret.isRotatedSecret,
secretValueHidden
});
if (cb) cb();
}
queryClient.invalidateQueries({
queryKey: dashboardKeys.getDashboardSecrets({
projectId,
secretPath
})
});
queryClient.invalidateQueries({
queryKey: secretKeys.getProjectSecret({ projectId, environment, secretPath })
});
queryClient.invalidateQueries({
queryKey: secretSnapshotKeys.list({
projectId,
environment,
directory: secretPath
})
});
queryClient.invalidateQueries({
queryKey: secretSnapshotKeys.count({
projectId,
environment,
directory: secretPath
})
});
queryClient.invalidateQueries({
queryKey: commitKeys.count({ projectId, environment, directory: secretPath })
});
queryClient.invalidateQueries({
queryKey: commitKeys.history({
projectId,
environment,
directory: secretPath
})
});
queryClient.invalidateQueries({
queryKey: secretApprovalRequestKeys.count({ projectId })
});
if (!isReminderEvent) {
handlePopUpClose("secretDetail");
}
let successMessage;
if (isReminderEvent) {
successMessage = reminderRepeatDays
? "Successfully saved secret reminder"
: "Successfully deleted secret reminder";
} else {
successMessage = "Successfully saved secrets";
}
createNotification({
type: isProtectedBranch && !personalAction ? "info" : "success",
text:
isProtectedBranch && !personalAction
? "Requested changes have been sent for review"
: successMessage
});
},
[environment, secretPath, isProtectedBranch, isBatchMode, projectId, addPendingChange]
);
@@ -488,75 +480,67 @@ export const SecretListView = ({
value,
secretValueHidden
} = popUp.deleteSecret?.data as SecretV3RawSanitized;
try {
if (isBatchMode) {
const deleteChange: PendingSecretDelete = {
id: `${secretId}`,
type: PendingAction.Delete,
secretKey: key,
secretValue: value || "",
timestamp: Date.now(),
resourceType: "secret",
secretValueHidden
};
if (isBatchMode) {
const deleteChange: PendingSecretDelete = {
id: `${secretId}`,
type: PendingAction.Delete,
secretKey: key,
secretValue: value || "",
timestamp: Date.now(),
resourceType: "secret",
secretValueHidden
};
addPendingChange(deleteChange, {
projectId,
environment,
secretPath
});
addPendingChange(deleteChange, {
projectId,
environment,
secretPath
});
handlePopUpClose("deleteSecret");
handlePopUpClose("secretDetail");
return;
}
await handleSecretOperation("delete", SecretType.Shared, key, { secretId });
// wrap this in another function and then reuse
queryClient.invalidateQueries({
queryKey: dashboardKeys.getDashboardSecrets({ projectId, secretPath })
});
queryClient.invalidateQueries({
queryKey: secretKeys.getProjectSecret({ projectId, environment, secretPath })
});
queryClient.invalidateQueries({
queryKey: secretSnapshotKeys.list({
projectId,
environment,
directory: secretPath
})
});
queryClient.invalidateQueries({
queryKey: secretSnapshotKeys.count({
projectId,
environment,
directory: secretPath
})
});
queryClient.invalidateQueries({
queryKey: commitKeys.count({ projectId, environment, directory: secretPath })
});
queryClient.invalidateQueries({
queryKey: commitKeys.history({ projectId, environment, directory: secretPath })
});
queryClient.invalidateQueries({
queryKey: secretApprovalRequestKeys.count({ projectId })
});
handlePopUpClose("deleteSecret");
handlePopUpClose("secretDetail");
createNotification({
type: isProtectedBranch ? "info" : "success",
text: isProtectedBranch
? "Requested changes have been sent for review"
: "Successfully deleted secret"
});
} catch (error) {
console.log(error);
createNotification({
type: "error",
text: "Failed to delete secret"
});
return;
}
await handleSecretOperation("delete", SecretType.Shared, key, { secretId });
// wrap this in another function and then reuse
queryClient.invalidateQueries({
queryKey: dashboardKeys.getDashboardSecrets({ projectId, secretPath })
});
queryClient.invalidateQueries({
queryKey: secretKeys.getProjectSecret({ projectId, environment, secretPath })
});
queryClient.invalidateQueries({
queryKey: secretSnapshotKeys.list({
projectId,
environment,
directory: secretPath
})
});
queryClient.invalidateQueries({
queryKey: secretSnapshotKeys.count({
projectId,
environment,
directory: secretPath
})
});
queryClient.invalidateQueries({
queryKey: commitKeys.count({ projectId, environment, directory: secretPath })
});
queryClient.invalidateQueries({
queryKey: commitKeys.history({ projectId, environment, directory: secretPath })
});
queryClient.invalidateQueries({
queryKey: secretApprovalRequestKeys.count({ projectId })
});
handlePopUpClose("deleteSecret");
handlePopUpClose("secretDetail");
createNotification({
type: isProtectedBranch ? "info" : "success",
text: isProtectedBranch
? "Requested changes have been sent for review"
: "Successfully deleted secret"
});
}, [
(popUp.deleteSecret?.data as SecretV3RawSanitized)?.key,
environment,

View File

@@ -13,26 +13,18 @@ export const AutoCapitalizationSection = () => {
const { mutateAsync } = useUpdateProject();
const handleToggleCapitalizationToggle = async (state: boolean) => {
try {
if (!currentProject?.id) return;
if (!currentProject?.id) return;
await mutateAsync({
projectId: currentProject.id,
autoCapitalization: state
});
await mutateAsync({
projectId: currentProject.id,
autoCapitalization: state
});
const text = `Successfully ${state ? "enabled" : "disabled"} auto capitalization`;
createNotification({
text,
type: "success"
});
} catch (err) {
console.error(err);
createNotification({
text: "Failed to update auto capitalization",
type: "error"
});
}
const text = `Successfully ${state ? "enabled" : "disabled"} auto capitalization`;
createNotification({
text,
type: "success"
});
};
return (

View File

@@ -124,17 +124,13 @@ const LoadBackupModal = ({
return;
}
try {
await loadKmsBackup(backupContent);
createNotification({
text: "Successfully loaded KMS backup",
type: "success"
});
await loadKmsBackup(backupContent);
createNotification({
text: "Successfully loaded KMS backup",
type: "success"
});
onOpenChange(false);
} catch (err) {
console.error(err);
}
onOpenChange(false);
};
const parseFile = (file?: File) => {
@@ -245,20 +241,16 @@ export const EncryptionTab = () => {
});
const onUpdateProjectKms = async (data: TForm) => {
try {
await updateProjectKms(
data.kmsKeyId === INTERNAL_KMS_KEY_ID
? { type: KmsType.Internal }
: { type: KmsType.External, kmsId: data.kmsKeyId }
);
await updateProjectKms(
data.kmsKeyId === INTERNAL_KMS_KEY_ID
? { type: KmsType.Internal }
: { type: KmsType.External, kmsId: data.kmsKeyId }
);
createNotification({
text: "Successfully updated project KMS",
type: "success"
});
} catch (err) {
console.error(err);
}
createNotification({
text: "Successfully updated project KMS",
type: "success"
});
};
return (

View File

@@ -36,28 +36,20 @@ const Content = ({ onComplete }: ContentProps) => {
});
const onFormSubmit = async ({ environmentName, environmentSlug }: FormData) => {
try {
if (!currentProject?.id) return;
if (!currentProject?.id) return;
const env = await mutateAsync({
projectId: currentProject.id,
name: environmentName,
slug: environmentSlug
});
const env = await mutateAsync({
projectId: currentProject.id,
name: environmentName,
slug: environmentSlug
});
createNotification({
text: "Successfully created environment",
type: "success"
});
createNotification({
text: "Successfully created environment",
type: "success"
});
onComplete(env);
} catch (err) {
console.error(err);
createNotification({
text: "Failed to create environment",
type: "error"
});
}
onComplete(env);
};
return (

View File

@@ -33,29 +33,21 @@ export const UpdateEnvironmentModal = ({ popUp, handlePopUpClose, handlePopUpTog
const oldEnvId = (popUp?.updateEnv?.data as { id: string })?.id;
const onFormSubmit = async ({ name, slug }: FormData) => {
try {
if (!currentProject?.id) return;
if (!currentProject?.id) return;
await mutateAsync({
projectId: currentProject.id,
name,
slug,
id: oldEnvId
});
await mutateAsync({
projectId: currentProject.id,
name,
slug,
id: oldEnvId
});
createNotification({
text: "Successfully updated environment",
type: "success"
});
createNotification({
text: "Successfully updated environment",
type: "success"
});
handlePopUpClose("updateEnv");
} catch (err) {
console.error(err);
createNotification({
text: "Failed to update environment",
type: "error"
});
}
handlePopUpClose("updateEnv");
};
return (

View File

@@ -34,22 +34,15 @@ export const PointInTimeVersionLimitSection = () => {
if (!currentProject) return null;
const handleVersionLimitSubmit = async ({ pitVersionLimit }: TForm) => {
try {
await updateProject({
pitVersionLimit,
projectId
});
await updateProject({
pitVersionLimit,
projectId
});
createNotification({
text: "Successfully updated version limit",
type: "success"
});
} catch {
createNotification({
text: "Failed updating project's version limit",
type: "error"
});
}
createNotification({
text: "Successfully updated version limit",
type: "success"
});
};
const isAdmin = hasProjectRole(ProjectMembershipRole.Admin);

View File

@@ -15,12 +15,12 @@ export const SecretSharingSection = () => {
const handleToggle = async (state: boolean) => {
setIsLoading(true);
try {
if (!currentProject?.id) {
setIsLoading(false);
return;
}
if (!currentProject?.id) {
setIsLoading(false);
return;
}
try {
await updateProject({
projectId: currentProject.id,
secretSharing: state
@@ -30,12 +30,6 @@ export const SecretSharingSection = () => {
text: `Successfully ${state ? "enabled" : "disabled"} secret sharing for this project`,
type: "success"
});
} catch (err) {
console.error(err);
createNotification({
text: "Failed to update secret sharing for this project",
type: "error"
});
} finally {
setIsLoading(false);
}

View File

@@ -39,29 +39,21 @@ export const AddSecretTagModal = ({ popUp, handlePopUpClose, handlePopUpToggle }
});
const onFormSubmit = async ({ slug }: FormData) => {
try {
if (!currentProject?.id) return;
if (!currentProject?.id) return;
await createWsTag.mutateAsync({
projectId: currentProject?.id,
tagSlug: slug,
tagColor: ""
});
await createWsTag.mutateAsync({
projectId: currentProject?.id,
tagSlug: slug,
tagColor: ""
});
handlePopUpClose("CreateSecretTag");
handlePopUpClose("CreateSecretTag");
createNotification({
text: "Successfully created a tag",
type: "success"
});
reset();
} catch (err) {
console.error(err);
createNotification({
text: "Failed to create a tag",
type: "error"
});
}
createNotification({
text: "Successfully created a tag",
type: "success"
});
reset();
};
return (

View File

@@ -29,25 +29,17 @@ export const SecretTagsSection = (): JSX.Element => {
const deleteWsTag = useDeleteWsTag();
const onDeleteApproved = async () => {
try {
await deleteWsTag.mutateAsync({
projectId: currentProject?.id || "",
tagID: (popUp?.deleteTagConfirmation?.data as DeleteModalData)?.id
});
await deleteWsTag.mutateAsync({
projectId: currentProject?.id || "",
tagID: (popUp?.deleteTagConfirmation?.data as DeleteModalData)?.id
});
createNotification({
text: "Successfully deleted tag",
type: "success"
});
createNotification({
text: "Successfully deleted tag",
type: "success"
});
handlePopUpClose("deleteTagConfirmation");
} catch (err) {
console.error(err);
createNotification({
text: "Failed to delete the tag",
type: "error"
});
}
handlePopUpClose("deleteTagConfirmation");
};
return (

View File

@@ -126,43 +126,35 @@ export const BitbucketConfigurePage = () => {
}: TFormData) => {
if (!targetRepo || !targetWorkspace) return;
try {
await createIntegration.mutateAsync({
integrationAuthId,
isActive: true,
app: targetRepo.name,
appId: targetRepo.appId,
sourceEnvironment: sourceEnvironment.slug,
targetEnvironment: targetWorkspace.name,
targetEnvironmentId: targetWorkspace.slug,
...(scope.value === BitbucketScope.Env &&
targetEnvironment && {
targetService: targetEnvironment.name,
targetServiceId: targetEnvironment.uuid
}),
secretPath
});
await createIntegration.mutateAsync({
integrationAuthId,
isActive: true,
app: targetRepo.name,
appId: targetRepo.appId,
sourceEnvironment: sourceEnvironment.slug,
targetEnvironment: targetWorkspace.name,
targetEnvironmentId: targetWorkspace.slug,
...(scope.value === BitbucketScope.Env &&
targetEnvironment && {
targetService: targetEnvironment.name,
targetServiceId: targetEnvironment.uuid
}),
secretPath
});
createNotification({
type: "success",
text: "Successfully created integration"
});
navigate({
to: "/projects/secret-management/$projectId/integrations",
params: {
projectId: currentProject.id
},
search: {
selectedTab: IntegrationsListPageTabs.NativeIntegrations
}
});
} catch (err) {
createNotification({
type: "error",
text: "Failed to create integration"
});
console.error(err);
}
createNotification({
type: "success",
text: "Successfully created integration"
});
navigate({
to: "/projects/secret-management/$projectId/integrations",
params: {
projectId: currentProject.id
},
search: {
selectedTab: IntegrationsListPageTabs.NativeIntegrations
}
});
};
useEffect(() => {

View File

@@ -73,51 +73,43 @@ export const CircleCIConfigurePage = () => {
: undefined;
const onSubmit = async (data: TFormData) => {
try {
if (data.scope === CircleCiScope.Context) {
await mutateAsync({
scope: data.scope,
integrationAuthId,
isActive: true,
sourceEnvironment: data.sourceEnvironment.slug,
app: data.targetContext.name,
appId: data.targetContext.id,
owner: data.targetOrg.name,
secretPath: data.secretPath
});
} else {
await mutateAsync({
scope: data.scope,
integrationAuthId,
isActive: true,
app: data.targetProject.name, // project name
owner: data.targetOrg.name, // organization name
appId: data.targetProject.id, // project id (used for syncing)
sourceEnvironment: data.sourceEnvironment.slug,
secretPath: data.secretPath
});
}
createNotification({
type: "success",
text: "Successfully created integration"
if (data.scope === CircleCiScope.Context) {
await mutateAsync({
scope: data.scope,
integrationAuthId,
isActive: true,
sourceEnvironment: data.sourceEnvironment.slug,
app: data.targetContext.name,
appId: data.targetContext.id,
owner: data.targetOrg.name,
secretPath: data.secretPath
});
navigate({
to: "/projects/secret-management/$projectId/integrations",
params: {
projectId: currentProject.id
},
search: {
selectedTab: IntegrationsListPageTabs.NativeIntegrations
}
} else {
await mutateAsync({
scope: data.scope,
integrationAuthId,
isActive: true,
app: data.targetProject.name, // project name
owner: data.targetOrg.name, // organization name
appId: data.targetProject.id, // project id (used for syncing)
sourceEnvironment: data.sourceEnvironment.slug,
secretPath: data.secretPath
});
} catch (err) {
createNotification({
type: "error",
text: "Failed to create integration"
});
console.error(err);
}
createNotification({
type: "success",
text: "Successfully created integration"
});
navigate({
to: "/projects/secret-management/$projectId/integrations",
params: {
projectId: currentProject.id
},
search: {
selectedTab: IntegrationsListPageTabs.NativeIntegrations
}
});
};
if (isCircleCIOrganizationsLoading)

View File

@@ -1,8 +1,6 @@
import { useEffect, useState } from "react";
import { useNavigate, useSearch } from "@tanstack/react-router";
import axios from "axios";
import { createNotification } from "@app/components/notifications";
import {
Button,
Card,
@@ -102,19 +100,7 @@ export const CloudflarePagesConfigurePage = () => {
selectedTab: IntegrationsListPageTabs.NativeIntegrations
}
});
} catch (err) {
console.error(err);
let errorMessage: string = "Something went wrong!";
if (axios.isAxiosError(err)) {
const { message } = err?.response?.data as { message: string };
errorMessage = message;
}
createNotification({
text: errorMessage,
type: "error"
});
} catch {
setIsLoading(false);
}
};

View File

@@ -1,8 +1,6 @@
import { useEffect, useState } from "react";
import { useNavigate, useSearch } from "@tanstack/react-router";
import axios from "axios";
import { createNotification } from "@app/components/notifications";
import { Button, Card, CardTitle, FormControl, Select, SelectItem } from "@app/components/v2";
import { SecretPathInput } from "@app/components/v2/SecretPathInput";
import { ROUTE_PATHS } from "@app/const/routes";
@@ -75,19 +73,7 @@ export const CloudflareWorkersConfigurePage = () => {
selectedTab: IntegrationsListPageTabs.NativeIntegrations
}
});
} catch (err) {
console.error(err);
let errorMessage: string = "Something went wrong!";
if (axios.isAxiosError(err)) {
const { message } = err?.response?.data as { message: string };
errorMessage = message;
}
createNotification({
text: errorMessage,
type: "error"
});
} catch {
setIsLoading(false);
}
};

View File

@@ -55,49 +55,45 @@ export const DatabricksConfigurePage = () => {
const [secretPath, setSecretPath] = useState("/");
const handleButtonClick = async () => {
try {
if (!integrationAuth?.id) return;
if (!integrationAuth?.id) return;
if (!targetScope) {
createNotification({
type: "error",
text: "Please select a scope"
});
return;
}
const selectedScope = integrationAuthScopes?.find(
(integrationAuthScope) => integrationAuthScope.name === targetScope
);
if (!selectedScope) {
createNotification({
type: "error",
text: "Invalid scope selected"
});
return;
}
await mutateAsync({
integrationAuthId: integrationAuth?.id,
isActive: true,
app: selectedScope.name, // scope name
sourceEnvironment: selectedSourceEnvironment,
secretPath
if (!targetScope) {
createNotification({
type: "error",
text: "Please select a scope"
});
navigate({
to: "/projects/secret-management/$projectId/integrations",
params: {
projectId: currentProject.id
},
search: {
selectedTab: IntegrationsListPageTabs.NativeIntegrations
}
});
} catch (err) {
console.error(err);
return;
}
const selectedScope = integrationAuthScopes?.find(
(integrationAuthScope) => integrationAuthScope.name === targetScope
);
if (!selectedScope) {
createNotification({
type: "error",
text: "Invalid scope selected"
});
return;
}
await mutateAsync({
integrationAuthId: integrationAuth?.id,
isActive: true,
app: selectedScope.name, // scope name
sourceEnvironment: selectedSourceEnvironment,
secretPath
});
navigate({
to: "/projects/secret-management/$projectId/integrations",
params: {
projectId: currentProject.id
},
search: {
selectedTab: IntegrationsListPageTabs.NativeIntegrations
}
});
};
return integrationAuth && selectedSourceEnvironment && integrationAuthScopes ? (

View File

@@ -12,12 +12,10 @@ import {
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { zodResolver } from "@hookform/resolvers/zod";
import { useNavigate, useSearch } from "@tanstack/react-router";
import axios from "axios";
import { motion } from "framer-motion";
import { twMerge } from "tailwind-merge";
import { z, ZodIssueCode } from "zod";
import { createNotification } from "@app/components/notifications";
import {
Button,
Card,
@@ -275,19 +273,7 @@ export const GithubConfigurePage = () => {
selectedTab: IntegrationsListPageTabs.NativeIntegrations
}
});
} catch (err) {
console.error(err);
let errorMessage: string = "Something went wrong!";
if (axios.isAxiosError(err)) {
const { message } = err?.response?.data as { message: string };
errorMessage = message;
}
createNotification({
text: errorMessage,
type: "error"
});
} catch {
setIsLoading(false);
}
};

View File

@@ -4,10 +4,8 @@ import { faArrowUpRightFromSquare, faBookOpen } from "@fortawesome/free-solid-sv
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { zodResolver } from "@hookform/resolvers/zod";
import { useNavigate } from "@tanstack/react-router";
import axios from "axios";
import { z } from "zod";
import { createNotification } from "@app/components/notifications";
import { Button, Card, CardBody, CardTitle, FormControl, Input } from "@app/components/v2";
import { useProject } from "@app/context";
import { useSaveIntegrationAccessToken } from "@app/hooks/api";
@@ -41,37 +39,23 @@ export const HashicorpVaultAuthorizePage = () => {
});
const handleFormSubmit = async (formData: TForm) => {
try {
const integrationAuth = await mutateAsync({
workspaceId: currentProject.id,
integration: "hashicorp-vault",
accessId: formData.vaultRoleID,
accessToken: formData.vaultSecretID,
url: formData.vaultURL,
namespace: formData.vaultNamespace
});
navigate({
to: "/projects/secret-management/$projectId/integrations/hashicorp-vault/create",
params: {
projectId: currentProject.id
},
search: {
integrationAuthId: integrationAuth.id
}
});
} catch (err) {
console.error(err);
let errorMessage: string = "Something went wrong!";
if (axios.isAxiosError(err)) {
const { message } = err?.response?.data as { message: string };
errorMessage = message;
const integrationAuth = await mutateAsync({
workspaceId: currentProject.id,
integration: "hashicorp-vault",
accessId: formData.vaultRoleID,
accessToken: formData.vaultSecretID,
url: formData.vaultURL,
namespace: formData.vaultNamespace
});
navigate({
to: "/projects/secret-management/$projectId/integrations/hashicorp-vault/create",
params: {
projectId: currentProject.id
},
search: {
integrationAuthId: integrationAuth.id
}
createNotification({
text: errorMessage,
type: "error"
});
}
});
};
return (

View File

@@ -10,10 +10,8 @@ import {
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { zodResolver } from "@hookform/resolvers/zod";
import { useNavigate, useSearch } from "@tanstack/react-router";
import axios from "axios";
import { z } from "zod";
import { createNotification } from "@app/components/notifications";
import {
Button,
Card,
@@ -90,38 +88,24 @@ export const HashicorpVaultConfigurePage = () => {
});
const handleFormSubmit = async (formData: TForm) => {
try {
if (!integrationAuth?.id) return;
await mutateAsync({
integrationAuthId: integrationAuth?.id,
isActive: true,
app: formData.vaultEnginePath,
sourceEnvironment: formData.selectedSourceEnvironment,
path: formData.vaultSecretPath,
secretPath: formData.secretPath
});
navigate({
to: "/projects/secret-management/$projectId/integrations",
params: {
projectId: currentProject.id
},
search: {
selectedTab: IntegrationsListPageTabs.NativeIntegrations
}
});
} catch (err) {
console.error(err);
let errorMessage: string = "Something went wrong!";
if (axios.isAxiosError(err)) {
const { message } = err?.response?.data as { message: string };
errorMessage = message;
if (!integrationAuth?.id) return;
await mutateAsync({
integrationAuthId: integrationAuth?.id,
isActive: true,
app: formData.vaultEnginePath,
sourceEnvironment: formData.selectedSourceEnvironment,
path: formData.vaultSecretPath,
secretPath: formData.secretPath
});
navigate({
to: "/projects/secret-management/$projectId/integrations",
params: {
projectId: currentProject.id
},
search: {
selectedTab: IntegrationsListPageTabs.NativeIntegrations
}
createNotification({
text: errorMessage,
type: "error"
});
}
});
};
return integrationAuth ? (

View File

@@ -6,7 +6,6 @@ import { zodResolver } from "@hookform/resolvers/zod";
import { useNavigate } from "@tanstack/react-router";
import { z } from "zod";
import { createNotification } from "@app/components/notifications";
import { Button, Card, CardTitle, FormControl, Input } from "@app/components/v2";
import { useProject } from "@app/context";
import { removeTrailingSlash } from "@app/helpers/string";
@@ -29,30 +28,22 @@ export const OctopusDeployAuthorizePage = () => {
});
const onSubmit = async ({ instanceUrl, apiKey }: TForm) => {
try {
const integrationAuth = await mutateAsync({
workspaceId: currentProject.id,
integration: "octopus-deploy",
url: removeTrailingSlash(instanceUrl),
accessToken: apiKey
});
const integrationAuth = await mutateAsync({
workspaceId: currentProject.id,
integration: "octopus-deploy",
url: removeTrailingSlash(instanceUrl),
accessToken: apiKey
});
navigate({
to: "/projects/secret-management/$projectId/integrations/octopus-deploy/create",
params: {
projectId: currentProject.id
},
search: {
integrationAuthId: integrationAuth.id
}
});
} catch (err: any) {
createNotification({
type: "error",
text: err.message ?? "Error authorizing integration"
});
console.error(err);
}
navigate({
to: "/projects/secret-management/$projectId/integrations/octopus-deploy/create",
params: {
projectId: currentProject.id
},
search: {
integrationAuthId: integrationAuth.id
}
});
};
return (

View File

@@ -107,49 +107,41 @@ export const OctopusDeployConfigurePage = () => {
targetRoles,
scope
}: TFormData) => {
try {
await createIntegration.mutateAsync({
integrationAuthId,
isActive: true,
scope,
app: targetResource.name,
appId: targetResource.appId,
targetEnvironment: targetSpace.Name,
targetEnvironmentId: targetSpace.Id,
metadata: {
octopusDeployScopeValues: {
Environment: targetEnvironments?.map(({ Id }) => Id),
Action: targetActions?.map(({ Id }) => Id),
Channel: targetChannels?.map(({ Id }) => Id),
ProcessOwner: targetProcesses?.map(({ Id }) => Id),
Role: targetRoles?.map(({ Id }) => Id),
Machine: targetMachines?.map(({ Id }) => Id)
}
},
sourceEnvironment: sourceEnvironment.slug,
secretPath
});
createNotification({
type: "success",
text: "Successfully created integration"
});
navigate({
to: "/projects/secret-management/$projectId/integrations",
params: {
projectId: currentProject.id
},
search: {
selectedTab: IntegrationsListPageTabs.NativeIntegrations
await createIntegration.mutateAsync({
integrationAuthId,
isActive: true,
scope,
app: targetResource.name,
appId: targetResource.appId,
targetEnvironment: targetSpace.Name,
targetEnvironmentId: targetSpace.Id,
metadata: {
octopusDeployScopeValues: {
Environment: targetEnvironments?.map(({ Id }) => Id),
Action: targetActions?.map(({ Id }) => Id),
Channel: targetChannels?.map(({ Id }) => Id),
ProcessOwner: targetProcesses?.map(({ Id }) => Id),
Role: targetRoles?.map(({ Id }) => Id),
Machine: targetMachines?.map(({ Id }) => Id)
}
});
} catch (err) {
createNotification({
type: "error",
text: "Failed to create integration"
});
console.error(err);
}
},
sourceEnvironment: sourceEnvironment.slug,
secretPath
});
createNotification({
type: "success",
text: "Successfully created integration"
});
navigate({
to: "/projects/secret-management/$projectId/integrations",
params: {
projectId: currentProject.id
},
search: {
selectedTab: IntegrationsListPageTabs.NativeIntegrations
}
});
};
useEffect(() => {

View File

@@ -83,23 +83,14 @@ export const ChangeEmailSection = () => {
return;
}
try {
await requestEmailChangeOTP({ newEmail });
setPendingEmail(newEmail);
setIsOTPModalOpen(true);
await requestEmailChangeOTP({ newEmail });
setPendingEmail(newEmail);
setIsOTPModalOpen(true);
createNotification({
text: "Verification code sent to your new email address. Check your inbox!",
type: "success"
});
} catch (err: any) {
console.error(err);
const errorMessage = err?.response?.data?.message || "Failed to send verification code";
createNotification({
text: errorMessage,
type: "error"
});
}
createNotification({
text: "Verification code sent to your new email address. Check your inbox!",
type: "success"
});
};
const [typedOTP, setTypedOTP] = useState("");
@@ -135,8 +126,6 @@ export const ChangeEmailSection = () => {
navigate({ to: "/login" });
}, 2000);
} catch (err: any) {
console.error(err);
const errorMessage = err?.response?.data?.message || "Invalid verification code";
if (errorMessage.includes("Invalid verification code")) {
// Reset to email step so user must request new OTP
@@ -149,11 +138,6 @@ export const ChangeEmailSection = () => {
text: "Invalid verification code. Please request a new one.",
type: "error"
});
} else {
createNotification({
text: errorMessage,
type: "error"
});
}
}
};

View File

@@ -97,21 +97,13 @@ export const ChangePasswordSection = () => {
};
const onSetupPassword = async () => {
try {
await sendSetupPasswordEmail.mutateAsync();
await sendSetupPasswordEmail.mutateAsync();
createNotification({
title: "Password setup verification email sent",
text: "Check your email to confirm password setup",
type: "info"
});
} catch (err) {
console.error(err);
createNotification({
text: "Failed to send password setup email",
type: "error"
});
}
createNotification({
title: "Password setup verification email sent",
text: "Check your email to confirm password setup",
type: "info"
});
};
return (

View File

@@ -15,23 +15,15 @@ export const DeleteAccountSection = () => {
const { mutateAsync: deleteUserMutateAsync, isPending } = useDeleteMe();
const handleDeleteAccountSubmit = async () => {
try {
await deleteUserMutateAsync();
await deleteUserMutateAsync();
createNotification({
text: "Successfully deleted account",
type: "success"
});
createNotification({
text: "Successfully deleted account",
type: "success"
});
navigate({ to: "/login" });
handlePopUpClose("deleteAccount");
} catch (err) {
console.error(err);
createNotification({
text: "Failed to delete account",
type: "error"
});
}
navigate({ to: "/login" });
handlePopUpClose("deleteAccount");
};
return (

View File

@@ -84,49 +84,27 @@ export const MFASection = () => {
}, [totpRegistration, showMobileAuthSetup]);
const handleTotpDeletion = async () => {
try {
await deleteTotpConfiguration();
await deleteTotpConfiguration();
await mutateAsync({
selectedMfaMethod: MfaMethod.EMAIL
});
await mutateAsync({
selectedMfaMethod: MfaMethod.EMAIL
});
createNotification({
text: "Successfully deleted mobile authenticator and switched to email authentication",
type: "success"
});
createNotification({
text: "Successfully deleted mobile authenticator and switched to email authentication",
type: "success"
});
handlePopUpClose("deleteTotpConfig");
} catch (err) {
console.error(err);
const error = err as any;
const text = error?.response?.data?.message ?? "Failed to delete mobile authenticator";
createNotification({
text,
type: "error"
});
}
handlePopUpClose("deleteTotpConfig");
};
const handleGenerateMoreRecoveryCodes = async () => {
try {
await createTotpRecoveryCodes();
await createTotpRecoveryCodes();
createNotification({
text: "Successfully generated new recovery codes",
type: "success"
});
} catch (err) {
console.error(err);
const error = err as any;
const text = error?.response?.data?.message ?? "Failed to generate new recovery codes";
createNotification({
text,
type: "error"
});
}
createNotification({
text: "Successfully generated new recovery codes",
type: "success"
});
};
const handleFormDataChange = async (field: string, value: any) => {
@@ -200,10 +178,6 @@ export const MFASection = () => {
await queryClient.invalidateQueries({ queryKey: userKeys.totpConfiguration });
} catch {
createNotification({
text: "Failed to verify TOTP code. Please try again.",
type: "error"
});
setIsLoading(false);
return;
}
@@ -249,12 +223,6 @@ export const MFASection = () => {
setShowMobileAuthSetup(false);
setTotpCode("");
setShouldShowRecoveryCodes.off();
} catch (err) {
createNotification({
text: "Something went wrong while updating two-factor authentication settings.",
type: "error"
});
console.error(err);
} finally {
setIsLoading(false);
}

View File

@@ -40,19 +40,11 @@ export const SessionsTable = () => {
] as const);
const handleSignOut = async (sessionId: string) => {
try {
await revokeMySessionById(sessionId);
createNotification({
text: "Session revoked successfully",
type: "success"
});
} catch (error) {
console.error(error);
createNotification({
text: "Failed to revoke session",
type: "error"
});
}
await revokeMySessionById(sessionId);
createNotification({
text: "Session revoked successfully",
type: "success"
});
handlePopUpClose("deleteSession");
};

View File

@@ -27,22 +27,14 @@ export const UserNameSection = (): JSX.Element => {
}, [user]);
const onFormSubmit = async ({ name }: FormData) => {
try {
if (!user?.id) return;
if (name === "") return;
if (!user?.id) return;
if (name === "") return;
await mutateAsync({ newName: name });
createNotification({
text: "Successfully renamed user",
type: "success"
});
} catch (error) {
console.error(error);
createNotification({
text: "Failed to rename user",
type: "error"
});
}
await mutateAsync({ newName: name });
createNotification({
text: "Successfully renamed user",
type: "success"
});
};
return (