From 83da0dd3d98c67197084153e49090e09007b2771 Mon Sep 17 00:00:00 2001 From: Sheen Capadngan Date: Sat, 1 Nov 2025 00:46:27 +0800 Subject: [PATCH 01/28] misc: improved monitoring and telemetry docs --- .../guides/monitoring-telemetry.mdx | 763 ++++++++++-------- 1 file changed, 408 insertions(+), 355 deletions(-) diff --git a/docs/self-hosting/guides/monitoring-telemetry.mdx b/docs/self-hosting/guides/monitoring-telemetry.mdx index b23c51b27..441a78ac0 100644 --- a/docs/self-hosting/guides/monitoring-telemetry.mdx +++ b/docs/self-hosting/guides/monitoring-telemetry.mdx @@ -27,7 +27,9 @@ Both approaches provide the same metrics data in OTEL format, so you can choose - Access to deploy monitoring services (Prometheus, Grafana, etc.) - Basic understanding of Prometheus and Grafana -## Environment Variables +## Setup + +### Environment Variables Configure the following environment variables in your Infisical backend: @@ -37,287 +39,282 @@ OTEL_TELEMETRY_COLLECTION_ENABLED=true # Choose export type: "prometheus" or "otlp" OTEL_EXPORT_TYPE=prometheus - -# For OTLP push mode, also configure: -# OTEL_EXPORT_OTLP_ENDPOINT=http://otel-collector:4318/v1/metrics -# OTEL_COLLECTOR_BASIC_AUTH_USERNAME=your_collector_username -# OTEL_COLLECTOR_BASIC_AUTH_PASSWORD=your_collector_password -# OTEL_OTLP_PUSH_INTERVAL=30000 ``` -**Note**: The `OTEL_COLLECTOR_BASIC_AUTH_USERNAME` and `OTEL_COLLECTOR_BASIC_AUTH_PASSWORD` values must match the credentials configured in your OpenTelemetry Collector's `basicauth/server` extension. These are not hardcoded values - you configure them in your collector configuration file. + + + This approach exposes metrics on port 9464 at the `/metrics` endpoint, allowing Prometheus to scrape the data. The metrics are exposed in Prometheus format but originate from OpenTelemetry instrumentation. -## Option 1: Pull-based Monitoring (Prometheus) + ### Configuration -This approach exposes metrics on port 9464 at the `/metrics` endpoint, allowing Prometheus to scrape the data. The metrics are exposed in Prometheus format but originate from OpenTelemetry instrumentation. + 1. **Enable Prometheus export in Infisical**: -### Configuration + ```bash + OTEL_TELEMETRY_COLLECTION_ENABLED=true + OTEL_EXPORT_TYPE=prometheus + ``` -1. **Enable Prometheus export in Infisical**: + 2. **Expose the metrics port** in your Infisical backend: - ```bash - OTEL_TELEMETRY_COLLECTION_ENABLED=true - OTEL_EXPORT_TYPE=prometheus - ``` + - **Docker**: Expose port 9464 + - **Kubernetes**: Create a service exposing port 9464 + - **Other**: Ensure port 9464 is accessible to your monitoring stack -2. **Expose the metrics port** in your Infisical backend: + 3. **Create Prometheus configuration** (`prometheus.yml`): - - **Docker**: Expose port 9464 - - **Kubernetes**: Create a service exposing port 9464 - - **Other**: Ensure port 9464 is accessible to your monitoring stack + ```yaml + global: + scrape_interval: 30s + evaluation_interval: 30s -3. **Create Prometheus configuration** (`prometheus.yml`): + scrape_configs: + - job_name: "infisical" + scrape_interval: 30s + static_configs: + - targets: ["infisical-backend:9464"] # Adjust hostname/port based on your deployment + metrics_path: "/metrics" + ``` - ```yaml - global: - scrape_interval: 30s - evaluation_interval: 30s + **Note**: Replace `infisical-backend:9464` with the actual hostname and port where your Infisical backend is running. This could be: - scrape_configs: - - job_name: "infisical" - scrape_interval: 30s - static_configs: - - targets: ["infisical-backend:9464"] # Adjust hostname/port based on your deployment - metrics_path: "/metrics" - ``` + - **Docker Compose**: `infisical-backend:9464` (service name) + - **Kubernetes**: `infisical-backend.default.svc.cluster.local:9464` (service name) + - **Bare Metal**: `192.168.1.100:9464` (actual IP address) + - **Cloud**: `your-infisical.example.com:9464` (domain name) - **Note**: Replace `infisical-backend:9464` with the actual hostname and port where your Infisical backend is running. This could be: + ### Deployment Options - - **Docker Compose**: `infisical-backend:9464` (service name) - - **Kubernetes**: `infisical-backend.default.svc.cluster.local:9464` (service name) - - **Bare Metal**: `192.168.1.100:9464` (actual IP address) - - **Cloud**: `your-infisical.example.com:9464` (domain name) + + + ```yaml + services: + prometheus: + image: prom/prometheus:latest + ports: + - "9090:9090" + volumes: + - ./prometheus.yml:/etc/prometheus/prometheus.yml:ro + command: + - "--config.file=/etc/prometheus/prometheus.yml" -### Deployment Options + grafana: + image: grafana/grafana:latest + ports: + - "3000:3000" + environment: + - GF_SECURITY_ADMIN_USER=admin + - GF_SECURITY_ADMIN_PASSWORD=admin + ``` + + + ```yaml + # prometheus-deployment.yaml + apiVersion: apps/v1 + kind: Deployment + metadata: + name: prometheus + spec: + replicas: 1 + selector: + matchLabels: + app: prometheus + template: + metadata: + labels: + app: prometheus + spec: + containers: + - name: prometheus + image: prom/prometheus:latest + ports: + - containerPort: 9090 + volumeMounts: + - name: config + mountPath: /etc/prometheus + volumes: + - name: config + configMap: + name: prometheus-config -#### Docker Compose - -```yaml -services: - prometheus: - image: prom/prometheus:latest - ports: - - "9090:9090" - volumes: - - ./prometheus.yml:/etc/prometheus/prometheus.yml:ro - command: - - "--config.file=/etc/prometheus/prometheus.yml" - - grafana: - image: grafana/grafana:latest - ports: - - "3000:3000" - environment: - - GF_SECURITY_ADMIN_USER=admin - - GF_SECURITY_ADMIN_PASSWORD=admin -``` - -#### Kubernetes - -```yaml -# prometheus-deployment.yaml -apiVersion: apps/v1 -kind: Deployment -metadata: - name: prometheus -spec: - replicas: 1 - selector: - matchLabels: - app: prometheus - template: - metadata: - labels: - app: prometheus - spec: - containers: - - name: prometheus - image: prom/prometheus:latest + --- + # prometheus-service.yaml + apiVersion: v1 + kind: Service + metadata: + name: prometheus + spec: + selector: + app: prometheus ports: - - containerPort: 9090 - volumeMounts: - - name: config - mountPath: /etc/prometheus - volumes: - - name: config - configMap: - name: prometheus-config + - port: 9090 + targetPort: 9090 + type: ClusterIP + ``` + + + ```bash + helm repo add prometheus-community https://prometheus-community.github.io/helm-charts + helm install prometheus prometheus-community/prometheus \ + --set server.config.global.scrape_interval=30s \ + --set server.config.scrape_configs[0].job_name=infisical \ + --set server.config.scrape_configs[0].static_configs[0].targets[0]=infisical-backend:9464 + ``` + + ---- -# prometheus-service.yaml -apiVersion: v1 -kind: Service -metadata: - name: prometheus -spec: - selector: - app: prometheus - ports: - - port: 9090 - targetPort: 9090 - type: ClusterIP -``` + + + This approach sends metrics directly to an OpenTelemetry Collector via the OTLP protocol. This gives you the most flexibility as you can configure the collector to export to multiple backends simultaneously. -#### Helm + ### Configuration -```bash -helm repo add prometheus-community https://prometheus-community.github.io/helm-charts -helm install prometheus prometheus-community/prometheus \ - --set server.config.global.scrape_interval=30s \ - --set server.config.scrape_configs[0].job_name=infisical \ - --set server.config.scrape_configs[0].static_configs[0].targets[0]=infisical-backend:9464 -``` + 1. **Enable OTLP export in Infisical**: -## Option 2: Push-based Monitoring (OTLP) + ```bash + OTEL_TELEMETRY_COLLECTION_ENABLED=true + OTEL_EXPORT_TYPE=otlp + OTEL_EXPORT_OTLP_ENDPOINT=http://otel-collector:4318/v1/metrics + OTEL_COLLECTOR_BASIC_AUTH_USERNAME=infisical + OTEL_COLLECTOR_BASIC_AUTH_PASSWORD=infisical + OTEL_OTLP_PUSH_INTERVAL=30000 + ``` -This approach sends metrics directly to an OpenTelemetry Collector via the OTLP protocol. This gives you the most flexibility as you can configure the collector to export to multiple backends simultaneously. + 2. **Create OpenTelemetry Collector configuration** (`otel-collector-config.yaml`): -### Configuration + ```yaml + extensions: + health_check: + pprof: + zpages: + basicauth/server: + htpasswd: + inline: | + your_username:your_password -1. **Enable OTLP export in Infisical**: + receivers: + otlp: + protocols: + http: + endpoint: 0.0.0.0:4318 + auth: + authenticator: basicauth/server - ```bash - OTEL_TELEMETRY_COLLECTION_ENABLED=true - OTEL_EXPORT_TYPE=otlp - OTEL_EXPORT_OTLP_ENDPOINT=http://otel-collector:4318/v1/metrics - OTEL_COLLECTOR_BASIC_AUTH_USERNAME=infisical - OTEL_COLLECTOR_BASIC_AUTH_PASSWORD=infisical - OTEL_OTLP_PUSH_INTERVAL=30000 - ``` + prometheus: + config: + scrape_configs: + - job_name: otel-collector + scrape_interval: 30s + static_configs: + - targets: [infisical-backend:9464] + metric_relabel_configs: + - action: labeldrop + regex: "service_instance_id|service_name" -2. **Create OpenTelemetry Collector configuration** (`otel-collector-config.yaml`): + processors: + batch: - ```yaml - extensions: - health_check: - pprof: - zpages: - basicauth/server: - htpasswd: - inline: | - your_username:your_password - - receivers: - otlp: - protocols: - http: - endpoint: 0.0.0.0:4318 + exporters: + prometheus: + endpoint: "0.0.0.0:8889" auth: authenticator: basicauth/server + resource_to_telemetry_conversion: + enabled: true - prometheus: - config: - scrape_configs: - - job_name: otel-collector - scrape_interval: 30s - static_configs: - - targets: [infisical-backend:9464] - metric_relabel_configs: - - action: labeldrop - regex: "service_instance_id|service_name" + service: + extensions: [basicauth/server, health_check, pprof, zpages] + pipelines: + metrics: + receivers: [otlp] + processors: [batch] + exporters: [prometheus] + ``` - processors: - batch: + **Important**: Replace `your_username:your_password` with your chosen credentials. These must match the values you set in Infisical's `OTEL_COLLECTOR_BASIC_AUTH_USERNAME` and `OTEL_COLLECTOR_BASIC_AUTH_PASSWORD` environment variables. - exporters: - prometheus: - endpoint: "0.0.0.0:8889" - auth: - authenticator: basicauth/server - resource_to_telemetry_conversion: - enabled: true + 3. **Create Prometheus configuration** for the collector: - service: - extensions: [basicauth/server, health_check, pprof, zpages] - pipelines: - metrics: - receivers: [otlp] - processors: [batch] - exporters: [prometheus] - ``` + ```yaml + global: + scrape_interval: 30s + evaluation_interval: 30s - **Important**: Replace `your_username:your_password` with your chosen credentials. These must match the values you set in Infisical's `OTEL_COLLECTOR_BASIC_AUTH_USERNAME` and `OTEL_COLLECTOR_BASIC_AUTH_PASSWORD` environment variables. + scrape_configs: + - job_name: "otel-collector" + scrape_interval: 30s + static_configs: + - targets: ["otel-collector:8889"] # Adjust hostname/port based on your deployment + metrics_path: "/metrics" + ``` -3. **Create Prometheus configuration** for the collector: + **Note**: Replace `otel-collector:8889` with the actual hostname and port where your OpenTelemetry Collector is running. This could be: - ```yaml - global: - scrape_interval: 30s - evaluation_interval: 30s + - **Docker Compose**: `otel-collector:8889` (service name) + - **Kubernetes**: `otel-collector.default.svc.cluster.local:8889` (service name) + - **Bare Metal**: `192.168.1.100:8889` (actual IP address) + - **Cloud**: `your-collector.example.com:8889` (domain name) - scrape_configs: - - job_name: "otel-collector" - scrape_interval: 30s - static_configs: - - targets: ["otel-collector:8889"] # Adjust hostname/port based on your deployment - metrics_path: "/metrics" - ``` + ### Deployment Options - **Note**: Replace `otel-collector:8889` with the actual hostname and port where your OpenTelemetry Collector is running. This could be: + + + ```yaml + services: + otel-collector: + image: otel/opentelemetry-collector-contrib:latest + ports: + - 4318:4318 # OTLP http receiver + - 8889:8889 # Prometheus exporter metrics + volumes: + - ./otel-collector-config.yaml:/etc/otelcol-contrib/config.yaml:ro + command: + - "--config=/etc/otelcol-contrib/config.yaml" + ``` + + + ```yaml + # otel-collector-deployment.yaml + apiVersion: apps/v1 + kind: Deployment + metadata: + name: otel-collector + spec: + replicas: 1 + selector: + matchLabels: + app: otel-collector + template: + metadata: + labels: + app: otel-collector + spec: + containers: + - name: otel-collector + image: otel/opentelemetry-collector-contrib:latest + ports: + - containerPort: 4318 + - containerPort: 8889 + volumeMounts: + - name: config + mountPath: /etc/otelcol-contrib + volumes: + - name: config + configMap: + name: otel-collector-config + ``` + + + ```bash + helm repo add open-telemetry https://open-telemetry.github.io/opentelemetry-helm-charts + helm install otel-collector open-telemetry/opentelemetry-collector \ + --set config.receivers.otlp.protocols.http.endpoint=0.0.0.0:4318 \ + --set config.exporters.prometheus.endpoint=0.0.0.0:8889 + ``` + + - - **Docker Compose**: `otel-collector:8889` (service name) - - **Kubernetes**: `otel-collector.default.svc.cluster.local:8889` (service name) - - **Bare Metal**: `192.168.1.100:8889` (actual IP address) - - **Cloud**: `your-collector.example.com:8889` (domain name) - -### Deployment Options - -#### Docker Compose - -```yaml -services: - otel-collector: - image: otel/opentelemetry-collector-contrib:latest - ports: - - 4318:4318 # OTLP http receiver - - 8889:8889 # Prometheus exporter metrics - volumes: - - ./otel-collector-config.yaml:/etc/otelcol-contrib/config.yaml:ro - command: - - "--config=/etc/otelcol-contrib/config.yaml" -``` - -#### Kubernetes - -```yaml -# otel-collector-deployment.yaml -apiVersion: apps/v1 -kind: Deployment -metadata: - name: otel-collector -spec: - replicas: 1 - selector: - matchLabels: - app: otel-collector - template: - metadata: - labels: - app: otel-collector - spec: - containers: - - name: otel-collector - image: otel/opentelemetry-collector-contrib:latest - ports: - - containerPort: 4318 - - containerPort: 8889 - volumeMounts: - - name: config - mountPath: /etc/otelcol-contrib - volumes: - - name: config - configMap: - name: otel-collector-config -``` - -#### Helm - -```bash -helm repo add open-telemetry https://open-telemetry.github.io/opentelemetry-helm-charts -helm install otel-collector open-telemetry/opentelemetry-collector \ - --set config.receivers.otlp.protocols.http.endpoint=0.0.0.0:4318 \ - --set config.exporters.prometheus.endpoint=0.0.0.0:8889 -``` + + ## Available Metrics @@ -327,154 +324,210 @@ Infisical exposes the following key metrics in OpenTelemetry format: These metrics track all HTTP API requests to Infisical, including request counts, latency, and errors. Use these to monitor overall API health, identify performance bottlenecks, and track usage patterns across users and machine identities. -#### Total API Requests + + + **Metric Name**: `infisical.http.server.request.count` -- **Metric Name**: `infisical.http.server.request.count` -- **Type**: Counter -- **Unit**: `{request}` -- **Description**: Total number of API requests to Infisical (covers both human users and machine identities) -- **Attributes**: - - `infisical.organization.id` (string): Organization ID - - `infisical.organization.name` (string): Organization name (e.g., "Platform Engineering Team") - - `infisical.user.id` (string, optional): User ID if human user - - `infisical.user.email` (string, optional): User email (e.g., "jane.doe@cisco.com") - - `infisical.identity.id` (string, optional): Machine identity ID - - `infisical.identity.name` (string, optional): Machine identity name (e.g., "prod-k8s-operator") - - `infisical.auth.method` (string, optional): Auth method used - - `http.request.method` (string): HTTP method (GET, POST, PUT, DELETE) - - `http.route` (string): API endpoint route pattern - - `http.response.status_code` (int): HTTP status code - - `infisical.project.id` (string, optional): Project ID - - `infisical.project.name` (string, optional): Project name - - `user_agent.original` (string, optional): User agent string - - `client.address` (string, optional): IP address + **Type**: Counter -#### Request Duration + **Unit**: `{request}` -- **Metric Name**: `infisical.http.server.request.duration` -- **Type**: Histogram -- **Unit**: `s` (seconds) -- **Description**: API request latency -- **Buckets**: [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10] -- **Attributes**: - - `infisical.organization.id` (string): Organization ID - - `infisical.organization.name` (string): Organization name - - `infisical.user.id` (string, optional): User ID if human user - - `infisical.user.email` (string, optional): User email - - `infisical.identity.id` (string, optional): Machine identity ID - - `infisical.identity.name` (string, optional): Machine identity name - - `http.request.method` (string): HTTP method - - `http.route` (string): API endpoint route pattern - - `http.response.status_code` (int): HTTP status code - - `infisical.project.id` (string, optional): Project ID - - `infisical.project.name` (string, optional): Project name + **Description**: Total number of API requests to Infisical (covers both human users and machine identities) -#### API Errors by Actor + **Attributes**: + - `infisical.organization.id` (string): Organization ID + - `infisical.organization.name` (string): Organization name (e.g., "Platform Engineering Team") + - `infisical.user.id` (string, optional): User ID if human user + - `infisical.user.email` (string, optional): User email (e.g., "jane.doe@cisco.com") + - `infisical.identity.id` (string, optional): Machine identity ID + - `infisical.identity.name` (string, optional): Machine identity name (e.g., "prod-k8s-operator") + - `infisical.auth.method` (string, optional): Auth method used + - `http.request.method` (string): HTTP method (GET, POST, PUT, DELETE) + - `http.route` (string): API endpoint route pattern + - `http.response.status_code` (int): HTTP status code + - `infisical.project.id` (string, optional): Project ID + - `infisical.project.name` (string, optional): Project name + - `user_agent.original` (string, optional): User agent string + - `client.address` (string, optional): IP address + -- **Metric Name**: `infisical.http.server.error.count` -- **Type**: Counter -- **Unit**: `{error}` -- **Description**: API errors grouped by actor (for identifying misconfigured services) -- **Attributes**: - - `infisical.organization.id` (string): Organization ID - - `infisical.organization.name` (string): Organization name - - `infisical.user.id` (string, optional): User ID if human - - `infisical.user.email` (string, optional): User email - - `infisical.identity.id` (string, optional): Identity ID if machine - - `infisical.identity.name` (string, optional): Identity name - - `http.route` (string): API endpoint where error occurred - - `http.request.method` (string): HTTP method - - `error.type` (string): Error category/type (client_error, server_error, auth_error, rate_limit_error, etc.) - - `infisical.project.id` (string, optional): Project ID - - `infisical.project.name` (string, optional): Project name - - `client.address` (string, optional): IP address - - `user_agent.original` (string, optional): User agent information + + **Metric Name**: `infisical.http.server.request.duration` + + **Type**: Histogram + + **Unit**: `s` (seconds) + + **Description**: API request latency + + **Buckets**: [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10] + + **Attributes**: + - `infisical.organization.id` (string): Organization ID + - `infisical.organization.name` (string): Organization name + - `infisical.user.id` (string, optional): User ID if human user + - `infisical.user.email` (string, optional): User email + - `infisical.identity.id` (string, optional): Machine identity ID + - `infisical.identity.name` (string, optional): Machine identity name + - `http.request.method` (string): HTTP method + - `http.route` (string): API endpoint route pattern + - `http.response.status_code` (int): HTTP status code + - `infisical.project.id` (string, optional): Project ID + - `infisical.project.name` (string, optional): Project name + + + + **Metric Name**: `infisical.http.server.error.count` + + **Type**: Counter + + **Unit**: `{error}` + + **Description**: API errors grouped by actor (for identifying misconfigured services) + + **Attributes**: + - `infisical.organization.id` (string): Organization ID + - `infisical.organization.name` (string): Organization name + - `infisical.user.id` (string, optional): User ID if human + - `infisical.user.email` (string, optional): User email + - `infisical.identity.id` (string, optional): Identity ID if machine + - `infisical.identity.name` (string, optional): Identity name + - `http.route` (string): API endpoint where error occurred + - `http.request.method` (string): HTTP method + - `error.type` (string): Error category/type (client_error, server_error, auth_error, rate_limit_error, etc.) + - `infisical.project.id` (string, optional): Project ID + - `infisical.project.name` (string, optional): Project name + - `client.address` (string, optional): IP address + - `user_agent.original` (string, optional): User agent information + + ### Secret Operations Metrics These metrics provide visibility into secret access patterns, helping you understand which secrets are being accessed, by whom, and from where. Essential for security auditing and access pattern analysis. -#### Secret Read Operations - -- **Metric Name**: `infisical.secret.read.count` -- **Type**: Counter -- **Unit**: `{operation}` -- **Description**: Number of secret read operations -- **Attributes**: - - `infisical.organization.id` (string): Organization ID - - `infisical.organization.name` (string): Organization name - - `infisical.project.id` (string): Project ID - - `infisical.project.name` (string): Project name (e.g., "payment-service-secrets") - - `infisical.environment` (string): Environment (dev, staging, prod) - - `infisical.secret.path` (string): Path to secrets (e.g., "/microservice-a/database") - - `infisical.secret.name` (string, optional): Name of secret - - `infisical.user.id` (string, optional): User ID if human - - `infisical.user.email` (string, optional): User email - - `infisical.identity.id` (string, optional): Machine identity ID - - `infisical.identity.name` (string, optional): Machine identity name - - `user_agent.original` (string, optional): User agent/SDK information - - `client.address` (string, optional): IP address + + + **Metric Name**: `infisical.secret.read.count` + + **Type**: Counter + + **Unit**: `{operation}` + + **Description**: Number of secret read operations + + **Attributes**: + - `infisical.organization.id` (string): Organization ID + - `infisical.organization.name` (string): Organization name + - `infisical.project.id` (string): Project ID + - `infisical.project.name` (string): Project name (e.g., "payment-service-secrets") + - `infisical.environment` (string): Environment (dev, staging, prod) + - `infisical.secret.path` (string): Path to secrets (e.g., "/microservice-a/database") + - `infisical.secret.name` (string, optional): Name of secret + - `infisical.user.id` (string, optional): User ID if human + - `infisical.user.email` (string, optional): User email + - `infisical.identity.id` (string, optional): Machine identity ID + - `infisical.identity.name` (string, optional): Machine identity name + - `user_agent.original` (string, optional): User agent/SDK information + - `client.address` (string, optional): IP address + + ### Authentication Metrics These metrics track authentication attempts and outcomes, enabling you to monitor login success rates, detect potential security threats, and identify authentication issues. -#### Login Attempts - -- **Metric Name**: `infisical.auth.attempt.count` -- **Type**: Counter -- **Unit**: `{attempt}` -- **Description**: Authentication attempts (both successful and failed) -- **Attributes**: - - `infisical.organization.id` (string): Organization ID - - `infisical.organization.name` (string): Organization name - - `infisical.user.id` (string, optional): User ID if human (if identifiable) - - `infisical.user.email` (string, optional): User email (if identifiable) - - `infisical.identity.id` (string, optional): Identity ID if machine (if identifiable) - - `infisical.identity.name` (string, optional): Identity name (if identifiable) - - `infisical.auth.method` (string): Authentication method attempted - - `infisical.auth.result` (string): success or failure - - `error.type` (string, optional): Reason for failure if failed (invalid_credentials, expired_token, invalid_token, etc.) - - `client.address` (string): IP address - - `user_agent.original` (string, optional): User agent/client information - - `infisical.auth.attempt.username` (string, optional): Attempted username/email (if available) + + + **Metric Name**: `infisical.auth.attempt.count` + + **Type**: Counter + + **Unit**: `{attempt}` + + **Description**: Authentication attempts (both successful and failed) + + **Attributes**: + - `infisical.organization.id` (string): Organization ID + - `infisical.organization.name` (string): Organization name + - `infisical.user.id` (string, optional): User ID if human (if identifiable) + - `infisical.user.email` (string, optional): User email (if identifiable) + - `infisical.identity.id` (string, optional): Identity ID if machine (if identifiable) + - `infisical.identity.name` (string, optional): Identity name (if identifiable) + - `infisical.auth.method` (string): Authentication method attempted + - `infisical.auth.result` (string): success or failure + - `error.type` (string, optional): Reason for failure if failed (invalid_credentials, expired_token, invalid_token, etc.) + - `client.address` (string): IP address + - `user_agent.original` (string, optional): User agent/client information + - `infisical.auth.attempt.username` (string, optional): Attempted username/email (if available) + + ### Legacy Metrics These metrics are from the previous instrumentation and may be deprecated in future versions. Consider migrating to the new Core API Metrics for more comprehensive observability. -- `API_latency` - API request latency histogram in milliseconds (Labels: `route`, `method`, `statusCode`) -- `API_errors` - API error count histogram (Labels: `route`, `method`, `type`, `name`) + + + API request latency histogram in milliseconds + + - **Labels**: `route`, `method`, `statusCode` + + + + API error count histogram + + - **Labels**: `route`, `method`, `type`, `name` + + ### Integration & Secret Sync Metrics These metrics monitor secret synchronization operations between Infisical and external systems, helping you track sync health, identify integration failures, and troubleshoot connectivity issues. -- `integration_secret_sync_errors` - Integration secret sync error count + + + Integration secret sync error count - - **Labels**: `version`, `integration`, `integrationId`, `type`, `status`, `name`, `projectId` - - **Example**: Monitor integration sync failures across different services + - **Labels**: `version`, `integration`, `integrationId`, `type`, `status`, `name`, `projectId` + - **Example**: Monitor integration sync failures across different services + -- `secret_sync_sync_secrets_errors` - Secret sync operation error count + + Secret sync operation error count - - **Labels**: `version`, `destination`, `syncId`, `projectId`, `type`, `status`, `name` - - **Example**: Track secret sync failures to external systems + - **Labels**: `version`, `destination`, `syncId`, `projectId`, `type`, `status`, `name` + - **Example**: Track secret sync failures to external systems + -- `secret_sync_import_secrets_errors` - Secret import operation error count + + Secret import operation error count - - **Labels**: `version`, `destination`, `syncId`, `projectId`, `type`, `status`, `name` - - **Example**: Monitor secret import failures + - **Labels**: `version`, `destination`, `syncId`, `projectId`, `type`, `status`, `name` + - **Example**: Monitor secret import failures + -- `secret_sync_remove_secrets_errors` - Secret removal operation error count - - **Labels**: `version`, `destination`, `syncId`, `projectId`, `type`, `status`, `name` - - **Example**: Track secret removal operation failures + + Secret removal operation error count + + - **Labels**: `version`, `destination`, `syncId`, `projectId`, `type`, `status`, `name` + - **Example**: Track secret removal operation failures + + ### System Metrics These low-level HTTP metrics are automatically collected by OpenTelemetry's instrumentation layer, providing baseline performance data for all HTTP traffic. -- `http_server_duration` - HTTP server request duration metrics (histogram buckets, count, sum) -- `http_client_duration` - HTTP client request duration metrics (histogram buckets, count, sum) + + + HTTP server request duration metrics (histogram buckets, count, sum) + + + + HTTP client request duration metrics (histogram buckets, count, sum) + + ## Troubleshooting From 78b8ff17da216cee27e853520e493ca7675bcab4 Mon Sep 17 00:00:00 2001 From: Sheen Capadngan Date: Sat, 1 Nov 2025 03:55:31 +0800 Subject: [PATCH 02/28] misc: addressed comments --- .../guides/monitoring-telemetry.mdx | 263 +++++++++--------- 1 file changed, 137 insertions(+), 126 deletions(-) diff --git a/docs/self-hosting/guides/monitoring-telemetry.mdx b/docs/self-hosting/guides/monitoring-telemetry.mdx index 441a78ac0..763826d4f 100644 --- a/docs/self-hosting/guides/monitoring-telemetry.mdx +++ b/docs/self-hosting/guides/monitoring-telemetry.mdx @@ -47,43 +47,53 @@ OTEL_EXPORT_TYPE=prometheus ### Configuration - 1. **Enable Prometheus export in Infisical**: + + +```bash +OTEL_TELEMETRY_COLLECTION_ENABLED=true +OTEL_EXPORT_TYPE=prometheus +``` + - ```bash - OTEL_TELEMETRY_COLLECTION_ENABLED=true - OTEL_EXPORT_TYPE=prometheus - ``` + + Expose the metrics port in your Infisical backend: - 2. **Expose the metrics port** in your Infisical backend: + - **Docker**: Expose port 9464 + - **Kubernetes**: Create a service exposing port 9464 + - **Other**: Ensure port 9464 is accessible to your monitoring stack + - - **Docker**: Expose port 9464 - - **Kubernetes**: Create a service exposing port 9464 - - **Other**: Ensure port 9464 is accessible to your monitoring stack + +Create `prometheus.yml`: - 3. **Create Prometheus configuration** (`prometheus.yml`): +```yaml +global: + scrape_interval: 30s + evaluation_interval: 30s - ```yaml - global: - scrape_interval: 30s - evaluation_interval: 30s +scrape_configs: + - job_name: "infisical" + scrape_interval: 30s + static_configs: + - targets: ["infisical-backend:9464"] # Adjust hostname/port based on your deployment + metrics_path: "/metrics" +``` - scrape_configs: - - job_name: "infisical" - scrape_interval: 30s - static_configs: - - targets: ["infisical-backend:9464"] # Adjust hostname/port based on your deployment - metrics_path: "/metrics" - ``` + +Replace `infisical-backend:9464` with the actual hostname and port where your Infisical backend is running. This could be: - **Note**: Replace `infisical-backend:9464` with the actual hostname and port where your Infisical backend is running. This could be: - - - **Docker Compose**: `infisical-backend:9464` (service name) - - **Kubernetes**: `infisical-backend.default.svc.cluster.local:9464` (service name) - - **Bare Metal**: `192.168.1.100:9464` (actual IP address) - - **Cloud**: `your-infisical.example.com:9464` (domain name) +- **Docker Compose**: `infisical-backend:9464` (service name) +- **Kubernetes**: `infisical-backend.default.svc.cluster.local:9464` (service name) +- **Bare Metal**: `192.168.1.100:9464` (actual IP address) +- **Cloud**: `your-infisical.example.com:9464` (domain name) + + + ### Deployment Options + Once you've configured Infisical to expose metrics, you'll need to deploy Prometheus to scrape and store them. Below are examples for different deployment environments. Choose the option that matches your infrastructure. + ```yaml @@ -168,94 +178,106 @@ OTEL_EXPORT_TYPE=prometheus ### Configuration - 1. **Enable OTLP export in Infisical**: + + +```bash +OTEL_TELEMETRY_COLLECTION_ENABLED=true +OTEL_EXPORT_TYPE=otlp +OTEL_EXPORT_OTLP_ENDPOINT=http://otel-collector:4318/v1/metrics +OTEL_COLLECTOR_BASIC_AUTH_USERNAME=infisical +OTEL_COLLECTOR_BASIC_AUTH_PASSWORD=infisical +OTEL_OTLP_PUSH_INTERVAL=30000 +``` + - ```bash - OTEL_TELEMETRY_COLLECTION_ENABLED=true - OTEL_EXPORT_TYPE=otlp - OTEL_EXPORT_OTLP_ENDPOINT=http://otel-collector:4318/v1/metrics - OTEL_COLLECTOR_BASIC_AUTH_USERNAME=infisical - OTEL_COLLECTOR_BASIC_AUTH_PASSWORD=infisical - OTEL_OTLP_PUSH_INTERVAL=30000 - ``` + +Create `otel-collector-config.yaml`: - 2. **Create OpenTelemetry Collector configuration** (`otel-collector-config.yaml`): +```yaml +extensions: + health_check: + pprof: + zpages: + basicauth/server: + htpasswd: + inline: | + your_username:your_password - ```yaml - extensions: - health_check: - pprof: - zpages: - basicauth/server: - htpasswd: - inline: | - your_username:your_password +receivers: + otlp: + protocols: + http: + endpoint: 0.0.0.0:4318 + auth: + authenticator: basicauth/server - receivers: - otlp: - protocols: - http: - endpoint: 0.0.0.0:4318 - auth: - authenticator: basicauth/server + prometheus: + config: + scrape_configs: + - job_name: otel-collector + scrape_interval: 30s + static_configs: + - targets: [infisical-backend:9464] + metric_relabel_configs: + - action: labeldrop + regex: "service_instance_id|service_name" - prometheus: - config: - scrape_configs: - - job_name: otel-collector - scrape_interval: 30s - static_configs: - - targets: [infisical-backend:9464] - metric_relabel_configs: - - action: labeldrop - regex: "service_instance_id|service_name" +processors: + batch: - processors: - batch: +exporters: + prometheus: + endpoint: "0.0.0.0:8889" + auth: + authenticator: basicauth/server + resource_to_telemetry_conversion: + enabled: true - exporters: - prometheus: - endpoint: "0.0.0.0:8889" - auth: - authenticator: basicauth/server - resource_to_telemetry_conversion: - enabled: true +service: + extensions: [basicauth/server, health_check, pprof, zpages] + pipelines: + metrics: + receivers: [otlp] + processors: [batch] + exporters: [prometheus] +``` - service: - extensions: [basicauth/server, health_check, pprof, zpages] - pipelines: - metrics: - receivers: [otlp] - processors: [batch] - exporters: [prometheus] - ``` + +Replace `your_username:your_password` with your chosen credentials. These must match the values you set in Infisical's `OTEL_COLLECTOR_BASIC_AUTH_USERNAME` and `OTEL_COLLECTOR_BASIC_AUTH_PASSWORD` environment variables. + + - **Important**: Replace `your_username:your_password` with your chosen credentials. These must match the values you set in Infisical's `OTEL_COLLECTOR_BASIC_AUTH_USERNAME` and `OTEL_COLLECTOR_BASIC_AUTH_PASSWORD` environment variables. + +Create Prometheus configuration for the collector: - 3. **Create Prometheus configuration** for the collector: +```yaml +global: + scrape_interval: 30s + evaluation_interval: 30s - ```yaml - global: - scrape_interval: 30s - evaluation_interval: 30s +scrape_configs: + - job_name: "otel-collector" + scrape_interval: 30s + static_configs: + - targets: ["otel-collector:8889"] # Adjust hostname/port based on your deployment + metrics_path: "/metrics" +``` - scrape_configs: - - job_name: "otel-collector" - scrape_interval: 30s - static_configs: - - targets: ["otel-collector:8889"] # Adjust hostname/port based on your deployment - metrics_path: "/metrics" - ``` + +Replace `otel-collector:8889` with the actual hostname and port where your OpenTelemetry Collector is running. This could be: - **Note**: Replace `otel-collector:8889` with the actual hostname and port where your OpenTelemetry Collector is running. This could be: - - - **Docker Compose**: `otel-collector:8889` (service name) - - **Kubernetes**: `otel-collector.default.svc.cluster.local:8889` (service name) - - **Bare Metal**: `192.168.1.100:8889` (actual IP address) - - **Cloud**: `your-collector.example.com:8889` (domain name) +- **Docker Compose**: `otel-collector:8889` (service name) +- **Kubernetes**: `otel-collector.default.svc.cluster.local:8889` (service name) +- **Bare Metal**: `192.168.1.100:8889` (actual IP address) +- **Cloud**: `your-collector.example.com:8889` (domain name) + + + ### Deployment Options + After configuring Infisical and the OpenTelemetry Collector, you'll need to deploy the collector to receive metrics from Infisical. Below are examples for different deployment environments. Choose the option that matches your infrastructure. + ```yaml @@ -463,24 +485,6 @@ These metrics track authentication attempts and outcomes, enabling you to monito -### Legacy Metrics - -These metrics are from the previous instrumentation and may be deprecated in future versions. Consider migrating to the new Core API Metrics for more comprehensive observability. - - - - API request latency histogram in milliseconds - - - **Labels**: `route`, `method`, `statusCode` - - - - API error count histogram - - - **Labels**: `route`, `method`, `type`, `name` - - - ### Integration & Secret Sync Metrics These metrics monitor secret synchronization operations between Infisical and external systems, helping you track sync health, identify integration failures, and troubleshoot connectivity issues. @@ -531,15 +535,22 @@ These low-level HTTP metrics are automatically collected by OpenTelemetry's inst ## Troubleshooting -### Common Issues + + If your metrics are not showing up in Prometheus or your monitoring system, check the following: -1. **Metrics not appearing**: + - Verify `OTEL_TELEMETRY_COLLECTION_ENABLED=true` is set in your Infisical environment variables + - Ensure the correct `OTEL_EXPORT_TYPE` is set (`prometheus` or `otlp`) + - Check network connectivity between Infisical and your monitoring services (Prometheus or OTLP collector) + - For pull-based monitoring: Verify port 9464 is exposed and accessible + - For push-based monitoring: Verify the OTLP endpoint URL is correct and reachable + - Check Infisical backend logs for any errors related to metrics export + - - Check if `OTEL_TELEMETRY_COLLECTION_ENABLED=true` - - Verify the correct `OTEL_EXPORT_TYPE` is set - - Check network connectivity between services + + If you're experiencing authentication errors with the OpenTelemetry Collector: -2. **Authentication errors**: - - - Verify basic auth credentials in OTLP configuration - - Check if credentials match between Infisical and collector + - Verify basic auth credentials in your OTLP configuration match between Infisical and the collector + - Check that `OTEL_COLLECTOR_BASIC_AUTH_USERNAME` and `OTEL_COLLECTOR_BASIC_AUTH_PASSWORD` match the credentials in your `otel-collector-config.yaml` + - Ensure the htpasswd format in the collector configuration is correct + - Test the collector endpoint manually using curl with the same credentials to verify they work + From b26fb73053b9fd0d926fd0f8fe940c82959e22c9 Mon Sep 17 00:00:00 2001 From: Victor Santos Date: Fri, 31 Oct 2025 18:43:34 -0300 Subject: [PATCH 03/28] refactor: streamline modal close handlers and completion callbacks across various components --- frontend/src/components/features/WishForm.tsx | 23 +- .../CreateOrgModal/CreateOrgModal.tsx | 40 ++-- .../pki-syncs/DeletePkiSyncModal.tsx | 31 +-- .../PkiSyncImportCertificatesModal.tsx | 29 +-- .../PkiSyncRemoveCertificatesModal.tsx | 29 +-- .../pki-syncs/forms/CreatePkiSyncForm.tsx | 8 +- .../pki-syncs/forms/EditPkiSyncForm.tsx | 33 ++- .../project/ProjectOverviewChangeSection.tsx | 36 ++-- .../components/projects/NewProjectModal.tsx | 39 ++-- .../DeleteSecretRotationV2Modal.tsx | 35 ++- .../RotateSecretRotationV2Modal.tsx | 31 +-- .../forms/SecretRotationV2Form.tsx | 20 +- .../DeleteSecretScanningDataSourceModal.tsx | 29 +-- .../forms/SecretScanningDataSourceForm.tsx | 20 +- .../secret-syncs/DeleteSecretSyncModal.tsx | 33 ++- .../SecretSyncImportSecretsModal.tsx | 31 +-- .../SecretSyncRemoveSecretsModal.tsx | 29 +-- .../forms/CreateSecretSyncForm.tsx | 8 +- .../secret-syncs/forms/EditSecretSyncForm.tsx | 35 ++- .../tags/CreateTagModal/CreateTagModal.tsx | 32 ++- .../NavBar/NewSubOrganizationForm.tsx | 33 ++- .../ProjectSelect/ProjectSelect.tsx | 31 +-- .../components/AddServerAdminModal.tsx | 19 +- .../components/ServerAdminsTable.tsx | 55 ++--- .../components/AuthenticationPageForm.tsx | 76 +++---- .../components/CachingPageForm.tsx | 13 +- .../components/EncryptionPageForm.tsx | 17 +- .../components/EnvironmentPageForm.tsx | 34 +-- .../components/GeneralPageForm.tsx | 52 ++--- .../components/UsageReportSection.tsx | 22 +- .../components/AddOrganizationModal.tsx | 29 +-- .../components/MachineIdentitiesTable.tsx | 17 +- .../components/OrganizationsTable.tsx | 35 +-- .../components/UserIdentitiesTable.tsx | 72 ++----- .../src/pages/admin/SignUpPage/SignUpPage.tsx | 35 ++- .../PasswordSetupPage/PasswordSetupPage.tsx | 6 +- .../EmailConfirmationStep.tsx | 82 +++---- .../AlertingPage/components/PkiAlertModal.tsx | 72 +++---- .../components/PkiAlertsSection.tsx | 28 +-- .../components/PkiCollectionModal.tsx | 70 +++--- .../components/PkiCollectionSection.tsx | 28 +-- .../CertAuthDetailsByIDPage.tsx | 41 ++-- .../components/CaRenewalModal.tsx | 30 ++- .../ExternalCaInstallForm.tsx | 33 ++- .../InternalCaInstallForm.tsx | 47 ++-- .../components/CaModal.tsx | 68 +++--- .../components/CaSection.tsx | 43 ++-- .../components/ExternalCaModal.tsx | 94 ++++---- .../components/ExternalCaSection.tsx | 43 ++-- .../components/CertificateImportModal.tsx | 46 ++-- .../components/CertificateIssuanceModal.tsx | 136 ++++++------ .../CertificateManageRenewalModal.tsx | 46 ++-- .../components/CertificateModal.tsx | 62 +++--- .../CertificateRenewalConfigModal.tsx | 40 ++-- .../CertificateRenewalDisableModal.tsx | 40 ++-- .../components/CertificateRenewalModal.tsx | 22 +- .../components/CertificateRevocationModal.tsx | 34 ++- .../components/CertificateTemplateModal.tsx | 94 ++++---- .../CertificateTemplatesSection.tsx | 26 +-- .../components/CertificatesSection.tsx | 22 +- .../components/CertificatesTable.tsx | 36 ++-- .../PkiSyncTable/PkiSyncsTable.tsx | 52 ++--- .../PkiCollectionDetailsByIDPage.tsx | 39 ++-- .../PkiSubscriberDetailsByIDPage.tsx | 34 ++- .../PkiSubscriberDetailsSection.tsx | 44 ++-- .../components/PkiSubscriberModal.tsx | 204 +++++++++--------- .../components/PkiSubscriberSection.tsx | 42 ++-- .../components/PkiSyncActionTriggers.tsx | 54 ++--- .../PkiTemplateListPage.tsx | 26 +-- .../components/PkiTemplateForm.tsx | 90 ++++---- .../CertificateProfilesTab.tsx | 25 +-- .../CreateProfileModal.tsx | 96 ++++----- .../CertificateTemplatesV2Tab.tsx | 26 +-- .../CreateTemplateModal.tsx | 84 ++++---- .../components/DeleteKmipClientModal.tsx | 29 +-- .../KmipPage/components/KmipClientModal.tsx | 20 +- .../components/CmekDecryptModal.tsx | 24 +-- .../components/CmekEncryptModal.tsx | 18 +- .../kms/OverviewPage/components/CmekModal.tsx | 20 +- .../OverviewPage/components/CmekSignModal.tsx | 18 +- .../kms/OverviewPage/components/CmekTable.tsx | 30 +-- .../components/CmekVerifyModal.tsx | 26 +-- .../components/DeleteCmekModal.tsx | 29 +-- .../OrgGroupsSection/OrgGroupModal.tsx | 57 +++-- .../OrgGroupsSection/OrgGroupsSection.tsx | 22 +- .../OrgGroupsSection/OrgGroupsTable.tsx | 24 +-- .../IdentitySection/IdentitySection.tsx | 58 ++--- .../OrgMembersSection/OrgMembersSection.tsx | 81 +++---- .../OrgMembersSection/OrgMembersTable.tsx | 49 ++--- .../OrgRoleTabSection/OrgRoleTable.tsx | 34 ++- .../AppConnectionForm/AppConnectionForm.tsx | 54 ++--- .../components/GroupCreateUpdateModal.tsx | 57 +++-- .../IdentityDetailsByIDPage.tsx | 41 ++-- .../RolePermissionsSection.tsx | 19 +- .../UserDetailsByIDPage.tsx | 64 ++---- .../components/UserDetailsSection.tsx | 28 +-- .../PamAccountForm/PamAccountForm.tsx | 62 ++---- .../components/PamAddFolderModal.tsx | 29 +-- .../components/PamDeleteAccountModal.tsx | 26 +-- .../components/PamDeleteFolderModal.tsx | 24 +-- .../components/PamUpdateFolderModal.tsx | 27 +-- .../components/PamDeleteResourceModal.tsx | 26 +-- .../PamResourceForm/PamResourceForm.tsx | 54 ++--- .../MemberRoleForm/MemberRbacSection.tsx | 18 +- .../IdentityRoleModify.tsx | 16 +- .../MemberRoleDetailsSection.tsx | 67 +++--- .../MemberRoleModify.tsx | 16 +- .../SecretRotationPage/SecretRotationPage.tsx | 50 ++--- .../components/SecretSyncActionTriggers.tsx | 52 ++--- .../components/SlackIntegrationForm.tsx | 43 ++-- .../components/SecretScanningResourceRow.tsx | 27 +-- .../SecretScanningUpdateFindingModal.tsx | 57 +++-- .../SecretScanningConfigForm.tsx | 23 +- .../components/SshHostGroupHostsSection.tsx | 26 +-- .../components/SshHostGroupsSection.tsx | 20 +- .../SshHostsPage/components/SshHostModal.tsx | 133 ++++++------ 116 files changed, 1865 insertions(+), 2949 deletions(-) diff --git a/frontend/src/components/features/WishForm.tsx b/frontend/src/components/features/WishForm.tsx index 118900bc9..28107809a 100644 --- a/frontend/src/components/features/WishForm.tsx +++ b/frontend/src/components/features/WishForm.tsx @@ -35,23 +35,16 @@ export const WishForm = () => { const [isOpen, setIsOpen] = useToggle(false); const createWish = async (data: TFormData) => { - try { - await mutateAsync({ - text: data.text - }); + await mutateAsync({ + text: data.text + }); - createNotification({ - text: "Your wish has been sent to the Infisical team!", - type: "success" - }); + createNotification({ + text: "Your wish has been sent to the Infisical team!", + type: "success" + }); - setIsOpen.off(); - } catch { - createNotification({ - text: "An error occured while sending your wish to the Infisical team.", - type: "error" - }); - } + setIsOpen.off(); }; return ( diff --git a/frontend/src/components/organization/CreateOrgModal/CreateOrgModal.tsx b/frontend/src/components/organization/CreateOrgModal/CreateOrgModal.tsx index 23c3fe6a5..84931f84a 100644 --- a/frontend/src/components/organization/CreateOrgModal/CreateOrgModal.tsx +++ b/frontend/src/components/organization/CreateOrgModal/CreateOrgModal.tsx @@ -43,35 +43,27 @@ export const CreateOrgModal: FC = ({ isOpen, onClose }) => const { mutateAsync: selectOrg } = useSelectOrganization(); const onFormSubmit = async ({ name }: FormData) => { - try { - const organization = await createOrg({ - name - }); + const organization = await createOrg({ + name + }); - await selectOrg({ - organizationId: organization.id - }); + await selectOrg({ + organizationId: organization.id + }); - createNotification({ - text: "Successfully created organization", - type: "success" - }); + createNotification({ + text: "Successfully created organization", + type: "success" + }); - navigate({ - to: "/organization/projects" - }); + navigate({ + to: "/organization/projects" + }); - localStorage.setItem("orgData.id", organization.id); + localStorage.setItem("orgData.id", organization.id); - reset(); - onClose(); - } catch (err) { - console.error(err); - createNotification({ - text: "Failed to created organization", - type: "error" - }); - } + reset(); + onClose(); }; return ( diff --git a/frontend/src/components/pki-syncs/DeletePkiSyncModal.tsx b/frontend/src/components/pki-syncs/DeletePkiSyncModal.tsx index e465d3f34..c01efcbf2 100644 --- a/frontend/src/components/pki-syncs/DeletePkiSyncModal.tsx +++ b/frontend/src/components/pki-syncs/DeletePkiSyncModal.tsx @@ -20,28 +20,19 @@ export const DeletePkiSyncModal = ({ isOpen, onOpenChange, pkiSync, onComplete } const handleDeletePkiSync = async () => { const destinationName = PKI_SYNC_MAP[destination].name; - try { - await deleteSync.mutateAsync({ - syncId, - projectId, - destination - }); + await deleteSync.mutateAsync({ + syncId, + projectId, + destination + }); - createNotification({ - text: `Successfully deleted ${destinationName} PKI Sync`, - type: "success" - }); + createNotification({ + text: `Successfully deleted ${destinationName} PKI Sync`, + type: "success" + }); - if (onComplete) onComplete(); - onOpenChange(false); - } catch (err) { - console.error(err); - - createNotification({ - text: `Failed to delete ${destinationName} PKI Sync`, - type: "error" - }); - } + if (onComplete) onComplete(); + onOpenChange(false); }; return ( diff --git a/frontend/src/components/pki-syncs/PkiSyncImportCertificatesModal.tsx b/frontend/src/components/pki-syncs/PkiSyncImportCertificatesModal.tsx index 33b06dbe4..43192c5e3 100644 --- a/frontend/src/components/pki-syncs/PkiSyncImportCertificatesModal.tsx +++ b/frontend/src/components/pki-syncs/PkiSyncImportCertificatesModal.tsx @@ -21,27 +21,18 @@ const Content = ({ pkiSync, onComplete }: ContentProps) => { const triggerImportCertificates = useTriggerPkiSyncImportCertificates(); const handleTriggerImportCertificates = async () => { - try { - await triggerImportCertificates.mutateAsync({ - syncId, - destination, - projectId - }); + await triggerImportCertificates.mutateAsync({ + syncId, + destination, + projectId + }); - createNotification({ - text: `Successfully triggered certificate import for ${destinationName} Sync`, - type: "success" - }); + createNotification({ + text: `Successfully triggered certificate import for ${destinationName} Sync`, + type: "success" + }); - onComplete(); - } catch (err) { - console.error(err); - - createNotification({ - text: `Failed to trigger certificate import for ${destinationName} Sync`, - type: "error" - }); - } + onComplete(); }; return ( diff --git a/frontend/src/components/pki-syncs/PkiSyncRemoveCertificatesModal.tsx b/frontend/src/components/pki-syncs/PkiSyncRemoveCertificatesModal.tsx index f17855289..cee845381 100644 --- a/frontend/src/components/pki-syncs/PkiSyncRemoveCertificatesModal.tsx +++ b/frontend/src/components/pki-syncs/PkiSyncRemoveCertificatesModal.tsx @@ -21,27 +21,18 @@ const Content = ({ pkiSync, onComplete }: ContentProps) => { const triggerRemoveCertificates = useTriggerPkiSyncRemoveCertificates(); const handleTriggerRemoveCertificates = async () => { - try { - await triggerRemoveCertificates.mutateAsync({ - syncId, - destination, - projectId - }); + await triggerRemoveCertificates.mutateAsync({ + syncId, + destination, + projectId + }); - createNotification({ - text: `Successfully triggered certificate removal for ${destinationName} Sync`, - type: "success" - }); + createNotification({ + text: `Successfully triggered certificate removal for ${destinationName} Sync`, + type: "success" + }); - onComplete(); - } catch (err) { - console.error(err); - - createNotification({ - text: `Failed to trigger certificate removal for ${destinationName} Sync`, - type: "error" - }); - } + onComplete(); }; return ( diff --git a/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsx b/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsx index 582518bd7..085e57882 100644 --- a/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsx +++ b/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsx @@ -72,14 +72,8 @@ export const CreatePkiSyncForm = ({ destination, onComplete, onCancel }: Props) type: "success" }); onComplete(pkiSync); - } catch (err: Error | unknown) { - console.error(err); + } catch { setShowConfirmation(false); - createNotification({ - title: `Failed to add ${destinationName} Certificate Sync`, - text: err instanceof Error ? err.message : "An unknown error occurred", - type: "error" - }); } }; diff --git a/frontend/src/components/pki-syncs/forms/EditPkiSyncForm.tsx b/frontend/src/components/pki-syncs/forms/EditPkiSyncForm.tsx index 73f5bc2bc..7f8ee207f 100644 --- a/frontend/src/components/pki-syncs/forms/EditPkiSyncForm.tsx +++ b/frontend/src/components/pki-syncs/forms/EditPkiSyncForm.tsx @@ -38,28 +38,19 @@ export const EditPkiSyncForm = ({ pkiSync, fields, onComplete }: Props) => { }); const onSubmit = async ({ connection, ...formData }: TUpdatePkiSyncForm) => { - try { - const updatedPkiSync = await updatePkiSync.mutateAsync({ - syncId: pkiSync.id, - ...formData, - connectionId: connection.id, - projectId: pkiSync.projectId, - destination: pkiSync.destination - }); + const updatedPkiSync = await updatePkiSync.mutateAsync({ + syncId: pkiSync.id, + ...formData, + connectionId: connection.id, + projectId: pkiSync.projectId, + destination: pkiSync.destination + }); - createNotification({ - text: `Successfully updated ${destinationName} PKI Sync`, - type: "success" - }); - onComplete(updatedPkiSync); - } catch (err: any) { - console.error(err); - createNotification({ - title: `Failed to update ${destinationName} PKI Sync`, - text: err.message, - type: "error" - }); - } + createNotification({ + text: `Successfully updated ${destinationName} PKI Sync`, + type: "success" + }); + onComplete(updatedPkiSync); }; let Component: ReactNode; diff --git a/frontend/src/components/project/ProjectOverviewChangeSection.tsx b/frontend/src/components/project/ProjectOverviewChangeSection.tsx index 548fbd1e3..455b0806a 100644 --- a/frontend/src/components/project/ProjectOverviewChangeSection.tsx +++ b/frontend/src/components/project/ProjectOverviewChangeSection.tsx @@ -56,30 +56,22 @@ export const ProjectOverviewChangeSection = ({ showSlugField = false }: Props) = }, [currentProject, showSlugField]); const onFormSubmit = async (data: BaseFormData | FormDataWithSlug) => { - try { - if (!currentProject?.id) return; + if (!currentProject?.id) return; - await mutateAsync({ - projectId: currentProject.id, - newProjectName: data.name, - newProjectDescription: data.description, - ...(showSlugField && - "slug" in data && { - newSlug: data.slug !== currentProject.slug ? data.slug : undefined - }) - }); + await mutateAsync({ + projectId: currentProject.id, + newProjectName: data.name, + newProjectDescription: data.description, + ...(showSlugField && + "slug" in data && { + newSlug: data.slug !== currentProject.slug ? data.slug : undefined + }) + }); - createNotification({ - text: "Successfully updated project overview", - type: "success" - }); - } catch (err) { - console.error(err); - createNotification({ - text: "Failed to update project overview", - type: "error" - }); - } + createNotification({ + text: "Successfully updated project overview", + type: "success" + }); }; return ( diff --git a/frontend/src/components/projects/NewProjectModal.tsx b/frontend/src/components/projects/NewProjectModal.tsx index d71e7b957..663d6a0b7 100644 --- a/frontend/src/components/projects/NewProjectModal.tsx +++ b/frontend/src/components/projects/NewProjectModal.tsx @@ -141,29 +141,24 @@ const NewProjectForm = ({ onOpenChange }: NewProjectFormProps) => { // type check if (!currentOrg) return; if (!user) return; - try { - const { - data: { project } - } = await createWs.mutateAsync({ - projectName: name, - projectDescription: description, - kmsKeyId: kmsKeyId !== INTERNAL_KMS_KEY_ID ? kmsKeyId : undefined, - template, - type - }); - await refetchWorkspaces(); + const { + data: { project } + } = await createWs.mutateAsync({ + projectName: name, + projectDescription: description, + kmsKeyId: kmsKeyId !== INTERNAL_KMS_KEY_ID ? kmsKeyId : undefined, + template, + type + }); + await refetchWorkspaces(); - createNotification({ text: "Project created", type: "success" }); - reset(); - onOpenChange(false); - navigate({ - to: getProjectHomePage(project.type, project.environments), - params: { projectId: project.id } - }); - } catch (err) { - console.error(err); - createNotification({ text: "Failed to create project", type: "error" }); - } + createNotification({ text: "Project created", type: "success" }); + reset(); + onOpenChange(false); + navigate({ + to: getProjectHomePage(project.type, project.environments), + params: { projectId: project.id } + }); }; const onSubmit = handleSubmit((data) => { return onCreateProject(data); diff --git a/frontend/src/components/secret-rotations-v2/DeleteSecretRotationV2Modal.tsx b/frontend/src/components/secret-rotations-v2/DeleteSecretRotationV2Modal.tsx index 20b08eb49..524c66933 100644 --- a/frontend/src/components/secret-rotations-v2/DeleteSecretRotationV2Modal.tsx +++ b/frontend/src/components/secret-rotations-v2/DeleteSecretRotationV2Modal.tsx @@ -37,29 +37,22 @@ export const DeleteSecretRotationV2Modal = ({ const handleDeleteSecretRotation = async () => { const rotationType = SECRET_ROTATION_MAP[type].name; - try { - await deleteSecretRotation.mutateAsync({ - rotationId, - type, - revokeGeneratedCredentials, - deleteSecrets, - projectId, - secretPath: folder.path - }); + await deleteSecretRotation.mutateAsync({ + rotationId, + type, + revokeGeneratedCredentials, + deleteSecrets, + projectId, + secretPath: folder.path + }); - createNotification({ - text: `Successfully deleted ${rotationType} Rotation`, - type: "success" - }); + createNotification({ + text: `Successfully deleted ${rotationType} Rotation`, + type: "success" + }); - if (onComplete) onComplete(); - onOpenChange(false); - } catch { - createNotification({ - text: `Failed to delete ${rotationType} Rotation`, - type: "error" - }); - } + if (onComplete) onComplete(); + onOpenChange(false); }; return ( diff --git a/frontend/src/components/secret-rotations-v2/RotateSecretRotationV2Modal.tsx b/frontend/src/components/secret-rotations-v2/RotateSecretRotationV2Modal.tsx index e2c931d49..7ad9611be 100644 --- a/frontend/src/components/secret-rotations-v2/RotateSecretRotationV2Modal.tsx +++ b/frontend/src/components/secret-rotations-v2/RotateSecretRotationV2Modal.tsx @@ -22,28 +22,19 @@ const Content = ({ secretRotation, onComplete }: ContentProps) => { const rotationType = SECRET_ROTATION_MAP[type].name; const handleRotateSecrets = async () => { - try { - await rotateSecrets.mutateAsync({ - rotationId, - type, - projectId, - secretPath: folder.path - }); + await rotateSecrets.mutateAsync({ + rotationId, + type, + projectId, + secretPath: folder.path + }); - createNotification({ - text: `Successfully rotated ${rotationType} secrets`, - type: "success" - }); + createNotification({ + text: `Successfully rotated ${rotationType} secrets`, + type: "success" + }); - onComplete(); - } catch (err) { - console.error(err); - - createNotification({ - text: `Failed to rotate ${rotationType} secrets`, - type: "error" - }); - } + onComplete(); }; return ( diff --git a/frontend/src/components/secret-rotations-v2/forms/SecretRotationV2Form.tsx b/frontend/src/components/secret-rotations-v2/forms/SecretRotationV2Form.tsx index 9887da026..320793ed1 100644 --- a/frontend/src/components/secret-rotations-v2/forms/SecretRotationV2Form.tsx +++ b/frontend/src/components/secret-rotations-v2/forms/SecretRotationV2Form.tsx @@ -120,21 +120,13 @@ export const SecretRotationV2Form = ({ environment: environment.slug, projectId: currentProject.id }); - try { - const rotation = await mutation; + const rotation = await mutation; - createNotification({ - text: `Successfully ${secretRotation ? "updated" : "created"} ${rotationType} Rotation`, - type: "success" - }); - onComplete(rotation); - } catch (err: any) { - createNotification({ - title: `Failed to ${secretRotation ? "update" : "create"} ${rotationType} Rotation`, - text: err.message, - type: "error" - }); - } + createNotification({ + text: `Successfully ${secretRotation ? "updated" : "created"} ${rotationType} Rotation`, + type: "success" + }); + onComplete(rotation); }; const handlePrev = () => { diff --git a/frontend/src/components/secret-scanning/DeleteSecretScanningDataSourceModal.tsx b/frontend/src/components/secret-scanning/DeleteSecretScanningDataSourceModal.tsx index 9cf918dfb..091de4cc0 100644 --- a/frontend/src/components/secret-scanning/DeleteSecretScanningDataSourceModal.tsx +++ b/frontend/src/components/secret-scanning/DeleteSecretScanningDataSourceModal.tsx @@ -28,26 +28,19 @@ export const DeleteSecretScanningDataSourceModal = ({ const handleDeleteDataSource = async () => { const dataSourceType = SECRET_SCANNING_DATA_SOURCE_MAP[type].name; - try { - await deleteDataSource.mutateAsync({ - dataSourceId, - type, - projectId - }); + await deleteDataSource.mutateAsync({ + dataSourceId, + type, + projectId + }); - createNotification({ - text: `Successfully deleted ${dataSourceType} Data Source`, - type: "success" - }); + createNotification({ + text: `Successfully deleted ${dataSourceType} Data Source`, + type: "success" + }); - if (onComplete) onComplete(); - onOpenChange(false); - } catch { - createNotification({ - text: `Failed to delete ${dataSourceType} Data Source`, - type: "error" - }); - } + if (onComplete) onComplete(); + onOpenChange(false); }; return ( diff --git a/frontend/src/components/secret-scanning/forms/SecretScanningDataSourceForm.tsx b/frontend/src/components/secret-scanning/forms/SecretScanningDataSourceForm.tsx index 4d5ccdc79..563f82d46 100644 --- a/frontend/src/components/secret-scanning/forms/SecretScanningDataSourceForm.tsx +++ b/frontend/src/components/secret-scanning/forms/SecretScanningDataSourceForm.tsx @@ -73,21 +73,13 @@ export const SecretScanningDataSourceForm = ({ connectionId: connection?.id, projectId: currentProject.id }); - try { - const source = await mutation; + const source = await mutation; - createNotification({ - text: `Successfully ${source ? "updated" : "created"} ${sourceType} Data Source`, - type: "success" - }); - onComplete(source); - } catch (err: any) { - createNotification({ - title: `Failed to ${dataSource ? "update" : "create"} ${sourceType} Data Source`, - text: err.message, - type: "error" - }); - } + createNotification({ + text: `Successfully ${source ? "updated" : "created"} ${sourceType} Data Source`, + type: "success" + }); + onComplete(source); }; const handlePrev = () => { diff --git a/frontend/src/components/secret-syncs/DeleteSecretSyncModal.tsx b/frontend/src/components/secret-syncs/DeleteSecretSyncModal.tsx index 2b3903a9b..de8b2e79d 100644 --- a/frontend/src/components/secret-syncs/DeleteSecretSyncModal.tsx +++ b/frontend/src/components/secret-syncs/DeleteSecretSyncModal.tsx @@ -23,29 +23,20 @@ export const DeleteSecretSyncModal = ({ isOpen, onOpenChange, secretSync, onComp const handleDeleteSecretSync = async () => { const destinationName = SECRET_SYNC_MAP[destination].name; - try { - await deleteSync.mutateAsync({ - syncId, - destination, - removeSecrets, - projectId - }); + await deleteSync.mutateAsync({ + syncId, + destination, + removeSecrets, + projectId + }); - createNotification({ - text: `Successfully removed ${destinationName} Sync`, - type: "success" - }); + createNotification({ + text: `Successfully removed ${destinationName} Sync`, + type: "success" + }); - if (onComplete) onComplete(); - onOpenChange(false); - } catch (err) { - console.error(err); - - createNotification({ - text: `Failed to remove ${destinationName} Sync`, - type: "error" - }); - } + if (onComplete) onComplete(); + onOpenChange(false); }; return ( diff --git a/frontend/src/components/secret-syncs/SecretSyncImportSecretsModal.tsx b/frontend/src/components/secret-syncs/SecretSyncImportSecretsModal.tsx index c1b21a771..656faffeb 100644 --- a/frontend/src/components/secret-syncs/SecretSyncImportSecretsModal.tsx +++ b/frontend/src/components/secret-syncs/SecretSyncImportSecretsModal.tsx @@ -51,28 +51,19 @@ const Content = ({ secretSync, onComplete }: ContentProps) => { const triggerImportSecrets = useTriggerSecretSyncImportSecrets(); const handleTriggerImportSecrets = async ({ importBehavior }: TFormData) => { - try { - await triggerImportSecrets.mutateAsync({ - syncId, - destination, - importBehavior, - projectId - }); + await triggerImportSecrets.mutateAsync({ + syncId, + destination, + importBehavior, + projectId + }); - createNotification({ - text: `Successfully triggered secret import for ${destinationName} Sync`, - type: "success" - }); + createNotification({ + text: `Successfully triggered secret import for ${destinationName} Sync`, + type: "success" + }); - onComplete(); - } catch (err) { - console.error(err); - - createNotification({ - text: `Failed to trigger secret import for ${destinationName} Sync`, - type: "error" - }); - } + onComplete(); }; return ( diff --git a/frontend/src/components/secret-syncs/SecretSyncRemoveSecretsModal.tsx b/frontend/src/components/secret-syncs/SecretSyncRemoveSecretsModal.tsx index 718392b92..9c9c0e659 100644 --- a/frontend/src/components/secret-syncs/SecretSyncRemoveSecretsModal.tsx +++ b/frontend/src/components/secret-syncs/SecretSyncRemoveSecretsModal.tsx @@ -21,27 +21,18 @@ const Content = ({ secretSync, onComplete }: ContentProps) => { const triggerSyncImport = useTriggerSecretSyncRemoveSecrets(); const handleTriggerRemoveSecrets = async () => { - try { - await triggerSyncImport.mutateAsync({ - syncId, - destination, - projectId - }); + await triggerSyncImport.mutateAsync({ + syncId, + destination, + projectId + }); - createNotification({ - text: `Successfully triggered secret removal for ${destinationName} Sync`, - type: "success" - }); + createNotification({ + text: `Successfully triggered secret removal for ${destinationName} Sync`, + type: "success" + }); - onComplete(); - } catch (err) { - console.error(err); - - createNotification({ - text: `Failed to trigger secret removal for ${destinationName} Sync`, - type: "error" - }); - } + onComplete(); }; return ( diff --git a/frontend/src/components/secret-syncs/forms/CreateSecretSyncForm.tsx b/frontend/src/components/secret-syncs/forms/CreateSecretSyncForm.tsx index ebad86cbd..21a69b163 100644 --- a/frontend/src/components/secret-syncs/forms/CreateSecretSyncForm.tsx +++ b/frontend/src/components/secret-syncs/forms/CreateSecretSyncForm.tsx @@ -88,14 +88,8 @@ export const CreateSecretSyncForm = ({ type: "success" }); onComplete(secretSync); - } catch (err: any) { - console.error(err); + } catch { setShowConfirmation(false); - createNotification({ - title: `Failed to add ${destinationName} Sync`, - text: err.message, - type: "error" - }); } }; diff --git a/frontend/src/components/secret-syncs/forms/EditSecretSyncForm.tsx b/frontend/src/components/secret-syncs/forms/EditSecretSyncForm.tsx index 2085afe9c..207b72cd8 100644 --- a/frontend/src/components/secret-syncs/forms/EditSecretSyncForm.tsx +++ b/frontend/src/components/secret-syncs/forms/EditSecretSyncForm.tsx @@ -58,29 +58,20 @@ export const EditSecretSyncForm = ({ secretSync, fields, onComplete }: Props) => const performUpdate = useCallback( async (formData: TSecretSyncForm) => { - try { - const { environment, connection, ...updateData } = formData; - const updatedSecretSync = await updateSecretSync.mutateAsync({ - syncId: secretSync.id, - ...updateData, - environment: environment?.slug, - connectionId: connection.id, - projectId: secretSync.projectId - }); + const { environment, connection, ...updateData } = formData; + const updatedSecretSync = await updateSecretSync.mutateAsync({ + syncId: secretSync.id, + ...updateData, + environment: environment?.slug, + connectionId: connection.id, + projectId: secretSync.projectId + }); - createNotification({ - text: `Successfully updated ${destinationName} Sync`, - type: "success" - }); - onComplete(updatedSecretSync); - } catch (err: any) { - console.error(err); - createNotification({ - title: `Failed to update ${destinationName} Sync`, - text: err.message, - type: "error" - }); - } + createNotification({ + text: `Successfully updated ${destinationName} Sync`, + type: "success" + }); + onComplete(updatedSecretSync); }, [updateSecretSync, secretSync.id, secretSync.projectId, destinationName, onComplete] ); diff --git a/frontend/src/components/tags/CreateTagModal/CreateTagModal.tsx b/frontend/src/components/tags/CreateTagModal/CreateTagModal.tsx index 3c38926af..97e74cae4 100644 --- a/frontend/src/components/tags/CreateTagModal/CreateTagModal.tsx +++ b/frontend/src/components/tags/CreateTagModal/CreateTagModal.tsx @@ -130,26 +130,18 @@ export const CreateTagModal = ({ isOpen, onToggle, append, currentSecret }: Prop }, [isOpen]); const onFormSubmit = async ({ slug, color }: FormData) => { - try { - const data = await createWsTag({ - projectId, - tagColor: color, - tagSlug: slug - }); - append(data); - onToggle(false); - reset(); - createNotification({ - text: "Successfully created a tag", - type: "success" - }); - } catch (error) { - console.error(error); - createNotification({ - text: "Failed to create a tag", - type: "error" - }); - } + const data = await createWsTag({ + projectId, + tagColor: color, + tagSlug: slug + }); + append(data); + onToggle(false); + reset(); + createNotification({ + text: "Successfully created a tag", + type: "success" + }); }; return ( diff --git a/frontend/src/layouts/OrganizationLayout/components/NavBar/NewSubOrganizationForm.tsx b/frontend/src/layouts/OrganizationLayout/components/NavBar/NewSubOrganizationForm.tsx index 75041a69e..bfea2e788 100644 --- a/frontend/src/layouts/OrganizationLayout/components/NavBar/NewSubOrganizationForm.tsx +++ b/frontend/src/layouts/OrganizationLayout/components/NavBar/NewSubOrganizationForm.tsx @@ -36,28 +36,21 @@ export const NewSubOrganizationForm = ({ onClose }: ContentProps) => { const router = useRouter(); const onSubmit = async ({ name }: FormData) => { - try { - const { organization } = await createSubOrg.mutateAsync({ - name - }); + const { organization } = await createSubOrg.mutateAsync({ + name + }); - createNotification({ - type: "success", - text: "Successfully created sub organization" - }); - onClose(); + createNotification({ + type: "success", + text: "Successfully created sub organization" + }); + onClose(); - navigate({ - to: "/organization/projects", - search: (prev) => ({ ...prev, subOrganization: organization.name }) - }); - await router.invalidate({ sync: true }).catch(() => null); - } catch { - createNotification({ - text: "Failed to create sub organization", - type: "error" - }); - } + navigate({ + to: "/organization/projects", + search: (prev) => ({ ...prev, subOrganization: organization.name }) + }); + await router.invalidate({ sync: true }).catch(() => null); }; return ( diff --git a/frontend/src/layouts/ProjectLayout/components/ProjectSelect/ProjectSelect.tsx b/frontend/src/layouts/ProjectLayout/components/ProjectSelect/ProjectSelect.tsx index c26333332..8e985fe58 100644 --- a/frontend/src/layouts/ProjectLayout/components/ProjectSelect/ProjectSelect.tsx +++ b/frontend/src/layouts/ProjectLayout/components/ProjectSelect/ProjectSelect.tsx @@ -11,7 +11,6 @@ import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { Link, linkOptions } from "@tanstack/react-router"; import { UpgradePlanModal } from "@app/components/license/UpgradePlanModal"; -import { createNotification } from "@app/components/notifications"; import { OrgPermissionCan } from "@app/components/permissions"; import { NewProjectModal } from "@app/components/projects"; import { @@ -59,31 +58,17 @@ export const ProjectSelect = () => { const { mutateAsync: updateUserProjectFavorites } = useUpdateUserProjectFavorites(); const addProjectToFavorites = async (projectId: string) => { - try { - await updateUserProjectFavorites({ - orgId: currentOrg!.id, - projectFavorites: [...(projectFavorites || []), projectId] - }); - } catch { - createNotification({ - text: "Failed to add project to favorites.", - type: "error" - }); - } + await updateUserProjectFavorites({ + orgId: currentOrg!.id, + projectFavorites: [...(projectFavorites || []), projectId] + }); }; const removeProjectFromFavorites = async (projectId: string) => { - try { - await updateUserProjectFavorites({ - orgId: currentOrg!.id, - projectFavorites: [...(projectFavorites || []).filter((entry) => entry !== projectId)] - }); - } catch { - createNotification({ - text: "Failed to remove project from favorites.", - type: "error" - }); - } + await updateUserProjectFavorites({ + orgId: currentOrg!.id, + projectFavorites: [...(projectFavorites || []).filter((entry) => entry !== projectId)] + }); }; const isAddingProjectsAllowed = subscription?.workspaceLimit diff --git a/frontend/src/pages/admin/AccessManagementPage/components/AddServerAdminModal.tsx b/frontend/src/pages/admin/AccessManagementPage/components/AddServerAdminModal.tsx index 3e7638627..63ec2fa44 100644 --- a/frontend/src/pages/admin/AccessManagementPage/components/AddServerAdminModal.tsx +++ b/frontend/src/pages/admin/AccessManagementPage/components/AddServerAdminModal.tsx @@ -65,20 +65,13 @@ const Content = ({ onClose }: ContentProps) => { const users = usersData.filter((user) => !user.superAdmin); const onSubmit = async ({ user }: FormData) => { - try { - await grantAdmin.mutateAsync(user.id); + await grantAdmin.mutateAsync(user.id); - createNotification({ - type: "success", - text: "Successfully granted server admin status" - }); - onClose(); - } catch { - createNotification({ - text: "Failed to grant server admin status", - type: "error" - }); - } + createNotification({ + type: "success", + text: "Successfully granted server admin status" + }); + onClose(); }; return ( diff --git a/frontend/src/pages/admin/AccessManagementPage/components/ServerAdminsTable.tsx b/frontend/src/pages/admin/AccessManagementPage/components/ServerAdminsTable.tsx index 7e207fbc5..2e7016ee7 100644 --- a/frontend/src/pages/admin/AccessManagementPage/components/ServerAdminsTable.tsx +++ b/frontend/src/pages/admin/AccessManagementPage/components/ServerAdminsTable.tsx @@ -303,18 +303,11 @@ export const ServerAdminsTable = () => { const handleRemoveUser = async () => { const { id } = popUp?.removeUser?.data as { id: string; username: string }; - try { - await deleteUser(id); - createNotification({ - type: "success", - text: "Successfully deleted user" - }); - } catch { - createNotification({ - type: "error", - text: "Error deleting user" - }); - } + await deleteUser(id); + createNotification({ + type: "success", + text: "Successfully deleted user" + }); handlePopUpClose("removeUser"); }; @@ -322,39 +315,25 @@ export const ServerAdminsTable = () => { const handleRemoveServerAdminAccess = async () => { const { id } = popUp?.removeServerAdmin?.data as { id: string; username: string }; - try { - await removeAdminAccess(id); - createNotification({ - type: "success", - text: "Successfully removed server admin access from user" - }); - } catch { - createNotification({ - type: "error", - text: "Error removing server admin access from user" - }); - } + await removeAdminAccess(id); + createNotification({ + type: "success", + text: "Successfully removed server admin access from user" + }); handlePopUpClose("removeServerAdmin"); }; const handleRemoveUsers = async () => { - try { - await deleteUsers(selectedUsers.map((user) => user.id)); + await deleteUsers(selectedUsers.map((user) => user.id)); - createNotification({ - text: "Successfully removed users", - type: "success" - }); + createNotification({ + text: "Successfully removed users", + type: "success" + }); - setSelectedUsers([]); - handlePopUpClose("removeUsers"); - } catch { - createNotification({ - text: "Failed to remove users", - type: "error" - }); - } + setSelectedUsers([]); + handlePopUpClose("removeUsers"); }; return ( diff --git a/frontend/src/pages/admin/AuthenticationPage/components/AuthenticationPageForm.tsx b/frontend/src/pages/admin/AuthenticationPage/components/AuthenticationPageForm.tsx index 2abb96e60..f8ca30c52 100644 --- a/frontend/src/pages/admin/AuthenticationPage/components/AuthenticationPageForm.tsx +++ b/frontend/src/pages/admin/AuthenticationPage/components/AuthenticationPageForm.tsx @@ -54,59 +54,51 @@ export const AuthenticationPageForm = () => { }); const onAuthFormSubmit = async (formData: TAuthForm) => { - try { - const enabledMethods: LoginMethod[] = []; - if (formData.isEmailEnabled) { - enabledMethods.push(LoginMethod.EMAIL); - } + const enabledMethods: LoginMethod[] = []; + if (formData.isEmailEnabled) { + enabledMethods.push(LoginMethod.EMAIL); + } - if (formData.isGoogleEnabled) { - enabledMethods.push(LoginMethod.GOOGLE); - } + if (formData.isGoogleEnabled) { + enabledMethods.push(LoginMethod.GOOGLE); + } - if (formData.isGithubEnabled) { - enabledMethods.push(LoginMethod.GITHUB); - } + if (formData.isGithubEnabled) { + enabledMethods.push(LoginMethod.GITHUB); + } - if (formData.isGitlabEnabled) { - enabledMethods.push(LoginMethod.GITLAB); - } + if (formData.isGitlabEnabled) { + enabledMethods.push(LoginMethod.GITLAB); + } - if (formData.isSamlEnabled) { - enabledMethods.push(LoginMethod.SAML); - } + if (formData.isSamlEnabled) { + enabledMethods.push(LoginMethod.SAML); + } - if (formData.isLdapEnabled) { - enabledMethods.push(LoginMethod.LDAP); - } + if (formData.isLdapEnabled) { + enabledMethods.push(LoginMethod.LDAP); + } - if (formData.isOidcEnabled) { - enabledMethods.push(LoginMethod.OIDC); - } + if (formData.isOidcEnabled) { + enabledMethods.push(LoginMethod.OIDC); + } - if (!enabledMethods.length) { - createNotification({ - type: "error", - text: "At least one login method should be enabled." - }); - return; - } - - await updateServerConfig({ - enabledLoginMethods: enabledMethods - }); - - createNotification({ - text: "Login methods have been successfully updated.", - type: "success" - }); - } catch (e) { - console.error(e); + if (!enabledMethods.length) { createNotification({ type: "error", - text: "Failed to update login methods." + text: "At least one login method should be enabled." }); + return; } + + await updateServerConfig({ + enabledLoginMethods: enabledMethods + }); + + createNotification({ + text: "Login methods have been successfully updated.", + type: "success" + }); }; return ( diff --git a/frontend/src/pages/admin/CachingPage/components/CachingPageForm.tsx b/frontend/src/pages/admin/CachingPage/components/CachingPageForm.tsx index fbf956b7b..e9bdc3d1e 100644 --- a/frontend/src/pages/admin/CachingPage/components/CachingPageForm.tsx +++ b/frontend/src/pages/admin/CachingPage/components/CachingPageForm.tsx @@ -31,15 +31,10 @@ export const CachingPageForm = () => { const handleInvalidateCacheSubmit = async () => { if (!type || isInvalidating) return; - try { - await invalidateCache({ type }); - createNotification({ text: `Began invalidating ${type} cache`, type: "success" }); - setShouldPoll(true); - handlePopUpClose("invalidateCache"); - } catch (err) { - console.error(err); - createNotification({ text: `Failed to invalidate ${type} cache`, type: "error" }); - } + await invalidateCache({ type }); + createNotification({ text: `Began invalidating ${type} cache`, type: "success" }); + setShouldPoll(true); + handlePopUpClose("invalidateCache"); }; useEffect(() => { diff --git a/frontend/src/pages/admin/EncryptionPage/components/EncryptionPageForm.tsx b/frontend/src/pages/admin/EncryptionPage/components/EncryptionPageForm.tsx index 8372dd557..3dafdabd3 100644 --- a/frontend/src/pages/admin/EncryptionPage/components/EncryptionPageForm.tsx +++ b/frontend/src/pages/admin/EncryptionPage/components/EncryptionPageForm.tsx @@ -60,19 +60,12 @@ export const EncryptionPageForm = () => { return; } - try { - await updateEncryptionStrategy(formData.encryptionStrategy); + await updateEncryptionStrategy(formData.encryptionStrategy); - createNotification({ - type: "success", - text: "Encryption strategy updated successfully" - }); - } catch { - createNotification({ - type: "error", - text: "Failed to update encryption strategy" - }); - } + createNotification({ + type: "success", + text: "Encryption strategy updated successfully" + }); }, []); return ( diff --git a/frontend/src/pages/admin/EnvironmentPage/components/EnvironmentPageForm.tsx b/frontend/src/pages/admin/EnvironmentPage/components/EnvironmentPageForm.tsx index 5f74593a3..8361aa944 100644 --- a/frontend/src/pages/admin/EnvironmentPage/components/EnvironmentPageForm.tsx +++ b/frontend/src/pages/admin/EnvironmentPage/components/EnvironmentPageForm.tsx @@ -176,31 +176,19 @@ export const EnvironmentPageForm = () => { const onSubmit = useCallback( async (formData: TForm) => { - try { - const filteredFormData = Object.fromEntries( - Object.entries(formData).filter(([, value]) => value !== "") - ); - await updateServerConfig({ - envOverrides: filteredFormData - }); + const filteredFormData = Object.fromEntries( + Object.entries(formData).filter(([, value]) => value !== "") + ); + await updateServerConfig({ + envOverrides: filteredFormData + }); - createNotification({ - type: "success", - text: "Environment overrides updated successfully. It can take up to 5 minutes to take effect." - }); + createNotification({ + type: "success", + text: "Environment overrides updated successfully. It can take up to 5 minutes to take effect." + }); - reset(formData); - } catch (error) { - const errorMessage = - (error as any)?.response?.data?.message || - (error as any)?.message || - "An unknown error occurred"; - createNotification({ - type: "error", - title: "Failed to update environment overrides", - text: errorMessage - }); - } + reset(formData); }, [reset, updateServerConfig] ); diff --git a/frontend/src/pages/admin/GeneralPage/components/GeneralPageForm.tsx b/frontend/src/pages/admin/GeneralPage/components/GeneralPageForm.tsx index be92dd679..eff3e3cf8 100644 --- a/frontend/src/pages/admin/GeneralPage/components/GeneralPageForm.tsx +++ b/frontend/src/pages/admin/GeneralPage/components/GeneralPageForm.tsx @@ -68,37 +68,29 @@ export const GeneralPageForm = () => { const organizations = useGetOrganizations(); const onFormSubmit = async (formData: TDashboardForm) => { - try { - const { - allowedSignUpDomain, - trustSamlEmails, - trustLdapEmails, - trustOidcEmails, - authConsentContent, - pageFrameContent - } = formData; + const { + allowedSignUpDomain, + trustSamlEmails, + trustLdapEmails, + trustOidcEmails, + authConsentContent, + pageFrameContent + } = formData; - await updateServerConfig({ - defaultAuthOrgId: defaultAuthOrgId || null, - allowSignUp: signUpMode !== SignUpModes.Disabled, - allowedSignUpDomain: signUpMode === SignUpModes.Anyone ? allowedSignUpDomain : null, - trustSamlEmails, - trustLdapEmails, - trustOidcEmails, - authConsentContent, - pageFrameContent - }); - createNotification({ - text: "Successfully changed sign up setting.", - type: "success" - }); - } catch (e) { - console.error(e); - createNotification({ - type: "error", - text: "Failed to update sign up setting." - }); - } + await updateServerConfig({ + defaultAuthOrgId: defaultAuthOrgId || null, + allowSignUp: signUpMode !== SignUpModes.Disabled, + allowedSignUpDomain: signUpMode === SignUpModes.Anyone ? allowedSignUpDomain : null, + trustSamlEmails, + trustLdapEmails, + trustOidcEmails, + authConsentContent, + pageFrameContent + }); + createNotification({ + text: "Successfully changed sign up setting.", + type: "success" + }); }; return ( diff --git a/frontend/src/pages/admin/GeneralPage/components/UsageReportSection.tsx b/frontend/src/pages/admin/GeneralPage/components/UsageReportSection.tsx index d05800996..663aa18b7 100644 --- a/frontend/src/pages/admin/GeneralPage/components/UsageReportSection.tsx +++ b/frontend/src/pages/admin/GeneralPage/components/UsageReportSection.tsx @@ -10,23 +10,15 @@ export const UsageReportSection = () => { const generateUsageReport = useGenerateUsageReport(); const handleGenerateReport = async () => { - try { - const response = await generateUsageReport.mutateAsync(); - const { csvContent, filename } = response; + const response = await generateUsageReport.mutateAsync(); + const { csvContent, filename } = response; - downloadFile(csvContent, filename, "text/csv"); + downloadFile(csvContent, filename, "text/csv"); - createNotification({ - text: `Usage report downloaded: "${filename}"`, - type: "success" - }); - } catch (error) { - console.error("Failed to generate usage report:", error); - createNotification({ - text: "Failed to generate usage report. Please try again.", - type: "error" - }); - } + createNotification({ + text: `Usage report downloaded: "${filename}"`, + type: "success" + }); }; return ( diff --git a/frontend/src/pages/admin/ResourceOverviewPage/components/AddOrganizationModal.tsx b/frontend/src/pages/admin/ResourceOverviewPage/components/AddOrganizationModal.tsx index d577998b5..48983496f 100644 --- a/frontend/src/pages/admin/ResourceOverviewPage/components/AddOrganizationModal.tsx +++ b/frontend/src/pages/admin/ResourceOverviewPage/components/AddOrganizationModal.tsx @@ -81,25 +81,18 @@ const Content = ({ onClose }: ContentProps) => { const { users = [] } = data ?? {}; const onSubmit = async ({ name, invitees }: FormData) => { - try { - await createOrg.mutateAsync({ - name, - inviteAdminEmails: invitees - .filter((user) => Boolean(user.email)) - .map((user) => user.email) as string[] - }); + await createOrg.mutateAsync({ + name, + inviteAdminEmails: invitees + .filter((user) => Boolean(user.email)) + .map((user) => user.email) as string[] + }); - createNotification({ - type: "success", - text: "Successfully created organization" - }); - onClose(); - } catch { - createNotification({ - text: "Failed to create organization", - type: "error" - }); - } + createNotification({ + type: "success", + text: "Successfully created organization" + }); + onClose(); }; const { append } = useFieldArray({ control, name: "invitees" }); diff --git a/frontend/src/pages/admin/ResourceOverviewPage/components/MachineIdentitiesTable.tsx b/frontend/src/pages/admin/ResourceOverviewPage/components/MachineIdentitiesTable.tsx index 9929d7500..d17786712 100644 --- a/frontend/src/pages/admin/ResourceOverviewPage/components/MachineIdentitiesTable.tsx +++ b/frontend/src/pages/admin/ResourceOverviewPage/components/MachineIdentitiesTable.tsx @@ -185,18 +185,11 @@ export const MachineIdentitiesTable = () => { const handleRemoveServerAdmin = async () => { const { id } = popUp?.removeServerAdmin?.data as { id: string; name: string }; - try { - await deleteIdentitySuperAdminAccess(id); - createNotification({ - type: "success", - text: "Successfully removed server admin permissions" - }); - } catch { - createNotification({ - type: "error", - text: "Error removing server admin permissions" - }); - } + await deleteIdentitySuperAdminAccess(id); + createNotification({ + type: "success", + text: "Successfully removed server admin permissions" + }); handlePopUpClose("removeServerAdmin"); }; diff --git a/frontend/src/pages/admin/ResourceOverviewPage/components/OrganizationsTable.tsx b/frontend/src/pages/admin/ResourceOverviewPage/components/OrganizationsTable.tsx index fbb9462d0..93d0253ff 100644 --- a/frontend/src/pages/admin/ResourceOverviewPage/components/OrganizationsTable.tsx +++ b/frontend/src/pages/admin/ResourceOverviewPage/components/OrganizationsTable.tsx @@ -179,12 +179,6 @@ const ViewMembersModalContent = ({ text: "Successfully resent org invitation", type: "success" }); - } catch (err) { - console.error(err); - createNotification({ - text: "Failed to resend org invitation", - type: "error" - }); } finally { setResendInviteId(null); } @@ -479,26 +473,19 @@ const OrganizationsPanelTable = ({ const { mutateAsync: accessOrganization } = useServerAdminAccessOrg(); const handleAccessOrg = async (orgId: string) => { - try { - await accessOrganization(orgId); + await accessOrganization(orgId); - navigate({ - to: "/login/select-organization", - search: { - org_id: orgId - } - }); + navigate({ + to: "/login/select-organization", + search: { + org_id: orgId + } + }); - createNotification({ - text: "Successfully joined organization", - type: "success" - }); - } catch { - createNotification({ - text: "Failed to join organization", - type: "error" - }); - } + createNotification({ + text: "Successfully joined organization", + type: "success" + }); }; return ( diff --git a/frontend/src/pages/admin/ResourceOverviewPage/components/UserIdentitiesTable.tsx b/frontend/src/pages/admin/ResourceOverviewPage/components/UserIdentitiesTable.tsx index 05d07d426..4f44a32aa 100644 --- a/frontend/src/pages/admin/ResourceOverviewPage/components/UserIdentitiesTable.tsx +++ b/frontend/src/pages/admin/ResourceOverviewPage/components/UserIdentitiesTable.tsx @@ -367,18 +367,11 @@ export const UserIdentitiesTable = () => { const handleRemoveUser = async () => { const { id } = popUp?.removeUser?.data as { id: string; username: string }; - try { - await deleteUser(id); - createNotification({ - type: "success", - text: "Successfully deleted user" - }); - } catch { - createNotification({ - type: "error", - text: "Error deleting user" - }); - } + await deleteUser(id); + createNotification({ + type: "success", + text: "Successfully deleted user" + }); handlePopUpClose("removeUser"); }; @@ -386,18 +379,11 @@ export const UserIdentitiesTable = () => { const handleGrantServerAdminAccess = async () => { const { id } = popUp?.upgradeToServerAdmin?.data as { id: string; username: string }; - try { - await grantAdminAccess(id); - createNotification({ - type: "success", - text: "Successfully granted server admin access to user" - }); - } catch { - createNotification({ - type: "error", - text: "Error granting server admin access to user" - }); - } + await grantAdminAccess(id); + createNotification({ + type: "success", + text: "Successfully granted server admin access to user" + }); handlePopUpClose("upgradeToServerAdmin"); }; @@ -405,39 +391,25 @@ export const UserIdentitiesTable = () => { const handleRemoveServerAdminAccess = async () => { const { id } = popUp?.removeServerAdmin?.data as { id: string; username: string }; - try { - await removeAdminAccess(id); - createNotification({ - type: "success", - text: "Successfully removed server admin access from user" - }); - } catch { - createNotification({ - type: "error", - text: "Error removing server admin access from user" - }); - } + await removeAdminAccess(id); + createNotification({ + type: "success", + text: "Successfully removed server admin access from user" + }); handlePopUpClose("removeServerAdmin"); }; const handleRemoveUsers = async () => { - try { - await deleteUsers(selectedUsers.map((user) => user.id)); + await deleteUsers(selectedUsers.map((user) => user.id)); - createNotification({ - text: "Successfully removed users", - type: "success" - }); + createNotification({ + text: "Successfully removed users", + type: "success" + }); - setSelectedUsers([]); - handlePopUpClose("removeUsers"); - } catch { - createNotification({ - text: "Failed to remove users", - type: "error" - }); - } + setSelectedUsers([]); + handlePopUpClose("removeUsers"); }; return ( diff --git a/frontend/src/pages/admin/SignUpPage/SignUpPage.tsx b/frontend/src/pages/admin/SignUpPage/SignUpPage.tsx index 04bd2f55c..81959a647 100644 --- a/frontend/src/pages/admin/SignUpPage/SignUpPage.tsx +++ b/frontend/src/pages/admin/SignUpPage/SignUpPage.tsx @@ -6,7 +6,6 @@ import { useNavigate } from "@tanstack/react-router"; import { AnimatePresence, motion } from "framer-motion"; import { z } from "zod"; -import { createNotification } from "@app/components/notifications"; // TODO(akhilmhdh): rewrite this into module functions in lib import SecurityClient from "@app/components/utilities/SecurityClient"; import { Button, ContentLoader, FormControl, Input } from "@app/components/v2"; @@ -46,29 +45,21 @@ export const SignUpPage = () => { const handleFormSubmit = async ({ email, password, firstName, lastName }: TFormSchema) => { // avoid multi submission if (isSubmitting) return; - try { - const res = await createAdminUser({ - email, - password, - firstName, - lastName - }); + const res = await createAdminUser({ + email, + password, + firstName, + lastName + }); - SecurityClient.setToken(res.token); - await selectOrganization({ organizationId: res.organization.id }); + SecurityClient.setToken(res.token); + await selectOrganization({ organizationId: res.organization.id }); - // TODO(akhilmhdh): This is such a confusing pattern and too unreliable - // Will be refactored in next iteration to make it url based rather than local storage ones - // Part of migration to nextjs 14 - localStorage.setItem("orgData.id", res.organization.id); - navigate({ to: "/admin" }); - } catch (err) { - console.log(err); - createNotification({ - type: "error", - text: "Failed to create admin" - }); - } + // TODO(akhilmhdh): This is such a confusing pattern and too unreliable + // Will be refactored in next iteration to make it url based rather than local storage ones + // Part of migration to nextjs 14 + localStorage.setItem("orgData.id", res.organization.id); + navigate({ to: "/admin" }); }; if (config?.initialized) return ; diff --git a/frontend/src/pages/auth/PasswordSetupPage/PasswordSetupPage.tsx b/frontend/src/pages/auth/PasswordSetupPage/PasswordSetupPage.tsx index a1dad3cc5..9626f4cc5 100644 --- a/frontend/src/pages/auth/PasswordSetupPage/PasswordSetupPage.tsx +++ b/frontend/src/pages/auth/PasswordSetupPage/PasswordSetupPage.tsx @@ -75,11 +75,7 @@ export const PasswordSetupPage = () => { setTimeout(() => { window.location.href = "/login"; }, 3000); - } catch (error) { - createNotification({ - type: "error", - text: (error as Error).message ?? "Error setting password" - }); + } catch { navigate({ to: "/personal-settings" }); } } diff --git a/frontend/src/pages/auth/SignUpSsoPage/components/EmailConfirmationStep/EmailConfirmationStep.tsx b/frontend/src/pages/auth/SignUpSsoPage/components/EmailConfirmationStep/EmailConfirmationStep.tsx index efa498749..2240fe263 100644 --- a/frontend/src/pages/auth/SignUpSsoPage/components/EmailConfirmationStep/EmailConfirmationStep.tsx +++ b/frontend/src/pages/auth/SignUpSsoPage/components/EmailConfirmationStep/EmailConfirmationStep.tsx @@ -73,67 +73,53 @@ export const EmailConfirmationStep = ({ const { mutateAsync: verifyEmailVerificationCode } = useVerifyEmailVerificationCode(); const checkCode = async () => { - try { - await verifyEmailVerificationCode({ username, code }); - setCodeError(false); + await verifyEmailVerificationCode({ username, code }); + setCodeError(false); - createNotification({ - text: "Successfully verified code", - type: "success" - }); + createNotification({ + text: "Successfully verified code", + type: "success" + }); - switch (authType) { - case UserAliasType.SAML: { - window.open(`/api/v1/sso/redirect/saml2/organizations/${organizationSlug}`); - window.close(); - break; - } - case UserAliasType.LDAP: { - navigate({ to: "/login/ldap", search: { organizationSlug } }); - break; - } - case UserAliasType.OIDC: { - window.open(`/api/v1/sso/oidc/login?orgSlug=${organizationSlug}`); - window.close(); - break; - } - default: { - setStep(1); - break; - } + switch (authType) { + case UserAliasType.SAML: { + window.open(`/api/v1/sso/redirect/saml2/organizations/${organizationSlug}`); + window.close(); + break; + } + case UserAliasType.LDAP: { + navigate({ to: "/login/ldap", search: { organizationSlug } }); + break; + } + case UserAliasType.OIDC: { + window.open(`/api/v1/sso/oidc/login?orgSlug=${organizationSlug}`); + window.close(); + break; + } + default: { + setStep(1); + break; } - } catch { - createNotification({ - text: "Failed to verify code", - type: "error" - }); } setCode(""); }; const resendCode = async () => { - try { - const queryParams = new URLSearchParams(window.location.search); - const token = queryParams.get("token"); - if (!token) { - createNotification({ - text: "Failed to resend code, no token found", - type: "error" - }); - return; - } - await sendEmailVerificationCode(token); + const queryParams = new URLSearchParams(window.location.search); + const token = queryParams.get("token"); + if (!token) { createNotification({ - text: "Successfully resent code", - type: "success" - }); - } catch { - createNotification({ - text: "Failed to resend code", + text: "Failed to resend code, no token found", type: "error" }); + return; } + await sendEmailVerificationCode(token); + createNotification({ + text: "Successfully resent code", + type: "success" + }); }; return ( diff --git a/frontend/src/pages/cert-manager/AlertingPage/components/PkiAlertModal.tsx b/frontend/src/pages/cert-manager/AlertingPage/components/PkiAlertModal.tsx index 5601e48db..af5bcb7ae 100644 --- a/frontend/src/pages/cert-manager/AlertingPage/components/PkiAlertModal.tsx +++ b/frontend/src/pages/cert-manager/AlertingPage/components/PkiAlertModal.tsx @@ -113,52 +113,44 @@ export const PkiAlertModal = ({ popUp, handlePopUpToggle }: Props) => { alertUnit, emails }: FormData) => { - try { - if (!projectId) return; + if (!projectId) return; - const emailArray = emails - .split(",") - .map((email) => email.trim()) - .filter((email) => email.length > 0); + const emailArray = emails + .split(",") + .map((email) => email.trim()) + .filter((email) => email.length > 0); - const alertBeforeDays = convertToDays(alertUnit, Number(alertBefore)); + const alertBeforeDays = convertToDays(alertUnit, Number(alertBefore)); - if (alert) { - // update - await updatePkiAlert({ - alertId: alert.id, - pkiCollectionId, - name, - projectId, - alertBeforeDays, - emails: emailArray - }); - } else { - // create - await createPkiAlert({ - name, - projectId, - pkiCollectionId, - alertBeforeDays, - emails: emailArray - }); - } - - handlePopUpToggle("pkiAlert", false); - - reset(); - - createNotification({ - text: `Successfully ${alert ? "updated" : "created"} alert`, - type: "success" + if (alert) { + // update + await updatePkiAlert({ + alertId: alert.id, + pkiCollectionId, + name, + projectId, + alertBeforeDays, + emails: emailArray }); - } catch (err) { - console.error(err); - createNotification({ - text: `Failed to ${alert ? "updated" : "created"} alert`, - type: "error" + } else { + // create + await createPkiAlert({ + name, + projectId, + pkiCollectionId, + alertBeforeDays, + emails: emailArray }); } + + handlePopUpToggle("pkiAlert", false); + + reset(); + + createNotification({ + text: `Successfully ${alert ? "updated" : "created"} alert`, + type: "success" + }); }; return ( diff --git a/frontend/src/pages/cert-manager/AlertingPage/components/PkiAlertsSection.tsx b/frontend/src/pages/cert-manager/AlertingPage/components/PkiAlertsSection.tsx index 329974f65..1529dfc19 100644 --- a/frontend/src/pages/cert-manager/AlertingPage/components/PkiAlertsSection.tsx +++ b/frontend/src/pages/cert-manager/AlertingPage/components/PkiAlertsSection.tsx @@ -22,27 +22,19 @@ export const PkiAlertsSection = () => { ] as const); const onRemoveAlertSubmit = async (alertId: string) => { - try { - if (!projectId) return; + if (!projectId) return; - await deletePkiAlert({ - alertId, - projectId - }); + await deletePkiAlert({ + alertId, + projectId + }); - createNotification({ - text: "Successfully deleted alert", - type: "success" - }); + createNotification({ + text: "Successfully deleted alert", + type: "success" + }); - handlePopUpClose("deletePkiAlert"); - } catch (err) { - console.error(err); - createNotification({ - text: "Failed to delete alert", - type: "error" - }); - } + handlePopUpClose("deletePkiAlert"); }; return ( diff --git a/frontend/src/pages/cert-manager/AlertingPage/components/PkiCollectionModal.tsx b/frontend/src/pages/cert-manager/AlertingPage/components/PkiCollectionModal.tsx index 5900a1ba9..a29e9028b 100644 --- a/frontend/src/pages/cert-manager/AlertingPage/components/PkiCollectionModal.tsx +++ b/frontend/src/pages/cert-manager/AlertingPage/components/PkiCollectionModal.tsx @@ -62,49 +62,41 @@ export const PkiCollectionModal = ({ popUp, handlePopUpToggle }: Props) => { }, [pkiCollection]); const onFormSubmit = async ({ name, description }: FormData) => { - try { - if (!projectId) return; + if (!projectId) return; - if (pkiCollection) { - // update - await updatePkiCollection({ - collectionId: pkiCollection.id, - name, - description, - projectId - }); - } else { - // create - const { id: collectionId } = await createPkiCollection({ - name, - description, - projectId - }); - - navigate({ - to: "/projects/cert-management/$projectId/pki-collections/$collectionId", - params: { - projectId, - collectionId - } - }); - } - - handlePopUpToggle("pkiCollection", false); - - reset(); - - createNotification({ - text: `Successfully ${pkiCollection ? "updated" : "created"} PKI collection`, - type: "success" + if (pkiCollection) { + // update + await updatePkiCollection({ + collectionId: pkiCollection.id, + name, + description, + projectId }); - } catch (err) { - console.error(err); - createNotification({ - text: `Failed to ${pkiCollection ? "updated" : "created"} PKI collection`, - type: "error" + } else { + // create + const { id: collectionId } = await createPkiCollection({ + name, + description, + projectId + }); + + navigate({ + to: "/projects/cert-management/$projectId/pki-collections/$collectionId", + params: { + projectId, + collectionId + } }); } + + handlePopUpToggle("pkiCollection", false); + + reset(); + + createNotification({ + text: `Successfully ${pkiCollection ? "updated" : "created"} PKI collection`, + type: "success" + }); }; return ( diff --git a/frontend/src/pages/cert-manager/AlertingPage/components/PkiCollectionSection.tsx b/frontend/src/pages/cert-manager/AlertingPage/components/PkiCollectionSection.tsx index eecceaa7d..fa9cf7bea 100644 --- a/frontend/src/pages/cert-manager/AlertingPage/components/PkiCollectionSection.tsx +++ b/frontend/src/pages/cert-manager/AlertingPage/components/PkiCollectionSection.tsx @@ -22,27 +22,19 @@ export const PkiCollectionSection = () => { ] as const); const onRemovePkiCollectionSubmit = async (collectionId: string) => { - try { - if (!projectId) return; + if (!projectId) return; - await deletePkiCollection({ - collectionId, - projectId - }); + await deletePkiCollection({ + collectionId, + projectId + }); - createNotification({ - text: "Successfully deleted PKI collection", - type: "success" - }); + createNotification({ + text: "Successfully deleted PKI collection", + type: "success" + }); - handlePopUpClose("deletePkiCollection"); - } catch (err) { - console.error(err); - createNotification({ - text: "Failed to delete PKI collection", - type: "error" - }); - } + handlePopUpClose("deletePkiCollection"); }; return ( diff --git a/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/CertAuthDetailsByIDPage.tsx b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/CertAuthDetailsByIDPage.tsx index ca73abd50..b464a2230 100644 --- a/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/CertAuthDetailsByIDPage.tsx +++ b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/CertAuthDetailsByIDPage.tsx @@ -57,33 +57,26 @@ const Page = () => { ] as const); const onRemoveCaSubmit = async () => { - try { - if (!currentProject?.slug) return; + if (!currentProject?.slug) return; - await deleteCa({ - caName, - projectId: currentProject.id, - type: CaType.INTERNAL - }); + await deleteCa({ + caName, + projectId: currentProject.id, + type: CaType.INTERNAL + }); - createNotification({ - text: "Successfully deleted CA", - type: "success" - }); + createNotification({ + text: "Successfully deleted CA", + type: "success" + }); - handlePopUpClose("deleteCa"); - navigate({ - to: "/projects/cert-management/$projectId/certificate-authorities", - params: { - projectId - } - }); - } catch { - createNotification({ - text: "Failed to delete CA", - type: "error" - }); - } + handlePopUpClose("deleteCa"); + navigate({ + to: "/projects/cert-management/$projectId/certificate-authorities", + params: { + projectId + } + }); }; return ( diff --git a/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaRenewalModal.tsx b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaRenewalModal.tsx index 857586a58..c6283da37 100644 --- a/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaRenewalModal.tsx +++ b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaRenewalModal.tsx @@ -84,27 +84,23 @@ export const CaRenewalModal = ({ popUp, handlePopUpToggle }: Props) => { // }, [ca, parentCa]); const onFormSubmit = async ({ type, notAfter }: FormData) => { - try { - if (!projectSlug || !popUpData.caId) return; + if (!projectSlug || !popUpData.caId) return; - await renewCa({ - projectSlug, - caId: popUpData.caId, - notAfter, - type - }); + await renewCa({ + projectSlug, + caId: popUpData.caId, + notAfter, + type + }); - handlePopUpToggle("renewCa", false); + handlePopUpToggle("renewCa", false); - createNotification({ - text: "Successfully renewed CA", - type: "success" - }); + createNotification({ + text: "Successfully renewed CA", + type: "success" + }); - reset(); - } catch (err) { - console.error(err); - } + reset(); }; return ( diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/ExternalCaInstallForm.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/ExternalCaInstallForm.tsx index f730322c9..8a7e9690e 100644 --- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/ExternalCaInstallForm.tsx +++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/ExternalCaInstallForm.tsx @@ -48,29 +48,22 @@ export const ExternalCaInstallForm = ({ caId, handlePopUpToggle }: Props) => { }, []); const onFormSubmit = async ({ certificate, certificateChain }: FormData) => { - try { - if (!csr || !caId || !currentProject?.slug) return; + if (!csr || !caId || !currentProject?.slug) return; - await importCaCertificate({ - caId, - projectSlug: currentProject?.slug, - certificate, - certificateChain - }); + await importCaCertificate({ + caId, + projectSlug: currentProject?.slug, + certificate, + certificateChain + }); - reset(); + reset(); - createNotification({ - text: "Successfully installed certificate for CA", - type: "success" - }); - handlePopUpToggle("installCaCert", false); - } catch { - createNotification({ - text: "Failed to install certificate for CA", - type: "error" - }); - } + createNotification({ + text: "Successfully installed certificate for CA", + type: "success" + }); + handlePopUpToggle("installCaCert", false); }; const downloadTxtFile = (filename: string, content: string) => { diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/InternalCaInstallForm.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/InternalCaInstallForm.tsx index 5979d9711..f80e21212 100644 --- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/InternalCaInstallForm.tsx +++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/InternalCaInstallForm.tsx @@ -101,37 +101,30 @@ export const InternalCaInstallForm = ({ caId, handlePopUpToggle }: Props) => { }, [parentCa]); const onFormSubmit = async ({ notAfter, maxPathLength }: FormData) => { - try { - if (!csr || !caId || !currentProject?.slug) return; + if (!csr || !caId || !currentProject?.slug) return; - const { certificate, certificateChain } = await signIntermediate({ - caId: parentCaId, - csr, - maxPathLength: Number(maxPathLength), - notAfter, - notBefore: new Date().toISOString() - }); + const { certificate, certificateChain } = await signIntermediate({ + caId: parentCaId, + csr, + maxPathLength: Number(maxPathLength), + notAfter, + notBefore: new Date().toISOString() + }); - await importCaCertificate({ - caId, - projectSlug: currentProject?.slug, - certificate, - certificateChain - }); + await importCaCertificate({ + caId, + projectSlug: currentProject?.slug, + certificate, + certificateChain + }); - reset(); + reset(); - createNotification({ - text: "Successfully installed certificate for CA", - type: "success" - }); - handlePopUpToggle("installCaCert", false); - } catch { - createNotification({ - text: "Failed to install certificate for CA", - type: "error" - }); - } + createNotification({ + text: "Successfully installed certificate for CA", + type: "success" + }); + handlePopUpToggle("installCaCert", false); }; function generatePathLengthOpts(parentCaMaxPathLength: number): number[] { diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaModal.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaModal.tsx index a19a3a9c7..53434b79d 100644 --- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaModal.tsx +++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaModal.tsx @@ -175,48 +175,40 @@ export const CaModal = ({ popUp, handlePopUpToggle }: Props) => { status, configuration }: FormData) => { - try { - if (!currentProject?.slug) return; + if (!currentProject?.slug) return; - if (ca) { - // update - await updateMutateAsync({ - caName: ca.name, - projectId: currentProject.id, - name, - type: CaType.INTERNAL, - status, - enableDirectIssuance - }); - } else { - // create - await createMutateAsync({ - projectId: currentProject.id, - name, - type, - status, - enableDirectIssuance, - configuration: { - ...configuration, - maxPathLength: Number(configuration.maxPathLength) - } - }); - } - - reset(); - handlePopUpToggle("ca", false); - - createNotification({ - text: `Successfully ${ca ? "updated" : "created"} CA`, - type: "success" + if (ca) { + // update + await updateMutateAsync({ + caName: ca.name, + projectId: currentProject.id, + name, + type: CaType.INTERNAL, + status, + enableDirectIssuance }); - } catch (err) { - console.error(err); - createNotification({ - text: "Failed to create CA", - type: "error" + } else { + // create + await createMutateAsync({ + projectId: currentProject.id, + name, + type, + status, + enableDirectIssuance, + configuration: { + ...configuration, + maxPathLength: Number(configuration.maxPathLength) + } }); } + + reset(); + handlePopUpToggle("ca", false); + + createNotification({ + text: `Successfully ${ca ? "updated" : "created"} CA`, + type: "success" + }); }; return ( diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaSection.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaSection.tsx index e853dc801..a817042a7 100644 --- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaSection.tsx +++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaSection.tsx @@ -29,44 +29,29 @@ export const CaSection = () => { ] as const); const onRemoveCaSubmit = async (caName: string) => { - try { - if (!currentProject?.slug) return; + if (!currentProject?.slug) return; - await deleteCa({ caName, projectId: currentProject.id, type: CaType.INTERNAL }); + await deleteCa({ caName, projectId: currentProject.id, type: CaType.INTERNAL }); - createNotification({ - text: "Successfully deleted CA", - type: "success" - }); + createNotification({ + text: "Successfully deleted CA", + type: "success" + }); - handlePopUpClose("deleteCa"); - } catch { - createNotification({ - text: "Failed to delete CA", - type: "error" - }); - } + handlePopUpClose("deleteCa"); }; const onUpdateCaStatus = async ({ caName, status }: { caName: string; status: CaStatus }) => { - try { - if (!currentProject?.slug) return; + if (!currentProject?.slug) return; - await updateCa({ caName, projectId: currentProject.id, type: CaType.INTERNAL, status }); + await updateCa({ caName, projectId: currentProject.id, type: CaType.INTERNAL, status }); - createNotification({ - text: `Successfully ${status === CaStatus.ACTIVE ? "enabled" : "disabled"} CA`, - type: "success" - }); + createNotification({ + text: `Successfully ${status === CaStatus.ACTIVE ? "enabled" : "disabled"} CA`, + type: "success" + }); - handlePopUpClose("caStatus"); - } catch (err) { - console.error(err); - createNotification({ - text: `Failed to ${status === CaStatus.ACTIVE ? "enabled" : "disabled"} CA`, - type: "error" - }); - } + handlePopUpClose("caStatus"); }; return ( diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaModal.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaModal.tsx index 121c32e5f..825368d1c 100644 --- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaModal.tsx +++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaModal.tsx @@ -297,63 +297,55 @@ export const ExternalCaModal = ({ popUp, handlePopUpToggle }: Props) => { status, configuration: formConfiguration }: FormData) => { - try { - if (!currentProject?.slug) return; + if (!currentProject?.slug) return; - let configPayload: any; + let configPayload: any; - if (type === CaType.ACME && "dnsAppConnection" in formConfiguration) { - configPayload = { - dnsProviderConfig: formConfiguration.dnsProviderConfig, - directoryUrl: formConfiguration.directoryUrl, - accountEmail: formConfiguration.accountEmail, - dnsAppConnectionId: formConfiguration.dnsAppConnection.id, - eabKid: formConfiguration.eabKid, - eabHmacKey: formConfiguration.eabHmacKey - }; - } else if (type === CaType.AZURE_AD_CS && "azureAdcsConnection" in formConfiguration) { - configPayload = { - azureAdcsConnectionId: formConfiguration.azureAdcsConnection.id - }; - } else { - throw new Error("Invalid certificate authority configuration"); - } + if (type === CaType.ACME && "dnsAppConnection" in formConfiguration) { + configPayload = { + dnsProviderConfig: formConfiguration.dnsProviderConfig, + directoryUrl: formConfiguration.directoryUrl, + accountEmail: formConfiguration.accountEmail, + dnsAppConnectionId: formConfiguration.dnsAppConnection.id, + eabKid: formConfiguration.eabKid, + eabHmacKey: formConfiguration.eabHmacKey + }; + } else if (type === CaType.AZURE_AD_CS && "azureAdcsConnection" in formConfiguration) { + configPayload = { + azureAdcsConnectionId: formConfiguration.azureAdcsConnection.id + }; + } else { + throw new Error("Invalid certificate authority configuration"); + } - if (ca) { - await updateMutateAsync({ - caName: ca.name, - projectId: currentProject.id, - name, - type, - status, - enableDirectIssuance: type === CaType.AZURE_AD_CS ? false : enableDirectIssuance, - configuration: configPayload - }); - } else { - await createMutateAsync({ - projectId: currentProject.id, - name, - type, - status, - enableDirectIssuance: type === CaType.AZURE_AD_CS ? false : enableDirectIssuance, - configuration: configPayload - }); - } - - reset(); - handlePopUpToggle("ca", false); - - createNotification({ - text: `Successfully ${ca ? "updated" : "created"} CA`, - type: "success" + if (ca) { + await updateMutateAsync({ + caName: ca.name, + projectId: currentProject.id, + name, + type, + status, + enableDirectIssuance: type === CaType.AZURE_AD_CS ? false : enableDirectIssuance, + configuration: configPayload }); - } catch (err) { - console.error(err); - createNotification({ - text: "Failed to create CA", - type: "error" + } else { + await createMutateAsync({ + projectId: currentProject.id, + name, + type, + status, + enableDirectIssuance: type === CaType.AZURE_AD_CS ? false : enableDirectIssuance, + configuration: configPayload }); } + + reset(); + handlePopUpToggle("ca", false); + + createNotification({ + text: `Successfully ${ca ? "updated" : "created"} CA`, + type: "success" + }); }; return ( diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaSection.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaSection.tsx index 14ce122ec..b40dec6f5 100644 --- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaSection.tsx +++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaSection.tsx @@ -25,23 +25,16 @@ export const ExternalCaSection = () => { ] as const); const onRemoveCaSubmit = async (caName: string, type: CaType) => { - try { - if (!currentProject?.id) return; + if (!currentProject?.id) return; - await deleteCa({ caName, type, projectId: currentProject.id }); + await deleteCa({ caName, type, projectId: currentProject.id }); - createNotification({ - text: "Successfully deleted CA", - type: "success" - }); + createNotification({ + text: "Successfully deleted CA", + type: "success" + }); - handlePopUpClose("deleteCa"); - } catch { - createNotification({ - text: "Failed to delete CA", - type: "error" - }); - } + handlePopUpClose("deleteCa"); }; const onUpdateCaStatus = async ({ @@ -53,24 +46,16 @@ export const ExternalCaSection = () => { type: CaType; status: CaStatus; }) => { - try { - if (!currentProject?.slug) return; + if (!currentProject?.slug) return; - await updateCa({ caName: name, type, status, projectId: currentProject.id }); + await updateCa({ caName: name, type, status, projectId: currentProject.id }); - createNotification({ - text: `Successfully ${status === CaStatus.ACTIVE ? "enabled" : "disabled"} CA`, - type: "success" - }); + createNotification({ + text: `Successfully ${status === CaStatus.ACTIVE ? "enabled" : "disabled"} CA`, + type: "success" + }); - handlePopUpClose("caStatus"); - } catch (err) { - console.error(err); - createNotification({ - text: `Failed to ${status === CaStatus.ACTIVE ? "enable" : "disable"} CA`, - type: "error" - }); - } + handlePopUpClose("caStatus"); }; return ( diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateImportModal.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateImportModal.tsx index bb0bbda0b..d0434b79a 100644 --- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateImportModal.tsx +++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateImportModal.tsx @@ -71,38 +71,30 @@ export const CertificateImportModal = ({ popUp, handlePopUpToggle }: Props) => { chainPem, collectionId }: FormData) => { - try { - if (!currentProject?.slug) return; + if (!currentProject?.slug) return; - const { serialNumber, certificate, certificateChain, privateKey } = await importCertificate({ - projectSlug: currentProject.slug, + const { serialNumber, certificate, certificateChain, privateKey } = await importCertificate({ + projectSlug: currentProject.slug, - certificatePem, - privateKeyPem, - chainPem, - pkiCollectionId: collectionId - }); + certificatePem, + privateKeyPem, + chainPem, + pkiCollectionId: collectionId + }); - reset(); + reset(); - setCertificateDetails({ - serialNumber, - certificate, - certificateChain, - privateKey - }); + setCertificateDetails({ + serialNumber, + certificate, + certificateChain, + privateKey + }); - createNotification({ - text: "Successfully imported certificate", - type: "success" - }); - } catch (err) { - console.error(err); - createNotification({ - text: "Failed to import certificate", - type: "error" - }); - } + createNotification({ + text: "Successfully imported certificate", + type: "success" + }); }; return ( diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal.tsx index dc0dffb0d..537229714 100644 --- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal.tsx +++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal.tsx @@ -242,84 +242,72 @@ export const CertificateIssuanceModal = ({ popUp, handlePopUpToggle, profileId } keyUsages, extendedKeyUsages }: FormData) => { - try { - if (!currentProject?.slug) { - createNotification({ - text: "Project not found. Please refresh and try again.", - type: "error" - }); - return; - } - - if (!formProfileId) { - createNotification({ - text: "Please select a certificate profile.", - type: "error" - }); - return; - } - - let commonName = ""; - if ( - constraints.shouldShowSubjectSection && - subjectAttributes && - subjectAttributes.length > 0 - ) { - commonName = getAttributeValue(subjectAttributes, "common_name"); - if (!commonName.trim()) { - createNotification({ - text: "Common name is required.", - type: "error" - }); - return; - } - } - - const certificateRequest: any = { - profileId: formProfileId, - projectSlug: currentProject.slug, - ttl, - signatureAlgorithm, - keyAlgorithm, - keyUsages: filterUsages(keyUsages) as CertKeyUsage[], - extendedKeyUsages: filterUsages(extendedKeyUsages) as CertExtendedKeyUsage[] - }; - - if (constraints.shouldShowSubjectSection && commonName) { - certificateRequest.commonName = commonName; - } - if (constraints.shouldShowSanSection && subjectAltNames && subjectAltNames.length > 0) { - const formattedSans = formatSubjectAltNames(subjectAltNames); - if (formattedSans && formattedSans.length > 0) { - certificateRequest.altNames = formattedSans; - } - } - - const { serialNumber, certificate, certificateChain, privateKey } = - await createCertificate(certificateRequest); - - setCertificateDetails({ - serialNumber, - certificate, - certificateChain, - privateKey - }); - + if (!currentProject?.slug) { createNotification({ - text: "Successfully created certificate", - type: "success" - }); - } catch (err) { - console.error("Certificate creation failed:", err); - const errorMessage = - err instanceof Error - ? err.message - : "An unexpected error occurred while creating the certificate"; - createNotification({ - text: `Failed to create certificate: ${errorMessage}`, + text: "Project not found. Please refresh and try again.", type: "error" }); + return; } + + if (!formProfileId) { + createNotification({ + text: "Please select a certificate profile.", + type: "error" + }); + return; + } + + let commonName = ""; + if ( + constraints.shouldShowSubjectSection && + subjectAttributes && + subjectAttributes.length > 0 + ) { + commonName = getAttributeValue(subjectAttributes, "common_name"); + if (!commonName.trim()) { + createNotification({ + text: "Common name is required.", + type: "error" + }); + return; + } + } + + const certificateRequest: any = { + profileId: formProfileId, + projectSlug: currentProject.slug, + ttl, + signatureAlgorithm, + keyAlgorithm, + keyUsages: filterUsages(keyUsages) as CertKeyUsage[], + extendedKeyUsages: filterUsages(extendedKeyUsages) as CertExtendedKeyUsage[] + }; + + if (constraints.shouldShowSubjectSection && commonName) { + certificateRequest.commonName = commonName; + } + if (constraints.shouldShowSanSection && subjectAltNames && subjectAltNames.length > 0) { + const formattedSans = formatSubjectAltNames(subjectAltNames); + if (formattedSans && formattedSans.length > 0) { + certificateRequest.altNames = formattedSans; + } + } + + const { serialNumber, certificate, certificateChain, privateKey } = + await createCertificate(certificateRequest); + + setCertificateDetails({ + serialNumber, + certificate, + certificateChain, + privateKey + }); + + createNotification({ + text: "Successfully created certificate", + type: "success" + }); }, [ currentProject?.slug, diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateManageRenewalModal.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateManageRenewalModal.tsx index d6199678a..96eb2654a 100644 --- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateManageRenewalModal.tsx +++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateManageRenewalModal.tsx @@ -163,38 +163,28 @@ export const CertificateManageRenewalModal = ({ popUp, handlePopUpToggle }: Prop }, [popUp.manageRenewal.isOpen, defaultRenewalDays, reset]); const onUpdateRenewal = async (data: FormData) => { - try { - if (!currentProject?.slug) { - createNotification({ - text: "Unable to update auto-renewal: Project not found. Please refresh the page and try again.", - type: "error" - }); - return; - } - - await updateRenewalConfig({ - certificateId: certificateData.certificateId, - renewBeforeDays: data.renewBeforeDays, - projectSlug: currentProject.slug - }); - + if (!currentProject?.slug) { createNotification({ - text: isAutoRenewalEnabled - ? "Auto-renewal configuration updated successfully" - : "Auto-renewal enabled successfully", - type: "success" - }); - - handlePopUpToggle("manageRenewal", false); - } catch (err) { - console.error(err); - createNotification({ - text: isAutoRenewalEnabled - ? "Failed to update auto-renewal configuration. Please check your inputs and try again." - : "Failed to enable auto-renewal. Please check your inputs and try again.", + text: "Unable to update auto-renewal: Project not found. Please refresh the page and try again.", type: "error" }); + return; } + + await updateRenewalConfig({ + certificateId: certificateData.certificateId, + renewBeforeDays: data.renewBeforeDays, + projectSlug: currentProject.slug + }); + + createNotification({ + text: isAutoRenewalEnabled + ? "Auto-renewal configuration updated successfully" + : "Auto-renewal enabled successfully", + type: "success" + }); + + handlePopUpToggle("manageRenewal", false); }; const getModalTitle = () => { diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateModal.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateModal.tsx index 22718222a..f56f0fde8 100644 --- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateModal.tsx +++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateModal.tsx @@ -186,45 +186,37 @@ export const CertificateModal = ({ popUp, handlePopUpToggle }: Props) => { keyUsages, extendedKeyUsages }: FormData) => { - try { - if (!currentProject?.slug) return; + if (!currentProject?.slug) return; - const { serialNumber, certificate, certificateChain, privateKey } = await createCertificate({ - caId: !selectedCertTemplate ? caId : undefined, - certificateTemplateId: selectedCertTemplate ? selectedCertTemplateId : undefined, - projectSlug: currentProject.slug, - pkiCollectionId: collectionId, - commonName, - subjectAltNames, - ttl, - keyUsages: Object.entries(keyUsages) - .filter(([, value]) => value) - .map(([key]) => key as CertKeyUsage), - extendedKeyUsages: Object.entries(extendedKeyUsages) - .filter(([, value]) => value) - .map(([key]) => key as CertExtendedKeyUsage) - }); + const { serialNumber, certificate, certificateChain, privateKey } = await createCertificate({ + caId: !selectedCertTemplate ? caId : undefined, + certificateTemplateId: selectedCertTemplate ? selectedCertTemplateId : undefined, + projectSlug: currentProject.slug, + pkiCollectionId: collectionId, + commonName, + subjectAltNames, + ttl, + keyUsages: Object.entries(keyUsages) + .filter(([, value]) => value) + .map(([key]) => key as CertKeyUsage), + extendedKeyUsages: Object.entries(extendedKeyUsages) + .filter(([, value]) => value) + .map(([key]) => key as CertExtendedKeyUsage) + }); - reset(); + reset(); - setCertificateDetails({ - serialNumber, - certificate, - certificateChain, - privateKey - }); + setCertificateDetails({ + serialNumber, + certificate, + certificateChain, + privateKey + }); - createNotification({ - text: "Successfully created certificate", - type: "success" - }); - } catch (err) { - console.error(err); - createNotification({ - text: "Failed to create certificate", - type: "error" - }); - } + createNotification({ + text: "Successfully created certificate", + type: "success" + }); }; useEffect(() => { diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalConfigModal.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalConfigModal.tsx index c952f1e54..039151866 100644 --- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalConfigModal.tsx +++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalConfigModal.tsx @@ -61,34 +61,26 @@ export const CertificateRenewalConfigModal = ({ popUp, handlePopUpToggle }: Prop const renewBeforeDays = watch("renewBeforeDays"); const onSubmit = async (data: FormData) => { - try { - if (!currentProject?.slug) { - createNotification({ - text: "Project not found", - type: "error" - }); - return; - } - - await updateRenewalConfig({ - certificateId: certificateData.certificateId, - renewBeforeDays: data.renewBeforeDays, - projectSlug: currentProject.slug - }); - + if (!currentProject?.slug) { createNotification({ - text: "Successfully updated auto-renewal configuration", - type: "success" - }); - - handlePopUpToggle("configureRenewal", false); - } catch (err) { - console.error(err); - createNotification({ - text: "Failed to update auto-renewal configuration", + text: "Project not found", type: "error" }); + return; } + + await updateRenewalConfig({ + certificateId: certificateData.certificateId, + renewBeforeDays: data.renewBeforeDays, + projectSlug: currentProject.slug + }); + + createNotification({ + text: "Successfully updated auto-renewal configuration", + type: "success" + }); + + handlePopUpToggle("configureRenewal", false); }; return ( diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalDisableModal.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalDisableModal.tsx index 613080cd7..e44d7e774 100644 --- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalDisableModal.tsx +++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalDisableModal.tsx @@ -19,34 +19,26 @@ export const CertificateRenewalDisableModal = ({ popUp, handlePopUpToggle }: Pro }; const onDisableConfirm = async () => { - try { - if (!currentProject?.slug) { - createNotification({ - text: "Project not found", - type: "error" - }); - return; - } - - await updateRenewalConfig({ - certificateId: certificateData.certificateId, - projectSlug: currentProject.slug, - enableAutoRenewal: false - }); - + if (!currentProject?.slug) { createNotification({ - text: "Successfully disabled auto-renewal", - type: "success" - }); - - handlePopUpToggle("disableRenewal", false); - } catch (err) { - console.error(err); - createNotification({ - text: "Failed to disable auto-renewal", + text: "Project not found", type: "error" }); + return; } + + await updateRenewalConfig({ + certificateId: certificateData.certificateId, + projectSlug: currentProject.slug, + enableAutoRenewal: false + }); + + createNotification({ + text: "Successfully disabled auto-renewal", + type: "success" + }); + + handlePopUpToggle("disableRenewal", false); }; return ( diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalModal.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalModal.tsx index 0e2b1c17d..87906e5a5 100644 --- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalModal.tsx +++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalModal.tsx @@ -18,22 +18,18 @@ export const CertificateRenewalModal = ({ popUp, handlePopUpToggle }: Props) => const { mutateAsync: renewCertificate, isPending: isRenewing } = useRenewCertificate(); const onRenewConfirm = async () => { - try { - const { certificateId } = popUp.renewCertificate.data as { certificateId: string }; + const { certificateId } = popUp.renewCertificate.data as { certificateId: string }; - await renewCertificate({ - certificateId - }); + await renewCertificate({ + certificateId + }); - createNotification({ - text: "Certificate renewed successfully", - type: "success" - }); + createNotification({ + text: "Certificate renewed successfully", + type: "success" + }); - handlePopUpToggle("renewCertificate", false); - } catch (err) { - console.error(err); - } + handlePopUpToggle("renewCertificate", false); }; const certificateData = popUp.renewCertificate.data as { diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRevocationModal.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRevocationModal.tsx index 1d1539296..d9a564fb1 100644 --- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRevocationModal.tsx +++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRevocationModal.tsx @@ -48,31 +48,23 @@ export const CertificateRevocationModal = ({ popUp, handlePopUpToggle }: Props) }); const onFormSubmit = async ({ revocationReason }: FormData) => { - try { - if (!currentProject?.slug) return; + if (!currentProject?.slug) return; - const { serialNumber } = popUp.revokeCertificate.data as { serialNumber: string }; + const { serialNumber } = popUp.revokeCertificate.data as { serialNumber: string }; - await revokeCertificate({ - projectSlug: currentProject.slug, - serialNumber, - revocationReason - }); + await revokeCertificate({ + projectSlug: currentProject.slug, + serialNumber, + revocationReason + }); - reset(); - handlePopUpToggle("revokeCertificate", false); + reset(); + handlePopUpToggle("revokeCertificate", false); - createNotification({ - text: "Successfully revoked certificate", - type: "success" - }); - } catch (err) { - console.error(err); - createNotification({ - text: "Failed to revoke certificate", - type: "error" - }); - } + createNotification({ + text: "Successfully revoked certificate", + type: "success" + }); }; return ( diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateTemplateModal.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateTemplateModal.tsx index 9d5d9355f..66e9ec57a 100644 --- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateTemplateModal.tsx +++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateTemplateModal.tsx @@ -159,61 +159,53 @@ export const CertificateTemplateModal = ({ popUp, handlePopUpToggle, caId }: Pro return; } - try { - if (certTemplate) { - await updateCertTemplate({ - id: certTemplate.id, - projectId: currentProject.id, - pkiCollectionId: collectionId, - caId, - name, - commonName, - subjectAlternativeName, - ttl, - keyUsages: Object.entries(keyUsages) - .filter(([, value]) => value) - .map(([key]) => key as CertKeyUsage), - extendedKeyUsages: Object.entries(extendedKeyUsages) - .filter(([, value]) => value) - .map(([key]) => key as CertExtendedKeyUsage) - }); + if (certTemplate) { + await updateCertTemplate({ + id: certTemplate.id, + projectId: currentProject.id, + pkiCollectionId: collectionId, + caId, + name, + commonName, + subjectAlternativeName, + ttl, + keyUsages: Object.entries(keyUsages) + .filter(([, value]) => value) + .map(([key]) => key as CertKeyUsage), + extendedKeyUsages: Object.entries(extendedKeyUsages) + .filter(([, value]) => value) + .map(([key]) => key as CertExtendedKeyUsage) + }); - createNotification({ - text: "Successfully updated certificate template", - type: "success" - }); - } else { - await createCertTemplate({ - projectId: currentProject.id, - pkiCollectionId: collectionId, - caId, - name, - commonName, - subjectAlternativeName, - ttl, - keyUsages: Object.entries(keyUsages) - .filter(([, value]) => value) - .map(([key]) => key as CertKeyUsage), - extendedKeyUsages: Object.entries(extendedKeyUsages) - .filter(([, value]) => value) - .map(([key]) => key as CertExtendedKeyUsage) - }); - - createNotification({ - text: "Successfully created certificate template", - type: "success" - }); - } - - reset(); - handlePopUpToggle("certificateTemplate", false); - } catch (err) { - console.error(err); createNotification({ - text: "Failed to save changes", - type: "error" + text: "Successfully updated certificate template", + type: "success" + }); + } else { + await createCertTemplate({ + projectId: currentProject.id, + pkiCollectionId: collectionId, + caId, + name, + commonName, + subjectAlternativeName, + ttl, + keyUsages: Object.entries(keyUsages) + .filter(([, value]) => value) + .map(([key]) => key as CertKeyUsage), + extendedKeyUsages: Object.entries(extendedKeyUsages) + .filter(([, value]) => value) + .map(([key]) => key as CertExtendedKeyUsage) + }); + + createNotification({ + text: "Successfully created certificate template", + type: "success" }); } + + reset(); + handlePopUpToggle("certificateTemplate", false); }; return ( diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateTemplatesSection.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateTemplatesSection.tsx index 629553200..ce55c7e80 100644 --- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateTemplatesSection.tsx +++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateTemplatesSection.tsx @@ -41,25 +41,17 @@ export const CertificateTemplatesSection = ({ caId }: Props) => { return; } - try { - await deleteCertTemplate({ - id, - projectId: currentProject.id - }); + await deleteCertTemplate({ + id, + projectId: currentProject.id + }); - createNotification({ - text: "Successfully deleted certificate template", - type: "success" - }); + createNotification({ + text: "Successfully deleted certificate template", + type: "success" + }); - handlePopUpClose("deleteCertificateTemplate"); - } catch (err) { - console.error(err); - createNotification({ - text: "Failed to delete certificate template", - type: "error" - }); - } + handlePopUpClose("deleteCertificateTemplate"); }; return ( diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesSection.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesSection.tsx index 4102d8ea5..0252b1238 100644 --- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesSection.tsx +++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesSection.tsx @@ -41,24 +41,16 @@ export const CertificatesSection = () => { ] as const); const onRemoveCertificateSubmit = async (serialNumber: string) => { - try { - if (!currentProject?.slug) return; + if (!currentProject?.slug) return; - await deleteCert({ serialNumber, projectSlug: currentProject.slug }); + await deleteCert({ serialNumber, projectSlug: currentProject.slug }); - createNotification({ - text: "Successfully deleted certificate", - type: "success" - }); + createNotification({ + text: "Successfully deleted certificate", + type: "success" + }); - handlePopUpClose("deleteCertificate"); - } catch (err) { - console.error(err); - createNotification({ - text: "Failed to delete certificate", - type: "error" - }); - } + handlePopUpClose("deleteCertificate"); }; return ( diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesTable.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesTable.tsx index 500286d67..77f287ac5 100644 --- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesTable.tsx +++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesTable.tsx @@ -200,32 +200,24 @@ export const CertificatesTable = ({ handlePopUpOpen }: Props) => { }, [caData]); const handleDisableAutoRenewal = async (certificateId: string, commonName: string) => { - try { - if (!currentProject?.slug) { - createNotification({ - text: "Unable to disable auto-renewal: Project not found. Please refresh the page and try again.", - type: "error" - }); - return; - } - - await updateRenewalConfig({ - certificateId, - projectSlug: currentProject.slug, - enableAutoRenewal: false - }); - + if (!currentProject?.slug) { createNotification({ - text: `Auto-renewal disabled for ${commonName}`, - type: "success" - }); - } catch (err) { - console.error(err); - createNotification({ - text: "Failed to disable auto-renewal. Please try again or contact support if the issue persists.", + text: "Unable to disable auto-renewal: Project not found. Please refresh the page and try again.", type: "error" }); + return; } + + await updateRenewalConfig({ + certificateId, + projectSlug: currentProject.slug, + enableAutoRenewal: false + }); + + createNotification({ + text: `Auto-renewal disabled for ${commonName}`, + type: "success" + }); }; return ( diff --git a/frontend/src/pages/cert-manager/IntegrationsListPage/components/PkiSyncsTab/PkiSyncTable/PkiSyncsTable.tsx b/frontend/src/pages/cert-manager/IntegrationsListPage/components/PkiSyncsTab/PkiSyncTable/PkiSyncsTable.tsx index ca4aa7473..f997c350d 100644 --- a/frontend/src/pages/cert-manager/IntegrationsListPage/components/PkiSyncsTab/PkiSyncTable/PkiSyncsTable.tsx +++ b/frontend/src/pages/cert-manager/IntegrationsListPage/components/PkiSyncsTab/PkiSyncTable/PkiSyncsTable.tsx @@ -226,46 +226,32 @@ export const PkiSyncsTable = ({ pkiSyncs }: Props) => { const isAutoSyncEnabled = !pkiSync.isAutoSyncEnabled; - try { - await updateSync.mutateAsync({ - syncId: pkiSync.id, - projectId: pkiSync.projectId, - destination: pkiSync.destination, - isAutoSyncEnabled - }); + await updateSync.mutateAsync({ + syncId: pkiSync.id, + projectId: pkiSync.projectId, + destination: pkiSync.destination, + isAutoSyncEnabled + }); - createNotification({ - text: `Successfully ${isAutoSyncEnabled ? "enabled" : "disabled"} auto-sync for ${destinationName} Sync`, - type: "success" - }); - } catch { - createNotification({ - text: `Failed to ${isAutoSyncEnabled ? "enable" : "disable"} auto-sync for ${destinationName} Sync`, - type: "error" - }); - } + createNotification({ + text: `Successfully ${isAutoSyncEnabled ? "enabled" : "disabled"} auto-sync for ${destinationName} Sync`, + type: "success" + }); }; const handleTriggerSync = async (pkiSync: TPkiSync) => { const destinationName = PKI_SYNC_MAP[pkiSync.destination].name; - try { - await triggerSync.mutateAsync({ - syncId: pkiSync.id, - destination: pkiSync.destination, - projectId: pkiSync.projectId - }); + await triggerSync.mutateAsync({ + syncId: pkiSync.id, + destination: pkiSync.destination, + projectId: pkiSync.projectId + }); - createNotification({ - text: `Successfully triggered ${destinationName} Sync`, - type: "success" - }); - } catch { - createNotification({ - text: `Failed to trigger ${destinationName} Sync`, - type: "error" - }); - } + createNotification({ + text: `Successfully triggered ${destinationName} Sync`, + type: "success" + }); }; return ( diff --git a/frontend/src/pages/cert-manager/PkiCollectionDetailsByIDPage/PkiCollectionDetailsByIDPage.tsx b/frontend/src/pages/cert-manager/PkiCollectionDetailsByIDPage/PkiCollectionDetailsByIDPage.tsx index b8235f488..064f8f7a2 100644 --- a/frontend/src/pages/cert-manager/PkiCollectionDetailsByIDPage/PkiCollectionDetailsByIDPage.tsx +++ b/frontend/src/pages/cert-manager/PkiCollectionDetailsByIDPage/PkiCollectionDetailsByIDPage.tsx @@ -45,31 +45,24 @@ export const PkiCollectionPage = () => { ] as const); const onDeletePkiCollectionSubmit = async (collectionIdToDelete: string) => { - try { - if (!projectId) return; + if (!projectId) return; - await deletePkiCollection({ - projectId, - collectionId: collectionIdToDelete - }); + await deletePkiCollection({ + projectId, + collectionId: collectionIdToDelete + }); - createNotification({ - text: "Successfully deleted PKI collection", - type: "success" - }); - handlePopUpClose("deletePkiCollection"); - navigate({ - to: "/projects/cert-management/$projectId/certificates", - params: { - projectId - } - }); - } catch { - createNotification({ - text: "Failed to delete PKI collection", - type: "error" - }); - } + createNotification({ + text: "Successfully deleted PKI collection", + type: "success" + }); + handlePopUpClose("deletePkiCollection"); + navigate({ + to: "/projects/cert-management/$projectId/certificates", + params: { + projectId + } + }); }; return ( diff --git a/frontend/src/pages/cert-manager/PkiSubscriberDetailsByIDPage/PkiSubscriberDetailsByIDPage.tsx b/frontend/src/pages/cert-manager/PkiSubscriberDetailsByIDPage/PkiSubscriberDetailsByIDPage.tsx index 1f723b395..572ee998e 100644 --- a/frontend/src/pages/cert-manager/PkiSubscriberDetailsByIDPage/PkiSubscriberDetailsByIDPage.tsx +++ b/frontend/src/pages/cert-manager/PkiSubscriberDetailsByIDPage/PkiSubscriberDetailsByIDPage.tsx @@ -51,30 +51,22 @@ const Page = () => { ] as const); const onRemoveSubscriberSubmit = async (subscriberNameToDelete: string) => { - try { - if (!projectId) return; + if (!projectId) return; - await deletePkiSubscriber({ subscriberName: subscriberNameToDelete, projectId }); + await deletePkiSubscriber({ subscriberName: subscriberNameToDelete, projectId }); - createNotification({ - text: "Successfully deleted subscriber", - type: "success" - }); + createNotification({ + text: "Successfully deleted subscriber", + type: "success" + }); - handlePopUpClose("deletePkiSubscriber"); - navigate({ - to: "/projects/cert-management/$projectId/subscribers", - params: { - projectId - } - }); - } catch (err) { - console.error(err); - createNotification({ - text: "Failed to delete subscriber", - type: "error" - }); - } + handlePopUpClose("deletePkiSubscriber"); + navigate({ + to: "/projects/cert-management/$projectId/subscribers", + params: { + projectId + } + }); }; return ( diff --git a/frontend/src/pages/cert-manager/PkiSubscriberDetailsByIDPage/components/PkiSubscriberDetailsSection.tsx b/frontend/src/pages/cert-manager/PkiSubscriberDetailsByIDPage/components/PkiSubscriberDetailsSection.tsx index f9c94740a..5da5be55a 100644 --- a/frontend/src/pages/cert-manager/PkiSubscriberDetailsByIDPage/components/PkiSubscriberDetailsSection.tsx +++ b/frontend/src/pages/cert-manager/PkiSubscriberDetailsByIDPage/components/PkiSubscriberDetailsSection.tsx @@ -70,36 +70,28 @@ export const PkiSubscriberDetailsSection = ({ subscriberName, handlePopUpOpen }: useOrderPkiSubscriberCert(); const onIssuePkiSubscriberCert = async () => { - try { - if (pkiSubscriber?.supportsImmediateCertIssuance) { - const response = await issuePkiSubscriberCert({ subscriberName, projectId }); + if (pkiSubscriber?.supportsImmediateCertIssuance) { + const response = await issuePkiSubscriberCert({ subscriberName, projectId }); - setCertificateDetails({ - serialNumber: response.serialNumber, - certificate: response.certificate, - certificateChain: response.certificateChain, - privateKey: response.privateKey - }); + setCertificateDetails({ + serialNumber: response.serialNumber, + certificate: response.certificate, + certificateChain: response.certificateChain, + privateKey: response.privateKey + }); - setIsModalOpen(true); + setIsModalOpen(true); - createNotification({ - text: "Successfully issued certificate", - type: "success" - }); - } else { - await orderPkiSubscriberCert({ subscriberName, projectId }); - - createNotification({ - text: "Successfully ordered certificate. It will be issued after CA processing which could take a few minutes.", - type: "info" - }); - } - } catch (err) { - console.error(err); createNotification({ - text: "Failed to issue certificate", - type: "error" + text: "Successfully issued certificate", + type: "success" + }); + } else { + await orderPkiSubscriberCert({ subscriberName, projectId }); + + createNotification({ + text: "Successfully ordered certificate. It will be issued after CA processing which could take a few minutes.", + type: "info" }); } }; diff --git a/frontend/src/pages/cert-manager/PkiSubscribersPage/components/PkiSubscriberModal.tsx b/frontend/src/pages/cert-manager/PkiSubscribersPage/components/PkiSubscriberModal.tsx index 4bc427e48..15c016587 100644 --- a/frontend/src/pages/cert-manager/PkiSubscribersPage/components/PkiSubscriberModal.tsx +++ b/frontend/src/pages/cert-manager/PkiSubscribersPage/components/PkiSubscriberModal.tsx @@ -276,117 +276,109 @@ export const PkiSubscriberModal = ({ popUp, handlePopUpToggle }: Props) => { locality, emailAddress }: FormData) => { - try { - if (!projectId) return; - - if (!caId) { - createNotification({ - text: "Please select an Issuing CA", - type: "error" - }); - return; - } - - // Check if there is already a different subscriber with the same name - const existingNames = - subscribers?.filter((s) => s.id !== pkiSubscriber?.id).map((s) => s.name) || []; - - if (existingNames.includes(name.trim())) { - createNotification({ - text: "A subscriber with this name already exists.", - type: "error" - }); - return; - } - - // Validate Azure template for Azure ADCS CA - if (selectedCa?.type === CaType.AZURE_AD_CS && !azureTemplateType) { - createNotification({ - text: "Please select an Azure certificate template", - type: "error" - }); - return; - } - - const keyUsagesList = - selectedCa?.type === CaType.AZURE_AD_CS - ? [] - : Object.entries(keyUsages) - .filter(([, value]) => value) - .map(([key]) => key as CertKeyUsage); - - const extendedKeyUsagesList = - selectedCa?.type === CaType.AZURE_AD_CS - ? [] - : Object.entries(extendedKeyUsages) - .filter(([, value]) => value) - .map(([key]) => key as CertExtendedKeyUsage); - - const subjectAlternativeNamesList = subjectAlternativeNames - .split(",") - .map((san) => san.trim()) - .filter(Boolean); - - const autoRenewalPeriodInDays = enableAutoRenewal - ? convertTimeUnitValueToDays(renewalUnit, renewalBefore) - : undefined; - - // Build properties object - const properties = { - ...(selectedCa?.type === CaType.AZURE_AD_CS && azureTemplateType && { azureTemplateType }), - ...(organization && { organization }), - ...(organizationalUnit && { organizationalUnit }), - ...(country && { country }), - ...(state && { state }), - ...(locality && { locality }), - ...(emailAddress && { emailAddress }) - }; - - if (pkiSubscriber) { - await updateMutateAsync({ - subscriberName: pkiSubscriber.name, - projectId, - name, - caId, - commonName, - subjectAlternativeNames: subjectAlternativeNamesList, - ttl, - keyUsages: keyUsagesList, - extendedKeyUsages: extendedKeyUsagesList, - enableAutoRenewal, - autoRenewalPeriodInDays, - properties: Object.keys(properties).length > 0 ? properties : undefined - }); - } else { - await createMutateAsync({ - projectId, - name, - caId, - commonName, - subjectAlternativeNames: subjectAlternativeNamesList, - ttl, - keyUsages: keyUsagesList, - extendedKeyUsages: extendedKeyUsagesList, - enableAutoRenewal, - autoRenewalPeriodInDays, - properties: Object.keys(properties).length > 0 ? properties : undefined - }); - } - - reset(); - handlePopUpToggle("pkiSubscriber", false); + if (!projectId) return; + if (!caId) { createNotification({ - text: `Successfully ${pkiSubscriber ? "updated" : "added"} PKI subscriber`, - type: "success" - }); - } catch (err) { - console.error(err); - createNotification({ - text: `Failed to ${pkiSubscriber ? "update" : "add"} PKI subscriber`, + text: "Please select an Issuing CA", type: "error" }); + return; } + + // Check if there is already a different subscriber with the same name + const existingNames = + subscribers?.filter((s) => s.id !== pkiSubscriber?.id).map((s) => s.name) || []; + + if (existingNames.includes(name.trim())) { + createNotification({ + text: "A subscriber with this name already exists.", + type: "error" + }); + return; + } + + // Validate Azure template for Azure ADCS CA + if (selectedCa?.type === CaType.AZURE_AD_CS && !azureTemplateType) { + createNotification({ + text: "Please select an Azure certificate template", + type: "error" + }); + return; + } + + const keyUsagesList = + selectedCa?.type === CaType.AZURE_AD_CS + ? [] + : Object.entries(keyUsages) + .filter(([, value]) => value) + .map(([key]) => key as CertKeyUsage); + + const extendedKeyUsagesList = + selectedCa?.type === CaType.AZURE_AD_CS + ? [] + : Object.entries(extendedKeyUsages) + .filter(([, value]) => value) + .map(([key]) => key as CertExtendedKeyUsage); + + const subjectAlternativeNamesList = subjectAlternativeNames + .split(",") + .map((san) => san.trim()) + .filter(Boolean); + + const autoRenewalPeriodInDays = enableAutoRenewal + ? convertTimeUnitValueToDays(renewalUnit, renewalBefore) + : undefined; + + // Build properties object + const properties = { + ...(selectedCa?.type === CaType.AZURE_AD_CS && azureTemplateType && { azureTemplateType }), + ...(organization && { organization }), + ...(organizationalUnit && { organizationalUnit }), + ...(country && { country }), + ...(state && { state }), + ...(locality && { locality }), + ...(emailAddress && { emailAddress }) + }; + + if (pkiSubscriber) { + await updateMutateAsync({ + subscriberName: pkiSubscriber.name, + projectId, + name, + caId, + commonName, + subjectAlternativeNames: subjectAlternativeNamesList, + ttl, + keyUsages: keyUsagesList, + extendedKeyUsages: extendedKeyUsagesList, + enableAutoRenewal, + autoRenewalPeriodInDays, + properties: Object.keys(properties).length > 0 ? properties : undefined + }); + } else { + await createMutateAsync({ + projectId, + name, + caId, + commonName, + subjectAlternativeNames: subjectAlternativeNamesList, + ttl, + keyUsages: keyUsagesList, + extendedKeyUsages: extendedKeyUsagesList, + enableAutoRenewal, + autoRenewalPeriodInDays, + properties: Object.keys(properties).length > 0 ? properties : undefined + }); + } + + reset(); + handlePopUpToggle("pkiSubscriber", false); + + createNotification({ + text: `Successfully ${pkiSubscriber ? "updated" : "added"} PKI subscriber`, + type: "success" + }); }; return ( diff --git a/frontend/src/pages/cert-manager/PkiSubscribersPage/components/PkiSubscriberSection.tsx b/frontend/src/pages/cert-manager/PkiSubscribersPage/components/PkiSubscriberSection.tsx index cb4b9ef39..e902711ce 100644 --- a/frontend/src/pages/cert-manager/PkiSubscribersPage/components/PkiSubscriberSection.tsx +++ b/frontend/src/pages/cert-manager/PkiSubscribersPage/components/PkiSubscriberSection.tsx @@ -33,22 +33,14 @@ export const PkiSubscriberSection = () => { ] as const); const onRemovePkiSubscriberSubmit = async (subscriberName: string) => { - try { - const subscriber = await deletePkiSubscriber({ subscriberName, projectId }); + const subscriber = await deletePkiSubscriber({ subscriberName, projectId }); - createNotification({ - text: `Successfully deleted PKI subscriber: ${subscriber.name}`, - type: "success" - }); + createNotification({ + text: `Successfully deleted PKI subscriber: ${subscriber.name}`, + type: "success" + }); - handlePopUpClose("deletePkiSubscriber"); - } catch (err) { - console.error(err); - createNotification({ - text: "Failed to delete PKI subscriber", - type: "error" - }); - } + handlePopUpClose("deletePkiSubscriber"); }; const onUpdatePkiSubscriberStatus = async ({ @@ -58,24 +50,16 @@ export const PkiSubscriberSection = () => { subscriberName: string; status: PkiSubscriberStatus; }) => { - try { - if (!currentProject?.slug) return; + if (!currentProject?.slug) return; - await updatePkiSubscriber({ subscriberName, projectId, status }); + await updatePkiSubscriber({ subscriberName, projectId, status }); - createNotification({ - text: `Successfully ${status === PkiSubscriberStatus.ACTIVE ? "enabled" : "disabled"} subscriber`, - type: "success" - }); + createNotification({ + text: `Successfully ${status === PkiSubscriberStatus.ACTIVE ? "enabled" : "disabled"} subscriber`, + type: "success" + }); - handlePopUpClose("pkiSubscriberStatus"); - } catch (err) { - console.error(err); - createNotification({ - text: `Failed to ${status === PkiSubscriberStatus.ACTIVE ? "enable" : "disable"} subscriber`, - type: "error" - }); - } + handlePopUpClose("pkiSubscriberStatus"); }; const subscriberStatusData = popUp?.pkiSubscriberStatus?.data as { diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncActionTriggers.tsx b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncActionTriggers.tsx index bb8e9d02a..5171b4d95 100644 --- a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncActionTriggers.tsx +++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncActionTriggers.tsx @@ -86,44 +86,28 @@ export const PkiSyncActionTriggers = ({ pkiSync }: Props) => { }, [pkiSync.id, setIsIdCopied]); const handleTriggerSync = useCallback(async () => { - try { - await triggerSyncMutation.mutateAsync({ - syncId: id, - destination, - projectId - }); - createNotification({ - text: "PKI sync job queued successfully", - type: "success" - }); - } catch (error) { - console.error("Failed to trigger sync:", error); - createNotification({ - text: "Failed to trigger PKI sync", - type: "error" - }); - } + await triggerSyncMutation.mutateAsync({ + syncId: id, + destination, + projectId + }); + createNotification({ + text: "PKI sync job queued successfully", + type: "success" + }); }, [triggerSyncMutation, id, destination, projectId]); const handleToggleAutoSync = useCallback(async () => { - try { - await updatePkiSyncMutation.mutateAsync({ - syncId: id, - projectId, - destination, - isAutoSyncEnabled: !pkiSync.isAutoSyncEnabled - }); - createNotification({ - text: `Auto-sync ${pkiSync.isAutoSyncEnabled ? "disabled" : "enabled"} successfully`, - type: "success" - }); - } catch (error) { - console.error("Failed to toggle auto-sync:", error); - createNotification({ - text: "Failed to toggle auto-sync", - type: "error" - }); - } + await updatePkiSyncMutation.mutateAsync({ + syncId: id, + projectId, + destination, + isAutoSyncEnabled: !pkiSync.isAutoSyncEnabled + }); + createNotification({ + text: `Auto-sync ${pkiSync.isAutoSyncEnabled ? "disabled" : "enabled"} successfully`, + type: "success" + }); }, [updatePkiSyncMutation, id, projectId, pkiSync.isAutoSyncEnabled]); const permissionSubject = subject(ProjectPermissionSub.PkiSyncs, { diff --git a/frontend/src/pages/cert-manager/PkiTemplateListPage/PkiTemplateListPage.tsx b/frontend/src/pages/cert-manager/PkiTemplateListPage/PkiTemplateListPage.tsx index b395d0ec2..9ad290062 100644 --- a/frontend/src/pages/cert-manager/PkiTemplateListPage/PkiTemplateListPage.tsx +++ b/frontend/src/pages/cert-manager/PkiTemplateListPage/PkiTemplateListPage.tsx @@ -78,25 +78,17 @@ export const PkiTemplateListPage = () => { const deleteCertTemplate = useDeleteCertTemplateV2(); const onRemovePkiSubscriberSubmit = async () => { - try { - const pkiTemplate = await deleteCertTemplate.mutateAsync({ - projectId: currentProject.id, - templateName: popUp?.deleteTemplate?.data?.name - }); + const pkiTemplate = await deleteCertTemplate.mutateAsync({ + projectId: currentProject.id, + templateName: popUp?.deleteTemplate?.data?.name + }); - createNotification({ - text: `Successfully deleted PKI template: ${pkiTemplate.name}`, - type: "success" - }); + createNotification({ + text: `Successfully deleted PKI template: ${pkiTemplate.name}`, + type: "success" + }); - handlePopUpClose("deleteTemplate"); - } catch (err) { - console.error(err); - createNotification({ - text: "Failed to delete PKI subscriber", - type: "error" - }); - } + handlePopUpClose("deleteTemplate"); }; return ( diff --git a/frontend/src/pages/cert-manager/PkiTemplateListPage/components/PkiTemplateForm.tsx b/frontend/src/pages/cert-manager/PkiTemplateListPage/components/PkiTemplateForm.tsx index 093a2fcc1..00aa192a6 100644 --- a/frontend/src/pages/cert-manager/PkiTemplateListPage/components/PkiTemplateForm.tsx +++ b/frontend/src/pages/cert-manager/PkiTemplateListPage/components/PkiTemplateForm.tsx @@ -128,59 +128,51 @@ export const PkiTemplateForm = ({ certTemplate, handlePopUpToggle }: Props) => { return; } - try { - if (certTemplate) { - await updateCertTemplate({ - templateName: certTemplate.name, - projectId: currentProject.id, - caName: ca.name, - name, - commonName, - subjectAlternativeName, - ttl, - keyUsages: Object.entries(keyUsages) - .filter(([, value]) => value) - .map(([key]) => key as CertKeyUsage), - extendedKeyUsages: Object.entries(extendedKeyUsages) - .filter(([, value]) => value) - .map(([key]) => key as CertExtendedKeyUsage) - }); + if (certTemplate) { + await updateCertTemplate({ + templateName: certTemplate.name, + projectId: currentProject.id, + caName: ca.name, + name, + commonName, + subjectAlternativeName, + ttl, + keyUsages: Object.entries(keyUsages) + .filter(([, value]) => value) + .map(([key]) => key as CertKeyUsage), + extendedKeyUsages: Object.entries(extendedKeyUsages) + .filter(([, value]) => value) + .map(([key]) => key as CertExtendedKeyUsage) + }); - createNotification({ - text: "Successfully updated certificate template", - type: "success" - }); - } else { - await createCertTemplate({ - projectId: currentProject.id, - caName: ca.name, - name, - commonName, - subjectAlternativeName, - ttl, - keyUsages: Object.entries(keyUsages) - .filter(([, value]) => value) - .map(([key]) => key as CertKeyUsage), - extendedKeyUsages: Object.entries(extendedKeyUsages) - .filter(([, value]) => value) - .map(([key]) => key as CertExtendedKeyUsage) - }); - - createNotification({ - text: "Successfully created certificate template", - type: "success" - }); - } - - reset(); - handlePopUpToggle(false); - } catch (err) { - console.error(err); createNotification({ - text: "Failed to save changes", - type: "error" + text: "Successfully updated certificate template", + type: "success" + }); + } else { + await createCertTemplate({ + projectId: currentProject.id, + caName: ca.name, + name, + commonName, + subjectAlternativeName, + ttl, + keyUsages: Object.entries(keyUsages) + .filter(([, value]) => value) + .map(([key]) => key as CertKeyUsage), + extendedKeyUsages: Object.entries(extendedKeyUsages) + .filter(([, value]) => value) + .map(([key]) => key as CertExtendedKeyUsage) + }); + + createNotification({ + text: "Successfully created certificate template", + type: "success" }); } + + reset(); + handlePopUpToggle(false); }; return ( diff --git a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CertificateProfilesTab.tsx b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CertificateProfilesTab.tsx index d034aeda1..7938d04f5 100644 --- a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CertificateProfilesTab.tsx +++ b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CertificateProfilesTab.tsx @@ -51,22 +51,15 @@ export const CertificateProfilesTab = () => { const handleDeleteConfirm = async () => { if (!selectedProfile) return; - try { - await deleteProfile.mutateAsync({ - profileId: selectedProfile.id - }); - setIsDeleteModalOpen(false); - setSelectedProfile(null); - createNotification({ - text: `Certificate profile "${selectedProfile.slug}" deleted successfully`, - type: "success" - }); - } catch (error) { - console.error( - `Failed to delete profile "${selectedProfile.slug}" (ID: ${selectedProfile.id}):`, - error - ); - } + await deleteProfile.mutateAsync({ + profileId: selectedProfile.id + }); + setIsDeleteModalOpen(false); + setSelectedProfile(null); + createNotification({ + text: `Certificate profile "${selectedProfile.slug}" deleted successfully`, + type: "success" + }); }; return ( diff --git a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal.tsx b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal.tsx index ea82fd843..56e72ca2b 100644 --- a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal.tsx +++ b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal.tsx @@ -236,64 +236,56 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" } }, [isEdit, profile, reset]); const onFormSubmit = async (data: FormData) => { - try { - if (!currentProject?.id && !isEdit) return; + if (!currentProject?.id && !isEdit) return; - if (isEdit) { - const updateData: TUpdateCertificateProfileDTO = { - profileId: profile.id, - slug: data.slug, - description: data.description - }; + if (isEdit) { + const updateData: TUpdateCertificateProfileDTO = { + profileId: profile.id, + slug: data.slug, + description: data.description + }; - if (data.enrollmentType === "est" && data.estConfig) { - updateData.estConfig = data.estConfig; - } else if (data.enrollmentType === "api" && data.apiConfig) { - updateData.apiConfig = data.apiConfig; - } - - await updateProfile.mutateAsync(updateData); - } else { - if (!currentProject?.id) { - throw new Error("Project ID is required for creating a profile"); - } - - const createData: TCreateCertificateProfileDTO = { - projectId: currentProject.id, - slug: data.slug, - description: data.description, - enrollmentType: data.enrollmentType, - caId: data.certificateAuthorityId, - certificateTemplateId: data.certificateTemplateId - }; - - if (data.enrollmentType === "est" && data.estConfig) { - createData.estConfig = { - passphrase: data.estConfig.passphrase, - caChain: data.estConfig.caChain || undefined, - disableBootstrapCaValidation: data.estConfig.disableBootstrapCaValidation - }; - } else if (data.enrollmentType === "api" && data.apiConfig) { - createData.apiConfig = data.apiConfig; - } - - await createProfile.mutateAsync(createData); + if (data.enrollmentType === "est" && data.estConfig) { + updateData.estConfig = data.estConfig; + } else if (data.enrollmentType === "api" && data.apiConfig) { + updateData.apiConfig = data.apiConfig; } - createNotification({ - text: `Certificate profile ${isEdit ? "updated" : "created"} successfully`, - type: "success" - }); + await updateProfile.mutateAsync(updateData); + } else { + if (!currentProject?.id) { + throw new Error("Project ID is required for creating a profile"); + } - reset(); - onClose(); - } catch (error) { - console.error(`Error ${isEdit ? "updating" : "creating"} profile:`, error); - createNotification({ - text: `Failed to ${isEdit ? "update" : "create"} certificate profile`, - type: "error" - }); + const createData: TCreateCertificateProfileDTO = { + projectId: currentProject.id, + slug: data.slug, + description: data.description, + enrollmentType: data.enrollmentType, + caId: data.certificateAuthorityId, + certificateTemplateId: data.certificateTemplateId + }; + + if (data.enrollmentType === "est" && data.estConfig) { + createData.estConfig = { + passphrase: data.estConfig.passphrase, + caChain: data.estConfig.caChain || undefined, + disableBootstrapCaValidation: data.estConfig.disableBootstrapCaValidation + }; + } else if (data.enrollmentType === "api" && data.apiConfig) { + createData.apiConfig = data.apiConfig; + } + + await createProfile.mutateAsync(createData); } + + createNotification({ + text: `Certificate profile ${isEdit ? "updated" : "created"} successfully`, + type: "success" + }); + + reset(); + onClose(); }; return ( diff --git a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateTemplatesV2Tab/CertificateTemplatesV2Tab.tsx b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateTemplatesV2Tab/CertificateTemplatesV2Tab.tsx index ae14f2dea..ec660b339 100644 --- a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateTemplatesV2Tab/CertificateTemplatesV2Tab.tsx +++ b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateTemplatesV2Tab/CertificateTemplatesV2Tab.tsx @@ -48,23 +48,15 @@ export const CertificateTemplatesV2Tab = () => { const handleDeleteConfirm = async () => { if (!selectedTemplate) return; - try { - await deleteTemplateV2.mutateAsync({ - templateId: selectedTemplate.id - }); - setIsDeleteModalOpen(false); - setSelectedTemplate(null); - createNotification({ - text: `Certificate template "${selectedTemplate.name}" deleted successfully`, - type: "success" - }); - } catch (error) { - console.error("Failed to delete template:", error); - createNotification({ - text: "Failed to delete certificate template", - type: "error" - }); - } + await deleteTemplateV2.mutateAsync({ + templateId: selectedTemplate.id + }); + setIsDeleteModalOpen(false); + setSelectedTemplate(null); + createNotification({ + text: `Certificate template "${selectedTemplate.name}" deleted successfully`, + type: "success" + }); }; return ( diff --git a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateTemplatesV2Tab/CreateTemplateModal.tsx b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateTemplatesV2Tab/CreateTemplateModal.tsx index a96beccad..1387171fb 100644 --- a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateTemplatesV2Tab/CreateTemplateModal.tsx +++ b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateTemplatesV2Tab/CreateTemplateModal.tsx @@ -407,59 +407,51 @@ export const CreateTemplateModal = ({ isOpen, onClose, template, mode = "create" }; const onFormSubmit = async (data: FormData) => { - try { - if (!currentProject?.id && !isEdit) return; + if (!currentProject?.id && !isEdit) return; - const hasEmptyAttributeValues = data.attributes?.some( - (attr) => !attr.value || attr.value.length === 0 || attr.value.some((v) => !v.trim()) - ); + const hasEmptyAttributeValues = data.attributes?.some( + (attr) => !attr.value || attr.value.length === 0 || attr.value.some((v) => !v.trim()) + ); - const hasEmptySanValues = data.subjectAlternativeNames?.some( - (san) => !san.value || san.value.length === 0 || san.value.some((v) => !v.trim()) - ); - - if (hasEmptyAttributeValues || hasEmptySanValues) { - createNotification({ - text: "All values must be non-empty. Use wildcards (*) if needed.", - type: "error" - }); - return; - } - - const transformedData = transformToApiFormat(data); - - if (isEdit) { - const updateData = { - templateId: template.id, - ...transformedData - }; - await updateTemplate.mutateAsync(updateData); - } else { - if (!currentProject?.id) { - throw new Error("Project ID is required for creating a template"); - } - - const createData = { - projectId: currentProject.id, - ...transformedData - }; - await createTemplate.mutateAsync(createData); - } + const hasEmptySanValues = data.subjectAlternativeNames?.some( + (san) => !san.value || san.value.length === 0 || san.value.some((v) => !v.trim()) + ); + if (hasEmptyAttributeValues || hasEmptySanValues) { createNotification({ - text: `Certificate template ${isEdit ? "updated" : "created"} successfully`, - type: "success" - }); - - reset(); - onClose(); - } catch (error) { - console.error(`Error ${isEdit ? "updating" : "creating"} template:`, error); - createNotification({ - text: `Failed to ${isEdit ? "update" : "create"} certificate template`, + text: "All values must be non-empty. Use wildcards (*) if needed.", type: "error" }); + return; } + + const transformedData = transformToApiFormat(data); + + if (isEdit) { + const updateData = { + templateId: template.id, + ...transformedData + }; + await updateTemplate.mutateAsync(updateData); + } else { + if (!currentProject?.id) { + throw new Error("Project ID is required for creating a template"); + } + + const createData = { + projectId: currentProject.id, + ...transformedData + }; + await createTemplate.mutateAsync(createData); + } + + createNotification({ + text: `Certificate template ${isEdit ? "updated" : "created"} successfully`, + type: "success" + }); + + reset(); + onClose(); }; const addAttribute = () => { diff --git a/frontend/src/pages/kms/KmipPage/components/DeleteKmipClientModal.tsx b/frontend/src/pages/kms/KmipPage/components/DeleteKmipClientModal.tsx index fe9c956ab..2d6accf76 100644 --- a/frontend/src/pages/kms/KmipPage/components/DeleteKmipClientModal.tsx +++ b/frontend/src/pages/kms/KmipPage/components/DeleteKmipClientModal.tsx @@ -17,28 +17,17 @@ export const DeleteKmipClientModal = ({ isOpen, onOpenChange, kmipClient }: Prop const { id, projectId, name } = kmipClient; const handleDeleteKmipClient = async () => { - try { - await deleteKmipClients.mutateAsync({ - id, - projectId - }); + await deleteKmipClients.mutateAsync({ + id, + projectId + }); - createNotification({ - text: "KMIP client successfully deleted", - type: "success" - }); + createNotification({ + text: "KMIP client successfully deleted", + type: "success" + }); - onOpenChange(false); - } catch (err) { - console.error(err); - const error = err as any; - const text = error?.response?.data?.message ?? "Failed to delete KMIP client"; - - createNotification({ - text, - type: "error" - }); - } + onOpenChange(false); }; return ( diff --git a/frontend/src/pages/kms/KmipPage/components/KmipClientModal.tsx b/frontend/src/pages/kms/KmipPage/components/KmipClientModal.tsx index b3f3fb380..f10d077a4 100644 --- a/frontend/src/pages/kms/KmipPage/components/KmipClientModal.tsx +++ b/frontend/src/pages/kms/KmipPage/components/KmipClientModal.tsx @@ -98,20 +98,12 @@ const KmipClientForm = ({ onComplete, kmipClient }: FormProps) => { .map(([key]) => key as KmipPermission) }); - try { - await mutation; - createNotification({ - text: `Successfully ${isUpdate ? "updated" : "added"} KMIP client`, - type: "success" - }); - onComplete(); - } catch (err) { - console.error(err); - createNotification({ - text: `Failed to ${isUpdate ? "update" : "add"} KMIP client`, - type: "error" - }); - } + await mutation; + createNotification({ + text: `Successfully ${isUpdate ? "updated" : "added"} KMIP client`, + type: "success" + }); + onComplete(); }; return ( diff --git a/frontend/src/pages/kms/OverviewPage/components/CmekDecryptModal.tsx b/frontend/src/pages/kms/OverviewPage/components/CmekDecryptModal.tsx index 4c9cf685b..4fd6b3419 100644 --- a/frontend/src/pages/kms/OverviewPage/components/CmekDecryptModal.tsx +++ b/frontend/src/pages/kms/OverviewPage/components/CmekDecryptModal.tsx @@ -52,23 +52,15 @@ const DecryptForm = ({ cmek }: FormProps) => { }); const handleDecryptData = async (formData: FormData) => { - try { - const data = await cmekDecrypt.mutateAsync({ ...formData, keyId: cmek.id }); - createNotification({ - text: "Successfully decrypted data", - type: "success" - }); + const data = await cmekDecrypt.mutateAsync({ ...formData, keyId: cmek.id }); + createNotification({ + text: "Successfully decrypted data", + type: "success" + }); - setPlaintext( - shouldDecode ? Buffer.from(decodeBase64(data.plaintext)).toString("utf8") : data.plaintext - ); - } catch (err) { - console.error(err); - createNotification({ - text: "Failed to decrypt data", - type: "error" - }); - } + setPlaintext( + shouldDecode ? Buffer.from(decodeBase64(data.plaintext)).toString("utf8") : data.plaintext + ); }; useEffect(() => { diff --git a/frontend/src/pages/kms/OverviewPage/components/CmekEncryptModal.tsx b/frontend/src/pages/kms/OverviewPage/components/CmekEncryptModal.tsx index 4fb09cf4e..a5bf01d5a 100644 --- a/frontend/src/pages/kms/OverviewPage/components/CmekEncryptModal.tsx +++ b/frontend/src/pages/kms/OverviewPage/components/CmekEncryptModal.tsx @@ -53,19 +53,11 @@ const EncryptForm = ({ cmek }: FormProps) => { }); const handleEncryptData = async (formData: FormData) => { - try { - await cmekEncrypt.mutateAsync({ ...formData, keyId: cmek.id }); - createNotification({ - text: "Successfully encrypted data", - type: "success" - }); - } catch (err) { - console.error(err); - createNotification({ - text: "Failed to encrypt data", - type: "error" - }); - } + await cmekEncrypt.mutateAsync({ ...formData, keyId: cmek.id }); + createNotification({ + text: "Successfully encrypted data", + type: "success" + }); }; const ciphertext = cmekEncrypt.data?.ciphertext; diff --git a/frontend/src/pages/kms/OverviewPage/components/CmekModal.tsx b/frontend/src/pages/kms/OverviewPage/components/CmekModal.tsx index c3cccd678..e79d91e15 100644 --- a/frontend/src/pages/kms/OverviewPage/components/CmekModal.tsx +++ b/frontend/src/pages/kms/OverviewPage/components/CmekModal.tsx @@ -86,20 +86,12 @@ const CmekForm = ({ onComplete, cmek }: FormProps) => { encryptionAlgorithm: encryptionAlgorithm as AsymmetricKeyAlgorithm | SymmetricKeyAlgorithm }); - try { - await mutation; - createNotification({ - text: `Successfully ${isUpdate ? "updated" : "added"} key`, - type: "success" - }); - onComplete(); - } catch (err) { - console.error(err); - createNotification({ - text: `Failed to ${isUpdate ? "update" : "add"} key`, - type: "error" - }); - } + await mutation; + createNotification({ + text: `Successfully ${isUpdate ? "updated" : "added"} key`, + type: "success" + }); + onComplete(); }; const selectedKeyUsage = watch("keyUsage"); diff --git a/frontend/src/pages/kms/OverviewPage/components/CmekSignModal.tsx b/frontend/src/pages/kms/OverviewPage/components/CmekSignModal.tsx index fec66a31f..e52c03dbe 100644 --- a/frontend/src/pages/kms/OverviewPage/components/CmekSignModal.tsx +++ b/frontend/src/pages/kms/OverviewPage/components/CmekSignModal.tsx @@ -59,19 +59,11 @@ const SignForm = ({ cmek }: FormProps) => { }); const handleSignData = async (formData: FormData) => { - try { - await cmekSign.mutateAsync({ ...formData, keyId: cmek.id }); - createNotification({ - text: "Successfully signed data", - type: "success" - }); - } catch (err) { - console.error(err); - createNotification({ - text: "Failed to sign data", - type: "error" - }); - } + await cmekSign.mutateAsync({ ...formData, keyId: cmek.id }); + createNotification({ + text: "Successfully signed data", + type: "success" + }); }; const signature = cmekSign.data?.signature; diff --git a/frontend/src/pages/kms/OverviewPage/components/CmekTable.tsx b/frontend/src/pages/kms/OverviewPage/components/CmekTable.tsx index a6675ea88..c9a0054c5 100644 --- a/frontend/src/pages/kms/OverviewPage/components/CmekTable.tsx +++ b/frontend/src/pages/kms/OverviewPage/components/CmekTable.tsx @@ -152,28 +152,16 @@ export const CmekTable = () => { const updateCmek = useUpdateCmek(); const handleDisableCmek = async ({ id: keyId, isDisabled }: TCmek) => { - try { - await updateCmek.mutateAsync({ - keyId, - projectId, - isDisabled: !isDisabled - }); + await updateCmek.mutateAsync({ + keyId, + projectId, + isDisabled: !isDisabled + }); - createNotification({ - text: `Key successfully ${isDisabled ? "enabled" : "disabled"}`, - type: "success" - }); - } catch (err) { - console.error(err); - const error = err as any; - const text = - error?.response?.data?.message ?? `Failed to ${isDisabled ? "enable" : "disable"} key`; - - createNotification({ - text, - type: "error" - }); - } + createNotification({ + text: `Key successfully ${isDisabled ? "enabled" : "disabled"}`, + type: "success" + }); }; const cannotEditKey = permission.cannot( diff --git a/frontend/src/pages/kms/OverviewPage/components/CmekVerifyModal.tsx b/frontend/src/pages/kms/OverviewPage/components/CmekVerifyModal.tsx index 5c9eac072..d8203e373 100644 --- a/frontend/src/pages/kms/OverviewPage/components/CmekVerifyModal.tsx +++ b/frontend/src/pages/kms/OverviewPage/components/CmekVerifyModal.tsx @@ -69,25 +69,17 @@ const VerifyForm = ({ cmek }: FormProps) => { }); const handleVerifyData = async (formData: FormData) => { - try { - const result = await cmekVerify.mutateAsync({ ...formData, keyId: cmek.id }); + const result = await cmekVerify.mutateAsync({ ...formData, keyId: cmek.id }); - if (result.signatureValid) { - createNotification({ - text: "Successfully verified signature", - type: "success" - }); - } else { - createNotification({ - title: "Signature Verification Failed", - text: "The signature is invalid. The signature was not created using the same signing algorithm and key as the one used to sign the data. The data and signature may have been tampered with.", - type: "error" - }); - } - } catch (err) { - console.error(err); + if (result.signatureValid) { createNotification({ - text: "Failed to sign data", + text: "Successfully verified signature", + type: "success" + }); + } else { + createNotification({ + title: "Signature Verification Failed", + text: "The signature is invalid. The signature was not created using the same signing algorithm and key as the one used to sign the data. The data and signature may have been tampered with.", type: "error" }); } diff --git a/frontend/src/pages/kms/OverviewPage/components/DeleteCmekModal.tsx b/frontend/src/pages/kms/OverviewPage/components/DeleteCmekModal.tsx index 4c5528c39..62389d1ba 100644 --- a/frontend/src/pages/kms/OverviewPage/components/DeleteCmekModal.tsx +++ b/frontend/src/pages/kms/OverviewPage/components/DeleteCmekModal.tsx @@ -16,28 +16,17 @@ export const DeleteCmekModal = ({ isOpen, onOpenChange, cmek }: Props) => { const { id: keyId, projectId, name } = cmek; const handleDeleteCmek = async () => { - try { - await deleteCmek.mutateAsync({ - keyId, - projectId - }); + await deleteCmek.mutateAsync({ + keyId, + projectId + }); - createNotification({ - text: "Key successfully deleted", - type: "success" - }); + createNotification({ + text: "Key successfully deleted", + type: "success" + }); - onOpenChange(false); - } catch (err) { - console.error(err); - const error = err as any; - const text = error?.response?.data?.message ?? "Failed to delete key"; - - createNotification({ - text, - type: "error" - }); - } + onOpenChange(false); }; return ( diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgGroupsTab/components/OrgGroupsSection/OrgGroupModal.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgGroupsTab/components/OrgGroupsSection/OrgGroupModal.tsx index 908be4935..4b6ea0858 100644 --- a/frontend/src/pages/organization/AccessManagementPage/components/OrgGroupsTab/components/OrgGroupsSection/OrgGroupModal.tsx +++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgGroupsTab/components/OrgGroupsSection/OrgGroupModal.tsx @@ -74,43 +74,36 @@ export const OrgGroupModal = ({ popUp, handlePopUpClose, handlePopUpToggle }: Pr }, [popUp?.group?.data, roles]); const onGroupModalSubmit = async ({ name, slug, role }: TGroupFormData) => { - try { - if (!currentOrg?.id) return; + if (!currentOrg?.id) return; - const group = popUp?.group?.data as { - groupId: string; - name: string; - slug: string; - }; + const group = popUp?.group?.data as { + groupId: string; + name: string; + slug: string; + }; - if (group) { - await updateMutateAsync({ - id: group.groupId, - name, - slug, - role: role.slug || undefined - }); - } else { - await createMutateAsync({ - name, - slug, - organizationId: currentOrg.id, - role: role.slug || undefined - }); - } - handlePopUpToggle("group", false); - reset(); - - createNotification({ - text: `Successfully ${popUp?.group?.data ? "updated" : "created"} group`, - type: "success" + if (group) { + await updateMutateAsync({ + id: group.groupId, + name, + slug, + role: role.slug || undefined }); - } catch { - createNotification({ - text: `Failed to ${popUp?.group?.data ? "updated" : "created"} group`, - type: "error" + } else { + await createMutateAsync({ + name, + slug, + organizationId: currentOrg.id, + role: role.slug || undefined }); } + handlePopUpToggle("group", false); + reset(); + + createNotification({ + text: `Successfully ${popUp?.group?.data ? "updated" : "created"} group`, + type: "success" + }); }; return ( diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgGroupsTab/components/OrgGroupsSection/OrgGroupsSection.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgGroupsTab/components/OrgGroupsSection/OrgGroupsSection.tsx index 88cbc17f0..1cf5407d1 100644 --- a/frontend/src/pages/organization/AccessManagementPage/components/OrgGroupsTab/components/OrgGroupsSection/OrgGroupsSection.tsx +++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgGroupsTab/components/OrgGroupsSection/OrgGroupsSection.tsx @@ -37,21 +37,13 @@ export const OrgGroupsSection = () => { }; const onDeleteGroupSubmit = async ({ name, groupId }: { name: string; groupId: string }) => { - try { - await deleteMutateAsync({ - id: groupId - }); - createNotification({ - text: `Successfully deleted the group named ${name}`, - type: "success" - }); - } catch (err) { - console.error(err); - createNotification({ - text: `Failed to delete the group named ${name}`, - type: "error" - }); - } + await deleteMutateAsync({ + id: groupId + }); + createNotification({ + text: `Successfully deleted the group named ${name}`, + type: "success" + }); handlePopUpClose("deleteGroup"); }; diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgGroupsTab/components/OrgGroupsSection/OrgGroupsTable.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgGroupsTab/components/OrgGroupsSection/OrgGroupsTable.tsx index 61119fce1..cc6d7c7aa 100644 --- a/frontend/src/pages/organization/AccessManagementPage/components/OrgGroupsTab/components/OrgGroupsSection/OrgGroupsTable.tsx +++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgGroupsTab/components/OrgGroupsSection/OrgGroupsTable.tsx @@ -79,23 +79,15 @@ export const OrgGroupsTable = ({ handlePopUpOpen }: Props) => { const { data: roles } = useGetOrgRoles(orgId); const handleChangeRole = async ({ id, role }: { id: string; role: string }) => { - try { - await updateMutateAsync({ - id, - role - }); + await updateMutateAsync({ + id, + role + }); - createNotification({ - text: "Successfully updated group role", - type: "success" - }); - } catch (err) { - console.error(err); - createNotification({ - text: "Failed to update group role", - type: "error" - }); - } + createNotification({ + text: "Successfully updated group role", + type: "success" + }); }; const { diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentitySection.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentitySection.tsx index 355dec803..b7ebfcdc4 100644 --- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentitySection.tsx +++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentitySection.tsx @@ -56,53 +56,31 @@ export const IdentitySection = withPermission( const isEnterprise = subscription?.slug === "enterprise"; const onDeleteIdentitySubmit = async (identityId: string) => { - try { - await deleteMutateAsync({ - identityId, - organizationId: orgId - }); + await deleteMutateAsync({ + identityId, + organizationId: orgId + }); - createNotification({ - text: "Successfully deleted identity", - type: "success" - }); + createNotification({ + text: "Successfully deleted identity", + type: "success" + }); - handlePopUpClose("deleteIdentity"); - } catch (err) { - console.error(err); - const error = err as any; - const text = error?.response?.data?.message ?? "Failed to delete identity"; - - createNotification({ - text, - type: "error" - }); - } + handlePopUpClose("deleteIdentity"); }; const onDeleteTemplateSubmit = async (templateId: string) => { - try { - await deleteTemplateMutateAsync({ - templateId, - organizationId: orgId - }); + await deleteTemplateMutateAsync({ + templateId, + organizationId: orgId + }); - createNotification({ - text: "Successfully deleted template", - type: "success" - }); + createNotification({ + text: "Successfully deleted template", + type: "success" + }); - handlePopUpClose("deleteTemplate"); - } catch (err) { - console.error(err); - const error = err as any; - const text = error?.response?.data?.message ?? "Failed to delete template"; - - createNotification({ - text, - type: "error" - }); - } + handlePopUpClose("deleteTemplate"); }; return ( diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgMembersTab/components/OrgMembersSection/OrgMembersSection.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgMembersTab/components/OrgMembersSection/OrgMembersSection.tsx index adb729d75..dc033f3fa 100644 --- a/frontend/src/pages/organization/AccessManagementPage/components/OrgMembersTab/components/OrgMembersSection/OrgMembersSection.tsx +++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgMembersTab/components/OrgMembersSection/OrgMembersSection.tsx @@ -85,46 +85,30 @@ export const OrgMembersSection = () => { }; const onDeactivateMemberSubmit = async (orgMembershipId: string) => { - try { - await updateOrgMembership({ - organizationId: orgId, - membershipId: orgMembershipId, - isActive: false - }); + await updateOrgMembership({ + organizationId: orgId, + membershipId: orgMembershipId, + isActive: false + }); - createNotification({ - text: "Successfully deactivated user in organization", - type: "success" - }); - } catch (err) { - console.error(err); - createNotification({ - text: "Failed to deactivate user in organization", - type: "error" - }); - } + createNotification({ + text: "Successfully deactivated user in organization", + type: "success" + }); handlePopUpClose("deactivateMember"); }; const onRemoveMemberSubmit = async (orgMembershipId: string) => { - try { - await deleteMutateAsync({ - orgId, - membershipId: orgMembershipId - }); + await deleteMutateAsync({ + orgId, + membershipId: orgMembershipId + }); - createNotification({ - text: "Successfully removed user from org", - type: "success" - }); - } catch (err) { - console.error(err); - createNotification({ - text: "Failed to remove user from the organization", - type: "error" - }); - } + createNotification({ + text: "Successfully removed user from org", + type: "success" + }); handlePopUpClose("removeMember"); }; @@ -132,27 +116,20 @@ export const OrgMembersSection = () => { const { data: members = [] } = useGetOrgUsers(orgId); const handleRemoveMembers = async (selectedMembers: OrgUser[]) => { - try { - await deleteBatchMutateAsync({ - orgId, - membershipIds: selectedMembers - .filter((member) => member.user.id !== userId) - .map((member) => member.id) - }); + await deleteBatchMutateAsync({ + orgId, + membershipIds: selectedMembers + .filter((member) => member.user.id !== userId) + .map((member) => member.id) + }); - createNotification({ - text: "Successfully removed users from organization", - type: "success" - }); + createNotification({ + text: "Successfully removed users from organization", + type: "success" + }); - setSelectedMemberIds([]); - handlePopUpClose("removeMembers"); - } catch { - createNotification({ - text: "Failed to remove users from the organization", - type: "error" - }); - } + setSelectedMemberIds([]); + handlePopUpClose("removeMembers"); }; return ( diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgMembersTab/components/OrgMembersSection/OrgMembersTable.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgMembersTab/components/OrgMembersSection/OrgMembersTable.tsx index 68a4e795a..fe71c207d 100644 --- a/frontend/src/pages/organization/AccessManagementPage/components/OrgMembersTab/components/OrgMembersSection/OrgMembersTable.tsx +++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgMembersTab/components/OrgMembersSection/OrgMembersTable.tsx @@ -127,35 +127,26 @@ export const OrgMembersTable = ({ const onRoleChange = async (membershipId: string, role: string) => { if (!currentOrg?.id) return; - try { - // TODO: replace hardcoding default role - const isCustomRole = !["admin", "member", "no-access"].includes(role); + // TODO: replace hardcoding default role + const isCustomRole = !["admin", "member", "no-access"].includes(role); - if (isCustomRole && subscription && !subscription?.rbac) { - handlePopUpOpen("upgradePlan", { - description: - "You can assign custom roles to members if you switch to Infisical's Pro plan." - }); - return; - } - - await updateOrgMembership({ - organizationId: currentOrg?.id, - membershipId, - role - }); - - createNotification({ - text: "Successfully updated user role", - type: "success" - }); - } catch (error) { - console.error(error); - createNotification({ - text: "Failed to update user role", - type: "error" + if (isCustomRole && subscription && !subscription?.rbac) { + handlePopUpOpen("upgradePlan", { + description: "You can assign custom roles to members if you switch to Infisical's Pro plan." }); + return; } + + await updateOrgMembership({ + organizationId: currentOrg?.id, + membershipId, + role + }); + + createNotification({ + text: "Successfully updated user role", + type: "success" + }); }; const onResendInvite = async (membershipId: string) => { @@ -174,12 +165,6 @@ export const OrgMembersTable = ({ text: "Successfully resent org invitation", type: "success" }); - } catch (err) { - console.error(err); - createNotification({ - text: "Failed to resend org invitation", - type: "error" - }); } finally { setResendInviteId(null); } diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgRoleTabSection/OrgRoleTable.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgRoleTabSection/OrgRoleTable.tsx index d6dae6ae2..36249967a 100644 --- a/frontend/src/pages/organization/AccessManagementPage/components/OrgRoleTabSection/OrgRoleTable.tsx +++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgRoleTabSection/OrgRoleTable.tsx @@ -86,17 +86,12 @@ export const OrgRoleTable = () => { const handleRoleDelete = async () => { const { id } = popUp?.deleteRole?.data as TOrgRole; - try { - await deleteRole({ - orgId, - id - }); - createNotification({ type: "success", text: "Successfully removed the role" }); - handlePopUpClose("deleteRole"); - } catch (err) { - console.log(err); - createNotification({ type: "error", text: "Failed to delete role" }); - } + await deleteRole({ + orgId, + id + }); + createNotification({ type: "success", text: "Successfully removed the role" }); + handlePopUpClose("deleteRole"); }; const handleSetRoleAsDefault = async (defaultMembershipRoleSlug: string) => { @@ -110,17 +105,12 @@ export const OrgRoleTable = () => { return; } - try { - await updateOrg({ - orgId, - defaultMembershipRoleSlug - }); - createNotification({ type: "success", text: "Successfully updated default membership role" }); - handlePopUpClose("deleteRole"); - } catch (err) { - console.log(err); - createNotification({ type: "error", text: "Failed to update default membership role" }); - } + await updateOrg({ + orgId, + defaultMembershipRoleSlug + }); + createNotification({ type: "success", text: "Successfully updated default membership role" }); + handlePopUpClose("deleteRole"); }; const { diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AppConnectionForm.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AppConnectionForm.tsx index c09a58960..9d7e3ab48 100644 --- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AppConnectionForm.tsx +++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AppConnectionForm.tsx @@ -73,24 +73,15 @@ const CreateForm = ({ app, onComplete, projectId }: CreateFormProps) => { "method" | "name" | "app" | "credentials" | "isPlatformManagedCredentials" > ) => { - try { - const connection = await createAppConnection.mutateAsync({ - ...formData, - projectId - }); - createNotification({ - text: `Successfully added ${appName} Connection`, - type: "success" - }); - onComplete(connection); - } catch (err: any) { - console.error(err); - createNotification({ - title: `Failed to add ${appName} Connection`, - text: err.message, - type: "error" - }); - } + const connection = await createAppConnection.mutateAsync({ + ...formData, + projectId + }); + createNotification({ + text: `Successfully added ${appName} Connection`, + type: "success" + }); + onComplete(connection); }; switch (app) { @@ -191,24 +182,15 @@ const UpdateForm = ({ appConnection, onComplete }: UpdateFormProps) => { "method" | "name" | "app" | "credentials" | "isPlatformManagedCredentials" > ) => { - try { - const connection = await updateAppConnection.mutateAsync({ - connectionId: appConnection.id, - ...formData - }); - createNotification({ - text: `Successfully updated ${appName} Connection`, - type: "success" - }); - onComplete(connection); - } catch (err: any) { - console.error(err); - createNotification({ - title: `Failed to update ${appName} Connection`, - text: err.message, - type: "error" - }); - } + const connection = await updateAppConnection.mutateAsync({ + connectionId: appConnection.id, + ...formData + }); + createNotification({ + text: `Successfully updated ${appName} Connection`, + type: "success" + }); + onComplete(connection); }; switch (appConnection.app) { diff --git a/frontend/src/pages/organization/GroupDetailsByIDPage/components/GroupCreateUpdateModal.tsx b/frontend/src/pages/organization/GroupDetailsByIDPage/components/GroupCreateUpdateModal.tsx index e4364e874..bc6e3fab5 100644 --- a/frontend/src/pages/organization/GroupDetailsByIDPage/components/GroupCreateUpdateModal.tsx +++ b/frontend/src/pages/organization/GroupDetailsByIDPage/components/GroupCreateUpdateModal.tsx @@ -77,43 +77,36 @@ export const GroupCreateUpdateModal = ({ popUp, handlePopUpClose, handlePopUpTog }, [popUp?.groupCreateUpdate?.data, roles]); const onGroupModalSubmit = async ({ name, slug, role }: TGroupFormData) => { - try { - if (!currentOrg?.id) return; + if (!currentOrg?.id) return; - const group = popUp?.groupCreateUpdate?.data as { - groupId: string; - name: string; - slug: string; - }; + const group = popUp?.groupCreateUpdate?.data as { + groupId: string; + name: string; + slug: string; + }; - if (group) { - await updateMutateAsync({ - id: group.groupId, - name, - slug, - role: role.slug || undefined - }); - } else { - await createMutateAsync({ - name, - slug, - organizationId: currentOrg.id, - role: role.slug || undefined - }); - } - handlePopUpToggle("groupCreateUpdate", false); - reset(); - - createNotification({ - text: `Successfully ${popUp?.groupCreateUpdate?.data ? "updated" : "created"} group`, - type: "success" + if (group) { + await updateMutateAsync({ + id: group.groupId, + name, + slug, + role: role.slug || undefined }); - } catch { - createNotification({ - text: `Failed to ${popUp?.groupCreateUpdate?.data ? "updated" : "created"} group`, - type: "error" + } else { + await createMutateAsync({ + name, + slug, + organizationId: currentOrg.id, + role: role.slug || undefined }); } + handlePopUpToggle("groupCreateUpdate", false); + reset(); + + createNotification({ + text: `Successfully ${popUp?.groupCreateUpdate?.data ? "updated" : "created"} group`, + type: "success" + }); }; return ( diff --git a/frontend/src/pages/organization/IdentityDetailsByIDPage/IdentityDetailsByIDPage.tsx b/frontend/src/pages/organization/IdentityDetailsByIDPage/IdentityDetailsByIDPage.tsx index f3bd05eeb..c2e7bbe57 100644 --- a/frontend/src/pages/organization/IdentityDetailsByIDPage/IdentityDetailsByIDPage.tsx +++ b/frontend/src/pages/organization/IdentityDetailsByIDPage/IdentityDetailsByIDPage.tsx @@ -44,34 +44,23 @@ const Page = () => { ] as const); const onDeleteIdentitySubmit = async (id: string) => { - try { - await deleteIdentity({ - identityId: id, - organizationId: orgId - }); + await deleteIdentity({ + identityId: id, + organizationId: orgId + }); - createNotification({ - text: "Successfully deleted identity", - type: "success" - }); + createNotification({ + text: "Successfully deleted identity", + type: "success" + }); - handlePopUpClose("deleteIdentity"); - navigate({ - to: "/organization/access-management", - search: { - selectedTab: OrgAccessControlTabSections.Identities - } - }); - } catch (err) { - console.error(err); - const error = err as any; - const text = error?.response?.data?.message ?? "Failed to delete identity"; - - createNotification({ - text, - type: "error" - }); - } + handlePopUpClose("deleteIdentity"); + navigate({ + to: "/organization/access-management", + search: { + selectedTab: OrgAccessControlTabSections.Identities + } + }); }; return ( diff --git a/frontend/src/pages/organization/RoleByIDPage/components/RolePermissionsSection/RolePermissionsSection.tsx b/frontend/src/pages/organization/RoleByIDPage/components/RolePermissionsSection/RolePermissionsSection.tsx index 0d6b269a8..c25d11cb7 100644 --- a/frontend/src/pages/organization/RoleByIDPage/components/RolePermissionsSection/RolePermissionsSection.tsx +++ b/frontend/src/pages/organization/RoleByIDPage/components/RolePermissionsSection/RolePermissionsSection.tsx @@ -107,18 +107,13 @@ export const RolePermissionsSection = ({ roleId }: Props) => { const { mutateAsync: updateRole } = useUpdateOrgRole(); const onSubmit = async (el: TFormSchema) => { - try { - await updateRole({ - orgId, - id: roleId, - ...el, - permissions: formRolePermission2API(el.permissions) - }); - createNotification({ type: "success", text: "Successfully updated role" }); - } catch (err) { - console.log(err); - createNotification({ type: "error", text: "Failed to update role" }); - } + await updateRole({ + orgId, + id: roleId, + ...el, + permissions: formRolePermission2API(el.permissions) + }); + createNotification({ type: "success", text: "Successfully updated role" }); }; const isCustomRole = !["admin", "member", "no-access"].includes(role?.slug ?? ""); diff --git a/frontend/src/pages/organization/UserDetailsByIDPage/UserDetailsByIDPage.tsx b/frontend/src/pages/organization/UserDetailsByIDPage/UserDetailsByIDPage.tsx index 2d433bba8..8ddc27763 100644 --- a/frontend/src/pages/organization/UserDetailsByIDPage/UserDetailsByIDPage.tsx +++ b/frontend/src/pages/organization/UserDetailsByIDPage/UserDetailsByIDPage.tsx @@ -64,56 +64,38 @@ const Page = withPermission( ] as const); const onDeactivateMemberSubmit = async (orgMembershipId: string) => { - try { - await updateOrgMembership({ - organizationId: orgId, - membershipId: orgMembershipId, - isActive: false - }); + await updateOrgMembership({ + organizationId: orgId, + membershipId: orgMembershipId, + isActive: false + }); - createNotification({ - text: "Successfully deactivated user in organization", - type: "success" - }); - } catch (err) { - console.error(err); - createNotification({ - text: "Failed to deactivate user in organization", - type: "error" - }); - } + createNotification({ + text: "Successfully deactivated user in organization", + type: "success" + }); handlePopUpClose("deactivateMember"); }; const onRemoveMemberSubmit = async (orgMembershipId: string) => { - try { - await deleteOrgMembership({ - orgId, - membershipId: orgMembershipId - }); + await deleteOrgMembership({ + orgId, + membershipId: orgMembershipId + }); - createNotification({ - text: "Successfully removed user from org", - type: "success" - }); - - handlePopUpClose("removeMember"); - navigate({ - to: "/organization/access-management" as const, - search: { - selectedTab: OrgAccessControlTabSections.Member - } - }); - } catch (err) { - console.error(err); - createNotification({ - text: "Failed to remove user from the organization", - type: "error" - }); - } + createNotification({ + text: "Successfully removed user from org", + type: "success" + }); handlePopUpClose("removeMember"); + navigate({ + to: "/organization/access-management" as const, + search: { + selectedTab: OrgAccessControlTabSections.Member + } + }); }; return ( diff --git a/frontend/src/pages/organization/UserDetailsByIDPage/components/UserDetailsSection.tsx b/frontend/src/pages/organization/UserDetailsByIDPage/components/UserDetailsSection.tsx index bef98e875..d26163de0 100644 --- a/frontend/src/pages/organization/UserDetailsByIDPage/components/UserDetailsSection.tsx +++ b/frontend/src/pages/organization/UserDetailsByIDPage/components/UserDetailsSection.tsx @@ -46,26 +46,18 @@ export const UserDetailsSection = ({ membershipId, handlePopUpOpen }: Props) => const { mutateAsync: resendOrgMemberInvitation, isPending } = useResendOrgMemberInvitation(); const onResendInvite = async () => { - try { - const signupToken = await resendOrgMemberInvitation({ - membershipId - }); + const signupToken = await resendOrgMemberInvitation({ + membershipId + }); - if (signupToken) { - return; - } - - createNotification({ - text: "Successfully resent org invitation", - type: "success" - }); - } catch (err) { - console.error(err); - createNotification({ - text: "Failed to resend org invitation", - type: "error" - }); + if (signupToken) { + return; } + + createNotification({ + text: "Successfully resent org invitation", + type: "success" + }); }; const getStatus = (m: OrgUser) => { diff --git a/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/PamAccountForm.tsx b/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/PamAccountForm.tsx index b9599be2d..346195e11 100644 --- a/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/PamAccountForm.tsx +++ b/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/PamAccountForm.tsx @@ -38,27 +38,18 @@ const CreateForm = ({ const onSubmit = async ( formData: DiscriminativePick ) => { - try { - const account = await createPamAccount.mutateAsync({ - ...formData, - folderId, - resourceId, - resourceType, - projectId - }); - createNotification({ - text: "Successfully created account", - type: "success" - }); - onComplete(account); - } catch (err: any) { - console.error(err); - createNotification({ - title: "Failed to create account", - text: err.message, - type: "error" - }); - } + const account = await createPamAccount.mutateAsync({ + ...formData, + folderId, + resourceId, + resourceType, + projectId + }); + createNotification({ + text: "Successfully created account", + type: "success" + }); + onComplete(account); }; switch (resourceType) { @@ -85,25 +76,16 @@ const UpdateForm = ({ account, onComplete }: UpdateFormProps) => { const onSubmit = async ( formData: DiscriminativePick ) => { - try { - const updatedAccount = await updatePamAccount.mutateAsync({ - accountId: account.id, - resourceType: account.resource.resourceType, - ...formData - }); - createNotification({ - text: "Successfully updated account", - type: "success" - }); - onComplete(updatedAccount); - } catch (err: any) { - console.error(err); - createNotification({ - title: "Failed to update account", - text: err.message, - type: "error" - }); - } + const updatedAccount = await updatePamAccount.mutateAsync({ + accountId: account.id, + resourceType: account.resource.resourceType, + ...formData + }); + createNotification({ + text: "Successfully updated account", + type: "success" + }); + onComplete(updatedAccount); }; switch (account.resource.resourceType) { diff --git a/frontend/src/pages/pam/PamAccountsPage/components/PamAddFolderModal.tsx b/frontend/src/pages/pam/PamAccountsPage/components/PamAddFolderModal.tsx index 7b057a648..266a724cd 100644 --- a/frontend/src/pages/pam/PamAccountsPage/components/PamAddFolderModal.tsx +++ b/frontend/src/pages/pam/PamAccountsPage/components/PamAddFolderModal.tsx @@ -17,25 +17,16 @@ export const PamAddFolderModal = ({ isOpen, onOpenChange, projectId, currentFold console.log({ currentFolderId }); const onSubmit = async (formData: Pick) => { - try { - await createPamFolder.mutateAsync({ - ...formData, - parentId: currentFolderId, - projectId - }); - createNotification({ - text: "Successfully created folder", - type: "success" - }); - onOpenChange(false); - } catch (err: any) { - console.error(err); - createNotification({ - title: "Failed to create folder", - text: err.message, - type: "error" - }); - } + await createPamFolder.mutateAsync({ + ...formData, + parentId: currentFolderId, + projectId + }); + createNotification({ + text: "Successfully created folder", + type: "success" + }); + onOpenChange(false); }; return ( diff --git a/frontend/src/pages/pam/PamAccountsPage/components/PamDeleteAccountModal.tsx b/frontend/src/pages/pam/PamAccountsPage/components/PamDeleteAccountModal.tsx index 45ac03082..c094d3c53 100644 --- a/frontend/src/pages/pam/PamAccountsPage/components/PamDeleteAccountModal.tsx +++ b/frontend/src/pages/pam/PamAccountsPage/components/PamDeleteAccountModal.tsx @@ -20,25 +20,17 @@ export const PamDeleteAccountModal = ({ isOpen, onOpenChange, account }: Props) } = account; const handleDelete = async () => { - try { - await deletePamAccount.mutateAsync({ - accountId, - resourceType - }); + await deletePamAccount.mutateAsync({ + accountId, + resourceType + }); - createNotification({ - text: "Successfully deleted account", - type: "success" - }); + createNotification({ + text: "Successfully deleted account", + type: "success" + }); - onOpenChange(false); - } catch (err) { - console.error(err); - createNotification({ - text: "Failed to delete account", - type: "error" - }); - } + onOpenChange(false); }; return ( diff --git a/frontend/src/pages/pam/PamAccountsPage/components/PamDeleteFolderModal.tsx b/frontend/src/pages/pam/PamAccountsPage/components/PamDeleteFolderModal.tsx index f0e2476c2..d901d0ba0 100644 --- a/frontend/src/pages/pam/PamAccountsPage/components/PamDeleteFolderModal.tsx +++ b/frontend/src/pages/pam/PamAccountsPage/components/PamDeleteFolderModal.tsx @@ -16,24 +16,16 @@ export const PamDeleteFolderModal = ({ isOpen, onOpenChange, folder }: Props) => const { id: folderId, name } = folder; const handleDelete = async () => { - try { - await deletePamFolder.mutateAsync({ - folderId - }); + await deletePamFolder.mutateAsync({ + folderId + }); - createNotification({ - text: "Successfully deleted folder", - type: "success" - }); + createNotification({ + text: "Successfully deleted folder", + type: "success" + }); - onOpenChange(false); - } catch (err) { - console.error(err); - createNotification({ - text: "Failed to delete folder", - type: "error" - }); - } + onOpenChange(false); }; return ( diff --git a/frontend/src/pages/pam/PamAccountsPage/components/PamUpdateFolderModal.tsx b/frontend/src/pages/pam/PamAccountsPage/components/PamUpdateFolderModal.tsx index b4bcc46a4..4162ce25f 100644 --- a/frontend/src/pages/pam/PamAccountsPage/components/PamUpdateFolderModal.tsx +++ b/frontend/src/pages/pam/PamAccountsPage/components/PamUpdateFolderModal.tsx @@ -16,24 +16,15 @@ export const PamUpdateFolderModal = ({ isOpen, onOpenChange, folder }: Props) => if (!folder) return null; const onSubmit = async (formData: Pick) => { - try { - await updatePamFolder.mutateAsync({ - ...formData, - folderId: folder.id - }); - createNotification({ - text: "Successfully updated folder", - type: "success" - }); - onOpenChange(false); - } catch (err: any) { - console.error(err); - createNotification({ - title: "Failed to updated folder", - text: err.message, - type: "error" - }); - } + await updatePamFolder.mutateAsync({ + ...formData, + folderId: folder.id + }); + createNotification({ + text: "Successfully updated folder", + type: "success" + }); + onOpenChange(false); }; return ( diff --git a/frontend/src/pages/pam/PamResourcesPage/components/PamDeleteResourceModal.tsx b/frontend/src/pages/pam/PamResourcesPage/components/PamDeleteResourceModal.tsx index efda53466..7f0d2bd19 100644 --- a/frontend/src/pages/pam/PamResourcesPage/components/PamDeleteResourceModal.tsx +++ b/frontend/src/pages/pam/PamResourcesPage/components/PamDeleteResourceModal.tsx @@ -16,25 +16,17 @@ export const PamDeleteResourceModal = ({ isOpen, onOpenChange, resource }: Props const { id: resourceId, name, resourceType } = resource; const handleDelete = async () => { - try { - await deletePamResource.mutateAsync({ - resourceId, - resourceType - }); + await deletePamResource.mutateAsync({ + resourceId, + resourceType + }); - createNotification({ - text: `Successfully removed ${PAM_RESOURCE_TYPE_MAP[resourceType].name} resource`, - type: "success" - }); + createNotification({ + text: `Successfully removed ${PAM_RESOURCE_TYPE_MAP[resourceType].name} resource`, + type: "success" + }); - onOpenChange(false); - } catch (err) { - console.error(err); - createNotification({ - text: `Failed to remove ${PAM_RESOURCE_TYPE_MAP[resourceType].name} resource`, - type: "error" - }); - } + onOpenChange(false); }; return ( diff --git a/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/PamResourceForm.tsx b/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/PamResourceForm.tsx index 2bc54e7cd..3dd3aeec8 100644 --- a/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/PamResourceForm.tsx +++ b/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/PamResourceForm.tsx @@ -35,24 +35,15 @@ const CreateForm = ({ resourceType, onComplete, projectId }: CreateFormProps) => "name" | "resourceType" | "connectionDetails" | "gatewayId" > ) => { - try { - const resource = await createPamResource.mutateAsync({ - ...formData, - projectId - }); - createNotification({ - text: `Successfully created ${resourceName} resource`, - type: "success" - }); - onComplete(resource); - } catch (err: any) { - console.error(err); - createNotification({ - title: `Failed to create ${resourceName} resource`, - text: err.message, - type: "error" - }); - } + const resource = await createPamResource.mutateAsync({ + ...formData, + projectId + }); + createNotification({ + text: `Successfully created ${resourceName} resource`, + type: "success" + }); + onComplete(resource); }; switch (resourceType) { @@ -72,24 +63,15 @@ const UpdateForm = ({ resource, onComplete }: UpdateFormProps) => { const onSubmit = async ( formData: DiscriminativePick ) => { - try { - const updatedResource = await updatePamResource.mutateAsync({ - resourceId: resource.id, - ...formData - }); - createNotification({ - text: `Successfully updated ${resourceName} resource`, - type: "success" - }); - onComplete(updatedResource); - } catch (err: any) { - console.error(err); - createNotification({ - title: `Failed to update ${resourceName} resource`, - text: err.message, - type: "error" - }); - } + const updatedResource = await updatePamResource.mutateAsync({ + resourceId: resource.id, + ...formData + }); + createNotification({ + text: `Successfully updated ${resourceName} resource`, + type: "success" + }); + onComplete(updatedResource); }; switch (resource.resourceType) { diff --git a/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/MemberRoleForm/MemberRbacSection.tsx b/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/MemberRoleForm/MemberRbacSection.tsx index 291a5b58b..5be239042 100644 --- a/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/MemberRoleForm/MemberRbacSection.tsx +++ b/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/MemberRoleForm/MemberRbacSection.tsx @@ -127,17 +127,13 @@ export const MemberRbacSection = ({ projectMember, onOpenUpgradeModal }: Props) return; } - try { - await updateMembershipRole.mutateAsync({ - projectId, - membershipId: projectMember.id, - roles: sanitizedRoles - }); - createNotification({ text: "Successfully updated roles", type: "success" }); - roleForm.reset(undefined, { keepValues: true }); - } catch { - createNotification({ text: "Failed to update role", type: "error" }); - } + await updateMembershipRole.mutateAsync({ + projectId, + membershipId: projectMember.id, + roles: sanitizedRoles + }); + createNotification({ text: "Successfully updated roles", type: "success" }); + roleForm.reset(undefined, { keepValues: true }); }; if (isRolesLoading) diff --git a/frontend/src/pages/project/IdentityDetailsByIDPage/components/IdentityRoleDetailsSection/IdentityRoleModify.tsx b/frontend/src/pages/project/IdentityDetailsByIDPage/components/IdentityRoleDetailsSection/IdentityRoleModify.tsx index a74428e98..8bc451151 100644 --- a/frontend/src/pages/project/IdentityDetailsByIDPage/components/IdentityRoleDetailsSection/IdentityRoleModify.tsx +++ b/frontend/src/pages/project/IdentityDetailsByIDPage/components/IdentityRoleDetailsSection/IdentityRoleModify.tsx @@ -114,16 +114,12 @@ export const IdentityRoleModify = ({ identityProjectMembership }: Props) => { }; }); - try { - await updateIdentityWorkspaceRole.mutateAsync({ - projectId, - identityId: identityProjectMembership.identity.id, - roles: sanitizedRoles - }); - createNotification({ text: "Successfully updated roles", type: "success" }); - } catch { - createNotification({ text: "Failed to update roles", type: "error" }); - } + await updateIdentityWorkspaceRole.mutateAsync({ + projectId, + identityId: identityProjectMembership.identity.id, + roles: sanitizedRoles + }); + createNotification({ text: "Successfully updated roles", type: "success" }); }; if (isRolesLoading) diff --git a/frontend/src/pages/project/MemberDetailsByIDPage/components/MemberRoleDetailsSection/MemberRoleDetailsSection.tsx b/frontend/src/pages/project/MemberDetailsByIDPage/components/MemberRoleDetailsSection/MemberRoleDetailsSection.tsx index 703511c84..2654e237e 100644 --- a/frontend/src/pages/project/MemberDetailsByIDPage/components/MemberRoleDetailsSection/MemberRoleDetailsSection.tsx +++ b/frontend/src/pages/project/MemberDetailsByIDPage/components/MemberRoleDetailsSection/MemberRoleDetailsSection.tsx @@ -55,42 +55,37 @@ export const MemberRoleDetailsSection = ({ const handleRoleDelete = async () => { const { id } = popUp?.deleteRole?.data as TProjectRole; - try { - const updatedRoles = membershipDetails?.roles?.filter((el) => el.id !== id); - await updateUserWorkspaceRole({ - projectId, - roles: updatedRoles.map( - ({ - role, - customRoleSlug, - isTemporary, - temporaryMode, - temporaryRange, - temporaryAccessStartTime, - temporaryAccessEndTime - }) => ({ - role: role === "custom" ? customRoleSlug : role, - ...(isTemporary - ? { - isTemporary, - temporaryMode, - temporaryRange, - temporaryAccessStartTime, - temporaryAccessEndTime - } - : { - isTemporary - }) - }) - ), - membershipId: membershipDetails.id - }); - createNotification({ type: "success", text: "Successfully removed role" }); - handlePopUpClose("deleteRole"); - } catch (err) { - console.log(err); - createNotification({ type: "error", text: "Failed to delete role" }); - } + const updatedRoles = membershipDetails?.roles?.filter((el) => el.id !== id); + await updateUserWorkspaceRole({ + projectId, + roles: updatedRoles.map( + ({ + role, + customRoleSlug, + isTemporary, + temporaryMode, + temporaryRange, + temporaryAccessStartTime, + temporaryAccessEndTime + }) => ({ + role: role === "custom" ? customRoleSlug : role, + ...(isTemporary + ? { + isTemporary, + temporaryMode, + temporaryRange, + temporaryAccessStartTime, + temporaryAccessEndTime + } + : { + isTemporary + }) + }) + ), + membershipId: membershipDetails.id + }); + createNotification({ type: "success", text: "Successfully removed role" }); + handlePopUpClose("deleteRole"); }; return ( diff --git a/frontend/src/pages/project/MemberDetailsByIDPage/components/MemberRoleDetailsSection/MemberRoleModify.tsx b/frontend/src/pages/project/MemberDetailsByIDPage/components/MemberRoleDetailsSection/MemberRoleModify.tsx index 287ea3ad7..947424191 100644 --- a/frontend/src/pages/project/MemberDetailsByIDPage/components/MemberRoleDetailsSection/MemberRoleModify.tsx +++ b/frontend/src/pages/project/MemberDetailsByIDPage/components/MemberRoleDetailsSection/MemberRoleModify.tsx @@ -126,16 +126,12 @@ export const MemberRoleModify = ({ projectMember, onOpenUpgradeModal }: Props) = return; } - try { - await updateMembershipRole.mutateAsync({ - projectId, - membershipId: projectMember.id, - roles: sanitizedRoles - }); - createNotification({ text: "Successfully updated roles", type: "success" }); - } catch { - createNotification({ text: "Failed to update roles", type: "error" }); - } + await updateMembershipRole.mutateAsync({ + projectId, + membershipId: projectMember.id, + roles: sanitizedRoles + }); + createNotification({ text: "Successfully updated roles", type: "success" }); }; if (isRolesLoading) diff --git a/frontend/src/pages/secret-manager/SecretRotationPage/SecretRotationPage.tsx b/frontend/src/pages/secret-manager/SecretRotationPage/SecretRotationPage.tsx index 8efa28a63..b69d8fadb 100644 --- a/frontend/src/pages/secret-manager/SecretRotationPage/SecretRotationPage.tsx +++ b/frontend/src/pages/secret-manager/SecretRotationPage/SecretRotationPage.tsx @@ -95,42 +95,26 @@ const Page = () => { const handleDeleteRotation = async () => { const { id } = popUp.deleteRotation.data as { id: string }; - try { - await deleteSecretRotation({ - id, - workspaceId - }); - handlePopUpClose("deleteRotation"); - createNotification({ - type: "success", - text: "Successfully removed rotation" - }); - } catch (error) { - console.log(error); - createNotification({ - type: "error", - text: "Failed to remove rotation" - }); - } + await deleteSecretRotation({ + id, + workspaceId + }); + handlePopUpClose("deleteRotation"); + createNotification({ + type: "success", + text: "Successfully removed rotation" + }); }; const handleRestartRotation = async (id: string) => { - try { - await restartSecretRotation({ - id, - workspaceId - }); - createNotification({ - type: "success", - text: "Secret rotation initiated" - }); - } catch (error) { - console.log(error); - createNotification({ - type: "error", - text: "Failed to restart rotation" - }); - } + await restartSecretRotation({ + id, + workspaceId + }); + createNotification({ + type: "success", + text: "Secret rotation initiated" + }); }; const handleCreateRotation = (provider: TSecretRotationProviderTemplate) => { diff --git a/frontend/src/pages/secret-manager/SecretSyncDetailsByIDPage/components/SecretSyncActionTriggers.tsx b/frontend/src/pages/secret-manager/SecretSyncDetailsByIDPage/components/SecretSyncActionTriggers.tsx index 78cdf899e..ad82460eb 100644 --- a/frontend/src/pages/secret-manager/SecretSyncDetailsByIDPage/components/SecretSyncActionTriggers.tsx +++ b/frontend/src/pages/secret-manager/SecretSyncDetailsByIDPage/components/SecretSyncActionTriggers.tsx @@ -89,44 +89,30 @@ export const SecretSyncActionTriggers = ({ secretSync }: Props) => { const handleToggleEnableSync = async () => { const isAutoSyncEnabled = !secretSync.isAutoSyncEnabled; - try { - await updateSync.mutateAsync({ - syncId: secretSync.id, - destination: secretSync.destination, - isAutoSyncEnabled, - projectId: secretSync.projectId - }); + await updateSync.mutateAsync({ + syncId: secretSync.id, + destination: secretSync.destination, + isAutoSyncEnabled, + projectId: secretSync.projectId + }); - createNotification({ - text: `Successfully ${isAutoSyncEnabled ? "enabled" : "disabled"} auto-sync for ${destinationName} Sync`, - type: "success" - }); - } catch { - createNotification({ - text: `Failed to ${isAutoSyncEnabled ? "enable" : "disable"} auto-sync for ${destinationName} Sync`, - type: "error" - }); - } + createNotification({ + text: `Successfully ${isAutoSyncEnabled ? "enabled" : "disabled"} auto-sync for ${destinationName} Sync`, + type: "success" + }); }; const handleTriggerSync = async () => { - try { - await triggerSyncSecrets.mutateAsync({ - syncId: secretSync.id, - destination: secretSync.destination, - projectId: secretSync.projectId - }); + await triggerSyncSecrets.mutateAsync({ + syncId: secretSync.id, + destination: secretSync.destination, + projectId: secretSync.projectId + }); - createNotification({ - text: `Successfully triggered ${destinationName} Sync`, - type: "success" - }); - } catch { - createNotification({ - text: `Failed to trigger ${destinationName} Sync`, - type: "error" - }); - } + createNotification({ + text: `Successfully triggered ${destinationName} Sync`, + type: "success" + }); }; const permissionSubject = diff --git a/frontend/src/pages/secret-manager/SettingsPage/components/WorkflowIntegrationSection/components/SlackIntegrationForm.tsx b/frontend/src/pages/secret-manager/SettingsPage/components/WorkflowIntegrationSection/components/SlackIntegrationForm.tsx index bcc2d81b5..4af602e12 100644 --- a/frontend/src/pages/secret-manager/SettingsPage/components/WorkflowIntegrationSection/components/SlackIntegrationForm.tsx +++ b/frontend/src/pages/secret-manager/SettingsPage/components/WorkflowIntegrationSection/components/SlackIntegrationForm.tsx @@ -76,32 +76,25 @@ export const SlackIntegrationForm = ({ onClose }: Props) => { }); const handleIntegrationSave = async (data: TSlackConfigForm) => { - try { - if (!currentProject) { - return; - } - - await updateProjectSlackConfig({ - ...data, - projectId: currentProject.id, - integration: WorkflowIntegrationPlatform.SLACK, - integrationId: data.slackIntegrationId, - accessRequestChannels: data.accessRequestChannels.filter(Boolean).join(", "), - secretRequestChannels: data.secretRequestChannels.filter(Boolean).join(", ") - }); - - createNotification({ - type: "success", - text: "Successfully created slack integration" - }); - - onClose(); - } catch { - createNotification({ - type: "error", - text: "Failed to create slack integration" - }); + if (!currentProject) { + return; } + + await updateProjectSlackConfig({ + ...data, + projectId: currentProject.id, + integration: WorkflowIntegrationPlatform.SLACK, + integrationId: data.slackIntegrationId, + accessRequestChannels: data.accessRequestChannels.filter(Boolean).join(", "), + secretRequestChannels: data.secretRequestChannels.filter(Boolean).join(", ") + }); + + createNotification({ + type: "success", + text: "Successfully created slack integration" + }); + + onClose(); }; const secretRequestNotifState = watch("isSecretRequestNotificationEnabled"); diff --git a/frontend/src/pages/secret-scanning/SecretScanningDataSourceByIdPage/components/SecretScanningResourceRow.tsx b/frontend/src/pages/secret-scanning/SecretScanningDataSourceByIdPage/components/SecretScanningResourceRow.tsx index 740cf6d71..b2021bf5c 100644 --- a/frontend/src/pages/secret-scanning/SecretScanningDataSourceByIdPage/components/SecretScanningResourceRow.tsx +++ b/frontend/src/pages/secret-scanning/SecretScanningDataSourceByIdPage/components/SecretScanningResourceRow.tsx @@ -81,24 +81,17 @@ export const SecretScanningResourceRow = ({ resource, dataSource }: Props) => { const navigate = useNavigate(); const handleTriggerScan = async () => { - try { - await triggerDataSourceScan.mutateAsync({ - dataSourceId: dataSource.id, - type: dataSource.type, - projectId: dataSource.projectId, - resourceId: id - }); + await triggerDataSourceScan.mutateAsync({ + dataSourceId: dataSource.id, + type: dataSource.type, + projectId: dataSource.projectId, + resourceId: id + }); - createNotification({ - text: `Successfully triggered scan for ${name}`, - type: "success" - }); - } catch { - createNotification({ - text: `Failed to trigger scan for ${name}`, - type: "error" - }); - } + createNotification({ + text: `Successfully triggered scan for ${name}`, + type: "success" + }); }; const [isIdCopied, setIsIdCopied] = useToggle(false); diff --git a/frontend/src/pages/secret-scanning/SecretScanningFindingsPage/components/SecretScanningUpdateFindingModal.tsx b/frontend/src/pages/secret-scanning/SecretScanningFindingsPage/components/SecretScanningUpdateFindingModal.tsx index 484cbcf36..c4838673b 100644 --- a/frontend/src/pages/secret-scanning/SecretScanningFindingsPage/components/SecretScanningUpdateFindingModal.tsx +++ b/frontend/src/pages/secret-scanning/SecretScanningFindingsPage/components/SecretScanningUpdateFindingModal.tsx @@ -55,39 +55,32 @@ const Content = ({ findings, onComplete }: ContentProps) => { const onSubmit = async (data: FormType) => { if (!data.status) return; - try { - if (findings.length > 1) { - await updateMultipleFindings.mutateAsync( - findings.map((f) => ({ - ...data, - status: data.status!, - findingId: f.id, - projectId: f.projectId - })) - ); - } else { - await updateMultipleFindings.mutateAsync([ - { - ...data, - status: data.status, - findingId: findings[0].id, - projectId: findings[0].projectId - } - ]); - } - - createNotification({ - type: "success", - text: `Finding status${single ? "" : "es"} successfully updated` - }); - - onComplete(); - } catch { - createNotification({ - type: "error", - text: `Failed to update finding status${single ? "" : "es"}` - }); + if (findings.length > 1) { + await updateMultipleFindings.mutateAsync( + findings.map((f) => ({ + ...data, + status: data.status!, + findingId: f.id, + projectId: f.projectId + })) + ); + } else { + await updateMultipleFindings.mutateAsync([ + { + ...data, + status: data.status, + findingId: findings[0].id, + projectId: findings[0].projectId + } + ]); } + + createNotification({ + type: "success", + text: `Finding status${single ? "" : "es"} successfully updated` + }); + + onComplete(); }; return ( diff --git a/frontend/src/pages/secret-scanning/SettingsPage/components/ProjectScanningConfigTab/SecretScanningConfigForm.tsx b/frontend/src/pages/secret-scanning/SettingsPage/components/ProjectScanningConfigTab/SecretScanningConfigForm.tsx index c9df333c4..7ff36964d 100644 --- a/frontend/src/pages/secret-scanning/SettingsPage/components/ProjectScanningConfigTab/SecretScanningConfigForm.tsx +++ b/frontend/src/pages/secret-scanning/SettingsPage/components/ProjectScanningConfigTab/SecretScanningConfigForm.tsx @@ -38,22 +38,15 @@ export const SecretScanningConfigForm = ({ config }: Props) => { }); const onSubmit = async ({ content }: FormType) => { - try { - await updateConfig.mutateAsync({ - projectId: config.projectId, - content: content || null - }); + await updateConfig.mutateAsync({ + projectId: config.projectId, + content: content || null + }); - createNotification({ - type: "success", - text: "Configuration successfully updated" - }); - } catch { - createNotification({ - type: "error", - text: "Failed to update Configuration" - }); - } + createNotification({ + type: "success", + text: "Configuration successfully updated" + }); }; return ( diff --git a/frontend/src/pages/ssh/SshHostGroupDetailsByIDPage/components/SshHostGroupHostsSection.tsx b/frontend/src/pages/ssh/SshHostGroupDetailsByIDPage/components/SshHostGroupHostsSection.tsx index df6f2b723..9b482538c 100644 --- a/frontend/src/pages/ssh/SshHostGroupDetailsByIDPage/components/SshHostGroupHostsSection.tsx +++ b/frontend/src/pages/ssh/SshHostGroupDetailsByIDPage/components/SshHostGroupHostsSection.tsx @@ -41,25 +41,17 @@ export const SshHostGroupHostsSection = ({ sshHostGroupId }: Props) => { }; const onRemoveSshHostSubmit = async (sshHostId: string) => { - try { - await removeHostFromGroup({ - sshHostId, - sshHostGroupId - }); + await removeHostFromGroup({ + sshHostId, + sshHostGroupId + }); - await createNotification({ - text: "Successfully removed host from SSH group", - type: "success" - }); + createNotification({ + text: "Successfully removed host from SSH group", + type: "success" + }); - handlePopUpClose("removeHostFromSshHostGroup"); - } catch (err) { - console.error(err); - createNotification({ - text: "Failed to remove host from SSH group", - type: "error" - }); - } + handlePopUpClose("removeHostFromSshHostGroup"); }; return ( diff --git a/frontend/src/pages/ssh/SshHostsPage/components/SshHostGroupsSection.tsx b/frontend/src/pages/ssh/SshHostsPage/components/SshHostGroupsSection.tsx index 189a49686..e690480e1 100644 --- a/frontend/src/pages/ssh/SshHostsPage/components/SshHostGroupsSection.tsx +++ b/frontend/src/pages/ssh/SshHostsPage/components/SshHostGroupsSection.tsx @@ -35,22 +35,14 @@ export const SshHostGroupsSection = () => { }; const onRemoveSshHostGroupSubmit = async (sshHostGroupId: string) => { - try { - const hostGroup = await deleteSshHostGroup({ sshHostGroupId }); + const hostGroup = await deleteSshHostGroup({ sshHostGroupId }); - createNotification({ - text: `Successfully deleted SSH host group: ${hostGroup.name}`, - type: "success" - }); + createNotification({ + text: `Successfully deleted SSH host group: ${hostGroup.name}`, + type: "success" + }); - handlePopUpClose("deleteSshHostGroup"); - } catch (err) { - console.error(err); - createNotification({ - text: "Failed to delete SSH host group", - type: "error" - }); - } + handlePopUpClose("deleteSshHostGroup"); }; return ( diff --git a/frontend/src/pages/ssh/SshHostsPage/components/SshHostModal.tsx b/frontend/src/pages/ssh/SshHostsPage/components/SshHostModal.tsx index e9b0d870a..afcde908f 100644 --- a/frontend/src/pages/ssh/SshHostsPage/components/SshHostModal.tsx +++ b/frontend/src/pages/ssh/SshHostsPage/components/SshHostModal.tsx @@ -140,93 +140,84 @@ export const SshHostModal = ({ popUp, handlePopUpToggle }: Props) => { }, [sshHost]); const onFormSubmit = async ({ hostname, alias, userCertTtl, loginMappings }: FormData) => { - try { - if (!projectId) return; + if (!projectId) return; - // Filter out login mappings that are from host groups - const hostLoginMappings = loginMappings.filter( - (mapping) => mapping.source === LoginMappingSource.HOST - ); + // Filter out login mappings that are from host groups + const hostLoginMappings = loginMappings.filter( + (mapping) => mapping.source === LoginMappingSource.HOST + ); - // check if there is already a different host with the same hostname - const existingHostnames = - sshHosts?.filter((h) => h.id !== sshHost?.id).map((h) => h.hostname) || []; + // check if there is already a different host with the same hostname + const existingHostnames = + sshHosts?.filter((h) => h.id !== sshHost?.id).map((h) => h.hostname) || []; - if (existingHostnames.includes(hostname.trim())) { + if (existingHostnames.includes(hostname.trim())) { + createNotification({ + text: "A host with this hostname already exists.", + type: "error" + }); + return; + } + + const trimmedAlias = alias.trim(); + + // check if there is already a different host with the same non-null alias + if (trimmedAlias) { + const existingAliases = + sshHosts?.filter((h) => h.id !== sshHost?.id && h.alias !== null).map((h) => h.alias) || []; + + if (existingAliases.includes(trimmedAlias)) { createNotification({ - text: "A host with this hostname already exists.", + text: "A host with this alias already exists.", type: "error" }); return; } + } - const trimmedAlias = alias.trim(); + const transformedLoginMappings = hostLoginMappings.map(({ loginUser, allowedPrincipals }) => { + const usernames = allowedPrincipals + .filter((p) => p.type === "user" && p.value) + .map((p) => p.value); - // check if there is already a different host with the same non-null alias - if (trimmedAlias) { - const existingAliases = - sshHosts?.filter((h) => h.id !== sshHost?.id && h.alias !== null).map((h) => h.alias) || - []; + const groupNames = allowedPrincipals + .filter((p) => p.type === "group" && p.value) + .map((p) => p.value); - if (existingAliases.includes(trimmedAlias)) { - createNotification({ - text: "A host with this alias already exists.", - type: "error" - }); - return; + return { + loginUser, + allowedPrincipals: { + usernames, + groups: groupNames } - } + }; + }); - const transformedLoginMappings = hostLoginMappings.map(({ loginUser, allowedPrincipals }) => { - const usernames = allowedPrincipals - .filter((p) => p.type === "user" && p.value) - .map((p) => p.value); - - const groupNames = allowedPrincipals - .filter((p) => p.type === "group" && p.value) - .map((p) => p.value); - - return { - loginUser, - allowedPrincipals: { - usernames, - groups: groupNames - } - }; + if (sshHost) { + await updateMutateAsync({ + sshHostId: sshHost.id, + hostname, + alias: trimmedAlias, + userCertTtl, + loginMappings: transformedLoginMappings }); - - if (sshHost) { - await updateMutateAsync({ - sshHostId: sshHost.id, - hostname, - alias: trimmedAlias, - userCertTtl, - loginMappings: transformedLoginMappings - }); - } else { - await createMutateAsync({ - projectId, - hostname, - alias: trimmedAlias, - userCertTtl, - loginMappings: transformedLoginMappings - }); - } - - reset(); - handlePopUpToggle("sshHost", false); - - createNotification({ - text: `Successfully ${sshHost ? "updated" : "added"} SSH host`, - type: "success" - }); - } catch (err) { - console.error(err); - createNotification({ - text: `Failed to ${sshHost ? "update" : "add"} SSH host`, - type: "error" + } else { + await createMutateAsync({ + projectId, + hostname, + alias: trimmedAlias, + userCertTtl, + loginMappings: transformedLoginMappings }); } + + reset(); + handlePopUpToggle("sshHost", false); + + createNotification({ + text: `Successfully ${sshHost ? "updated" : "added"} SSH host`, + type: "success" + }); }; const toggleMapping = (index: number) => { From eba04e4278ba71814daee4b5c7631adebfbcc7b4 Mon Sep 17 00:00:00 2001 From: Victor Santos Date: Fri, 31 Oct 2025 19:23:32 -0300 Subject: [PATCH 04/28] refactor: simplify authentication form submission logic across multiple identity sections --- .../IdentityAliCloudAuthForm.tsx | 63 ++++---- .../IdentityAuthTemplateModal.tsx | 82 +++++------ .../IdentitySection/IdentityAwsAuthForm.tsx | 71 +++++---- .../IdentitySection/IdentityAzureAuthForm.tsx | 71 +++++---- .../IdentitySection/IdentityGcpAuthForm.tsx | 75 +++++----- .../IdentitySection/IdentityJwtAuthForm.tsx | 95 ++++++------ .../IdentityKubernetesAuthForm.tsx | 115 +++++++-------- .../IdentitySection/IdentityLdapAuthForm.tsx | 135 +++++++++--------- .../IdentitySection/IdentityLinkForm.tsx | 39 ++--- .../IdentitySection/IdentityModal.tsx | 123 +++++++--------- .../IdentitySection/IdentityOciAuthForm.tsx | 67 ++++----- .../IdentitySection/IdentityOidcAuthForm.tsx | 99 ++++++------- 12 files changed, 468 insertions(+), 567 deletions(-) diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAliCloudAuthForm.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAliCloudAuthForm.tsx index 4ddcf964e..7dc5d7f70 100644 --- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAliCloudAuthForm.tsx +++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAliCloudAuthForm.tsx @@ -137,45 +137,38 @@ export const IdentityAliCloudAuthForm = ({ accessTokenNumUsesLimit, accessTokenTrustedIps }: FormData) => { - try { - if (!identityId) return; + if (!identityId) return; - if (data) { - await updateMutateAsync({ - organizationId: orgId, - allowedArns, - identityId, - accessTokenTTL: Number(accessTokenTTL), - accessTokenMaxTTL: Number(accessTokenMaxTTL), - accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit), - accessTokenTrustedIps - }); - } else { - await addMutateAsync({ - organizationId: orgId, - identityId, - allowedArns, - accessTokenTTL: Number(accessTokenTTL), - accessTokenMaxTTL: Number(accessTokenMaxTTL), - accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit), - accessTokenTrustedIps - }); - } - - handlePopUpToggle("identityAuthMethod", false); - - createNotification({ - text: `Successfully ${isUpdate ? "updated" : "configured"} auth method`, - type: "success" + if (data) { + await updateMutateAsync({ + organizationId: orgId, + allowedArns, + identityId, + accessTokenTTL: Number(accessTokenTTL), + accessTokenMaxTTL: Number(accessTokenMaxTTL), + accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit), + accessTokenTrustedIps }); - - reset(); - } catch { - createNotification({ - text: `Failed to ${isUpdate ? "update" : "configure"} identity`, - type: "error" + } else { + await addMutateAsync({ + organizationId: orgId, + identityId, + allowedArns, + accessTokenTTL: Number(accessTokenTTL), + accessTokenMaxTTL: Number(accessTokenMaxTTL), + accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit), + accessTokenTrustedIps }); } + + handlePopUpToggle("identityAuthMethod", false); + + createNotification({ + text: `Successfully ${isUpdate ? "updated" : "configured"} auth method`, + type: "success" + }); + + reset(); }; return ( diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAuthTemplateModal.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAuthTemplateModal.tsx index 3bd423982..6db81f19e 100644 --- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAuthTemplateModal.tsx +++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAuthTemplateModal.tsx @@ -103,56 +103,44 @@ export const IdentityAuthTemplateModal = ({ popUp, handlePopUpToggle }: Props) = const selectedMethod = watch("method"); const onFormSubmit = async (data: FormData) => { - try { - if (isEdit && template) { - await updateTemplate({ - templateId: template.id, - organizationId: orgId, - name: data.name, - templateFields: { - url: data.url, - bindDN: data.bindDN, - bindPass: data.bindPass, - searchBase: data.searchBase, - ldapCaCertificate: data.ldapCaCertificate - } - }); - createNotification({ - text: "Successfully updated auth template", - type: "success" - }); - } else { - await createTemplate({ - organizationId: orgId, - name: data.name, - authMethod: data.method, - templateFields: { - url: data.url, - bindDN: data.bindDN, - bindPass: data.bindPass, - searchBase: data.searchBase, - ldapCaCertificate: data.ldapCaCertificate - } - }); - createNotification({ - text: "Successfully created auth template", - type: "success" - }); - } - - handlePopUpToggle(isEdit ? "editTemplate" : "createTemplate", false); - reset(); - } catch (err) { - console.error(err); - const error = err as any; - const text = - error?.response?.data?.message ?? `Failed to ${isEdit ? "update" : "create"} auth template`; - + if (isEdit && template) { + await updateTemplate({ + templateId: template.id, + organizationId: orgId, + name: data.name, + templateFields: { + url: data.url, + bindDN: data.bindDN, + bindPass: data.bindPass, + searchBase: data.searchBase, + ldapCaCertificate: data.ldapCaCertificate + } + }); createNotification({ - text, - type: "error" + text: "Successfully updated auth template", + type: "success" + }); + } else { + await createTemplate({ + organizationId: orgId, + name: data.name, + authMethod: data.method, + templateFields: { + url: data.url, + bindDN: data.bindDN, + bindPass: data.bindPass, + searchBase: data.searchBase, + ldapCaCertificate: data.ldapCaCertificate + } + }); + createNotification({ + text: "Successfully created auth template", + type: "success" }); } + + handlePopUpToggle(isEdit ? "editTemplate" : "createTemplate", false); + reset(); }; const handleClose = () => { diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAwsAuthForm.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAwsAuthForm.tsx index 7e3292c18..db1066731 100644 --- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAwsAuthForm.tsx +++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAwsAuthForm.tsx @@ -147,49 +147,42 @@ export const IdentityAwsAuthForm = ({ accessTokenNumUsesLimit, accessTokenTrustedIps }: FormData) => { - try { - if (!identityId) return; + if (!identityId) return; - if (data) { - await updateMutateAsync({ - organizationId: orgId, - stsEndpoint, - allowedPrincipalArns, - allowedAccountIds, - identityId, - accessTokenTTL: Number(accessTokenTTL), - accessTokenMaxTTL: Number(accessTokenMaxTTL), - accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit), - accessTokenTrustedIps - }); - } else { - await addMutateAsync({ - organizationId: orgId, - identityId, - stsEndpoint: stsEndpoint || "", - allowedPrincipalArns: allowedPrincipalArns || "", - allowedAccountIds: allowedAccountIds || "", - accessTokenTTL: Number(accessTokenTTL), - accessTokenMaxTTL: Number(accessTokenMaxTTL), - accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit), - accessTokenTrustedIps - }); - } - - handlePopUpToggle("identityAuthMethod", false); - - createNotification({ - text: `Successfully ${isUpdate ? "updated" : "configured"} auth method`, - type: "success" + if (data) { + await updateMutateAsync({ + organizationId: orgId, + stsEndpoint, + allowedPrincipalArns, + allowedAccountIds, + identityId, + accessTokenTTL: Number(accessTokenTTL), + accessTokenMaxTTL: Number(accessTokenMaxTTL), + accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit), + accessTokenTrustedIps }); - - reset(); - } catch { - createNotification({ - text: `Failed to ${isUpdate ? "update" : "configure"} identity`, - type: "error" + } else { + await addMutateAsync({ + organizationId: orgId, + identityId, + stsEndpoint: stsEndpoint || "", + allowedPrincipalArns: allowedPrincipalArns || "", + allowedAccountIds: allowedAccountIds || "", + accessTokenTTL: Number(accessTokenTTL), + accessTokenMaxTTL: Number(accessTokenMaxTTL), + accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit), + accessTokenTrustedIps }); } + + handlePopUpToggle("identityAuthMethod", false); + + createNotification({ + text: `Successfully ${isUpdate ? "updated" : "configured"} auth method`, + type: "success" + }); + + reset(); }; return ( diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAzureAuthForm.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAzureAuthForm.tsx index 518d97e7b..86f22c27e 100644 --- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAzureAuthForm.tsx +++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAzureAuthForm.tsx @@ -143,49 +143,42 @@ export const IdentityAzureAuthForm = ({ accessTokenNumUsesLimit, accessTokenTrustedIps }: FormData) => { - try { - if (!identityId) return; + if (!identityId) return; - if (data) { - await updateMutateAsync({ - organizationId: orgId, - identityId, - tenantId, - resource, - allowedServicePrincipalIds, - accessTokenTTL: Number(accessTokenTTL), - accessTokenMaxTTL: Number(accessTokenMaxTTL), - accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit), - accessTokenTrustedIps - }); - } else { - await addMutateAsync({ - organizationId: orgId, - identityId, - tenantId: tenantId || "", - resource: resource || "", - allowedServicePrincipalIds: allowedServicePrincipalIds || "", - accessTokenTTL: Number(accessTokenTTL), - accessTokenMaxTTL: Number(accessTokenMaxTTL), - accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit), - accessTokenTrustedIps - }); - } - - handlePopUpToggle("identityAuthMethod", false); - - createNotification({ - text: `Successfully ${isUpdate ? "updated" : "configured"} auth method`, - type: "success" + if (data) { + await updateMutateAsync({ + organizationId: orgId, + identityId, + tenantId, + resource, + allowedServicePrincipalIds, + accessTokenTTL: Number(accessTokenTTL), + accessTokenMaxTTL: Number(accessTokenMaxTTL), + accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit), + accessTokenTrustedIps }); - - reset(); - } catch { - createNotification({ - text: `Failed to ${isUpdate ? "update" : "configure"} identity`, - type: "error" + } else { + await addMutateAsync({ + organizationId: orgId, + identityId, + tenantId: tenantId || "", + resource: resource || "", + allowedServicePrincipalIds: allowedServicePrincipalIds || "", + accessTokenTTL: Number(accessTokenTTL), + accessTokenMaxTTL: Number(accessTokenMaxTTL), + accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit), + accessTokenTrustedIps }); } + + handlePopUpToggle("identityAuthMethod", false); + + createNotification({ + text: `Successfully ${isUpdate ? "updated" : "configured"} auth method`, + type: "success" + }); + + reset(); }; return ( diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityGcpAuthForm.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityGcpAuthForm.tsx index 7175e8b62..4d6ea63b2 100644 --- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityGcpAuthForm.tsx +++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityGcpAuthForm.tsx @@ -152,51 +152,44 @@ export const IdentityGcpAuthForm = ({ accessTokenNumUsesLimit, accessTokenTrustedIps }: FormData) => { - try { - if (!identityId) return; + if (!identityId) return; - if (data) { - await updateMutateAsync({ - identityId, - organizationId: orgId, - type, - allowedServiceAccounts, - allowedProjects, - allowedZones, - accessTokenTTL: Number(accessTokenTTL), - accessTokenMaxTTL: Number(accessTokenMaxTTL), - accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit), - accessTokenTrustedIps - }); - } else { - await addMutateAsync({ - identityId, - organizationId: orgId, - type, - allowedServiceAccounts: allowedServiceAccounts || "", - allowedProjects: allowedProjects || "", - allowedZones: allowedZones || "", - accessTokenTTL: Number(accessTokenTTL), - accessTokenMaxTTL: Number(accessTokenMaxTTL), - accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit), - accessTokenTrustedIps - }); - } - - handlePopUpToggle("identityAuthMethod", false); - - createNotification({ - text: `Successfully ${isUpdate ? "updated" : "configured"} auth method`, - type: "success" + if (data) { + await updateMutateAsync({ + identityId, + organizationId: orgId, + type, + allowedServiceAccounts, + allowedProjects, + allowedZones, + accessTokenTTL: Number(accessTokenTTL), + accessTokenMaxTTL: Number(accessTokenMaxTTL), + accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit), + accessTokenTrustedIps }); - - reset(); - } catch { - createNotification({ - text: `Failed to ${isUpdate ? "update" : "configure"} identity`, - type: "error" + } else { + await addMutateAsync({ + identityId, + organizationId: orgId, + type, + allowedServiceAccounts: allowedServiceAccounts || "", + allowedProjects: allowedProjects || "", + allowedZones: allowedZones || "", + accessTokenTTL: Number(accessTokenTTL), + accessTokenMaxTTL: Number(accessTokenMaxTTL), + accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit), + accessTokenTrustedIps }); } + + handlePopUpToggle("identityAuthMethod", false); + + createNotification({ + text: `Successfully ${isUpdate ? "updated" : "configured"} auth method`, + type: "success" + }); + + reset(); }; return ( diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityJwtAuthForm.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityJwtAuthForm.tsx index f62045810..dfc079790 100644 --- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityJwtAuthForm.tsx +++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityJwtAuthForm.tsx @@ -217,61 +217,54 @@ export const IdentityJwtAuthForm = ({ boundClaims, boundSubject }: FormData) => { - try { - if (!identityId) { - return; - } + if (!identityId) { + return; + } - if (data) { - await updateMutateAsync({ - identityId, - organizationId: orgId, - configurationType, - jwksUrl, - jwksCaCert, - publicKeys: publicKeys?.map((field) => field.value).filter(Boolean), - boundIssuer, - boundAudiences, - boundClaims: Object.fromEntries(boundClaims.map((entry) => [entry.key, entry.value])), - boundSubject, - accessTokenTTL: Number(accessTokenTTL), - accessTokenMaxTTL: Number(accessTokenMaxTTL), - accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit), - accessTokenTrustedIps - }); - } else { - await addMutateAsync({ - identityId, - configurationType, - jwksUrl, - jwksCaCert, - publicKeys: publicKeys?.map((field) => field.value).filter(Boolean), - boundIssuer, - boundAudiences, - boundClaims: Object.fromEntries(boundClaims.map((entry) => [entry.key, entry.value])), - boundSubject, - organizationId: orgId, - accessTokenTTL: Number(accessTokenTTL), - accessTokenMaxTTL: Number(accessTokenMaxTTL), - accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit), - accessTokenTrustedIps - }); - } - - handlePopUpToggle("identityAuthMethod", false); - - createNotification({ - text: `Successfully ${isUpdate ? "updated" : "configured"} auth method`, - type: "success" + if (data) { + await updateMutateAsync({ + identityId, + organizationId: orgId, + configurationType, + jwksUrl, + jwksCaCert, + publicKeys: publicKeys?.map((field) => field.value).filter(Boolean), + boundIssuer, + boundAudiences, + boundClaims: Object.fromEntries(boundClaims.map((entry) => [entry.key, entry.value])), + boundSubject, + accessTokenTTL: Number(accessTokenTTL), + accessTokenMaxTTL: Number(accessTokenMaxTTL), + accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit), + accessTokenTrustedIps }); - - reset(); - } catch { - createNotification({ - text: `Failed to ${isUpdate ? "update" : "configure"} identity`, - type: "error" + } else { + await addMutateAsync({ + identityId, + configurationType, + jwksUrl, + jwksCaCert, + publicKeys: publicKeys?.map((field) => field.value).filter(Boolean), + boundIssuer, + boundAudiences, + boundClaims: Object.fromEntries(boundClaims.map((entry) => [entry.key, entry.value])), + boundSubject, + organizationId: orgId, + accessTokenTTL: Number(accessTokenTTL), + accessTokenMaxTTL: Number(accessTokenMaxTTL), + accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit), + accessTokenTrustedIps }); } + + handlePopUpToggle("identityAuthMethod", false); + + createNotification({ + text: `Successfully ${isUpdate ? "updated" : "configured"} auth method`, + type: "success" + }); + + reset(); }; return ( diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityKubernetesAuthForm.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityKubernetesAuthForm.tsx index 9b8624990..7fedf4a99 100644 --- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityKubernetesAuthForm.tsx +++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityKubernetesAuthForm.tsx @@ -311,71 +311,64 @@ export const IdentityKubernetesAuthForm = ({ tokenReviewMode, accessTokenTrustedIps }: FormData) => { - try { - if (!identityId) return; + if (!identityId) return; - if (data) { - await updateMutateAsync({ - organizationId: orgId, - ...(tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Api - ? { - kubernetesHost: kubernetesHost || "" - } - : { - kubernetesHost: null - }), - tokenReviewerJwt: tokenReviewerJwt || null, - allowedNames, - allowedNamespaces, - allowedAudience, - caCert, - identityId, - gatewayId: gatewayId || null, - tokenReviewMode, - accessTokenTTL: Number(accessTokenTTL), - accessTokenMaxTTL: Number(accessTokenMaxTTL), - accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit), - accessTokenTrustedIps - }); - } else { - await addMutateAsync({ - organizationId: orgId, - identityId, - ...(tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Api - ? { - kubernetesHost: kubernetesHost || "" - } - : { - kubernetesHost: null - }), - tokenReviewerJwt: tokenReviewerJwt || undefined, - allowedNames: allowedNames || "", - allowedNamespaces: allowedNamespaces || "", - allowedAudience: allowedAudience || "", - gatewayId: gatewayId || null, - caCert: caCert || "", - tokenReviewMode, - accessTokenTTL: Number(accessTokenTTL), - accessTokenMaxTTL: Number(accessTokenMaxTTL), - accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit), - accessTokenTrustedIps - }); - } - - handlePopUpToggle("identityAuthMethod", false); - - createNotification({ - text: `Successfully ${isUpdate ? "updated" : "configured"} auth method`, - type: "success" + if (data) { + await updateMutateAsync({ + organizationId: orgId, + ...(tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Api + ? { + kubernetesHost: kubernetesHost || "" + } + : { + kubernetesHost: null + }), + tokenReviewerJwt: tokenReviewerJwt || null, + allowedNames, + allowedNamespaces, + allowedAudience, + caCert, + identityId, + gatewayId: gatewayId || null, + tokenReviewMode, + accessTokenTTL: Number(accessTokenTTL), + accessTokenMaxTTL: Number(accessTokenMaxTTL), + accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit), + accessTokenTrustedIps }); - - reset(); - } catch { - createNotification({ - text: `Failed to ${isUpdate ? "update" : "configure"} identity`, - type: "error" + } else { + await addMutateAsync({ + organizationId: orgId, + identityId, + ...(tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Api + ? { + kubernetesHost: kubernetesHost || "" + } + : { + kubernetesHost: null + }), + tokenReviewerJwt: tokenReviewerJwt || undefined, + allowedNames: allowedNames || "", + allowedNamespaces: allowedNamespaces || "", + allowedAudience: allowedAudience || "", + gatewayId: gatewayId || null, + caCert: caCert || "", + tokenReviewMode, + accessTokenTTL: Number(accessTokenTTL), + accessTokenMaxTTL: Number(accessTokenMaxTTL), + accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit), + accessTokenTrustedIps }); } + + handlePopUpToggle("identityAuthMethod", false); + + createNotification({ + text: `Successfully ${isUpdate ? "updated" : "configured"} auth method`, + type: "success" + }); + + reset(); }; const tokenReviewMode = watch("tokenReviewMode"); diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityLdapAuthForm.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityLdapAuthForm.tsx index b2096fa06..44b3a32de 100644 --- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityLdapAuthForm.tsx +++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityLdapAuthForm.tsx @@ -316,83 +316,76 @@ export const IdentityLdapAuthForm = ({ }, [subscription, handlePopUpOpen, handlePopUpToggle]); const onFormSubmit = async (formData: FormData) => { - try { - if (!identityId) return; + if (!identityId) return; - const { - scope: submissionScope, - templateId: submissionTemplateId, - url: submissionUrl, - bindDN: submissionBindDN, - bindPass: submissionBindPass, - searchBase: submissionSearchBase, - searchFilter, - ldapCaCertificate, - allowedFields, - accessTokenTTL, - accessTokenMaxTTL, - accessTokenNumUsesLimit, - accessTokenTrustedIps, - lockoutEnabled, - lockoutThreshold, - lockoutDurationValue, - lockoutDurationUnit, - lockoutCounterResetValue, - lockoutCounterResetUnit - } = formData; + const { + scope: submissionScope, + templateId: submissionTemplateId, + url: submissionUrl, + bindDN: submissionBindDN, + bindPass: submissionBindPass, + searchBase: submissionSearchBase, + searchFilter, + ldapCaCertificate, + allowedFields, + accessTokenTTL, + accessTokenMaxTTL, + accessTokenNumUsesLimit, + accessTokenTrustedIps, + lockoutEnabled, + lockoutThreshold, + lockoutDurationValue, + lockoutDurationUnit, + lockoutCounterResetValue, + lockoutCounterResetUnit + } = formData; - const lockoutDurationSeconds = ms(`${lockoutDurationValue}${lockoutDurationUnit}`) / 1000; - const lockoutCounterResetSeconds = - ms(`${lockoutCounterResetValue}${lockoutCounterResetUnit}`) / 1000; + const lockoutDurationSeconds = ms(`${lockoutDurationValue}${lockoutDurationUnit}`) / 1000; + const lockoutCounterResetSeconds = + ms(`${lockoutCounterResetValue}${lockoutCounterResetUnit}`) / 1000; - const basePayload = { - organizationId: orgId, - identityId, - searchFilter, - ldapCaCertificate, - allowedFields, - accessTokenTTL: Number(accessTokenTTL), - accessTokenMaxTTL: Number(accessTokenMaxTTL), - accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit), - accessTokenTrustedIps, - lockoutEnabled, - lockoutThreshold: Number(lockoutThreshold), - lockoutDurationSeconds, - lockoutCounterResetSeconds - }; + const basePayload = { + organizationId: orgId, + identityId, + searchFilter, + ldapCaCertificate, + allowedFields, + accessTokenTTL: Number(accessTokenTTL), + accessTokenMaxTTL: Number(accessTokenMaxTTL), + accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit), + accessTokenTrustedIps, + lockoutEnabled, + lockoutThreshold: Number(lockoutThreshold), + lockoutDurationSeconds, + lockoutCounterResetSeconds + }; - // Add scope-specific fields - const payload = - submissionScope === "template" - ? { ...basePayload, templateId: submissionTemplateId } - : { - ...basePayload, - url: submissionUrl, - bindDN: submissionBindDN, - bindPass: submissionBindPass, - searchBase: submissionSearchBase - }; + // Add scope-specific fields + const payload = + submissionScope === "template" + ? { ...basePayload, templateId: submissionTemplateId } + : { + ...basePayload, + url: submissionUrl, + bindDN: submissionBindDN, + bindPass: submissionBindPass, + searchBase: submissionSearchBase + }; - if (data) { - await updateMutateAsync(payload); - } else { - await addMutateAsync(payload); - } - - handlePopUpToggle("identityAuthMethod", false); - - createNotification({ - text: `Successfully ${isUpdate ? "updated" : "configured"} auth method`, - type: "success" - }); - - reset(); - } catch { - createNotification({ - text: `Failed to ${isUpdate ? "update" : "configure"} identity`, - type: "error" - }); + if (data) { + await updateMutateAsync(payload); + } else { + await addMutateAsync(payload); } + + handlePopUpToggle("identityAuthMethod", false); + + createNotification({ + text: `Successfully ${isUpdate ? "updated" : "configured"} auth method`, + type: "success" + }); + + reset(); }; return ( diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityLinkForm.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityLinkForm.tsx index b0977437b..545aea5aa 100644 --- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityLinkForm.tsx +++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityLinkForm.tsx @@ -42,31 +42,20 @@ export const IdentityLinkForm = ({ onClose }: Props) => { }); const onFormSubmit = async ({ identity, role }: FormData) => { - try { - await createMutateAsync({ - identityId: identity.id, - roles: [{ role: role.slug, isTemporary: false }] - }); - createNotification({ - text: "Successfully linked identity", - type: "success" - }); - navigate({ - to: "/organization/identities/$identityId", - params: { - identityId: identity.id - } - }); - } catch (err) { - console.error(err); - const error = err as any; - const text = error?.response?.data?.message ?? "Failed to link identity"; - - createNotification({ - text, - type: "error" - }); - } + await createMutateAsync({ + identityId: identity.id, + roles: [{ role: role.slug, isTemporary: false }] + }); + createNotification({ + text: "Successfully linked identity", + type: "success" + }); + navigate({ + to: "/organization/identities/$identityId", + params: { + identityId: identity.id + } + }); }; return ( diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityModal.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityModal.tsx index dacbba428..09e779fa9 100644 --- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityModal.tsx +++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityModal.tsx @@ -108,81 +108,68 @@ export const IdentityModal = ({ popUp, handlePopUpToggle }: Props) => { }, [popUp?.identity?.data, roles]); const onFormSubmit = async ({ name, role, metadata, hasDeleteProtection }: FormData) => { - try { - const identity = popUp?.identity?.data as { - identityId: string; - name: string; - role: string; - hasDeleteProtection: boolean; - orgId: string; - }; + const identity = popUp?.identity?.data as { + identityId: string; + name: string; + role: string; + hasDeleteProtection: boolean; + orgId: string; + }; - if (identity) { - // update + if (identity) { + // update - await updateMutateAsync({ - identityId: identity.identityId, - name, - role: role.slug || undefined, - hasDeleteProtection, - organizationId: orgId, - metadata - }); - - handlePopUpToggle("identity", false); - } else { - // create - - const { id: createdId } = await createMutateAsync({ - name, - role: role.slug || undefined, - hasDeleteProtection, - organizationId: orgId, - metadata - }); - - await addMutateAsync({ - organizationId: orgId, - identityId: createdId, - clientSecretTrustedIps: [{ ipAddress: "0.0.0.0/0" }, { ipAddress: "::/0" }], - accessTokenTrustedIps: [{ ipAddress: "0.0.0.0/0" }, { ipAddress: "::/0" }], - accessTokenTTL: 2592000, - accessTokenMaxTTL: 2592000, - accessTokenNumUsesLimit: 0, - accessTokenPeriod: 0, - lockoutEnabled: true, - lockoutThreshold: 3, - lockoutDurationSeconds: 300, - lockoutCounterResetSeconds: 30 - }); - - handlePopUpToggle("identity", false); - navigate({ - to: "/organization/identities/$identityId", - params: { - identityId: createdId - } - }); - } - - createNotification({ - text: `Successfully ${popUp?.identity?.data ? "updated" : "created"} identity`, - type: "success" + await updateMutateAsync({ + identityId: identity.identityId, + name, + role: role.slug || undefined, + hasDeleteProtection, + organizationId: orgId, + metadata }); - reset(); - } catch (err) { - console.error(err); - const error = err as any; - const text = - error?.response?.data?.message ?? - `Failed to ${popUp?.identity?.data ? "update" : "create"} identity`; + handlePopUpToggle("identity", false); + } else { + // create - createNotification({ - text, - type: "error" + const { id: createdId } = await createMutateAsync({ + name, + role: role.slug || undefined, + hasDeleteProtection, + organizationId: orgId, + metadata + }); + + await addMutateAsync({ + organizationId: orgId, + identityId: createdId, + clientSecretTrustedIps: [{ ipAddress: "0.0.0.0/0" }, { ipAddress: "::/0" }], + accessTokenTrustedIps: [{ ipAddress: "0.0.0.0/0" }, { ipAddress: "::/0" }], + accessTokenTTL: 2592000, + accessTokenMaxTTL: 2592000, + accessTokenNumUsesLimit: 0, + accessTokenPeriod: 0, + lockoutEnabled: true, + lockoutThreshold: 3, + lockoutDurationSeconds: 300, + lockoutCounterResetSeconds: 30 + }); + + handlePopUpToggle("identity", false); + navigate({ + to: "/organization/identities/$identityId", + params: { + identityId: createdId + } }); } + + createNotification({ + text: `Successfully ${popUp?.identity?.data ? "updated" : "created"} identity`, + type: "success" + }); + + reset(); }; return ( diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityOciAuthForm.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityOciAuthForm.tsx index 5e33c71bb..ffbde6f7a 100644 --- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityOciAuthForm.tsx +++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityOciAuthForm.tsx @@ -149,47 +149,40 @@ export const IdentityOciAuthForm = ({ accessTokenNumUsesLimit, accessTokenTrustedIps }: FormData) => { - try { - if (!identityId) return; + if (!identityId) return; - if (data) { - await updateMutateAsync({ - organizationId: orgId, - tenancyOcid, - allowedUsernames, - identityId, - accessTokenTTL: Number(accessTokenTTL), - accessTokenMaxTTL: Number(accessTokenMaxTTL), - accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit), - accessTokenTrustedIps - }); - } else { - await addMutateAsync({ - organizationId: orgId, - identityId, - tenancyOcid, - allowedUsernames: allowedUsernames || undefined, - accessTokenTTL: Number(accessTokenTTL), - accessTokenMaxTTL: Number(accessTokenMaxTTL), - accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit), - accessTokenTrustedIps - }); - } - - handlePopUpToggle("identityAuthMethod", false); - - createNotification({ - text: `Successfully ${isUpdate ? "updated" : "configured"} auth method`, - type: "success" + if (data) { + await updateMutateAsync({ + organizationId: orgId, + tenancyOcid, + allowedUsernames, + identityId, + accessTokenTTL: Number(accessTokenTTL), + accessTokenMaxTTL: Number(accessTokenMaxTTL), + accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit), + accessTokenTrustedIps }); - - reset(); - } catch { - createNotification({ - text: `Failed to ${isUpdate ? "update" : "configure"} identity`, - type: "error" + } else { + await addMutateAsync({ + organizationId: orgId, + identityId, + tenancyOcid, + allowedUsernames: allowedUsernames || undefined, + accessTokenTTL: Number(accessTokenTTL), + accessTokenMaxTTL: Number(accessTokenMaxTTL), + accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit), + accessTokenTrustedIps }); } + + handlePopUpToggle("identityAuthMethod", false); + + createNotification({ + text: `Successfully ${isUpdate ? "updated" : "configured"} auth method`, + type: "success" + }); + + reset(); }; return ( diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityOidcAuthForm.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityOidcAuthForm.tsx index 15fbc4b72..0ada2e663 100644 --- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityOidcAuthForm.tsx +++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityOidcAuthForm.tsx @@ -201,63 +201,56 @@ export const IdentityOidcAuthForm = ({ claimMetadataMapping, boundSubject }: FormData) => { - try { - if (!identityId) { - return; - } + if (!identityId) { + return; + } - if (data) { - await updateMutateAsync({ - identityId, - organizationId: orgId, - oidcDiscoveryUrl, - caCert, - boundIssuer, - boundAudiences, - boundClaims: Object.fromEntries(boundClaims.map((entry) => [entry.key, entry.value])), - claimMetadataMapping: claimMetadataMapping - ? Object.fromEntries(claimMetadataMapping.map((entry) => [entry.key, entry.value])) - : undefined, - boundSubject, - accessTokenTTL: Number(accessTokenTTL), - accessTokenMaxTTL: Number(accessTokenMaxTTL), - accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit), - accessTokenTrustedIps - }); - } else { - await addMutateAsync({ - identityId, - oidcDiscoveryUrl, - caCert, - boundIssuer, - boundAudiences, - boundClaims: Object.fromEntries(boundClaims.map((entry) => [entry.key, entry.value])), - claimMetadataMapping: claimMetadataMapping - ? Object.fromEntries(claimMetadataMapping.map((entry) => [entry.key, entry.value])) - : undefined, - boundSubject, - organizationId: orgId, - accessTokenTTL: Number(accessTokenTTL), - accessTokenMaxTTL: Number(accessTokenMaxTTL), - accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit), - accessTokenTrustedIps - }); - } - - handlePopUpToggle("identityAuthMethod", false); - - createNotification({ - text: `Successfully ${isUpdate ? "updated" : "configured"} auth method`, - type: "success" + if (data) { + await updateMutateAsync({ + identityId, + organizationId: orgId, + oidcDiscoveryUrl, + caCert, + boundIssuer, + boundAudiences, + boundClaims: Object.fromEntries(boundClaims.map((entry) => [entry.key, entry.value])), + claimMetadataMapping: claimMetadataMapping + ? Object.fromEntries(claimMetadataMapping.map((entry) => [entry.key, entry.value])) + : undefined, + boundSubject, + accessTokenTTL: Number(accessTokenTTL), + accessTokenMaxTTL: Number(accessTokenMaxTTL), + accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit), + accessTokenTrustedIps }); - - reset(); - } catch { - createNotification({ - text: `Failed to ${isUpdate ? "update" : "configure"} identity`, - type: "error" + } else { + await addMutateAsync({ + identityId, + oidcDiscoveryUrl, + caCert, + boundIssuer, + boundAudiences, + boundClaims: Object.fromEntries(boundClaims.map((entry) => [entry.key, entry.value])), + claimMetadataMapping: claimMetadataMapping + ? Object.fromEntries(claimMetadataMapping.map((entry) => [entry.key, entry.value])) + : undefined, + boundSubject, + organizationId: orgId, + accessTokenTTL: Number(accessTokenTTL), + accessTokenMaxTTL: Number(accessTokenMaxTTL), + accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit), + accessTokenTrustedIps }); } + + handlePopUpToggle("identityAuthMethod", false); + + createNotification({ + text: `Successfully ${isUpdate ? "updated" : "configured"} auth method`, + type: "success" + }); + + reset(); }; return ( From 19ba7a28922431dd76e166933e46f011594fe662 Mon Sep 17 00:00:00 2001 From: Scott Wilson Date: Fri, 31 Oct 2025 16:17:46 -0700 Subject: [PATCH 05/28] fix: update audit log clear filters to apply to subsequent filter settings --- .../AuditLogsPage/components/LogsFilter.tsx | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/frontend/src/pages/organization/AuditLogsPage/components/LogsFilter.tsx b/frontend/src/pages/organization/AuditLogsPage/components/LogsFilter.tsx index 72561b90d..8e0124fb5 100644 --- a/frontend/src/pages/organization/AuditLogsPage/components/LogsFilter.tsx +++ b/frontend/src/pages/organization/AuditLogsPage/components/LogsFilter.tsx @@ -165,7 +165,7 @@ export const LogsFilter = ({ presets, setFilter, filter, project }: Props) => { { - resetField("eventType"); + setValue("eventType", [], { shouldDirty: true }); }} > { { - resetField("userAgentType"); + setValue("userAgentType", undefined, { shouldDirty: true }); }} > { { - resetField("project"); - resetField("environment"); - setValue("secretPath", ""); - setValue("secretKey", ""); + setValue("project", null, { shouldDirty: true }); + setValue("environment", undefined, { shouldDirty: true }); + setValue("secretPath", "", { shouldDirty: true }); + setValue("secretKey", "", { shouldDirty: true }); }} > { } className={twMerge(!selectedProject && "opacity-50")} onClear={() => { - resetField("environment"); + setValue("environment", undefined, { shouldDirty: true }); }} > { } className={twMerge(!selectedProject && "opacity-50")} onClear={() => { - setValue("secretPath", ""); + setValue("secretPath", "", { shouldDirty: true }); }} > { className={twMerge(!selectedProject && "opacity-50")} label="Secret Key" onClear={() => { - setValue("secretKey", ""); + setValue("secretKey", "", { shouldDirty: true }); }} > Date: Sat, 1 Nov 2025 03:21:22 -0400 Subject: [PATCH 06/28] Fix focus ring & trim logs --- .../components/PamSessionLogsSection.tsx | 55 ++++++++++++++++++- 1 file changed, 52 insertions(+), 3 deletions(-) diff --git a/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionLogsSection.tsx b/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionLogsSection.tsx index 5f06a64e2..66d2fad8d 100644 --- a/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionLogsSection.tsx +++ b/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionLogsSection.tsx @@ -4,6 +4,52 @@ import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { TPamSession } from "@app/hooks/api/pam"; +const formatLogContent = (text: string | null | undefined): string => { + if (!text) return ""; + + let lines = text.split("\n"); + + // Find the first and last non-empty lines to trim vertical padding + let firstLineIndex = -1; + for (let i = 0; i < lines.length; i += 1) { + if (lines[i].trim() !== "") { + firstLineIndex = i; + break; + } + } + + if (firstLineIndex === -1) { + return ""; + } + + let lastLineIndex = -1; + for (let i = lines.length - 1; i >= 0; i -= 1) { + if (lines[i].trim() !== "") { + lastLineIndex = i; + break; + } + } + + lines = lines.slice(firstLineIndex, lastLineIndex + 1); + + // Determine the minimum indentation of non-empty lines + const indentations = lines + .filter((line) => line.trim() !== "") + .map((line) => { + const match = line.match(/^\s*/); + return match ? match[0].length : 0; + }); + + const minIndentation = Math.min(...indentations); + + // Remove the common indentation from all lines + if (minIndentation > 0) { + lines = lines.map((line) => line.substring(minIndentation)); + } + + return lines.join("\n"); +}; + type Props = { session: TPamSession; }; @@ -32,11 +78,14 @@ export const PamSessionLogsSection = ({ session }: Props) => { {session.commandLogs.length > 0 ? ( session.commandLogs.map((log) => { const isExpanded = expandedLogTimestamps.has(log.timestamp); + const formattedInput = formatLogContent(log.input); + const formattedOutput = formatLogContent(log.output); + return ( From 0425a085feea885bd1b2b2572dd21f6b57c98d2d Mon Sep 17 00:00:00 2001 From: x032205 Date: Sat, 1 Nov 2025 03:43:30 -0400 Subject: [PATCH 07/28] Format row outputs into tables, and only allow one log expanded at a time --- .../components/PamSessionLogOutput.tsx | 95 +++++++++++++++++++ .../components/PamSessionLogsSection.tsx | 23 +++-- 2 files changed, 109 insertions(+), 9 deletions(-) create mode 100644 frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionLogOutput.tsx diff --git a/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionLogOutput.tsx b/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionLogOutput.tsx new file mode 100644 index 000000000..92d173f7e --- /dev/null +++ b/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionLogOutput.tsx @@ -0,0 +1,95 @@ +import { useState } from "react"; + +type TableLog = { + command?: string; + data_rows: Record[]; + total_rows?: number; +}; + +export const PamSessionLogOutput = ({ content }: { content: string }) => { + const [isRawView, setIsRawView] = useState(false); + + let parsedContent: TableLog | null = null; + try { + const parsed = JSON.parse(content); + if ( + parsed && + typeof parsed === "object" && + !Array.isArray(parsed) && + parsed.data_rows && + Array.isArray(parsed.data_rows) && + parsed.data_rows.length > 0 && + typeof parsed.data_rows[0] === "object" && + parsed.data_rows[0] !== null + ) { + parsedContent = parsed; + } + } catch (error) { + // Not a valid JSON or doesn't match structure, will render as plain text + } + + if (parsedContent) { + const headers = Object.keys(parsedContent.data_rows[0]); + return ( +
+ {isRawView ? ( +
{content}
+ ) : ( + <> + {parsedContent.command && ( +
{`> ${parsedContent.command}`}
+ )} +
+ + + + {headers.map((header) => ( + + ))} + + + + {parsedContent.data_rows.map((row, rowIndex) => ( + + {headers.map((header) => ( + + ))} + + ))} + +
+ {header.replace(/_/g, " ")} +
+ {String(row[header] ?? "")} +
+
+ + )} +
+ + + {parsedContent.total_rows !== undefined && ( +
+ Total rows: {parsedContent.total_rows} +
+ )} +
+
+ ); + } + + return
{content}
; +}; diff --git a/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionLogsSection.tsx b/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionLogsSection.tsx index 66d2fad8d..d620cf4cc 100644 --- a/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionLogsSection.tsx +++ b/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionLogsSection.tsx @@ -3,6 +3,7 @@ import { faChevronDown, faChevronRight } from "@fortawesome/free-solid-svg-icons import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { TPamSession } from "@app/hooks/api/pam"; +import { PamSessionLogOutput } from "./PamSessionLogOutput"; const formatLogContent = (text: string | null | undefined): string => { if (!text) return ""; @@ -59,13 +60,10 @@ export const PamSessionLogsSection = ({ session }: Props) => { const toggleExpand = (timestamp: string) => { setExpandedLogTimestamps((prev) => { - const newSet = new Set(prev); - if (newSet.has(timestamp)) { - newSet.delete(timestamp); - } else { - newSet.add(timestamp); + if (prev.has(timestamp)) { + return new Set(); } - return newSet; + return new Set([timestamp]); }); }; @@ -109,9 +107,16 @@ export const PamSessionLogsSection = ({ session }: Props) => { {isExpanded && log.output && ( -
- {formattedOutput} -
+ <> +
+
+ OUTPUT +
+
+
+ +
+ )} ); From 7d978443c7e0f02a6579b8ce4128b7742291055d Mon Sep 17 00:00:00 2001 From: x032205 Date: Sat, 1 Nov 2025 03:47:03 -0400 Subject: [PATCH 08/28] Move formatLogContent to a utils file --- .../components/PamSessionLogsSection.tsx | 50 +------------------ .../components/PamSessionLogsSection.utils.ts | 46 +++++++++++++++++ 2 files changed, 48 insertions(+), 48 deletions(-) create mode 100644 frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionLogsSection.utils.ts diff --git a/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionLogsSection.tsx b/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionLogsSection.tsx index d620cf4cc..9350f6cd9 100644 --- a/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionLogsSection.tsx +++ b/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionLogsSection.tsx @@ -4,52 +4,7 @@ import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { TPamSession } from "@app/hooks/api/pam"; import { PamSessionLogOutput } from "./PamSessionLogOutput"; - -const formatLogContent = (text: string | null | undefined): string => { - if (!text) return ""; - - let lines = text.split("\n"); - - // Find the first and last non-empty lines to trim vertical padding - let firstLineIndex = -1; - for (let i = 0; i < lines.length; i += 1) { - if (lines[i].trim() !== "") { - firstLineIndex = i; - break; - } - } - - if (firstLineIndex === -1) { - return ""; - } - - let lastLineIndex = -1; - for (let i = lines.length - 1; i >= 0; i -= 1) { - if (lines[i].trim() !== "") { - lastLineIndex = i; - break; - } - } - - lines = lines.slice(firstLineIndex, lastLineIndex + 1); - - // Determine the minimum indentation of non-empty lines - const indentations = lines - .filter((line) => line.trim() !== "") - .map((line) => { - const match = line.match(/^\s*/); - return match ? match[0].length : 0; - }); - - const minIndentation = Math.min(...indentations); - - // Remove the common indentation from all lines - if (minIndentation > 0) { - lines = lines.map((line) => line.substring(minIndentation)); - } - - return lines.join("\n"); -}; +import { formatLogContent } from "./PamSessionLogsSection.utils"; type Props = { session: TPamSession; @@ -77,7 +32,6 @@ export const PamSessionLogsSection = ({ session }: Props) => { session.commandLogs.map((log) => { const isExpanded = expandedLogTimestamps.has(log.timestamp); const formattedInput = formatLogContent(log.input); - const formattedOutput = formatLogContent(log.output); return ( ); }) From 050bc2d66ba480e80d35b9d3f9e7e54f03ba5ef2 Mon Sep 17 00:00:00 2001 From: Andre <120525481+x032205@users.noreply.github.com> Date: Sat, 1 Nov 2025 16:00:09 -0400 Subject: [PATCH 11/28] Update frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionLogsSection.utils.ts Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com> --- .../components/PamSessionLogsSection.utils.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionLogsSection.utils.ts b/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionLogsSection.utils.ts index 4696331fb..d76145655 100644 --- a/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionLogsSection.utils.ts +++ b/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionLogsSection.utils.ts @@ -35,7 +35,7 @@ export const formatLogContent = (text: string | null | undefined): string => { return match ? match[0].length : 0; }); - const minIndentation = Math.min(...indentations); + const minIndentation = indentations.length > 0 ? Math.min(...indentations) : 0; // Remove the common indentation from all lines if (minIndentation > 0) { From 0f461816cc4f0739c18fb6411fd41845e395e085 Mon Sep 17 00:00:00 2001 From: Piyush Gupta Date: Mon, 3 Nov 2025 18:16:01 +0530 Subject: [PATCH 12/28] chore: moves chef integration to ee --- .../chef-connection-router.ts | 11 +++++------ .../v1/secret-sync-routers/chef-sync-router.ts | 5 ++--- .../app-connections}/chef/chef-connection-enums.ts | 0 .../app-connections}/chef/chef-connection-fns.ts | 2 +- .../chef/chef-connection-schemas.ts | 0 .../chef/chef-connection-service.ts | 2 +- .../app-connections}/chef/chef-connection-types.ts | 4 ++-- .../services/app-connections}/chef/index.ts | 0 .../secret-sync/chef/chef-sync-constants.ts | 3 ++- .../services/secret-sync/chef/chef-sync-fns.ts | 2 +- .../services/secret-sync/chef/chef-sync-schemas.ts | 3 ++- .../services/secret-sync/chef/chef-sync-types.ts | 2 +- .../{ => ee}/services/secret-sync/chef/index.ts | 0 .../app-connection-router.ts | 2 +- .../routes/v1/app-connection-routers/index.ts | 2 +- .../server/routes/v1/secret-sync-routers/index.ts | 2 +- .../v1/secret-sync-routers/secret-sync-router.ts | 2 +- .../services/app-connection/app-connection-fns.ts | 8 ++++++-- .../services/app-connection/app-connection-maps.ts | 2 +- .../app-connection/app-connection-service.ts | 4 ++-- .../app-connection/app-connection-types.ts | 12 ++++++------ .../src/services/secret-sync/secret-sync-fns.ts | 14 ++++---------- .../src/services/secret-sync/secret-sync-maps.ts | 2 +- .../src/services/secret-sync/secret-sync-types.ts | 7 ++++++- frontend/src/helpers/appConnections.ts | 2 +- 25 files changed, 48 insertions(+), 45 deletions(-) rename backend/src/{server => ee}/routes/v1/app-connection-routers/chef-connection-router.ts (92%) rename backend/src/{server => ee}/routes/v1/secret-sync-routers/chef-sync-router.ts (72%) rename backend/src/{services/app-connection => ee/services/app-connections}/chef/chef-connection-enums.ts (100%) rename backend/src/{services/app-connection => ee/services/app-connections}/chef/chef-connection-fns.ts (98%) rename backend/src/{services/app-connection => ee/services/app-connections}/chef/chef-connection-schemas.ts (100%) rename backend/src/{services/app-connection => ee/services/app-connections}/chef/chef-connection-service.ts (93%) rename backend/src/{services/app-connection => ee/services/app-connections}/chef/chef-connection-types.ts (87%) rename backend/src/{services/app-connection => ee/services/app-connections}/chef/index.ts (100%) rename backend/src/{ => ee}/services/secret-sync/chef/chef-sync-constants.ts (89%) rename backend/src/{ => ee}/services/secret-sync/chef/chef-sync-fns.ts (99%) rename backend/src/{ => ee}/services/secret-sync/chef/chef-sync-schemas.ts (96%) rename backend/src/{ => ee}/services/secret-sync/chef/chef-sync-types.ts (92%) rename backend/src/{ => ee}/services/secret-sync/chef/index.ts (100%) diff --git a/backend/src/server/routes/v1/app-connection-routers/chef-connection-router.ts b/backend/src/ee/routes/v1/app-connection-routers/chef-connection-router.ts similarity index 92% rename from backend/src/server/routes/v1/app-connection-routers/chef-connection-router.ts rename to backend/src/ee/routes/v1/app-connection-routers/chef-connection-router.ts index 6bfd83391..2855d8b37 100644 --- a/backend/src/server/routes/v1/app-connection-routers/chef-connection-router.ts +++ b/backend/src/ee/routes/v1/app-connection-routers/chef-connection-router.ts @@ -1,17 +1,16 @@ import z from "zod"; -import { readLimit } from "@app/server/config/rateLimiter"; -import { verifyAuth } from "@app/server/plugins/auth/verify-auth"; -import { AppConnection } from "@app/services/app-connection/app-connection-enums"; import { CreateChefConnectionSchema, SanitizedChefConnectionSchema, UpdateChefConnectionSchema -} from "@app/services/app-connection/chef"; +} from "@app/ee/services/app-connections/chef"; +import { readLimit } from "@app/server/config/rateLimiter"; +import { verifyAuth } from "@app/server/plugins/auth/verify-auth"; +import { registerAppConnectionEndpoints } from "@app/server/routes/v1/app-connection-routers/app-connection-endpoints"; +import { AppConnection } from "@app/services/app-connection/app-connection-enums"; import { AuthMode } from "@app/services/auth/auth-type"; -import { registerAppConnectionEndpoints } from "./app-connection-endpoints"; - export const registerChefConnectionRouter = async (server: FastifyZodProvider) => { registerAppConnectionEndpoints({ app: AppConnection.Chef, diff --git a/backend/src/server/routes/v1/secret-sync-routers/chef-sync-router.ts b/backend/src/ee/routes/v1/secret-sync-routers/chef-sync-router.ts similarity index 72% rename from backend/src/server/routes/v1/secret-sync-routers/chef-sync-router.ts rename to backend/src/ee/routes/v1/secret-sync-routers/chef-sync-router.ts index 6972a9b70..3bdd5bce6 100644 --- a/backend/src/server/routes/v1/secret-sync-routers/chef-sync-router.ts +++ b/backend/src/ee/routes/v1/secret-sync-routers/chef-sync-router.ts @@ -1,8 +1,7 @@ -import { ChefSyncSchema, CreateChefSyncSchema, UpdateChefSyncSchema } from "@app/services/secret-sync/chef"; +import { ChefSyncSchema, CreateChefSyncSchema, UpdateChefSyncSchema } from "@app/ee/services/secret-sync/chef"; +import { registerSyncSecretsEndpoints } from "@app/server/routes/v1/secret-sync-routers/secret-sync-endpoints"; import { SecretSync } from "@app/services/secret-sync/secret-sync-enums"; -import { registerSyncSecretsEndpoints } from "./secret-sync-endpoints"; - export const registerChefSyncRouter = async (server: FastifyZodProvider) => registerSyncSecretsEndpoints({ destination: SecretSync.Chef, diff --git a/backend/src/services/app-connection/chef/chef-connection-enums.ts b/backend/src/ee/services/app-connections/chef/chef-connection-enums.ts similarity index 100% rename from backend/src/services/app-connection/chef/chef-connection-enums.ts rename to backend/src/ee/services/app-connections/chef/chef-connection-enums.ts diff --git a/backend/src/services/app-connection/chef/chef-connection-fns.ts b/backend/src/ee/services/app-connections/chef/chef-connection-fns.ts similarity index 98% rename from backend/src/services/app-connection/chef/chef-connection-fns.ts rename to backend/src/ee/services/app-connections/chef/chef-connection-fns.ts index 1b35628bc..31f5d0ee0 100644 --- a/backend/src/services/app-connection/chef/chef-connection-fns.ts +++ b/backend/src/ee/services/app-connections/chef/chef-connection-fns.ts @@ -8,7 +8,7 @@ import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator"; import { IntegrationUrls } from "@app/services/integration-auth/integration-list"; import { TChefDataBagItemContent } from "../../secret-sync/chef/chef-sync-types"; -import { AppConnection } from "../app-connection-enums"; +import { AppConnection } from "../../../../services/app-connection/app-connection-enums"; import { ChefConnectionMethod } from "./chef-connection-enums"; import { TChefConnection, diff --git a/backend/src/services/app-connection/chef/chef-connection-schemas.ts b/backend/src/ee/services/app-connections/chef/chef-connection-schemas.ts similarity index 100% rename from backend/src/services/app-connection/chef/chef-connection-schemas.ts rename to backend/src/ee/services/app-connections/chef/chef-connection-schemas.ts diff --git a/backend/src/services/app-connection/chef/chef-connection-service.ts b/backend/src/ee/services/app-connections/chef/chef-connection-service.ts similarity index 93% rename from backend/src/services/app-connection/chef/chef-connection-service.ts rename to backend/src/ee/services/app-connections/chef/chef-connection-service.ts index c989e7eaf..05969bf5d 100644 --- a/backend/src/services/app-connection/chef/chef-connection-service.ts +++ b/backend/src/ee/services/app-connections/chef/chef-connection-service.ts @@ -1,7 +1,7 @@ import { ForbiddenRequestError } from "@app/lib/errors"; import { OrgServiceActor } from "@app/lib/types"; -import { AppConnection } from "../app-connection-enums"; +import { AppConnection } from "../../../../services/app-connection/app-connection-enums"; import { listChefDataBagItems, listChefDataBags } from "./chef-connection-fns"; import { TChefConnection } from "./chef-connection-types"; diff --git a/backend/src/services/app-connection/chef/chef-connection-types.ts b/backend/src/ee/services/app-connections/chef/chef-connection-types.ts similarity index 87% rename from backend/src/services/app-connection/chef/chef-connection-types.ts rename to backend/src/ee/services/app-connections/chef/chef-connection-types.ts index a2da80d3d..096218951 100644 --- a/backend/src/services/app-connection/chef/chef-connection-types.ts +++ b/backend/src/ee/services/app-connections/chef/chef-connection-types.ts @@ -1,9 +1,9 @@ import z from "zod"; import { DiscriminativePick } from "@app/lib/types"; -import { TChefDataBagItemContent } from "@app/services/secret-sync/chef"; +import { TChefDataBagItemContent } from "@app/ee/services/secret-sync/chef"; -import { AppConnection } from "../app-connection-enums"; +import { AppConnection } from "../../../../services/app-connection/app-connection-enums"; import { ChefConnectionSchema, CreateChefConnectionSchema, diff --git a/backend/src/services/app-connection/chef/index.ts b/backend/src/ee/services/app-connections/chef/index.ts similarity index 100% rename from backend/src/services/app-connection/chef/index.ts rename to backend/src/ee/services/app-connections/chef/index.ts diff --git a/backend/src/services/secret-sync/chef/chef-sync-constants.ts b/backend/src/ee/services/secret-sync/chef/chef-sync-constants.ts similarity index 89% rename from backend/src/services/secret-sync/chef/chef-sync-constants.ts rename to backend/src/ee/services/secret-sync/chef/chef-sync-constants.ts index 567b25bbe..8bbf0e12a 100644 --- a/backend/src/services/secret-sync/chef/chef-sync-constants.ts +++ b/backend/src/ee/services/secret-sync/chef/chef-sync-constants.ts @@ -6,5 +6,6 @@ export const CHEF_SYNC_LIST_OPTION: TSecretSyncListItem = { name: "Chef", destination: SecretSync.Chef, connection: AppConnection.Chef, - canImportSecrets: true + canImportSecrets: true, + enterprise: true }; diff --git a/backend/src/services/secret-sync/chef/chef-sync-fns.ts b/backend/src/ee/services/secret-sync/chef/chef-sync-fns.ts similarity index 99% rename from backend/src/services/secret-sync/chef/chef-sync-fns.ts rename to backend/src/ee/services/secret-sync/chef/chef-sync-fns.ts index 7f32b398a..65a4fca9b 100644 --- a/backend/src/services/secret-sync/chef/chef-sync-fns.ts +++ b/backend/src/ee/services/secret-sync/chef/chef-sync-fns.ts @@ -1,4 +1,4 @@ -import { getChefDataBagItem, updateChefDataBagItem } from "@app/services/app-connection/chef"; +import { getChefDataBagItem, updateChefDataBagItem } from "@app/ee/services/app-connections/chef"; import { matchesSchema } from "@app/services/secret-sync/secret-sync-fns"; import { TSecretMap } from "@app/services/secret-sync/secret-sync-types"; diff --git a/backend/src/services/secret-sync/chef/chef-sync-schemas.ts b/backend/src/ee/services/secret-sync/chef/chef-sync-schemas.ts similarity index 96% rename from backend/src/services/secret-sync/chef/chef-sync-schemas.ts rename to backend/src/ee/services/secret-sync/chef/chef-sync-schemas.ts index c2e09011e..9702f97d3 100644 --- a/backend/src/services/secret-sync/chef/chef-sync-schemas.ts +++ b/backend/src/ee/services/secret-sync/chef/chef-sync-schemas.ts @@ -42,5 +42,6 @@ export const ChefSyncListItemSchema = z.object({ name: z.literal("Chef"), connection: z.literal(AppConnection.Chef), destination: z.literal(SecretSync.Chef), - canImportSecrets: z.literal(true) + canImportSecrets: z.literal(true), + enterprise: z.boolean() }); diff --git a/backend/src/services/secret-sync/chef/chef-sync-types.ts b/backend/src/ee/services/secret-sync/chef/chef-sync-types.ts similarity index 92% rename from backend/src/services/secret-sync/chef/chef-sync-types.ts rename to backend/src/ee/services/secret-sync/chef/chef-sync-types.ts index 464e0372d..0f70e7e1a 100644 --- a/backend/src/services/secret-sync/chef/chef-sync-types.ts +++ b/backend/src/ee/services/secret-sync/chef/chef-sync-types.ts @@ -1,6 +1,6 @@ import z from "zod"; -import { TChefConnection } from "@app/services/app-connection/chef"; +import { TChefConnection } from "@app/ee/services/app-connections/chef"; import { ChefSyncListItemSchema, ChefSyncSchema, CreateChefSyncSchema } from "./chef-sync-schemas"; diff --git a/backend/src/services/secret-sync/chef/index.ts b/backend/src/ee/services/secret-sync/chef/index.ts similarity index 100% rename from backend/src/services/secret-sync/chef/index.ts rename to backend/src/ee/services/secret-sync/chef/index.ts diff --git a/backend/src/server/routes/v1/app-connection-routers/app-connection-router.ts b/backend/src/server/routes/v1/app-connection-routers/app-connection-router.ts index 9a4d7f38b..5a3496750 100644 --- a/backend/src/server/routes/v1/app-connection-routers/app-connection-router.ts +++ b/backend/src/server/routes/v1/app-connection-routers/app-connection-router.ts @@ -1,6 +1,7 @@ import { z } from "zod"; import { ProjectType } from "@app/db/schemas"; +import { ChefConnectionListItemSchema, SanitizedChefConnectionSchema } from "@app/ee/services/app-connections/chef"; import { OCIConnectionListItemSchema, SanitizedOCIConnectionSchema } from "@app/ee/services/app-connections/oci"; import { OracleDBConnectionListItemSchema, @@ -48,7 +49,6 @@ import { ChecklyConnectionListItemSchema, SanitizedChecklyConnectionSchema } from "@app/services/app-connection/checkly"; -import { ChefConnectionListItemSchema, SanitizedChefConnectionSchema } from "@app/services/app-connection/chef"; import { CloudflareConnectionListItemSchema, SanitizedCloudflareConnectionSchema diff --git a/backend/src/server/routes/v1/app-connection-routers/index.ts b/backend/src/server/routes/v1/app-connection-routers/index.ts index 32e9efe4c..aa1d671b6 100644 --- a/backend/src/server/routes/v1/app-connection-routers/index.ts +++ b/backend/src/server/routes/v1/app-connection-routers/index.ts @@ -1,3 +1,4 @@ +import { registerChefConnectionRouter } from "@app/ee/routes/v1/app-connection-routers/chef-connection-router"; import { registerOCIConnectionRouter } from "@app/ee/routes/v1/app-connection-routers/oci-connection-router"; import { registerOracleDBConnectionRouter } from "@app/ee/routes/v1/app-connection-routers/oracledb-connection-router"; import { AppConnection } from "@app/services/app-connection/app-connection-enums"; @@ -13,7 +14,6 @@ import { registerAzureKeyVaultConnectionRouter } from "./azure-key-vault-connect import { registerBitbucketConnectionRouter } from "./bitbucket-connection-router"; import { registerCamundaConnectionRouter } from "./camunda-connection-router"; import { registerChecklyConnectionRouter } from "./checkly-connection-router"; -import { registerChefConnectionRouter } from "./chef-connection-router"; import { registerCloudflareConnectionRouter } from "./cloudflare-connection-router"; import { registerDatabricksConnectionRouter } from "./databricks-connection-router"; import { registerDigitalOceanConnectionRouter } from "./digital-ocean-connection-router"; diff --git a/backend/src/server/routes/v1/secret-sync-routers/index.ts b/backend/src/server/routes/v1/secret-sync-routers/index.ts index d305dc342..810e5b7fa 100644 --- a/backend/src/server/routes/v1/secret-sync-routers/index.ts +++ b/backend/src/server/routes/v1/secret-sync-routers/index.ts @@ -1,3 +1,4 @@ +import { registerChefSyncRouter } from "@app/ee/routes/v1/secret-sync-routers/chef-sync-router"; import { registerOCIVaultSyncRouter } from "@app/ee/routes/v1/secret-sync-routers/oci-vault-sync-router"; import { SecretSync } from "@app/services/secret-sync/secret-sync-enums"; @@ -10,7 +11,6 @@ import { registerAzureKeyVaultSyncRouter } from "./azure-key-vault-sync-router"; import { registerBitbucketSyncRouter } from "./bitbucket-sync-router"; import { registerCamundaSyncRouter } from "./camunda-sync-router"; import { registerChecklySyncRouter } from "./checkly-sync-router"; -import { registerChefSyncRouter } from "./chef-sync-router"; import { registerCloudflarePagesSyncRouter } from "./cloudflare-pages-sync-router"; import { registerCloudflareWorkersSyncRouter } from "./cloudflare-workers-sync-router"; import { registerDatabricksSyncRouter } from "./databricks-sync-router"; diff --git a/backend/src/server/routes/v1/secret-sync-routers/secret-sync-router.ts b/backend/src/server/routes/v1/secret-sync-routers/secret-sync-router.ts index 85adf12f1..0f394f8b2 100644 --- a/backend/src/server/routes/v1/secret-sync-routers/secret-sync-router.ts +++ b/backend/src/server/routes/v1/secret-sync-routers/secret-sync-router.ts @@ -24,7 +24,7 @@ import { AzureKeyVaultSyncListItemSchema, AzureKeyVaultSyncSchema } from "@app/s import { BitbucketSyncListItemSchema, BitbucketSyncSchema } from "@app/services/secret-sync/bitbucket"; import { CamundaSyncListItemSchema, CamundaSyncSchema } from "@app/services/secret-sync/camunda"; import { ChecklySyncListItemSchema, ChecklySyncSchema } from "@app/services/secret-sync/checkly/checkly-sync-schemas"; -import { ChefSyncListItemSchema, ChefSyncSchema } from "@app/services/secret-sync/chef"; +import { ChefSyncListItemSchema, ChefSyncSchema } from "@app/ee/services/secret-sync/chef"; import { CloudflarePagesSyncListItemSchema, CloudflarePagesSyncSchema diff --git a/backend/src/services/app-connection/app-connection-fns.ts b/backend/src/services/app-connection/app-connection-fns.ts index 3c511fd4d..87f22b031 100644 --- a/backend/src/services/app-connection/app-connection-fns.ts +++ b/backend/src/services/app-connection/app-connection-fns.ts @@ -1,5 +1,10 @@ import { ProjectType } from "@app/db/schemas"; import { TAppConnections } from "@app/db/schemas/app-connections"; +import { + ChefConnectionMethod, + getChefConnectionListItem, + validateChefConnectionCredentials +} from "@app/ee/services/app-connections/chef"; import { getOCIConnectionListItem, OCIConnectionMethod, @@ -68,7 +73,6 @@ import { } from "./bitbucket"; import { CamundaConnectionMethod, getCamundaConnectionListItem, validateCamundaConnectionCredentials } from "./camunda"; import { ChecklyConnectionMethod, getChecklyConnectionListItem, validateChecklyConnectionCredentials } from "./checkly"; -import { ChefConnectionMethod, getChefConnectionListItem, validateChefConnectionCredentials } from "./chef"; import { CloudflareConnectionMethod } from "./cloudflare/cloudflare-connection-enum"; import { getCloudflareConnectionListItem, @@ -292,7 +296,7 @@ export const decryptAppConnectionCredentials = async ({ cipherTextBlob: encryptedCredentials }); - return JSON.parse(decryptedPlainTextBlob.toString()) as TAppConnection["credentials"]; + return JSON.parse(decryptedPlainTextBlob.toString()); }; export const validateAppConnectionCredentials = async ( diff --git a/backend/src/services/app-connection/app-connection-maps.ts b/backend/src/services/app-connection/app-connection-maps.ts index 08ca0c681..5b8cc3fc1 100644 --- a/backend/src/services/app-connection/app-connection-maps.ts +++ b/backend/src/services/app-connection/app-connection-maps.ts @@ -86,6 +86,6 @@ export const APP_CONNECTION_PLAN_MAP: Record = { [SecretSync.Northflank]: SecretSyncPlanType.Regular, [SecretSync.Bitbucket]: SecretSyncPlanType.Regular, [SecretSync.LaravelForge]: SecretSyncPlanType.Regular, - [SecretSync.Chef]: SecretSyncPlanType.Regular + [SecretSync.Chef]: SecretSyncPlanType.Enterprise }; export const SECRET_SYNC_SKIP_FIELDS_MAP: Record = { diff --git a/backend/src/services/secret-sync/secret-sync-types.ts b/backend/src/services/secret-sync/secret-sync-types.ts index d6ef0b3fc..f1a87a9d2 100644 --- a/backend/src/services/secret-sync/secret-sync-types.ts +++ b/backend/src/services/secret-sync/secret-sync-types.ts @@ -1,6 +1,12 @@ import { Job } from "bullmq"; import { AuditLogInfo } from "@app/ee/services/audit-log/audit-log-types"; +import { + TChefSync, + TChefSyncInput, + TChefSyncListItem, + TChefSyncWithCredentials +} from "@app/ee/services/secret-sync/chef"; import { TOCIVaultSync, TOCIVaultSyncInput, @@ -21,7 +27,6 @@ import { TCamundaSyncListItem, TCamundaSyncWithCredentials } from "@app/services/secret-sync/camunda"; -import { TChefSync, TChefSyncInput, TChefSyncListItem, TChefSyncWithCredentials } from "@app/services/secret-sync/chef"; import { TDatabricksSync, TDatabricksSyncInput, diff --git a/frontend/src/helpers/appConnections.ts b/frontend/src/helpers/appConnections.ts index 1d0d7bec3..b27da2441 100644 --- a/frontend/src/helpers/appConnections.ts +++ b/frontend/src/helpers/appConnections.ts @@ -131,7 +131,7 @@ export const APP_CONNECTION_MAP: Record< image: "Laravel Forge.png", size: 65 }, - [AppConnection.Chef]: { name: "Chef", image: "Chef.png" } + [AppConnection.Chef]: { name: "Chef", image: "Chef.png", enterprise: true } }; export const getAppConnectionMethodDetails = (method: TAppConnection["method"]) => { From ebab43716ec2321fca9c76f90e773e35069aa392 Mon Sep 17 00:00:00 2001 From: Piyush Gupta Date: Mon, 3 Nov 2025 19:27:56 +0530 Subject: [PATCH 13/28] feat: Implement enterprise plan check for Chef connections and update documentation --- .../chef/chef-connection-fns.ts | 2 +- .../chef/chef-connection-service.ts | 22 +++++++++++++++++-- .../chef/chef-connection-types.ts | 2 +- .../secret-sync-routers/secret-sync-router.ts | 2 +- .../app-connection/app-connection-service.ts | 2 +- .../services/secret-sync/secret-sync-fns.ts | 12 +++++++--- docs/integrations/app-connections/chef.mdx | 8 +++++++ docs/integrations/secret-syncs/chef.mdx | 8 +++++++ 8 files changed, 49 insertions(+), 9 deletions(-) diff --git a/backend/src/ee/services/app-connections/chef/chef-connection-fns.ts b/backend/src/ee/services/app-connections/chef/chef-connection-fns.ts index 31f5d0ee0..6cef8373f 100644 --- a/backend/src/ee/services/app-connections/chef/chef-connection-fns.ts +++ b/backend/src/ee/services/app-connections/chef/chef-connection-fns.ts @@ -5,10 +5,10 @@ import { request } from "@app/lib/config/request"; import { BadRequestError } from "@app/lib/errors"; import { removeTrailingSlash } from "@app/lib/fn"; import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator"; +import { AppConnection } from "@app/services/app-connection/app-connection-enums"; import { IntegrationUrls } from "@app/services/integration-auth/integration-list"; import { TChefDataBagItemContent } from "../../secret-sync/chef/chef-sync-types"; -import { AppConnection } from "../../../../services/app-connection/app-connection-enums"; import { ChefConnectionMethod } from "./chef-connection-enums"; import { TChefConnection, diff --git a/backend/src/ee/services/app-connections/chef/chef-connection-service.ts b/backend/src/ee/services/app-connections/chef/chef-connection-service.ts index 05969bf5d..242b1fbf9 100644 --- a/backend/src/ee/services/app-connections/chef/chef-connection-service.ts +++ b/backend/src/ee/services/app-connections/chef/chef-connection-service.ts @@ -1,7 +1,8 @@ -import { ForbiddenRequestError } from "@app/lib/errors"; +import { BadRequestError, ForbiddenRequestError } from "@app/lib/errors"; import { OrgServiceActor } from "@app/lib/types"; import { AppConnection } from "../../../../services/app-connection/app-connection-enums"; +import { TLicenseServiceFactory } from "../../license/license-service"; import { listChefDataBagItems, listChefDataBags } from "./chef-connection-fns"; import { TChefConnection } from "./chef-connection-types"; @@ -11,8 +12,23 @@ type TGetAppConnectionFunc = ( actor: OrgServiceActor ) => Promise; -export const chefConnectionService = (getAppConnection: TGetAppConnectionFunc) => { +// Enterprise check +export const checkPlan = async (licenseService: Pick, orgId: string) => { + const plan = await licenseService.getPlan(orgId); + if (!plan.enterpriseAppConnections) + throw new BadRequestError({ + message: + "Failed to use app connection due to plan restriction. Upgrade plan to access enterprise app connections." + }); +}; + +export const chefConnectionService = ( + getAppConnection: TGetAppConnectionFunc, + licenseService: Pick +) => { const listDataBags = async (appConnectionId: string, actor: OrgServiceActor) => { + await checkPlan(licenseService, actor.orgId); + const appConnection = await getAppConnection(AppConnection.Chef, appConnectionId, actor); if (!appConnection) { @@ -23,6 +39,8 @@ export const chefConnectionService = (getAppConnection: TGetAppConnectionFunc) = }; const listDataBagItems = async (appConnectionId: string, dataBagName: string, actor: OrgServiceActor) => { + await checkPlan(licenseService, actor.orgId); + const appConnection = await getAppConnection(AppConnection.Chef, appConnectionId, actor); if (!appConnection) { diff --git a/backend/src/ee/services/app-connections/chef/chef-connection-types.ts b/backend/src/ee/services/app-connections/chef/chef-connection-types.ts index 096218951..5673614e9 100644 --- a/backend/src/ee/services/app-connections/chef/chef-connection-types.ts +++ b/backend/src/ee/services/app-connections/chef/chef-connection-types.ts @@ -1,7 +1,7 @@ import z from "zod"; -import { DiscriminativePick } from "@app/lib/types"; import { TChefDataBagItemContent } from "@app/ee/services/secret-sync/chef"; +import { DiscriminativePick } from "@app/lib/types"; import { AppConnection } from "../../../../services/app-connection/app-connection-enums"; import { diff --git a/backend/src/server/routes/v1/secret-sync-routers/secret-sync-router.ts b/backend/src/server/routes/v1/secret-sync-routers/secret-sync-router.ts index 0f394f8b2..61e4ab79d 100644 --- a/backend/src/server/routes/v1/secret-sync-routers/secret-sync-router.ts +++ b/backend/src/server/routes/v1/secret-sync-routers/secret-sync-router.ts @@ -1,6 +1,7 @@ import { z } from "zod"; import { EventType } from "@app/ee/services/audit-log/audit-log-types"; +import { ChefSyncListItemSchema, ChefSyncSchema } from "@app/ee/services/secret-sync/chef"; import { OCIVaultSyncListItemSchema, OCIVaultSyncSchema } from "@app/ee/services/secret-sync/oci-vault"; import { ApiDocsTags, SecretSyncs } from "@app/lib/api-docs"; import { readLimit } from "@app/server/config/rateLimiter"; @@ -24,7 +25,6 @@ import { AzureKeyVaultSyncListItemSchema, AzureKeyVaultSyncSchema } from "@app/s import { BitbucketSyncListItemSchema, BitbucketSyncSchema } from "@app/services/secret-sync/bitbucket"; import { CamundaSyncListItemSchema, CamundaSyncSchema } from "@app/services/secret-sync/camunda"; import { ChecklySyncListItemSchema, ChecklySyncSchema } from "@app/services/secret-sync/checkly/checkly-sync-schemas"; -import { ChefSyncListItemSchema, ChefSyncSchema } from "@app/ee/services/secret-sync/chef"; import { CloudflarePagesSyncListItemSchema, CloudflarePagesSyncSchema diff --git a/backend/src/services/app-connection/app-connection-service.ts b/backend/src/services/app-connection/app-connection-service.ts index 6d23d3c0a..99ff253d2 100644 --- a/backend/src/services/app-connection/app-connection-service.ts +++ b/backend/src/services/app-connection/app-connection-service.ts @@ -885,6 +885,6 @@ export const appConnectionServiceFactory = ({ northflank: northflankConnectionService(connectAppConnectionById), okta: oktaConnectionService(connectAppConnectionById), laravelForge: laravelForgeConnectionService(connectAppConnectionById), - chef: chefConnectionService(connectAppConnectionById) + chef: chefConnectionService(connectAppConnectionById, licenseService) }; }; diff --git a/backend/src/services/secret-sync/secret-sync-fns.ts b/backend/src/services/secret-sync/secret-sync-fns.ts index ca779bf6a..6ee9b91d3 100644 --- a/backend/src/services/secret-sync/secret-sync-fns.ts +++ b/backend/src/services/secret-sync/secret-sync-fns.ts @@ -290,7 +290,9 @@ export const SecretSyncFns = { case SecretSync.Chef: return ChefSyncFns.syncSecrets(secretSync, schemaSecretMap); default: - throw new Error(`Unhandled sync destination for sync secrets fns: ${secretSync.destination}`); + throw new Error( + `Unhandled sync destination for sync secrets fns: ${(secretSync as TSecretSyncWithCredentials).destination}` + ); } }, getSecrets: async ( @@ -413,7 +415,9 @@ export const SecretSyncFns = { secretMap = await ChefSyncFns.getSecrets(secretSync); break; default: - throw new Error(`Unhandled sync destination for get secrets fns: ${secretSync.destination}`); + throw new Error( + `Unhandled sync destination for get secrets fns: ${(secretSync as TSecretSyncWithCredentials).destination}` + ); } const filtered = filterForSchema(secretMap, secretSync.environment?.slug || "", secretSync.syncOptions.keySchema); @@ -510,7 +514,9 @@ export const SecretSyncFns = { case SecretSync.Chef: return ChefSyncFns.removeSecrets(secretSync, schemaSecretMap); default: - throw new Error(`Unhandled sync destination for remove secrets fns: ${secretSync.destination}`); + throw new Error( + `Unhandled sync destination for remove secrets fns: ${(secretSync as TSecretSyncWithCredentials).destination}` + ); } } }; diff --git a/docs/integrations/app-connections/chef.mdx b/docs/integrations/app-connections/chef.mdx index 60c49fb1f..fdb866557 100644 --- a/docs/integrations/app-connections/chef.mdx +++ b/docs/integrations/app-connections/chef.mdx @@ -3,6 +3,14 @@ title: "Chef Connection" description: "Learn how to configure a Chef Connection for Infisical." --- + + Chef App Connection is a paid feature. + + If you're using Infisical Cloud, then it is available under the **Enterprise Tier**. If you're self-hosting Infisical, + then you should contact team@infisical.com to purchase an enterprise license to use it. + + + Infisical supports the use of User Private Key to connect with Chef Server. Please access your **starter kit** to get all the required information to create a Chef Connection. diff --git a/docs/integrations/secret-syncs/chef.mdx b/docs/integrations/secret-syncs/chef.mdx index 13f3b3474..423d42b4b 100644 --- a/docs/integrations/secret-syncs/chef.mdx +++ b/docs/integrations/secret-syncs/chef.mdx @@ -3,6 +3,14 @@ title: "Chef Sync" description: "Learn how to configure a Chef Sync for Infisical." --- + + Chef Sync is a paid feature. + + If you're using Infisical Cloud, then it is available under the **Enterprise Tier**. If you're self-hosting Infisical, + then you should contact team@infisical.com to purchase an enterprise license to use it. + + + **Prerequisites:** - Create a [Chef Connection](/integrations/app-connections/chef) From 14e0a0ff6d27f198a72525f10d2acc3e32c8be6a Mon Sep 17 00:00:00 2001 From: Piyush Gupta Date: Mon, 3 Nov 2025 19:41:20 +0530 Subject: [PATCH 14/28] fix: lint --- backend/src/services/app-connection/app-connection-fns.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/src/services/app-connection/app-connection-fns.ts b/backend/src/services/app-connection/app-connection-fns.ts index 87f22b031..863fa75f9 100644 --- a/backend/src/services/app-connection/app-connection-fns.ts +++ b/backend/src/services/app-connection/app-connection-fns.ts @@ -296,7 +296,7 @@ export const decryptAppConnectionCredentials = async ({ cipherTextBlob: encryptedCredentials }); - return JSON.parse(decryptedPlainTextBlob.toString()); + return JSON.parse(decryptedPlainTextBlob.toString()) as TAppConnection["credentials"]; }; export const validateAppConnectionCredentials = async ( From 1ed59a7304af103b1004f28040dafd5abde94d21 Mon Sep 17 00:00:00 2001 From: Victor Santos Date: Mon, 3 Nov 2025 11:12:38 -0300 Subject: [PATCH 15/28] refactor: streamline error handling and notification logic across various components --- .../src/components/mfa/TotpRegistration.tsx | 31 ++--- .../IdentitySection/IdentityTable.tsx | 29 ++-- .../IdentityTlsCertAuthForm.tsx | 67 ++++----- .../IdentitySection/IdentityTokenAuthForm.tsx | 59 ++++---- .../IdentityUniversalAuthForm.tsx | 95 ++++++------- .../OrgMembersSection/AddOrgMemberModal.tsx | 89 ++++++------ .../AddSubOrgMemberModal.tsx | 42 +++--- .../UpgradePrivilegeSystemModal.tsx | 19 +-- .../components/DeleteAppConnectionModal.tsx | 27 ++-- .../EditAppConnectionDetailsModal.tsx | 27 ++-- .../OauthCallbackPage/OauthCallbackPage.tsx | 56 ++------ .../BillingDetailsTab/CompanyNameSection.tsx | 28 ++-- .../BillingDetailsTab/InvoiceEmailSection.tsx | 28 ++-- .../BillingDetailsTab/PmtMethodsTable.tsx | 25 ++-- .../BillingDetailsTab/TaxIDModal.tsx | 30 ++-- .../GroupDetailsByIDPage.tsx | 34 ++--- .../components/AddGroupMemberModal.tsx | 35 ++--- .../GroupMembersSection.tsx | 27 ++-- .../IdentityAddToProjectModal.tsx | 33 ++--- .../IdentityProjectsSection.tsx | 29 ++-- .../components/IdentityTokenModal.tsx | 55 +++----- .../IdentityAuthLockoutFields.tsx | 26 ++-- .../IdentityTokenAuthTokensTable.tsx | 29 ++-- ...dentityUniversalAuthClientSecretsTable.tsx | 26 ++-- .../ViewIdentityAuthModal.tsx | 28 ++-- .../components/GatewayCliDeploymentMethod.tsx | 7 +- .../components/RelayCliDeploymentMethod.tsx | 7 +- .../components/AllProjectView.tsx | 24 ++-- .../ProjectsPage/components/MyProjectView.tsx | 31 ++--- .../RoleByIDPage/RoleByIDPage.tsx | 43 +++--- .../RoleByIDPage/components/RoleModal.tsx | 75 +++++----- .../RequestSecret/RequestSecretForm.tsx | 46 +++---- .../RequestSecret/RequestSecretTab.tsx | 24 ++-- .../OrgSecretShareLimitSection.tsx | 31 ++--- .../SecretSharingAllowShareToAnyone.tsx | 26 ++-- .../components/ShareSecret/ShareSecretTab.tsx | 24 ++-- .../AuditLogStreamForm/AuditLogStreamForm.tsx | 48 ++----- .../components/DeleteAuditLogStreamModal.tsx | 27 ++-- .../components/VaultConnectionSection.tsx | 22 +-- .../components/VaultNamespaceConfigModal.tsx | 46 +++---- .../OrgDeleteSection/OrgDeleteSection.tsx | 28 ++-- .../OrgEncryptionTab/OrgEncryptionTab.tsx | 16 +-- .../AddOrgIncidentContactModal.tsx | 34 ++--- .../OrgIncidentContactsTable.tsx | 30 ++-- .../OrgNameChangeSection.tsx | 30 ++-- .../SubOrgNameChangeSection.tsx | 30 ++-- .../OrgProductSelectSection.tsx | 20 +-- .../OrgProductSettingsTab.tsx | 6 - .../ExternalGroupOrgRoleMappings.tsx | 18 +-- .../components/OrgSsoTab/LDAPModal.tsx | 78 +++++------ .../components/OrgSsoTab/OIDCModal.tsx | 129 ++++++++---------- .../components/OrgSsoTab/SSOModal.tsx | 85 +++++------- .../components/GroupsSection/GroupRoles.tsx | 20 ++- .../ProjectRoleList/ProjectRoleList.tsx | 17 +-- ...rojectAdditionalPrivilegeModifySection.tsx | 47 +++---- ...ntityProjectAdditionalPrivilegeSection.tsx | 19 +-- .../IdentityRoleDetailsSection.tsx | 67 +++++---- ...emberProjectAdditionalPrivilegeSection.tsx | 17 +-- ...rojectAdditionalPrivilegeModifySection.tsx | 43 +++--- .../components/RolePermissionsSection.tsx | 21 ++- .../BackfillSecretReferenceSection.tsx | 8 +- 61 files changed, 843 insertions(+), 1375 deletions(-) diff --git a/frontend/src/components/mfa/TotpRegistration.tsx b/frontend/src/components/mfa/TotpRegistration.tsx index 0b79bfd98..bcb0d3691 100644 --- a/frontend/src/components/mfa/TotpRegistration.tsx +++ b/frontend/src/components/mfa/TotpRegistration.tsx @@ -25,27 +25,20 @@ const TotpRegistration = ({ onComplete, shouldCenterQr }: Props) => { const handleTotpVerify = async (event: React.FormEvent) => { event.preventDefault(); - try { - const result = await verifyUserTotp({ - totp - }); + const result = await verifyUserTotp({ + totp + }); - createNotification({ - text: "Successfully configured mobile authenticator", - type: "success" - }); + createNotification({ + text: "Successfully configured mobile authenticator", + type: "success" + }); - if (result.recoveryCodes && result.recoveryCodes.length > 0) { - setRecoveryCodes(result.recoveryCodes); - setShowRecoveryModal(true); - } else if (onComplete) { - onComplete(); - } - } catch { - createNotification({ - text: "Failed to verify TOTP code", - type: "error" - }); + if (result.recoveryCodes && result.recoveryCodes.length > 0) { + setRecoveryCodes(result.recoveryCodes); + setShowRecoveryModal(true); + } else if (onComplete) { + onComplete(); } }; diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityTable.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityTable.tsx index c4c1561e7..d202b909a 100644 --- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityTable.tsx +++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityTable.tsx @@ -145,27 +145,16 @@ export const IdentityTable = ({ handlePopUpOpen }: Props) => { }; const handleChangeRole = async ({ identityId, role }: { identityId: string; role: string }) => { - try { - await updateMutateAsync({ - identityId, - role, - organizationId - }); + await updateMutateAsync({ + identityId, + role, + organizationId + }); - createNotification({ - text: "Successfully updated identity role", - type: "success" - }); - } catch (err) { - console.error(err); - const error = err as any; - const text = error?.response?.data?.message ?? "Failed to update identity role"; - - createNotification({ - text, - type: "error" - }); - } + createNotification({ + text: "Successfully updated identity role", + type: "success" + }); }; const handleRoleToggle = useCallback( diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityTlsCertAuthForm.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityTlsCertAuthForm.tsx index 19a0499fc..2a2ca45c3 100644 --- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityTlsCertAuthForm.tsx +++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityTlsCertAuthForm.tsx @@ -134,47 +134,40 @@ export const IdentityTlsCertAuthForm = ({ accessTokenNumUsesLimit, accessTokenTrustedIps }: FormData) => { - try { - if (!identityId) return; + if (!identityId) return; - if (data) { - await updateMutateAsync({ - organizationId: orgId, - caCertificate, - allowedCommonNames: allowedCommonNames || null, - identityId, - accessTokenTTL: Number(accessTokenTTL), - accessTokenMaxTTL: Number(accessTokenMaxTTL), - accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit), - accessTokenTrustedIps - }); - } else { - await addMutateAsync({ - organizationId: orgId, - identityId, - caCertificate, - allowedCommonNames: allowedCommonNames || undefined, - accessTokenTTL: Number(accessTokenTTL), - accessTokenMaxTTL: Number(accessTokenMaxTTL), - accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit), - accessTokenTrustedIps - }); - } - - handlePopUpToggle("identityAuthMethod", false); - - createNotification({ - text: `Successfully ${isUpdate ? "updated" : "configured"} auth method`, - type: "success" + if (data) { + await updateMutateAsync({ + organizationId: orgId, + caCertificate, + allowedCommonNames: allowedCommonNames || null, + identityId, + accessTokenTTL: Number(accessTokenTTL), + accessTokenMaxTTL: Number(accessTokenMaxTTL), + accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit), + accessTokenTrustedIps }); - - reset(); - } catch { - createNotification({ - text: `Failed to ${isUpdate ? "update" : "configure"} identity`, - type: "error" + } else { + await addMutateAsync({ + organizationId: orgId, + identityId, + caCertificate, + allowedCommonNames: allowedCommonNames || undefined, + accessTokenTTL: Number(accessTokenTTL), + accessTokenMaxTTL: Number(accessTokenMaxTTL), + accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit), + accessTokenTrustedIps }); } + + handlePopUpToggle("identityAuthMethod", false); + + createNotification({ + text: `Successfully ${isUpdate ? "updated" : "configured"} auth method`, + type: "success" + }); + + reset(); }; return ( diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityTokenAuthForm.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityTokenAuthForm.tsx index b819202fc..8da4bad17 100644 --- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityTokenAuthForm.tsx +++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityTokenAuthForm.tsx @@ -127,43 +127,36 @@ export const IdentityTokenAuthForm = ({ accessTokenNumUsesLimit, accessTokenTrustedIps }: FormData) => { - try { - if (!identityId) return; + if (!identityId) return; - if (data) { - await updateMutateAsync({ - organizationId: orgId, - identityId, - accessTokenTTL: Number(accessTokenTTL), - accessTokenMaxTTL: Number(accessTokenMaxTTL), - accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit), - accessTokenTrustedIps - }); - } else { - await addMutateAsync({ - organizationId: orgId, - identityId, - accessTokenTTL: Number(accessTokenTTL), - accessTokenMaxTTL: Number(accessTokenMaxTTL), - accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit), - accessTokenTrustedIps - }); - } - - handlePopUpToggle("identityAuthMethod", false); - - createNotification({ - text: `Successfully ${isUpdate ? "updated" : "configured"} auth method`, - type: "success" + if (data) { + await updateMutateAsync({ + organizationId: orgId, + identityId, + accessTokenTTL: Number(accessTokenTTL), + accessTokenMaxTTL: Number(accessTokenMaxTTL), + accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit), + accessTokenTrustedIps }); - - reset(); - } catch { - createNotification({ - text: `Failed to ${isUpdate ? "update" : "configure"} identity`, - type: "error" + } else { + await addMutateAsync({ + organizationId: orgId, + identityId, + accessTokenTTL: Number(accessTokenTTL), + accessTokenMaxTTL: Number(accessTokenMaxTTL), + accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit), + accessTokenTrustedIps }); } + + handlePopUpToggle("identityAuthMethod", false); + + createNotification({ + text: `Successfully ${isUpdate ? "updated" : "configured"} auth method`, + type: "success" + }); + + reset(); }; return ( diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityUniversalAuthForm.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityUniversalAuthForm.tsx index d43d84c86..dd85f5342 100644 --- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityUniversalAuthForm.tsx +++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityUniversalAuthForm.tsx @@ -220,64 +220,55 @@ export const IdentityUniversalAuthForm = ({ lockoutCounterResetValue, lockoutCounterResetUnit }: FormData) => { - try { - if (!identityId) return; + if (!identityId) return; - const lockoutDurationSeconds = ms(`${lockoutDurationValue}${lockoutDurationUnit}`) / 1000; - const lockoutCounterResetSeconds = - ms(`${lockoutCounterResetValue}${lockoutCounterResetUnit}`) / 1000; + const lockoutDurationSeconds = ms(`${lockoutDurationValue}${lockoutDurationUnit}`) / 1000; + const lockoutCounterResetSeconds = + ms(`${lockoutCounterResetValue}${lockoutCounterResetUnit}`) / 1000; - if (data) { - // update universal auth configuration - await updateMutateAsync({ - organizationId: orgId, - identityId, - clientSecretTrustedIps, - accessTokenTTL: Number(accessTokenTTL), - accessTokenMaxTTL: Number(accessTokenMaxTTL), - accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit), - accessTokenTrustedIps, - accessTokenPeriod: Number(accessTokenPeriod), - lockoutEnabled, - lockoutThreshold: Number(lockoutThreshold), - lockoutDurationSeconds, - lockoutCounterResetSeconds - }); - } else { - // create new universal auth configuration - - await addMutateAsync({ - organizationId: orgId, - identityId, - clientSecretTrustedIps, - accessTokenTTL: Number(accessTokenTTL), - accessTokenMaxTTL: Number(accessTokenMaxTTL), - accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit), - accessTokenTrustedIps, - accessTokenPeriod: Number(accessTokenPeriod), - lockoutEnabled, - lockoutThreshold: Number(lockoutThreshold), - lockoutDurationSeconds: Number(lockoutDurationSeconds), - lockoutCounterResetSeconds: Number(lockoutCounterResetSeconds) - }); - } - - handlePopUpToggle("identityAuthMethod", false); - - createNotification({ - text: `Successfully ${isUpdate ? "updated" : "created"} auth method`, - type: "success" + if (data) { + // update universal auth configuration + await updateMutateAsync({ + organizationId: orgId, + identityId, + clientSecretTrustedIps, + accessTokenTTL: Number(accessTokenTTL), + accessTokenMaxTTL: Number(accessTokenMaxTTL), + accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit), + accessTokenTrustedIps, + accessTokenPeriod: Number(accessTokenPeriod), + lockoutEnabled, + lockoutThreshold: Number(lockoutThreshold), + lockoutDurationSeconds, + lockoutCounterResetSeconds }); + } else { + // create new universal auth configuration - reset(); - } catch { - const text = `Failed to ${isUpdate ? "update" : "configure"} identity`; - - createNotification({ - text, - type: "error" + await addMutateAsync({ + organizationId: orgId, + identityId, + clientSecretTrustedIps, + accessTokenTTL: Number(accessTokenTTL), + accessTokenMaxTTL: Number(accessTokenMaxTTL), + accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit), + accessTokenTrustedIps, + accessTokenPeriod: Number(accessTokenPeriod), + lockoutEnabled, + lockoutThreshold: Number(lockoutThreshold), + lockoutDurationSeconds: Number(lockoutDurationSeconds), + lockoutCounterResetSeconds: Number(lockoutCounterResetSeconds) }); } + + handlePopUpToggle("identityAuthMethod", false); + + createNotification({ + text: `Successfully ${isUpdate ? "updated" : "created"} auth method`, + type: "success" + }); + + reset(); }; return ( diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgMembersTab/components/OrgMembersSection/AddOrgMemberModal.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgMembersTab/components/OrgMembersSection/AddOrgMemberModal.tsx index e49beadae..da88603fc 100644 --- a/frontend/src/pages/organization/AccessManagementPage/components/OrgMembersTab/components/OrgMembersSection/AddOrgMemberModal.tsx +++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgMembersTab/components/OrgMembersSection/AddOrgMemberModal.tsx @@ -122,64 +122,55 @@ export const AddOrgMemberModal = ({ } } - try { - const parsedEmails = emails - .replace(/\s/g, "") - .split(",") - .map((email) => { - if (EmailSchema.safeParse(email).success) { - return email.trim(); - } + const parsedEmails = emails + .replace(/\s/g, "") + .split(",") + .map((email) => { + if (EmailSchema.safeParse(email).success) { + return email.trim(); + } - return null; - }); - - if (parsedEmails.includes(null)) { - createNotification({ - text: "Invalid email addresses provided.", - type: "error" - }); - return; - } - - const usernames = emails.split(",").map((email) => email.trim()); - const { data } = await addUsersMutateAsync({ - organizationId: currentOrg?.id, - inviteeEmails: usernames, - organizationRoleSlug: organizationRole.slug + return null; }); - await Promise.allSettled( - selectedProjects.map((el) => - addUserToProject({ - orgId: currentOrg.id, - projectId: el.id, - roleSlugs: [projectRoleSlug], - usernames - }) - ) - ); - - setCompleteInviteLinks(data?.completeInviteLinks ?? null); - - // only show this notification when email is configured. - // A [completeInviteLink] will not be sent if smtp is configured - - if (!data.completeInviteLinks) { - createNotification({ - text: "Successfully invited user to the organization.", - type: "success" - }); - } - } catch (error) { - console.error(error); + if (parsedEmails.includes(null)) { createNotification({ - text: "Failed to invite user to org", + text: "Invalid email addresses provided.", type: "error" }); return; } + const usernames = emails.split(",").map((email) => email.trim()); + const { data } = await addUsersMutateAsync({ + organizationId: currentOrg?.id, + inviteeEmails: usernames, + organizationRoleSlug: organizationRole.slug + }); + + await Promise.allSettled( + selectedProjects.map((el) => + addUserToProject({ + orgId: currentOrg.id, + projectId: el.id, + roleSlugs: [projectRoleSlug], + usernames + }) + ) + ); + + setCompleteInviteLinks(data?.completeInviteLinks ?? null); + + // only show this notification when email is configured. + // A [completeInviteLink] will not be sent if smtp is configured + + if (!data.completeInviteLinks) { + createNotification({ + text: "Successfully invited user to the organization.", + type: "success" + }); + } + if (serverDetails?.emailConfigured) { handlePopUpToggle("addMember", false); } diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgMembersTab/components/OrgMembersSection/AddSubOrgMemberModal.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgMembersTab/components/OrgMembersSection/AddSubOrgMemberModal.tsx index 290f8db4b..5edba7cde 100644 --- a/frontend/src/pages/organization/AccessManagementPage/components/OrgMembersTab/components/OrgMembersSection/AddSubOrgMemberModal.tsx +++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgMembersTab/components/OrgMembersSection/AddSubOrgMemberModal.tsx @@ -106,32 +106,24 @@ export const AddSubOrgMemberModal = ({ onClose }: Props) => { } } - try { - const usernames = users.map((el) => el.username); - await addUsersMutateAsync({ - organizationId: currentOrg?.id, - inviteeEmails: usernames, - organizationRoleSlug: organizationRole.slug - }); + const usernames = users.map((el) => el.username); + await addUsersMutateAsync({ + organizationId: currentOrg?.id, + inviteeEmails: usernames, + organizationRoleSlug: organizationRole.slug + }); - await Promise.allSettled( - selectedProjects.map((el) => - addUserToProject({ - orgId: currentOrg.id, - projectId: el.id, - roleSlugs: [projectRoleSlug], - usernames - }) - ) - ); - onClose(); - } catch (error) { - console.error(error); - createNotification({ - text: "Failed to add user to suborganization", - type: "error" - }); - } + await Promise.allSettled( + selectedProjects.map((el) => + addUserToProject({ + orgId: currentOrg.id, + projectId: el.id, + roleSlugs: [projectRoleSlug], + usernames + }) + ) + ); + onClose(); }; const getGroupHeaderLabel = (type: ProjectType) => { diff --git a/frontend/src/pages/organization/AccessManagementPage/components/UpgradePrivilegeSystemModal/UpgradePrivilegeSystemModal.tsx b/frontend/src/pages/organization/AccessManagementPage/components/UpgradePrivilegeSystemModal/UpgradePrivilegeSystemModal.tsx index 97aaff73d..c2a200805 100644 --- a/frontend/src/pages/organization/AccessManagementPage/components/UpgradePrivilegeSystemModal/UpgradePrivilegeSystemModal.tsx +++ b/frontend/src/pages/organization/AccessManagementPage/components/UpgradePrivilegeSystemModal/UpgradePrivilegeSystemModal.tsx @@ -44,21 +44,14 @@ export const UpgradePrivilegeSystemModal = ({ isOpen, onOpenChange }: Props) => acknowledgesPermanentChange; const handlePrivilegeSystemUpgrade = async () => { - try { - await upgradePrivilegeSystem(); + await upgradePrivilegeSystem(); - createNotification({ - text: "Privilege system upgrade completed", - type: "success" - }); + createNotification({ + text: "Privilege system upgrade completed", + type: "success" + }); - onOpenChange(false); - } catch { - createNotification({ - text: "Failed to upgrade privilege system", - type: "error" - }); - } + onOpenChange(false); }; const handleClose = () => { diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/DeleteAppConnectionModal.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/DeleteAppConnectionModal.tsx index e5f6b3684..f5782adbb 100644 --- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/DeleteAppConnectionModal.tsx +++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/DeleteAppConnectionModal.tsx @@ -18,26 +18,17 @@ export const DeleteAppConnectionModal = ({ isOpen, onOpenChange, appConnection } const { id: connectionId, name, app } = appConnection; const handleDeleteAppConnection = async () => { - try { - await deleteAppConnection.mutateAsync({ - connectionId, - app - }); + await deleteAppConnection.mutateAsync({ + connectionId, + app + }); - createNotification({ - text: `Successfully removed ${APP_CONNECTION_MAP[app].name} connection`, - type: "success" - }); + createNotification({ + text: `Successfully removed ${APP_CONNECTION_MAP[app].name} connection`, + type: "success" + }); - onOpenChange(false); - } catch (err) { - console.error(err); - - createNotification({ - text: `Failed to remove ${APP_CONNECTION_MAP[app].name} connection`, - type: "error" - }); - } + onOpenChange(false); }; return ( diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/EditAppConnectionDetailsModal.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/EditAppConnectionDetailsModal.tsx index f46a3b3cf..7d1a542c0 100644 --- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/EditAppConnectionDetailsModal.tsx +++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/EditAppConnectionDetailsModal.tsx @@ -43,24 +43,15 @@ const Content = ({ appConnection, onComplete }: ContentProps) => { } = form; const onSubmit = async (formData: FormData) => { - try { - await updateAppConnection.mutateAsync({ - connectionId: appConnection.id, - ...formData - }); - createNotification({ - text: `Successfully updated ${appName} Connection`, - type: "success" - }); - onComplete(); - } catch (err: any) { - console.error(err); - createNotification({ - title: `Failed to update ${appName} Connection`, - text: err.message, - type: "error" - }); - } + await updateAppConnection.mutateAsync({ + connectionId: appConnection.id, + ...formData + }); + createNotification({ + text: `Successfully updated ${appName} Connection`, + type: "success" + }); + onComplete(); }; return ( diff --git a/frontend/src/pages/organization/AppConnections/OauthCallbackPage/OauthCallbackPage.tsx b/frontend/src/pages/organization/AppConnections/OauthCallbackPage/OauthCallbackPage.tsx index df3d1327a..96a474714 100644 --- a/frontend/src/pages/organization/AppConnections/OauthCallbackPage/OauthCallbackPage.tsx +++ b/frontend/src/pages/organization/AppConnections/OauthCallbackPage/OauthCallbackPage.tsx @@ -127,12 +127,7 @@ export const OAuthCallbackPage = () => { projectId, connection }; - } catch (err: any) { - createNotification({ - title: `Failed to ${connectionId ? "update" : "add"} GitLab Connection`, - text: err?.message, - type: "error" - }); + } catch { navigate({ to: returnUrl, params: { @@ -176,12 +171,7 @@ export const OAuthCallbackPage = () => { } }); } - } catch (err: any) { - createNotification({ - title: `Failed to ${connectionId ? "update" : "add"} Azure Key Vault Connection`, - text: err?.message, - type: "error" - }); + } catch { navigate({ to: returnUrl, params: { @@ -233,12 +223,7 @@ export const OAuthCallbackPage = () => { } }); } - } catch (err: any) { - createNotification({ - title: `Failed to ${connectionId ? "update" : "add"} Azure App Configuration Connection`, - text: err?.message, - type: "error" - }); + } catch { navigate({ to: returnUrl, params: { @@ -290,12 +275,7 @@ export const OAuthCallbackPage = () => { } }); } - } catch (err: any) { - createNotification({ - title: `Failed to ${connectionId ? "update" : "add"} Azure Client Secrets Connection`, - text: err?.message, - type: "error" - }); + } catch { navigate({ to: returnUrl, params: { @@ -353,12 +333,7 @@ export const OAuthCallbackPage = () => { } }); } - } catch (err: any) { - createNotification({ - title: `Failed to ${connectionId ? "update" : "add"} Azure DevOps Connection`, - text: err?.message, - type: "error" - }); + } catch { navigate({ to: returnUrl, params: { @@ -441,12 +416,7 @@ export const OAuthCallbackPage = () => { }) }); } - } catch (e: any) { - createNotification({ - title: `Failed to ${connectionId ? "update" : "add"} GitHub Connection`, - text: e.message, - type: "error" - }); + } catch { navigate({ to: returnUrl, params: { @@ -498,12 +468,7 @@ export const OAuthCallbackPage = () => { } }); } - } catch (e: any) { - createNotification({ - title: `Failed to ${connectionId ? "update" : "add"} GitHub Radar Connection`, - text: e.message, - type: "error" - }); + } catch { navigate({ to: returnUrl, params: { @@ -553,12 +518,7 @@ export const OAuthCallbackPage = () => { } }); } - } catch (e: any) { - createNotification({ - title: `Failed to ${connectionId ? "update" : "add"} Heroku Connection`, - text: e.message, - type: "error" - }); + } catch { navigate({ to: returnUrl, params: { diff --git a/frontend/src/pages/organization/BillingPage/components/BillingDetailsTab/CompanyNameSection.tsx b/frontend/src/pages/organization/BillingPage/components/BillingDetailsTab/CompanyNameSection.tsx index fce3978c7..f63b5d6d1 100644 --- a/frontend/src/pages/organization/BillingPage/components/BillingDetailsTab/CompanyNameSection.tsx +++ b/frontend/src/pages/organization/BillingPage/components/BillingDetailsTab/CompanyNameSection.tsx @@ -35,25 +35,17 @@ export const CompanyNameSection = () => { }, [data]); const onFormSubmit = async ({ name }: { name: string }) => { - try { - if (!currentOrg?.id) return; - if (name === "") return; - await mutateAsync({ - name, - organizationId: currentOrg.id - }); + if (!currentOrg?.id) return; + if (name === "") return; + await mutateAsync({ + name, + organizationId: currentOrg.id + }); - createNotification({ - text: "Successfully updated business name", - type: "success" - }); - } catch (err) { - console.error(err); - createNotification({ - text: "Failed to update business name", - type: "error" - }); - } + createNotification({ + text: "Successfully updated business name", + type: "success" + }); }; return ( diff --git a/frontend/src/pages/organization/BillingPage/components/BillingDetailsTab/InvoiceEmailSection.tsx b/frontend/src/pages/organization/BillingPage/components/BillingDetailsTab/InvoiceEmailSection.tsx index 8b471346f..dc05a7208 100644 --- a/frontend/src/pages/organization/BillingPage/components/BillingDetailsTab/InvoiceEmailSection.tsx +++ b/frontend/src/pages/organization/BillingPage/components/BillingDetailsTab/InvoiceEmailSection.tsx @@ -35,26 +35,18 @@ export const InvoiceEmailSection = () => { }, [data]); const onFormSubmit = async ({ email }: { email: string }) => { - try { - if (!currentOrg?.id) return; - if (email === "") return; + if (!currentOrg?.id) return; + if (email === "") return; - await mutateAsync({ - email, - organizationId: currentOrg.id - }); + await mutateAsync({ + email, + organizationId: currentOrg.id + }); - createNotification({ - text: "Successfully updated invoice email recipient", - type: "success" - }); - } catch (err) { - console.error(err); - createNotification({ - text: "Failed to update invoice email recipient", - type: "error" - }); - } + createNotification({ + text: "Successfully updated invoice email recipient", + type: "success" + }); }; return ( diff --git a/frontend/src/pages/organization/BillingPage/components/BillingDetailsTab/PmtMethodsTable.tsx b/frontend/src/pages/organization/BillingPage/components/BillingDetailsTab/PmtMethodsTable.tsx index bf0851e11..15a6bc8e9 100644 --- a/frontend/src/pages/organization/BillingPage/components/BillingDetailsTab/PmtMethodsTable.tsx +++ b/frontend/src/pages/organization/BillingPage/components/BillingDetailsTab/PmtMethodsTable.tsx @@ -39,22 +39,15 @@ export const PmtMethodsTable = () => { }); return; } - try { - await deleteOrgPmtMethod.mutateAsync({ - organizationId: currentOrg.id, - pmtMethodId: pmtMethodToRemove.id - }); - createNotification({ - type: "success", - text: "Successfully removed payment method" - }); - handlePopUpClose("removeCard"); - } catch (error: any) { - createNotification({ - type: "error", - text: error.message ?? "Error removing payment method" - }); - } + await deleteOrgPmtMethod.mutateAsync({ + organizationId: currentOrg.id, + pmtMethodId: pmtMethodToRemove.id + }); + createNotification({ + type: "success", + text: "Successfully removed payment method" + }); + handlePopUpClose("removeCard"); }; return ( diff --git a/frontend/src/pages/organization/BillingPage/components/BillingDetailsTab/TaxIDModal.tsx b/frontend/src/pages/organization/BillingPage/components/BillingDetailsTab/TaxIDModal.tsx index 01b11e81a..23542ac8d 100644 --- a/frontend/src/pages/organization/BillingPage/components/BillingDetailsTab/TaxIDModal.tsx +++ b/frontend/src/pages/organization/BillingPage/components/BillingDetailsTab/TaxIDModal.tsx @@ -98,26 +98,18 @@ export const TaxIDModal = ({ popUp, handlePopUpClose, handlePopUpToggle }: Props }); const onTaxIDModalSubmit = async ({ type, value }: AddTaxIDFormData) => { - try { - if (!currentOrg?.id) return; - await addOrgTaxId.mutateAsync({ - organizationId: currentOrg.id, - type, - value - }); + if (!currentOrg?.id) return; + await addOrgTaxId.mutateAsync({ + organizationId: currentOrg.id, + type, + value + }); - createNotification({ - text: "Successfully added Tax ID", - type: "success" - }); - handlePopUpClose("addTaxID"); - } catch (err) { - console.error(err); - createNotification({ - text: "Failed to add Tax ID", - type: "error" - }); - } + createNotification({ + text: "Successfully added Tax ID", + type: "success" + }); + handlePopUpClose("addTaxID"); }; return ( diff --git a/frontend/src/pages/organization/GroupDetailsByIDPage/GroupDetailsByIDPage.tsx b/frontend/src/pages/organization/GroupDetailsByIDPage/GroupDetailsByIDPage.tsx index b33ce0ef2..57c7b5a7d 100644 --- a/frontend/src/pages/organization/GroupDetailsByIDPage/GroupDetailsByIDPage.tsx +++ b/frontend/src/pages/organization/GroupDetailsByIDPage/GroupDetailsByIDPage.tsx @@ -56,27 +56,19 @@ const Page = () => { ] as const); const onDeleteGroupSubmit = async ({ name, id }: { name: string; id: string }) => { - try { - await deleteMutateAsync({ - id - }); - createNotification({ - text: `Successfully deleted the ${name} group`, - type: "success" - }); - navigate({ - to: "/organization/access-management" as const, - search: { - selectedTab: TabSections.Groups - } - }); - } catch (err) { - console.error(err); - createNotification({ - text: `Failed to delete the ${name} group`, - type: "error" - }); - } + await deleteMutateAsync({ + id + }); + createNotification({ + text: `Successfully deleted the ${name} group`, + type: "success" + }); + navigate({ + to: "/organization/access-management" as const, + search: { + selectedTab: TabSections.Groups + } + }); handlePopUpClose("deleteGroup"); }; diff --git a/frontend/src/pages/organization/GroupDetailsByIDPage/components/AddGroupMemberModal.tsx b/frontend/src/pages/organization/GroupDetailsByIDPage/components/AddGroupMemberModal.tsx index 0995830e5..b9d1b184c 100644 --- a/frontend/src/pages/organization/GroupDetailsByIDPage/components/AddGroupMemberModal.tsx +++ b/frontend/src/pages/organization/GroupDetailsByIDPage/components/AddGroupMemberModal.tsx @@ -63,31 +63,24 @@ export const AddGroupMembersModal = ({ popUp, handlePopUpToggle }: Props) => { const { mutateAsync: addUserToGroupMutateAsync } = useAddUserToGroup(); const handleAddMember = async (username: string) => { - try { - if (!popUpData?.slug) { - createNotification({ - text: "Some data is missing, please refresh the page and try again", - type: "error" - }); - return; - } - - await addUserToGroupMutateAsync({ - groupId: popUpData.groupId, - username, - slug: popUpData.slug - }); - + if (!popUpData?.slug) { createNotification({ - text: "Successfully assigned user to the group", - type: "success" - }); - } catch { - createNotification({ - text: "Failed to assign user to the group", + text: "Some data is missing, please refresh the page and try again", type: "error" }); + return; } + + await addUserToGroupMutateAsync({ + groupId: popUpData.groupId, + username, + slug: popUpData.slug + }); + + createNotification({ + text: "Successfully assigned user to the group", + type: "success" + }); }; return ( diff --git a/frontend/src/pages/organization/GroupDetailsByIDPage/components/GroupMembersSection/GroupMembersSection.tsx b/frontend/src/pages/organization/GroupDetailsByIDPage/components/GroupMembersSection/GroupMembersSection.tsx index 2ca6859b0..c78b5404e 100644 --- a/frontend/src/pages/organization/GroupDetailsByIDPage/components/GroupMembersSection/GroupMembersSection.tsx +++ b/frontend/src/pages/organization/GroupDetailsByIDPage/components/GroupMembersSection/GroupMembersSection.tsx @@ -29,25 +29,18 @@ export const GroupMembersSection = ({ groupId, groupSlug }: Props) => { const { mutateAsync: removeUserFromGroupMutateAsync } = useRemoveUserFromGroup(); const handleRemoveUserFromGroup = async (username: string) => { - try { - await removeUserFromGroupMutateAsync({ - groupId, - username, - slug: groupSlug - }); + await removeUserFromGroupMutateAsync({ + groupId, + username, + slug: groupSlug + }); - createNotification({ - text: `Successfully removed user ${username} from the group`, - type: "success" - }); + createNotification({ + text: `Successfully removed user ${username} from the group`, + type: "success" + }); - handlePopUpToggle("removeMemberFromGroup", false); - } catch { - createNotification({ - text: `Failed to remove user ${username} from the group`, - type: "error" - }); - } + handlePopUpToggle("removeMemberFromGroup", false); }; return ( diff --git a/frontend/src/pages/organization/IdentityDetailsByIDPage/components/IdentityProjectsSection/IdentityAddToProjectModal.tsx b/frontend/src/pages/organization/IdentityDetailsByIDPage/components/IdentityProjectsSection/IdentityAddToProjectModal.tsx index 2e5c7101c..2f407142a 100644 --- a/frontend/src/pages/organization/IdentityDetailsByIDPage/components/IdentityProjectsSection/IdentityAddToProjectModal.tsx +++ b/frontend/src/pages/organization/IdentityDetailsByIDPage/components/IdentityProjectsSection/IdentityAddToProjectModal.tsx @@ -75,30 +75,19 @@ const Content = ({ identityId, handlePopUpToggle }: Omit) => { }, [workspaces, projectMemberships]); const onFormSubmit = async ({ project: selectedProject, role }: FormData) => { - try { - await addIdentityToWorkspace({ - projectId: selectedProject.id, - identityId, - role: role.slug || undefined - }); + await addIdentityToWorkspace({ + projectId: selectedProject.id, + identityId, + role: role.slug || undefined + }); - createNotification({ - text: "Successfully added identity to project", - type: "success" - }); + createNotification({ + text: "Successfully added identity to project", + type: "success" + }); - reset(); - handlePopUpToggle("addIdentityToProject", false); - } catch (err) { - console.error(err); - const error = err as any; - const text = error?.response?.data?.message ?? "Failed to add identity to project"; - - createNotification({ - text, - type: "error" - }); - } + reset(); + handlePopUpToggle("addIdentityToProject", false); }; const isProjectSelected = Boolean(projectId); diff --git a/frontend/src/pages/organization/IdentityDetailsByIDPage/components/IdentityProjectsSection/IdentityProjectsSection.tsx b/frontend/src/pages/organization/IdentityDetailsByIDPage/components/IdentityProjectsSection/IdentityProjectsSection.tsx index 6530b9ae5..8d67ef6a4 100644 --- a/frontend/src/pages/organization/IdentityDetailsByIDPage/components/IdentityProjectsSection/IdentityProjectsSection.tsx +++ b/frontend/src/pages/organization/IdentityDetailsByIDPage/components/IdentityProjectsSection/IdentityProjectsSection.tsx @@ -22,28 +22,17 @@ export const IdentityProjectsSection = ({ identityId }: Props) => { ] as const); const onRemoveIdentitySubmit = async (id: string, projectId: string) => { - try { - await deleteMutateAsync({ - identityId: id, - projectId - }); + await deleteMutateAsync({ + identityId: id, + projectId + }); - createNotification({ - text: "Successfully removed identity from project", - type: "success" - }); + createNotification({ + text: "Successfully removed identity from project", + type: "success" + }); - handlePopUpClose("removeIdentityFromProject"); - } catch (err) { - console.error(err); - const error = err as any; - const text = error?.response?.data?.message ?? "Failed to remove identity from project"; - - createNotification({ - text, - type: "error" - }); - } + handlePopUpClose("removeIdentityFromProject"); }; return ( diff --git a/frontend/src/pages/organization/IdentityDetailsByIDPage/components/IdentityTokenModal.tsx b/frontend/src/pages/organization/IdentityDetailsByIDPage/components/IdentityTokenModal.tsx index d2b865a5a..d5c1aa2ac 100644 --- a/frontend/src/pages/organization/IdentityDetailsByIDPage/components/IdentityTokenModal.tsx +++ b/frontend/src/pages/organization/IdentityDetailsByIDPage/components/IdentityTokenModal.tsx @@ -72,46 +72,33 @@ export const IdentityTokenModal = ({ popUp, handlePopUpToggle }: Props) => { }, [popUp?.token?.data]); const onFormSubmit = async ({ name }: FormData) => { - try { - if (tokenData?.tokenId) { - // update + if (tokenData?.tokenId) { + // update - await updateToken({ - identityId: tokenData.identityId, - tokenId: tokenData.tokenId, - name - }); - - handlePopUpToggle("token", false); - } else { - // create - - const newTokenData = await createToken({ - identityId: tokenData.identityId, - name - }); - - setToken(newTokenData.accessToken); - } - - createNotification({ - text: `Successfully ${popUp?.token?.data ? "updated" : "created"} token`, - type: "success" + await updateToken({ + identityId: tokenData.identityId, + tokenId: tokenData.tokenId, + name }); - reset(); - } catch (err) { - console.error(err); - const error = err as any; - const text = - error?.response?.data?.message ?? - `Failed to ${popUp?.token?.data ? "update" : "create"} token`; + handlePopUpToggle("token", false); + } else { + // create - createNotification({ - text, - type: "error" + const newTokenData = await createToken({ + identityId: tokenData.identityId, + name }); + + setToken(newTokenData.accessToken); } + + createNotification({ + text: `Successfully ${popUp?.token?.data ? "updated" : "created"} token`, + type: "success" + }); + + reset(); }; return ( diff --git a/frontend/src/pages/organization/IdentityDetailsByIDPage/components/ViewIdentityAuthModal/IdentityAuthLockoutFields.tsx b/frontend/src/pages/organization/IdentityDetailsByIDPage/components/ViewIdentityAuthModal/IdentityAuthLockoutFields.tsx index b5cb2d901..4ec5871a2 100644 --- a/frontend/src/pages/organization/IdentityDetailsByIDPage/components/ViewIdentityAuthModal/IdentityAuthLockoutFields.tsx +++ b/frontend/src/pages/organization/IdentityDetailsByIDPage/components/ViewIdentityAuthModal/IdentityAuthLockoutFields.tsx @@ -31,23 +31,15 @@ export const LockoutFields = ({ const [lockedOutState, setLockedOutState] = useState(lockedOut); - async function clearLockouts() { - try { - const deleted = await mutateAsync({ identityId }); - createNotification({ - text: `Successfully cleared ${deleted} lockout${deleted === 1 ? "" : "s"}`, - type: "success" - }); - setLockedOutState(false); - onResetAllLockouts(); - } catch (error) { - console.error(error); - createNotification({ - text: "Failed to clear lockouts. Please try again.", - type: "error" - }); - } - } + const clearLockouts = async () => { + const deleted = await mutateAsync({ identityId }); + createNotification({ + text: `Successfully cleared ${deleted} lockout${deleted === 1 ? "" : "s"}`, + type: "success" + }); + setLockedOutState(false); + onResetAllLockouts(); + }; return ( <> diff --git a/frontend/src/pages/organization/IdentityDetailsByIDPage/components/ViewIdentityAuthModal/IdentityTokenAuthTokensTable.tsx b/frontend/src/pages/organization/IdentityDetailsByIDPage/components/ViewIdentityAuthModal/IdentityTokenAuthTokensTable.tsx index be9c166b3..cc11d9d10 100644 --- a/frontend/src/pages/organization/IdentityDetailsByIDPage/components/ViewIdentityAuthModal/IdentityTokenAuthTokensTable.tsx +++ b/frontend/src/pages/organization/IdentityDetailsByIDPage/components/ViewIdentityAuthModal/IdentityTokenAuthTokensTable.tsx @@ -51,28 +51,17 @@ export const IdentityTokenAuthTokensTable = ({ tokens, identityId }: Props) => { tokenId: string; name: string; }) => { - try { - await revokeToken({ - identityId: parentIdentityId, - tokenId - }); + await revokeToken({ + identityId: parentIdentityId, + tokenId + }); - handlePopUpClose("revokeToken"); + handlePopUpClose("revokeToken"); - createNotification({ - text: `Successfully revoked token ${name ?? ""}`, - type: "success" - }); - } catch (err) { - console.error(err); - const error = err as any; - const text = error?.response?.data?.message ?? "Failed to revoke token"; - - createNotification({ - text, - type: "error" - }); - } + createNotification({ + text: `Successfully revoked token ${name ?? ""}`, + type: "success" + }); }; return ( diff --git a/frontend/src/pages/organization/IdentityDetailsByIDPage/components/ViewIdentityAuthModal/IdentityUniversalAuthClientSecretsTable.tsx b/frontend/src/pages/organization/IdentityDetailsByIDPage/components/ViewIdentityAuthModal/IdentityUniversalAuthClientSecretsTable.tsx index b034b5367..017f30719 100644 --- a/frontend/src/pages/organization/IdentityDetailsByIDPage/components/ViewIdentityAuthModal/IdentityUniversalAuthClientSecretsTable.tsx +++ b/frontend/src/pages/organization/IdentityDetailsByIDPage/components/ViewIdentityAuthModal/IdentityUniversalAuthClientSecretsTable.tsx @@ -43,25 +43,17 @@ export const IdentityUniversalAuthClientSecretsTable = ({ clientSecrets, identit const { mutateAsync: revokeClientSecret } = useRevokeIdentityUniversalAuthClientSecret(); const onDeleteClientSecretSubmit = async (clientSecretId: string) => { - try { - await revokeClientSecret({ - identityId, - clientSecretId - }); + await revokeClientSecret({ + identityId, + clientSecretId + }); - handlePopUpToggle("revokeClientSecret", false); + handlePopUpToggle("revokeClientSecret", false); - createNotification({ - text: "Successfully deleted client secret", - type: "success" - }); - } catch (err) { - console.error(err); - createNotification({ - text: "Failed to delete client secret", - type: "error" - }); - } + createNotification({ + text: "Successfully deleted client secret", + type: "success" + }); }; return ( diff --git a/frontend/src/pages/organization/IdentityDetailsByIDPage/components/ViewIdentityAuthModal/ViewIdentityAuthModal.tsx b/frontend/src/pages/organization/IdentityDetailsByIDPage/components/ViewIdentityAuthModal/ViewIdentityAuthModal.tsx index f95a20789..09fc9f67e 100644 --- a/frontend/src/pages/organization/IdentityDetailsByIDPage/components/ViewIdentityAuthModal/ViewIdentityAuthModal.tsx +++ b/frontend/src/pages/organization/IdentityDetailsByIDPage/components/ViewIdentityAuthModal/ViewIdentityAuthModal.tsx @@ -140,25 +140,17 @@ export const Content = ({ } const handleDeleteAuthMethod = async () => { - try { - await revokeMethod({ - identityId, - organizationId: orgId - }); + await revokeMethod({ + identityId, + organizationId: orgId + }); - createNotification({ - text: "Successfully removed auth method", - type: "success" - }); - - handlePopUpToggle("revokeAuthMethod", false); - onDeleteAuthMethod(); - } catch { - createNotification({ - text: "Failed to remove auth method", - type: "error" - }); - } + createNotification({ + text: "Successfully removed auth method", + type: "success" + }); + handlePopUpToggle("revokeAuthMethod", false); + onDeleteAuthMethod(); }; return ( diff --git a/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/components/GatewayCliDeploymentMethod.tsx b/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/components/GatewayCliDeploymentMethod.tsx index 7537d95a3..8e69e7c0a 100644 --- a/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/components/GatewayCliDeploymentMethod.tsx +++ b/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/components/GatewayCliDeploymentMethod.tsx @@ -168,12 +168,7 @@ export const GatewayCliDeploymentMethod = () => { type: "info" }); setStep("command"); - } catch (err) { - console.error(err); - createNotification({ - text: "Failed to generate token for the selected identity", - type: "error" - }); + } catch { setIdentityToken(""); } } else { diff --git a/frontend/src/pages/organization/NetworkingPage/components/RelayTab/components/RelayCliDeploymentMethod.tsx b/frontend/src/pages/organization/NetworkingPage/components/RelayTab/components/RelayCliDeploymentMethod.tsx index 1d89e9877..f41f8204b 100644 --- a/frontend/src/pages/organization/NetworkingPage/components/RelayTab/components/RelayCliDeploymentMethod.tsx +++ b/frontend/src/pages/organization/NetworkingPage/components/RelayTab/components/RelayCliDeploymentMethod.tsx @@ -141,12 +141,7 @@ export const RelayCliDeploymentMethod = () => { type: "info" }); setStep("command"); - } catch (err) { - console.error(err); - createNotification({ - text: "Failed to generate token for the selected identity", - type: "error" - }); + } catch { setIdentityToken(""); } } else { diff --git a/frontend/src/pages/organization/ProjectsPage/components/AllProjectView.tsx b/frontend/src/pages/organization/ProjectsPage/components/AllProjectView.tsx index cf60ffa59..a1bd8c9e4 100644 --- a/frontend/src/pages/organization/ProjectsPage/components/AllProjectView.tsx +++ b/frontend/src/pages/organization/ProjectsPage/components/AllProjectView.tsx @@ -13,7 +13,6 @@ import { useNavigate } from "@tanstack/react-router"; import { CheckIcon } from "lucide-react"; import { twMerge } from "tailwind-merge"; -import { createNotification } from "@app/components/notifications"; import { OrgPermissionCan } from "@app/components/permissions"; import { RequestProjectAccessModal } from "@app/components/projects/RequestProjectAccessModal"; import { @@ -103,22 +102,15 @@ export const AllProjectView = ({ projectId: string, environments: ProjectEnv[] ) => { - try { - await orgAdminAccessProject.mutateAsync({ + await orgAdminAccessProject.mutateAsync({ + projectId + }); + await navigate({ + to: getProjectHomePage(type, environments), + params: { projectId - }); - await navigate({ - to: getProjectHomePage(type, environments), - params: { - projectId - } - }); - } catch { - createNotification({ - text: "Failed to access project", - type: "error" - }); - } + } + }); }; useResetPageHelper({ diff --git a/frontend/src/pages/organization/ProjectsPage/components/MyProjectView.tsx b/frontend/src/pages/organization/ProjectsPage/components/MyProjectView.tsx index a86023b6c..32301923b 100644 --- a/frontend/src/pages/organization/ProjectsPage/components/MyProjectView.tsx +++ b/frontend/src/pages/organization/ProjectsPage/components/MyProjectView.tsx @@ -15,7 +15,6 @@ import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { useNavigate } from "@tanstack/react-router"; import { twMerge } from "tailwind-merge"; -import { createNotification } from "@app/components/notifications"; import { OrgPermissionCan } from "@app/components/permissions"; import { Button, @@ -158,32 +157,18 @@ export const MyProjectView = ({ }; const addProjectToFavorites = async (projectId: string) => { - try { - if (currentOrg?.id) { - await updateUserProjectFavorites({ - orgId: currentOrg?.id, - projectFavorites: [...(projectFavorites || []), projectId] - }); - } - } catch { - createNotification({ - text: "Failed to add project to favorites.", - type: "error" + if (currentOrg?.id) { + await updateUserProjectFavorites({ + orgId: currentOrg?.id, + projectFavorites: [...(projectFavorites || []), projectId] }); } }; const removeProjectFromFavorites = async (projectId: string) => { - try { - if (currentOrg?.id) { - await updateUserProjectFavorites({ - orgId: currentOrg?.id, - projectFavorites: [...(projectFavorites || []).filter((entry) => entry !== projectId)] - }); - } - } catch { - createNotification({ - text: "Failed to remove project from favorites.", - type: "error" + if (currentOrg?.id) { + await updateUserProjectFavorites({ + orgId: currentOrg?.id, + projectFavorites: [...(projectFavorites || []).filter((entry) => entry !== projectId)] }); } }; diff --git a/frontend/src/pages/organization/RoleByIDPage/RoleByIDPage.tsx b/frontend/src/pages/organization/RoleByIDPage/RoleByIDPage.tsx index 0d30dd2f8..78c5393a7 100644 --- a/frontend/src/pages/organization/RoleByIDPage/RoleByIDPage.tsx +++ b/frontend/src/pages/organization/RoleByIDPage/RoleByIDPage.tsx @@ -42,36 +42,25 @@ export const Page = () => { ] as const); const onDeleteOrgRoleSubmit = async () => { - try { - if (!orgId || !roleId) return; + if (!orgId || !roleId) return; - await deleteOrgRole({ - orgId, - id: roleId - }); + await deleteOrgRole({ + orgId, + id: roleId + }); - createNotification({ - text: "Successfully deleted organization role", - type: "success" - }); + createNotification({ + text: "Successfully deleted organization role", + type: "success" + }); - handlePopUpClose("deleteOrgRole"); - navigate({ - to: "/organization/access-management" as const, - search: { - selectedTab: OrgAccessControlTabSections.Roles - } - }); - } catch (err) { - console.error(err); - const error = err as any; - const text = error?.response?.data?.message ?? "Failed to delete organization role"; - - createNotification({ - text, - type: "error" - }); - } + handlePopUpClose("deleteOrgRole"); + navigate({ + to: "/organization/access-management" as const, + search: { + selectedTab: OrgAccessControlTabSections.Roles + } + }); }; const isCustomRole = !["admin", "member", "no-access"].includes(data?.slug ?? ""); diff --git a/frontend/src/pages/organization/RoleByIDPage/components/RoleModal.tsx b/frontend/src/pages/organization/RoleByIDPage/components/RoleModal.tsx index 88f568c4a..73da4f161 100644 --- a/frontend/src/pages/organization/RoleByIDPage/components/RoleModal.tsx +++ b/frontend/src/pages/organization/RoleByIDPage/components/RoleModal.tsx @@ -70,55 +70,46 @@ export const RoleModal = ({ popUp, handlePopUpToggle }: Props) => { }, [role]); const onFormSubmit = async ({ name, description, slug }: FormData) => { - try { - if (!orgId) return; + if (!orgId) return; - if (role) { - // update + if (role) { + // update - await updateOrgRole({ - orgId, - id: role.id, - name, - description, - slug - }); - - handlePopUpToggle("role", false); - } else { - // create - - const newRole = await createOrgRole({ - orgId, - name, - description, - slug, - permissions: [] - }); - - handlePopUpToggle("role", false); - navigate({ - to: "/organization/roles/$roleId", - params: { - roleId: newRole.id - } - }); - } - - createNotification({ - text: `Successfully ${popUp?.role?.data ? "updated" : "created"} role`, - type: "success" + await updateOrgRole({ + orgId, + id: role.id, + name, + description, + slug }); - reset(); - } catch { - const text = `Failed to ${popUp?.role?.data ? "update" : "create"} role`; + handlePopUpToggle("role", false); + } else { + // create - createNotification({ - text, - type: "error" + const newRole = await createOrgRole({ + orgId, + name, + description, + slug, + permissions: [] + }); + + handlePopUpToggle("role", false); + navigate({ + to: "/organization/roles/$roleId", + params: { + roleId: newRole.id + } }); } + + createNotification({ + text: `Successfully ${popUp?.role?.data ? "updated" : "created"} role`, + type: "success" + }); + + reset(); }; return ( diff --git a/frontend/src/pages/organization/SecretSharingPage/components/RequestSecret/RequestSecretForm.tsx b/frontend/src/pages/organization/SecretSharingPage/components/RequestSecret/RequestSecretForm.tsx index 50a9e0f58..d50873339 100644 --- a/frontend/src/pages/organization/SecretSharingPage/components/RequestSecret/RequestSecretForm.tsx +++ b/frontend/src/pages/organization/SecretSharingPage/components/RequestSecret/RequestSecretForm.tsx @@ -56,35 +56,27 @@ export const RequestSecretForm = () => { const onFormSubmit = async ({ name, accessType, expiresIn }: FormData) => { const expiresAt = new Date(new Date().getTime() + Number(expiresIn)); - try { - const { id } = await createSecretRequest({ - name, - accessType, - expiresAt - }); + const { id } = await createSecretRequest({ + name, + accessType, + expiresAt + }); - const link = new URL(`${window.location.origin}/secret-request/secret/${id}`); - if (subOrganization) { - link.searchParams.set("subOrganization", subOrganization); - } - - setSecretLink(link.toString()); - reset(); - - navigator.clipboard.writeText(link.toString()); - setCopyTextSecret("secret"); - - createNotification({ - text: "Shared secret link copied to clipboard.", - type: "success" - }); - } catch (error) { - console.error(error); - createNotification({ - text: "Failed to create a shared secret.", - type: "error" - }); + const link = new URL(`${window.location.origin}/secret-request/secret/${id}`); + if (subOrganization) { + link.searchParams.set("subOrganization", subOrganization); } + + setSecretLink(link.toString()); + reset(); + + navigator.clipboard.writeText(link.toString()); + setCopyTextSecret("secret"); + + createNotification({ + text: "Shared secret link copied to clipboard.", + type: "success" + }); }; const hasSecretLink = Boolean(secretLink); diff --git a/frontend/src/pages/organization/SecretSharingPage/components/RequestSecret/RequestSecretTab.tsx b/frontend/src/pages/organization/SecretSharingPage/components/RequestSecret/RequestSecretTab.tsx index fd3b1d5b5..1253cdbc0 100644 --- a/frontend/src/pages/organization/SecretSharingPage/components/RequestSecret/RequestSecretTab.tsx +++ b/frontend/src/pages/organization/SecretSharingPage/components/RequestSecret/RequestSecretTab.tsx @@ -22,23 +22,15 @@ export const RequestSecretTab = () => { const { mutateAsync: deleteSecretRequest } = useDeleteSecretRequest(); const onDeleteApproved = async () => { - try { - await deleteSecretRequest({ - secretRequestId: popUp.deleteSecretRequestConfirmation.data?.id - }); - createNotification({ - text: "Successfully deleted secret request", - type: "success" - }); + await deleteSecretRequest({ + secretRequestId: popUp.deleteSecretRequestConfirmation.data?.id + }); + createNotification({ + text: "Successfully deleted secret request", + type: "success" + }); - handlePopUpClose("deleteSecretRequestConfirmation"); - } catch (err) { - console.error(err); - createNotification({ - text: "Failed to delete shared secret", - type: "error" - }); - } + handlePopUpClose("deleteSecretRequestConfirmation"); }; return ( diff --git a/frontend/src/pages/organization/SecretSharingPage/components/SecretSharingSettings/OrgSecretShareLimitSection.tsx b/frontend/src/pages/organization/SecretSharingPage/components/SecretSharingSettings/OrgSecretShareLimitSection.tsx index 034c7d8fe..d7c337332 100644 --- a/frontend/src/pages/organization/SecretSharingPage/components/SecretSharingSettings/OrgSecretShareLimitSection.tsx +++ b/frontend/src/pages/organization/SecretSharingPage/components/SecretSharingSettings/OrgSecretShareLimitSection.tsx @@ -90,28 +90,21 @@ export const OrgSecretShareLimitSection = () => { }, [currentOrg, reset]); const handleFormSubmit = async (formData: TForm) => { - try { - const maxSharedSecretLifetimeSeconds = - ms(`${formData.maxLifetimeValue}${formData.maxLifetimeUnit}`) / 1000; + const maxSharedSecretLifetimeSeconds = + ms(`${formData.maxLifetimeValue}${formData.maxLifetimeUnit}`) / 1000; - await mutateAsync({ - orgId: currentOrg.id, - maxSharedSecretViewLimit: formData.shouldLimitView ? Number(formData.maxViewLimit) : null, - maxSharedSecretLifetime: maxSharedSecretLifetimeSeconds - }); + await mutateAsync({ + orgId: currentOrg.id, + maxSharedSecretViewLimit: formData.shouldLimitView ? Number(formData.maxViewLimit) : null, + maxSharedSecretLifetime: maxSharedSecretLifetimeSeconds + }); - createNotification({ - text: "Successfully updated secret share limits", - type: "success" - }); + createNotification({ + text: "Successfully updated secret share limits", + type: "success" + }); - reset(formData); - } catch { - createNotification({ - text: "Failed to update secret share limits", - type: "error" - }); - } + reset(formData); }; // Units for the dropdown with readable labels diff --git a/frontend/src/pages/organization/SecretSharingPage/components/SecretSharingSettings/SecretSharingAllowShareToAnyone.tsx b/frontend/src/pages/organization/SecretSharingPage/components/SecretSharingSettings/SecretSharingAllowShareToAnyone.tsx index 1ea62c187..31b2221ce 100644 --- a/frontend/src/pages/organization/SecretSharingPage/components/SecretSharingSettings/SecretSharingAllowShareToAnyone.tsx +++ b/frontend/src/pages/organization/SecretSharingPage/components/SecretSharingSettings/SecretSharingAllowShareToAnyone.tsx @@ -9,25 +9,17 @@ export const SecretSharingAllowShareToAnyone = () => { const { mutateAsync } = useUpdateOrg(); const handleSecretSharingToggle = async (value: boolean) => { - try { - if (!currentOrg?.id) return; + if (!currentOrg?.id) return; - await mutateAsync({ - orgId: currentOrg.id, - allowSecretSharingOutsideOrganization: value - }); + await mutateAsync({ + orgId: currentOrg.id, + allowSecretSharingOutsideOrganization: value + }); - createNotification({ - text: `Successfully ${value ? "enabled" : "disabled"} secret sharing to members outside of this organization`, - type: "success" - }); - } catch (err) { - console.error(err); - createNotification({ - text: (err as { response: { data: { message: string } } }).response.data.message, - type: "error" - }); - } + createNotification({ + text: `Successfully ${value ? "enabled" : "disabled"} secret sharing to members outside of this organization`, + type: "success" + }); }; return ( diff --git a/frontend/src/pages/organization/SecretSharingPage/components/ShareSecret/ShareSecretTab.tsx b/frontend/src/pages/organization/SecretSharingPage/components/ShareSecret/ShareSecretTab.tsx index d4f2f0a1f..2ea61ca98 100644 --- a/frontend/src/pages/organization/SecretSharingPage/components/ShareSecret/ShareSecretTab.tsx +++ b/frontend/src/pages/organization/SecretSharingPage/components/ShareSecret/ShareSecretTab.tsx @@ -20,23 +20,15 @@ export const ShareSecretTab = () => { const deleteSecretShare = useDeleteSharedSecret(); const onDeleteApproved = async () => { - try { - deleteSecretShare.mutateAsync({ - sharedSecretId: (popUp?.deleteSharedSecretConfirmation?.data as DeleteModalData)?.id - }); - createNotification({ - text: "Successfully deleted shared secret", - type: "success" - }); + deleteSecretShare.mutateAsync({ + sharedSecretId: (popUp?.deleteSharedSecretConfirmation?.data as DeleteModalData)?.id + }); + createNotification({ + text: "Successfully deleted shared secret", + type: "success" + }); - handlePopUpClose("deleteSharedSecretConfirmation"); - } catch (err) { - console.error(err); - createNotification({ - text: "Failed to delete shared secret", - type: "error" - }); - } + handlePopUpClose("deleteSharedSecretConfirmation"); }; return ( diff --git a/frontend/src/pages/organization/SettingsPage/components/AuditLogStreamTab/AuditLogStreamForm/AuditLogStreamForm.tsx b/frontend/src/pages/organization/SettingsPage/components/AuditLogStreamTab/AuditLogStreamForm/AuditLogStreamForm.tsx index f59ae23aa..5ea16050a 100644 --- a/frontend/src/pages/organization/SettingsPage/components/AuditLogStreamTab/AuditLogStreamForm/AuditLogStreamForm.tsx +++ b/frontend/src/pages/organization/SettingsPage/components/AuditLogStreamTab/AuditLogStreamForm/AuditLogStreamForm.tsx @@ -28,21 +28,12 @@ const CreateForm = ({ provider, onComplete }: CreateFormProps) => { const onSubmit = async ( formData: DiscriminativePick ) => { - try { - const logStream = await createAuditLogStream.mutateAsync(formData); - createNotification({ - text: `Successfully created ${providerName} Log Stream`, - type: "success" - }); - onComplete(logStream); - } catch (err: any) { - console.error(err); - createNotification({ - title: `Failed to create ${providerName} Log Stream`, - text: err.message, - type: "error" - }); - } + const logStream = await createAuditLogStream.mutateAsync(formData); + createNotification({ + text: `Successfully created ${providerName} Log Stream`, + type: "success" + }); + onComplete(logStream); }; switch (provider) { @@ -68,24 +59,15 @@ const UpdateForm = ({ auditLogStream, onComplete }: UpdateFormProps) => { const onSubmit = async ( formData: DiscriminativePick ) => { - try { - const connection = await updateAuditLogStream.mutateAsync({ - auditLogStreamId: auditLogStream.id, - ...formData - }); - createNotification({ - text: `Successfully updated ${providerName} Log Stream`, - type: "success" - }); - onComplete(connection); - } catch (err: any) { - console.error(err); - createNotification({ - title: `Failed to update ${providerName} Log Stream`, - text: err.message, - type: "error" - }); - } + const connection = await updateAuditLogStream.mutateAsync({ + auditLogStreamId: auditLogStream.id, + ...formData + }); + createNotification({ + text: `Successfully updated ${providerName} Log Stream`, + type: "success" + }); + onComplete(connection); }; switch (auditLogStream.provider) { diff --git a/frontend/src/pages/organization/SettingsPage/components/AuditLogStreamTab/components/DeleteAuditLogStreamModal.tsx b/frontend/src/pages/organization/SettingsPage/components/AuditLogStreamTab/components/DeleteAuditLogStreamModal.tsx index 1a65e6c67..74eb19af3 100644 --- a/frontend/src/pages/organization/SettingsPage/components/AuditLogStreamTab/components/DeleteAuditLogStreamModal.tsx +++ b/frontend/src/pages/organization/SettingsPage/components/AuditLogStreamTab/components/DeleteAuditLogStreamModal.tsx @@ -20,26 +20,17 @@ export const DeleteAuditLogStreamModal = ({ isOpen, onOpenChange, auditLogStream const providerDetails = AUDIT_LOG_STREAM_PROVIDER_MAP[provider]; const handleDelete = async () => { - try { - await deleteAuditLogStream.mutateAsync({ - auditLogStreamId, - provider - }); + await deleteAuditLogStream.mutateAsync({ + auditLogStreamId, + provider + }); - createNotification({ - text: `Successfully deleted ${providerDetails.name} stream`, - type: "success" - }); + createNotification({ + text: `Successfully deleted ${providerDetails.name} stream`, + type: "success" + }); - onOpenChange(false); - } catch (err) { - console.error(err); - - createNotification({ - text: `Failed to delete ${providerDetails.name} stream`, - type: "error" - }); - } + onOpenChange(false); }; return ( diff --git a/frontend/src/pages/organization/SettingsPage/components/ExternalMigrationsTab/components/VaultConnectionSection.tsx b/frontend/src/pages/organization/SettingsPage/components/ExternalMigrationsTab/components/VaultConnectionSection.tsx index c91e9c24c..e802e250b 100644 --- a/frontend/src/pages/organization/SettingsPage/components/ExternalMigrationsTab/components/VaultConnectionSection.tsx +++ b/frontend/src/pages/organization/SettingsPage/components/ExternalMigrationsTab/components/VaultConnectionSection.tsx @@ -54,21 +54,13 @@ export const VaultConnectionSection = () => { const handleDeleteConfirm = async () => { if (!configToDelete) return; - try { - await deleteConfig({ id: configToDelete.id }); - createNotification({ - type: "success", - text: "Namespace configuration deleted successfully" - }); - setIsDeleteModalOpen(false); - setConfigToDelete(null); - } catch (error) { - console.error("Failed to delete namespace config:", error); - createNotification({ - type: "error", - text: "Failed to delete namespace configuration" - }); - } + await deleteConfig({ id: configToDelete.id }); + createNotification({ + type: "success", + text: "Namespace configuration deleted successfully" + }); + setIsDeleteModalOpen(false); + setConfigToDelete(null); }; const getConnectionName = (connectionId: string | null) => { diff --git a/frontend/src/pages/organization/SettingsPage/components/ExternalMigrationsTab/components/VaultNamespaceConfigModal.tsx b/frontend/src/pages/organization/SettingsPage/components/ExternalMigrationsTab/components/VaultNamespaceConfigModal.tsx index 62fb78b48..f08aae204 100644 --- a/frontend/src/pages/organization/SettingsPage/components/ExternalMigrationsTab/components/VaultNamespaceConfigModal.tsx +++ b/frontend/src/pages/organization/SettingsPage/components/ExternalMigrationsTab/components/VaultNamespaceConfigModal.tsx @@ -74,36 +74,28 @@ export const VaultNamespaceConfigModal = ({ isOpen, onOpenChange, editConfig }: }, [isOpen, editConfig, reset]); const onFormSubmit = async (data: FormData) => { - try { - if (isEdit && editConfig) { - await updateConfig({ - id: editConfig.id, - namespace: data.namespace, - connectionId: data.connectionId - }); - createNotification({ - type: "success", - text: "Namespace configuration updated successfully" - }); - } else { - await createConfig({ - namespace: data.namespace, - connectionId: data.connectionId - }); - createNotification({ - type: "success", - text: "Namespace configuration created successfully" - }); - } - reset(); - onOpenChange(false); - } catch (error) { - console.error("Failed to save namespace config:", error); + if (isEdit && editConfig) { + await updateConfig({ + id: editConfig.id, + namespace: data.namespace, + connectionId: data.connectionId + }); createNotification({ - type: "error", - text: `Failed to ${isEdit ? "update" : "create"} namespace configuration` + type: "success", + text: "Namespace configuration updated successfully" + }); + } else { + await createConfig({ + namespace: data.namespace, + connectionId: data.connectionId + }); + createNotification({ + type: "success", + text: "Namespace configuration created successfully" }); } + reset(); + onOpenChange(false); }; const handleClose = () => { diff --git a/frontend/src/pages/organization/SettingsPage/components/OrgDeleteSection/OrgDeleteSection.tsx b/frontend/src/pages/organization/SettingsPage/components/OrgDeleteSection/OrgDeleteSection.tsx index 4dfe89f71..6e5c0e1cb 100644 --- a/frontend/src/pages/organization/SettingsPage/components/OrgDeleteSection/OrgDeleteSection.tsx +++ b/frontend/src/pages/organization/SettingsPage/components/OrgDeleteSection/OrgDeleteSection.tsx @@ -19,27 +19,19 @@ export const OrgDeleteSection = () => { const { mutateAsync, isPending } = useDeleteOrgById(); const handleDeleteOrgSubmit = async () => { - try { - if (!currentOrg?.id) return; + if (!currentOrg?.id) return; - await mutateAsync({ - organizationId: currentOrg?.id - }); + await mutateAsync({ + organizationId: currentOrg?.id + }); - createNotification({ - text: "Successfully deleted organization", - type: "success" - }); + createNotification({ + text: "Successfully deleted organization", + type: "success" + }); - clearSession(); - navigate({ to: "/login" }); - } catch (err) { - console.error(err); - createNotification({ - text: "Failed to delete organization", - type: "error" - }); - } + clearSession(); + navigate({ to: "/login" }); }; return ( diff --git a/frontend/src/pages/organization/SettingsPage/components/OrgEncryptionTab/OrgEncryptionTab.tsx b/frontend/src/pages/organization/SettingsPage/components/OrgEncryptionTab/OrgEncryptionTab.tsx index a0b09b573..3fcf71e62 100644 --- a/frontend/src/pages/organization/SettingsPage/components/OrgEncryptionTab/OrgEncryptionTab.tsx +++ b/frontend/src/pages/organization/SettingsPage/components/OrgEncryptionTab/OrgEncryptionTab.tsx @@ -51,18 +51,14 @@ export const OrgEncryptionTab = withPermission( kmsId: string; }; - try { - await removeExternalKms(kmsId); + await removeExternalKms(kmsId); - createNotification({ - text: "Successfully deleted external KMS", - type: "success" - }); + createNotification({ + text: "Successfully deleted external KMS", + type: "success" + }); - handlePopUpToggle("removeExternalKms", false); - } catch (err) { - console.error(err); - } + handlePopUpToggle("removeExternalKms", false); }; return ( diff --git a/frontend/src/pages/organization/SettingsPage/components/OrgIncidentContactsSection/AddOrgIncidentContactModal.tsx b/frontend/src/pages/organization/SettingsPage/components/OrgIncidentContactsSection/AddOrgIncidentContactModal.tsx index 84bb083ec..125a3f310 100644 --- a/frontend/src/pages/organization/SettingsPage/components/OrgIncidentContactsSection/AddOrgIncidentContactModal.tsx +++ b/frontend/src/pages/organization/SettingsPage/components/OrgIncidentContactsSection/AddOrgIncidentContactModal.tsx @@ -35,31 +35,23 @@ export const AddOrgIncidentContactModal = ({ const { mutateAsync, isPending } = useAddIncidentContact(); const onFormSubmit = async ({ email }: TAddContactForm) => { - try { - if (!currentOrg?.id) return; + if (!currentOrg?.id) return; - await mutateAsync({ - orgId: currentOrg.id, - email - }); + await mutateAsync({ + orgId: currentOrg.id, + email + }); - createNotification({ - text: "Successfully added incident contact", - type: "success" - }); + createNotification({ + text: "Successfully added incident contact", + type: "success" + }); - if (serverDetails?.emailConfigured) { - handlePopUpClose("addContact"); - } - - reset(); - } catch (err) { - console.error(err); - createNotification({ - text: "Failed to add incident contact", - type: "error" - }); + if (serverDetails?.emailConfigured) { + handlePopUpClose("addContact"); } + + reset(); }; return ( diff --git a/frontend/src/pages/organization/SettingsPage/components/OrgIncidentContactsSection/OrgIncidentContactsTable.tsx b/frontend/src/pages/organization/SettingsPage/components/OrgIncidentContactsSection/OrgIncidentContactsTable.tsx index d0723fdaf..c16431b9c 100644 --- a/frontend/src/pages/organization/SettingsPage/components/OrgIncidentContactsSection/OrgIncidentContactsTable.tsx +++ b/frontend/src/pages/organization/SettingsPage/components/OrgIncidentContactsSection/OrgIncidentContactsTable.tsx @@ -33,28 +33,20 @@ export const OrgIncidentContactsTable = () => { const { mutateAsync } = useDeleteIncidentContact(); const onRemoveIncidentContact = async () => { - try { - const incidentContactId = (popUp?.removeContact?.data as { id: string })?.id; + const incidentContactId = (popUp?.removeContact?.data as { id: string })?.id; - if (!currentOrg?.id) return; - await mutateAsync({ - orgId: currentOrg.id, - incidentContactId - }); + if (!currentOrg?.id) return; + await mutateAsync({ + orgId: currentOrg.id, + incidentContactId + }); - createNotification({ - text: "Successfully removed incident contact", - type: "success" - }); + createNotification({ + text: "Successfully removed incident contact", + type: "success" + }); - handlePopUpClose("removeContact"); - } catch (err) { - console.error(err); - createNotification({ - text: "Failed to remove incident contact", - type: "error" - }); - } + handlePopUpClose("removeContact"); }; const filteredContacts = contacts diff --git a/frontend/src/pages/organization/SettingsPage/components/OrgNameChangeSection/OrgNameChangeSection.tsx b/frontend/src/pages/organization/SettingsPage/components/OrgNameChangeSection/OrgNameChangeSection.tsx index 766a22158..03fb14dc7 100644 --- a/frontend/src/pages/organization/SettingsPage/components/OrgNameChangeSection/OrgNameChangeSection.tsx +++ b/frontend/src/pages/organization/SettingsPage/components/OrgNameChangeSection/OrgNameChangeSection.tsx @@ -56,27 +56,19 @@ export const OrgNameChangeSection = (): JSX.Element => { }, [roles]); const onFormSubmit = async ({ name, slug, defaultMembershipRole }: FormData) => { - try { - if (!currentOrg?.id || !roles?.length) return; + if (!currentOrg?.id || !roles?.length) return; - await mutateAsync({ - orgId: currentOrg?.id, - name, - slug, - defaultMembershipRoleSlug: defaultMembershipRole - }); + await mutateAsync({ + orgId: currentOrg?.id, + name, + slug, + defaultMembershipRoleSlug: defaultMembershipRole + }); - createNotification({ - text: "Successfully updated organization details", - type: "success" - }); - } catch (error) { - console.error(error); - createNotification({ - text: "Failed to update organization details", - type: "error" - }); - } + createNotification({ + text: "Successfully updated organization details", + type: "success" + }); }; if (!isFormInitialized) { diff --git a/frontend/src/pages/organization/SettingsPage/components/OrgNameChangeSection/SubOrgNameChangeSection.tsx b/frontend/src/pages/organization/SettingsPage/components/OrgNameChangeSection/SubOrgNameChangeSection.tsx index ca625be6c..e08d4d1b5 100644 --- a/frontend/src/pages/organization/SettingsPage/components/OrgNameChangeSection/SubOrgNameChangeSection.tsx +++ b/frontend/src/pages/organization/SettingsPage/components/OrgNameChangeSection/SubOrgNameChangeSection.tsx @@ -39,26 +39,18 @@ export const SubOrgNameChangeSection = (): JSX.Element => { const { mutateAsync, isPending } = useUpdateSubOrganization(); const onFormSubmit = async ({ name }: FormData) => { - try { - await mutateAsync({ - name, - subOrgId: currentOrg.id - }); + await mutateAsync({ + name, + subOrgId: currentOrg.id + }); - navigate({ to: "/organization/settings", search: { subOrganization: name } }); - queryClient.invalidateQueries(); - await router.invalidate({ sync: true }); - createNotification({ - text: "Successfully updated sub-organization details", - type: "success" - }); - } catch (error) { - console.error(error); - createNotification({ - text: "Failed to update sub-organization details", - type: "error" - }); - } + navigate({ to: "/organization/settings", search: { subOrganization: name } }); + queryClient.invalidateQueries(); + await router.invalidate({ sync: true }); + createNotification({ + text: "Successfully updated sub-organization details", + type: "success" + }); }; return ( diff --git a/frontend/src/pages/organization/SettingsPage/components/OrgProductSelectSection/OrgProductSelectSection.tsx b/frontend/src/pages/organization/SettingsPage/components/OrgProductSelectSection/OrgProductSelectSection.tsx index 5be15edad..e1fc2712d 100644 --- a/frontend/src/pages/organization/SettingsPage/components/OrgProductSelectSection/OrgProductSelectSection.tsx +++ b/frontend/src/pages/organization/SettingsPage/components/OrgProductSelectSection/OrgProductSelectSection.tsx @@ -1,7 +1,5 @@ import { useEffect, useState } from "react"; -import axios from "axios"; -import { createNotification } from "@app/components/notifications"; import { Switch } from "@app/components/v2"; import { useOrganization } from "@app/context"; import { useUpdateOrg } from "@app/hooks/api"; @@ -60,20 +58,10 @@ export const OrgProductSelectSection = () => { [key]: { ...products[key], enabled: value } })); - try { - await mutateAsync({ - orgId: currentOrg.id, - [key]: value - }); - } catch (e) { - if (axios.isAxiosError(e)) { - const { message = "Something went wrong" } = e.response?.data as { message: string }; - createNotification({ - type: "error", - text: message - }); - } - } + await mutateAsync({ + orgId: currentOrg.id, + [key]: value + }); setIsLoading(false); }; diff --git a/frontend/src/pages/organization/SettingsPage/components/OrgProductSettingsTab/OrgProductSettingsTab.tsx b/frontend/src/pages/organization/SettingsPage/components/OrgProductSettingsTab/OrgProductSettingsTab.tsx index e4d935996..95cc7b870 100644 --- a/frontend/src/pages/organization/SettingsPage/components/OrgProductSettingsTab/OrgProductSettingsTab.tsx +++ b/frontend/src/pages/organization/SettingsPage/components/OrgProductSettingsTab/OrgProductSettingsTab.tsx @@ -30,12 +30,6 @@ export const OrgProductSettingsTab = () => { text: `Successfully ${state ? "enabled" : "disabled"} blocking duplicate secret sync destinations for this organization`, type: "success" }); - } catch (err) { - console.error(err); - createNotification({ - text: "Failed to update blocking duplicate secret sync destinations setting for this organization", - type: "error" - }); } finally { setIsLoading(false); } diff --git a/frontend/src/pages/organization/SettingsPage/components/OrgProvisioningTab/ExternalGroupOrgRoleMappings.tsx b/frontend/src/pages/organization/SettingsPage/components/OrgProvisioningTab/ExternalGroupOrgRoleMappings.tsx index 8e181e8c4..bc9a02921 100644 --- a/frontend/src/pages/organization/SettingsPage/components/OrgProvisioningTab/ExternalGroupOrgRoleMappings.tsx +++ b/frontend/src/pages/organization/SettingsPage/components/OrgProvisioningTab/ExternalGroupOrgRoleMappings.tsx @@ -75,19 +75,11 @@ export const ExternalGroupOrgRoleMappings = () => { const mappingField = useFieldArray({ control, name: "mappings" }); const handleUpdateMappings = async (form: TForm) => { - try { - await updateMappings.mutateAsync(form); - createNotification({ - text: "Group organization role mappings updated.", - type: "success" - }); - } catch (e) { - console.error(e); - createNotification({ - text: "Failed to update group organization role mappings.", - type: "error" - }); - } + await updateMappings.mutateAsync(form); + createNotification({ + text: "Group organization role mappings updated.", + type: "success" + }); }; const disableScimEdit = permission.cannot(OrgPermissionActions.Edit, OrgPermissionSubjects.Scim); diff --git a/frontend/src/pages/organization/SettingsPage/components/OrgSsoTab/LDAPModal.tsx b/frontend/src/pages/organization/SettingsPage/components/OrgSsoTab/LDAPModal.tsx index 580ecdeb1..b9ba7a2b6 100644 --- a/frontend/src/pages/organization/SettingsPage/components/OrgSsoTab/LDAPModal.tsx +++ b/frontend/src/pages/organization/SettingsPage/components/OrgSsoTab/LDAPModal.tsx @@ -122,53 +122,45 @@ export const LDAPModal = ({ popUp, handlePopUpClose, handlePopUpToggle, hideDele caCert, shouldCloseModal = true }: TLDAPFormData & { shouldCloseModal?: boolean }) => { - try { - if (!currentOrg) return; + if (!currentOrg) return; - if (!data) { - await createMutateAsync({ - organizationId: currentOrg.id, - isActive: false, - url, - bindDN, - bindPass, - searchBase, - searchFilter, - uniqueUserAttribute, - groupSearchBase, - groupSearchFilter, - caCert - }); - } else { - await updateMutateAsync({ - organizationId: currentOrg.id, - url, - bindDN, - bindPass, - searchBase, - searchFilter, - uniqueUserAttribute, - groupSearchBase, - groupSearchFilter, - caCert - }); - } - - if (shouldCloseModal) { - handlePopUpClose("addLDAP"); - } - - createNotification({ - text: `Successfully ${!data ? "added" : "updated"} LDAP configuration`, - type: "success" + if (!data) { + await createMutateAsync({ + organizationId: currentOrg.id, + isActive: false, + url, + bindDN, + bindPass, + searchBase, + searchFilter, + uniqueUserAttribute, + groupSearchBase, + groupSearchFilter, + caCert }); - } catch (err) { - console.error(err); - createNotification({ - text: `Failed to ${!data ? "add" : "update"} LDAP configuration`, - type: "error" + } else { + await updateMutateAsync({ + organizationId: currentOrg.id, + url, + bindDN, + bindPass, + searchBase, + searchFilter, + uniqueUserAttribute, + groupSearchBase, + groupSearchFilter, + caCert }); } + + if (shouldCloseModal) { + handlePopUpClose("addLDAP"); + } + + createNotification({ + text: `Successfully ${!data ? "added" : "updated"} LDAP configuration`, + type: "success" + }); }; const handleTestLDAPConnection = async () => { diff --git a/frontend/src/pages/organization/SettingsPage/components/OrgSsoTab/OIDCModal.tsx b/frontend/src/pages/organization/SettingsPage/components/OrgSsoTab/OIDCModal.tsx index 03f946ace..f980b2e4f 100644 --- a/frontend/src/pages/organization/SettingsPage/components/OrgSsoTab/OIDCModal.tsx +++ b/frontend/src/pages/organization/SettingsPage/components/OrgSsoTab/OIDCModal.tsx @@ -122,31 +122,24 @@ export const OIDCModal = ({ popUp, handlePopUpClose, handlePopUpToggle, hideDele if (!currentOrg) { return; } - try { - await updateMutateAsync({ - issuer: "", - discoveryURL: "", - authorizationEndpoint: "", - allowedEmailDomains: "", - jwksUri: "", - tokenEndpoint: "", - userinfoEndpoint: "", - clientId: "", - clientSecret: "", - isActive: false, - organizationId: currentOrg.id - }); + await updateMutateAsync({ + issuer: "", + discoveryURL: "", + authorizationEndpoint: "", + allowedEmailDomains: "", + jwksUri: "", + tokenEndpoint: "", + userinfoEndpoint: "", + clientId: "", + clientSecret: "", + isActive: false, + organizationId: currentOrg.id + }); - createNotification({ - text: "Successfully deleted OIDC configuration.", - type: "success" - }); - } catch { - createNotification({ - text: "Failed deleting OIDC configuration.", - type: "error" - }); - } + createNotification({ + text: "Successfully deleted OIDC configuration.", + type: "success" + }); }; useEffect(() => { @@ -178,58 +171,50 @@ export const OIDCModal = ({ popUp, handlePopUpClose, handlePopUpToggle, hideDele clientSecret, jwtSignatureAlgorithm }: OIDCFormData) => { - try { - if (!currentOrg) { - return; - } + if (!currentOrg) { + return; + } - if (!data) { - await createMutateAsync({ - issuer, - configurationType, - discoveryURL, - authorizationEndpoint, - allowedEmailDomains, - jwksUri, - tokenEndpoint, - userinfoEndpoint, - clientId, - clientSecret, - isActive: true, - organizationId: currentOrg.id, - jwtSignatureAlgorithm - }); - } else { - await updateMutateAsync({ - issuer, - configurationType, - discoveryURL, - authorizationEndpoint, - allowedEmailDomains, - jwksUri, - tokenEndpoint, - userinfoEndpoint, - clientId, - clientSecret, - isActive: true, - organizationId: currentOrg.id, - jwtSignatureAlgorithm - }); - } - - handlePopUpClose("addOIDC"); - - createNotification({ - text: `Successfully ${!data ? "added" : "updated"} OIDC SSO configuration`, - type: "success" + if (!data) { + await createMutateAsync({ + issuer, + configurationType, + discoveryURL, + authorizationEndpoint, + allowedEmailDomains, + jwksUri, + tokenEndpoint, + userinfoEndpoint, + clientId, + clientSecret, + isActive: true, + organizationId: currentOrg.id, + jwtSignatureAlgorithm }); - } catch (err) { - console.error(err); - createNotification({ - text: `Failed to ${!data ? "add" : "update"} OIDC SSO configuration`, - type: "error" + } else { + await updateMutateAsync({ + issuer, + configurationType, + discoveryURL, + authorizationEndpoint, + allowedEmailDomains, + jwksUri, + tokenEndpoint, + userinfoEndpoint, + clientId, + clientSecret, + isActive: true, + organizationId: currentOrg.id, + jwtSignatureAlgorithm }); } + + handlePopUpClose("addOIDC"); + + createNotification({ + text: `Successfully ${!data ? "added" : "updated"} OIDC SSO configuration`, + type: "success" + }); }; return ( diff --git a/frontend/src/pages/organization/SettingsPage/components/OrgSsoTab/SSOModal.tsx b/frontend/src/pages/organization/SettingsPage/components/OrgSsoTab/SSOModal.tsx index df5fca59f..558f37dcb 100644 --- a/frontend/src/pages/organization/SettingsPage/components/OrgSsoTab/SSOModal.tsx +++ b/frontend/src/pages/organization/SettingsPage/components/OrgSsoTab/SSOModal.tsx @@ -108,64 +108,49 @@ export const SSOModal = ({ popUp, handlePopUpClose, handlePopUpToggle, hideDelet if (!currentOrg) { return; } - try { - await updateMutateAsync({ - organizationId: currentOrg.id, - isActive: false, - entryPoint: "", - issuer: "", - cert: "" - }); + await updateMutateAsync({ + organizationId: currentOrg.id, + isActive: false, + entryPoint: "", + issuer: "", + cert: "" + }); - createNotification({ - text: "Successfully deleted SAML SSO configuration.", - type: "success" - }); - } catch { - createNotification({ - text: "Failed deleting SAML SSO configuration.", - type: "error" - }); - } + createNotification({ + text: "Successfully deleted SAML SSO configuration.", + type: "success" + }); }; const onSSOModalSubmit = async ({ authProvider, entryPoint, issuer, cert }: AddSSOFormData) => { - try { - if (!currentOrg) return; + if (!currentOrg) return; - if (!data) { - await createMutateAsync({ - organizationId: currentOrg.id, - authProvider, - isActive: false, - entryPoint, - issuer, - cert - }); - } else { - await updateMutateAsync({ - organizationId: currentOrg.id, - authProvider, - isActive: false, - entryPoint, - issuer, - cert - }); - } - - handlePopUpClose("addSSO"); - - createNotification({ - text: `Successfully ${!data ? "added" : "updated"} SAML SSO configuration`, - type: "success" + if (!data) { + await createMutateAsync({ + organizationId: currentOrg.id, + authProvider, + isActive: false, + entryPoint, + issuer, + cert }); - } catch (err) { - console.error(err); - createNotification({ - text: `Failed to ${!data ? "add" : "update"} SAML SSO configuration`, - type: "error" + } else { + await updateMutateAsync({ + organizationId: currentOrg.id, + authProvider, + isActive: false, + entryPoint, + issuer, + cert }); } + + handlePopUpClose("addSSO"); + + createNotification({ + text: `Successfully ${!data ? "added" : "updated"} SAML SSO configuration`, + type: "success" + }); }; const renderLabels = (authProvider: string) => { diff --git a/frontend/src/pages/project/AccessControlPage/components/GroupsTab/components/GroupsSection/GroupRoles.tsx b/frontend/src/pages/project/AccessControlPage/components/GroupsTab/components/GroupsSection/GroupRoles.tsx index 188c2ba7d..67e962cfc 100644 --- a/frontend/src/pages/project/AccessControlPage/components/GroupsTab/components/GroupsSection/GroupRoles.tsx +++ b/frontend/src/pages/project/AccessControlPage/components/GroupsTab/components/GroupsSection/GroupRoles.tsx @@ -253,18 +253,14 @@ const GroupRolesForm = ({ projectRoles, roles, groupId, onClose }: FormProps) => }; }); - try { - await updateGroupWorkspaceRole.mutateAsync({ - projectId: currentProject?.id || "", - groupId, - roles: selectedRoles - }); - createNotification({ text: "Successfully updated group role", type: "success" }); - onClose(); - setSearchRoles(""); - } catch { - createNotification({ text: "Failed to update group role", type: "error" }); - } + await updateGroupWorkspaceRole.mutateAsync({ + projectId: currentProject?.id || "", + groupId, + roles: selectedRoles + }); + createNotification({ text: "Successfully updated group role", type: "success" }); + onClose(); + setSearchRoles(""); }; return ( diff --git a/frontend/src/pages/project/AccessControlPage/components/ProjectRoleListTab/components/ProjectRoleList/ProjectRoleList.tsx b/frontend/src/pages/project/AccessControlPage/components/ProjectRoleListTab/components/ProjectRoleList/ProjectRoleList.tsx index fca53fa06..eeb29725f 100644 --- a/frontend/src/pages/project/AccessControlPage/components/ProjectRoleListTab/components/ProjectRoleList/ProjectRoleList.tsx +++ b/frontend/src/pages/project/AccessControlPage/components/ProjectRoleListTab/components/ProjectRoleList/ProjectRoleList.tsx @@ -77,17 +77,12 @@ export const ProjectRoleList = () => { const handleRoleDelete = async () => { const { id } = popUp?.deleteRole?.data as TProjectRole; - try { - await deleteRole({ - projectId, - id - }); - createNotification({ type: "success", text: "Successfully removed the role" }); - handlePopUpClose("deleteRole"); - } catch (err) { - console.log(err); - createNotification({ type: "error", text: "Failed to delete role" }); - } + await deleteRole({ + projectId, + id + }); + createNotification({ type: "success", text: "Successfully removed the role" }); + handlePopUpClose("deleteRole"); }; const { diff --git a/frontend/src/pages/project/IdentityDetailsByIDPage/components/IdentityProjectAdditionalPrivilegeSection/IdentityProjectAdditionalPrivilegeModifySection.tsx b/frontend/src/pages/project/IdentityDetailsByIDPage/components/IdentityProjectAdditionalPrivilegeSection/IdentityProjectAdditionalPrivilegeModifySection.tsx index a5d74271c..956c01d69 100644 --- a/frontend/src/pages/project/IdentityDetailsByIDPage/components/IdentityProjectAdditionalPrivilegeSection/IdentityProjectAdditionalPrivilegeModifySection.tsx +++ b/frontend/src/pages/project/IdentityDetailsByIDPage/components/IdentityProjectAdditionalPrivilegeSection/IdentityProjectAdditionalPrivilegeModifySection.tsx @@ -131,33 +131,28 @@ export const IdentityProjectAdditionalPrivilegeModifySection = ({ temporaryAccessStartTime: el.temporaryAccess.temporaryAccessStartTime }; - try { - if (isCreate) { - await createIdentityProjectAdditionalPrivilege({ - permissions: formRolePermission2API(el.permissions), - identityId, - projectId, - slug: el.slug || undefined, - type: accessType - }); - createNotification({ type: "success", text: "Successfully created privilege" }); - } else { - if (!projectId || !privilegeDetails?.id) return; - await updateIdentityProjectAdditionalPrivilege({ - privilegeId: privilegeDetails.id, - permissions: formRolePermission2API(el.permissions), - projectId, - identityId, - slug: el.slug || undefined, - type: accessType - }); - createNotification({ type: "success", text: "Successfully updated privilege" }); - } - onGoBack(); - } catch (err) { - console.log(err); - createNotification({ type: "error", text: "Failed to update privilege" }); + if (isCreate) { + await createIdentityProjectAdditionalPrivilege({ + permissions: formRolePermission2API(el.permissions), + identityId, + projectId, + slug: el.slug || undefined, + type: accessType + }); + createNotification({ type: "success", text: "Successfully created privilege" }); + } else { + if (!projectId || !privilegeDetails?.id) return; + await updateIdentityProjectAdditionalPrivilege({ + privilegeId: privilegeDetails.id, + permissions: formRolePermission2API(el.permissions), + projectId, + identityId, + slug: el.slug || undefined, + type: accessType + }); + createNotification({ type: "success", text: "Successfully updated privilege" }); } + onGoBack(); }; const privilegeTemporaryAccess = form.watch("temporaryAccess"); diff --git a/frontend/src/pages/project/IdentityDetailsByIDPage/components/IdentityProjectAdditionalPrivilegeSection/IdentityProjectAdditionalPrivilegeSection.tsx b/frontend/src/pages/project/IdentityDetailsByIDPage/components/IdentityProjectAdditionalPrivilegeSection/IdentityProjectAdditionalPrivilegeSection.tsx index f98f6ebf8..431875b3c 100644 --- a/frontend/src/pages/project/IdentityDetailsByIDPage/components/IdentityProjectAdditionalPrivilegeSection/IdentityProjectAdditionalPrivilegeSection.tsx +++ b/frontend/src/pages/project/IdentityDetailsByIDPage/components/IdentityProjectAdditionalPrivilegeSection/IdentityProjectAdditionalPrivilegeSection.tsx @@ -57,18 +57,13 @@ export const IdentityProjectAdditionalPrivilegeSection = ({ identityMembershipDe const handlePrivilegeDelete = async () => { const { id } = popUp?.deletePrivilege?.data as { id: string }; - try { - await deletePrivilege({ - privilegeId: id, - projectId, - identityId - }); - createNotification({ type: "success", text: "Successfully removed the privilege" }); - handlePopUpClose("deletePrivilege"); - } catch (err) { - console.log(err); - createNotification({ type: "error", text: "Failed to delete privilege" }); - } + await deletePrivilege({ + privilegeId: id, + projectId, + identityId + }); + createNotification({ type: "success", text: "Successfully removed the privilege" }); + handlePopUpClose("deletePrivilege"); }; return ( diff --git a/frontend/src/pages/project/IdentityDetailsByIDPage/components/IdentityRoleDetailsSection/IdentityRoleDetailsSection.tsx b/frontend/src/pages/project/IdentityDetailsByIDPage/components/IdentityRoleDetailsSection/IdentityRoleDetailsSection.tsx index 34b5229d6..dce632121 100644 --- a/frontend/src/pages/project/IdentityDetailsByIDPage/components/IdentityRoleDetailsSection/IdentityRoleDetailsSection.tsx +++ b/frontend/src/pages/project/IdentityDetailsByIDPage/components/IdentityRoleDetailsSection/IdentityRoleDetailsSection.tsx @@ -50,42 +50,37 @@ export const IdentityRoleDetailsSection = ({ const handleRoleDelete = async () => { const { id } = popUp?.deleteRole?.data as TProjectRole; - try { - const updatedRoles = identityMembershipDetails?.roles?.filter((el) => el.id !== id); - await updateIdentityWorkspaceRole({ - projectId: currentProject?.id || "", - identityId: identityMembershipDetails.identity.id, - roles: updatedRoles.map( - ({ - role, - customRoleSlug, - isTemporary, - temporaryMode, - temporaryRange, - temporaryAccessStartTime, - temporaryAccessEndTime - }) => ({ - role: role === "custom" ? customRoleSlug : role, - ...(isTemporary - ? { - isTemporary, - temporaryMode, - temporaryRange, - temporaryAccessStartTime, - temporaryAccessEndTime - } - : { - isTemporary - }) - }) - ) - }); - createNotification({ type: "success", text: "Successfully removed role" }); - handlePopUpClose("deleteRole"); - } catch (err) { - console.log(err); - createNotification({ type: "error", text: "Failed to delete role" }); - } + const updatedRoles = identityMembershipDetails?.roles?.filter((el) => el.id !== id); + await updateIdentityWorkspaceRole({ + projectId: currentProject?.id || "", + identityId: identityMembershipDetails.identity.id, + roles: updatedRoles.map( + ({ + role, + customRoleSlug, + isTemporary, + temporaryMode, + temporaryRange, + temporaryAccessStartTime, + temporaryAccessEndTime + }) => ({ + role: role === "custom" ? customRoleSlug : role, + ...(isTemporary + ? { + isTemporary, + temporaryMode, + temporaryRange, + temporaryAccessStartTime, + temporaryAccessEndTime + } + : { + isTemporary + }) + }) + ) + }); + createNotification({ type: "success", text: "Successfully removed role" }); + handlePopUpClose("deleteRole"); }; return ( diff --git a/frontend/src/pages/project/MemberDetailsByIDPage/components/MemberProjectAdditionalPrivilegeSection/MemberProjectAdditionalPrivilegeSection.tsx b/frontend/src/pages/project/MemberDetailsByIDPage/components/MemberProjectAdditionalPrivilegeSection/MemberProjectAdditionalPrivilegeSection.tsx index 7094c9ca8..28c3c9b5f 100644 --- a/frontend/src/pages/project/MemberDetailsByIDPage/components/MemberProjectAdditionalPrivilegeSection/MemberProjectAdditionalPrivilegeSection.tsx +++ b/frontend/src/pages/project/MemberDetailsByIDPage/components/MemberProjectAdditionalPrivilegeSection/MemberProjectAdditionalPrivilegeSection.tsx @@ -60,17 +60,12 @@ export const MemberProjectAdditionalPrivilegeSection = ({ membershipDetails }: P const handlePrivilegeDelete = async () => { const { id } = popUp?.deletePrivilege?.data as { id: string }; - try { - await deletePrivilege({ - privilegeId: id, - projectMembershipId: membershipDetails.id - }); - createNotification({ type: "success", text: "Successfully removed the privilege" }); - handlePopUpClose("deletePrivilege"); - } catch (err) { - console.log(err); - createNotification({ type: "error", text: "Failed to delete privilege" }); - } + await deletePrivilege({ + privilegeId: id, + projectMembershipId: membershipDetails.id + }); + createNotification({ type: "success", text: "Successfully removed the privilege" }); + handlePopUpClose("deletePrivilege"); }; return ( diff --git a/frontend/src/pages/project/MemberDetailsByIDPage/components/MemberProjectAdditionalPrivilegeSection/MembershipProjectAdditionalPrivilegeModifySection.tsx b/frontend/src/pages/project/MemberDetailsByIDPage/components/MemberProjectAdditionalPrivilegeSection/MembershipProjectAdditionalPrivilegeModifySection.tsx index 1a217a509..bc5bd3a6f 100644 --- a/frontend/src/pages/project/MemberDetailsByIDPage/components/MemberProjectAdditionalPrivilegeSection/MembershipProjectAdditionalPrivilegeModifySection.tsx +++ b/frontend/src/pages/project/MemberDetailsByIDPage/components/MemberProjectAdditionalPrivilegeSection/MembershipProjectAdditionalPrivilegeModifySection.tsx @@ -129,31 +129,26 @@ export const MembershipProjectAdditionalPrivilegeModifySection = ({ temporaryAccessStartTime: el.temporaryAccess.temporaryAccessStartTime }; - try { - if (isCreate) { - await createUserProjectAdditionalPrivilege({ - permissions: formRolePermission2API(el.permissions), - projectMembershipId, - slug: el.slug || undefined, - type: accessType - }); - createNotification({ type: "success", text: "Successfully created privilege" }); - } else { - if (!projectId || !privilegeDetails?.id) return; - await updateUserProjectAdditionalPrivilege({ - privilegeId: privilegeDetails.id, - permissions: formRolePermission2API(el.permissions), - projectMembershipId, - slug: el.slug || undefined, - type: accessType - }); - createNotification({ type: "success", text: "Successfully updated privilege" }); - } - onGoBack(); - } catch (err) { - console.log(err); - createNotification({ type: "error", text: "Failed to update privilege" }); + if (isCreate) { + await createUserProjectAdditionalPrivilege({ + permissions: formRolePermission2API(el.permissions), + projectMembershipId, + slug: el.slug || undefined, + type: accessType + }); + createNotification({ type: "success", text: "Successfully created privilege" }); + } else { + if (!projectId || !privilegeDetails?.id) return; + await updateUserProjectAdditionalPrivilege({ + privilegeId: privilegeDetails.id, + permissions: formRolePermission2API(el.permissions), + projectMembershipId, + slug: el.slug || undefined, + type: accessType + }); + createNotification({ type: "success", text: "Successfully updated privilege" }); } + onGoBack(); }; const privilegeTemporaryAccess = form.watch("temporaryAccess"); diff --git a/frontend/src/pages/project/RoleDetailsBySlugPage/components/RolePermissionsSection.tsx b/frontend/src/pages/project/RoleDetailsBySlugPage/components/RolePermissionsSection.tsx index fd95d2659..c93cea534 100644 --- a/frontend/src/pages/project/RoleDetailsBySlugPage/components/RolePermissionsSection.tsx +++ b/frontend/src/pages/project/RoleDetailsBySlugPage/components/RolePermissionsSection.tsx @@ -122,19 +122,14 @@ export const RolePermissionsSection = ({ roleSlug, isDisabled }: Props) => { const { mutateAsync: updateRole } = useUpdateProjectRole(); const onSubmit = async (el: TFormSchema) => { - try { - if (!projectId || !role?.id) return; - await updateRole({ - id: role?.id as string, - projectId, - ...el, - permissions: formRolePermission2API(el.permissions) - }); - createNotification({ type: "success", text: "Successfully updated role" }); - } catch (err) { - console.log(err); - createNotification({ type: "error", text: "Failed to update role" }); - } + if (!projectId || !role?.id) return; + await updateRole({ + id: role?.id as string, + projectId, + ...el, + permissions: formRolePermission2API(el.permissions) + }); + createNotification({ type: "success", text: "Successfully updated role" }); }; const isCustomRole = !Object.values(ProjectMembershipRole).includes( diff --git a/frontend/src/pages/secret-manager/SettingsPage/components/BackfillSecretReferenceSection/BackfillSecretReferenceSection.tsx b/frontend/src/pages/secret-manager/SettingsPage/components/BackfillSecretReferenceSection/BackfillSecretReferenceSection.tsx index 26f5c7fc9..9350698dc 100644 --- a/frontend/src/pages/secret-manager/SettingsPage/components/BackfillSecretReferenceSection/BackfillSecretReferenceSection.tsx +++ b/frontend/src/pages/secret-manager/SettingsPage/components/BackfillSecretReferenceSection/BackfillSecretReferenceSection.tsx @@ -13,12 +13,8 @@ export const BackfillSecretReferenceSecretion = () => { const handleBackfill = async () => { if (backfillSecretReferences.isPending) return; - try { - await backfillSecretReferences.mutateAsync({ projectId: currentProject.id || "" }); - createNotification({ text: "Successfully re-indexed secret references", type: "success" }); - } catch { - createNotification({ text: "Failed to re-index secret references", type: "error" }); - } + await backfillSecretReferences.mutateAsync({ projectId: currentProject.id || "" }); + createNotification({ text: "Successfully re-indexed secret references", type: "success" }); }; const isAdmin = hasProjectRole(ProjectMembershipRole.Admin); From 3aeee8d552fed4065029f8adee547accc339e499 Mon Sep 17 00:00:00 2001 From: Victor Santos Date: Mon, 3 Nov 2025 11:58:44 -0300 Subject: [PATCH 16/28] refactor: enhance notification handling and streamline async logic across various components --- .../OauthCallbackPage/OauthCallbackPage.tsx | 18 +--- .../GithubOrgSyncConfigModal.tsx | 67 +++++------- .../OrgGithubSyncSection.tsx | 83 ++++++-------- .../OrgProvisioningTab/OrgSCIMSection.tsx | 37 +++---- .../OrgProvisioningTab/ScimTokenModal.tsx | 58 ++++------ .../OrgSecurityTab/OrgGenericAuthSection.tsx | 72 +++++-------- .../OrgUserAccessTokenLimitSection.tsx | 25 ++--- .../OrgSsoTab/LDAPGroupMapModal.tsx | 56 ++++------ .../components/OrgSsoTab/LDAPModal.tsx | 77 +++++-------- .../OrgSsoTab/OrgGeneralAuthSection.tsx | 100 ++++++++--------- .../components/OrgSsoTab/OrgLDAPSection.tsx | 38 +++---- .../components/OrgSsoTab/OrgOIDCSection.tsx | 64 +++++------ .../components/OrgSsoTab/OrgSSOSection.tsx | 79 ++++++-------- .../components/DeleteProjectTemplateModal.tsx | 25 ++--- .../components/EditProjectTemplate.tsx | 24 ++--- .../ProjectTemplateEditRoleForm.tsx | 42 +++----- .../ProjectTemplateEnvironmentsForm.tsx | 32 +++--- .../ProjectTemplateRolesSection.tsx | 30 ++---- .../ProjectTemplateDetailsModal.tsx | 26 ++--- .../components/UserOrgMembershipModal.tsx | 37 +++---- .../UserAddToProjectModal.tsx | 33 ++---- .../UserProjectsSection/UserGroupsSection.tsx | 27 ++--- .../components/GroupsSection/GroupModal.tsx | 29 ++--- .../GroupsSection/GroupsSection.tsx | 29 ++--- .../components/IdentityTab/IdentityTab.tsx | 29 ++--- .../IdentityTab/components/IdentityModal.tsx | 51 ++++----- .../MembersTab/components/AddMemberModal.tsx | 101 ++++++++---------- .../SpecificPrivilegeSection.tsx | 23 ++-- .../MembersTab/components/MembersSection.tsx | 26 ++--- .../AddServiceTokenModal.tsx | 57 ++++------ .../ServiceTokenSection.tsx | 24 ++--- .../components/GroupDetailsSection.tsx | 49 ++++----- .../IdentityDetailsByIDPage.tsx | 45 +++----- .../MemberDetailsByIDPage.tsx | 38 +++---- .../RoleDetailsBySlugPage.tsx | 49 ++++----- .../components/RoleModal.tsx | 79 ++++++-------- .../DeleteProjectProtection.tsx | 26 ++--- .../DeleteProjectSection.tsx | 12 --- 38 files changed, 653 insertions(+), 1064 deletions(-) diff --git a/frontend/src/pages/organization/SettingsPage/OauthCallbackPage/OauthCallbackPage.tsx b/frontend/src/pages/organization/SettingsPage/OauthCallbackPage/OauthCallbackPage.tsx index df5bf4f60..5efec93d9 100644 --- a/frontend/src/pages/organization/SettingsPage/OauthCallbackPage/OauthCallbackPage.tsx +++ b/frontend/src/pages/organization/SettingsPage/OauthCallbackPage/OauthCallbackPage.tsx @@ -72,20 +72,12 @@ export const OAuthCallbackPage = () => { if (!isReady) return; (async () => { - try { - await handleMicrosoftTeams(); + await handleMicrosoftTeams(); - createNotification({ - text: "Successfully created Microsoft Teams workflow integration", - type: "success" - }); - } catch (err) { - console.error(err); - createNotification({ - text: "Failed to create Microsoft Teams workflow integration", - type: "error" - }); - } + createNotification({ + text: "Successfully created Microsoft Teams workflow integration", + type: "success" + }); })(); }, [isReady]); diff --git a/frontend/src/pages/organization/SettingsPage/components/OrgProvisioningTab/GithubOrgSyncConfigModal.tsx b/frontend/src/pages/organization/SettingsPage/components/OrgProvisioningTab/GithubOrgSyncConfigModal.tsx index 180b63278..868dd17f7 100644 --- a/frontend/src/pages/organization/SettingsPage/components/OrgProvisioningTab/GithubOrgSyncConfigModal.tsx +++ b/frontend/src/pages/organization/SettingsPage/components/OrgProvisioningTab/GithubOrgSyncConfigModal.tsx @@ -55,55 +55,40 @@ export const GithubOrgSyncConfigModal = ({ }); const onFormSubmit = async ({ githubOrgName, githubOrgAccessToken }: FormData) => { - try { - if (isUpdate) { - await updateGithubSyncOrgConfig({ - githubOrgName, - githubOrgAccessToken - }); + if (isUpdate) { + await updateGithubSyncOrgConfig({ + githubOrgName, + githubOrgAccessToken + }); - createNotification({ - text: "Successfully updated GitHub Organization Sync", - type: "success" - }); - } else { - await createGithubSyncOrgConfig({ - githubOrgName, - githubOrgAccessToken, - isActive: false - }); - - createNotification({ - text: "Successfully created GitHub Organization Sync", - type: "success" - }); - } - handlePopUpToggle("githubOrgSyncConfig"); - } catch { createNotification({ - text: "Failed to setup GitHub Organization Sync", - type: "error" + text: "Successfully updated GitHub Organization Sync", + type: "success" + }); + } else { + await createGithubSyncOrgConfig({ + githubOrgName, + githubOrgAccessToken, + isActive: false + }); + + createNotification({ + text: "Successfully created GitHub Organization Sync", + type: "success" }); } + handlePopUpToggle("githubOrgSyncConfig"); }; const onDelete = async () => { - try { - await deleteGithubSyncOrgConfig(); + await deleteGithubSyncOrgConfig(); - handlePopUpToggle("deleteGithubOrgSyncConfig", false); - handlePopUpToggle("githubOrgSyncConfig", false); - createNotification({ - text: "Successfully deleted GitHub Organization Sync", - type: "success" - }); - } catch (err) { - console.error(err); - createNotification({ - text: "Failed to delete GitHub Organization Sync", - type: "error" - }); - } + handlePopUpToggle("deleteGithubOrgSyncConfig", false); + handlePopUpToggle("githubOrgSyncConfig", false); + createNotification({ + text: "Successfully deleted GitHub Organization Sync", + type: "success" + }); }; return ( diff --git a/frontend/src/pages/organization/SettingsPage/components/OrgProvisioningTab/OrgGithubSyncSection.tsx b/frontend/src/pages/organization/SettingsPage/components/OrgProvisioningTab/OrgGithubSyncSection.tsx index 188a83354..610cb61c1 100644 --- a/frontend/src/pages/organization/SettingsPage/components/OrgProvisioningTab/OrgGithubSyncSection.tsx +++ b/frontend/src/pages/organization/SettingsPage/components/OrgProvisioningTab/OrgGithubSyncSection.tsx @@ -35,64 +35,41 @@ export const OrgGithubSyncSection = () => { const data = !isPending && !githubOrgSyncConfig?.isError ? githubOrgSyncConfig?.data : undefined; const handleBulkSync = async () => { - try { - const result = await syncAllTeamsMutation.mutateAsync(); - let message = "Successfully synced teams"; + const result = await syncAllTeamsMutation.mutateAsync(); + let message = "Successfully synced teams"; - const details = []; - if (result.createdTeams.length > 0) { - details.push( - `${result.createdTeams.length} new team${result.createdTeams.length === 1 ? "" : "s"} created` - ); - } - if (result.updatedTeams.length > 0) { - details.push( - `${result.updatedTeams.length} team${result.updatedTeams.length === 1 ? "" : "s"} updated` - ); - } - if (result.removedMemberships > 0) { - details.push( - `${result.removedMemberships} membership${result.removedMemberships === 1 ? "" : "s"} removed` - ); - } + const details = []; + if (result.createdTeams.length > 0) { + details.push( + `${result.createdTeams.length} new team${result.createdTeams.length === 1 ? "" : "s"} created` + ); + } + if (result.updatedTeams.length > 0) { + details.push( + `${result.updatedTeams.length} team${result.updatedTeams.length === 1 ? "" : "s"} updated` + ); + } + if (result.removedMemberships > 0) { + details.push( + `${result.removedMemberships} membership${result.removedMemberships === 1 ? "" : "s"} removed` + ); + } - if (details.length > 0) { - message += `. ${details.join(", ")}`; - } + if (details.length > 0) { + message += `. ${details.join(", ")}`; + } + createNotification({ + text: message, + type: "success" + }); + + if (result.errors && result.errors.length > 0) { createNotification({ - text: message, - type: "success" + text: `Sync completed with ${result.errors.length} warnings. Check the console for details.`, + type: "warning" }); - - if (result.errors && result.errors.length > 0) { - createNotification({ - text: `Sync completed with ${result.errors.length} warnings. Check the console for details.`, - type: "warning" - }); - console.warn("Sync errors:", result.errors); - } - } catch (error) { - const errorMessage = - (error as any)?.response?.data?.message || (error as Error)?.message || "Unknown error"; - - if ( - errorMessage.includes("token") && - (errorMessage.includes("required") || - errorMessage.includes("invalid") || - errorMessage.includes("expired") || - errorMessage.includes("set a token first")) - ) { - createNotification({ - text: "Please set a GitHub access token in the configuration modal to continue with the sync", - type: "error" - }); - } else { - createNotification({ - text: `Failed to sync GitHub teams: ${errorMessage}`, - type: "error" - }); - } + console.warn("Sync errors:", result.errors); } }; diff --git a/frontend/src/pages/organization/SettingsPage/components/OrgProvisioningTab/OrgSCIMSection.tsx b/frontend/src/pages/organization/SettingsPage/components/OrgProvisioningTab/OrgSCIMSection.tsx index 3936a20ee..3d079ccef 100644 --- a/frontend/src/pages/organization/SettingsPage/components/OrgProvisioningTab/OrgSCIMSection.tsx +++ b/frontend/src/pages/organization/SettingsPage/components/OrgProvisioningTab/OrgSCIMSection.tsx @@ -36,30 +36,23 @@ export const OrgScimSection = () => { }; const handleEnableSCIMToggle = async (value: boolean) => { - try { - if (!currentOrg?.id) return; - if (!subscription?.scim) { - handlePopUpOpen("upgradePlan", { - isEnterpriseFeature: true - }); - return; - } - - await mutateAsync({ - orgId: currentOrg?.id, - scimEnabled: value - }); - - createNotification({ - text: `Successfully ${value ? "enabled" : "disabled"} SCIM provisioning`, - type: "success" - }); - } catch (err) { - createNotification({ - text: (err as { response: { data: { message: string } } }).response.data.message, - type: "error" + if (!currentOrg?.id) return; + if (!subscription?.scim) { + handlePopUpOpen("upgradePlan", { + isEnterpriseFeature: true }); + return; } + + await mutateAsync({ + orgId: currentOrg?.id, + scimEnabled: value + }); + + createNotification({ + text: `Successfully ${value ? "enabled" : "disabled"} SCIM provisioning`, + type: "success" + }); }; return ( diff --git a/frontend/src/pages/organization/SettingsPage/components/OrgProvisioningTab/ScimTokenModal.tsx b/frontend/src/pages/organization/SettingsPage/components/OrgProvisioningTab/ScimTokenModal.tsx index c542a88bb..5d6007ac0 100644 --- a/frontend/src/pages/organization/SettingsPage/components/OrgProvisioningTab/ScimTokenModal.tsx +++ b/frontend/src/pages/organization/SettingsPage/components/OrgProvisioningTab/ScimTokenModal.tsx @@ -92,52 +92,36 @@ export const ScimTokenModal = ({ popUp, handlePopUpOpen, handlePopUpToggle }: Pr }, [isScimTokenCopied, isScimUrlCopied]); const onFormSubmit = async ({ description, ttlDays }: FormData) => { - try { - if (!currentOrg?.id) return; + if (!currentOrg?.id) return; - const { scimToken } = await createScimTokenMutateAsync({ - organizationId: currentOrg.id, - description, - ttlDays: Number(ttlDays) - }); + const { scimToken } = await createScimTokenMutateAsync({ + organizationId: currentOrg.id, + description, + ttlDays: Number(ttlDays) + }); - setToken(scimToken); + setToken(scimToken); - createNotification({ - text: "Successfully created SCIM token", - type: "success" - }); - } catch (err) { - console.error(err); - createNotification({ - text: "Failed to create SCIM token", - type: "error" - }); - } + createNotification({ + text: "Successfully created SCIM token", + type: "success" + }); }; const onDeleteScimTokenSubmit = async (scimTokenId: string) => { - try { - if (!currentOrg?.id) return; + if (!currentOrg?.id) return; - await deleteScimTokenMutateAsync({ - organizationId: currentOrg.id, - scimTokenId - }); + await deleteScimTokenMutateAsync({ + organizationId: currentOrg.id, + scimTokenId + }); - handlePopUpToggle("deleteScimToken", false); + handlePopUpToggle("deleteScimToken", false); - createNotification({ - text: "Successfully deleted SCIM token", - type: "success" - }); - } catch (err) { - console.error(err); - createNotification({ - text: "Failed to delete SCIM token", - type: "error" - }); - } + createNotification({ + text: "Successfully deleted SCIM token", + type: "success" + }); }; const hasToken = Boolean(token); diff --git a/frontend/src/pages/organization/SettingsPage/components/OrgSecurityTab/OrgGenericAuthSection.tsx b/frontend/src/pages/organization/SettingsPage/components/OrgSecurityTab/OrgGenericAuthSection.tsx index 7e2bd522b..7fe5fc219 100644 --- a/frontend/src/pages/organization/SettingsPage/components/OrgSecurityTab/OrgGenericAuthSection.tsx +++ b/frontend/src/pages/organization/SettingsPage/components/OrgSecurityTab/OrgGenericAuthSection.tsx @@ -20,55 +20,39 @@ export const OrgGenericAuthSection = () => { const { mutateAsync } = useUpdateOrg(); const handleEnforceMfaToggle = async (value: boolean) => { - try { - if (!currentOrg?.id) return; - if (!subscription?.enforceMfa) { - handlePopUpOpen("upgradePlan"); - return; - } - - await mutateAsync({ - orgId: currentOrg?.id, - enforceMfa: value - }); - - createNotification({ - text: `Successfully ${value ? "enforced" : "un-enforced"} MFA`, - type: "success" - }); - } catch (err) { - console.error(err); - createNotification({ - text: (err as { response: { data: { message: string } } }).response.data.message, - type: "error" - }); + if (!currentOrg?.id) return; + if (!subscription?.enforceMfa) { + handlePopUpOpen("upgradePlan"); + return; } + + await mutateAsync({ + orgId: currentOrg?.id, + enforceMfa: value + }); + + createNotification({ + text: `Successfully ${value ? "enforced" : "un-enforced"} MFA`, + type: "success" + }); }; const handleUpdateSelectedMfa = async (selectedMfaMethod: MfaMethod) => { - try { - if (!currentOrg?.id) return; - if (!subscription?.enforceMfa) { - handlePopUpOpen("upgradePlan"); - return; - } - - await mutateAsync({ - orgId: currentOrg?.id, - selectedMfaMethod - }); - - createNotification({ - text: "Successfully updated selected MFA method", - type: "success" - }); - } catch (err) { - console.error(err); - createNotification({ - text: (err as { response: { data: { message: string } } }).response.data.message, - type: "error" - }); + if (!currentOrg?.id) return; + if (!subscription?.enforceMfa) { + handlePopUpOpen("upgradePlan"); + return; } + + await mutateAsync({ + orgId: currentOrg?.id, + selectedMfaMethod + }); + + createNotification({ + text: "Successfully updated selected MFA method", + type: "success" + }); }; return ( diff --git a/frontend/src/pages/organization/SettingsPage/components/OrgSecurityTab/OrgUserAccessTokenLimitSection.tsx b/frontend/src/pages/organization/SettingsPage/components/OrgSecurityTab/OrgUserAccessTokenLimitSection.tsx index 6e9865532..c78b5475e 100644 --- a/frontend/src/pages/organization/SettingsPage/components/OrgSecurityTab/OrgUserAccessTokenLimitSection.tsx +++ b/frontend/src/pages/organization/SettingsPage/components/OrgSecurityTab/OrgUserAccessTokenLimitSection.tsx @@ -57,24 +57,17 @@ export const OrgUserAccessTokenLimitSection = () => { if (!currentOrg) return null; const handleUserTokenExpirationSubmit = async (formData: TForm) => { - try { - const userTokenExpiration = formatDuration(formData.expirationValue, formData.expirationUnit); + const userTokenExpiration = formatDuration(formData.expirationValue, formData.expirationUnit); - await updateUserTokenExpiration({ - userTokenExpiration, - orgId: currentOrg.id - }); + await updateUserTokenExpiration({ + userTokenExpiration, + orgId: currentOrg.id + }); - createNotification({ - text: "Successfully updated user token expiration", - type: "success" - }); - } catch { - createNotification({ - text: "Failed updating user token expiration", - type: "error" - }); - } + createNotification({ + text: "Successfully updated user token expiration", + type: "success" + }); }; // Units for the dropdown with readable labels diff --git a/frontend/src/pages/organization/SettingsPage/components/OrgSsoTab/LDAPGroupMapModal.tsx b/frontend/src/pages/organization/SettingsPage/components/OrgSsoTab/LDAPGroupMapModal.tsx index aee845187..31e96a1cb 100644 --- a/frontend/src/pages/organization/SettingsPage/components/OrgSsoTab/LDAPGroupMapModal.tsx +++ b/frontend/src/pages/organization/SettingsPage/components/OrgSsoTab/LDAPGroupMapModal.tsx @@ -79,28 +79,20 @@ export const LDAPGroupMapModal = ({ popUp, handlePopUpOpen, handlePopUpToggle }: }); const onFormSubmit = async ({ groupSlug, ldapGroupCN }: TFormData) => { - try { - if (!ldapConfig) return; + if (!ldapConfig) return; - await createLDAPGroupMapping({ - ldapConfigId: ldapConfig.id, - groupSlug, - ldapGroupCN - }); + await createLDAPGroupMapping({ + ldapConfigId: ldapConfig.id, + groupSlug, + ldapGroupCN + }); - reset(); + reset(); - createNotification({ - text: `Successfully added LDAP group mapping for ${ldapGroupCN}`, - type: "success" - }); - } catch (err) { - console.error(err); - createNotification({ - text: `Failed to add LDAP group mapping for ${ldapGroupCN}`, - type: "error" - }); - } + createNotification({ + text: `Successfully added LDAP group mapping for ${ldapGroupCN}`, + type: "success" + }); }; const onDeleteGroupMapSubmit = async ({ @@ -112,25 +104,17 @@ export const LDAPGroupMapModal = ({ popUp, handlePopUpOpen, handlePopUpToggle }: ldapGroupMapId: string; ldapGroupCN: string; }) => { - try { - await deleteLDAPGroupMapping({ - ldapConfigId, - ldapGroupMapId - }); + await deleteLDAPGroupMapping({ + ldapConfigId, + ldapGroupMapId + }); - handlePopUpToggle("deleteLdapGroupMap", false); + handlePopUpToggle("deleteLdapGroupMap", false); - createNotification({ - text: `Successfully deleted LDAP group mapping ${ldapGroupCN}`, - type: "success" - }); - } catch (err) { - console.error(err); - createNotification({ - text: `Failed to delete LDAP group mapping ${ldapGroupCN}`, - type: "error" - }); - } + createNotification({ + text: `Successfully deleted LDAP group mapping ${ldapGroupCN}`, + type: "success" + }); }; useEffect(() => { diff --git a/frontend/src/pages/organization/SettingsPage/components/OrgSsoTab/LDAPModal.tsx b/frontend/src/pages/organization/SettingsPage/components/OrgSsoTab/LDAPModal.tsx index b9ba7a2b6..01429f512 100644 --- a/frontend/src/pages/organization/SettingsPage/components/OrgSsoTab/LDAPModal.tsx +++ b/frontend/src/pages/organization/SettingsPage/components/OrgSsoTab/LDAPModal.tsx @@ -62,31 +62,24 @@ export const LDAPModal = ({ popUp, handlePopUpClose, handlePopUpToggle, hideDele if (!currentOrg) { return; } - try { - await updateMutateAsync({ - organizationId: currentOrg.id, - isActive: false, - url: "", - bindDN: "", - bindPass: "", - searchBase: "", - searchFilter: "", - uniqueUserAttribute: "", - groupSearchBase: "", - groupSearchFilter: "", - caCert: "" - }); + await updateMutateAsync({ + organizationId: currentOrg.id, + isActive: false, + url: "", + bindDN: "", + bindPass: "", + searchBase: "", + searchFilter: "", + uniqueUserAttribute: "", + groupSearchBase: "", + groupSearchFilter: "", + caCert: "" + }); - createNotification({ - text: "Successfully deleted OIDC configuration.", - type: "success" - }); - } catch { - createNotification({ - text: "Failed deleting OIDC configuration.", - type: "error" - }); - } + createNotification({ + text: "Successfully deleted OIDC configuration.", + type: "success" + }); }; const watchUrl = watch("url"); @@ -164,33 +157,17 @@ export const LDAPModal = ({ popUp, handlePopUpClose, handlePopUpToggle, hideDele }; const handleTestLDAPConnection = async () => { - try { - const result = await testLDAPConnection({ - url: watchUrl, - bindDN: watchBindDN, - bindPass: watchBindPass, - caCert: watchCaCert ?? "" - }); + await testLDAPConnection({ + url: watchUrl, + bindDN: watchBindDN, + bindPass: watchBindPass, + caCert: watchCaCert ?? "" + }); - if (!result) { - createNotification({ - text: "Failed to test the LDAP connection: Bind operation was unsuccessful", - type: "error" - }); - return; - } - - createNotification({ - text: "Successfully tested the LDAP connection: Bind operation was successful", - type: "success" - }); - } catch (err) { - console.error(err); - createNotification({ - text: "Failed to test the LDAP connection", - type: "error" - }); - } + createNotification({ + text: "Successfully tested the LDAP connection: Bind operation was successful", + type: "success" + }); }; return ( diff --git a/frontend/src/pages/organization/SettingsPage/components/OrgSsoTab/OrgGeneralAuthSection.tsx b/frontend/src/pages/organization/SettingsPage/components/OrgSsoTab/OrgGeneralAuthSection.tsx index 527239898..f8d5b3200 100644 --- a/frontend/src/pages/organization/SettingsPage/components/OrgSsoTab/OrgGeneralAuthSection.tsx +++ b/frontend/src/pages/organization/SettingsPage/components/OrgSsoTab/OrgGeneralAuthSection.tsx @@ -45,69 +45,61 @@ export const OrgGeneralAuthSection = ({ const logout = useLogoutUser(); const handleEnforceOrgAuthToggle = async (value: boolean, type: EnforceAuthType) => { - try { - if (!currentOrg?.id) return; + if (!currentOrg?.id) return; - if (type === EnforceAuthType.SAML) { - if (!subscription?.samlSSO) { - handlePopUpOpen("upgradePlan"); - return; - } - - await mutateAsync({ - orgId: currentOrg?.id, - authEnforced: value - }); - } else if (type === EnforceAuthType.GOOGLE) { - if (!subscription?.enforceGoogleSSO) { - handlePopUpOpen("upgradePlan"); - return; - } - - await mutateAsync({ - orgId: currentOrg?.id, - googleSsoAuthEnforced: value - }); - } else if (type === EnforceAuthType.OIDC) { - if (!subscription?.oidcSSO) { - handlePopUpOpen("upgradePlan"); - return; - } - - await mutateAsync({ - orgId: currentOrg?.id, - authEnforced: value - }); - } else { - createNotification({ - text: `Invalid auth enforcement type ${type}`, - type: "error" - }); + if (type === EnforceAuthType.SAML) { + if (!subscription?.samlSSO) { + handlePopUpOpen("upgradePlan"); + return; } - createNotification({ - text: `Successfully ${value ? "enabled" : "disabled"} org-level auth`, - type: "success" + await mutateAsync({ + orgId: currentOrg?.id, + authEnforced: value }); - - if (value) { - await logout.mutateAsync(); - - if (type === EnforceAuthType.SAML) { - window.open(`/api/v1/sso/redirect/saml2/organizations/${currentOrg.slug}`); - } else if (type === EnforceAuthType.GOOGLE) { - window.open(`/api/v1/sso/redirect/google?org_slug=${currentOrg.slug}`); - } - - window.close(); + } else if (type === EnforceAuthType.GOOGLE) { + if (!subscription?.enforceGoogleSSO) { + handlePopUpOpen("upgradePlan"); + return; } - } catch (err) { - console.error(err); + + await mutateAsync({ + orgId: currentOrg?.id, + googleSsoAuthEnforced: value + }); + } else if (type === EnforceAuthType.OIDC) { + if (!subscription?.oidcSSO) { + handlePopUpOpen("upgradePlan"); + return; + } + + await mutateAsync({ + orgId: currentOrg?.id, + authEnforced: value + }); + } else { createNotification({ - text: (err as { response: { data: { message: string } } }).response.data.message, + text: `Invalid auth enforcement type ${type}`, type: "error" }); } + + createNotification({ + text: `Successfully ${value ? "enabled" : "disabled"} org-level auth`, + type: "success" + }); + + if (value) { + await logout.mutateAsync(); + + if (type === EnforceAuthType.SAML) { + window.open(`/api/v1/sso/redirect/saml2/organizations/${currentOrg.slug}`); + } else if (type === EnforceAuthType.GOOGLE) { + window.open(`/api/v1/sso/redirect/google?org_slug=${currentOrg.slug}`); + } + + window.close(); + } }; const handleEnableBypassOrgAuthToggle = async (value: boolean) => { diff --git a/frontend/src/pages/organization/SettingsPage/components/OrgSsoTab/OrgLDAPSection.tsx b/frontend/src/pages/organization/SettingsPage/components/OrgSsoTab/OrgLDAPSection.tsx index 9d94d595c..e4c4fec56 100644 --- a/frontend/src/pages/organization/SettingsPage/components/OrgSsoTab/OrgLDAPSection.tsx +++ b/frontend/src/pages/organization/SettingsPage/components/OrgSsoTab/OrgLDAPSection.tsx @@ -31,31 +31,23 @@ export const OrgLDAPSection = (): JSX.Element => { const { mutateAsync: createMutateAsync } = useCreateLDAPConfig(); const handleLDAPToggle = async (value: boolean) => { - try { - if (!currentOrg?.id) return; - if (!subscription?.ldap) { - handlePopUpOpen("upgradePlan", { - isEnterpriseFeature: true - }); - return; - } - - await mutateAsync({ - organizationId: currentOrg?.id, - isActive: value - }); - - createNotification({ - text: `Successfully ${value ? "enabled" : "disabled"} LDAP`, - type: "success" - }); - } catch (err) { - console.error(err); - createNotification({ - text: `Failed to ${value ? "enable" : "disable"} LDAP`, - type: "error" + if (!currentOrg?.id) return; + if (!subscription?.ldap) { + handlePopUpOpen("upgradePlan", { + isEnterpriseFeature: true }); + return; } + + await mutateAsync({ + organizationId: currentOrg?.id, + isActive: value + }); + + createNotification({ + text: `Successfully ${value ? "enabled" : "disabled"} LDAP`, + type: "success" + }); }; const addLDAPBtnClick = async () => { diff --git a/frontend/src/pages/organization/SettingsPage/components/OrgSsoTab/OrgOIDCSection.tsx b/frontend/src/pages/organization/SettingsPage/components/OrgSsoTab/OrgOIDCSection.tsx index 7e4b2b3ef..35962349b 100644 --- a/frontend/src/pages/organization/SettingsPage/components/OrgSsoTab/OrgOIDCSection.tsx +++ b/frontend/src/pages/organization/SettingsPage/components/OrgSsoTab/OrgOIDCSection.tsx @@ -30,49 +30,41 @@ export const OrgOIDCSection = (): JSX.Element => { ] as const); const handleOIDCToggle = async (value: boolean) => { - try { - if (!currentOrg?.id) return; + if (!currentOrg?.id) return; - if (!subscription?.oidcSSO) { - handlePopUpOpen("upgradePlan"); - return; - } - - await mutateAsync({ - organizationId: currentOrg?.id, - isActive: value - }); - - createNotification({ - text: `Successfully ${value ? "enabled" : "disabled"} OIDC SSO`, - type: "success" - }); - } catch (err) { - console.error(err); + if (!subscription?.oidcSSO) { + handlePopUpOpen("upgradePlan"); + return; } + + await mutateAsync({ + organizationId: currentOrg?.id, + isActive: value + }); + + createNotification({ + text: `Successfully ${value ? "enabled" : "disabled"} OIDC SSO`, + type: "success" + }); }; const handleOIDCGroupManagement = async (value: boolean) => { - try { - if (!currentOrg?.id) return; + if (!currentOrg?.id) return; - if (!subscription?.oidcSSO) { - handlePopUpOpen("upgradePlan"); - return; - } - - await mutateAsync({ - organizationId: currentOrg?.id, - manageGroupMemberships: value - }); - - createNotification({ - text: `Successfully ${value ? "enabled" : "disabled"} OIDC group membership mapping`, - type: "success" - }); - } catch (err) { - console.error(err); + if (!subscription?.oidcSSO) { + handlePopUpOpen("upgradePlan"); + return; } + + await mutateAsync({ + organizationId: currentOrg?.id, + manageGroupMemberships: value + }); + + createNotification({ + text: `Successfully ${value ? "enabled" : "disabled"} OIDC group membership mapping`, + type: "success" + }); }; const addOidcButtonClick = async () => { diff --git a/frontend/src/pages/organization/SettingsPage/components/OrgSsoTab/OrgSSOSection.tsx b/frontend/src/pages/organization/SettingsPage/components/OrgSsoTab/OrgSSOSection.tsx index 5e9d4c211..80ed79551 100644 --- a/frontend/src/pages/organization/SettingsPage/components/OrgSsoTab/OrgSSOSection.tsx +++ b/frontend/src/pages/organization/SettingsPage/components/OrgSsoTab/OrgSSOSection.tsx @@ -34,63 +34,46 @@ export const OrgSSOSection = (): JSX.Element => { const { mutateAsync: createMutateAsync } = useCreateSSOConfig(); const handleSamlSSOToggle = async (value: boolean) => { - try { - if (!currentOrg?.id) return; + if (!currentOrg?.id) return; - if (!subscription?.samlSSO) { - handlePopUpOpen("upgradePlan", { - description: "You can use SAML SSO if you switch to Infisical's Pro plan." - }); - return; - } - - await mutateAsync({ - organizationId: currentOrg?.id, - isActive: value - }); - - createNotification({ - text: `Successfully ${value ? "enabled" : "disabled"} SAML SSO`, - type: "success" - }); - } catch (err) { - console.error(err); - createNotification({ - text: `Failed to ${value ? "enable" : "disable"} SAML SSO`, - type: "error" + if (!subscription?.samlSSO) { + handlePopUpOpen("upgradePlan", { + description: "You can use SAML SSO if you switch to Infisical's Pro plan." }); + return; } + + await mutateAsync({ + organizationId: currentOrg?.id, + isActive: value + }); + + createNotification({ + text: `Successfully ${value ? "enabled" : "disabled"} SAML SSO`, + type: "success" + }); }; const handleSamlGroupManagement = async (value: boolean) => { - try { - if (!currentOrg?.id) return; + if (!currentOrg?.id) return; - if (!subscription?.samlSSO || !subscription?.groups) { - handlePopUpOpen("upgradePlan", { - isEnterpriseFeature: true, - description: - "You can use SAML group mapping if you switch to Infisical's Enterprise plan." - }); - return; - } - - await mutateAsync({ - organizationId: currentOrg?.id, - enableGroupSync: value - }); - - createNotification({ - text: `Successfully ${value ? "enabled" : "disabled"} SAML group membership mapping`, - type: "success" - }); - } catch (err) { - console.error(err); - createNotification({ - text: `Failed to ${value ? "enable" : "disable"} SAML group membership mapping`, - type: "error" + if (!subscription?.samlSSO || !subscription?.groups) { + handlePopUpOpen("upgradePlan", { + isEnterpriseFeature: true, + description: "You can use SAML group mapping if you switch to Infisical's Enterprise plan." }); + return; } + + await mutateAsync({ + organizationId: currentOrg?.id, + enableGroupSync: value + }); + + createNotification({ + text: `Successfully ${value ? "enabled" : "disabled"} SAML group membership mapping`, + type: "success" + }); }; const addSSOBtnClick = async () => { diff --git a/frontend/src/pages/organization/SettingsPage/components/ProjectTemplatesTab/components/DeleteProjectTemplateModal.tsx b/frontend/src/pages/organization/SettingsPage/components/ProjectTemplatesTab/components/DeleteProjectTemplateModal.tsx index 8ccdb0191..33b54afca 100644 --- a/frontend/src/pages/organization/SettingsPage/components/ProjectTemplatesTab/components/DeleteProjectTemplateModal.tsx +++ b/frontend/src/pages/organization/SettingsPage/components/ProjectTemplatesTab/components/DeleteProjectTemplateModal.tsx @@ -16,25 +16,16 @@ export const DeleteProjectTemplateModal = ({ isOpen, onOpenChange, template }: P const { id: templateId, name } = template; const handleDeleteProjectTemplate = async () => { - try { - await deleteTemplate.mutateAsync({ - templateId - }); + await deleteTemplate.mutateAsync({ + templateId + }); - createNotification({ - text: "Successfully removed project template", - type: "success" - }); + createNotification({ + text: "Successfully removed project template", + type: "success" + }); - onOpenChange(false); - } catch (err) { - console.error(err); - - createNotification({ - text: "Failed remove project template", - type: "error" - }); - } + onOpenChange(false); }; return ( diff --git a/frontend/src/pages/organization/SettingsPage/components/ProjectTemplatesTab/components/EditProjectTemplateSection/components/EditProjectTemplate.tsx b/frontend/src/pages/organization/SettingsPage/components/ProjectTemplatesTab/components/EditProjectTemplateSection/components/EditProjectTemplate.tsx index 7a99af1d6..afa8261b3 100644 --- a/frontend/src/pages/organization/SettingsPage/components/ProjectTemplatesTab/components/EditProjectTemplateSection/components/EditProjectTemplate.tsx +++ b/frontend/src/pages/organization/SettingsPage/components/ProjectTemplatesTab/components/EditProjectTemplateSection/components/EditProjectTemplate.tsx @@ -31,22 +31,14 @@ export const EditProjectTemplate = ({ isInfisicalTemplate, projectTemplate, onBa const deleteProjectTemplate = useDeleteProjectTemplate(); const handleRemoveTemplate = async () => { - try { - await deleteProjectTemplate.mutateAsync({ - templateId - }); - createNotification({ - text: "Successfully removed project template", - type: "success" - }); - onBack(); - } catch (error) { - console.error(error); - createNotification({ - text: "Failed to remove project template", - type: "error" - }); - } + await deleteProjectTemplate.mutateAsync({ + templateId + }); + createNotification({ + text: "Successfully removed project template", + type: "success" + }); + onBack(); handlePopUpClose("removeTemplate"); }; diff --git a/frontend/src/pages/organization/SettingsPage/components/ProjectTemplatesTab/components/EditProjectTemplateSection/components/ProjectTemplateEditRoleForm.tsx b/frontend/src/pages/organization/SettingsPage/components/ProjectTemplatesTab/components/EditProjectTemplateSection/components/ProjectTemplateEditRoleForm.tsx index 09a2a69af..e54eaf19d 100644 --- a/frontend/src/pages/organization/SettingsPage/components/ProjectTemplatesTab/components/EditProjectTemplateSection/components/ProjectTemplateEditRoleForm.tsx +++ b/frontend/src/pages/organization/SettingsPage/components/ProjectTemplatesTab/components/EditProjectTemplateSection/components/ProjectTemplateEditRoleForm.tsx @@ -57,31 +57,23 @@ export const ProjectTemplateEditRoleForm = ({ const updateProjectTemplate = useUpdateProjectTemplate(); const onSubmit = async (form: TFormSchema) => { - try { - await updateProjectTemplate.mutateAsync({ - templateId: projectTemplate.id, - roles: [ - ...projectTemplate.roles.filter( - (r) => r.slug !== role?.slug && isCustomProjectRole(r.slug) // filter out default roles as well - ), - { - ...form, - permissions: formRolePermission2API(form.permissions) - } - ] - }); - onGoBack(); - createNotification({ - text: "Template roles successfully updated", - type: "success" - }); - } catch (e: any) { - console.error(e); - createNotification({ - text: "Failed to update template roles", - type: "error" - }); - } + await updateProjectTemplate.mutateAsync({ + templateId: projectTemplate.id, + roles: [ + ...projectTemplate.roles.filter( + (r) => r.slug !== role?.slug && isCustomProjectRole(r.slug) // filter out default roles as well + ), + { + ...form, + permissions: formRolePermission2API(form.permissions) + } + ] + }); + onGoBack(); + createNotification({ + text: "Template roles successfully updated", + type: "success" + }); }; return ( diff --git a/frontend/src/pages/organization/SettingsPage/components/ProjectTemplatesTab/components/EditProjectTemplateSection/components/ProjectTemplateEnvironmentsForm.tsx b/frontend/src/pages/organization/SettingsPage/components/ProjectTemplatesTab/components/EditProjectTemplateSection/components/ProjectTemplateEnvironmentsForm.tsx index ec1899369..f11e9ecc8 100644 --- a/frontend/src/pages/organization/SettingsPage/components/ProjectTemplatesTab/components/EditProjectTemplateSection/components/ProjectTemplateEnvironmentsForm.tsx +++ b/frontend/src/pages/organization/SettingsPage/components/ProjectTemplatesTab/components/EditProjectTemplateSection/components/ProjectTemplateEnvironmentsForm.tsx @@ -68,28 +68,20 @@ export const ProjectTemplateEnvironmentsForm = ({ const updateProjectTemplate = useUpdateProjectTemplate(); const onFormSubmit = async (form: TFormSchema) => { - try { - const { environments: updatedEnvs } = await updateProjectTemplate.mutateAsync({ - environments: form.environments?.map((env, index) => ({ - ...env, - position: index + 1 - })), - templateId: projectTemplate.id - }); + const { environments: updatedEnvs } = await updateProjectTemplate.mutateAsync({ + environments: form.environments?.map((env, index) => ({ + ...env, + position: index + 1 + })), + templateId: projectTemplate.id + }); - reset({ environments: updatedEnvs }); + reset({ environments: updatedEnvs }); - createNotification({ - text: "Project template updated successfully", - type: "success" - }); - } catch (e: any) { - console.error(e); - createNotification({ - text: e.message ?? "Failed to update project template", - type: "error" - }); - } + createNotification({ + text: "Project template updated successfully", + type: "success" + }); }; const isEnvironmentLimitExceeded = diff --git a/frontend/src/pages/organization/SettingsPage/components/ProjectTemplatesTab/components/EditProjectTemplateSection/components/ProjectTemplateRolesSection.tsx b/frontend/src/pages/organization/SettingsPage/components/ProjectTemplatesTab/components/EditProjectTemplateSection/components/ProjectTemplateRolesSection.tsx index d65f7d785..cd5e41d2a 100644 --- a/frontend/src/pages/organization/SettingsPage/components/ProjectTemplatesTab/components/EditProjectTemplateSection/components/ProjectTemplateRolesSection.tsx +++ b/frontend/src/pages/organization/SettingsPage/components/ProjectTemplatesTab/components/EditProjectTemplateSection/components/ProjectTemplateRolesSection.tsx @@ -42,26 +42,18 @@ export const ProjectTemplateRolesSection = ({ projectTemplate, isInfisicalTempla const updateProjectTemplate = useUpdateProjectTemplate(); const handleRemoveRole = async (slug: string) => { - try { - await updateProjectTemplate.mutateAsync({ - templateId: projectTemplate.id, - roles: projectTemplate.roles.filter( - (role) => role.slug !== slug && isCustomProjectRole(role.slug) // filter out default roles as well - ) - }); + await updateProjectTemplate.mutateAsync({ + templateId: projectTemplate.id, + roles: projectTemplate.roles.filter( + (role) => role.slug !== slug && isCustomProjectRole(role.slug) // filter out default roles as well + ) + }); - createNotification({ - text: "Successfully removed role from template", - type: "success" - }); - handlePopUpClose("removeRole"); - } catch (e) { - console.error(e); - createNotification({ - text: "Error removing role from template", - type: "error" - }); - } + createNotification({ + text: "Successfully removed role from template", + type: "success" + }); + handlePopUpClose("removeRole"); }; const editRole = popUp?.editRole?.data as TProjectRole; diff --git a/frontend/src/pages/organization/SettingsPage/components/ProjectTemplatesTab/components/ProjectTemplateDetailsModal.tsx b/frontend/src/pages/organization/SettingsPage/components/ProjectTemplatesTab/components/ProjectTemplateDetailsModal.tsx index 6010d61f1..17224536d 100644 --- a/frontend/src/pages/organization/SettingsPage/components/ProjectTemplatesTab/components/ProjectTemplateDetailsModal.tsx +++ b/frontend/src/pages/organization/SettingsPage/components/ProjectTemplatesTab/components/ProjectTemplateDetailsModal.tsx @@ -93,25 +93,15 @@ const ProjectTemplateForm = ({ onComplete, projectTemplate }: FormProps) => { ? updateProjectTemplate.mutateAsync({ templateId: projectTemplate.id, ...data }) : createProjectTemplate.mutateAsync({ ...data }); - try { - const template = await mutation; - createNotification({ - text: `Successfully ${ - projectTemplate ? "updated template details" : "created project template" - }`, - type: "success" - }); + const template = await mutation; + createNotification({ + text: `Successfully ${ + projectTemplate ? "updated template details" : "created project template" + }`, + type: "success" + }); - onComplete(template); - } catch (err) { - console.error(err); - createNotification({ - text: `Failed to ${ - projectTemplate ? "update template details" : "create project template" - }`, - type: "error" - }); - } + onComplete(template); }; return ( diff --git a/frontend/src/pages/organization/UserDetailsByIDPage/components/UserOrgMembershipModal.tsx b/frontend/src/pages/organization/UserDetailsByIDPage/components/UserOrgMembershipModal.tsx index 59d83749c..c7ebe8efe 100644 --- a/frontend/src/pages/organization/UserDetailsByIDPage/components/UserOrgMembershipModal.tsx +++ b/frontend/src/pages/organization/UserDetailsByIDPage/components/UserOrgMembershipModal.tsx @@ -87,34 +87,23 @@ export const UserOrgMembershipModal = ({ popUp, handlePopUpOpen, handlePopUpTogg }, [popUp?.orgMembership?.data, roles]); const onFormSubmit = async ({ role, metadata }: FormData) => { - try { - if (!orgId) return; + if (!orgId) return; - await updateOrgMembership({ - organizationId: orgId, - membershipId: popUpData.membershipId, - role: role.slug, - metadata - }); + await updateOrgMembership({ + organizationId: orgId, + membershipId: popUpData.membershipId, + role: role.slug, + metadata + }); - handlePopUpToggle("orgMembership", false); + handlePopUpToggle("orgMembership", false); - createNotification({ - text: "Successfully updated user organization role", - type: "success" - }); + createNotification({ + text: "Successfully updated user organization role", + type: "success" + }); - reset(); - } catch (err) { - console.error(err); - const error = err as any; - const text = error?.response?.data?.message ?? "Failed to update user organization role"; - - createNotification({ - text, - type: "error" - }); - } + reset(); }; return ( diff --git a/frontend/src/pages/organization/UserDetailsByIDPage/components/UserProjectsSection/UserAddToProjectModal.tsx b/frontend/src/pages/organization/UserDetailsByIDPage/components/UserProjectsSection/UserAddToProjectModal.tsx index 572be1d81..013358c5f 100644 --- a/frontend/src/pages/organization/UserDetailsByIDPage/components/UserProjectsSection/UserAddToProjectModal.tsx +++ b/frontend/src/pages/organization/UserDetailsByIDPage/components/UserProjectsSection/UserAddToProjectModal.tsx @@ -67,30 +67,19 @@ const UserAddToProjectModalChild = ({ membershipId, popUp, handlePopUpToggle }: }, [workspaces, projectMemberships]); const onFormSubmit = async ({ projectId }: FormData) => { - try { - await addUserToWorkspaceNonE2EE({ - projectId, - usernames: [popupData.username], - orgId - }); + await addUserToWorkspaceNonE2EE({ + projectId, + usernames: [popupData.username], + orgId + }); - createNotification({ - text: "Successfully added user to project", - type: "success" - }); + createNotification({ + text: "Successfully added user to project", + type: "success" + }); - reset(); - handlePopUpToggle("addUserToProject", false); - } catch (err) { - console.error(err); - const error = err as any; - const text = error?.response?.data?.message ?? "Failed to add identity to project"; - - createNotification({ - text, - type: "error" - }); - } + reset(); + handlePopUpToggle("addUserToProject", false); }; return ( diff --git a/frontend/src/pages/organization/UserDetailsByIDPage/components/UserProjectsSection/UserGroupsSection.tsx b/frontend/src/pages/organization/UserDetailsByIDPage/components/UserProjectsSection/UserGroupsSection.tsx index 8e7cf3ce8..fafa7aff3 100644 --- a/frontend/src/pages/organization/UserDetailsByIDPage/components/UserProjectsSection/UserGroupsSection.tsx +++ b/frontend/src/pages/organization/UserDetailsByIDPage/components/UserProjectsSection/UserGroupsSection.tsx @@ -20,25 +20,18 @@ export const UserGroupsSection = ({ orgMembership }: Props) => { const { mutateAsync: removeUserFromGroup } = useRemoveUserFromGroup(); const handleRemoveUserFromGroup = useCallback(async (groupId: string, groupSlug: string) => { - try { - await removeUserFromGroup({ - groupId, - slug: groupSlug, - username: orgMembership.user.username - }); + await removeUserFromGroup({ + groupId, + slug: groupSlug, + username: orgMembership.user.username + }); - createNotification({ - type: "success", - text: "User removed from group successfully" - }); + createNotification({ + type: "success", + text: "User removed from group successfully" + }); - handlePopUpClose("removeUserFromGroup"); - } catch { - createNotification({ - type: "error", - text: "Failed to remove user from group" - }); - } + handlePopUpClose("removeUserFromGroup"); }, []); return ( diff --git a/frontend/src/pages/project/AccessControlPage/components/GroupsTab/components/GroupsSection/GroupModal.tsx b/frontend/src/pages/project/AccessControlPage/components/GroupsTab/components/GroupsSection/GroupModal.tsx index a279bd1b0..f8788762c 100644 --- a/frontend/src/pages/project/AccessControlPage/components/GroupsTab/components/GroupsSection/GroupModal.tsx +++ b/frontend/src/pages/project/AccessControlPage/components/GroupsTab/components/GroupsSection/GroupModal.tsx @@ -62,26 +62,19 @@ const Content = ({ popUp, handlePopUpToggle }: Props) => { }); const onFormSubmit = async ({ group, role }: FormData) => { - try { - await addGroupToWorkspaceMutateAsync({ - projectId: currentProject?.id || "", - groupId: group.id, - role: role.slug || undefined - }); + await addGroupToWorkspaceMutateAsync({ + projectId: currentProject?.id || "", + groupId: group.id, + role: role.slug || undefined + }); - reset(); - handlePopUpToggle("group", false); + reset(); + handlePopUpToggle("group", false); - createNotification({ - text: "Successfully added group to project", - type: "success" - }); - } catch { - createNotification({ - text: "Failed to add group to project", - type: "error" - }); - } + createNotification({ + text: "Successfully added group to project", + type: "success" + }); }; return filteredGroupMembershipOrgs.length ? ( diff --git a/frontend/src/pages/project/AccessControlPage/components/GroupsTab/components/GroupsSection/GroupsSection.tsx b/frontend/src/pages/project/AccessControlPage/components/GroupsTab/components/GroupsSection/GroupsSection.tsx index 115be60fe..bfac55bc2 100644 --- a/frontend/src/pages/project/AccessControlPage/components/GroupsTab/components/GroupsSection/GroupsSection.tsx +++ b/frontend/src/pages/project/AccessControlPage/components/GroupsTab/components/GroupsSection/GroupsSection.tsx @@ -43,28 +43,17 @@ export const GroupsSection = () => { }; const onRemoveGroupSubmit = async (groupId: string) => { - try { - await deleteMutateAsync({ - groupId, - projectId: currentProject?.id || "" - }); + await deleteMutateAsync({ + groupId, + projectId: currentProject?.id || "" + }); - createNotification({ - text: "Successfully removed identity from project", - type: "success" - }); + createNotification({ + text: "Successfully removed identity from project", + type: "success" + }); - handlePopUpClose("deleteGroup"); - } catch (err) { - console.error(err); - const error = err as any; - const text = error?.response?.data?.message ?? "Failed to remove group from project"; - - createNotification({ - text, - type: "error" - }); - } + handlePopUpClose("deleteGroup"); }; return ( diff --git a/frontend/src/pages/project/AccessControlPage/components/IdentityTab/IdentityTab.tsx b/frontend/src/pages/project/AccessControlPage/components/IdentityTab/IdentityTab.tsx index 17dbdca27..48e01e2aa 100644 --- a/frontend/src/pages/project/AccessControlPage/components/IdentityTab/IdentityTab.tsx +++ b/frontend/src/pages/project/AccessControlPage/components/IdentityTab/IdentityTab.tsx @@ -119,28 +119,17 @@ export const IdentityTab = withProjectPermission( ] as const); const onRemoveIdentitySubmit = async (identityId: string) => { - try { - await deleteMutateAsync({ - identityId, - projectId - }); + await deleteMutateAsync({ + identityId, + projectId + }); - createNotification({ - text: "Successfully removed identity from project", - type: "success" - }); + createNotification({ + text: "Successfully removed identity from project", + type: "success" + }); - handlePopUpClose("deleteIdentity"); - } catch (err) { - console.error(err); - const error = err as any; - const text = error?.response?.data?.message ?? "Failed to remove identity from project"; - - createNotification({ - text, - type: "error" - }); - } + handlePopUpClose("deleteIdentity"); }; const handleSort = (column: ProjectIdentityOrderBy) => { diff --git a/frontend/src/pages/project/AccessControlPage/components/IdentityTab/components/IdentityModal.tsx b/frontend/src/pages/project/AccessControlPage/components/IdentityTab/components/IdentityModal.tsx index 55f22c5ae..3274185b1 100644 --- a/frontend/src/pages/project/AccessControlPage/components/IdentityTab/components/IdentityModal.tsx +++ b/frontend/src/pages/project/AccessControlPage/components/IdentityTab/components/IdentityModal.tsx @@ -104,40 +104,29 @@ const Content = ({ popUp, handlePopUpToggle }: Props) => { }); const onFormSubmit = async ({ identity, role }: FormData) => { - try { - await addIdentityToWorkspaceMutateAsync({ - projectId, - identityId: identity.id, - role: role.slug || undefined - }); + await addIdentityToWorkspaceMutateAsync({ + projectId, + identityId: identity.id, + role: role.slug || undefined + }); - createNotification({ - text: "Successfully added identity to project", - type: "success" - }); + createNotification({ + text: "Successfully added identity to project", + type: "success" + }); - const nextAvailableMembership = filteredIdentityMembershipOrgs.filter( - (membership) => membership.identity.id !== identity.id - )[0]; + const nextAvailableMembership = filteredIdentityMembershipOrgs.filter( + (membership) => membership.identity.id !== identity.id + )[0]; - // prevents combobox from displaying previously added identity - reset({ - identity: { - name: nextAvailableMembership?.identity.name, - id: nextAvailableMembership?.identity.id - } - }); - handlePopUpToggle("identity", false); - } catch (err) { - console.error(err); - const error = err as any; - const text = error?.response?.data?.message ?? "Failed to add identity to project"; - - createNotification({ - text, - type: "error" - }); - } + // prevents combobox from displaying previously added identity + reset({ + identity: { + name: nextAvailableMembership?.identity.name, + id: nextAvailableMembership?.identity.id + } + }); + handlePopUpToggle("identity", false); }; if (isMembershipsLoading || isRolesLoading) diff --git a/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/AddMemberModal.tsx b/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/AddMemberModal.tsx index 3477440fe..cb6934240 100644 --- a/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/AddMemberModal.tsx +++ b/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/AddMemberModal.tsx @@ -110,65 +110,56 @@ export const AddMemberModal = ({ popUp, handlePopUpToggle }: Props) => { if (!selectedMembers) return; - try { - if (currentProject.version === ProjectVersion.V1) { + if (currentProject.version === ProjectVersion.V1) { + createNotification({ + type: "error", + text: "Please upgrade your project to invite new members to the project." + }); + } else { + const inviteeEmails = selectedMembers + .map((member) => { + if (!member) return null; + + if (member.user.username) { + return member.user.username; + } + + if (member.user.email) { + return member.user.email; + } + + return null; + }) + .filter(Boolean) as string[]; + + if (inviteeEmails.length !== selectedMembers.length) { createNotification({ - type: "error", - text: "Please upgrade your project to invite new members to the project." + text: "Failed to add users to project. One or more users were invalid.", + type: "error" + }); + return; + } + + if (newInvitees.length) { + await addMemberToOrg({ + inviteeEmails: newInvitees, + organizationId: orgId, + organizationRoleSlug: ProjectMembershipRole.Member // only applies to new invites + }); + } + if (newInvitees.length || inviteeEmails.length) { + await addUserToProject({ + usernames: [...inviteeEmails, ...newInvitees], + orgId, + projectId: currentProject.id, + roleSlugs: projectRoleSlugs.map((role) => role.slug) }); - } else { - const inviteeEmails = selectedMembers - .map((member) => { - if (!member) return null; - - if (member.user.username) { - return member.user.username; - } - - if (member.user.email) { - return member.user.email; - } - - return null; - }) - .filter(Boolean) as string[]; - - if (inviteeEmails.length !== selectedMembers.length) { - createNotification({ - text: "Failed to add users to project. One or more users were invalid.", - type: "error" - }); - return; - } - - if (newInvitees.length) { - await addMemberToOrg({ - inviteeEmails: newInvitees, - organizationId: orgId, - organizationRoleSlug: ProjectMembershipRole.Member // only applies to new invites - }); - } - if (newInvitees.length || inviteeEmails.length) { - await addUserToProject({ - usernames: [...inviteeEmails, ...newInvitees], - orgId, - projectId: currentProject.id, - roleSlugs: projectRoleSlugs.map((role) => role.slug) - }); - } } - createNotification({ - text: "Successfully added user to the project", - type: "success" - }); - } catch (error) { - console.error(error); - createNotification({ - text: "Failed to add user to project", - type: "error" - }); - return; } + createNotification({ + text: "Successfully added user to the project", + type: "success" + }); handlePopUpToggle("addMember", false); reset(); }; diff --git a/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/MemberRoleForm/SpecificPrivilegeSection.tsx b/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/MemberRoleForm/SpecificPrivilegeSection.tsx index 33c0d1077..c3eb0c9aa 100644 --- a/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/MemberRoleForm/SpecificPrivilegeSection.tsx +++ b/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/MemberRoleForm/SpecificPrivilegeSection.tsx @@ -182,21 +182,14 @@ export const SpecificPrivilegeSecretForm = ({ } if (deleteUserPrivilege.isPending) return; - try { - await deleteUserPrivilege.mutateAsync({ - privilegeId: privilege.id, - projectMembershipId: privilege.projectMembershipId - }); - createNotification({ - type: "success", - text: "Successfully deleted privilege" - }); - } catch { - createNotification({ - type: "error", - text: "Failed to delete privilege" - }); - } + await deleteUserPrivilege.mutateAsync({ + privilegeId: privilege.id, + projectMembershipId: privilege.projectMembershipId + }); + createNotification({ + type: "success", + text: "Successfully deleted privilege" + }); }; // This is used for requesting access additional privileges, not directly creating a privilege! diff --git a/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/MembersSection.tsx b/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/MembersSection.tsx index 5904f12fb..7ec7bd4bc 100644 --- a/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/MembersSection.tsx +++ b/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/MembersSection.tsx @@ -35,23 +35,15 @@ export const MembersSection = () => { if (!currentOrg?.id) return; if (!currentProject?.id) return; - try { - await removeUserFromWorkspace({ - projectId: currentProject.id, - usernames: [username], - orgId: currentOrg.id - }); - createNotification({ - text: "Successfully removed user from project", - type: "success" - }); - } catch (error) { - console.error(error); - createNotification({ - text: "Failed to remove user from the project", - type: "error" - }); - } + await removeUserFromWorkspace({ + projectId: currentProject.id, + usernames: [username], + orgId: currentOrg.id + }); + createNotification({ + text: "Successfully removed user from project", + type: "success" + }); handlePopUpClose("removeMember"); }; diff --git a/frontend/src/pages/project/AccessControlPage/components/ServiceTokenTab/components/ServiceTokenSection/AddServiceTokenModal.tsx b/frontend/src/pages/project/AccessControlPage/components/ServiceTokenTab/components/ServiceTokenSection/AddServiceTokenModal.tsx index 873422f3c..25d943f4a 100644 --- a/frontend/src/pages/project/AccessControlPage/components/ServiceTokenTab/components/ServiceTokenSection/AddServiceTokenModal.tsx +++ b/frontend/src/pages/project/AccessControlPage/components/ServiceTokenTab/components/ServiceTokenSection/AddServiceTokenModal.tsx @@ -6,7 +6,6 @@ import { useTranslation } from "react-i18next"; import { faCheck, faCopy, faPlus, faTrashCan } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { zodResolver } from "@hookform/resolvers/zod"; -import { AxiosError } from "axios"; import { z } from "zod"; import { createNotification } from "@app/components/notifications"; @@ -110,45 +109,29 @@ const ServiceTokenForm = () => { }; const onFormSubmit = async ({ name, scopes, expiresIn, permissions }: FormData) => { - try { - if (!currentProject?.id) return; + if (!currentProject?.id) return; - const randomBytes = crypto.randomBytes(16).toString("hex"); + const randomBytes = crypto.randomBytes(16).toString("hex"); - const { serviceToken } = await createServiceToken.mutateAsync({ - encryptedKey: "", - iv: "", - tag: "", - scopes, - expiresIn: Number(expiresIn), - name, - workspaceId: currentProject.id, - randomBytes, - permissions: Object.entries(permissions) - .filter(([, permissionsValue]) => permissionsValue) - .map(([permissionsKey]) => permissionsKey) - }); + const { serviceToken } = await createServiceToken.mutateAsync({ + encryptedKey: "", + iv: "", + tag: "", + scopes, + expiresIn: Number(expiresIn), + name, + workspaceId: currentProject.id, + randomBytes, + permissions: Object.entries(permissions) + .filter(([, permissionsValue]) => permissionsValue) + .map(([permissionsKey]) => permissionsKey) + }); - setToken(serviceToken); - createNotification({ - text: "Successfully created a service token", - type: "success" - }); - } catch (err) { - console.error(err); - const axiosError = err as AxiosError; - if (axiosError?.response?.status === 401) { - createNotification({ - text: "You do not have access to the selected environment/path", - type: "error" - }); - } else { - createNotification({ - text: "Failed to create a service token", - type: "error" - }); - } - } + setToken(serviceToken); + createNotification({ + text: "Successfully created a service token", + type: "success" + }); }; return !hasServiceToken ? ( diff --git a/frontend/src/pages/project/AccessControlPage/components/ServiceTokenTab/components/ServiceTokenSection/ServiceTokenSection.tsx b/frontend/src/pages/project/AccessControlPage/components/ServiceTokenTab/components/ServiceTokenSection/ServiceTokenSection.tsx index 64b042c35..6f2e82e02 100644 --- a/frontend/src/pages/project/AccessControlPage/components/ServiceTokenTab/components/ServiceTokenSection/ServiceTokenSection.tsx +++ b/frontend/src/pages/project/AccessControlPage/components/ServiceTokenTab/components/ServiceTokenSection/ServiceTokenSection.tsx @@ -28,23 +28,15 @@ export const ServiceTokenSection = withProjectPermission( ] as const); const onDeleteApproved = async () => { - try { - deleteServiceToken.mutateAsync( - (popUp?.deleteAPITokenConfirmation?.data as DeleteModalData)?.id - ); - createNotification({ - text: "Successfully deleted service token", - type: "success" - }); + await deleteServiceToken.mutateAsync( + (popUp?.deleteAPITokenConfirmation?.data as DeleteModalData)?.id + ); + createNotification({ + text: "Successfully deleted service token", + type: "success" + }); - handlePopUpClose("deleteAPITokenConfirmation"); - } catch (err) { - console.error(err); - createNotification({ - text: "Failed to delete service token", - type: "error" - }); - } + handlePopUpClose("deleteAPITokenConfirmation"); }; return ( diff --git a/frontend/src/pages/project/GroupDetailsByIDPage/components/GroupDetailsSection.tsx b/frontend/src/pages/project/GroupDetailsByIDPage/components/GroupDetailsSection.tsx index cca6cabfd..368a740c2 100644 --- a/frontend/src/pages/project/GroupDetailsByIDPage/components/GroupDetailsSection.tsx +++ b/frontend/src/pages/project/GroupDetailsByIDPage/components/GroupDetailsSection.tsx @@ -35,38 +35,27 @@ export const GroupDetailsSection = ({ groupMembership }: Props) => { const navigate = useNavigate(); const onRemoveGroupSubmit = async () => { - try { - await deleteMutateAsync({ - groupId: groupMembership.group.id, + await deleteMutateAsync({ + groupId: groupMembership.group.id, + projectId: currentProject.id + }); + + createNotification({ + text: "Successfully removed group from project", + type: "success" + }); + + navigate({ + to: `${getProjectBaseURL(currentProject.type)}/access-management`, + params: { projectId: currentProject.id - }); + }, + search: { + selectedTab: "groups" + } + }); - createNotification({ - text: "Successfully removed group from project", - type: "success" - }); - - navigate({ - to: `${getProjectBaseURL(currentProject.type)}/access-management`, - params: { - projectId: currentProject.id - }, - search: { - selectedTab: "groups" - } - }); - - handlePopUpClose("deleteGroup"); - } catch (err) { - console.error(err); - const error = err as any; - const text = error?.response?.data?.message ?? "Failed to remove group from project"; - - createNotification({ - text, - type: "error" - }); - } + handlePopUpClose("deleteGroup"); }; return ( diff --git a/frontend/src/pages/project/IdentityDetailsByIDPage/IdentityDetailsByIDPage.tsx b/frontend/src/pages/project/IdentityDetailsByIDPage/IdentityDetailsByIDPage.tsx index e49e05022..65a2a5710 100644 --- a/frontend/src/pages/project/IdentityDetailsByIDPage/IdentityDetailsByIDPage.tsx +++ b/frontend/src/pages/project/IdentityDetailsByIDPage/IdentityDetailsByIDPage.tsx @@ -76,35 +76,24 @@ const Page = () => { }; const onRemoveIdentitySubmit = async () => { - try { - await deleteMutateAsync({ - identityId, + await deleteMutateAsync({ + identityId, + projectId + }); + createNotification({ + text: "Successfully removed identity from project", + type: "success" + }); + handlePopUpClose("deleteIdentity"); + navigate({ + to: `${getProjectBaseURL(currentProject.type)}/access-management` as const, + params: { projectId - }); - createNotification({ - text: "Successfully removed identity from project", - type: "success" - }); - handlePopUpClose("deleteIdentity"); - navigate({ - to: `${getProjectBaseURL(currentProject.type)}/access-management` as const, - params: { - projectId - }, - search: { - selectedTab: "identities" - } - }); - } catch (err) { - console.error(err); - const error = err as any; - const text = error?.response?.data?.message ?? "Failed to remove identity from project"; - - createNotification({ - text, - type: "error" - }); - } + }, + search: { + selectedTab: "identities" + } + }); }; if (isMembershipDetailsLoading) { diff --git a/frontend/src/pages/project/MemberDetailsByIDPage/MemberDetailsByIDPage.tsx b/frontend/src/pages/project/MemberDetailsByIDPage/MemberDetailsByIDPage.tsx index 2b85291d0..b4b83bfb4 100644 --- a/frontend/src/pages/project/MemberDetailsByIDPage/MemberDetailsByIDPage.tsx +++ b/frontend/src/pages/project/MemberDetailsByIDPage/MemberDetailsByIDPage.tsx @@ -83,29 +83,21 @@ export const Page = () => { const handleRemoveUser = async () => { if (!currentOrg?.id || !currentProject?.id || !membershipDetails?.user?.username) return; - try { - await removeUserFromWorkspace({ - projectId, - usernames: [membershipDetails?.user?.username], - orgId: currentOrg.id - }); - createNotification({ - text: "Successfully removed user from project", - type: "success" - }); - navigate({ - to: `${getProjectBaseURL(currentProject.type)}/access-management` as const, - params: { - projectId: currentProject.id - } - }); - } catch (error) { - console.error(error); - createNotification({ - text: "Failed to remove user from the project", - type: "error" - }); - } + await removeUserFromWorkspace({ + projectId, + usernames: [membershipDetails?.user?.username], + orgId: currentOrg.id + }); + createNotification({ + text: "Successfully removed user from project", + type: "success" + }); + navigate({ + to: `${getProjectBaseURL(currentProject.type)}/access-management` as const, + params: { + projectId: currentProject.id + } + }); handlePopUpClose("removeMember"); }; diff --git a/frontend/src/pages/project/RoleDetailsBySlugPage/RoleDetailsBySlugPage.tsx b/frontend/src/pages/project/RoleDetailsBySlugPage/RoleDetailsBySlugPage.tsx index 9650b3fb8..9a87266c4 100644 --- a/frontend/src/pages/project/RoleDetailsBySlugPage/RoleDetailsBySlugPage.tsx +++ b/frontend/src/pages/project/RoleDetailsBySlugPage/RoleDetailsBySlugPage.tsx @@ -53,38 +53,27 @@ const Page = () => { ] as const); const onDeleteRoleSubmit = async () => { - try { - if (!currentProject?.slug || !data?.id) return; + if (!currentProject?.slug || !data?.id) return; - await deleteProjectRole({ - projectId, - id: data.id - }); + await deleteProjectRole({ + projectId, + id: data.id + }); - createNotification({ - text: "Successfully deleted project role", - type: "success" - }); - handlePopUpClose("deleteRole"); - navigate({ - to: `${getProjectBaseURL(currentProject.type)}/access-management` as const, - params: { - projectId - }, - search: { - selectedTab: ProjectAccessControlTabs.Roles - } - }); - } catch (err) { - console.error(err); - const error = err as any; - const text = error?.response?.data?.message ?? "Failed to delete project role"; - - createNotification({ - text, - type: "error" - }); - } + createNotification({ + text: "Successfully deleted project role", + type: "success" + }); + handlePopUpClose("deleteRole"); + navigate({ + to: `${getProjectBaseURL(currentProject.type)}/access-management` as const, + params: { + projectId + }, + search: { + selectedTab: ProjectAccessControlTabs.Roles + } + }); }; const isCustomRole = !Object.values(ProjectMembershipRole).includes( diff --git a/frontend/src/pages/project/RoleDetailsBySlugPage/components/RoleModal.tsx b/frontend/src/pages/project/RoleDetailsBySlugPage/components/RoleModal.tsx index 43467876b..03525eac5 100644 --- a/frontend/src/pages/project/RoleDetailsBySlugPage/components/RoleModal.tsx +++ b/frontend/src/pages/project/RoleDetailsBySlugPage/components/RoleModal.tsx @@ -76,63 +76,54 @@ export const RoleModal = ({ popUp, handlePopUpToggle }: Props) => { }, [role]); const onFormSubmit = async ({ name, description, slug }: FormData) => { - try { - if (!projectId) return; + if (!projectId) return; - if (role) { - // update - await updateProjectRole({ - id: role.id, - projectId, - name, - description, - slug - }); - - handlePopUpToggle("role", false); - if (slug) { - navigate({ - to: `${getProjectBaseURL(currentProject.type)}/roles/$roleSlug` as const, - params: { - roleSlug: slug, - projectId - } - }); - } - } else { - // create - const newRole = await createProjectRole({ - projectId, - name, - description, - slug, - permissions: [] - }); + if (role) { + // update + await updateProjectRole({ + id: role.id, + projectId, + name, + description, + slug + }); + handlePopUpToggle("role", false); + if (slug) { navigate({ to: `${getProjectBaseURL(currentProject.type)}/roles/$roleSlug` as const, params: { - roleSlug: newRole.slug, + roleSlug: slug, projectId } }); - handlePopUpToggle("role", false); } - - createNotification({ - text: `Successfully ${popUp?.role?.data ? "updated" : "created"} role`, - type: "success" + } else { + // create + const newRole = await createProjectRole({ + projectId, + name, + description, + slug, + permissions: [] }); - reset(); - } catch { - const text = `Failed to ${popUp?.role?.data ? "update" : "create"} role`; - - createNotification({ - text, - type: "error" + navigate({ + to: `${getProjectBaseURL(currentProject.type)}/roles/$roleSlug` as const, + params: { + roleSlug: newRole.slug, + projectId + } }); + handlePopUpToggle("role", false); } + + createNotification({ + text: `Successfully ${popUp?.role?.data ? "updated" : "created"} role`, + type: "success" + }); + + reset(); }; return ( diff --git a/frontend/src/pages/project/SettingsPage/components/DeleteProjectProtection/DeleteProjectProtection.tsx b/frontend/src/pages/project/SettingsPage/components/DeleteProjectProtection/DeleteProjectProtection.tsx index 7160e9adf..3cb0c9371 100644 --- a/frontend/src/pages/project/SettingsPage/components/DeleteProjectProtection/DeleteProjectProtection.tsx +++ b/frontend/src/pages/project/SettingsPage/components/DeleteProjectProtection/DeleteProjectProtection.tsx @@ -10,24 +10,16 @@ export const DeleteProjectProtection = () => { const { mutateAsync } = useUpdateProject(); const handleToggleDeleteProjectProtection = async (state: boolean) => { - try { - await mutateAsync({ - projectId, - hasDeleteProtection: state - }); + await mutateAsync({ + projectId, + hasDeleteProtection: state + }); - const text = `Successfully ${state ? "enabled" : "disabled"} delete protection`; - createNotification({ - text, - type: "success" - }); - } catch (err) { - console.error(err); - createNotification({ - text: "Failed to update delete protection", - type: "error" - }); - } + const text = `Successfully ${state ? "enabled" : "disabled"} delete protection`; + createNotification({ + text, + type: "success" + }); }; return ( diff --git a/frontend/src/pages/project/SettingsPage/components/DeleteProjectSection/DeleteProjectSection.tsx b/frontend/src/pages/project/SettingsPage/components/DeleteProjectSection/DeleteProjectSection.tsx index fb66f0a74..58db07484 100644 --- a/frontend/src/pages/project/SettingsPage/components/DeleteProjectSection/DeleteProjectSection.tsx +++ b/frontend/src/pages/project/SettingsPage/components/DeleteProjectSection/DeleteProjectSection.tsx @@ -68,12 +68,6 @@ export const DeleteProjectSection = () => { to: "/organization/projects" }); handlePopUpClose("deleteWorkspace"); - } catch (err) { - console.error(err); - createNotification({ - text: "Failed to delete project", - type: "error" - }); } finally { setIsDeleting.off(); } @@ -118,12 +112,6 @@ export const DeleteProjectSection = () => { navigate({ to: "/organization/projects" }); - } catch (err) { - console.error(err); - createNotification({ - text: "Failed to leave project", - type: "error" - }); } finally { setIsLeaving.off(); } From 35c04abb29cded7cc238a27e05762e1348c93d6a Mon Sep 17 00:00:00 2001 From: Carlos Monastyrski Date: Mon, 3 Nov 2025 14:57:38 -0300 Subject: [PATCH 17/28] Rename Azure PKI option to be more clear --- .../forms/PkiSyncOptionsFields/PkiSyncOptionsFields.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/frontend/src/components/pki-syncs/forms/PkiSyncOptionsFields/PkiSyncOptionsFields.tsx b/frontend/src/components/pki-syncs/forms/PkiSyncOptionsFields/PkiSyncOptionsFields.tsx index 5fe067283..c1313e684 100644 --- a/frontend/src/components/pki-syncs/forms/PkiSyncOptionsFields/PkiSyncOptionsFields.tsx +++ b/frontend/src/components/pki-syncs/forms/PkiSyncOptionsFields/PkiSyncOptionsFields.tsx @@ -71,7 +71,7 @@ export const PkiSyncOptionsFields = ({ destination }: Props) => { isChecked={value} >

- Enable Removal of Active/Revoked Certificates{" "} + Enable Removal of Expired/Revoked Certificates{" "} { isChecked={value} >

- Preserve Version on Renewal{" "} + Enable Versioning on Renewal{" "} Date: Mon, 3 Nov 2025 15:11:10 -0300 Subject: [PATCH 18/28] refactor: streamline async logic and notification handling across various settings and integration components --- .../AuditLogsRetentionSection.tsx | 55 +-- .../components/ProjectAccessError.tsx | 20 +- .../components/ShareSecretForm.tsx | 68 ++- .../RollbackPreviewTab/RollbackPreviewTab.tsx | 21 +- .../IntegrationsDetailsByIDPage.tsx | 32 +- .../OverviewPage/OverviewPage.tsx | 164 +++---- .../CreateSecretForm/CreateSecretForm.tsx | 19 +- .../CreateSecretForm/CreateSecretForm.tsx | 93 ++-- .../SecretListView/SecretListView.tsx | 424 +++++++++--------- .../AutoCapitalizationSection.tsx | 28 +- .../EncryptionTab/EncryptionTab.tsx | 38 +- .../AddEnvironmentModal.tsx | 30 +- .../UpdateEnvironmentModal.tsx | 32 +- .../PointInTimeVersionLimitSection.tsx | 23 +- .../SecretSharingSection.tsx | 16 +- .../SecretTagsSection/AddSecretTagModal.tsx | 32 +- .../SecretTagsSection/SecretTagsSection.tsx | 26 +- .../BitbucketConfigurePage.tsx | 64 ++- .../CircleCIConfigurePage.tsx | 76 ++-- .../CloudflarePagesConfigurePage.tsx | 16 +- .../CloudflareWorkersConfigurePage.tsx | 16 +- .../DatabricksConfigurePage.tsx | 76 ++-- .../GithubConfigurePage.tsx | 16 +- .../HashicorpVaultAuthorizePage.tsx | 48 +- .../HashicorpVaultConfigurePage.tsx | 50 +-- .../OctopusDeployAuthorizePage.tsx | 39 +- .../OctopusDeployConfigurePage.tsx | 76 ++-- .../ChangeEmailSection/ChangeEmailSection.tsx | 30 +- .../ChangePasswordSection.tsx | 20 +- .../DeleteAccountSection.tsx | 22 +- .../components/SecuritySection/MFASection.tsx | 60 +-- .../SessionsSection/SessionsTable.tsx | 18 +- .../UserNameSection/UserNameSection.tsx | 22 +- 33 files changed, 709 insertions(+), 1061 deletions(-) diff --git a/frontend/src/pages/project/SettingsPage/components/AuditLogsRetentionSection/AuditLogsRetentionSection.tsx b/frontend/src/pages/project/SettingsPage/components/AuditLogsRetentionSection/AuditLogsRetentionSection.tsx index d9bbc80d8..1618c73aa 100644 --- a/frontend/src/pages/project/SettingsPage/components/AuditLogsRetentionSection/AuditLogsRetentionSection.tsx +++ b/frontend/src/pages/project/SettingsPage/components/AuditLogsRetentionSection/AuditLogsRetentionSection.tsx @@ -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 diff --git a/frontend/src/pages/public/ErrorPage/components/ProjectAccessError.tsx b/frontend/src/pages/public/ErrorPage/components/ProjectAccessError.tsx index d6fd57d56..a07dd1674 100644 --- a/frontend/src/pages/public/ErrorPage/components/ProjectAccessError.tsx +++ b/frontend/src/pages/public/ErrorPage/components/ProjectAccessError.tsx @@ -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 ( diff --git a/frontend/src/pages/public/ShareSecretPage/components/ShareSecretForm.tsx b/frontend/src/pages/public/ShareSecretPage/components/ShareSecretForm.tsx index a34c08f9d..b8e93f0fe 100644 --- a/frontend/src/pages/public/ShareSecretPage/components/ShareSecretForm.tsx +++ b/frontend/src/pages/public/ShareSecretPage/components/ShareSecretForm.tsx @@ -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) diff --git a/frontend/src/pages/secret-manager/CommitDetailsPage/components/RollbackPreviewTab/RollbackPreviewTab.tsx b/frontend/src/pages/secret-manager/CommitDetailsPage/components/RollbackPreviewTab/RollbackPreviewTab.tsx index 43992d73a..baf2b015b 100644 --- a/frontend/src/pages/secret-manager/CommitDetailsPage/components/RollbackPreviewTab/RollbackPreviewTab.tsx +++ b/frontend/src/pages/secret-manager/CommitDetailsPage/components/RollbackPreviewTab/RollbackPreviewTab.tsx @@ -140,22 +140,15 @@ export const RollbackPreviewTab = (): JSX.Element => { ); const handleRollback = async (): Promise => { - 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 || []; diff --git a/frontend/src/pages/secret-manager/IntegrationsDetailsByIDPage/IntegrationsDetailsByIDPage.tsx b/frontend/src/pages/secret-manager/IntegrationsDetailsByIDPage/IntegrationsDetailsByIDPage.tsx index 3b5600665..9043c35ef 100644 --- a/frontend/src/pages/secret-manager/IntegrationsDetailsByIDPage/IntegrationsDetailsByIDPage.tsx +++ b/frontend/src/pages/secret-manager/IntegrationsDetailsByIDPage/IntegrationsDetailsByIDPage.tsx @@ -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([ diff --git a/frontend/src/pages/secret-manager/OverviewPage/OverviewPage.tsx b/frontend/src/pages/secret-manager/OverviewPage/OverviewPage.tsx index 2dc370321..09fa1044d 100644 --- a/frontend/src/pages/secret-manager/OverviewPage/OverviewPage.tsx +++ b/frontend/src/pages/secret-manager/OverviewPage/OverviewPage.tsx @@ -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" }); } }; diff --git a/frontend/src/pages/secret-manager/OverviewPage/components/CreateSecretForm/CreateSecretForm.tsx b/frontend/src/pages/secret-manager/OverviewPage/components/CreateSecretForm/CreateSecretForm.tsx index fede4e44d..977943330 100644 --- a/frontend/src/pages/secret-manager/OverviewPage/components/CreateSecretForm/CreateSecretForm.tsx +++ b/frontend/src/pages/secret-manager/OverviewPage/components/CreateSecretForm/CreateSecretForm.tsx @@ -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 ( diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/CreateSecretForm/CreateSecretForm.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/CreateSecretForm/CreateSecretForm.tsx index dd0561495..858fcde77 100644 --- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/CreateSecretForm/CreateSecretForm.tsx +++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/CreateSecretForm/CreateSecretForm.tsx @@ -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) => { diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretListView/SecretListView.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretListView/SecretListView.tsx index bd43e1271..be5dfaaed 100644 --- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretListView/SecretListView.tsx +++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretListView/SecretListView.tsx @@ -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, diff --git a/frontend/src/pages/secret-manager/SettingsPage/components/AutoCapitalizationSection/AutoCapitalizationSection.tsx b/frontend/src/pages/secret-manager/SettingsPage/components/AutoCapitalizationSection/AutoCapitalizationSection.tsx index 73bec81b9..7c9d03904 100644 --- a/frontend/src/pages/secret-manager/SettingsPage/components/AutoCapitalizationSection/AutoCapitalizationSection.tsx +++ b/frontend/src/pages/secret-manager/SettingsPage/components/AutoCapitalizationSection/AutoCapitalizationSection.tsx @@ -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 ( diff --git a/frontend/src/pages/secret-manager/SettingsPage/components/EncryptionTab/EncryptionTab.tsx b/frontend/src/pages/secret-manager/SettingsPage/components/EncryptionTab/EncryptionTab.tsx index 9e4627d26..e22719c83 100644 --- a/frontend/src/pages/secret-manager/SettingsPage/components/EncryptionTab/EncryptionTab.tsx +++ b/frontend/src/pages/secret-manager/SettingsPage/components/EncryptionTab/EncryptionTab.tsx @@ -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 ( diff --git a/frontend/src/pages/secret-manager/SettingsPage/components/EnvironmentSection/AddEnvironmentModal.tsx b/frontend/src/pages/secret-manager/SettingsPage/components/EnvironmentSection/AddEnvironmentModal.tsx index 611504a14..70c486616 100644 --- a/frontend/src/pages/secret-manager/SettingsPage/components/EnvironmentSection/AddEnvironmentModal.tsx +++ b/frontend/src/pages/secret-manager/SettingsPage/components/EnvironmentSection/AddEnvironmentModal.tsx @@ -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 ( diff --git a/frontend/src/pages/secret-manager/SettingsPage/components/EnvironmentSection/UpdateEnvironmentModal.tsx b/frontend/src/pages/secret-manager/SettingsPage/components/EnvironmentSection/UpdateEnvironmentModal.tsx index e2d64ee72..1c9d09101 100644 --- a/frontend/src/pages/secret-manager/SettingsPage/components/EnvironmentSection/UpdateEnvironmentModal.tsx +++ b/frontend/src/pages/secret-manager/SettingsPage/components/EnvironmentSection/UpdateEnvironmentModal.tsx @@ -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 ( diff --git a/frontend/src/pages/secret-manager/SettingsPage/components/PointInTimeVersionLimitSection/PointInTimeVersionLimitSection.tsx b/frontend/src/pages/secret-manager/SettingsPage/components/PointInTimeVersionLimitSection/PointInTimeVersionLimitSection.tsx index e647ff481..6345301a0 100644 --- a/frontend/src/pages/secret-manager/SettingsPage/components/PointInTimeVersionLimitSection/PointInTimeVersionLimitSection.tsx +++ b/frontend/src/pages/secret-manager/SettingsPage/components/PointInTimeVersionLimitSection/PointInTimeVersionLimitSection.tsx @@ -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); diff --git a/frontend/src/pages/secret-manager/SettingsPage/components/SecretSharingSection/SecretSharingSection.tsx b/frontend/src/pages/secret-manager/SettingsPage/components/SecretSharingSection/SecretSharingSection.tsx index bd8928823..ac1f735f9 100644 --- a/frontend/src/pages/secret-manager/SettingsPage/components/SecretSharingSection/SecretSharingSection.tsx +++ b/frontend/src/pages/secret-manager/SettingsPage/components/SecretSharingSection/SecretSharingSection.tsx @@ -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); } diff --git a/frontend/src/pages/secret-manager/SettingsPage/components/SecretTagsSection/AddSecretTagModal.tsx b/frontend/src/pages/secret-manager/SettingsPage/components/SecretTagsSection/AddSecretTagModal.tsx index 1d4c8e492..cfe7dff8e 100644 --- a/frontend/src/pages/secret-manager/SettingsPage/components/SecretTagsSection/AddSecretTagModal.tsx +++ b/frontend/src/pages/secret-manager/SettingsPage/components/SecretTagsSection/AddSecretTagModal.tsx @@ -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 ( diff --git a/frontend/src/pages/secret-manager/SettingsPage/components/SecretTagsSection/SecretTagsSection.tsx b/frontend/src/pages/secret-manager/SettingsPage/components/SecretTagsSection/SecretTagsSection.tsx index 508ef2867..2964467ad 100644 --- a/frontend/src/pages/secret-manager/SettingsPage/components/SecretTagsSection/SecretTagsSection.tsx +++ b/frontend/src/pages/secret-manager/SettingsPage/components/SecretTagsSection/SecretTagsSection.tsx @@ -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 ( diff --git a/frontend/src/pages/secret-manager/integrations/BitbucketConfigurePage/BitbucketConfigurePage.tsx b/frontend/src/pages/secret-manager/integrations/BitbucketConfigurePage/BitbucketConfigurePage.tsx index 8d855f284..b66644bdc 100644 --- a/frontend/src/pages/secret-manager/integrations/BitbucketConfigurePage/BitbucketConfigurePage.tsx +++ b/frontend/src/pages/secret-manager/integrations/BitbucketConfigurePage/BitbucketConfigurePage.tsx @@ -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(() => { diff --git a/frontend/src/pages/secret-manager/integrations/CircleCIConfigurePage/CircleCIConfigurePage.tsx b/frontend/src/pages/secret-manager/integrations/CircleCIConfigurePage/CircleCIConfigurePage.tsx index 7df2ae35c..a7ecbca6a 100644 --- a/frontend/src/pages/secret-manager/integrations/CircleCIConfigurePage/CircleCIConfigurePage.tsx +++ b/frontend/src/pages/secret-manager/integrations/CircleCIConfigurePage/CircleCIConfigurePage.tsx @@ -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) diff --git a/frontend/src/pages/secret-manager/integrations/CloudflarePagesConfigurePage/CloudflarePagesConfigurePage.tsx b/frontend/src/pages/secret-manager/integrations/CloudflarePagesConfigurePage/CloudflarePagesConfigurePage.tsx index 0a0d08863..3948351c3 100644 --- a/frontend/src/pages/secret-manager/integrations/CloudflarePagesConfigurePage/CloudflarePagesConfigurePage.tsx +++ b/frontend/src/pages/secret-manager/integrations/CloudflarePagesConfigurePage/CloudflarePagesConfigurePage.tsx @@ -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); } }; diff --git a/frontend/src/pages/secret-manager/integrations/CloudflareWorkersConfigurePage/CloudflareWorkersConfigurePage.tsx b/frontend/src/pages/secret-manager/integrations/CloudflareWorkersConfigurePage/CloudflareWorkersConfigurePage.tsx index 58bc8596b..417f0fe84 100644 --- a/frontend/src/pages/secret-manager/integrations/CloudflareWorkersConfigurePage/CloudflareWorkersConfigurePage.tsx +++ b/frontend/src/pages/secret-manager/integrations/CloudflareWorkersConfigurePage/CloudflareWorkersConfigurePage.tsx @@ -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); } }; diff --git a/frontend/src/pages/secret-manager/integrations/DatabricksConfigurePage/DatabricksConfigurePage.tsx b/frontend/src/pages/secret-manager/integrations/DatabricksConfigurePage/DatabricksConfigurePage.tsx index 1f5a3c40a..05c943fc5 100644 --- a/frontend/src/pages/secret-manager/integrations/DatabricksConfigurePage/DatabricksConfigurePage.tsx +++ b/frontend/src/pages/secret-manager/integrations/DatabricksConfigurePage/DatabricksConfigurePage.tsx @@ -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 ? ( diff --git a/frontend/src/pages/secret-manager/integrations/GithubConfigurePage/GithubConfigurePage.tsx b/frontend/src/pages/secret-manager/integrations/GithubConfigurePage/GithubConfigurePage.tsx index 5e9871ade..741c03032 100644 --- a/frontend/src/pages/secret-manager/integrations/GithubConfigurePage/GithubConfigurePage.tsx +++ b/frontend/src/pages/secret-manager/integrations/GithubConfigurePage/GithubConfigurePage.tsx @@ -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); } }; diff --git a/frontend/src/pages/secret-manager/integrations/HashicorpVaultAuthorizePage/HashicorpVaultAuthorizePage.tsx b/frontend/src/pages/secret-manager/integrations/HashicorpVaultAuthorizePage/HashicorpVaultAuthorizePage.tsx index 4b922a9bc..93d892241 100644 --- a/frontend/src/pages/secret-manager/integrations/HashicorpVaultAuthorizePage/HashicorpVaultAuthorizePage.tsx +++ b/frontend/src/pages/secret-manager/integrations/HashicorpVaultAuthorizePage/HashicorpVaultAuthorizePage.tsx @@ -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 ( diff --git a/frontend/src/pages/secret-manager/integrations/HashicorpVaultConfigurePage/HashicorpVaultConfigurePage.tsx b/frontend/src/pages/secret-manager/integrations/HashicorpVaultConfigurePage/HashicorpVaultConfigurePage.tsx index 0dfcbb0bf..0636625df 100644 --- a/frontend/src/pages/secret-manager/integrations/HashicorpVaultConfigurePage/HashicorpVaultConfigurePage.tsx +++ b/frontend/src/pages/secret-manager/integrations/HashicorpVaultConfigurePage/HashicorpVaultConfigurePage.tsx @@ -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 ? ( diff --git a/frontend/src/pages/secret-manager/integrations/OctopusDeployAuthorizePage/OctopusDeployAuthorizePage.tsx b/frontend/src/pages/secret-manager/integrations/OctopusDeployAuthorizePage/OctopusDeployAuthorizePage.tsx index 21851e4cd..9e50fd43d 100644 --- a/frontend/src/pages/secret-manager/integrations/OctopusDeployAuthorizePage/OctopusDeployAuthorizePage.tsx +++ b/frontend/src/pages/secret-manager/integrations/OctopusDeployAuthorizePage/OctopusDeployAuthorizePage.tsx @@ -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 ( diff --git a/frontend/src/pages/secret-manager/integrations/OctopusDeployConfigurePage/OctopusDeployConfigurePage.tsx b/frontend/src/pages/secret-manager/integrations/OctopusDeployConfigurePage/OctopusDeployConfigurePage.tsx index 5b531ac2d..75f8f5031 100644 --- a/frontend/src/pages/secret-manager/integrations/OctopusDeployConfigurePage/OctopusDeployConfigurePage.tsx +++ b/frontend/src/pages/secret-manager/integrations/OctopusDeployConfigurePage/OctopusDeployConfigurePage.tsx @@ -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(() => { diff --git a/frontend/src/pages/user/PersonalSettingsPage/components/ChangeEmailSection/ChangeEmailSection.tsx b/frontend/src/pages/user/PersonalSettingsPage/components/ChangeEmailSection/ChangeEmailSection.tsx index c9d457e44..bd37e5620 100644 --- a/frontend/src/pages/user/PersonalSettingsPage/components/ChangeEmailSection/ChangeEmailSection.tsx +++ b/frontend/src/pages/user/PersonalSettingsPage/components/ChangeEmailSection/ChangeEmailSection.tsx @@ -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" - }); } } }; diff --git a/frontend/src/pages/user/PersonalSettingsPage/components/ChangePasswordSection/ChangePasswordSection.tsx b/frontend/src/pages/user/PersonalSettingsPage/components/ChangePasswordSection/ChangePasswordSection.tsx index 552eab741..1ae492162 100644 --- a/frontend/src/pages/user/PersonalSettingsPage/components/ChangePasswordSection/ChangePasswordSection.tsx +++ b/frontend/src/pages/user/PersonalSettingsPage/components/ChangePasswordSection/ChangePasswordSection.tsx @@ -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 ( diff --git a/frontend/src/pages/user/PersonalSettingsPage/components/DeleteAccountSection/DeleteAccountSection.tsx b/frontend/src/pages/user/PersonalSettingsPage/components/DeleteAccountSection/DeleteAccountSection.tsx index 5761a772a..301942346 100644 --- a/frontend/src/pages/user/PersonalSettingsPage/components/DeleteAccountSection/DeleteAccountSection.tsx +++ b/frontend/src/pages/user/PersonalSettingsPage/components/DeleteAccountSection/DeleteAccountSection.tsx @@ -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 ( diff --git a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MFASection.tsx b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MFASection.tsx index ef29f3ff6..74f4ed99b 100644 --- a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MFASection.tsx +++ b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MFASection.tsx @@ -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); } diff --git a/frontend/src/pages/user/PersonalSettingsPage/components/SessionsSection/SessionsTable.tsx b/frontend/src/pages/user/PersonalSettingsPage/components/SessionsSection/SessionsTable.tsx index 027f2ed46..f37be42a1 100644 --- a/frontend/src/pages/user/PersonalSettingsPage/components/SessionsSection/SessionsTable.tsx +++ b/frontend/src/pages/user/PersonalSettingsPage/components/SessionsSection/SessionsTable.tsx @@ -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"); }; diff --git a/frontend/src/pages/user/PersonalSettingsPage/components/UserNameSection/UserNameSection.tsx b/frontend/src/pages/user/PersonalSettingsPage/components/UserNameSection/UserNameSection.tsx index df0dae9cb..1e06d298f 100644 --- a/frontend/src/pages/user/PersonalSettingsPage/components/UserNameSection/UserNameSection.tsx +++ b/frontend/src/pages/user/PersonalSettingsPage/components/UserNameSection/UserNameSection.tsx @@ -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 ( From dbd4a9ea516ac1614e08d6ebab5ef8cc509f2a20 Mon Sep 17 00:00:00 2001 From: x032205 Date: Mon, 3 Nov 2025 13:27:13 -0500 Subject: [PATCH 19/28] added log searching, improved minor styling --- .../v2/HighlightText/HighlightText.tsx | 28 ++-------- .../components/PamSessionLogOutput.tsx | 19 +++++-- .../components/PamSessionLogsSection.tsx | 56 +++++++++++++++---- .../components/PamSessionRow.tsx | 34 ++++++----- 4 files changed, 84 insertions(+), 53 deletions(-) diff --git a/frontend/src/components/v2/HighlightText/HighlightText.tsx b/frontend/src/components/v2/HighlightText/HighlightText.tsx index c81dab2df..92fdc1d6d 100644 --- a/frontend/src/components/v2/HighlightText/HighlightText.tsx +++ b/frontend/src/components/v2/HighlightText/HighlightText.tsx @@ -9,22 +9,10 @@ export const HighlightText = ({ }) => { if (!text) return null; - const renderTextWithNewlines = (input: string, baseKeyPrefix: string = ""): React.ReactNode[] => { - if (!input) return []; - const lines = input.split("\n"); - return lines.flatMap((line, index) => { - const nodes: React.ReactNode[] = [line]; - if (index < lines.length - 1) { - nodes.push(
); - } - return nodes; - }); - }; - const searchTerm = highlight.toLowerCase().trim(); if (!searchTerm) { - return {renderTextWithNewlines(text, "full-text")}; + return {text}; } const parts: React.ReactNode[] = []; @@ -36,16 +24,12 @@ export const HighlightText = ({ text.replace(regex, (match: string, offset: number) => { if (offset > lastIndex) { const preMatchText = text.substring(lastIndex, offset); - parts.push( - - {renderTextWithNewlines(preMatchText, `pre-${lastIndex}`)} - - ); + parts.push({preMatchText}); } parts.push( - {renderTextWithNewlines(match, `match-${offset}`)} + {match} ); @@ -56,11 +40,7 @@ export const HighlightText = ({ if (lastIndex < text.length) { const postMatchText = text.substring(lastIndex); - parts.push( - - {renderTextWithNewlines(postMatchText, `post-${lastIndex}`)} - - ); + parts.push({postMatchText}); } return parts; diff --git a/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionLogOutput.tsx b/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionLogOutput.tsx index a0cfb6cb9..99e30627d 100644 --- a/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionLogOutput.tsx +++ b/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionLogOutput.tsx @@ -1,5 +1,6 @@ import { useState } from "react"; +import { HighlightText } from "@app/components/v2/HighlightText"; import { PamResourceType } from "@app/hooks/api/pam"; type TableLog = { @@ -10,10 +11,12 @@ type TableLog = { export const PamSessionLogOutput = ({ content, - resourceType + resourceType, + search }: { content: string; resourceType: PamResourceType; + search: string; }) => { const [isRawView, setIsRawView] = useState(false); @@ -45,7 +48,9 @@ export const PamSessionLogOutput = ({ return (

{isRawView ? ( -
{content}
+
+ +
) : ( <> {parsedContent.command && ( @@ -57,7 +62,7 @@ export const PamSessionLogOutput = ({ {headers.map((header) => ( - {header.replace(/_/g, " ")} + ))} @@ -71,7 +76,7 @@ export const PamSessionLogOutput = ({ > {headers.map((header) => ( - {String(row[header] ?? "")} + ))} @@ -103,5 +108,9 @@ export const PamSessionLogOutput = ({ ); } - return
{content}
; + return ( +
+ +
+ ); }; diff --git a/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionLogsSection.tsx b/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionLogsSection.tsx index b3c287380..0fbccbc9b 100644 --- a/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionLogsSection.tsx +++ b/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionLogsSection.tsx @@ -1,8 +1,10 @@ -import { useState } from "react"; -import { faChevronRight } from "@fortawesome/free-solid-svg-icons"; +import { useMemo, useState } from "react"; +import { faChevronRight, faMagnifyingGlass } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { twMerge } from "tailwind-merge"; +import { Input } from "@app/components/v2"; +import { HighlightText } from "@app/components/v2/HighlightText"; import { TPamSession } from "@app/hooks/api/pam"; import { PamSessionLogOutput } from "./PamSessionLogOutput"; @@ -14,6 +16,7 @@ type Props = { export const PamSessionLogsSection = ({ session }: Props) => { const [expandedLogTimestamps, setExpandedLogTimestamps] = useState>(new Set()); + const [search, setSearch] = useState(""); const toggleExpand = (timestamp: string) => { setExpandedLogTimestamps((prev) => { @@ -24,15 +27,43 @@ export const PamSessionLogsSection = ({ session }: Props) => { }); }; + const filteredLogs = useMemo( + () => + session.commandLogs.filter((log) => { + const { input, output } = log; + + const searchValue = search.trim().toLowerCase(); + + return ( + input.toLowerCase().includes(searchValue) || output.toLowerCase().includes(searchValue) + ); + }), + [session.commandLogs, search] + ); + return (

Session Logs

-
- {session.commandLogs.length > 0 ? ( - session.commandLogs.map((log) => { - const isExpanded = expandedLogTimestamps.has(log.timestamp); + +
+ { + const newSearch = e.target.value; + setSearch(newSearch); + }} + leftIcon={} + placeholder="Search logs..." + className="flex-1 bg-mineshaft-800" + containerClassName="bg-transparent" + /> +
+
+ {filteredLogs.length > 0 ? ( + filteredLogs.map((log) => { + const isExpanded = search.length || expandedLogTimestamps.has(log.timestamp); const formattedInput = formatLogContent(log.input); return ( @@ -62,7 +93,7 @@ export const PamSessionLogsSection = ({ session }: Props) => { isExpanded ? "break-all whitespace-pre-wrap" : "truncate" }`} > - {formattedInput} +
{
@@ -93,8 +125,12 @@ export const PamSessionLogsSection = ({ session }: Props) => { ); }) ) : ( -
- {session.startedAt && session.endedAt ? ( +
+ {search.length ? ( +
+
No logs match search criteria
+
+ ) : (
Session logs are not yet available
@@ -103,8 +139,6 @@ export const PamSessionLogsSection = ({ session }: Props) => { If logs do not appear after some time, please contact your Gateway administrators.
- ) : ( - "No session logs" )}
)} diff --git a/frontend/src/pages/pam/PamSessionsPage/components/PamSessionRow.tsx b/frontend/src/pages/pam/PamSessionsPage/components/PamSessionRow.tsx index f730e331d..8721560c4 100644 --- a/frontend/src/pages/pam/PamSessionsPage/components/PamSessionRow.tsx +++ b/frontend/src/pages/pam/PamSessionsPage/components/PamSessionRow.tsx @@ -27,6 +27,7 @@ import { HighlightText } from "@app/components/v2/HighlightText"; import { ProjectPermissionActions, ProjectPermissionSub } from "@app/context"; import { PAM_RESOURCE_TYPE_MAP, TPamSession } from "@app/hooks/api/pam"; +import { formatLogContent } from "../../PamSessionsByIDPage/components/PamSessionLogsSection.utils"; import { PamSessionStatusBadge } from "./PamSessionStatusBadge"; type Props = { @@ -159,21 +160,28 @@ export const PamSessionRow = ({ session, search, filteredCommandLogs }: Props) = {filteredCommandLogs.length > 0 && ( - {logsToShow.map((log) => ( -
-
- - {new Date(log.timestamp).toLocaleString()} -
+ {logsToShow.map((log) => { + const formattedInput = formatLogContent(log.input); -
- + return ( +
+
+ + {new Date(log.timestamp).toLocaleString()} +
+ +
+ +
+
+ +
-
- -
-
- ))} + ); + })} {filteredCommandLogs.length > LOGS_TO_SHOW && (