Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

feat(infisical-pg): auth injection completed and validation in password router

Akhil Mohanf3b37de3f3d6
diff --git a/backend-pg/.eslintrc.js b/backend-pg/.eslintrc.js
index 5d564d416a..6d62176347 100644
--- a/backend-pg/.eslintrc.js
+++ b/backend-pg/.eslintrc.js
@@ -18,6 +18,7 @@ module.exports = {
"import/first": "error",
"import/newline-after-import": "error",
"import/no-duplicates": "error",
+ "consistent-return": "off",
"simple-import-sort/imports": [
"warn",
{
diff --git a/backend-pg/package.json b/backend-pg/package.json
index 6499ab5e9c..93e94eac36 100644
--- a/backend-pg/package.json
+++ b/backend-pg/package.json
@@ -11,6 +11,7 @@
"lint:fix": "eslint --fix 'src/**/*.ts'",
"lint": "eslint 'src/**/*.ts'",
"generate:component": "tsx ./scripts/create-backend-file.ts",
+ "generate:schema": "tsx ./scripts/generate-schema-types.ts",
"migration:new": "tsx ./scripts/create-migration.ts",
"migration:up": "knex --knexfile ./src/db/knexfile.ts --client pg migrate:up",
"migration:down": "knex --knexfile ./src/db/knexfile.ts --client pg migrate:down",
diff --git a/backend-pg/scripts/create-backend-file.ts b/backend-pg/scripts/create-backend-file.ts
index 2ea0a773a5..3b1cb96c80 100644
--- a/backend-pg/scripts/create-backend-file.ts
+++ b/backend-pg/scripts/create-backend-file.ts
@@ -10,7 +10,6 @@ console.log(`
Component List
--------------
1. Service component
-2. Schema file
`);
const componentType = parseInt(prompt("Select a component: "), 10);
@@ -55,27 +54,4 @@ export const ${serviceName} = ({ ${componentName}Dal }: ${serviceTypeName}Dep) =
`
);
writeFileSync(path.join(dir, `${componentName}-types.ts`), "");
-} else if (componentType === 2) {
- const componentName = prompt("Type component name in lowercase with space seperated: ");
- const dashcase = componentName.split(" ").join("-");
- const pascalCase = componentName
- .split(" ")
- .reduce(
- (prev, curr) => prev + `${curr.at(0)?.toUpperCase()}${curr.slice(1).toLowerCase()}`,
- ""
- );
- writeFileSync(
- path.join(__dirname, "../src/db/schemas", `${dashcase}.ts`),
- `
-import { z } from "zod";
-
-import { TImmutableDBKeys } from "./models";
-
-export const ${pascalCase}Schema = z.object({});
-
-export type T${pascalCase} = z.infer<typeof ${pascalCase}Schema>;
-export type T${pascalCase}Insert = Omit<T${pascalCase}, TImmutableDBKeys>;
-export type T${pascalCase}Update = Partial<Omit<T${pascalCase}, TImmutableDBKeys>>;
-`
- );
}
diff --git a/backend-pg/scripts/generate-schema-types.ts b/backend-pg/scripts/generate-schema-types.ts
new file mode 100644
index 0000000000..5c279f7f31
--- /dev/null
+++ b/backend-pg/scripts/generate-schema-types.ts
@@ -0,0 +1,163 @@
+import dotenv from "dotenv";
+import path from "path";
+import knex from "knex";
+import { appendFileSync, readFileSync, writeFileSync } from "fs";
+import promptSync from "prompt-sync";
+
+const prompt = promptSync();
+
+dotenv.config({
+ path: path.join(__dirname, "../.env"),
+ debug: true
+});
+
+const db = knex({
+ client: "pg",
+ connection: process.env.DB_CONNECTION_URI
+});
+
+const getZodPrimitiveType = (type: string) => {
+ switch (type) {
+ case "uuid":
+ return "z.string().uuid()";
+ case "character varying":
+ return "z.string()";
+ case "ARRAY":
+ return "z.string().array()";
+ case "boolean":
+ return "z.boolean()";
+ case "jsonb":
+ return "z.string()";
+ case "json":
+ return "z.string()";
+ case "timestamp with time zone":
+ return "z.string().datetime()";
+ case "integer":
+ return "z.number()";
+ case "text":
+ return "z.string()";
+ default:
+ throw new Error(`Invalid type: ${type}`);
+ }
+};
+
+const getZodDefaultValue = (type: unknown, value: string | number | boolean | Object) => {
+ if (!value || value === "null") return;
+ switch (type) {
+ case "uuid":
+ return;
+ case "character varying": {
+ if (typeof value === "string" && value.includes("::")) {
+ return `.default(${value.split("::")[0]})`;
+ }
+ return `.default(${value})`;
+ }
+ case "ARRAY":
+ return `.default(${value})`;
+ case "boolean":
+ return `.default(${value})`;
+ case "jsonb":
+ return "z.string()";
+ case "json":
+ return "z.string()";
+ case "timestamp with time zone": {
+ if (value === "CURRENT_TIMESTAMP") return;
+ return "z.string().datetime()";
+ }
+ case "integer": {
+ if ((value as string).includes("nextval")) return;
+ return `.default(${value})`;
+ }
+ case "text":
+ if (typeof value === "string" && value.includes("::")) {
+ return `.default(${value.split("::")[0]})`;
+ }
+ return `.default(${value})`;
+ default:
+ throw new Error(`Invalid type: ${type}`);
+ }
+};
+
+const main = async () => {
+ const tables = (
+ await db("information_schema.tables")
+ .whereRaw("table_schema = current_schema()")
+ .select<{ tableName: string }[]>("table_name as tableName")
+ .orderBy("table_name")
+ ).filter(
+ (el) => el.tableName !== "infisical_migrations_lock" && el.tableName !== "infisical_migrations"
+ );
+
+ console.log("Select a table to generate schema");
+ console.table(tables);
+ console.log("all: all tables");
+ const selectedTables = prompt("Type table numbers comma seperated: ");
+ const tableNumbers =
+ selectedTables !== "all" ? selectedTables.split(",").map((el) => Number(el)) : [];
+
+ for (let i = 0; i < tables.length; i++) {
+ // skip if not desired table
+ if (selectedTables !== "all" && !tableNumbers.includes(i)) continue;
+
+ const tableName = tables[i].tableName;
+ const columns = await db(tableName).columnInfo();
+ const columnNames = Object.keys(columns);
+
+ let schema = "";
+ for (let colNum = 0; colNum < columnNames.length; colNum++) {
+ const columnName = columnNames[colNum];
+ const colInfo = columns[columnName];
+ let ztype = getZodPrimitiveType(colInfo.type);
+ if (colInfo.defaultValue) {
+ const defaultValue = colInfo.defaultValue;
+ const zSchema = getZodDefaultValue(colInfo.type, defaultValue);
+ if (zSchema) {
+ ztype = ztype.concat(zSchema);
+ }
+ }
+ if (colInfo.nullable) {
+ ztype = ztype.concat(".nullable().optional()");
+ }
+ schema = schema.concat(`${!schema ? "\n" : ""} ${columnName}: ${ztype},\n`);
+ }
+
+ const dashcase = tableName.split("_").join("-");
+ const pascalCase = tableName
+ .split("_")
+ .reduce(
+ (prev, curr) => prev + `${curr.at(0)?.toUpperCase()}${curr.slice(1).toLowerCase()}`,
+ ""
+ );
+ writeFileSync(
+ path.join(__dirname, "../src/db/schemas", `${dashcase}.ts`),
+ `// Code generated by automation script, DO NOT EDIT.
+// Automated by pulling database and generating zod schema
+// To update. Just run npm run generate:schema
+// Written by akhilmhdh.
+
+import { z } from "zod";
+
+import { TImmutableDBKeys } from "./models";
+
+export const ${pascalCase}Schema = z.object({${schema}});
+
+export type T${pascalCase} = z.infer<typeof ${pascalCase}Schema>;
+export type T${pascalCase}Insert = Omit<T${pascalCase}, TImmutableDBKeys>;
+export type T${pascalCase}Update = Partial<Omit<T${pascalCase}, TImmutableDBKeys>>;
+`
+ );
+
+ // const file = readFileSync(path.join(__dirname, "../src/db/schemas/index.ts"), "utf8");
+ // if (!file.includes(`export * from "./${dashcase};"`)) {
+ // appendFileSync(
+ // path.join(__dirname, "../src/db/schemas/index.ts"),
+ // `\nexport * from "./${dashcase}";`,
+ // "utf8"
+ // );
+ // }
+ }
+
+ process.exit(0);
+};
+
+main();
diff --git a/backend-pg/src/@types/fastify.d.ts b/backend-pg/src/@types/fastify.d.ts
index 33b744166e..01833e08f8 100644
--- a/backend-pg/src/@types/fastify.d.ts
+++ b/backend-pg/src/@types/fastify.d.ts
@@ -3,6 +3,8 @@ import { TAuthDalFactory } from "@app/services/auth/auth-dal";
import { TAuthLoginFactory } from "@app/services/auth/auth-login-service";
import { TAuthPasswordFactory } from "@app/services/auth/auth-password-service";
import { TAuthSignupFactory } from "@app/services/auth/auth-signup-service";
+import { AuthMode } from "@app/services/auth/auth-signup-type";
+import { TAuthTokenServiceFactory } from "@app/services/token/token-service";
import "fastify";
@@ -14,6 +16,12 @@ declare module "fastify" {
userId: string;
user: TUser;
};
+ // identity injection. depending on which kinda of token the information is filled in auth
+ auth: {
+ authMode: AuthMode.JWT | AuthMode.API_KEY_V2 | AuthMode.API_KEY;
+ userId: string;
+ user: TUser;
+ };
}
interface FastifyInstance {
@@ -21,6 +29,7 @@ declare module "fastify" {
login: TAuthLoginFactory;
password: TAuthPasswordFactory;
signup: TAuthSignupFactory;
+ authToken: TAuthTokenServiceFactory;
};
// this is exclusive use for middlewares in which we need to inject data
diff --git a/backend-pg/src/@types/knex.d.ts b/backend-pg/src/@types/knex.d.ts
index 8b3776fe3b..09e8935f51 100644
--- a/backend-pg/src/@types/knex.d.ts
+++ b/backend-pg/src/@types/knex.d.ts
@@ -2,42 +2,58 @@ import { Knex } from "knex";
import {
TableName,
+ TAuthTokens,
+ TAuthTokenSessions,
+ TAuthTokenSessionsInsert,
+ TAuthTokenSessionsUpdate,
+ TAuthTokensUpdate,
TBackupPrivateKey,
TBackupPrivateKeyInsert,
- TToken,
- TTokenInsert,
- TTokenUpdate,
- TUser,
- TUserEncryptionKey,
- TUserEncryptionKeyInsert,
- TUserEncryptionKeyUpdate,
- TUserInsert,
- TUserUpdate
+ TBackupPrivateKeyUpdate,
+ TOrganizationMemberships,
+ TOrganizations,
+ TOrganizationsInsert,
+ TOrganizationsUpdate,
+ TUserEncryptionKeys,
+ TUserEncryptionKeysInsert,
+ TUserEncryptionKeysUpdate,
+ TUsers,
+ TUsersInsert,
+ TUsersUpdate
} from "@app/db/schemas";
-import {
- TTokenSession,
- TTokenSessionInsert,
- TTokenSessionUpdate
-} from "@app/db/schemas/token-session";
declare module "knex/types/tables" {
interface Tables extends { [key in TableName]: Knex.CompositeTableType<any> } {
- [TableName.Users]: Knex.CompositeTableType<TUser, TUserInsert, TUserUpdate>;
+ [TableName.Users]: Knex.CompositeTableType<TUsers, TUsersInsert, TUsersUpdate>;
[TableName.UserEncryptionKey]: Knex.CompositeTableType<
- TUserEncryptionKey,
- TUserEncryptionKeyInsert,
- TUserEncryptionKeyUpdate
+ TUserEncryptionKeys,
+ TUserEncryptionKeysInsert,
+ TUserEncryptionKeysUpdate
+ >;
+ [TableName.AuthTokens]: Knex.CompositeTableType<
+ TAuthTokens,
+ TAuthTokensInsert,
+ TAuthTokensUpdate
>;
- [TableName.AuthTokens]: Knex.CompositeTableType<TToken, TTokenInsert, TTokenUpdate>;
[TableName.AuthTokenSession]: Knex.CompositeTableType<
- TTokenSession,
- TTokenSessionInsert,
- TTokenSessionUpdate
+ TAuthTokenSessions,
+ TAuthTokenSessionsInsert,
+ TAuthTokenSessionsUpdate
>;
[TableName.BackupPrivateKey]: Knex.CompositeTableType<
TBackupPrivateKey,
TBackupPrivateKeyInsert,
- TTokenSessionUpdate
+ TBackupPrivateKeyUpdate
+ >;
+ [TableName.Organization]: Knex.CompositeTableType<
+ TOrganizations,
+ TOrganizationsInsert,
+ TOrganizationsUpdate
+ >;
+ [TableName.OrgMembership]: Knex.CompositeTableType<
+ TOrganizationMemberships,
+ TOrganizationsInsert,
+ TOrganizationsUpdate
>;
}
}
diff --git a/backend-pg/src/db/migrations/20231128072457_user.ts b/backend-pg/src/db/migrations/20231128072457_user.ts
index 9fd26031c8..f0572824e6 100644
--- a/backend-pg/src/db/migrations/20231128072457_user.ts
+++ b/backend-pg/src/db/migrations/20231128072457_user.ts
@@ -12,7 +12,7 @@ export async function up(knex: Knex): Promise<void> {
const isTablePresent = await knex.schema.hasTable(TableName.Users);
if (!isTablePresent) {
await knex.schema.createTable(TableName.Users, (t) => {
- t.uuid("id").primary().defaultTo(knex.fn.uuid());
+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
t.string("email").notNullable();
t.specificType("authMethods", "text[]");
t.boolean("superAdmin").defaultTo(false);
diff --git a/backend-pg/src/db/migrations/20231128092347_user-encryption-key.ts b/backend-pg/src/db/migrations/20231128092347_user-encryption-key.ts
index b9b3124560..153aeb077c 100644
--- a/backend-pg/src/db/migrations/20231128092347_user-encryption-key.ts
+++ b/backend-pg/src/db/migrations/20231128092347_user-encryption-key.ts
@@ -6,10 +6,10 @@ export async function up(knex: Knex): Promise<void> {
const isTablePresent = await knex.schema.hasTable(TableName.UserEncryptionKey);
if (!isTablePresent) {
await knex.schema.createTable(TableName.UserEncryptionKey, (t) => {
- t.increments().primary();
+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
t.text("clientPublicKey");
t.text("serverPrivateKey");
- t.text("encryptionVersion").defaultTo(1);
+ t.integer("encryptionVersion").defaultTo(1);
t.text("protectedKey").notNullable();
t.text("protectedKeyIV").notNullable();
t.text("protectedKeyTag").notNullable();
diff --git a/backend-pg/src/db/migrations/20231129072939_auth-token.ts b/backend-pg/src/db/migrations/20231129072939_auth-token.ts
index 0b186b8b0b..ed23ebe9d3 100644
--- a/backend-pg/src/db/migrations/20231129072939_auth-token.ts
+++ b/backend-pg/src/db/migrations/20231129072939_auth-token.ts
@@ -6,6 +6,7 @@ export async function up(knex: Knex): Promise<void> {
const isTablePresent = await knex.schema.hasTable(TableName.AuthTokens);
if (!isTablePresent) {
await knex.schema.createTable(TableName.AuthTokens, (t) => {
+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
t.string("type").notNullable();
t.string("phoneNumber");
t.string("tokenHash").notNullable();
diff --git a/backend-pg/src/db/migrations/20231130072734_auth-token-session.ts b/backend-pg/src/db/migrations/20231130072734_auth-token-session.ts
index 4acde142fd..9d5b98910f 100644
--- a/backend-pg/src/db/migrations/20231130072734_auth-token-session.ts
+++ b/backend-pg/src/db/migrations/20231130072734_auth-token-session.ts
@@ -7,7 +7,7 @@ export async function up(knex: Knex): Promise<void> {
const isTablePresent = await knex.schema.hasTable(TableName.AuthTokenSession);
if (!isTablePresent) {
await knex.schema.createTable(TableName.AuthTokenSession, (t) => {
- t.increments();
+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
t.string("ip").notNullable();
t.string("userAgent");
t.integer("refreshVersion").notNullable().defaultTo(1);
diff --git a/backend-pg/src/db/migrations/20231201151432_backup-key.ts b/backend-pg/src/db/migrations/20231201151432_backup-key.ts
index 2f7ff96652..3672ffacec 100644
--- a/backend-pg/src/db/migrations/20231201151432_backup-key.ts
+++ b/backend-pg/src/db/migrations/20231201151432_backup-key.ts
@@ -6,7 +6,7 @@ export async function up(knex: Knex): Promise<void> {
const doesTableExist = await knex.schema.hasTable(TableName.BackupPrivateKey);
if (!doesTableExist) {
await knex.schema.createTable(TableName.BackupPrivateKey, (t) => {
- t.increments();
+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
t.string("encryptedPrivateKey").notNullable();
t.string("iv").notNullable();
t.string("tag").notNullable();
diff --git a/backend-pg/src/db/migrations/20231204092737_organization.ts b/backend-pg/src/db/migrations/20231204092737_organization.ts
new file mode 100644
index 0000000000..45badacb9b
--- /dev/null
+++ b/backend-pg/src/db/migrations/20231204092737_organization.ts
@@ -0,0 +1,24 @@
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+import { createOnUpdateTrigger, dropOnUpdateTrigger } from "../utils";
+
+export async function up(knex: Knex): Promise<void> {
+ const isTablePresent = await knex.schema.hasTable(TableName.Organization);
+ if (!isTablePresent) {
+ await knex.schema.createTable(TableName.Organization, (t) => {
+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
+ t.string("name").notNullable();
+ t.string("customerId");
+ // does not need update trigger we will do it manually
+ t.timestamps(true, true, true);
+ });
+ }
+ // this is a one time function
+ await createOnUpdateTrigger(knex, TableName.Organization);
+}
+
+export async function down(knex: Knex): Promise<void> {
+ await knex.schema.dropTableIfExists(TableName.Organization);
+ await dropOnUpdateTrigger(knex, TableName.Organization);
+}
diff --git a/backend-pg/src/db/migrations/20231204092747_org-membership.ts b/backend-pg/src/db/migrations/20231204092747_org-membership.ts
new file mode 100644
index 0000000000..20e6e2fef8
--- /dev/null
+++ b/backend-pg/src/db/migrations/20231204092747_org-membership.ts
@@ -0,0 +1,30 @@
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+import { OrgMembershipStatus } from "../schemas/models";
+import { createOnUpdateTrigger, dropOnUpdateTrigger } from "../utils";
+
+export async function up(knex: Knex): Promise<void> {
+ const isTablePresent = await knex.schema.hasTable(TableName.OrgMembership);
+ if (!isTablePresent) {
+ await knex.schema.createTable(TableName.OrgMembership, (t) => {
+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
+ t.string("role").notNullable();
+ t.string("status").notNullable().defaultTo(OrgMembershipStatus.Invited);
+ t.string("inviteEmail");
+ // does not need update trigger we will do it manually
+ t.timestamps(true, true, true);
+ t.uuid("userId").notNullable();
+ t.foreign("userId").references("id").inTable(TableName.Users).onDelete("CASCADE");
+ t.uuid("orgId").notNullable();
+ t.foreign("orgId").references("id").inTable(TableName.Organization).onDelete("CASCADE");
+ });
+ }
+ // this is a one time function
+ await createOnUpdateTrigger(knex, TableName.OrgMembership);
+}
+
+export async function down(knex: Knex): Promise<void> {
+ await knex.schema.dropTableIfExists(TableName.OrgMembership);
+ await dropOnUpdateTrigger(knex, TableName.OrgMembership);
+}
diff --git a/backend-pg/src/db/schemas/auth-token-sessions.ts b/backend-pg/src/db/schemas/auth-token-sessions.ts
new file mode 100644
index 0000000000..dd4fd94160
--- /dev/null
+++ b/backend-pg/src/db/schemas/auth-token-sessions.ts
@@ -0,0 +1,24 @@
+// Code generated by automation script, DO NOT EDIT.
+// Automated by pulling database and generating zod schema
+// To update. Just run npm run generate:schema
+// Written by akhilmhdh.
+
+import { z } from "zod";
+
+import { TImmutableDBKeys } from "./models";
+
+export const AuthTokenSessionsSchema = z.object({
+ id: z.string().uuid(),
+ ip: z.string(),
+ userAgent: z.string().nullable().optional(),
+ refreshVersion: z.number().default(1),
+ accessVersion: z.number().default(1),
+ lastUsed: z.string().datetime(),
+ createdAt: z.string().datetime(),
+ updatedAt: z.string().datetime(),
+ userId: z.string().uuid(),
+});
+
+export type TAuthTokenSessions = z.infer<typeof AuthTokenSessionsSchema>;
+export type TAuthTokenSessionsInsert = Omit<TAuthTokenSessions, TImmutableDBKeys>;
+export type TAuthTokenSessionsUpdate = Partial<Omit<TAuthTokenSessions, TImmutableDBKeys>>;
diff --git a/backend-pg/src/db/schemas/auth-tokens.ts b/backend-pg/src/db/schemas/auth-tokens.ts
new file mode 100644
index 0000000000..a471461707
--- /dev/null
+++ b/backend-pg/src/db/schemas/auth-tokens.ts
@@ -0,0 +1,24 @@
+// Code generated by automation script, DO NOT EDIT.
+// Automated by pulling database and generating zod schema
+// To update. Just run npm run generate:schema
+// Written by akhilmhdh.
+
+import { z } from "zod";
+
+import { TImmutableDBKeys } from "./models";
+
+export const AuthTokensSchema = z.object({
+ id: z.string().uuid(),
+ type: z.string(),
+ phoneNumber: z.string().nullable().optional(),
+ tokenHash: z.string(),
+ triesLeft: z.number().nullable().optional(),
+ expiresAt: z.string().datetime(),
+ createdAt: z.string().datetime(),
+ updatedAt: z.string().datetime(),
+ userId: z.string().uuid().nullable().optional(),
+});
+
+export type TAuthTokens = z.infer<typeof AuthTokensSchema>;
+export type TAuthTokensInsert = Omit<TAuthTokens, TImmutableDBKeys>;
+export type TAuthTokensUpdate = Partial<Omit<TAuthTokens, TImmutableDBKeys>>;
diff --git a/backend-pg/src/db/schemas/backup-private-key.ts b/backend-pg/src/db/schemas/backup-private-key.ts
index 73bcc59a13..bb2b8a048b 100644
--- a/backend-pg/src/db/schemas/backup-private-key.ts
+++ b/backend-pg/src/db/schemas/backup-private-key.ts
@@ -1,19 +1,24 @@
+// Code generated by automation script, DO NOT EDIT.
+// Automated by pulling database and generating zod schema
+// To update. Just run npm run generate:schema
+// Written by akhilmhdh.
+
import { z } from "zod";
-import { SecretEncryptionAlgo, SecretKeyEncoding, TImmutableDBKeys } from "./models";
+import { TImmutableDBKeys } from "./models";
export const BackupPrivateKeySchema = z.object({
- id: z.string(),
- userId: z.string(),
+ id: z.string().uuid(),
encryptedPrivateKey: z.string(),
iv: z.string(),
tag: z.string(),
- algorithm: z.nativeEnum(SecretEncryptionAlgo),
- keyEncoding: z.nativeEnum(SecretKeyEncoding),
+ algorithm: z.string(),
+ keyEncoding: z.string(),
salt: z.string(),
verifier: z.string(),
createdAt: z.string().datetime(),
- updatedAt: z.string().datetime()
+ updatedAt: z.string().datetime(),
+ userId: z.string().uuid(),
});
export type TBackupPrivateKey = z.infer<typeof BackupPrivateKeySchema>;
diff --git a/backend-pg/src/db/schemas/index.ts b/backend-pg/src/db/schemas/index.ts
index 33c7fea0f2..b63b35e147 100644
--- a/backend-pg/src/db/schemas/index.ts
+++ b/backend-pg/src/db/schemas/index.ts
@@ -1,15 +1,8 @@
-export {
- BackupPrivateKeySchema,
- TBackupPrivateKey,
- TBackupPrivateKeyInsert,
- TBackupPrivateKeyUpdate
-} from "./backup-private-key";
-export { TableName } from "./models";
-export { TokenSchema, TToken, TTokenInsert, TTokenUpdate } from "./token";
-export { AuthMethod, TUser, TUserInsert, TUserUpdate, UserSchema } from "./user";
-export {
- TUserEncryptionKey,
- TUserEncryptionKeyInsert,
- TUserEncryptionKeyUpdate,
- UserEncryptionKey
-} from "./user-encryption-key";
+export * from "./auth-token-sessions";
+export * from "./auth-tokens";
+export * from "./backup-private-key";
+export * from "./models";
+export * from "./organization-memberships";
+export * from "./organizations";
+export * from "./user-encryption-keys";
+export * from "./users";
diff --git a/backend-pg/src/db/schemas/models.ts b/backend-pg/src/db/schemas/models.ts
index 8c9cc0daa7..9be605cd2c 100644
--- a/backend-pg/src/db/schemas/models.ts
+++ b/backend-pg/src/db/schemas/models.ts
@@ -1,13 +1,36 @@
+import { z } from "zod";
+
export enum TableName {
Users = "users",
UserEncryptionKey = "user_encryption_keys",
AuthTokens = "auth_tokens",
AuthTokenSession = "auth_token_sessions",
- BackupPrivateKey = "backup_private_key"
+ BackupPrivateKey = "backup_private_key",
+ Organization = "organizations",
+ OrgMembership = "organization_memberships"
}
export type TImmutableDBKeys = "id" | "createdAt" | "updatedAt";
+export const UserDeviceSchema = z
+ .object({
+ ip: z.string(),
+ userAgent: z.string()
+ })
+ .array()
+ .default([]);
+
+export enum OrgMembershipRole {
+ Admin = "admin",
+ Member = "member",
+ Custom = "custom"
+}
+
+export enum OrgMembershipStatus {
+ Invited = "invited",
+ Accepted = "accepted"
+}
+
export enum SecretEncryptionAlgo {
AES_256_GCM = "aes-256-gcm"
}
diff --git a/backend-pg/src/db/schemas/organization-memberships.ts b/backend-pg/src/db/schemas/organization-memberships.ts
new file mode 100644
index 0000000000..97cf01dbd6
--- /dev/null
+++ b/backend-pg/src/db/schemas/organization-memberships.ts
@@ -0,0 +1,23 @@
+// Code generated by automation script, DO NOT EDIT.
+// Automated by pulling database and generating zod schema
+// To update. Just run npm run generate:schema
+// Written by akhilmhdh.
+
+import { z } from "zod";
+
+import { TImmutableDBKeys } from "./models";
+
+export const OrganizationMembershipsSchema = z.object({
+ id: z.string().uuid(),
+ role: z.string(),
+ status: z.string().default('invited'),
+ inviteEmail: z.string().nullable().optional(),
+ createdAt: z.string().datetime(),
+ updatedAt: z.string().datetime(),
+ userId: z.string().uuid(),
+ orgId: z.string().uuid(),
+});
+
+export type TOrganizationMemberships = z.infer<typeof OrganizationMembershipsSchema>;
+export type TOrganizationMembershipsInsert = Omit<TOrganizationMemberships, TImmutableDBKeys>;
+export type TOrganizationMembershipsUpdate = Partial<Omit<TOrganizationMemberships, TImmutableDBKeys>>;
diff --git a/backend-pg/src/db/schemas/organizations.ts b/backend-pg/src/db/schemas/organizations.ts
new file mode 100644
index 0000000000..a79b7c57b4
--- /dev/null
+++ b/backend-pg/src/db/schemas/organizations.ts
@@ -0,0 +1,20 @@
+// Code generated by automation script, DO NOT EDIT.
+// Automated by pulling database and generating zod schema
+// To update. Just run npm run generate:schema
+// Written by akhilmhdh.
+
+import { z } from "zod";
+
+import { TImmutableDBKeys } from "./models";
+
+export const OrganizationsSchema = z.object({
+ id: z.string().uuid(),
+ name: z.string(),
+ customerId: z.string().nullable().optional(),
+ createdAt: z.string().datetime(),
+ updatedAt: z.string().datetime(),
+});
+
+export type TOrganizations = z.infer<typeof OrganizationsSchema>;
+export type TOrganizationsInsert = Omit<TOrganizations, TImmutableDBKeys>;
+export type TOrganizationsUpdate = Partial<Omit<TOrganizations, TImmutableDBKeys>>;
diff --git a/backend-pg/src/db/schemas/token-session.ts b/backend-pg/src/db/schemas/token-session.ts
deleted file mode 100644
index 196871aa0a..0000000000
--- a/backend-pg/src/db/schemas/token-session.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import { z } from "zod";
-
-import { TImmutableDBKeys } from "./models";
-
-export const TokenSessionSchema = z.object({
- id: z.string(),
- userId: z.string(),
- ip: z.string(),
- userAgent: z.string(),
- refreshVersion: z.number().default(1),
- accessVersion: z.number().default(1),
- lastUsed: z.string().datetime()
-});
-
-export type TTokenSession = z.infer<typeof TokenSessionSchema>;
-export type TTokenSessionInsert = Omit<TTokenSession, TImmutableDBKeys>;
-export type TTokenSessionUpdate = Partial<Omit<TTokenSession, TImmutableDBKeys>>;
diff --git a/backend-pg/src/db/schemas/token.ts b/backend-pg/src/db/schemas/token.ts
deleted file mode 100644
index 401d5db87b..0000000000
--- a/backend-pg/src/db/schemas/token.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import { z } from "zod";
-
-import { TImmutableDBKeys } from "./models";
-
-export const TokenSchema = z.object({
- id: z.number(),
- type: z.enum(["emailConfirmation", "emailMfa", "organizationInvitation", "passwordReset"]),
- phoneNumber: z.string().optional(),
- tokenHash: z.string(),
- triesLeft: z.number().optional(),
- expiresAt: z.string().datetime().optional(),
- createdAt: z.string().datetime(),
- updatedAt: z.string().datetime(),
- userId: z.string().optional()
-});
-
-export type TToken = z.infer<typeof TokenSchema>;
-export type TTokenInsert = Omit<TToken, TImmutableDBKeys>;
-export type TTokenUpdate = Partial<Omit<TToken, TImmutableDBKeys>>;
diff --git a/backend-pg/src/db/schemas/user-encryption-key.ts b/backend-pg/src/db/schemas/user-encryption-key.ts
deleted file mode 100644
index 103ee5bd21..0000000000
--- a/backend-pg/src/db/schemas/user-encryption-key.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-import { z } from "zod";
-
-import { PickRequired } from "@app/lib/types";
-
-import { TImmutableDBKeys } from "./models";
-
-export const UserEncryptionKey = z.object({
- id: z.number(),
- userId: z.string(),
- serverPrivateKey: z.string().optional().nullable(),
- clientPublicKey: z.string().optional().nullable(),
- encryptionVersion: z.number().default(1).optional(),
- protectedKey: z.string(),
- protectedKeyIV: z.string(),
- protectedKeyTag: z.string(),
- publicKey: z.string(),
- encryptedPrivateKey: z.string(),
- iv: z.string(),
- tag: z.string(),
- salt: z.string(),
- verifier: z.string()
-});
-
-export type TUserEncryptionKey = z.infer<typeof UserEncryptionKey>;
-export type TUserEncryptionKeyInsert = Omit<PickRequired<TUserEncryptionKey>, TImmutableDBKeys>;
-export type TUserEncryptionKeyUpdate = Partial<Omit<TUserEncryptionKey, TImmutableDBKeys>>;
diff --git a/backend-pg/src/db/schemas/user-encryption-keys.ts b/backend-pg/src/db/schemas/user-encryption-keys.ts
new file mode 100644
index 0000000000..5d71c7f570
--- /dev/null
+++ b/backend-pg/src/db/schemas/user-encryption-keys.ts
@@ -0,0 +1,29 @@
+// Code generated by automation script, DO NOT EDIT.
+// Automated by pulling database and generating zod schema
+// To update. Just run npm run generate:schema
+// Written by akhilmhdh.
+
+import { z } from "zod";
+
+import { TImmutableDBKeys } from "./models";
+
+export const UserEncryptionKeysSchema = z.object({
+ id: z.string().uuid(),
+ clientPublicKey: z.string().nullable().optional(),
+ serverPrivateKey: z.string().nullable().optional(),
+ encryptionVersion: z.number().default(1).nullable().optional(),
+ protectedKey: z.string(),
+ protectedKeyIV: z.string(),
+ protectedKeyTag: z.string(),
+ publicKey: z.string(),
+ encryptedPrivateKey: z.string(),
+ iv: z.string(),
+ tag: z.string(),
+ salt: z.string(),
+ verifier: z.string(),
+ userId: z.string().uuid(),
+});
+
+export type TUserEncryptionKeys = z.infer<typeof UserEncryptionKeysSchema>;
+export type TUserEncryptionKeysInsert = Omit<TUserEncryptionKeys, TImmutableDBKeys>;
+export type TUserEncryptionKeysUpdate = Partial<Omit<TUserEncryptionKeys, TImmutableDBKeys>>;
diff --git a/backend-pg/src/db/schemas/user.ts b/backend-pg/src/db/schemas/user.ts
deleted file mode 100644
index 59428f08dd..0000000000
--- a/backend-pg/src/db/schemas/user.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-import { z } from "zod";
-
-import { TImmutableDBKeys } from "./models";
-
-export enum AuthMethod {
- EMAIL = "email",
- GOOGLE = "google",
- GITHUB = "github",
- GITLAB = "gitlab",
- OKTA_SAML = "okta-saml",
- AZURE_SAML = "azure-saml",
- JUMPCLOUD_SAML = "jumpcloud-saml"
-}
-
-export const UserSchema = z.object({
- id: z.string(),
- authMethods: z.nativeEnum(AuthMethod).array().default([AuthMethod.EMAIL]).optional().nullable(),
- email: z.string(),
- isSuperAdmin: z.boolean().default(false).optional(),
- firstName: z.string().optional().nullable(),
- lastName: z.string().optional().nullable(),
- isMfaEnabled: z.boolean().default(false).optional(),
- mfaMethods: z.string().array().default([]).optional().nullable(),
- isAccepted: z.boolean().default(false).optional(),
- devices: z.string().nullable().optional()
-});
-
-export const UserDeviceSchema = z
- .object({
- ip: z.string(),
- userAgent: z.string()
- })
- .array()
- .default([]);
-
-export type TUser = z.infer<typeof UserSchema>;
-export type TUserInsert = Omit<TUser, TImmutableDBKeys>;
-export type TUserUpdate = Partial<Omit<TUser, "id" | "email">>;
diff --git a/backend-pg/src/db/schemas/users.ts b/backend-pg/src/db/schemas/users.ts
new file mode 100644
index 0000000000..7e12344e13
--- /dev/null
+++ b/backend-pg/src/db/schemas/users.ts
@@ -0,0 +1,27 @@
+// Code generated by automation script, DO NOT EDIT.
+// Automated by pulling database and generating zod schema
+// To update. Just run npm run generate:schema
+// Written by akhilmhdh.
+
+import { z } from "zod";
+
+import { TImmutableDBKeys } from "./models";
+
+export const UsersSchema = z.object({
+ id: z.string().uuid(),
+ email: z.string(),
+ authMethods: z.string().array().nullable().optional(),
+ superAdmin: z.boolean().default(false).nullable().optional(),
+ firstName: z.string().nullable().optional(),
+ lastName: z.string().nullable().optional(),
+ isAccepted: z.boolean().default(false).nullable().optional(),
+ isMfaEnabled: z.boolean().default(false).nullable().optional(),
+ mfaMethods: z.string().array().nullable().optional(),
+ devices: z.string().nullable().optional(),
+ createdAt: z.string().datetime(),
+ updatedAt: z.string().datetime(),
+});
+
+export type TUsers = z.infer<typeof UsersSchema>;
+export type TUsersInsert = Omit<TUsers, TImmutableDBKeys>;
+export type TUsersUpdate = Partial<Omit<TUsers, TImmutableDBKeys>>;
diff --git a/backend-pg/src/lib/errors/index.ts b/backend-pg/src/lib/errors/index.ts
index ab090fa466..2786194e97 100644
--- a/backend-pg/src/lib/errors/index.ts
+++ b/backend-pg/src/lib/errors/index.ts
@@ -16,7 +16,7 @@ export class UnauthorizedError extends Error {
error: unknown;
- constructor({ name, error, message }: { message?: string; name: string; error: unknown }) {
+ constructor({ name, error, message }: { message?: string; name: string; error?: unknown }) {
super(message ?? "You are not allowed to access this resourve");
this.name = name;
this.error = error;
diff --git a/backend-pg/src/lib/knex/index.ts b/backend-pg/src/lib/knex/index.ts
new file mode 100644
index 0000000000..d480f73010
--- /dev/null
+++ b/backend-pg/src/lib/knex/index.ts
@@ -0,0 +1,10 @@
+import { Knex } from "knex";
+
+export const withTransaction = <K extends object>(db: Knex, dal: K) => ({
+ transaction: async <T>(cb: (tx: Knex) => T) =>
+ db.transaction(async (trx) => {
+ const res = await cb(trx);
+ return res;
+ }),
+ ...dal
+});
diff --git a/backend-pg/src/lib/zod/index.ts b/backend-pg/src/lib/zod/index.ts
index 3b04f033e5..331a5fbb68 100644
--- a/backend-pg/src/lib/zod/index.ts
+++ b/backend-pg/src/lib/zod/index.ts
@@ -1,7 +1,7 @@
-import { z } from "zod";
+import { z,ZodTypeAny } from "zod";
// this is a patched zod string to remove empty string to undefined
-export const zpStr = <T extends z.ZodString>(
+export const zpStr = <T extends ZodTypeAny>(
schema: T,
opt: { stripNull: boolean } = { stripNull: true }
) =>
diff --git a/backend-pg/src/server/plugins/auth/inject-identity.ts b/backend-pg/src/server/plugins/auth/inject-identity.ts
new file mode 100644
index 0000000000..6fcff596ea
--- /dev/null
+++ b/backend-pg/src/server/plugins/auth/inject-identity.ts
@@ -0,0 +1,75 @@
+import { FastifyRequest } from "fastify";
+import jwt, { JwtPayload } from "jsonwebtoken";
+
+import { getConfig } from "@app/lib/config/env";
+import { UnauthorizedError } from "@app/lib/errors";
+import { AuthMode, AuthModeJwtTokenPayload, AuthTokenType } from "@app/services/auth/auth-type";
+
+const extractAuth = async (req: FastifyRequest, jwtSecret: string) => {
+ const apiKey = req.headers?.["x-api-key"];
+ if (apiKey) {
+ return { authMode: AuthMode.API_KEY, token: apiKey };
+ }
+ const authHeader = req.headers?.authorization;
+ if (!authHeader) return { authMode: null, token: null };
+
+ const authTokenValue = authHeader.slice(7); // slice of after Bearer
+ if (authTokenValue.startsWith("st.")) {
+ return { authMode: AuthMode.SERVICE_TOKEN, token: authTokenValue } as const;
+ }
+
+ const decodedToken = jwt.verify(authTokenValue, jwtSecret) as JwtPayload;
+ switch (decodedToken.authTokenType) {
+ case AuthTokenType.ACCESS_TOKEN:
+ return { authMode: AuthMode.JWT, token: decodedToken as AuthModeJwtTokenPayload } as const;
+ case AuthTokenType.API_KEY:
+ return { authMode: AuthMode.API_KEY_V2, token: decodedToken } as const;
+ case AuthMode.SERVICE_ACCESS_TOKEN:
+ return { authMode: AuthMode.SERVICE_ACCESS_TOKEN, token: decodedToken } as const;
+ default:
+ throw new UnauthorizedError({ name: "Invalid token type" });
+ }
+};
+
+const getJwtIdentity = async (server: FastifyZodProvider, token: AuthModeJwtTokenPayload) => {
+ const session = await server.services.authToken.getUserTokenSessionById(
+ token.tokenVersionId,
+ token.userId
+ );
+
+ if (!session) throw new UnauthorizedError({ name: "Session not found" });
+ if (token.accessVersion !== session.accessVersion)
+ throw new UnauthorizedError({ name: "Stale session" });
+
+ const user = await server.store.user.getUserById(session.userId);
+ if (!user || !user.isAccepted) throw new UnauthorizedError({ name: "Token user not found" });
+
+ return user;
+};
+
+export const injectIdentity = (server: FastifyZodProvider) => {
+ server.decorateRequest("auth", null);
+ server.addHook("onRequest", async (req) => {
+ const appCfg = getConfig();
+ const { authMode, token } = await extractAuth(req, appCfg.JWT_AUTH_SECRET);
+ if (!authMode) return;
+ // TODO(akhilmhdh-pg): fill in rest of auth mode logic
+ switch (authMode) {
+ case AuthMode.JWT: {
+ const user = await getJwtIdentity(server, token as AuthModeJwtTokenPayload);
+ req.auth = { authMode: AuthMode.JWT, user, userId: user.id };
+ break;
+ }
+ case AuthMode.SERVICE_TOKEN:
+ break;
+ case AuthMode.SERVICE_ACCESS_TOKEN:
+ break;
+ case AuthMode.API_KEY:
+ break;
+ case AuthMode.API_KEY_V2:
+ break;
+ default:
+ throw new UnauthorizedError({ name: "Unknown token strategy" });
+ }
+ });
+};
diff --git a/backend-pg/src/server/plugins/auth/verify-auth.ts b/backend-pg/src/server/plugins/auth/verify-auth.ts
new file mode 100644
index 0000000000..90432e380c
--- /dev/null
+++ b/backend-pg/src/server/plugins/auth/verify-auth.ts
@@ -0,0 +1,17 @@
+import { FastifyRequest } from "fastify";
+
+import { UnauthorizedError } from "@app/lib/errors";
+import { AuthMode } from "@app/services/auth/auth-type";
+
+export const verifyAuth =
+ <T extends FastifyRequest>(authStrats: AuthMode[]) =>
+ (req: T) => {
+ if (!Array.isArray(authStrats)) throw new Error("Auth strategy must be array");
+ if (!req.auth)
+ throw new UnauthorizedError({ name: "Unauthorized access", message: "Token missing" });
+
+ const isAccessAllowed = authStrats.some((strat) => strat === req.auth.authMode);
+ if (!isAccessAllowed) {
+ throw new UnauthorizedError({ name: `${req.url} Unauthorized Access` });
+ }
+ };
diff --git a/backend-pg/src/server/routes/index.ts b/backend-pg/src/server/routes/index.ts
index 3488843adf..8d81b238a4 100644
--- a/backend-pg/src/server/routes/index.ts
+++ b/backend-pg/src/server/routes/index.ts
@@ -11,6 +11,7 @@ import { tokenServiceFactory } from "@app/services/token/token-service";
import { registerV1Routes } from "./v1";
import { registerV2Routes } from "./v2";
import { registerV3Routes } from "./v3";
+import { injectIdentity } from "../plugins/auth/inject-identity";
export const registerRoutes = async (
server: FastifyZodProvider,
@@ -37,6 +38,8 @@ export const registerRoutes = async (
user: authDal
} as FastifyZodProvider["store"]);
+ await server.register(injectIdentity);
+
// register routes for v1
await server.register(registerV1Routes, { prefix: "/v1" });
await server.register(registerV2Routes, { prefix: "/v2" });
diff --git a/backend-pg/src/server/routes/v1/password-router.ts b/backend-pg/src/server/routes/v1/password-router.ts
index d506f9814b..92da5eeea7 100644
--- a/backend-pg/src/server/routes/v1/password-router.ts
+++ b/backend-pg/src/server/routes/v1/password-router.ts
@@ -2,6 +2,8 @@ import { z } from "zod";
import { BackupPrivateKeySchema } from "@app/db/schemas";
import { getConfig } from "@app/lib/config/env";
+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
+import { AuthMode } from "@app/services/auth/auth-type";
export const registerPasswordRouter = async (server: FastifyZodProvider) => {
server.route({
@@ -18,6 +20,7 @@ export const registerPasswordRouter = async (server: FastifyZodProvider) => {
})
}
},
+ onRequest: verifyAuth([AuthMode.JWT]),
handler: async (req) => {
const { salt, serverPublicKey } = await server.services.password.generateServerPubKey(
req.auth.userId,
@@ -48,6 +51,7 @@ export const registerPasswordRouter = async (server: FastifyZodProvider) => {
})
}
},
+ onRequest: verifyAuth([AuthMode.JWT]),
handler: async (req, res) => {
const appCfg = getConfig();
await server.services.password.changePassword({ ...req.body, userId: req.auth.userId });
@@ -65,6 +69,7 @@ export const registerPasswordRouter = async (server: FastifyZodProvider) => {
server.route({
method: "POST",
url: "/backup-private-key",
+ onRequest: verifyAuth([AuthMode.JWT]),
schema: {
body: z.object({
clientProof: z.string().trim(),
@@ -95,6 +100,7 @@ export const registerPasswordRouter = async (server: FastifyZodProvider) => {
server.route({
method: "GET",
url: "/backup-private-key",
+ onRequest: verifyAuth([AuthMode.JWT]),
schema: {
response: {
200: z.object({
diff --git a/backend-pg/src/server/routes/v2/mfa-router.ts b/backend-pg/src/server/routes/v2/mfa-router.ts
index b5fbfadcb7..71f841ad71 100644
--- a/backend-pg/src/server/routes/v2/mfa-router.ts
+++ b/backend-pg/src/server/routes/v2/mfa-router.ts
@@ -2,20 +2,24 @@ import jwt, { JwtPayload } from "jsonwebtoken";
import { z } from "zod";
import { getConfig } from "@app/lib/config/env";
-import { AuthTokenType } from "@app/services/auth/auth-signup-type";
+import { AuthTokenType } from "@app/services/auth/auth-type";
export const registerMfaRouter = async (server: FastifyZodProvider) => {
const cfg = getConfig();
+ server.decorateRequest("mfa", null);
server.addHook("preParsing", async (req, res) => {
const authorizationHeader = req.headers.authorization;
if (!authorizationHeader || !authorizationHeader.startsWith("Bearer ")) {
res.status(401).send({ error: "Missing bearer token" });
- return;
+ return res;
}
const token = authorizationHeader.split(" ")[1];
- if (!token) res.status(401).send({ error: "Missing bearer token" });
+ if (!token) {
+ res.status(401).send({ error: "Missing bearer token" });
+ return res;
+ }
const decodedToken = jwt.verify(token, cfg.JWT_AUTH_SECRET) as JwtPayload;
if (decodedToken.authTokenType !== AuthTokenType.MFA_TOKEN)
@@ -23,8 +27,7 @@ export const registerMfaRouter = async (server: FastifyZodProvider) => {
const user = await server.store.user.getUserById(decodedToken.userId);
if (!user) throw new Error("User not found");
- req.mfa.userId = user.id;
- req.mfa.user = user;
+ req.mfa = { userId: user.id, user };
});
server.route({
@@ -52,7 +55,7 @@ export const registerMfaRouter = async (server: FastifyZodProvider) => {
}),
response: {
200: z.object({
- encryptionVersion: z.number().default(1).optional(),
+ encryptionVersion: z.number().default(1).nullable().optional(),
protectedKey: z.string(),
protectedKeyIV: z.string(),
protectedKeyTag: z.string(),
diff --git a/backend-pg/src/server/routes/v3/login-router.ts b/backend-pg/src/server/routes/v3/login-router.ts
index 83fa5f89e8..5af1ba4485 100644
--- a/backend-pg/src/server/routes/v3/login-router.ts
+++ b/backend-pg/src/server/routes/v3/login-router.ts
@@ -44,7 +44,7 @@ export const registerLoginRouter = async (server: FastifyZodProvider) => {
z.object({ mfaEnabled: z.literal(true), token: z.string() }),
z.object({
mfaEnabled: z.literal(false),
- encryptionVersion: z.number().default(1).optional(),
+ encryptionVersion: z.number().default(1).nullable().optional(),
protectedKey: z.string(),
protectedKeyIV: z.string(),
protectedKeyTag: z.string(),
diff --git a/backend-pg/src/server/routes/v3/signup-router.ts b/backend-pg/src/server/routes/v3/signup-router.ts
index ff6ec2036d..731b79548d 100644
--- a/backend-pg/src/server/routes/v3/signup-router.ts
+++ b/backend-pg/src/server/routes/v3/signup-router.ts
@@ -1,6 +1,6 @@
import { z } from "zod";
-import { UserSchema } from "@app/db/schemas";
+import { UsersSchema } from "@app/db/schemas";
import { getConfig } from "@app/lib/config/env";
export const registerSignupRouter = async (server: FastifyZodProvider) => {
@@ -35,7 +35,7 @@ export const registerSignupRouter = async (server: FastifyZodProvider) => {
200: z.object({
message: z.string(),
token: z.string(),
- user: UserSchema
+ user: UsersSchema
})
}
},
@@ -72,7 +72,7 @@ export const registerSignupRouter = async (server: FastifyZodProvider) => {
response: {
200: z.object({
message: z.string(),
- user: UserSchema,
+ user: UsersSchema,
token: z.string()
})
}
diff --git a/backend-pg/src/services/auth/auth-dal.ts b/backend-pg/src/services/auth/auth-dal.ts
index eb539f911b..004cde5b42 100644
--- a/backend-pg/src/services/auth/auth-dal.ts
+++ b/backend-pg/src/services/auth/auth-dal.ts
@@ -1,16 +1,17 @@
import { Knex } from "knex";
import { TDbClient } from "@app/db";
-import { TableName, TBackupPrivateKey, TUser, TUserEncryptionKey } from "@app/db/schemas";
+import { TableName, TBackupPrivateKey, TUserEncryptionKeys, TUsers } from "@app/db/schemas";
+import { withTransaction } from "@app/lib/knex";
export type TAuthDalFactory = ReturnType<typeof authDalFactory>;
export const authDalFactory = (db: TDbClient) => {
// getters
- const getUserByEmail = async (email: string): Promise<TUser | undefined> =>
+ const getUserByEmail = async (email: string): Promise<TUsers | undefined> =>
db(TableName.Users).where({ email }).select("*").first();
- const getUserById = async (userId: string): Promise<TUser | undefined> =>
+ const getUserById = async (userId: string): Promise<TUsers | undefined> =>
db(TableName.Users).where({ id: userId }).select("*").first();
const getUserEncKeyByEmail = async (email: string) =>
@@ -39,8 +40,8 @@ export const authDalFactory = (db: TDbClient) => {
// all inserts and updates
const createUser = async (
email: string,
- data: Partial<TUser> = {}
- ): Promise<TUser | undefined> => {
+ data: Partial<TUsers> = {}
+ ): Promise<TUsers | undefined> => {
const [user] = await db(TableName.Users)
.insert({ email, ...data })
.returning("*");
@@ -49,8 +50,8 @@ export const authDalFactory = (db: TDbClient) => {
const updateUser = async (
email: string,
- data: Partial<TUser> = {}
- ): Promise<TUser | undefined> => {
+ data: Partial<TUsers> = {}
+ ): Promise<TUsers | undefined> => {
const [user] = await db(TableName.Users)
.where({ email })
.update({ ...data })
@@ -60,9 +61,9 @@ export const authDalFactory = (db: TDbClient) => {
const updateUserById = async (
id: string,
- data: Partial<TUser> = {},
+ data: Partial<TUsers> = {},
tx?: Knex
- ): Promise<TUser | undefined> => {
+ ): Promise<TUsers | undefined> => {
const [user] = await (tx ? tx(TableName.Users) : db(TableName.Users))
.where({ id })
.update({ ...data })
@@ -72,9 +73,9 @@ export const authDalFactory = (db: TDbClient) => {
const updateUserEncryptionByUserId = async (
userId: string,
- data: Partial<TUserEncryptionKey> = {},
+ data: Partial<TUserEncryptionKeys> = {},
tx?: Knex
- ): Promise<TUserEncryptionKey | undefined> => {
+ ): Promise<TUserEncryptionKeys | undefined> => {
const [userEnc] = await (tx ? tx(TableName.UserEncryptionKey) : db(TableName.UserEncryptionKey))
.where({ userId })
.update({ ...data })
@@ -85,12 +86,12 @@ export const authDalFactory = (db: TDbClient) => {
// all upserts
const upsertUserEncryptionKey = async (
userId: string,
- data: Partial<TUserEncryptionKey>,
+ data: Partial<TUserEncryptionKeys>,
tx?: Knex
) => {
const [userEnc] = await (tx ? tx(TableName.UserEncryptionKey) : db(TableName.UserEncryptionKey))
// if user insert make sure to pass all required data
- .insert({ userId, ...data } as TUserEncryptionKey)
+ .insert({ userId, ...data } as TUserEncryptionKeys)
.onConflict("userId")
.merge()
.returning("*");
@@ -110,12 +111,7 @@ export const authDalFactory = (db: TDbClient) => {
return backupKey;
};
- return {
- transaction: async <T>(cb: (tx: Knex) => T) =>
- db.transaction(async (trx) => {
- const res = await cb(trx);
- return res;
- }),
+ return withTransaction(db, {
getUserByEmail,
getUserById,
getUserEncKeyByEmail,
@@ -127,5 +123,5 @@ export const authDalFactory = (db: TDbClient) => {
updateUserEncryptionByUserId,
upsertUserEncryptionKey,
upsertBackupKey
- };
+ });
};
diff --git a/backend-pg/src/services/auth/auth-login-service.ts b/backend-pg/src/services/auth/auth-login-service.ts
index b1850e7896..4b44adcc68 100644
--- a/backend-pg/src/services/auth/auth-login-service.ts
+++ b/backend-pg/src/services/auth/auth-login-service.ts
@@ -1,12 +1,11 @@
import jwt from "jsonwebtoken";
-import { AuthMethod, TUser } from "@app/db/schemas";
-import { UserDeviceSchema } from "@app/db/schemas/user";
+import { TUsers, UserDeviceSchema } from "@app/db/schemas";
import { getConfig } from "@app/lib/config/env";
import { generateSrpServerKey, srpCheckClientProof } from "@app/lib/crypto";
import { SmtpTemplates, TSmtpService } from "../smtp/smtp-service";
-import { TTokenServiceFactory } from "../token/token-service";
+import { TAuthTokenServiceFactory } from "../token/token-service";
import { TokenType } from "../token/token-types";
import { TAuthDalFactory } from "./auth-dal";
import {
@@ -14,7 +13,7 @@ import {
TLoginGenServerPublicKeyDTO,
TVerifyMfaTokenDTO
} from "./auth-login-type";
-import { AuthTokenType } from "./auth-signup-type";
+import { AuthMethod, AuthTokenType } from "./auth-type";
const isValidProviderAuthToken = (email: string, jwtSecret: string, providerAuthToken?: string) => {
if (!providerAuthToken) return false;
@@ -27,7 +26,7 @@ const isValidProviderAuthToken = (email: string, jwtSecret: string, providerAuth
type TAuthLoginServiceFactoryDep = {
authDal: TAuthDalFactory;
- tokenService: TTokenServiceFactory;
+ tokenService: TAuthTokenServiceFactory;
smtpService: TSmtpService;
};
@@ -42,7 +41,7 @@ export const authLoginServiceFactory = ({
* Not exported. This is to update user device list
* If new device is found. Will be saved and a mail will be send
*/
- const updateUserDeviceSession = async (user: TUser, ip: string, userAgent: string) => {
+ const updateUserDeviceSession = async (user: TUsers, ip: string, userAgent: string) => {
const devices = await UserDeviceSchema.parseAsync(JSON.parse(user.devices || "[]"));
const isDeviceSeen = devices.some(
(device) => device.ip === ip && device.userAgent === userAgent
@@ -69,7 +68,7 @@ export const authLoginServiceFactory = ({
* Private
* Send mfa code via email
* */
- const sendUserMfaCode = async (user: TUser) => {
+ const sendUserMfaCode = async (user: TUsers) => {
const code = await tokenService.createTokenForUser({
type: TokenType.TOKEN_EMAIL_MFA,
userId: user.id
@@ -89,7 +88,7 @@ export const authLoginServiceFactory = ({
* Check user device and send mail if new device
* generate the auth and refresh token. fn shared by mfa verification and login verification with mfa disabled
*/
- const generateUserTokens = async (user: TUser, ip: string, userAgent: string) => {
+ const generateUserTokens = async (user: TUsers, ip: string, userAgent: string) => {
const cfg = getConfig();
await updateUserDeviceSession(user, ip, userAgent);
const tokenSession = await tokenService.getUserTokenSession({
diff --git a/backend-pg/src/services/auth/auth-password-service.ts b/backend-pg/src/services/auth/auth-password-service.ts
index ea41198a6e..cf748958e6 100644
--- a/backend-pg/src/services/auth/auth-password-service.ts
+++ b/backend-pg/src/services/auth/auth-password-service.ts
@@ -4,7 +4,7 @@ import { getConfig } from "@app/lib/config/env";
import { generateSrpServerKey, srpCheckClientProof } from "@app/lib/crypto";
import { SmtpTemplates, TSmtpService } from "../smtp/smtp-service";
-import { TTokenServiceFactory } from "../token/token-service";
+import { TAuthTokenServiceFactory } from "../token/token-service";
import { TokenType } from "../token/token-types";
import { TAuthDalFactory } from "./auth-dal";
import {
@@ -12,11 +12,11 @@ import {
TCreateBackupPrivateKeyDTO,
TResetPasswordViaBackupKeyDTO
} from "./auth-password-type";
-import { AuthTokenType } from "./auth-signup-type";
+import { AuthTokenType } from "./auth-type";
type TAuthPasswordServiceFactoryDep = {
authDal: TAuthDalFactory;
- tokenService: TTokenServiceFactory;
+ tokenService: TAuthTokenServiceFactory;
smtpService: TSmtpService;
};
diff --git a/backend-pg/src/services/auth/auth-signup-service.ts b/backend-pg/src/services/auth/auth-signup-service.ts
index ef2fafa3b9..adefb385a5 100644
--- a/backend-pg/src/services/auth/auth-signup-service.ts
+++ b/backend-pg/src/services/auth/auth-signup-service.ts
@@ -1,16 +1,18 @@
-import { AuthMethod } from "@app/db/schemas";
+import jwt from "jsonwebtoken";
+
import { getConfig } from "@app/lib/config/env";
import { isDisposableEmail } from "@app/lib/validator";
import { SmtpTemplates, TSmtpService } from "../smtp/smtp-service";
-import { TTokenServiceFactory } from "../token/token-service";
+import { TAuthTokenServiceFactory } from "../token/token-service";
import { TokenType } from "../token/token-types";
import { TAuthDalFactory } from "./auth-dal";
-import { AuthTokenType, TCompleteAccountSignupDTO } from "./auth-signup-type";
+import { TCompleteAccountSignupDTO } from "./auth-signup-type";
+import { AuthMethod, AuthTokenType } from "./auth-type";
type TAuthSignupDep = {
authDal: TAuthDalFactory;
- tokenService: TTokenServiceFactory;
+ tokenService: TAuthTokenServiceFactory;
smtpService: TSmtpService;
};
@@ -66,7 +68,7 @@ export const authSignupServiceFactory = ({
});
// generate jwt token this is a temporary token
- const jwtToken = tokenService.createJwtToken(
+ const jwtToken = jwt.sign(
{
authTokenType: AuthTokenType.SIGNUP_TOKEN,
userId: user.id.toString()
@@ -136,7 +138,7 @@ export const authSignupServiceFactory = ({
if (!tokenSession) throw new Error("Failed to create token");
const appCfg = getConfig();
- const accessToken = tokenService.createJwtToken(
+ const accessToken = jwt.sign(
{
authTokenType: AuthTokenType.ACCESS_TOKEN,
userId: updateduser.info.id,
@@ -147,7 +149,7 @@ export const authSignupServiceFactory = ({
{ expiresIn: appCfg.JWT_SIGNUP_LIFETIME }
);
- const refreshToken = tokenService.createJwtToken(
+ const refreshToken = jwt.sign(
{
authTokenType: AuthTokenType.REFRESH_TOKEN,
userId: updateduser.info.id,
diff --git a/backend-pg/src/services/auth/auth-signup-type.ts b/backend-pg/src/services/auth/auth-signup-type.ts
index ddfa153363..2d1310a24f 100644
--- a/backend-pg/src/services/auth/auth-signup-type.ts
+++ b/backend-pg/src/services/auth/auth-signup-type.ts
@@ -1,22 +1,3 @@
-export enum AuthTokenType {
- ACCESS_TOKEN = "accessToken",
- REFRESH_TOKEN = "refreshToken",
- SIGNUP_TOKEN = "signupToken", // TODO: remove in favor of claim
- MFA_TOKEN = "mfaToken", // TODO: remove in favor of claim
- PROVIDER_TOKEN = "providerToken", // TODO: remove in favor of claim
- API_KEY = "apiKey",
- SERVICE_ACCESS_TOKEN = "serviceAccessToken",
- SERVICE_REFRESH_TOKEN = "serviceRefreshToken"
-}
-
-export enum AuthMode {
- JWT = "jwt",
- SERVICE_TOKEN = "serviceToken",
- SERVICE_ACCESS_TOKEN = "serviceAccessToken",
- API_KEY = "apiKey",
- API_KEY_V2 = "apiKeyV2"
-}
-
export type TCompleteAccountSignupDTO = {
email: string;
firstName: string;
diff --git a/backend-pg/src/services/auth/auth-type.ts b/backend-pg/src/services/auth/auth-type.ts
new file mode 100644
index 0000000000..b80cb6d42f
--- /dev/null
+++ b/backend-pg/src/services/auth/auth-type.ts
@@ -0,0 +1,35 @@
+export enum AuthMethod {
+ EMAIL = "email",
+ GOOGLE = "google",
+ GITHUB = "github",
+ GITLAB = "gitlab",
+ OKTA_SAML = "okta-saml",
+ AZURE_SAML = "azure-saml",
+ JUMPCLOUD_SAML = "jumpcloud-saml"
+}
+
+export enum AuthTokenType {
+ ACCESS_TOKEN = "accessToken",
+ REFRESH_TOKEN = "refreshToken",
+ SIGNUP_TOKEN = "signupToken", // TODO: remove in favor of claim
+ MFA_TOKEN = "mfaToken", // TODO: remove in favor of claim
+ PROVIDER_TOKEN = "providerToken", // TODO: remove in favor of claim
+ API_KEY = "apiKey",
+ SERVICE_ACCESS_TOKEN = "serviceAccessToken",
+ SERVICE_REFRESH_TOKEN = "serviceRefreshToken"
+}
+
+export enum AuthMode {
+ JWT = "jwt",
+ SERVICE_TOKEN = "serviceToken",
+ SERVICE_ACCESS_TOKEN = "serviceAccessToken",
+ API_KEY = "apiKey",
+ API_KEY_V2 = "apiKeyV2"
+}
+
+export type AuthModeJwtTokenPayload = {
+ authTokenType: AuthTokenType.ACCESS_TOKEN;
+ userId: string;
+ tokenVersionId: string;
+ accessVersion: number;
+};
diff --git a/backend-pg/src/services/token/token-dal.ts b/backend-pg/src/services/token/token-dal.ts
index 8235086100..16db26468b 100644
--- a/backend-pg/src/services/token/token-dal.ts
+++ b/backend-pg/src/services/token/token-dal.ts
@@ -1,6 +1,5 @@
import { TDbClient } from "@app/db";
-import { TableName, TToken } from "@app/db/schemas";
-import { TTokenSession } from "@app/db/schemas/token-session";
+import { TableName, TAuthTokens, TAuthTokenSessions } from "@app/db/schemas";
import {
TDeleteTokenForUserDalDTO,
@@ -19,7 +18,7 @@ export const tokenDalFactory = (db: TDbClient) => {
userId,
type,
triesLeft
- }: TUpsertTokenForUserDalDTO): Promise<TToken | undefined> => {
+ }: TUpsertTokenForUserDalDTO): Promise<TAuthTokens | undefined> => {
const token = await db.transaction(async (tx) => {
await tx(TableName.AuthTokens).where({ userId, type }).delete().returning("*");
const [newToken] = await tx(TableName.AuthTokens)
@@ -33,13 +32,23 @@ export const tokenDalFactory = (db: TDbClient) => {
const getTokenForUser = async ({
userId,
type
- }: TGetTokenForUserDalDTO): Promise<TToken | undefined> =>
+ }: TGetTokenForUserDalDTO): Promise<TAuthTokens | undefined> =>
db(TableName.AuthTokens).where({ userId, type }).first();
+ const getTokenSession = async (
+ userId: string,
+ ip: string,
+ userAgent: string
+ ): Promise<TAuthTokenSessions | undefined> =>
+ db(TableName.AuthTokenSession).where({ userId, ip, userAgent }).first();
+
+ const getTokenSessionById = async (id: string, userId: string) =>
+ db(TableName.AuthTokenSession).where({ id, userId }).first();
+
const deleteTokenForUser = async ({
userId,
type
- }: TDeleteTokenForUserDalDTO): Promise<TToken[] | undefined> =>
+ }: TDeleteTokenForUserDalDTO): Promise<TAuthTokens[] | undefined> =>
db(TableName.AuthTokens).where({ userId, type }).delete().returning("*");
const decrementTriesField = async ({
@@ -49,18 +58,11 @@ export const tokenDalFactory = (db: TDbClient) => {
await db(TableName.AuthTokens).where({ userId, type }).decrement("triesLeft", 1);
};
- const getTokenSession = async (
- userId: string,
- ip: string,
- userAgent: string
- ): Promise<TTokenSession | undefined> =>
- db(TableName.AuthTokenSession).where({ userId, ip, userAgent }).first();
-
const insertTokenSession = async (
userId: string,
ip: string,
userAgent: string
- ): Promise<TTokenSession | undefined> => {
+ ): Promise<TAuthTokenSessions | undefined> => {
const [session] = await db(TableName.AuthTokenSession)
.insert({
userId,
@@ -77,7 +79,7 @@ export const tokenDalFactory = (db: TDbClient) => {
const incrementVersion = async (
userId: string,
sessionId: string
- ): Promise<TTokenSession | undefined> => {
+ ): Promise<TAuthTokenSessions | undefined> => {
const [session] = await db(TableName.AuthTokenSession)
.where({ userId, id: sessionId })
.increment("accessVersion", 1)
@@ -87,8 +89,9 @@ export const tokenDalFactory = (db: TDbClient) => {
};
return {
- upsertTokenForUser,
getTokenForUser,
+ getTokenSessionById,
+ upsertTokenForUser,
deleteTokenForUser,
decrementTriesField,
getTokenSession,
diff --git a/backend-pg/src/services/token/token-service.ts b/backend-pg/src/services/token/token-service.ts
index 1b7c80c43a..37f577a7d4 100644
--- a/backend-pg/src/services/token/token-service.ts
+++ b/backend-pg/src/services/token/token-service.ts
@@ -1,9 +1,7 @@
import crypto from "node:crypto";
import bcrypt from "bcrypt";
-import jwt, { SignOptions } from "jsonwebtoken";
-import { TToken } from "@app/db/schemas";
-import { TTokenSession } from "@app/db/schemas/token-session";
+import { TAuthTokens, TAuthTokenSessions } from "@app/db/schemas";
import { getConfig } from "@app/lib/config/env";
import { TTokenDalFactory } from "./token-dal";
@@ -14,11 +12,11 @@ import {
TValidateTokenForUserDTO
} from "./token-types";
-type TTokenServiceFactoryDep = {
+type TAuthTokenServiceFactoryDep = {
tokenDal: TTokenDalFactory;
// adjust the expiry from env through here
};
-export type TTokenServiceFactory = ReturnType<typeof tokenServiceFactory>;
+export type TAuthTokenServiceFactory = ReturnType<typeof tokenServiceFactory>;
export const getTokenConfig = (tokenType: TokenType) => {
// generate random token based on specified token use-case
@@ -57,7 +55,7 @@ export const getTokenConfig = (tokenType: TokenType) => {
}
};
-export const tokenServiceFactory = ({ tokenDal }: TTokenServiceFactoryDep) => {
+export const tokenServiceFactory = ({ tokenDal }: TAuthTokenServiceFactoryDep) => {
const createTokenForUser = async ({ type, userId }: TCreateTokenForUserDTO) => {
const { token, ...tkCfg } = getTokenConfig(type);
const appCfg = getConfig();
@@ -76,7 +74,7 @@ export const tokenServiceFactory = ({ tokenDal }: TTokenServiceFactoryDep) => {
type,
userId,
code
- }: TValidateTokenForUserDTO): Promise<TToken | undefined> => {
+ }: TValidateTokenForUserDTO): Promise<TAuthTokens | undefined> => {
const token = await tokenDal.getTokenForUser({ type, userId });
// validate token
if (!token) throw new Error("Failed to find token");
@@ -105,7 +103,7 @@ export const tokenServiceFactory = ({ tokenDal }: TTokenServiceFactoryDep) => {
userId,
ip,
userAgent
- }: TIssueAuthTokenDTO): Promise<TTokenSession | undefined> => {
+ }: TIssueAuthTokenDTO): Promise<TAuthTokenSessions | undefined> => {
let session = await tokenDal.getTokenSession(userId, ip, userAgent);
if (!session) {
session = await tokenDal.insertTokenSession(userId, ip, userAgent);
@@ -113,22 +111,19 @@ export const tokenServiceFactory = ({ tokenDal }: TTokenServiceFactoryDep) => {
return session;
};
+ const getUserTokenSessionById = async (id: string, userId: string) =>
+ tokenDal.getTokenSessionById(id, userId);
+
const clearTokenSessionById = async (
userId: string,
sessionId: string
- ): Promise<TTokenSession | undefined> => tokenDal.incrementVersion(userId, sessionId);
-
- const createJwtToken = (
- payload: string | Buffer | object,
- secret: string,
- options?: SignOptions
- ) => jwt.sign(payload, secret, options);
+ ): Promise<TAuthTokenSessions | undefined> => tokenDal.incrementVersion(userId, sessionId);
return {
createTokenForUser,
validateTokenForUser,
- createJwtToken,
getUserTokenSession,
- clearTokenSessionById
+ clearTokenSessionById,
+ getUserTokenSessionById
};
};
diff --git a/backend/src/utils/authn/helpers/index.ts b/backend/src/utils/authn/helpers/index.ts
index 7f3998e571..45849c9890 100644
--- a/backend/src/utils/authn/helpers/index.ts
+++ b/backend/src/utils/authn/helpers/index.ts
@@ -16,19 +16,19 @@ import { getUserAgentType } from "../../posthog";
export * from "./authDataExtractors";
interface ExtractAuthModeParams {
- headers: { [key: string]: string | string[] | undefined }
+ headers: { [key: string]: string | string[] | undefined };
}
interface ExtractAuthModeReturn {
- authMode: AuthMode;
- authTokenValue: string;
+ authMode: AuthMode;
+ authTokenValue: string;
}
interface GetAuthDataParams {
- authMode: AuthMode;
- authTokenValue: string;
- ipAddress: string;
- userAgent: string;
+ authMode: AuthMode;
+ authTokenValue: string;
+ ipAddress: string;
+ userAgent: string;
}
/**
@@ -44,33 +44,30 @@ interface GetAuthDataParams {
* @throws {UnauthorizedError} Throws an error if no applicable authMode is found.
*/
export const extractAuthMode = async ({
- headers
+ headers
}: ExtractAuthModeParams): Promise<ExtractAuthModeReturn> => {
+ const apiKey = headers["x-api-key"] as string;
+ const authHeader = headers["authorization"] as string;
- const apiKey = headers["x-api-key"] as string;
- const authHeader = headers["authorization"] as string;
-
- if (apiKey) {
- return { authMode: AuthMode.API_KEY, authTokenValue: apiKey };
- }
-
- if (!authHeader) throw UnauthorizedRequestError({
- message: "Failed to authenticate unknown authentication method"
+ if (apiKey) {
+ return { authMode: AuthMode.API_KEY, authTokenValue: apiKey };
+ }
+
+ if (!authHeader)
+ throw UnauthorizedRequestError({
+ message: "Failed to authenticate unknown authentication method"
});
- if (!authHeader.startsWith("Bearer ")) throw UnauthorizedRequestError({
- message: "Failed to authenticate unknown authentication method"
+ if (!authHeader.startsWith("Bearer "))
+ throw UnauthorizedRequestError({
+ message: "Failed to authenticate unknown authentication method"
});
- const authTokenValue = authHeader.slice(7);
-
- if (authTokenValue.startsWith("st.")) {
- return { authMode: AuthMode.SERVICE_TOKEN, authTokenValue };
- }
+ const authTokenValue = authHeader.slice(7);
- const decodedToken = <jwt.AuthnJwtPayload>(
- jwt.verify(authTokenValue, await getAuthSecret())
- );
+ if (authTokenValue.startsWith("st.")) {
+ return { authMode: AuthMode.SERVICE_TOKEN, authTokenValue };
+ }
switch (decodedToken.authTokenType) {
case AuthTokenType.ACCESS_TOKEN:
@@ -87,13 +84,18 @@ export const extractAuthMode = async ({
}
export const getAuthData = async ({
- authMode,
- authTokenValue,
- ipAddress,
- userAgent
+ authMode,
+ authTokenValue,
+ ipAddress,
+ userAgent
}: GetAuthDataParams): Promise<AuthData> => {
+ const userAgentType = getUserAgentType(userAgent);
- const userAgentType = getUserAgentType(userAgent);
+ switch (authMode) {
+ case AuthMode.SERVICE_TOKEN: {
+ const serviceTokenData = await validateServiceTokenV2({
+ authTokenValue
+ });
switch (authMode) {
case AuthMode.SERVICE_TOKEN: {
@@ -193,4 +195,81 @@ export const getAuthData = async ({
}
}
}
-}
\ No newline at end of file
+ case AuthMode.SERVICE_ACCESS_TOKEN: {
+ const serviceTokenData = await validateServiceTokenV3({
+ authTokenValue
+ });
+
+ return {
+ actor: {
+ type: ActorType.SERVICE_V3,
+ metadata: {
+ serviceId: serviceTokenData._id.toString(),
+ name: serviceTokenData.name
+ }
+ },
+ authPayload: serviceTokenData,
+ ipAddress,
+ userAgent,
+ userAgentType
+ };
+ }
+ case AuthMode.API_KEY: {
+ const user = await validateAPIKey({
+ authTokenValue
+ });
+
+ return {
+ actor: {
+ type: ActorType.USER,
+ metadata: {
+ userId: user._id.toString(),
+ email: user.email
+ }
+ },
+ authPayload: user,
+ ipAddress,
+ userAgent,
+ userAgentType
+ };
+ }
+ case AuthMode.API_KEY_V2: {
+ const user = await validateAPIKeyV2({
+ authTokenValue
+ });
+
+ return {
+ actor: {
+ type: ActorType.USER,
+ metadata: {
+ userId: user._id.toString(),
+ email: user.email
+ }
+ },
+ authPayload: user,
+ ipAddress,
+ userAgent,
+ userAgentType
+ };
+ }
+ case AuthMode.JWT: {
+ const user = await validateJWT({
+ authTokenValue
+ });
+
+ return {
+ actor: {
+ type: ActorType.USER,
+ metadata: {
+ userId: user._id.toString(),
+ email: user.email
+ }
+ },
+ authPayload: user,
+ ipAddress,
+ userAgent,
+ userAgentType
+ };
+ }
+ }
+};
diff --git a/frontend/src/components/AddTagPopoverContent/AddTagPopoverContent.tsx b/frontend/src/components/AddTagPopoverContent/AddTagPopoverContent.tsx
index 77ca8c24f5..d69cc76c87 100644
--- a/frontend/src/components/AddTagPopoverContent/AddTagPopoverContent.tsx
+++ b/frontend/src/components/AddTagPopoverContent/AddTagPopoverContent.tsx
@@ -41,7 +41,7 @@ const AddTagPopoverContent = ({
<div className="flex flex-col space-y-1.5">
{wsTags?.map((wsTag: WsTag) => (
<div
- key={`tag-${wsTag._id}`}
+ key={`tag-${wsTag.id}`}
className="mt-4 h-[32px] relative flex items-center justify-start hover:border-mineshaft-600 hover:border hover:bg-mineshaft-700 p-2 rounded-md hover:text-bunker-200 bg-none"
onClick={() => handleSelectTag(wsTag)}
onMouseEnter={() => handleTagOnMouseEnter(wsTag)}
diff --git a/frontend/src/components/basic/dialog/UpgradePlan.tsx b/frontend/src/components/basic/dialog/UpgradePlan.tsx
index 0fd9af4040..517d5a2335 100644
--- a/frontend/src/components/basic/dialog/UpgradePlan.tsx
+++ b/frontend/src/components/basic/dialog/UpgradePlan.tsx
@@ -64,7 +64,7 @@ const UpgradePlanModal = ({
<button
type='button'
className='inline-flex justify-center rounded-md border border-transparent bg-primary opacity-80 hover:opacity-100 px-4 py-2 text-sm font-medium text-black hover:text-semibold duration-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2'
- onClick={() => router.push(`/org/${currentOrg?._id}/billing`)}
+ onClick={() => router.push(`/org/${currentOrg?.id}/billing`)}
>
Upgrade Now
</button>
diff --git a/frontend/src/components/basic/table/ProjectUsersTable.tsx b/frontend/src/components/basic/table/ProjectUsersTable.tsx
index 5838aaf419..a00eb6543c 100644
--- a/frontend/src/components/basic/table/ProjectUsersTable.tsx
+++ b/frontend/src/components/basic/table/ProjectUsersTable.tsx
@@ -41,7 +41,7 @@ type EnvironmentProps = {
const ProjectUsersTable = ({ userData, changeData, myUser, filter, isUserListLoading }: Props) => {
const { currentWorkspace } = useWorkspace();
const { subscription } = useSubscription();
- const { data: wsKey } = useGetUserWsKey(currentWorkspace?._id ?? "");
+ const { data: wsKey } = useGetUserWsKey(currentWorkspace?.id ?? "");
const { mutateAsync: deleteUserFromWorkspaceMutateAsync } = useDeleteUserFromWorkspace();
const { mutateAsync: uploadWsKeyMutateAsync } = useUploadWsKey();
diff --git a/frontend/src/components/dashboard/AddTagsMenu.tsx b/frontend/src/components/dashboard/AddTagsMenu.tsx
index e97c979a97..dfa902b878 100644
--- a/frontend/src/components/dashboard/AddTagsMenu.tsx
+++ b/frontend/src/components/dashboard/AddTagsMenu.tsx
@@ -37,7 +37,7 @@ const AddTagsMenu = ({ allTags, currentTags, modifyTags, id }: { allTags: Tag[];
>
<Menu.Items className="absolute z-[90] text-sm drop-shadow-xl right-0 mt-0.5 w-[12rem] origin-top-right rounded-md bg-mineshaft-600 border border-mineshaft-500 shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none p-1 space-y-1">
{allTags?.map((tag) => { return (
- <Menu.Item key={tag._id}>
+ <Menu.Item key={tag.id}>
<button
type="button"
className={`${currentTags?.map(currentTag => currentTag.name).includes(tag.name) ? "opacity-30 cursor-default" : "hover:bg-mineshaft-700"} w-full text-left bg-mineshaft-800 px-2 py-0.5 text-bunker-200 rounded-sm flex items-center`}
diff --git a/frontend/src/components/dashboard/KeyPair.tsx b/frontend/src/components/dashboard/KeyPair.tsx
index 7443a379a0..b46c6c07cf 100644
--- a/frontend/src/components/dashboard/KeyPair.tsx
+++ b/frontend/src/components/dashboard/KeyPair.tsx
@@ -147,9 +147,9 @@ const KeyPair = ({
<div className="w-2/12 h-10 flex items-center overflow-visible overflow-r-scroll no-scrollbar no-scrollbar::-webkit-scrollbar">
<div className="flex items-center max-h-16">
{keyPair.tags?.map((tag, index) => (
- index < 2 && <div key={keyPair.pos} className={`ml-2 px-1.5 ${tagData.filter(tagDp => tagDp._id === tag._id)[0]?.color} rounded-sm text-sm ${tagData.filter(tagDp => tagDp._id === tag._id)[0]?.colorText} flex items-center`}>
+ index < 2 && <div key={keyPair.pos} className={`ml-2 px-1.5 ${tagData.filter(tagDp => tagDp.id === tag.id)[0]?.color} rounded-sm text-sm ${tagData.filter(tagDp => tagDp.id === tag.id)[0]?.colorText} flex items-center`}>
<span className='mb-0.5 cursor-default'>{tag.name}</span>
- <FontAwesomeIcon icon={faXmark} className="ml-1 cursor-pointer p-1" onClick={() => modifyTags(keyPair.tags.filter(ttag => ttag._id !== tag._id), keyPair.id)}/>
+ <FontAwesomeIcon icon={faXmark} className="ml-1 cursor-pointer p-1" onClick={() => modifyTags(keyPair.tags.filter(ttag => ttag.id !== tag.id), keyPair.id)}/>
</div>
))}
diff --git a/frontend/src/components/navigation/NavHeader.tsx b/frontend/src/components/navigation/NavHeader.tsx
index 739c4eca85..b8ebee59c1 100644
--- a/frontend/src/components/navigation/NavHeader.tsx
+++ b/frontend/src/components/navigation/NavHeader.tsx
@@ -59,7 +59,7 @@ export default function NavHeader({
<div className="mr-2 flex h-5 w-5 items-center justify-center rounded-md bg-primary text-sm text-black">
{currentOrg?.name?.charAt(0)}
</div>
- <Link passHref legacyBehavior href={`/org/${currentOrg?._id}/overview`}>
+ <Link passHref legacyBehavior href={`/org/${currentOrg?.id}/overview`}>
<a className="pl-0.5 text-sm font-semibold text-primary/80 hover:text-primary">
{currentOrg?.name}
</a>
diff --git a/frontend/src/components/signup/UserInfoStep.tsx b/frontend/src/components/signup/UserInfoStep.tsx
index 0e2b02f87e..7af9ccc8fd 100644
--- a/frontend/src/components/signup/UserInfoStep.tsx
+++ b/frontend/src/components/signup/UserInfoStep.tsx
@@ -191,14 +191,14 @@ export default function UserInfoStep({
const userOrgs = await fetchOrganizations();
- const orgId = userOrgs[0]?._id;
+ const orgId = userOrgs[0]?.id;
const project = await ProjectService.initProject({
organizationId: orgId,
projectName: "Example Project"
});
localStorage.setItem("orgData.id", orgId);
- localStorage.setItem("projectData.id", project._id);
+ localStorage.setItem("projectData.id", project.id);
incrementStep();
} catch (error) {
diff --git a/frontend/src/components/tags/CreateTagModal/CreateTagModal.tsx b/frontend/src/components/tags/CreateTagModal/CreateTagModal.tsx
index 4c93a5a199..8f9fd4ccc3 100644
--- a/frontend/src/components/tags/CreateTagModal/CreateTagModal.tsx
+++ b/frontend/src/components/tags/CreateTagModal/CreateTagModal.tsx
@@ -112,7 +112,7 @@ export const CreateTagModal = ({ isOpen, onToggle }: Props): JSX.Element => {
});
const { createNotification } = useNotificationContext();
const { currentWorkspace } = useWorkspace();
- const workspaceId = currentWorkspace?._id || "";
+ const workspaceId = currentWorkspace?.id || "";
const { mutateAsync: createWsTag } = useCreateWsTag();
diff --git a/frontend/src/components/utilities/config/index.ts b/frontend/src/components/utilities/config/index.ts
index 6ced4cac9c..8804765a3f 100644
--- a/frontend/src/components/utilities/config/index.ts
+++ b/frontend/src/components/utilities/config/index.ts
@@ -2,11 +2,11 @@ const ENV = process.env.NEXT_PUBLIC_ENV! || "development"; // investigate
const POSTHOG_API_KEY = process.env.NEXT_PUBLIC_POSTHOG_API_KEY!;
const POSTHOG_HOST =
process.env.NEXT_PUBLIC_POSTHOG_HOST! || "https://app.posthog.com";
-const INTERCOM_ID = process.env.NEXT_PUBLIC_INTERCOM_ID!;
+const INTERCOMid = process.env.NEXT_PUBLIC_INTERCOMid!;
export {
ENV,
- INTERCOM_ID,
+ INTERCOMid,
POSTHOG_API_KEY,
POSTHOG_HOST
};
\ No newline at end of file
diff --git a/frontend/src/components/utilities/intercom/intercom.ts b/frontend/src/components/utilities/intercom/intercom.ts
index 94079bc2bd..fb531c4a49 100644
--- a/frontend/src/components/utilities/intercom/intercom.ts
+++ b/frontend/src/components/utilities/intercom/intercom.ts
@@ -9,7 +9,7 @@
/* eslint-disable func-names */
// @ts-nocheck
-import { INTERCOM_ID as APP_ID } from "@app/components/utilities/config";
+import { INTERCOMid as APPid } from "@app/components/utilities/config";
// Loads Intercom with the snippet
// This must be run before boot, it initializes window.Intercom
@@ -37,7 +37,7 @@ export const load = () => {
var s=d.createElement("script");
s.type="text/javascript";
s.async=true;
- s.src="https://widget.intercom.io/widget/" + APP_ID;
+ s.src="https://widget.intercom.io/widget/" + APPid;
var x=d.getElementsByTagName("script")[0];
x.parentNode.insertBefore(s, x);
};
@@ -56,7 +56,7 @@ export const load = () => {
export const boot = (options = {}) => {
window &&
window.Intercom &&
- window.Intercom("boot", { app_id: APP_ID, ...options });
+ window.Intercom("boot", { appid: APPid, ...options });
};
export const update = () => {
diff --git a/frontend/src/components/v2/UpgradePlanModal/UpgradePlanModal.tsx b/frontend/src/components/v2/UpgradePlanModal/UpgradePlanModal.tsx
index 1c1d732e1e..19621a25d9 100644
--- a/frontend/src/components/v2/UpgradePlanModal/UpgradePlanModal.tsx
+++ b/frontend/src/components/v2/UpgradePlanModal/UpgradePlanModal.tsx
@@ -16,7 +16,7 @@ export const UpgradePlanModal = ({ text, isOpen, onOpenChange }: Props): JSX.Ele
const { mutateAsync, isLoading } = useGetOrgTrialUrl();
const link =
subscription && subscription.slug !== null
- ? `/org/${currentOrg?._id}/billing`
+ ? `/org/${currentOrg?.id}/billing`
: "https://infisical.com/scheduledemo";
const handleUpgradeBtnClick = async () => {
@@ -27,7 +27,7 @@ export const UpgradePlanModal = ({ text, isOpen, onOpenChange }: Props): JSX.Ele
// direct user to start pro trial
const url = await mutateAsync({
- orgId: currentOrg._id,
+ orgId: currentOrg.id,
success_url: window.location.href
});
diff --git a/frontend/src/context/OrgPermissionContext/OrgPermissionContext.tsx b/frontend/src/context/OrgPermissionContext/OrgPermissionContext.tsx
index 312ae04370..932e33e9bd 100644
--- a/frontend/src/context/OrgPermissionContext/OrgPermissionContext.tsx
+++ b/frontend/src/context/OrgPermissionContext/OrgPermissionContext.tsx
@@ -17,7 +17,7 @@ const OrgPermissionContext = createContext<null | {
export const OrgPermissionProvider = ({ children }: Props): JSX.Element => {
const { currentOrg } = useOrganization();
- const orgId = currentOrg?._id || "";
+ const orgId = currentOrg?.id || "";
const { data: permission, isLoading } = useGetUserOrgPermissions({ orgId });
if (isLoading) {
diff --git a/frontend/src/context/OrganizationContext/OrganizationContext.tsx b/frontend/src/context/OrganizationContext/OrganizationContext.tsx
index 0c0878fa18..93c82b9233 100644
--- a/frontend/src/context/OrganizationContext/OrganizationContext.tsx
+++ b/frontend/src/context/OrganizationContext/OrganizationContext.tsx
@@ -26,7 +26,7 @@ export const OrgProvider = ({ children }: Props): JSX.Element => {
const value = useMemo<TOrgContext>(
() => ({
orgs: userOrgs,
- currentOrg: (userOrgs || []).find(({ _id }) => _id === currentWsOrgID) || (userOrgs || [])[0],
+ currentOrg: (userOrgs || []).find(({ id }) => id === currentWsOrgID) || (userOrgs || [])[0],
isLoading
}),
[currentWsOrgID, userOrgs, isLoading]
diff --git a/frontend/src/context/ProjectPermissionContext/ProjectPermissionContext.tsx b/frontend/src/context/ProjectPermissionContext/ProjectPermissionContext.tsx
index bb7fab7ec8..3b7a8af2fb 100644
--- a/frontend/src/context/ProjectPermissionContext/ProjectPermissionContext.tsx
+++ b/frontend/src/context/ProjectPermissionContext/ProjectPermissionContext.tsx
@@ -13,7 +13,7 @@ const ProjectPermissionContext = createContext<null | TProjectPermission>(null);
export const ProjectPermissionProvider = ({ children }: Props): JSX.Element => {
const { currentWorkspace, isLoading: isWsLoading } = useWorkspace();
- const workspaceId = currentWorkspace?._id || "";
+ const workspaceId = currentWorkspace?.id || "";
const { data: permission, isLoading } = useGetUserProjectPermissions({ workspaceId });
if ((isLoading && currentWorkspace) || isWsLoading) {
diff --git a/frontend/src/context/SubscriptionContext/SubscriptionContext.tsx b/frontend/src/context/SubscriptionContext/SubscriptionContext.tsx
index aca2e5328c..9c50e425f6 100644
--- a/frontend/src/context/SubscriptionContext/SubscriptionContext.tsx
+++ b/frontend/src/context/SubscriptionContext/SubscriptionContext.tsx
@@ -20,7 +20,7 @@ export const SubscriptionProvider = ({ children }: Props): JSX.Element => {
const { currentOrg } = useOrganization();
const { data, isLoading } = useGetOrgSubscription({
- orgID: currentOrg?._id || ""
+ orgID: currentOrg?.id || ""
});
// memorize the workspace details for the context
diff --git a/frontend/src/context/WorkspaceContext/WorkspaceContext.tsx b/frontend/src/context/WorkspaceContext/WorkspaceContext.tsx
index 177c41269a..1e0a01c7ec 100644
--- a/frontend/src/context/WorkspaceContext/WorkspaceContext.tsx
+++ b/frontend/src/context/WorkspaceContext/WorkspaceContext.tsx
@@ -26,7 +26,7 @@ export const WorkspaceProvider = ({ children }: Props): JSX.Element => {
const wsId = workspaceId || localStorage.getItem("projectData.id");
return {
workspaces: ws || [],
- currentWorkspace: (ws || []).find(({ _id: id }) => id === wsId),
+ currentWorkspace: (ws || []).find(({ id: id }) => id === wsId),
isLoading
};
}, [ws, workspaceId, isLoading]);
diff --git a/frontend/src/hooks/api/apiKeys/types.ts b/frontend/src/hooks/api/apiKeys/types.ts
index 9774c5824c..bc5ff3a56d 100644
--- a/frontend/src/hooks/api/apiKeys/types.ts
+++ b/frontend/src/hooks/api/apiKeys/types.ts
@@ -1,5 +1,5 @@
export type APIKeyDataV2 = {
- _id: string;
+ id: string;
name: string;
user: string;
lastUsed?: string;
diff --git a/frontend/src/hooks/api/bots/types.ts b/frontend/src/hooks/api/bots/types.ts
index 3ee4620bbc..abc7f4313e 100644
--- a/frontend/src/hooks/api/bots/types.ts
+++ b/frontend/src/hooks/api/bots/types.ts
@@ -1,5 +1,5 @@
export type TBot = {
- _id: string;
+ id: string;
name: string;
workspace: string;
isActive: boolean;
diff --git a/frontend/src/hooks/api/incidentContacts/types.ts b/frontend/src/hooks/api/incidentContacts/types.ts
index a1ef8ab957..bf79e2f833 100644
--- a/frontend/src/hooks/api/incidentContacts/types.ts
+++ b/frontend/src/hooks/api/incidentContacts/types.ts
@@ -1,5 +1,5 @@
export type IncidentContact = {
- _id: string;
+ id: string;
email: string;
organization: string;
__v: number;
diff --git a/frontend/src/hooks/api/integrationAuth/types.ts b/frontend/src/hooks/api/integrationAuth/types.ts
index 5af8a3773b..7a6ff6d533 100644
--- a/frontend/src/hooks/api/integrationAuth/types.ts
+++ b/frontend/src/hooks/api/integrationAuth/types.ts
@@ -1,5 +1,5 @@
export type IntegrationAuth = {
- _id: string;
+ id: string;
integration: string;
workspace: string;
__v: number;
diff --git a/frontend/src/hooks/api/integrations/types.ts b/frontend/src/hooks/api/integrations/types.ts
index c2cc9ecf66..3c814e80b4 100644
--- a/frontend/src/hooks/api/integrations/types.ts
+++ b/frontend/src/hooks/api/integrations/types.ts
@@ -10,7 +10,7 @@ export type TCloudIntegration = {
};
export type TIntegration = {
- _id: string;
+ id: string;
workspace: string;
environment: string;
isActive: boolean;
diff --git a/frontend/src/hooks/api/keys/types.ts b/frontend/src/hooks/api/keys/types.ts
index ee4660aeba..fc455deaf6 100644
--- a/frontend/src/hooks/api/keys/types.ts
+++ b/frontend/src/hooks/api/keys/types.ts
@@ -1,5 +1,5 @@
export type UserWsKeyPair = {
- _id: string;
+ id: string;
encryptedKey: string;
nonce: string;
sender: Sender;
@@ -11,7 +11,7 @@ export type UserWsKeyPair = {
};
export type Sender = {
- _id: string;
+ id: string;
email: string;
createdAt: string;
updatedAt: string;
diff --git a/frontend/src/hooks/api/organization/types.ts b/frontend/src/hooks/api/organization/types.ts
index cc4ad8e70b..c2468d8c21 100644
--- a/frontend/src/hooks/api/organization/types.ts
+++ b/frontend/src/hooks/api/organization/types.ts
@@ -1,5 +1,5 @@
export type Organization = {
- _id: string;
+ id: string;
name: string;
createAt: string;
updatedAt: string;
@@ -25,7 +25,7 @@ export type PlanBillingInfo = {
}
export type Invoice = {
- _id: string;
+ id: string;
created: number;
invoice_pdf: string;
number: string;
@@ -34,7 +34,7 @@ export type Invoice = {
}
export type PmtMethod = {
- _id: string;
+ id: string;
brand: string;
exp_month: number;
exp_year: number;
@@ -43,14 +43,14 @@ export type PmtMethod = {
}
export type TaxID = {
- _id: string;
+ id: string;
country: string;
type: string;
value: string;
}
export type License = {
- _id: string;
+ id: string;
customerId: string;
prefix: string;
licenseKey: string;
diff --git a/frontend/src/hooks/api/roles/types.ts b/frontend/src/hooks/api/roles/types.ts
index 8cf578fa62..05d0790fc3 100644
--- a/frontend/src/hooks/api/roles/types.ts
+++ b/frontend/src/hooks/api/roles/types.ts
@@ -4,7 +4,7 @@ export type TGetRolesDTO = {
};
export type TRole<T extends string | undefined> = {
- _id: string;
+ id: string;
organization: string;
workspace: T;
name: string;
diff --git a/frontend/src/hooks/api/secretApproval/types.ts b/frontend/src/hooks/api/secretApproval/types.ts
index 0095d699c5..01a1b64a6e 100644
--- a/frontend/src/hooks/api/secretApproval/types.ts
+++ b/frontend/src/hooks/api/secretApproval/types.ts
@@ -1,5 +1,5 @@
export type TSecretApprovalPolicy = {
- _id: string;
+ id: string;
workspace: string;
name: string;
environment: string;
diff --git a/frontend/src/hooks/api/secretApprovalRequest/queries.tsx b/frontend/src/hooks/api/secretApprovalRequest/queries.tsx
index db4f6f94c5..11325fb502 100644
--- a/frontend/src/hooks/api/secretApprovalRequest/queries.tsx
+++ b/frontend/src/hooks/api/secretApprovalRequest/queries.tsx
@@ -78,7 +78,7 @@ export const decryptSecretApprovalSecret = (
key
});
return {
- _id: encSecret._id,
+ id: encSecret.id,
version: encSecret.version,
secretKey,
secretValue,
diff --git a/frontend/src/hooks/api/secretApprovalRequest/types.ts b/frontend/src/hooks/api/secretApprovalRequest/types.ts
index 1e129a61c4..1364701a53 100644
--- a/frontend/src/hooks/api/secretApprovalRequest/types.ts
+++ b/frontend/src/hooks/api/secretApprovalRequest/types.ts
@@ -16,7 +16,7 @@ export enum CommitType {
}
export type TSecretApprovalSecChangeData = {
- _id: string;
+ id: string;
secretKeyCiphertext: string;
secretKeyIV: string;
secretKeyTag: string;
@@ -34,7 +34,7 @@ export type TSecretApprovalSecChangeData = {
};
export type TSecretApprovalSecChange = {
- _id: string;
+ id: string;
version: number;
secretKey: string;
secretValue: string;
@@ -46,7 +46,7 @@ export type TSecretApprovalRequest<
T extends unknown = TSecretApprovalSecChangeData,
J extends unknown = EncryptedSecret
> = {
- _id: string;
+ id: string;
slug: string;
createdAt: string;
committer: string;
diff --git a/frontend/src/hooks/api/secretImports/queries.tsx b/frontend/src/hooks/api/secretImports/queries.tsx
index 75c1820cc5..53c5cbe514 100644
--- a/frontend/src/hooks/api/secretImports/queries.tsx
+++ b/frontend/src/hooks/api/secretImports/queries.tsx
@@ -142,7 +142,7 @@ export const useGetImportedSecrets = ({
});
return {
- _id: encSecret._id,
+ id: encSecret.id,
env: encSecret.environment,
key: secretKey,
value: secretValue,
diff --git a/frontend/src/hooks/api/secretImports/types.ts b/frontend/src/hooks/api/secretImports/types.ts
index 019401092f..173e976e13 100644
--- a/frontend/src/hooks/api/secretImports/types.ts
+++ b/frontend/src/hooks/api/secretImports/types.ts
@@ -2,7 +2,7 @@ import { UserWsKeyPair } from "../keys/types";
import { EncryptedSecret } from "../secrets/types";
export type TSecretImports = {
- _id: string;
+ id: string;
workspaceId: string;
environment: string;
folderId: string;
diff --git a/frontend/src/hooks/api/secretRotation/types.ts b/frontend/src/hooks/api/secretRotation/types.ts
index 76d3b51747..90458f830a 100644
--- a/frontend/src/hooks/api/secretRotation/types.ts
+++ b/frontend/src/hooks/api/secretRotation/types.ts
@@ -71,7 +71,7 @@ export type TProviderTemplate = {
};
export type TSecretRotation<T extends unknown = EncryptedSecret> = {
- _id: string;
+ id: string;
interval: number;
provider: string;
customProvider: string;
diff --git a/frontend/src/hooks/api/secretSnapshots/queries.tsx b/frontend/src/hooks/api/secretSnapshots/queries.tsx
index 13db97aead..842f9d44c1 100644
--- a/frontend/src/hooks/api/secretSnapshots/queries.tsx
+++ b/frontend/src/hooks/api/secretSnapshots/queries.tsx
@@ -102,7 +102,7 @@ export const useGetSnapshotSecrets = ({ decryptFileKey, env, snapshotId }: TSnap
const secretComment = "";
const decryptedSecret = {
- _id: encSecret.secret,
+ id: encSecret.secret,
env: encSecret.environment,
key: secretKey,
value: secretValue,
diff --git a/frontend/src/hooks/api/secretSnapshots/types.ts b/frontend/src/hooks/api/secretSnapshots/types.ts
index 8fa5f94517..9f1fb4da63 100644
--- a/frontend/src/hooks/api/secretSnapshots/types.ts
+++ b/frontend/src/hooks/api/secretSnapshots/types.ts
@@ -2,7 +2,7 @@ import { UserWsKeyPair } from "../keys/types";
import { EncryptedSecretVersion } from "../secrets/types";
export type TSecretSnapshot = {
- _id: string;
+ id: string;
workspace: string;
version: number;
secretVersions: string[];
diff --git a/frontend/src/hooks/api/secrets/queries.tsx b/frontend/src/hooks/api/secrets/queries.tsx
index 55bce3338b..1ba9a52518 100644
--- a/frontend/src/hooks/api/secrets/queries.tsx
+++ b/frontend/src/hooks/api/secrets/queries.tsx
@@ -63,7 +63,7 @@ export const decryptSecrets = (
});
const decryptedSecret: DecryptedSecret = {
- _id: encSecret._id,
+ id: encSecret.id,
env: encSecret.environment,
key: secretKey,
value: secretValue,
@@ -79,7 +79,7 @@ export const decryptSecrets = (
if (encSecret.type === "personal") {
personalSecrets[decryptedSecret.key] = {
- id: encSecret._id,
+ id: encSecret.id,
value: secretValue
};
} else {
@@ -225,7 +225,7 @@ export const useGetSecretVersion = (dto: GetSecretVersionsDTO) =>
return data
.map((el) => ({
createdAt: el.createdAt,
- id: el._id,
+ id: el.id,
value: decryptSymmetric({
ciphertext: el.secretValueCiphertext,
iv: el.secretValueIV,
diff --git a/frontend/src/hooks/api/secrets/types.ts b/frontend/src/hooks/api/secrets/types.ts
index 36f62c3dff..66ad3f1fc9 100644
--- a/frontend/src/hooks/api/secrets/types.ts
+++ b/frontend/src/hooks/api/secrets/types.ts
@@ -2,7 +2,7 @@ import type { UserWsKeyPair } from "../keys/types";
import type { WsTag } from "../tags/types";
export type EncryptedSecret = {
- _id: string;
+ id: string;
version: number;
workspace: string;
type: "shared" | "personal";
@@ -26,7 +26,7 @@ export type EncryptedSecret = {
};
export type DecryptedSecret = {
- _id: string;
+ id: string;
version: number;
key: string;
value: string;
@@ -45,7 +45,7 @@ export type DecryptedSecret = {
};
export type EncryptedSecretVersion = {
- _id: string;
+ id: string;
secret: string;
version: number;
workspace: string;
diff --git a/frontend/src/hooks/api/subscriptions/types.ts b/frontend/src/hooks/api/subscriptions/types.ts
index e38a7527f3..b975f04728 100644
--- a/frontend/src/hooks/api/subscriptions/types.ts
+++ b/frontend/src/hooks/api/subscriptions/types.ts
@@ -1,5 +1,5 @@
export type SubscriptionPlan = {
- _id: string;
+ id: string;
membersUsed: number;
memberLimit: number;
auditLogs: boolean;
diff --git a/frontend/src/hooks/api/tags/types.ts b/frontend/src/hooks/api/tags/types.ts
index de09f5ac47..6e428da70f 100644
--- a/frontend/src/hooks/api/tags/types.ts
+++ b/frontend/src/hooks/api/tags/types.ts
@@ -1,7 +1,7 @@
export type UserWsTags = WsTag[];
export type WsTag = {
- _id: string;
+ id: string;
name: string;
slug: string;
tagColor?: string;
@@ -11,7 +11,7 @@ export type WsTag = {
__v: number;
}
-export type WorkspaceTag = { _id: string; name: string; slug: string };
+export type WorkspaceTag = { id: string; name: string; slug: string };
export type CreateTagDTO = {
workspaceID: string;
@@ -27,7 +27,7 @@ export type CreateTagRes = {
createdAt: string;
tagColor?: string;
user: string;
- _id: string;
+ id: string;
};
export type DeleteTagDTO = { tagID: string; };
@@ -38,12 +38,12 @@ export type DeleteWsTagRes = {
workspace: string;
createdAt: string;
user: string;
- _id: string;
+ id: string;
};
export type SecretTags = {
id: string;
- _id: string;
+ id: string;
slug: string;
tagColor: string;
}
diff --git a/frontend/src/hooks/api/trustedIps/types.ts b/frontend/src/hooks/api/trustedIps/types.ts
index e8985b2def..fb8177c452 100644
--- a/frontend/src/hooks/api/trustedIps/types.ts
+++ b/frontend/src/hooks/api/trustedIps/types.ts
@@ -1,5 +1,5 @@
export type TrustedIp = {
- _id: string;
+ id: string;
workspace: string;
ipAddress: string;
type: "ipv4" | "ipv6";
diff --git a/frontend/src/hooks/api/webhooks/types.ts b/frontend/src/hooks/api/webhooks/types.ts
index 8fd64bcc21..f9ae1ba432 100644
--- a/frontend/src/hooks/api/webhooks/types.ts
+++ b/frontend/src/hooks/api/webhooks/types.ts
@@ -1,5 +1,5 @@
export type TWebhook = {
- _id: string;
+ id: string;
workspace: string;
environment: string;
secretPath: string;
diff --git a/frontend/src/hooks/api/workspace/types.ts b/frontend/src/hooks/api/workspace/types.ts
index bebf5119fd..80d1aaaa84 100644
--- a/frontend/src/hooks/api/workspace/types.ts
+++ b/frontend/src/hooks/api/workspace/types.ts
@@ -1,6 +1,6 @@
export type Workspace = {
__v: number;
- _id: string;
+ id: string;
name: string;
organization: string;
autoCapitalization: boolean;
@@ -14,13 +14,13 @@ export type WorkspaceEnv = {
isWriteDenied: boolean;
};
-export type WorkspaceTag = { _id: string; name: string; slug: string };
+export type WorkspaceTag = { id: string; name: string; slug: string };
export type NameWorkspaceSecretsDTO = {
workspaceId: string;
secretsToUpdate: {
secretName: string;
- _id: string;
+ id: string;
}[];
}
diff --git a/frontend/src/layouts/AdminLayout/AdminLayout.tsx b/frontend/src/layouts/AdminLayout/AdminLayout.tsx
index 7597db8372..3cee01f11a 100644
--- a/frontend/src/layouts/AdminLayout/AdminLayout.tsx
+++ b/frontend/src/layouts/AdminLayout/AdminLayout.tsx
@@ -101,7 +101,7 @@ export const AdminLayout = ({ children }: LayoutProps) => {
<div>
{!router.asPath.includes("personal") && (
<div className="flex h-12 cursor-default justify-between items-center px-3 pt-6">
- <Link href={`/org/${currentOrg?._id}/overview`}>
+ <Link href={`/org/${currentOrg?.id}/overview`}>
<div className="my-6 flex cursor-default items-center justify-center pr-2 text-sm text-mineshaft-300 hover:text-mineshaft-100">
<FontAwesomeIcon icon={faArrowLeft} className="pr-3" />
Back to organization
@@ -264,7 +264,7 @@ export const AdminLayout = ({ children }: LayoutProps) => {
// direct user to start pro trial
const url = await mutateAsync({
- orgId: currentOrg._id,
+ orgId: currentOrg.id,
success_url: window.location.href
});
diff --git a/frontend/src/layouts/AppLayout/components/NavBar/NavBar.tsx b/frontend/src/layouts/AppLayout/components/NavBar/NavBar.tsx
index 7adb88959e..0e970eeebc 100644
--- a/frontend/src/layouts/AppLayout/components/NavBar/NavBar.tsx
+++ b/frontend/src/layouts/AppLayout/components/NavBar/NavBar.tsx
@@ -267,15 +267,15 @@ export const Navbar = () => {
</div>
<div className="mt-3 mb-2 flex flex-col items-start px-1">
{orgs
- ?.filter((org: { _id: string }) => org._id !== currentOrg?._id)
- .map((org: { _id: string; name: string }) => (
+ ?.filter((org: { id: string }) => org.id !== currentOrg?.id)
+ .map((org: { id: string; name: string }) => (
<div
onKeyDown={() => null}
role="button"
tabIndex={0}
key={guidGenerator()}
onClick={() => {
- localStorage.setItem("orgData.id", org._id);
+ localStorage.setItem("orgData.id", org.id);
router.reload();
}}
className="flex w-full cursor-pointer flex-row items-center justify-start rounded-md p-1.5 hover:bg-white/5"
@@ -326,7 +326,7 @@ export const Navbar = () => {
// direct user to start pro trial
const url = await mutateAsync({
- orgId: currentOrg._id,
+ orgId: currentOrg.id,
success_url: window.location.href
});
diff --git a/frontend/src/pages/api/secret-scanning/getRisksByOrganization.ts b/frontend/src/pages/api/secret-scanning/getRisksByOrganization.ts
index a2072f2ed6..2c555191c2 100644
--- a/frontend/src/pages/api/secret-scanning/getRisksByOrganization.ts
+++ b/frontend/src/pages/api/secret-scanning/getRisksByOrganization.ts
@@ -1,7 +1,7 @@
import SecurityClient from "@app/components/utilities/SecurityClient";
export type IGitRisks = {
- _id: string;
+ id: string;
description: string;
startLine: string;
endLine: string;
diff --git a/frontend/src/pages/dashboard.tsx b/frontend/src/pages/dashboard.tsx
index 3f24ab1017..42b55d1b36 100644
--- a/frontend/src/pages/dashboard.tsx
+++ b/frontend/src/pages/dashboard.tsx
@@ -18,7 +18,7 @@ export default function DashboardRedirect() {
if (localStorage.getItem("orgData.id")) {
router.push(`/org/${localStorage.getItem("orgData.id")}/overview`);
} else if (userOrgs) {
- userOrg = userOrgs[0]._id;
+ userOrg = userOrgs[0].id;
router.push(`/org/${userOrg}/overview`);
}
} catch (error) {
diff --git a/frontend/src/pages/integrations/aws-parameter-store/authorize.tsx b/frontend/src/pages/integrations/aws-parameter-store/authorize.tsx
index 14e8e97a04..53e8c34da2 100644
--- a/frontend/src/pages/integrations/aws-parameter-store/authorize.tsx
+++ b/frontend/src/pages/integrations/aws-parameter-store/authorize.tsx
@@ -52,7 +52,7 @@ export default function AWSParameterStoreAuthorizeIntegrationPage() {
setIsLoading(false);
router.push(
- `/integrations/aws-parameter-store/create?integrationAuthId=${integrationAuth._id}`
+ `/integrations/aws-parameter-store/create?integrationAuthId=${integrationAuth.id}`
);
} catch (err) {
console.error(err);
diff --git a/frontend/src/pages/integrations/aws-parameter-store/create.tsx b/frontend/src/pages/integrations/aws-parameter-store/create.tsx
index fd8de3c3fc..b9350ec03b 100644
--- a/frontend/src/pages/integrations/aws-parameter-store/create.tsx
+++ b/frontend/src/pages/integrations/aws-parameter-store/create.tsx
@@ -95,12 +95,12 @@ export default function AWSParameterStoreCreateIntegrationPage() {
}
}
- if (!integrationAuth?._id) return;
+ if (!integrationAuth?.id) return;
setIsLoading(true);
await mutateAsync({
- integrationAuthId: integrationAuth?._id,
+ integrationAuthId: integrationAuth?.id,
isActive: true,
sourceEnvironment: selectedSourceEnvironment,
path,
diff --git a/frontend/src/pages/integrations/aws-secret-manager/authorize.tsx b/frontend/src/pages/integrations/aws-secret-manager/authorize.tsx
index f69d46f718..daf3222b47 100644
--- a/frontend/src/pages/integrations/aws-secret-manager/authorize.tsx
+++ b/frontend/src/pages/integrations/aws-secret-manager/authorize.tsx
@@ -50,7 +50,7 @@ export default function AWSSecretManagerCreateIntegrationPage() {
setIsLoading(false);
router.push(
- `/integrations/aws-secret-manager/create?integrationAuthId=${integrationAuth._id}`
+ `/integrations/aws-secret-manager/create?integrationAuthId=${integrationAuth.id}`
);
} catch (err) {
console.error(err);
diff --git a/frontend/src/pages/integrations/aws-secret-manager/create.tsx b/frontend/src/pages/integrations/aws-secret-manager/create.tsx
index 3c5b205116..056b0d0999 100644
--- a/frontend/src/pages/integrations/aws-secret-manager/create.tsx
+++ b/frontend/src/pages/integrations/aws-secret-manager/create.tsx
@@ -94,12 +94,12 @@ export default function AWSSecretManagerCreateIntegrationPage() {
return;
}
- if (!integrationAuth?._id) return;
+ if (!integrationAuth?.id) return;
setIsLoading(true);
await mutateAsync({
- integrationAuthId: integrationAuth?._id,
+ integrationAuthId: integrationAuth?.id,
isActive: true,
app: targetSecretName.trim(),
sourceEnvironment: selectedSourceEnvironment,
diff --git a/frontend/src/pages/integrations/azure-key-vault/create.tsx b/frontend/src/pages/integrations/azure-key-vault/create.tsx
index 0797ecc033..da160a6f87 100644
--- a/frontend/src/pages/integrations/azure-key-vault/create.tsx
+++ b/frontend/src/pages/integrations/azure-key-vault/create.tsx
@@ -53,11 +53,11 @@ export default function AzureKeyVaultCreateIntegrationPage() {
return;
}
- if (!integrationAuth?._id) return;
+ if (!integrationAuth?.id) return;
setIsLoading(true);
await mutateAsync({
- integrationAuthId: integrationAuth?._id,
+ integrationAuthId: integrationAuth?.id,
isActive: true,
app: vaultBaseUrl,
sourceEnvironment: selectedSourceEnvironment,
diff --git a/frontend/src/pages/integrations/azure-key-vault/oauth2/callback.tsx b/frontend/src/pages/integrations/azure-key-vault/oauth2/callback.tsx
index 2f23f729f4..df5a500063 100644
--- a/frontend/src/pages/integrations/azure-key-vault/oauth2/callback.tsx
+++ b/frontend/src/pages/integrations/azure-key-vault/oauth2/callback.tsx
@@ -26,7 +26,7 @@ export default function AzureKeyVaultOAuth2CallbackPage() {
});
router.push(
- `/integrations/azure-key-vault/create?integrationAuthId=${integrationAuth._id}`
+ `/integrations/azure-key-vault/create?integrationAuthId=${integrationAuth.id}`
);
} catch (err) {
console.error(err);
diff --git a/frontend/src/pages/integrations/bitbucket/create.tsx b/frontend/src/pages/integrations/bitbucket/create.tsx
index f696ea5923..a9f678d9c6 100644
--- a/frontend/src/pages/integrations/bitbucket/create.tsx
+++ b/frontend/src/pages/integrations/bitbucket/create.tsx
@@ -72,7 +72,7 @@ export default function BitBucketCreateIntegrationPage() {
try {
setIsLoading(true);
- if (!integrationAuth?._id) return;
+ if (!integrationAuth?.id) return;
const targetApp = integrationAuthApps?.find(
(integrationAuthApp) => integrationAuthApp.appId === targetAppId
@@ -84,7 +84,7 @@ export default function BitBucketCreateIntegrationPage() {
if (!targetApp || !targetApp.appId || !targetEnvironment) return;
await mutateAsync({
- integrationAuthId: integrationAuth?._id,
+ integrationAuthId: integrationAuth?.id,
isActive: true,
app: targetApp.name,
appId: targetApp.appId,
diff --git a/frontend/src/pages/integrations/bitbucket/oauth2/callback.tsx b/frontend/src/pages/integrations/bitbucket/oauth2/callback.tsx
index a7326722af..205086c19c 100644
--- a/frontend/src/pages/integrations/bitbucket/oauth2/callback.tsx
+++ b/frontend/src/pages/integrations/bitbucket/oauth2/callback.tsx
@@ -24,7 +24,7 @@ export default function BitBucketOAuth2CallbackPage() {
integration: "bitbucket"
});
- router.push(`/integrations/bitbucket/create?integrationAuthId=${integrationAuth._id}`);
+ router.push(`/integrations/bitbucket/create?integrationAuthId=${integrationAuth.id}`);
} catch (err) {
console.error(err);
}
diff --git a/frontend/src/pages/integrations/checkly/authorize.tsx b/frontend/src/pages/integrations/checkly/authorize.tsx
index c3938641bc..6340aac988 100644
--- a/frontend/src/pages/integrations/checkly/authorize.tsx
+++ b/frontend/src/pages/integrations/checkly/authorize.tsx
@@ -38,7 +38,7 @@ export default function ChecklyCreateIntegrationPage() {
setIsLoading(false);
- router.push(`/integrations/checkly/create?integrationAuthId=${integrationAuth._id}`);
+ router.push(`/integrations/checkly/create?integrationAuthId=${integrationAuth.id}`);
} catch (err) {
console.error(err);
}
diff --git a/frontend/src/pages/integrations/checkly/create.tsx b/frontend/src/pages/integrations/checkly/create.tsx
index cd5ae71b7f..290ca1d1db 100644
--- a/frontend/src/pages/integrations/checkly/create.tsx
+++ b/frontend/src/pages/integrations/checkly/create.tsx
@@ -80,7 +80,7 @@ export default function ChecklyCreateIntegrationPage() {
const handleButtonClick = async () => {
try {
- if (!integrationAuth?._id) return;
+ if (!integrationAuth?.id) return;
setIsLoading(true);
@@ -94,7 +94,7 @@ export default function ChecklyCreateIntegrationPage() {
if (!targetApp) return;
await mutateAsync({
- integrationAuthId: integrationAuth?._id,
+ integrationAuthId: integrationAuth?.id,
isActive: true,
app: targetApp?.name,
appId: targetApp?.appId,
diff --git a/frontend/src/pages/integrations/circleci/authorize.tsx b/frontend/src/pages/integrations/circleci/authorize.tsx
index f276362f76..5d9f207bbd 100644
--- a/frontend/src/pages/integrations/circleci/authorize.tsx
+++ b/frontend/src/pages/integrations/circleci/authorize.tsx
@@ -38,7 +38,7 @@ export default function CircleCICreateIntegrationPage() {
setIsLoading(false);
- router.push(`/integrations/circleci/create?integrationAuthId=${integrationAuth._id}`);
+ router.push(`/integrations/circleci/create?integrationAuthId=${integrationAuth.id}`);
} catch (err) {
console.error(err);
}
diff --git a/frontend/src/pages/integrations/circleci/create.tsx b/frontend/src/pages/integrations/circleci/create.tsx
index 1fc84a4332..73bebaae8c 100644
--- a/frontend/src/pages/integrations/circleci/create.tsx
+++ b/frontend/src/pages/integrations/circleci/create.tsx
@@ -63,12 +63,12 @@ export default function CircleCICreateIntegrationPage() {
const handleButtonClick = async () => {
try {
- if (!integrationAuth?._id) return;
+ if (!integrationAuth?.id) return;
setIsLoading(true);
await mutateAsync({
- integrationAuthId: integrationAuth?._id,
+ integrationAuthId: integrationAuth?.id,
isActive: true,
app: targetApp,
appId: integrationAuthApps?.find((integrationAuthApp) => integrationAuthApp.name === targetApp)?.appId,
diff --git a/frontend/src/pages/integrations/cloud-66/authorize.tsx b/frontend/src/pages/integrations/cloud-66/authorize.tsx
index 70c1153378..6582cfab1b 100644
--- a/frontend/src/pages/integrations/cloud-66/authorize.tsx
+++ b/frontend/src/pages/integrations/cloud-66/authorize.tsx
@@ -33,7 +33,7 @@ export default function Cloud66CreateIntegrationPage() {
setIsLoading(false);
- router.push(`/integrations/cloud-66/create?integrationAuthId=${integrationAuth._id}`);
+ router.push(`/integrations/cloud-66/create?integrationAuthId=${integrationAuth.id}`);
} catch (err) {
console.error(err);
}
diff --git a/frontend/src/pages/integrations/cloud-66/create.tsx b/frontend/src/pages/integrations/cloud-66/create.tsx
index 5313f82cb5..7e7d42507e 100644
--- a/frontend/src/pages/integrations/cloud-66/create.tsx
+++ b/frontend/src/pages/integrations/cloud-66/create.tsx
@@ -56,12 +56,12 @@ export default function Cloud66CreateIntegrationPage() {
const handleButtonClick = async () => {
try {
- if (!integrationAuth?._id) return;
+ if (!integrationAuth?.id) return;
setIsLoading(true);
await mutateAsync({
- integrationAuthId: integrationAuth?._id,
+ integrationAuthId: integrationAuth?.id,
isActive: true,
app: targetApp,
appId: integrationAuthApps?.find((integrationAuthApp) => integrationAuthApp.name === targetApp)?.appId,
diff --git a/frontend/src/pages/integrations/cloudflare-pages/authorize.tsx b/frontend/src/pages/integrations/cloudflare-pages/authorize.tsx
index a16756c797..e526271e51 100644
--- a/frontend/src/pages/integrations/cloudflare-pages/authorize.tsx
+++ b/frontend/src/pages/integrations/cloudflare-pages/authorize.tsx
@@ -40,7 +40,7 @@ export default function CloudflarePagesIntegrationPage() {
setAccountId("");
setIsLoading(false);
- router.push(`/integrations/cloudflare-pages/create?integrationAuthId=${integrationAuth._id}`);
+ router.push(`/integrations/cloudflare-pages/create?integrationAuthId=${integrationAuth.id}`);
} catch (err) {
console.error(err);
}
diff --git a/frontend/src/pages/integrations/cloudflare-pages/create.tsx b/frontend/src/pages/integrations/cloudflare-pages/create.tsx
index 0f4d171a41..b18d2d9bd0 100644
--- a/frontend/src/pages/integrations/cloudflare-pages/create.tsx
+++ b/frontend/src/pages/integrations/cloudflare-pages/create.tsx
@@ -53,12 +53,12 @@ export default function CloudflarePagesIntegrationPage() {
const handleButtonClick = async () => {
try {
- if (!integrationAuth?._id) return;
+ if (!integrationAuth?.id) return;
setIsLoading(true);
await mutateAsync({
- integrationAuthId: integrationAuth?._id,
+ integrationAuthId: integrationAuth?.id,
isActive: true,
app: targetApp,
appId: targetAppId,
diff --git a/frontend/src/pages/integrations/cloudflare-workers/authorize.tsx b/frontend/src/pages/integrations/cloudflare-workers/authorize.tsx
index 3b46751fcc..36a1aa44d9 100644
--- a/frontend/src/pages/integrations/cloudflare-workers/authorize.tsx
+++ b/frontend/src/pages/integrations/cloudflare-workers/authorize.tsx
@@ -40,7 +40,7 @@ export default function CloudflareWorkersIntegrationPage() {
setAccountId("");
setIsLoading(false);
- router.push(`/integrations/cloudflare-workers/create?integrationAuthId=${integrationAuth._id}`);
+ router.push(`/integrations/cloudflare-workers/create?integrationAuthId=${integrationAuth.id}`);
} catch (err) {
console.error(err);
}
diff --git a/frontend/src/pages/integrations/cloudflare-workers/create.tsx b/frontend/src/pages/integrations/cloudflare-workers/create.tsx
index 333bdd17f2..2a07663d3f 100644
--- a/frontend/src/pages/integrations/cloudflare-workers/create.tsx
+++ b/frontend/src/pages/integrations/cloudflare-workers/create.tsx
@@ -45,12 +45,12 @@ export default function CloudflareWorkersIntegrationPage() {
const handleButtonClick = async () => {
try {
- if (!integrationAuth?._id) return;
+ if (!integrationAuth?.id) return;
setIsLoading(true);
await mutateAsync({
- integrationAuthId: integrationAuth?._id,
+ integrationAuthId: integrationAuth?.id,
isActive: true,
app: targetApp,
appId: targetAppId,
diff --git a/frontend/src/pages/integrations/codefresh/authorize.tsx b/frontend/src/pages/integrations/codefresh/authorize.tsx
index b6f96c1a29..6c73515d56 100644
--- a/frontend/src/pages/integrations/codefresh/authorize.tsx
+++ b/frontend/src/pages/integrations/codefresh/authorize.tsx
@@ -33,7 +33,7 @@ export default function CodefreshCreateIntegrationPage() {
setIsLoading(false);
- router.push(`/integrations/codefresh/create?integrationAuthId=${integrationAuth._id}`);
+ router.push(`/integrations/codefresh/create?integrationAuthId=${integrationAuth.id}`);
} catch (err) {
console.error(err);
}
diff --git a/frontend/src/pages/integrations/codefresh/create.tsx b/frontend/src/pages/integrations/codefresh/create.tsx
index 4ce9a4c536..d935512173 100644
--- a/frontend/src/pages/integrations/codefresh/create.tsx
+++ b/frontend/src/pages/integrations/codefresh/create.tsx
@@ -56,12 +56,12 @@ export default function CodefreshCreateIntegrationPage() {
const handleButtonClick = async () => {
try {
- if (!integrationAuth?._id) return;
+ if (!integrationAuth?.id) return;
setIsLoading(true);
await mutateAsync({
- integrationAuthId: integrationAuth?._id,
+ integrationAuthId: integrationAuth?.id,
isActive: true,
app: targetApp,
appId: integrationAuthApps?.find((integrationAuthApp) => integrationAuthApp.name === targetApp)?.appId,
diff --git a/frontend/src/pages/integrations/digital-ocean-app-platform/authorize.tsx b/frontend/src/pages/integrations/digital-ocean-app-platform/authorize.tsx
index ec4652b9e6..09f06041c1 100644
--- a/frontend/src/pages/integrations/digital-ocean-app-platform/authorize.tsx
+++ b/frontend/src/pages/integrations/digital-ocean-app-platform/authorize.tsx
@@ -33,7 +33,7 @@ export default function DigitalOceanAppPlatformCreateIntegrationPage() {
setIsLoading(false);
- router.push(`/integrations/digital-ocean-app-platform/create?integrationAuthId=${integrationAuth._id}`);
+ router.push(`/integrations/digital-ocean-app-platform/create?integrationAuthId=${integrationAuth.id}`);
} catch (err) {
console.error(err);
}
diff --git a/frontend/src/pages/integrations/digital-ocean-app-platform/create.tsx b/frontend/src/pages/integrations/digital-ocean-app-platform/create.tsx
index 3dddaf8317..848549b220 100644
--- a/frontend/src/pages/integrations/digital-ocean-app-platform/create.tsx
+++ b/frontend/src/pages/integrations/digital-ocean-app-platform/create.tsx
@@ -56,12 +56,12 @@ export default function DigitalOceanAppPlatformCreateIntegrationPage() {
const handleButtonClick = async () => {
try {
- if (!integrationAuth?._id) return;
+ if (!integrationAuth?.id) return;
setIsLoading(true);
await mutateAsync({
- integrationAuthId: integrationAuth?._id,
+ integrationAuthId: integrationAuth?.id,
isActive: true,
app: targetApp,
appId: integrationAuthApps?.find((integrationAuthApp) => integrationAuthApp.name === targetApp)?.appId,
diff --git a/frontend/src/pages/integrations/flyio/authorize.tsx b/frontend/src/pages/integrations/flyio/authorize.tsx
index fe6d8022ec..df1afca40b 100644
--- a/frontend/src/pages/integrations/flyio/authorize.tsx
+++ b/frontend/src/pages/integrations/flyio/authorize.tsx
@@ -51,7 +51,7 @@ export default function FlyioAuthorizeIntegrationPage() {
});
setIsLoading(false);
- router.push(`/integrations/flyio/create?integrationAuthId=${integrationAuth._id}`);
+ router.push(`/integrations/flyio/create?integrationAuthId=${integrationAuth.id}`);
} catch (err) {
setIsLoading(false);
console.error(err);
diff --git a/frontend/src/pages/integrations/flyio/create.tsx b/frontend/src/pages/integrations/flyio/create.tsx
index be1a577de6..4fa01cefb2 100644
--- a/frontend/src/pages/integrations/flyio/create.tsx
+++ b/frontend/src/pages/integrations/flyio/create.tsx
@@ -65,12 +65,12 @@ export default function FlyioCreateIntegrationPage() {
const handleButtonClick = async () => {
try {
- if (!integrationAuth?._id) return;
+ if (!integrationAuth?.id) return;
setIsLoading(true);
await mutateAsync({
- integrationAuthId: integrationAuth?._id,
+ integrationAuthId: integrationAuth?.id,
isActive: true,
app: targetApp,
sourceEnvironment: selectedSourceEnvironment,
diff --git a/frontend/src/pages/integrations/gcp-secret-manager/authorize.tsx b/frontend/src/pages/integrations/gcp-secret-manager/authorize.tsx
index 91755cc4cd..c5c633177f 100644
--- a/frontend/src/pages/integrations/gcp-secret-manager/authorize.tsx
+++ b/frontend/src/pages/integrations/gcp-secret-manager/authorize.tsx
@@ -49,7 +49,7 @@ export default function GCPSecretManagerAuthorizeIntegrationPage() {
const state = crypto.randomBytes(16).toString("hex");
localStorage.setItem("latestCSRFToken", state);
- const link = `https://accounts.google.com/o/oauth2/auth?scope=https://www.googleapis.com/auth/cloud-platform&response_type=code&access_type=offline&state=${state}&redirect_uri=${window.location.origin}/integrations/gcp-secret-manager/oauth2/callback&client_id=${integrationOption.clientId}`;
+ const link = `https://accounts.google.com/o/oauth2/auth?scope=https://www.googleapis.com/auth/cloud-platform&response_type=code&access_type=offline&state=${state}&redirect_uri=${window.location.origin}/integrations/gcp-secret-manager/oauth2/callback&clientid=${integrationOption.clientId}`;
window.location.assign(link);
}
@@ -66,7 +66,7 @@ export default function GCPSecretManagerAuthorizeIntegrationPage() {
});
setIsLoading(false);
- router.push(`/integrations/gcp-secret-manager/create?integrationAuthId=${integrationAuth._id}`);
+ router.push(`/integrations/gcp-secret-manager/create?integrationAuthId=${integrationAuth.id}`);
} catch (err) {
console.error(err);
setIsLoading(false);
diff --git a/frontend/src/pages/integrations/gcp-secret-manager/create.tsx b/frontend/src/pages/integrations/gcp-secret-manager/create.tsx
index cc7b3184fb..e171f3dba3 100644
--- a/frontend/src/pages/integrations/gcp-secret-manager/create.tsx
+++ b/frontend/src/pages/integrations/gcp-secret-manager/create.tsx
@@ -133,10 +133,10 @@ export default function GCPSecretManagerCreateIntegrationPage() {
try {
setIsLoading(true);
- if (!integrationAuth?._id) return;
+ if (!integrationAuth?.id) return;
await mutateAsync({
- integrationAuthId: integrationAuth?._id,
+ integrationAuthId: integrationAuth?.id,
isActive: true,
app: integrationAuthApps?.find((integrationAuthApp) => integrationAuthApp.appId === targetAppId)?.name,
appId: targetAppId,
diff --git a/frontend/src/pages/integrations/gcp-secret-manager/oauth2/callback.tsx b/frontend/src/pages/integrations/gcp-secret-manager/oauth2/callback.tsx
index 740897496d..3a9486d8d3 100644
--- a/frontend/src/pages/integrations/gcp-secret-manager/oauth2/callback.tsx
+++ b/frontend/src/pages/integrations/gcp-secret-manager/oauth2/callback.tsx
@@ -25,7 +25,7 @@ export default function GCPSecretManagerOAuth2CallbackPage() {
integration: "gcp-secret-manager"
});
- router.push(`/integrations/gcp-secret-manager/create?integrationAuthId=${integrationAuth._id}`);
+ router.push(`/integrations/gcp-secret-manager/create?integrationAuthId=${integrationAuth.id}`);
} catch (err) {
console.error(err);
}
diff --git a/frontend/src/pages/integrations/github/create.tsx b/frontend/src/pages/integrations/github/create.tsx
index ce0ec7858a..8c3759d909 100644
--- a/frontend/src/pages/integrations/github/create.tsx
+++ b/frontend/src/pages/integrations/github/create.tsx
@@ -79,7 +79,7 @@ export default function GitHubCreateIntegrationPage() {
try {
setIsLoading(true);
- if (!integrationAuth?._id) return;
+ if (!integrationAuth?.id) return;
const targetApps = integrationAuthApps?.filter(
(integrationAuthApp) => targetAppIds.includes(String(integrationAuthApp.appId))
@@ -90,7 +90,7 @@ export default function GitHubCreateIntegrationPage() {
await Promise.all(
targetApps.map(async (targetApp) => {
await mutateAsync({
- integrationAuthId: integrationAuth?._id,
+ integrationAuthId: integrationAuth?.id,
isActive: true,
app: targetApp.name,
sourceEnvironment: selectedSourceEnvironment,
diff --git a/frontend/src/pages/integrations/github/oauth2/callback.tsx b/frontend/src/pages/integrations/github/oauth2/callback.tsx
index d93e024781..341d0b0bd8 100644
--- a/frontend/src/pages/integrations/github/oauth2/callback.tsx
+++ b/frontend/src/pages/integrations/github/oauth2/callback.tsx
@@ -25,7 +25,7 @@ export default function GitHubOAuth2CallbackPage() {
integration: "github"
});
- router.push(`/integrations/github/create?integrationAuthId=${integrationAuth._id}`);
+ router.push(`/integrations/github/create?integrationAuthId=${integrationAuth.id}`);
} catch (err) {
console.error(err);
}
diff --git a/frontend/src/pages/integrations/gitlab/authorize.tsx b/frontend/src/pages/integrations/gitlab/authorize.tsx
index 32cf97869b..969c3cc85a 100644
--- a/frontend/src/pages/integrations/gitlab/authorize.tsx
+++ b/frontend/src/pages/integrations/gitlab/authorize.tsx
@@ -46,7 +46,7 @@ export default function GitLabAuthorizeIntegrationPage() {
localStorage.setItem("latestCSRFToken", csrfToken);
const state = `${csrfToken}|${(gitLabURL as string).trim() === "" ? "" : (gitLabURL as string).trim()}`;
- const link = `${baseURL}/oauth/authorize?client_id=${integrationOption.clientId}&redirect_uri=${window.location.origin}/integrations/gitlab/oauth2/callback&response_type=code&state=${state}`;
+ const link = `${baseURL}/oauth/authorize?clientid=${integrationOption.clientId}&redirect_uri=${window.location.origin}/integrations/gitlab/oauth2/callback&response_type=code&state=${state}`;
window.location.assign(link);
}
diff --git a/frontend/src/pages/integrations/gitlab/create.tsx b/frontend/src/pages/integrations/gitlab/create.tsx
index 33e7ef5e6d..421faf3645 100644
--- a/frontend/src/pages/integrations/gitlab/create.tsx
+++ b/frontend/src/pages/integrations/gitlab/create.tsx
@@ -146,10 +146,10 @@ export default function GitLabCreateIntegrationPage() {
}: FormData) => {
try {
setIsLoading(true);
- if (!integrationAuth?._id) return;
+ if (!integrationAuth?.id) return;
await mutateAsync({
- integrationAuthId: integrationAuth?._id,
+ integrationAuthId: integrationAuth?.id,
isActive: true,
app: integrationAuthApps?.find((integrationAuthApp) => String(integrationAuthApp.appId) === targetAppId)?.name,
appId: String(targetAppId),
diff --git a/frontend/src/pages/integrations/gitlab/oauth2/callback.tsx b/frontend/src/pages/integrations/gitlab/oauth2/callback.tsx
index 4ecf30de7a..ceb2fdef6e 100644
--- a/frontend/src/pages/integrations/gitlab/oauth2/callback.tsx
+++ b/frontend/src/pages/integrations/gitlab/oauth2/callback.tsx
@@ -29,7 +29,7 @@ export default function GitLabOAuth2CallbackPage() {
})
});
- router.push(`/integrations/gitlab/create?integrationAuthId=${integrationAuth._id}`);
+ router.push(`/integrations/gitlab/create?integrationAuthId=${integrationAuth.id}`);
} catch (err) {
console.error(err);
}
diff --git a/frontend/src/pages/integrations/hashicorp-vault/authorize.tsx b/frontend/src/pages/integrations/hashicorp-vault/authorize.tsx
index 56863734f2..2c9cc35ae4 100644
--- a/frontend/src/pages/integrations/hashicorp-vault/authorize.tsx
+++ b/frontend/src/pages/integrations/hashicorp-vault/authorize.tsx
@@ -77,7 +77,7 @@ export default function HashiCorpVaultAuthorizeIntegrationPage() {
setIsLoading(false);
- router.push(`/integrations/hashicorp-vault/create?integrationAuthId=${integrationAuth._id}`);
+ router.push(`/integrations/hashicorp-vault/create?integrationAuthId=${integrationAuth.id}`);
} catch (err) {
console.error(err);
}
diff --git a/frontend/src/pages/integrations/hashicorp-vault/create.tsx b/frontend/src/pages/integrations/hashicorp-vault/create.tsx
index 7cca22693f..73c6afbb04 100644
--- a/frontend/src/pages/integrations/hashicorp-vault/create.tsx
+++ b/frontend/src/pages/integrations/hashicorp-vault/create.tsx
@@ -48,7 +48,7 @@ export default function HashiCorpVaultCreateIntegrationPage() {
const handleButtonClick = async () => {
try {
- if (!integrationAuth?._id) return;
+ if (!integrationAuth?.id) return;
if (!isValidVaultPath(vaultEnginePath)) {
setVaultEnginePathErrorText("Vault KV Secrets Engine Path must be valid like kv");
@@ -67,7 +67,7 @@ export default function HashiCorpVaultCreateIntegrationPage() {
setIsLoading(true);
await mutateAsync({
- integrationAuthId: integrationAuth?._id,
+ integrationAuthId: integrationAuth?.id,
isActive: true,
app: vaultEnginePath,
sourceEnvironment: selectedSourceEnvironment,
diff --git a/frontend/src/pages/integrations/hasura-cloud/authorize.tsx b/frontend/src/pages/integrations/hasura-cloud/authorize.tsx
index d2cff62bab..4d00a1c28d 100644
--- a/frontend/src/pages/integrations/hasura-cloud/authorize.tsx
+++ b/frontend/src/pages/integrations/hasura-cloud/authorize.tsx
@@ -42,7 +42,7 @@ export default function HasuraCloudAuthorizeIntegrationPage() {
});
setIsLoading(false);
- router.push(`/integrations/hasura-cloud/create?integrationAuthId=${integrationAuth._id}`);
+ router.push(`/integrations/hasura-cloud/create?integrationAuthId=${integrationAuth.id}`);
} catch (err) {
setIsLoading(false);
console.error(err);
diff --git a/frontend/src/pages/integrations/hasura-cloud/create.tsx b/frontend/src/pages/integrations/hasura-cloud/create.tsx
index d104f6df79..6f8eac255c 100644
--- a/frontend/src/pages/integrations/hasura-cloud/create.tsx
+++ b/frontend/src/pages/integrations/hasura-cloud/create.tsx
@@ -58,11 +58,11 @@ export default function HasuraCloudCreateIntegrationPage() {
const onFormSubmit = async ({ secretPath, sourceEnvironment, appId }: FormData) => {
try {
- if (!integrationAuth?._id) return;
+ if (!integrationAuth?.id) return;
const app = integrationAuthApps?.find((data) => data.appId === appId);
await mutateAsync({
- integrationAuthId: integrationAuth?._id,
+ integrationAuthId: integrationAuth?.id,
isActive: true,
sourceEnvironment,
secretPath,
diff --git a/frontend/src/pages/integrations/heroku/create.tsx b/frontend/src/pages/integrations/heroku/create.tsx
index d73eb408b9..7f051136a3 100644
--- a/frontend/src/pages/integrations/heroku/create.tsx
+++ b/frontend/src/pages/integrations/heroku/create.tsx
@@ -59,10 +59,10 @@ export default function HerokuCreateIntegrationPage() {
try {
setIsLoading(true);
- if (!integrationAuth?._id) return;
+ if (!integrationAuth?.id) return;
await mutateAsync({
- integrationAuthId: integrationAuth?._id,
+ integrationAuthId: integrationAuth?.id,
isActive: true,
app: targetApp,
sourceEnvironment: selectedSourceEnvironment,
diff --git a/frontend/src/pages/integrations/heroku/oauth2/callback.tsx b/frontend/src/pages/integrations/heroku/oauth2/callback.tsx
index a3a978a6a8..4262985bbe 100644
--- a/frontend/src/pages/integrations/heroku/oauth2/callback.tsx
+++ b/frontend/src/pages/integrations/heroku/oauth2/callback.tsx
@@ -24,7 +24,7 @@ export default function HerokuOAuth2CallbackPage() {
integration: "heroku"
});
- router.push(`/integrations/heroku/create?integrationAuthId=${integrationAuth._id}`);
+ router.push(`/integrations/heroku/create?integrationAuthId=${integrationAuth.id}`);
} catch (err) {
console.error(err);
}
diff --git a/frontend/src/pages/integrations/laravel-forge/authorize.tsx b/frontend/src/pages/integrations/laravel-forge/authorize.tsx
index cf8d7020ea..0c02053f7f 100644
--- a/frontend/src/pages/integrations/laravel-forge/authorize.tsx
+++ b/frontend/src/pages/integrations/laravel-forge/authorize.tsx
@@ -43,7 +43,7 @@ export default function LaravelForgeCreateIntegrationPage() {
setIsLoading(false);
- router.push(`/integrations/laravel-forge/create?integrationAuthId=${integrationAuth._id}`);
+ router.push(`/integrations/laravel-forge/create?integrationAuthId=${integrationAuth.id}`);
} catch (err) {
console.error(err);
}
diff --git a/frontend/src/pages/integrations/laravel-forge/create.tsx b/frontend/src/pages/integrations/laravel-forge/create.tsx
index 91ff2a2d08..07e13ebf25 100644
--- a/frontend/src/pages/integrations/laravel-forge/create.tsx
+++ b/frontend/src/pages/integrations/laravel-forge/create.tsx
@@ -56,12 +56,12 @@ export default function LaravelForgeCreateIntegrationPage() {
const handleButtonClick = async () => {
try {
- if (!integrationAuth?._id) return;
+ if (!integrationAuth?.id) return;
setIsLoading(true);
await mutateAsync({
- integrationAuthId: integrationAuth?._id,
+ integrationAuthId: integrationAuth?.id,
isActive: true,
app: targetApp,
appId: String(integrationAuthApps?.find((integrationAuthApp) => integrationAuthApp.name === targetApp)?.appId),
diff --git a/frontend/src/pages/integrations/netlify/create.tsx b/frontend/src/pages/integrations/netlify/create.tsx
index eff335f978..bc3ac59766 100644
--- a/frontend/src/pages/integrations/netlify/create.tsx
+++ b/frontend/src/pages/integrations/netlify/create.tsx
@@ -67,10 +67,10 @@ export default function NetlifyCreateIntegrationPage() {
try {
setIsLoading(true);
- if (!integrationAuth?._id) return;
+ if (!integrationAuth?.id) return;
await mutateAsync({
- integrationAuthId: integrationAuth?._id,
+ integrationAuthId: integrationAuth?.id,
isActive: true,
app: targetApp,
appId: integrationAuthApps?.find((integrationAuthApp) => integrationAuthApp.name === targetApp)?.appId,
diff --git a/frontend/src/pages/integrations/netlify/oauth2/callback.tsx b/frontend/src/pages/integrations/netlify/oauth2/callback.tsx
index a3d680adc5..2c0d8ef1d0 100644
--- a/frontend/src/pages/integrations/netlify/oauth2/callback.tsx
+++ b/frontend/src/pages/integrations/netlify/oauth2/callback.tsx
@@ -25,7 +25,7 @@ export default function NetlifyOAuth2CallbackPage() {
integration: "netlify"
});
- router.push(`/integrations/netlify/create?integrationAuthId=${integrationAuth._id}`);
+ router.push(`/integrations/netlify/create?integrationAuthId=${integrationAuth.id}`);
} catch (err) {
console.error(err);
}
diff --git a/frontend/src/pages/integrations/northflank/authorize.tsx b/frontend/src/pages/integrations/northflank/authorize.tsx
index ad1ba9b1e8..e34ccc0645 100644
--- a/frontend/src/pages/integrations/northflank/authorize.tsx
+++ b/frontend/src/pages/integrations/northflank/authorize.tsx
@@ -33,7 +33,7 @@ export default function NorthflankCreateIntegrationPage() {
setIsLoading(false);
- router.push(`/integrations/northflank/create?integrationAuthId=${integrationAuth._id}`);
+ router.push(`/integrations/northflank/create?integrationAuthId=${integrationAuth.id}`);
} catch (err) {
console.error(err);
}
diff --git a/frontend/src/pages/integrations/northflank/create.tsx b/frontend/src/pages/integrations/northflank/create.tsx
index 055c937e1d..b2dc4ef250 100644
--- a/frontend/src/pages/integrations/northflank/create.tsx
+++ b/frontend/src/pages/integrations/northflank/create.tsx
@@ -78,12 +78,12 @@ export default function NorthflankCreateIntegrationPage() {
const handleButtonClick = async () => {
try {
- if (!integrationAuth?._id) return;
+ if (!integrationAuth?.id) return;
setIsLoading(true);
await mutateAsync({
- integrationAuthId: integrationAuth?._id,
+ integrationAuthId: integrationAuth?.id,
isActive: true,
app: integrationAuthApps?.find((integrationAuthApp) => integrationAuthApp.appId === targetAppId)?.name,
appId: targetAppId,
diff --git a/frontend/src/pages/integrations/qovery/authorize.tsx b/frontend/src/pages/integrations/qovery/authorize.tsx
index a3bab25699..e49e0774ac 100644
--- a/frontend/src/pages/integrations/qovery/authorize.tsx
+++ b/frontend/src/pages/integrations/qovery/authorize.tsx
@@ -38,7 +38,7 @@ export default function QoveryCreateIntegrationPage() {
setIsLoading(false);
- router.push(`/integrations/qovery/create?integrationAuthId=${integrationAuth._id}`);
+ router.push(`/integrations/qovery/create?integrationAuthId=${integrationAuth.id}`);
} catch (err) {
console.error(err);
}
diff --git a/frontend/src/pages/integrations/qovery/create.tsx b/frontend/src/pages/integrations/qovery/create.tsx
index ecf46a31fd..0a7fa8cabb 100644
--- a/frontend/src/pages/integrations/qovery/create.tsx
+++ b/frontend/src/pages/integrations/qovery/create.tsx
@@ -141,7 +141,7 @@ export default function QoveryCreateIntegrationPage() {
const handleButtonClick = async () => {
try {
- if (!integrationAuth?._id) return;
+ if (!integrationAuth?.id) return;
setIsLoading(true);
@@ -151,7 +151,7 @@ export default function QoveryCreateIntegrationPage() {
const targetApp = integrationAuthApps?.find((integrationAuthApp) => integrationAuthApp.appId === targetAppId)?.name;
await mutateAsync({
- integrationAuthId: integrationAuth?._id,
+ integrationAuthId: integrationAuth?.id,
isActive: true,
app: targetApp,
appId: targetAppId,
diff --git a/frontend/src/pages/integrations/railway/authorize.tsx b/frontend/src/pages/integrations/railway/authorize.tsx
index ca356081c5..39549c084a 100644
--- a/frontend/src/pages/integrations/railway/authorize.tsx
+++ b/frontend/src/pages/integrations/railway/authorize.tsx
@@ -33,7 +33,7 @@ export default function RailwayAuthorizeIntegrationPage() {
setIsLoading(false);
- router.push(`/integrations/railway/create?integrationAuthId=${integrationAuth._id}`);
+ router.push(`/integrations/railway/create?integrationAuthId=${integrationAuth.id}`);
} catch (err) {
console.error(err);
}
diff --git a/frontend/src/pages/integrations/railway/create.tsx b/frontend/src/pages/integrations/railway/create.tsx
index 229c633c27..3cc46dc283 100644
--- a/frontend/src/pages/integrations/railway/create.tsx
+++ b/frontend/src/pages/integrations/railway/create.tsx
@@ -90,7 +90,7 @@ export default function RailwayCreateIntegrationPage() {
try {
setIsLoading(true);
- if (!integrationAuth?._id) return;
+ if (!integrationAuth?.id) return;
const targetApp = integrationAuthApps?.find(
(integrationAuthApp) => integrationAuthApp.appId === targetAppId
@@ -106,7 +106,7 @@ export default function RailwayCreateIntegrationPage() {
);
await mutateAsync({
- integrationAuthId: integrationAuth?._id,
+ integrationAuthId: integrationAuth?.id,
isActive: true,
app: targetApp.name,
appId: targetApp.appId,
diff --git a/frontend/src/pages/integrations/render/authorize.tsx b/frontend/src/pages/integrations/render/authorize.tsx
index fb3b659441..2bb7dff7cc 100644
--- a/frontend/src/pages/integrations/render/authorize.tsx
+++ b/frontend/src/pages/integrations/render/authorize.tsx
@@ -36,7 +36,7 @@ export default function RenderCreateIntegrationPage() {
setIsLoading(false);
- router.push(`/integrations/render/create?integrationAuthId=${integrationAuth._id}`);
+ router.push(`/integrations/render/create?integrationAuthId=${integrationAuth.id}`);
} catch (err) {
console.error(err);
}
diff --git a/frontend/src/pages/integrations/render/create.tsx b/frontend/src/pages/integrations/render/create.tsx
index dd58aa32a2..82358544fa 100644
--- a/frontend/src/pages/integrations/render/create.tsx
+++ b/frontend/src/pages/integrations/render/create.tsx
@@ -61,12 +61,12 @@ export default function RenderCreateIntegrationPage() {
const handleButtonClick = async () => {
try {
- if (!integrationAuth?._id) return;
+ if (!integrationAuth?.id) return;
setIsLoading(true);
await mutateAsync({
- integrationAuthId: integrationAuth?._id,
+ integrationAuthId: integrationAuth?.id,
isActive: true,
app: targetApp,
appId: integrationAuthApps?.find((integrationAuthApp) => integrationAuthApp.name === targetApp)?.appId,
diff --git a/frontend/src/pages/integrations/supabase/authorize.tsx b/frontend/src/pages/integrations/supabase/authorize.tsx
index 9e76a3cd3e..5af9b36846 100644
--- a/frontend/src/pages/integrations/supabase/authorize.tsx
+++ b/frontend/src/pages/integrations/supabase/authorize.tsx
@@ -33,7 +33,7 @@ export default function SupabaseCreateIntegrationPage() {
setIsLoading(false);
- router.push(`/integrations/supabase/create?integrationAuthId=${integrationAuth._id}`);
+ router.push(`/integrations/supabase/create?integrationAuthId=${integrationAuth.id}`);
} catch (err) {
console.error(err);
}
diff --git a/frontend/src/pages/integrations/supabase/create.tsx b/frontend/src/pages/integrations/supabase/create.tsx
index a26dfa27fc..e238f47259 100644
--- a/frontend/src/pages/integrations/supabase/create.tsx
+++ b/frontend/src/pages/integrations/supabase/create.tsx
@@ -57,12 +57,12 @@ export default function SupabaseCreateIntegrationPage() {
const handleButtonClick = async () => {
try {
- if (!integrationAuth?._id) return;
+ if (!integrationAuth?.id) return;
setIsLoading(true);
await mutateAsync({
- integrationAuthId: integrationAuth?._id,
+ integrationAuthId: integrationAuth?.id,
isActive: true,
app: targetApp,
appId: integrationAuthApps?.find((integrationAuthApp) => integrationAuthApp.name === targetApp)?.appId,
diff --git a/frontend/src/pages/integrations/teamcity/authorize.tsx b/frontend/src/pages/integrations/teamcity/authorize.tsx
index 60007466cd..6f29641fc0 100644
--- a/frontend/src/pages/integrations/teamcity/authorize.tsx
+++ b/frontend/src/pages/integrations/teamcity/authorize.tsx
@@ -48,7 +48,7 @@ export default function TeamCityCreateIntegrationPage() {
setIsLoading(false);
- router.push(`/integrations/teamcity/create?integrationAuthId=${integrationAuth._id}`);
+ router.push(`/integrations/teamcity/create?integrationAuthId=${integrationAuth.id}`);
} catch (err) {
console.error(err);
}
diff --git a/frontend/src/pages/integrations/teamcity/create.tsx b/frontend/src/pages/integrations/teamcity/create.tsx
index 80cfaba8c9..4dde4a7f15 100644
--- a/frontend/src/pages/integrations/teamcity/create.tsx
+++ b/frontend/src/pages/integrations/teamcity/create.tsx
@@ -68,7 +68,7 @@ export default function TeamCityCreateIntegrationPage() {
const handleButtonClick = async () => {
try {
- if (!integrationAuth?._id) return;
+ if (!integrationAuth?.id) return;
setIsLoading(true);
@@ -77,7 +77,7 @@ export default function TeamCityCreateIntegrationPage() {
);
await mutateAsync({
- integrationAuthId: integrationAuth?._id,
+ integrationAuthId: integrationAuth?.id,
isActive: true,
app: integrationAuthApps?.find((integrationAuthApp) => integrationAuthApp.appId === targetAppId)?.name,
appId: targetAppId,
diff --git a/frontend/src/pages/integrations/terraform-cloud/authorize.tsx b/frontend/src/pages/integrations/terraform-cloud/authorize.tsx
index dc797e409c..d5282ab182 100644
--- a/frontend/src/pages/integrations/terraform-cloud/authorize.tsx
+++ b/frontend/src/pages/integrations/terraform-cloud/authorize.tsx
@@ -43,7 +43,7 @@ export default function TerraformCloudCreateIntegrationPage() {
setIsLoading(false);
- router.push(`/integrations/terraform-cloud/create?integrationAuthId=${integrationAuth._id}`);
+ router.push(`/integrations/terraform-cloud/create?integrationAuthId=${integrationAuth.id}`);
} catch (err) {
console.error(err);
}
diff --git a/frontend/src/pages/integrations/terraform-cloud/create.tsx b/frontend/src/pages/integrations/terraform-cloud/create.tsx
index ac5623c0b2..f86274e57e 100644
--- a/frontend/src/pages/integrations/terraform-cloud/create.tsx
+++ b/frontend/src/pages/integrations/terraform-cloud/create.tsx
@@ -62,7 +62,7 @@ export default function TerraformCloudCreateIntegrationPage() {
const handleButtonClick = async () => {
try {
- if (!integrationAuth?._id) return;
+ if (!integrationAuth?.id) return;
setVariableTypeErrorText("");
if (variableType.length === 0 ) {
@@ -73,7 +73,7 @@ export default function TerraformCloudCreateIntegrationPage() {
setIsLoading(true);
await mutateAsync({
- integrationAuthId: integrationAuth?._id,
+ integrationAuthId: integrationAuth?.id,
isActive: true,
app: targetApp,
appId: integrationAuthApps?.find((integrationAuthApp) => integrationAuthApp.name === targetApp)?.appId,
diff --git a/frontend/src/pages/integrations/travisci/authorize.tsx b/frontend/src/pages/integrations/travisci/authorize.tsx
index 3ed6c2635d..6fddcb5ca6 100644
--- a/frontend/src/pages/integrations/travisci/authorize.tsx
+++ b/frontend/src/pages/integrations/travisci/authorize.tsx
@@ -33,7 +33,7 @@ export default function TravisCICreateIntegrationPage() {
setIsLoading(false);
- router.push(`/integrations/travisci/create?integrationAuthId=${integrationAuth._id}`);
+ router.push(`/integrations/travisci/create?integrationAuthId=${integrationAuth.id}`);
} catch (err) {
console.error(err);
}
diff --git a/frontend/src/pages/integrations/travisci/create.tsx b/frontend/src/pages/integrations/travisci/create.tsx
index 7fcc38c325..83cc242072 100644
--- a/frontend/src/pages/integrations/travisci/create.tsx
+++ b/frontend/src/pages/integrations/travisci/create.tsx
@@ -56,12 +56,12 @@ export default function TravisCICreateIntegrationPage() {
const handleButtonClick = async () => {
try {
- if (!integrationAuth?._id) return;
+ if (!integrationAuth?.id) return;
setIsLoading(true);
await mutateAsync({
- integrationAuthId: integrationAuth?._id,
+ integrationAuthId: integrationAuth?.id,
isActive: true,
app: targetApp,
appId: integrationAuthApps?.find((integrationAuthApp) => integrationAuthApp.name === targetApp)?.appId,
diff --git a/frontend/src/pages/integrations/vercel/create.tsx b/frontend/src/pages/integrations/vercel/create.tsx
index 19c8ba087c..494876a426 100644
--- a/frontend/src/pages/integrations/vercel/create.tsx
+++ b/frontend/src/pages/integrations/vercel/create.tsx
@@ -78,7 +78,7 @@ export default function VercelCreateIntegrationPage() {
const handleButtonClick = async () => {
try {
- if (!integrationAuth?._id) return;
+ if (!integrationAuth?.id) return;
setIsLoading(true);
@@ -91,7 +91,7 @@ export default function VercelCreateIntegrationPage() {
const path = targetEnvironment === "preview" && targetBranch !== "" ? targetBranch : undefined;
await mutateAsync({
- integrationAuthId: integrationAuth?._id,
+ integrationAuthId: integrationAuth?.id,
isActive: true,
app: targetApp.name,
appId: targetApp.appId,
diff --git a/frontend/src/pages/integrations/vercel/oauth2/callback.tsx b/frontend/src/pages/integrations/vercel/oauth2/callback.tsx
index dd884d8b0a..888593c433 100644
--- a/frontend/src/pages/integrations/vercel/oauth2/callback.tsx
+++ b/frontend/src/pages/integrations/vercel/oauth2/callback.tsx
@@ -25,7 +25,7 @@ export default function VercelOAuth2CallbackPage() {
integration: "vercel"
});
- router.push(`/integrations/vercel/create?integrationAuthId=${integrationAuth._id}`);
+ router.push(`/integrations/vercel/create?integrationAuthId=${integrationAuth.id}`);
} catch (err) {
console.error(err);
}
diff --git a/frontend/src/pages/integrations/windmill/authorize.tsx b/frontend/src/pages/integrations/windmill/authorize.tsx
index 94fcd9d4b4..d2e2f92a56 100644
--- a/frontend/src/pages/integrations/windmill/authorize.tsx
+++ b/frontend/src/pages/integrations/windmill/authorize.tsx
@@ -34,7 +34,7 @@ export default function WindmillCreateIntegrationPage() {
setIsLoading(false);
- router.push(`/integrations/windmill/create?integrationAuthId=${integrationAuth._id}`);
+ router.push(`/integrations/windmill/create?integrationAuthId=${integrationAuth.id}`);
} catch (err) {
console.error(err);
}
diff --git a/frontend/src/pages/integrations/windmill/create.tsx b/frontend/src/pages/integrations/windmill/create.tsx
index 5430ad3a49..855f9f959e 100644
--- a/frontend/src/pages/integrations/windmill/create.tsx
+++ b/frontend/src/pages/integrations/windmill/create.tsx
@@ -57,12 +57,12 @@ export default function WindmillCreateIntegrationPage() {
const handleButtonClick = async () => {
try {
- if (!integrationAuth?._id) return;
+ if (!integrationAuth?.id) return;
setIsLoading(true);
await mutateAsync({
- integrationAuthId: integrationAuth?._id,
+ integrationAuthId: integrationAuth?.id,
isActive: true,
app: targetApp,
appId: integrationAuthApps?.find((integrationAuthApp) => integrationAuthApp.name === targetApp)?.appId,
diff --git a/frontend/src/pages/org/[id]/secret-scanning/index.tsx b/frontend/src/pages/org/[id]/secret-scanning/index.tsx
index 5dc5ffe1e6..49cc3bbc11 100644
--- a/frontend/src/pages/org/[id]/secret-scanning/index.tsx
+++ b/frontend/src/pages/org/[id]/secret-scanning/index.tsx
@@ -22,11 +22,11 @@ const SecretScanning = withPermission(
const linkInstallation = async () => {
if (
typeof queryParams.state === "string" &&
- typeof queryParams.installation_id === "string"
+ typeof queryParams.installationid === "string"
) {
try {
const isLinked = await linkGitAppInstallationWithOrganization(
- queryParams.installation_id as string,
+ queryParams.installationid as string,
queryParams.state as string
);
if (isLinked) {
@@ -47,7 +47,7 @@ const SecretScanning = withPermission(
fetchInstallationStatus();
linkInstallation();
- }, [queryParams.state, queryParams.installation_id]);
+ }, [queryParams.state, queryParams.installationid]);
const generateNewIntegrationSession = async () => {
const session = await createNewIntegrationSession(String(localStorage.getItem("orgData.id")));
diff --git a/frontend/src/pages/signup/index.tsx b/frontend/src/pages/signup/index.tsx
index 3dc518ae9a..fd697bab1c 100644
--- a/frontend/src/pages/signup/index.tsx
+++ b/frontend/src/pages/signup/index.tsx
@@ -47,7 +47,7 @@ export default function SignUp() {
const tryAuth = async () => {
try {
const userOrgs = await fetchOrganizations();
- router.push(`/org/${userOrgs[0]._id}/overview`);
+ router.push(`/org/${userOrgs[0].id}/overview`);
} catch (error) {
console.log("Error - Not logged in yet");
}
@@ -90,7 +90,7 @@ export default function SignUp() {
if (!serverDetails?.emailConfigured && step === 5) {
const userOrgs = await fetchOrganizations();
- router.push(`/org/${userOrgs[0]._id}/overview`);
+ router.push(`/org/${userOrgs[0].id}/overview`);
}
})();
}, [step]);
diff --git a/frontend/src/pages/signupinvite.tsx b/frontend/src/pages/signupinvite.tsx
index 0784806c86..6ce4c744f7 100644
--- a/frontend/src/pages/signupinvite.tsx
+++ b/frontend/src/pages/signupinvite.tsx
@@ -54,7 +54,7 @@ export default function SignupInvite() {
const router = useRouter();
const parsedUrl = queryString.parse(router.asPath.split("?")[1]);
const token = parsedUrl.token as string;
- const organizationId = parsedUrl.organization_id as string;
+ const organizationId = parsedUrl.organizationid as string;
const email = (parsedUrl.to as string)?.replace(" ", "+").trim();
// Verifies if the information that the users entered (name, workspace) is there, and if the password matched the criteria.
@@ -161,7 +161,7 @@ export default function SignupInvite() {
const userOrgs = await fetchOrganizations();
- const orgId = userOrgs[0]._id;
+ const orgId = userOrgs[0].id;
localStorage.setItem("orgData.id", orgId);
setStep(3);
diff --git a/frontend/src/views/IntegrationsPage/IntegrationPage.utils.tsx b/frontend/src/views/IntegrationsPage/IntegrationPage.utils.tsx
index bb517950a1..35eadc696a 100644
--- a/frontend/src/views/IntegrationsPage/IntegrationPage.utils.tsx
+++ b/frontend/src/views/IntegrationsPage/IntegrationPage.utils.tsx
@@ -42,7 +42,7 @@ export const redirectForProviderAuth = (integrationOption: TCloudIntegration) =>
link = `${window.location.origin}/integrations/gcp-secret-manager/authorize`;
break;
case "azure-key-vault":
- link = `https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=${integrationOption.clientId}&response_type=code&redirect_uri=${window.location.origin}/integrations/azure-key-vault/oauth2/callback&response_mode=query&scope=https://vault.azure.net/.default openid offline_access&state=${state}`;
+ link = `https://login.microsoftonline.com/common/oauth2/v2.0/authorize?clientid=${integrationOption.clientId}&response_type=code&redirect_uri=${window.location.origin}/integrations/azure-key-vault/oauth2/callback&response_mode=query&scope=https://vault.azure.net/.default openid offline_access&state=${state}`;
break;
case "aws-parameter-store":
link = `${window.location.origin}/integrations/aws-parameter-store/authorize`;
@@ -51,16 +51,16 @@ export const redirectForProviderAuth = (integrationOption: TCloudIntegration) =>
link = `${window.location.origin}/integrations/aws-secret-manager/authorize`;
break;
case "heroku":
- link = `https://id.heroku.com/oauth/authorize?client_id=${integrationOption.clientId}&response_type=code&scope=write-protected&state=${state}`;
+ link = `https://id.heroku.com/oauth/authorize?clientid=${integrationOption.clientId}&response_type=code&scope=write-protected&state=${state}`;
break;
case "vercel":
link = `https://vercel.com/integrations/${integrationOption.clientSlug}/new?state=${state}`;
break;
case "netlify":
- link = `https://app.netlify.com/authorize?client_id=${integrationOption.clientId}&response_type=code&state=${state}&redirect_uri=${window.location.origin}/integrations/netlify/oauth2/callback`;
+ link = `https://app.netlify.com/authorize?clientid=${integrationOption.clientId}&response_type=code&state=${state}&redirect_uri=${window.location.origin}/integrations/netlify/oauth2/callback`;
break;
case "github":
- link = `https://github.com/login/oauth/authorize?client_id=${integrationOption.clientId}&response_type=code&scope=repo&redirect_uri=${window.location.origin}/integrations/github/oauth2/callback&state=${state}`;
+ link = `https://github.com/login/oauth/authorize?clientid=${integrationOption.clientId}&response_type=code&scope=repo&redirect_uri=${window.location.origin}/integrations/github/oauth2/callback&state=${state}`;
break;
case "gitlab":
link = `${window.location.origin}/integrations/gitlab/authorize`;
@@ -105,7 +105,7 @@ export const redirectForProviderAuth = (integrationOption: TCloudIntegration) =>
link = `${window.location.origin}/integrations/cloudflare-workers/authorize`;
break;
case "bitbucket":
- link = `https://bitbucket.org/site/oauth2/authorize?client_id=${integrationOption.clientId}&response_type=code&redirect_uri=${window.location.origin}/integrations/bitbucket/oauth2/callback&state=${state}`;
+ link = `https://bitbucket.org/site/oauth2/authorize?clientid=${integrationOption.clientId}&response_type=code&redirect_uri=${window.location.origin}/integrations/bitbucket/oauth2/callback&state=${state}`;
break;
case "codefresh":
link = `${window.location.origin}/integrations/codefresh/authorize`;
diff --git a/frontend/src/views/IntegrationsPage/IntegrationsPage.tsx b/frontend/src/views/IntegrationsPage/IntegrationsPage.tsx
index f2c5c3ea28..fad848b99e 100644
--- a/frontend/src/views/IntegrationsPage/IntegrationsPage.tsx
+++ b/frontend/src/views/IntegrationsPage/IntegrationsPage.tsx
@@ -21,10 +21,7 @@ import { IntegrationAuth } from "@app/hooks/api/types";
import { CloudIntegrationSection } from "./components/CloudIntegrationSection";
import { FrameworkIntegrationSection } from "./components/FrameworkIntegrationSection";
import { IntegrationsSection } from "./components/IntegrationsSection";
-import {
- generateBotKey,
- redirectForProviderAuth
-} from "./IntegrationPage.utils";
+import { generateBotKey, redirectForProviderAuth } from "./IntegrationPage.utils";
type Props = {
frameworkIntegrations: Array<{ name: string; slug: string; image: string; docsLink: string }>;
@@ -36,7 +33,7 @@ export const IntegrationsPage = withProjectPermission(
const { createNotification } = useNotificationContext();
const { currentWorkspace } = useWorkspace();
- const workspaceId = currentWorkspace?._id || "";
+ const workspaceId = currentWorkspace?.id || "";
const environments = currentWorkspace?.environments || [];
const { data: latestWsKey } = useGetUserWsKey(workspaceId);
@@ -76,7 +73,7 @@ export const IntegrationsPage = withProjectPermission(
const { mutateAsync: updateBotActiveStatus, mutate: updateBotActiveStatusSync } =
useUpdateBotActiveStatus();
const { mutateAsync: deleteIntegration } = useDeleteIntegration();
- const {
+ const {
mutateAsync: deleteIntegrationAuths,
isSuccess: isDeleteIntegrationAuthSuccess,
reset: resetDeleteIntegrationAuths
@@ -95,10 +92,10 @@ export const IntegrationsPage = withProjectPermission(
isIntegrationsAuthorizedEmpty &&
isIntegrationsEmpty
) {
- if (bot?._id)
+ if (bot?.id)
updateBotActiveStatusSync({
isActive: false,
- botId: bot._id,
+ botId: bot.id,
workspaceId
});
resetDeleteIntegrationAuths();
@@ -114,7 +111,7 @@ export const IntegrationsPage = withProjectPermission(
const handleProviderIntegration = async (provider: string) => {
const selectedCloudIntegration = cloudIntegrations?.find(({ slug }) => provider === slug);
if (!selectedCloudIntegration) return;
-
+
try {
if (bot && !bot.isActive) {
const botKey = generateBotKey(bot.publicKey, latestWsKey!);
@@ -122,7 +119,7 @@ export const IntegrationsPage = withProjectPermission(
workspaceId,
botKey,
isActive: true,
- botId: bot._id
+ botId: bot.id
});
}
@@ -194,7 +191,7 @@ export const IntegrationsPage = withProjectPermission(
isLoading={isIntegrationLoading}
integrations={integrations}
environments={environments}
- onIntegrationDelete={({ _id: id }, cb) => handleIntegrationDelete(id, cb)}
+ onIntegrationDelete={({ id }, cb) => handleIntegrationDelete(id, cb)}
isBotActive={bot?.isActive}
workspaceId={workspaceId}
/>
diff --git a/frontend/src/views/IntegrationsPage/components/IntegrationsSection/IntegrationsSection.tsx b/frontend/src/views/IntegrationsPage/components/IntegrationsSection/IntegrationsSection.tsx
index 37fe8c59dc..0d918d3a0f 100644
--- a/frontend/src/views/IntegrationsPage/components/IntegrationsSection/IntegrationsSection.tsx
+++ b/frontend/src/views/IntegrationsPage/components/IntegrationsSection/IntegrationsSection.tsx
@@ -81,7 +81,7 @@ export const IntegrationsSection = ({
{integrations?.map((integration) => (
<div
className="max-w-8xl flex justify-between rounded-md border border-mineshaft-600 bg-mineshaft-800 p-6 pb-2"
- key={`integration-${integration?._id.toString()}`}
+ key={`integration-${integration?.id.toString()}`}
>
<div className="flex">
<div>
diff --git a/frontend/src/views/Login/Login.utils.tsx b/frontend/src/views/Login/Login.utils.tsx
index fd3a2df0bd..1f9b0f4fed 100644
--- a/frontend/src/views/Login/Login.utils.tsx
+++ b/frontend/src/views/Login/Login.utils.tsx
@@ -13,7 +13,7 @@ export const navigateUserToOrg = async (router: NextRouter, organizationId?: str
if (userOrgs.length > 0) {
// user is part of at least 1 org
- const userOrg = userOrgs[0] && userOrgs[0]._id;
+ const userOrg = userOrgs[0] && userOrgs[0].id;
localStorage.setItem("orgData.id", userOrg);
router.push(`/org/${userOrg}/overview`);
} else {
diff --git a/frontend/src/views/Project/IPAllowListPage/components/IPAllowlistModal.tsx b/frontend/src/views/Project/IPAllowListPage/components/IPAllowlistModal.tsx
index d6e746d1a1..35813f492b 100644
--- a/frontend/src/views/Project/IPAllowListPage/components/IPAllowlistModal.tsx
+++ b/frontend/src/views/Project/IPAllowListPage/components/IPAllowlistModal.tsx
@@ -80,11 +80,11 @@ export const IPAllowlistModal = ({
comment
}: FormData) => {
try {
- if (!currentWorkspace?._id) return;
+ if (!currentWorkspace?.id) return;
if (popUp?.trustedIp?.data) {
await updateTrustedIp.mutateAsync({
- workspaceId: currentWorkspace._id,
+ workspaceId: currentWorkspace.id,
trustedIpId: (popUp?.trustedIp?.data as { trustedIpId: string })?.trustedIpId,
ipAddress,
comment,
@@ -92,7 +92,7 @@ export const IPAllowlistModal = ({
});
} else {
await addTrustedIp.mutateAsync({
- workspaceId: currentWorkspace._id,
+ workspaceId: currentWorkspace.id,
ipAddress,
comment,
isActive: true
diff --git a/frontend/src/views/Project/IPAllowListPage/components/IPAllowlistSection.tsx b/frontend/src/views/Project/IPAllowListPage/components/IPAllowlistSection.tsx
index 3fa46051e8..4d98528017 100644
--- a/frontend/src/views/Project/IPAllowListPage/components/IPAllowlistSection.tsx
+++ b/frontend/src/views/Project/IPAllowListPage/components/IPAllowlistSection.tsx
@@ -30,10 +30,10 @@ export const IPAllowlistSection = () => {
const onDeleteTrustedIpSubmit = async (trustedIpId: string) => {
try {
- if (!currentWorkspace?._id) return;
+ if (!currentWorkspace?.id) return;
await mutateAsync({
- workspaceId: currentWorkspace._id,
+ workspaceId: currentWorkspace.id,
trustedIpId
});
diff --git a/frontend/src/views/Project/IPAllowListPage/components/IPAllowlistTable.tsx b/frontend/src/views/Project/IPAllowListPage/components/IPAllowlistTable.tsx
index a9a84a6080..83cd5f9227 100644
--- a/frontend/src/views/Project/IPAllowListPage/components/IPAllowlistTable.tsx
+++ b/frontend/src/views/Project/IPAllowListPage/components/IPAllowlistTable.tsx
@@ -42,7 +42,7 @@ type Props = {
export const IPAllowlistTable = ({ popUp, handlePopUpOpen, handlePopUpToggle }: Props) => {
const { subscription } = useSubscription();
const { currentWorkspace } = useWorkspace();
- const { data, isLoading } = useGetTrustedIps(currentWorkspace?._id ?? "");
+ const { data, isLoading } = useGetTrustedIps(currentWorkspace?.id ?? "");
const formatType = (type: string, prefix?: number) => {
return `${type.slice(0, 2).toUpperCase() + type.slice(2)} ${
@@ -69,9 +69,9 @@ export const IPAllowlistTable = ({ popUp, handlePopUpOpen, handlePopUpToggle }:
data?.length > 0 &&
data
.sort((a, b) => a.ipAddress.localeCompare(b.ipAddress))
- .map(({ _id, ipAddress, comment, type, prefix, isActive }) => {
+ .map(({ id, ipAddress, comment, type, prefix, isActive }) => {
return (
- <Tr key={`ip-access-range-${_id}`} className="h-10">
+ <Tr key={`ip-access-range-${id}`} className="h-10">
<Td>{`${ipAddress}${prefix !== undefined ? `/${prefix}` : ""}`}</Td>
<Td>{formatType(type, prefix)}</Td>
<Td>{comment}</Td>
@@ -95,7 +95,7 @@ export const IPAllowlistTable = ({ popUp, handlePopUpOpen, handlePopUpToggle }:
onClick={() => {
if (subscription?.ipAllowlisting) {
handlePopUpOpen("trustedIp", {
- trustedIpId: _id,
+ trustedIpId: id,
ipAddress,
comment,
prefix,
@@ -123,7 +123,7 @@ export const IPAllowlistTable = ({ popUp, handlePopUpOpen, handlePopUpToggle }:
onClick={() => {
if (subscription?.ipAllowlisting) {
handlePopUpOpen("deleteTrustedIp", {
- trustedIpId: _id
+ trustedIpId: id
});
} else {
handlePopUpOpen("upgradePlan");
diff --git a/frontend/src/views/Project/MembersPage/components/ServiceTokenTab/components/ServiceTokenSection/AddServiceTokenModal.tsx b/frontend/src/views/Project/MembersPage/components/ServiceTokenTab/components/ServiceTokenSection/AddServiceTokenModal.tsx
index 9761c70fca..0659e64f44 100644
--- a/frontend/src/views/Project/MembersPage/components/ServiceTokenTab/components/ServiceTokenSection/AddServiceTokenModal.tsx
+++ b/frontend/src/views/Project/MembersPage/components/ServiceTokenTab/components/ServiceTokenSection/AddServiceTokenModal.tsx
@@ -103,7 +103,7 @@ export const AddServiceTokenModal = ({ popUp, handlePopUpToggle }: Props) => {
const [newToken, setToken] = useState("");
const [isTokenCopied, setIsTokenCopied] = useToggle(false);
- const { data: latestFileKey } = useGetUserWsKey(currentWorkspace?._id ?? "");
+ const { data: latestFileKey } = useGetUserWsKey(currentWorkspace?.id ?? "");
const createServiceToken = useCreateServiceToken();
const hasServiceToken = Boolean(newToken);
@@ -123,7 +123,7 @@ export const AddServiceTokenModal = ({ popUp, handlePopUpToggle }: Props) => {
const onFormSubmit = async ({ name, scopes, expiresIn, permissions }: FormData) => {
try {
- if (!currentWorkspace?._id) return;
+ if (!currentWorkspace?.id) return;
if (!latestFileKey) return;
const key = decryptAssymmetric({
@@ -147,7 +147,7 @@ export const AddServiceTokenModal = ({ popUp, handlePopUpToggle }: Props) => {
scopes,
expiresIn: Number(expiresIn),
name,
- workspaceId: currentWorkspace._id,
+ workspaceId: currentWorkspace.id,
randomBytes,
permissions: Object.entries(permissions)
.filter(([, permissionsValue]) => permissionsValue)
diff --git a/frontend/src/views/Project/MembersPage/components/ServiceTokenTab/components/ServiceTokenSection/ServiceTokenTable.tsx b/frontend/src/views/Project/MembersPage/components/ServiceTokenTab/components/ServiceTokenSection/ServiceTokenTable.tsx
index 6ac54ba97d..51459e7660 100644
--- a/frontend/src/views/Project/MembersPage/components/ServiceTokenTab/components/ServiceTokenSection/ServiceTokenTable.tsx
+++ b/frontend/src/views/Project/MembersPage/components/ServiceTokenTab/components/ServiceTokenSection/ServiceTokenTable.tsx
@@ -34,7 +34,7 @@ type Props = {
export const ServiceTokenTable = ({ handlePopUpOpen }: Props) => {
const { currentWorkspace } = useWorkspace();
const { data, isLoading } = useGetUserWsServiceTokens({
- workspaceID: currentWorkspace?._id || ""
+ workspaceID: currentWorkspace?.id || ""
});
return (
@@ -53,13 +53,13 @@ export const ServiceTokenTable = ({ handlePopUpOpen }: Props) => {
{!isLoading &&
data &&
data.map((row) => (
- <Tr key={row._id}>
+ <Tr key={row.id}>
<Td>{row.name}</Td>
<Td>
<div className="mb-2 flex flex-col flex-wrap space-y-1">
{row?.scopes.map(({ secretPath, environment }) => (
<div
- key={`${row._id}-${environment}-${secretPath}`}
+ key={`${row.id}-${environment}-${secretPath}`}
className="inline-flex items-center space-x-1 rounded-md border border-mineshaft-600 p-1 px-2"
>
<div className="mr-2 border-r border-mineshaft-600 pr-2">{environment}</div>
@@ -80,7 +80,7 @@ export const ServiceTokenTable = ({ handlePopUpOpen }: Props) => {
onClick={() =>
handlePopUpOpen("deleteAPITokenConfirmation", {
name: row.name,
- id: row._id
+ id: row.id
})
}
colorSchema="danger"
diff --git a/frontend/src/views/Project/MembersPage/components/ServiceTokenTab/components/ServiceTokenV3Section/AddServiceTokenV3Modal.tsx b/frontend/src/views/Project/MembersPage/components/ServiceTokenTab/components/ServiceTokenV3Section/AddServiceTokenV3Modal.tsx
new file mode 100644
index 0000000000..faca3ba5d9
--- /dev/null
+++ b/frontend/src/views/Project/MembersPage/components/ServiceTokenTab/components/ServiceTokenV3Section/AddServiceTokenV3Modal.tsx
@@ -0,0 +1,539 @@
+import { useEffect, useState } from "react";
+import { Controller, useFieldArray, useForm } from "react-hook-form";
+import { faCheck, faCopy,faPlus, faXmark } from "@fortawesome/free-solid-svg-icons";
+import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
+import { yupResolver } from "@hookform/resolvers/yup";
+import { motion } from "framer-motion";
+import nacl from "tweetnacl";
+import { encodeBase64 } from "tweetnacl-util";
+import * as yup from "yup";
+
+import { useNotificationContext } from "@app/components/context/Notifications/NotificationProvider";
+import {
+ decryptAssymmetric,
+ encryptAssymmetric
+} from "@app/components/utilities/cryptography/crypto";
+import {
+ Button,
+ FormControl,
+ IconButton,
+ Input,
+ Modal,
+ ModalContent,
+ Select,
+ SelectItem,
+ Switch,
+ Tab,
+ TabList,
+ TabPanel,
+ Tabs,
+ UpgradePlanModal} from "@app/components/v2";
+import {
+ useOrganization,
+ useSubscription,
+ useWorkspace
+} from "@app/context";
+import { useToggle } from "@app/hooks";
+import {
+ useCreateServiceTokenV3,
+ useGetRoles,
+ useGetUserWsKey,
+ useUpdateServiceTokenV3} from "@app/hooks/api";
+import { ServiceTokenV3TrustedIp } from "@app/hooks/api/serviceTokens/types";
+import { UsePopUpState } from "@app/hooks/usePopUp";
+
+enum TabSections {
+ General = "general",
+ Advanced = "advanced"
+}
+
+const expirations = [
+ { label: "Never", value: "" },
+ { label: "1 day", value: "86400" },
+ { label: "7 days", value: "604800" },
+ { label: "1 month", value: "2592000" },
+ { label: "6 months", value: "15552000" },
+ { label: "12 months", value: "31104000" }
+];
+
+const schema = yup.object({
+ name: yup.string().required("ST V3 name is required"),
+ expiresIn: yup.string(),
+ accessTokenTTL: yup
+ .string()
+ .test("is-positive-integer", "Access Token TTL must be a positive integer", (value) => {
+ if (typeof value === "undefined") {
+ return false;
+ }
+
+ const num = parseInt(value, 10);
+ return !Number.isNaN(num) && num > 0 && String(num) === value;
+ })
+ .required("Access Token TTL is required"),
+ role: yup.string().required("ST V3 role is required"),
+ trustedIps: yup
+ .array(
+ yup.object({
+ ipAddress: yup.string().max(50).required().label("IP Address")
+ })
+ )
+ .min(1)
+ .required()
+ .label("Trusted IP"),
+ isRefreshTokenRotationEnabled: yup.boolean().default(false)
+}).required();
+
+export type FormData = yup.InferType<typeof schema>;
+
+type Props = {
+ popUp: UsePopUpState<["serviceTokenV3", "upgradePlan"]>;
+ handlePopUpOpen: (popUpName: keyof UsePopUpState<["upgradePlan"]>) => void;
+ handlePopUpToggle: (popUpName: keyof UsePopUpState<["serviceTokenV3", "upgradePlan"]>, state?: boolean) => void;
+};
+
+export const AddServiceTokenV3Modal = ({
+ popUp,
+ handlePopUpOpen,
+ handlePopUpToggle
+}: Props) => {
+ const [newServiceTokenJSON, setNewServiceTokenJSON] = useState("");
+ const [isServiceTokenJSONCopied, setIsServiceTokenJSONCopied] = useToggle(false);
+
+ const { subscription } = useSubscription();
+ const { currentOrg } = useOrganization();
+ const { currentWorkspace } = useWorkspace();
+
+ const orgId = currentOrg?.id || "";
+ const workspaceId = currentWorkspace?.id || "";
+
+ const { data: roles } = useGetRoles({
+ orgId,
+ workspaceId
+ });
+
+ const { data: latestFileKey } = useGetUserWsKey(workspaceId);
+ const { mutateAsync: createMutateAsync } = useCreateServiceTokenV3();
+ const { mutateAsync: updateMutateAsync } = useUpdateServiceTokenV3();
+ const { createNotification } = useNotificationContext();
+ const {
+ control,
+ handleSubmit,
+ reset,
+ formState: { isSubmitting }
+ } = useForm<FormData>({
+ resolver: yupResolver(schema),
+ defaultValues: {
+ name: "",
+ accessTokenTTL: "7200",
+ trustedIps: [{
+ ipAddress: "0.0.0.0/0"
+ }]
+ }
+ });
+
+ useEffect(() => {
+ let timer: NodeJS.Timeout;
+
+ if (isServiceTokenJSONCopied) {
+ timer = setTimeout(() => setIsServiceTokenJSONCopied.off(), 2000);
+ }
+
+ return () => clearTimeout(timer);
+ }, [setIsServiceTokenJSONCopied]);
+
+ const copyTokenToClipboard = () => {
+ navigator.clipboard.writeText(newServiceTokenJSON);
+ setIsServiceTokenJSONCopied.on();
+ };
+
+ useEffect(() => {
+ const serviceTokenData = popUp?.serviceTokenV3?.data as {
+ serviceTokenDataId: string;
+ name: string;
+ role: string;
+ customRole: {
+ name: string;
+ slug: string;
+ };
+ trustedIps: ServiceTokenV3TrustedIp[];
+ accessTokenTTL: number;
+ isRefreshTokenRotationEnabled: boolean;
+ };
+
+ if (!roles?.length) return;
+
+ if (serviceTokenData) {
+ reset({
+ name: serviceTokenData.name,
+ role: serviceTokenData?.customRole?.slug ?? serviceTokenData.role,
+ trustedIps: serviceTokenData.trustedIps.map(({
+ ipAddress,
+ prefix
+ }: ServiceTokenV3TrustedIp) => {
+ return ({
+ ipAddress: `${ipAddress}${prefix !== undefined ? `/${prefix}` : ""}`
+ });
+ }),
+ accessTokenTTL: String(serviceTokenData.accessTokenTTL),
+ isRefreshTokenRotationEnabled: serviceTokenData.isRefreshTokenRotationEnabled
+ });
+ } else {
+ reset({
+ name: "",
+ accessTokenTTL: "7200",
+ role: roles[0].slug,
+ trustedIps: [{
+ ipAddress: "0.0.0.0/0"
+ }]
+ });
+ }
+ }, [popUp?.serviceTokenV3?.data, roles]);
+
+ const { fields: tokenTrustedIps, append: appendTrustedIp, remove: removeTrustedIp } = useFieldArray({ control, name: "trustedIps" });
+
+ const onFormSubmit = async ({
+ name,
+ expiresIn,
+ accessTokenTTL,
+ role,
+ trustedIps,
+ isRefreshTokenRotationEnabled
+ }: FormData) => {
+ try {
+ const serviceTokenData = popUp?.serviceTokenV3?.data as {
+ serviceTokenDataId: string;
+ name: string;
+ role: string;
+ };
+
+ if (serviceTokenData) {
+ // update
+
+ await updateMutateAsync({
+ serviceTokenDataId: serviceTokenData.serviceTokenDataId,
+ name,
+ role,
+ trustedIps,
+ expiresIn: expiresIn === "" ? undefined : Number(expiresIn),
+ accessTokenTTL: Number(accessTokenTTL),
+ isRefreshTokenRotationEnabled
+ });
+
+ handlePopUpToggle("serviceTokenV3", false);
+ } else {
+ // create
+ if (!workspaceId) return;
+ if (!latestFileKey) return;
+
+ const pair = nacl.box.keyPair();
+ const secretKeyUint8Array = pair.secretKey;
+ const publicKeyUint8Array = pair.publicKey;
+ const privateKey = encodeBase64(secretKeyUint8Array);
+ const publicKey = encodeBase64(publicKeyUint8Array);
+
+ const key = decryptAssymmetric({
+ ciphertext: latestFileKey.encryptedKey,
+ nonce: latestFileKey.nonce,
+ publicKey: latestFileKey.sender.publicKey,
+ privateKey: localStorage.getItem("PRIVATE_KEY") as string
+ });
+
+ const { ciphertext, nonce } = encryptAssymmetric({
+ plaintext: key,
+ publicKey,
+ privateKey: localStorage.getItem("PRIVATE_KEY") as string
+ });
+
+ const { refreshToken } = await createMutateAsync({
+ name,
+ role,
+ workspaceId,
+ publicKey,
+ trustedIps,
+ expiresIn: expiresIn === "" ? undefined : Number(expiresIn),
+ accessTokenTTL: Number(accessTokenTTL),
+ encryptedKey: ciphertext,
+ nonce,
+ isRefreshTokenRotationEnabled
+ });
+
+ const downloadData = {
+ public_key: publicKey,
+ private_key: privateKey,
+ refresh_token: refreshToken
+ };
+
+ const serviceTokenJSON = JSON.stringify(downloadData, null, 2);
+ setNewServiceTokenJSON(serviceTokenJSON);
+
+ const blob = new Blob([serviceTokenJSON], { type: "application/json" });
+ const href = URL.createObjectURL(blob);
+ const link = document.createElement("a");
+ link.href = href;
+ link.download = `infisical_${name}.json`;
+ document.body.appendChild(link);
+ link.click();
+ document.body.removeChild(link);
+ }
+
+ createNotification({
+ text: `Successfully ${popUp?.serviceTokenV3?.data ? "updated" : "created"} ST V3`,
+ type: "success"
+ });
+
+ reset();
+ } catch (err) {
+ console.error(err);
+ createNotification({
+ text: `Failed to ${popUp?.serviceTokenV3?.data ? "updated" : "created"} ST V3`,
+ type: "error"
+ });
+ }
+ }
+
+ const hasServiceTokenJSON = Boolean(newServiceTokenJSON);
+
+ return (
+ <Modal
+ isOpen={popUp?.serviceTokenV3?.isOpen}
+ onOpenChange={(isOpen) => {
+ handlePopUpToggle("serviceTokenV3", isOpen);
+ reset();
+ setNewServiceTokenJSON("");
+ }}
+ >
+ <ModalContent title={`${popUp?.serviceTokenV3?.data ? "Update" : "Create"} Service Token V3`}>
+ {!hasServiceTokenJSON ? (
+ <form onSubmit={handleSubmit(onFormSubmit)}>
+ <Tabs defaultValue={TabSections.General}>
+ <TabList>
+ <div className="flex flex-row border-b border-mineshaft-600 w-full">
+ <Tab value={TabSections.General}>General</Tab>
+ <Tab value={TabSections.Advanced}>Advanced</Tab>
+ </div>
+ </TabList>
+ <TabPanel value={TabSections.General}>
+ <motion.div
+ key="panel-1"
+ transition={{ duration: 0.15 }}
+ initial={{ opacity: 0, translateX: 30 }}
+ animate={{ opacity: 1, translateX: 0 }}
+ exit={{ opacity: 0, translateX: 30 }}
+ >
+ <Controller
+ control={control}
+ defaultValue=""
+ name="name"
+ render={({ field, fieldState: { error } }) => (
+ <FormControl
+ label="Name"
+ isError={Boolean(error)}
+ errorText={error?.message}
+ >
+ <Input
+ {...field}
+ placeholder="My ST V3"
+ />
+ </FormControl>
+ )}
+ />
+ <Controller
+ control={control}
+ name="role"
+ defaultValue=""
+ render={({ field: { onChange, ...field }, fieldState: { error } }) => (
+ <FormControl
+ label={`${popUp?.serviceTokenV3?.data ? "Update" : ""} Role`}
+ errorText={error?.message}
+ isError={Boolean(error)}
+ className="mt-4"
+ >
+ <Select
+ defaultValue={field.value}
+ {...field}
+ onValueChange={(e) => onChange(e)}
+ className="w-full"
+ >
+ {(roles || []).map(({ name, slug }) => (
+ <SelectItem value={slug} key={`st-role-${slug}`}>
+ {name}
+ </SelectItem>
+ ))}
+ </Select>
+ </FormControl>
+ )}
+ />
+ <Controller
+ control={control}
+ name="expiresIn"
+ defaultValue=""
+ render={({ field: { onChange, ...field }, fieldState: { error } }) => (
+ <FormControl
+ label={`${popUp?.serviceTokenV3?.data ? "Update" : ""} Refresh Token Expires In`}
+ errorText={error?.message}
+ isError={Boolean(error)}
+ className="mt-4"
+ >
+ <Select
+ defaultValue={field.value}
+ {...field}
+ onValueChange={(e) => onChange(e)}
+ className="w-full"
+ >
+ {expirations.map(({ label, value }) => (
+ <SelectItem value={String(value || "")} key={`api-key-expiration-${label}`}>
+ {label}
+ </SelectItem>
+ ))}
+ </Select>
+ </FormControl>
+ )}
+ />
+ </motion.div>
+ </TabPanel>
+ <TabPanel value={TabSections.Advanced}>
+ <div>
+ {tokenTrustedIps.map(({ id }, index) => (
+ <div className="flex items-end space-x-2 mb-3" key={id}>
+ <Controller
+ control={control}
+ name={`trustedIps.${index}.ipAddress`}
+ defaultValue="0.0.0.0/0"
+ render={({ field, fieldState: { error } }) => {
+ return (
+ <FormControl
+ className="mb-0 flex-grow"
+ label={index === 0 ? "Trusted IP" : undefined}
+ isError={Boolean(error)}
+ errorText={error?.message}
+ >
+ <Input
+ value={field.value}
+ onChange={(e) => {
+ if (subscription?.ipAllowlisting) {
+ field.onChange(e);
+ return;
+ }
+
+ handlePopUpOpen("upgradePlan");
+ }}
+ placeholder="123.456.789.0"
+ />
+ </FormControl>
+ );
+ }}
+ />
+ <IconButton
+ onClick={() => {
+ if (subscription?.ipAllowlisting) {
+ removeTrustedIp(index);
+ return;
+ }
+
+ handlePopUpOpen("upgradePlan");
+ }}
+ size="lg"
+ colorSchema="danger"
+ variant="plain"
+ ariaLabel="update"
+ className="p-3"
+ >
+ <FontAwesomeIcon icon={faXmark} />
+ </IconButton>
+ </div>
+ ))}
+ <div className="my-4 ml-1">
+ <Button
+ variant="outline_bg"
+ onClick={() => {
+ if (subscription?.ipAllowlisting) {
+ appendTrustedIp({
+ ipAddress: "0.0.0.0/0"
+ })
+ return;
+ }
+
+ handlePopUpOpen("upgradePlan");
+ }}
+ leftIcon={<FontAwesomeIcon icon={faPlus} />}
+ size="xs"
+ >
+ Add IP Address
+ </Button>
+ </div>
+ <Controller
+ control={control}
+ defaultValue="7200"
+ name="accessTokenTTL"
+ render={({ field, fieldState: { error } }) => (
+ <FormControl
+ label="Access Token TTL (seconds)"
+ isError={Boolean(error)}
+ errorText={error?.message}
+ >
+ <Input
+ {...field}
+ placeholder="7200"
+ />
+ </FormControl>
+ )}
+ />
+ <div className="mt-8">
+ <Controller
+ control={control}
+ name="isRefreshTokenRotationEnabled"
+ render={({ field: { onChange, value } }) => (
+ <Switch
+ id="label-refresh-token-rotation"
+ onCheckedChange={(isChecked) => onChange(isChecked)}
+ isChecked={value}
+ >
+ Refresh Token Rotation
+ </Switch>
+ )}
+ />
+ <p className="mt-4 text-sm font-normal text-mineshaft-400">When enabled, as a result of exchanging a refresh token, a new refresh token will be issued and the existing token will be invalidated.</p>
+ </div>
+ </div>
+ </TabPanel>
+ </Tabs>
+ <div className="flex items-center">
+ <Button
+ className="mr-4"
+ size="sm"
+ type="submit"
+ isLoading={isSubmitting}
+ isDisabled={isSubmitting}
+ >
+ {popUp?.serviceTokenV3?.data ? "Update" : "Create"}
+ </Button>
+ <Button colorSchema="secondary" variant="plain">
+ Cancel
+ </Button>
+ </div>
+ </form>
+ ) : (
+ <div className="mt-2 mb-3 mr-2 flex items-center justify-end rounded-md bg-white/[0.07] p-2 text-base text-gray-400">
+ <p className="mr-4 break-all">{newServiceTokenJSON}</p>
+ <IconButton
+ ariaLabel="copy icon"
+ colorSchema="secondary"
+ className="group relative"
+ onClick={copyTokenToClipboard}
+ >
+ <FontAwesomeIcon icon={isServiceTokenJSONCopied ? faCheck : faCopy} />
+ <span className="absolute -left-8 -top-20 hidden w-28 translate-y-full rounded-md bg-bunker-800 py-2 pl-3 text-center text-sm text-gray-400 group-hover:flex group-hover:animate-fadeIn">
+ Click to copy
+ </span>
+ </IconButton>
+ </div>
+ )}
+ <UpgradePlanModal
+ isOpen={popUp?.upgradePlan?.isOpen}
+ onOpenChange={(isOpen) => handlePopUpToggle("upgradePlan", isOpen)}
+ text="You can use IP allowlisting if you switch to Infisical's Pro plan."
+ />
+ </ModalContent>
+ </Modal>
+ );
+}
\ No newline at end of file
diff --git a/frontend/src/views/Project/MembersPage/components/ServiceTokenTab/components/ServiceTokenV3Section/ServiceTokenV3Table.tsx b/frontend/src/views/Project/MembersPage/components/ServiceTokenTab/components/ServiceTokenV3Section/ServiceTokenV3Table.tsx
new file mode 100644
index 0000000000..43fb841e34
--- /dev/null
+++ b/frontend/src/views/Project/MembersPage/components/ServiceTokenTab/components/ServiceTokenV3Section/ServiceTokenV3Table.tsx
@@ -0,0 +1,218 @@
+import { faKey, faPencil,faXmark } from "@fortawesome/free-solid-svg-icons";
+import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
+import { format } from "date-fns";
+
+import { useNotificationContext } from "@app/components/context/Notifications/NotificationProvider";
+import { ProjectPermissionCan } from "@app/components/permissions";
+import {
+ EmptyState,
+ IconButton,
+ Switch,
+ Table,
+ TableContainer,
+ TableSkeleton,
+ TBody,
+ Td,
+ Th,
+ THead,
+ Tr
+} from "@app/components/v2";
+import { ProjectPermissionActions, ProjectPermissionSub , useWorkspace } from "@app/context";
+import {
+ useGetWorkspaceServiceTokenDataV3,
+ useUpdateServiceTokenV3
+} from "@app/hooks/api";
+import { ServiceTokenV3TrustedIp } from "@app/hooks/api/serviceTokens/types"
+import { UsePopUpState } from "@app/hooks/usePopUp";
+
+type Props = {
+ handlePopUpOpen: (
+ popUpName: keyof UsePopUpState<["deleteServiceTokenV3", "serviceTokenV3"]>,
+ data?: {
+ serviceTokenDataId?: string;
+ name?: string;
+ role?: string;
+ customRole?: {
+ name: string;
+ slug: string;
+ };
+ trustedIps?: ServiceTokenV3TrustedIp[];
+ accessTokenTTL?: number;
+ isRefreshTokenRotationEnabled?: boolean;
+ }
+ ) => void;
+ };
+
+export const ServiceTokenV3Table = ({
+ handlePopUpOpen
+}: Props) => {
+ const { createNotification } = useNotificationContext();
+ const { currentWorkspace } = useWorkspace();
+ const { data, isLoading } = useGetWorkspaceServiceTokenDataV3(currentWorkspace?.id || "");
+ const { mutateAsync: updateMutateAsync } = useUpdateServiceTokenV3();
+
+ const handleToggleServiceTokenDataStatus = async ({
+ serviceTokenDataId,
+ isActive
+ }: {
+ serviceTokenDataId: string;
+ isActive: boolean;
+ }) => {
+ try {
+ await updateMutateAsync({
+ serviceTokenDataId,
+ isActive
+ });
+
+ createNotification({
+ text: `Successfully ${isActive ? "enabled" : "disabled"} service token v3`,
+ type: "success"
+ });
+ } catch (err) {
+ console.log(err);
+ createNotification({
+ text: `Failed to ${isActive ? "enable" : "disable"} service token v3`,
+ type: "error"
+ });
+ }
+ }
+
+ return (
+ <TableContainer>
+ <Table>
+ <THead>
+ <Tr>
+ <Th>Name</Th>
+ <Th>Status</Th>
+ <Th>Role</Th>
+ <Th>Trusted IPs</Th>
+ <Th>Access Token TTL</Th>
+ <Th>Created At</Th>
+ <Th>Valid Until</Th>
+ <Th className="w-5" />
+ </Tr>
+ </THead>
+ <TBody>
+ {isLoading && <TableSkeleton columns={7} innerKey="service-tokens" />}
+ {!isLoading &&
+ data &&
+ data.length > 0 &&
+ data.map(({
+ id,
+ name,
+ isActive,
+ role,
+ customRole,
+ trustedIps,
+ createdAt,
+ expiresAt,
+ accessTokenTTL,
+ isRefreshTokenRotationEnabled
+ }) => {
+ return (
+ <Tr className="h-10" key={`st-v3-${id}`}>
+ <Td>{name}</Td>
+ <Td>
+ <ProjectPermissionCan
+ I={ProjectPermissionActions.Edit}
+ a={ProjectPermissionSub.ServiceTokens}
+ >
+ {(isAllowed) => (
+ <Switch
+ id={`enable-service-token-${id}`}
+ onCheckedChange={(value) => handleToggleServiceTokenDataStatus({
+ serviceTokenDataId: id,
+ isActive: value
+ })}
+ isChecked={isActive}
+ isDisabled={!isAllowed}
+ >
+ <p className="w-12 mr-4">{isActive ? "Active" : "Inactive"}</p>
+ </Switch>
+ )}
+ </ProjectPermissionCan>
+ </Td>
+ <Td>{customRole?.slug ?? role}</Td>
+ <Td>
+ {trustedIps.map(({
+ id: trustedIpId,
+ ipAddress,
+ prefix
+ }) => {
+ return (
+ <p key={`service-token-${id}-}-trusted-ip-${trustedIpId}`}>
+ {`${ipAddress}${prefix !== undefined ? `/${prefix}` : ""}`}
+ </p>
+ );
+ })}
+ </Td>
+ <Td>{accessTokenTTL}</Td>
+ <Td>{format(new Date(createdAt), "yyyy-MM-dd")}</Td>
+ <Td>{expiresAt ? format(new Date(expiresAt), "yyyy-MM-dd") : "-"}</Td>
+ <Td className="flex justify-end">
+ <ProjectPermissionCan
+ I={ProjectPermissionActions.Edit}
+ a={ProjectPermissionSub.ServiceTokens}
+ >
+ {(isAllowed) => (
+ <IconButton
+ onClick={async () => {
+ handlePopUpOpen("serviceTokenV3", {
+ serviceTokenDataId: id,
+ name,
+ role,
+ customRole,
+ trustedIps,
+ accessTokenTTL,
+ isRefreshTokenRotationEnabled
+ });
+ }}
+ size="lg"
+ colorSchema="primary"
+ variant="plain"
+ ariaLabel="update"
+ isDisabled={!isAllowed}
+ >
+ <FontAwesomeIcon icon={faPencil} />
+ </IconButton>
+ )}
+ </ProjectPermissionCan>
+ <ProjectPermissionCan
+ I={ProjectPermissionActions.Delete}
+ a={ProjectPermissionSub.ServiceTokens}
+ >
+ {(isAllowed) => (
+ <IconButton
+ onClick={() => {
+ handlePopUpOpen("deleteServiceTokenV3", {
+ serviceTokenDataId: id,
+ name
+ });
+ }}
+ size="lg"
+ colorSchema="danger"
+ variant="plain"
+ ariaLabel="update"
+ className="ml-4"
+ isDisabled={!isAllowed}
+ >
+ <FontAwesomeIcon icon={faXmark} />
+ </IconButton>
+ )}
+ </ProjectPermissionCan>
+ </Td>
+ </Tr>
+ );
+ })}
+ {!isLoading && data && data?.length === 0 && (
+ <Tr>
+ <Td colSpan={7}>
+ <EmptyState title="No service token v3 on file" icon={faKey} />
+ </Td>
+ </Tr>
+ )}
+ </TBody>
+ </Table>
+ </TableContainer>
+ );
+}
\ No newline at end of file
diff --git a/frontend/src/views/SecretApprovalPage/SecretApprovalPage.tsx b/frontend/src/views/SecretApprovalPage/SecretApprovalPage.tsx
index eee81608c7..5a96498971 100644
--- a/frontend/src/views/SecretApprovalPage/SecretApprovalPage.tsx
+++ b/frontend/src/views/SecretApprovalPage/SecretApprovalPage.tsx
@@ -15,7 +15,7 @@ enum TabSection {
export const SecretApprovalPage = () => {
const { currentWorkspace } = useWorkspace();
- const workspaceId = currentWorkspace?._id || "";
+ const workspaceId = currentWorkspace?.id || "";
return (
<div className="container mx-auto bg-bunker-800 text-white w-full h-full max-w-7xl px-6">
diff --git a/frontend/src/views/SecretApprovalPage/components/SecretApprovalPolicyList/SecretApprovalPolicyList.tsx b/frontend/src/views/SecretApprovalPage/components/SecretApprovalPolicyList/SecretApprovalPolicyList.tsx
index 0eb0a849df..2ea6a67f8d 100644
--- a/frontend/src/views/SecretApprovalPage/components/SecretApprovalPolicyList/SecretApprovalPolicyList.tsx
+++ b/frontend/src/views/SecretApprovalPage/components/SecretApprovalPolicyList/SecretApprovalPolicyList.tsx
@@ -59,7 +59,7 @@ export const SecretApprovalPolicyList = ({ workspaceId }: Props) => {
const { mutateAsync: deleteSecretApprovalPolicy } = useDeleteSecretApprovalPolicy();
const handleDeletePolicy = async () => {
- const { _id: id } = popUp.deletePolicy.data as TSecretApprovalPolicy;
+ const { id: id } = popUp.deletePolicy.data as TSecretApprovalPolicy;
try {
await deleteSecretApprovalPolicy({
workspaceId,
@@ -138,7 +138,7 @@ export const SecretApprovalPolicyList = ({ workspaceId }: Props) => {
<SecretApprovalPolicyRow
workspaceId={workspaceId}
policy={policy}
- key={policy._id}
+ key={policy.id}
members={members}
onEdit={() => handlePopUpOpen("secretPolicyForm", policy)}
onDelete={() => handlePopUpOpen("deletePolicy", policy)}
diff --git a/frontend/src/views/SecretApprovalPage/components/SecretApprovalRequest/components/SecretApprovalRequestChangeItem.tsx b/frontend/src/views/SecretApprovalPage/components/SecretApprovalRequest/components/SecretApprovalRequestChangeItem.tsx
index d921f99759..99d06c9c13 100644
--- a/frontend/src/views/SecretApprovalPage/components/SecretApprovalRequest/components/SecretApprovalRequestChangeItem.tsx
+++ b/frontend/src/views/SecretApprovalPage/components/SecretApprovalRequest/components/SecretApprovalRequestChangeItem.tsx
@@ -54,7 +54,7 @@ export const SecretApprovalRequestChangeItem = ({
// meaning request has changed
const isStale = (secretVersion?.version || 1) < presentSecretVersionNumber;
const itemConflict =
- hasMerged && conflicts.find((el) => el.op === op && el.secretId === newVersion?._id);
+ hasMerged && conflicts.find((el) => el.op === op && el.secretId === newVersion?.id);
const hasConflict = Boolean(itemConflict);
return (
@@ -97,10 +97,10 @@ export const SecretApprovalRequestChangeItem = ({
</Td>
<Td>{secretVersion?.comment}</Td>
<Td>
- {secretVersion?.tags?.map(({ name, _id: tagId, tagColor }) => (
+ {secretVersion?.tags?.map(({ name, id: tagId, tagColor }) => (
<Tag
className="flex items-center space-x-2 w-min"
- key={`${secretVersion._id}-${tagId}`}
+ key={`${secretVersion.id}-${tagId}`}
>
<div
className="w-3 h-3 rounded-full"
@@ -119,10 +119,10 @@ export const SecretApprovalRequestChangeItem = ({
</Td>
<Td>{newVersion?.secretComment}</Td>
<Td>
- {newVersion?.tags?.map(({ name, _id: tagId, tagColor }) => (
+ {newVersion?.tags?.map(({ name, id: tagId, tagColor }) => (
<Tag
className="flex items-center space-x-2 w-min"
- key={`${newVersion._id}-${tagId}`}
+ key={`${newVersion.id}-${tagId}`}
>
<div
className="w-3 h-3 rounded-full"
@@ -151,11 +151,11 @@ export const SecretApprovalRequestChangeItem = ({
</Td>
<Td>
{(op === CommitType.CREATE ? newVersion?.tags : secretVersion?.tags)?.map(
- ({ name, _id: tagId, tagColor }) => (
+ ({ name, id: tagId, tagColor }) => (
<Tag
className="flex items-center space-x-2 w-min"
key={`${
- op === CommitType.CREATE ? newVersion?._id : secretVersion?._id
+ op === CommitType.CREATE ? newVersion?.id : secretVersion?.id
}-${tagId}`}
>
<div
diff --git a/frontend/src/views/SecretMainPage/SecretMainPage.tsx b/frontend/src/views/SecretMainPage/SecretMainPage.tsx
index 136b75f6f1..6381fea7cd 100644
--- a/frontend/src/views/SecretMainPage/SecretMainPage.tsx
+++ b/frontend/src/views/SecretMainPage/SecretMainPage.tsx
@@ -63,7 +63,7 @@ export const SecretMainPage = () => {
// env slug
const environment = router.query.env as string;
- const workspaceId = currentWorkspace?._id || "";
+ const workspaceId = currentWorkspace?.id || "";
const secretPath = (router.query.secretPath as string) || "/";
const canReadSecret = permission.can(
ProjectPermissionActions.Read,
diff --git a/frontend/src/views/SecretMainPage/components/ActionBar/ActionBar.tsx b/frontend/src/views/SecretMainPage/components/ActionBar/ActionBar.tsx
index be511486d9..e530ea68fa 100644
--- a/frontend/src/views/SecretMainPage/components/ActionBar/ActionBar.tsx
+++ b/frontend/src/views/SecretMainPage/components/ActionBar/ActionBar.tsx
@@ -163,7 +163,7 @@ export const ActionBar = ({
};
const handleSecretBulkDelete = async () => {
- const bulkDeletedSecrets = secrets.filter(({ _id }) => Boolean(selectedSecrets?.[_id]));
+ const bulkDeletedSecrets = secrets.filter(({ id }) => Boolean(selectedSecrets?.[id]));
try {
await deleteBatchSecretV3({
secretPath,
@@ -233,14 +233,14 @@ export const ActionBar = ({
</DropdownSubMenuTrigger>
<DropdownSubMenuContent className="rounded-l-none">
<DropdownMenuLabel>Apply tags to filter secrets</DropdownMenuLabel>
- {tags.map(({ _id, name, tagColor }) => (
+ {tags.map(({ id, name, tagColor }) => (
<DropdownMenuItem
onClick={(evt) => {
evt.preventDefault();
- onToggleTagFilter(_id);
+ onToggleTagFilter(id);
}}
- key={_id}
- icon={filter?.tags[_id] && <FontAwesomeIcon icon={faCheckCircle} />}
+ key={id}
+ icon={filter?.tags[id] && <FontAwesomeIcon icon={faCheckCircle} />}
iconPos="right"
>
<div className="flex items-center">
diff --git a/frontend/src/views/SecretMainPage/components/PitDrawer/PitDrawer.tsx b/frontend/src/views/SecretMainPage/components/PitDrawer/PitDrawer.tsx
index 73a0028b9a..9b844887a2 100644
--- a/frontend/src/views/SecretMainPage/components/PitDrawer/PitDrawer.tsx
+++ b/frontend/src/views/SecretMainPage/components/PitDrawer/PitDrawer.tsx
@@ -41,26 +41,26 @@ export const PitDrawer = ({
<div className="flex flex-col space-y-2">
{secretSnaphots?.pages?.map((group, i) => (
<Fragment key={`snapshot-item-${i + 1}`}>
- {group.map(({ _id, createdAt }, index) => (
+ {group.map(({ id, createdAt }, index) => (
<Button
- key={_id}
+ key={id}
className="py-3 px-4 text-sm"
isFullWidth
colorSchema={
- (i === 0 && index === 0 && snapshotId === null) || snapshotId === _id
+ (i === 0 && index === 0 && snapshotId === null) || snapshotId === id
? "primary"
: "secondary"
}
variant={
- (i === 0 && index === 0 && snapshotId === null) || snapshotId === _id
+ (i === 0 && index === 0 && snapshotId === null) || snapshotId === id
? "selected"
: "star"
}
- onClick={() => onSelectSnapshot(_id)}
+ onClick={() => onSelectSnapshot(id)}
>
<div className="flex w-full justify-between">
<div>{timeSince(new Date(createdAt))}</div>
- <div>{getButtonLabel(i === 0 && index === 0, snapshotId === _id)}</div>
+ <div>{getButtonLabel(i === 0 && index === 0, snapshotId === id)}</div>
</div>
</Button>
))}
diff --git a/frontend/src/views/SecretMainPage/components/SecretDropzone/CopySecretsFromBoard.tsx b/frontend/src/views/SecretMainPage/components/SecretDropzone/CopySecretsFromBoard.tsx
index 12eaf840c1..9606f8141c 100644
--- a/frontend/src/views/SecretMainPage/components/SecretDropzone/CopySecretsFromBoard.tsx
+++ b/frontend/src/views/SecretMainPage/components/SecretDropzone/CopySecretsFromBoard.tsx
@@ -240,14 +240,14 @@ export const CopySecretsFromBoard = ({
{secrets
?.filter(({ key }) => key.toLowerCase().includes(searchFilter.toLowerCase()))
- ?.map(({ _id, key, value: secVal }) => (
+ ?.map(({ id, key, value: secVal }) => (
<Controller
- key={`pull-secret--${_id}`}
+ key={`pull-secret--${id}`}
control={control}
name={`secrets.${key}`}
render={({ field: { value, onChange } }) => (
<Checkbox
- id={`pull-secret-${_id}`}
+ id={`pull-secret-${id}`}
isChecked={Boolean(value)}
onCheckedChange={(isChecked) => onChange(isChecked ? secVal : "")}
>
diff --git a/frontend/src/views/SecretMainPage/components/SecretImportListView/SecretImportListView.tsx b/frontend/src/views/SecretMainPage/components/SecretImportListView/SecretImportListView.tsx
index 3b8f912350..6b216b8f87 100644
--- a/frontend/src/views/SecretMainPage/components/SecretImportListView/SecretImportListView.tsx
+++ b/frontend/src/views/SecretMainPage/components/SecretImportListView/SecretImportListView.tsx
@@ -132,12 +132,12 @@ export const SecretImportListView = ({
const { environment: importEnv, secretPath: impSecPath } = popUp.deleteSecretImport
?.data as TDeleteSecretImport;
try {
- if (secretImports?._id) {
+ if (secretImports?.id) {
await deleteSecretImport({
workspaceId,
environment,
directory: secretPath,
- id: secretImports?._id,
+ id: secretImports?.id,
secretImportEnv: importEnv,
secretImportPath: impSecPath
});
@@ -166,7 +166,7 @@ export const SecretImportListView = ({
workspaceId,
environment,
directory: secretPath,
- id: secretImports?._id || "",
+ id: secretImports?.id || "",
secretImports: newImportOrder
});
}
diff --git a/frontend/src/views/SecretMainPage/components/SecretListView/SecretDetaiSidebar.tsx b/frontend/src/views/SecretMainPage/components/SecretListView/SecretDetaiSidebar.tsx
index 0a9f38bc47..1c8063f430 100644
--- a/frontend/src/views/SecretMainPage/components/SecretListView/SecretDetaiSidebar.tsx
+++ b/frontend/src/views/SecretMainPage/components/SecretListView/SecretDetaiSidebar.tsx
@@ -49,7 +49,7 @@ type Props = {
onDeleteSecret: () => void;
onSaveSecret: (
orgSec: DecryptedSecret,
- modSec: Omit<DecryptedSecret, "tags"> & { tags: { _id: string }[] },
+ modSec: Omit<DecryptedSecret, "tags"> & { tags: { id: string }[] },
cb?: () => void
) => Promise<void>;
tags: WsTag[];
@@ -98,7 +98,7 @@ export const SecretDetailSidebar = ({
});
const selectedTags = watch("tags", []);
const selectedTagsGroupById = selectedTags.reduce<Record<string, boolean>>(
- (prev, curr) => ({ ...prev, [curr._id]: true }),
+ (prev, curr) => ({ ...prev, [curr.id]: true }),
{}
);
@@ -109,7 +109,7 @@ export const SecretDetailSidebar = ({
const { data: secretVersion } = useGetSecretVersion({
limit: 10,
offset: 0,
- secretId: secret?._id,
+ secretId: secret?.id,
decryptFileKey
});
@@ -133,8 +133,8 @@ export const SecretDetailSidebar = ({
};
const handleTagSelect = (tag: WsTag) => {
- if (selectedTagsGroupById?.[tag._id]) {
- const tagPos = selectedTags.findIndex(({ _id }) => _id === tag._id);
+ if (selectedTagsGroupById?.[tag.id]) {
+ const tagPos = selectedTags.findIndex(({ id }) => id === tag.id);
if (tagPos !== -1) {
remove(tagPos);
}
@@ -227,7 +227,7 @@ export const SecretDetailSidebar = ({
)}
<FormControl label="Tags" className="">
<div className="overflow-hidden grid gap-2 grid-flow-col auto-cols-min pt-2">
- {fields.map(({ tagColor, id: formId, name, _id }) => (
+ {fields.map(({ tagColor, id: formId, name, id }) => (
<Tag
className="flex items-center space-x-2 w-min"
key={formId}
@@ -236,7 +236,7 @@ export const SecretDetailSidebar = ({
createNotification({ type: "error", text: "Access denied" });
return;
}
- const tag = tags?.find(({ _id: id }) => id === _id);
+ const tag = tags?.find(({ id: id }) => id === id);
if (tag) handleTagSelect(tag);
}}
>
@@ -269,7 +269,7 @@ export const SecretDetailSidebar = ({
<DropdownMenuContent align="end" className="z-[100]">
<DropdownMenuLabel>Apply tags to this secrets</DropdownMenuLabel>
{tags.map((tag) => {
- const { _id: tagId, name, tagColor } = tag;
+ const { id: tagId, name, tagColor } = tag;
const isSelected = selectedTagsGroupById?.[tagId];
return (
diff --git a/frontend/src/views/SecretMainPage/components/SecretListView/SecretItem.tsx b/frontend/src/views/SecretMainPage/components/SecretListView/SecretItem.tsx
index 9fdd1e3f8e..1050923b33 100644
--- a/frontend/src/views/SecretMainPage/components/SecretListView/SecretItem.tsx
+++ b/frontend/src/views/SecretMainPage/components/SecretListView/SecretItem.tsx
@@ -56,7 +56,7 @@ type Props = {
secret: DecryptedSecret;
onSaveSecret: (
orgSec: DecryptedSecret,
- modSec: Omit<DecryptedSecret, "tags"> & { tags: { _id: string }[] },
+ modSec: Omit<DecryptedSecret, "tags"> & { tags: { id: string }[] },
cb?: () => void
) => Promise<void>;
onDeleteSecret: (sec: DecryptedSecret) => void;
@@ -117,7 +117,7 @@ export const SecretItem = memo(
const selectedTags = watch("tags", []);
const selectedTagsGroupById = selectedTags.reduce<Record<string, boolean>>(
- (prev, curr) => ({ ...prev, [curr._id]: true }),
+ (prev, curr) => ({ ...prev, [curr.id]: true }),
{}
);
const { fields, append, remove } = useFieldArray({
@@ -168,8 +168,8 @@ export const SecretItem = memo(
};
const handleTagSelect = (tag: WsTag) => {
- if (selectedTagsGroupById?.[tag._id]) {
- const tagPos = selectedTags.findIndex(({ _id }) => _id === tag._id);
+ if (selectedTagsGroupById?.[tag.id]) {
+ const tagPos = selectedTags.findIndex(({ id }) => id === tag.id);
if (tagPos !== -1) {
remove(tagPos);
}
@@ -217,9 +217,9 @@ export const SecretItem = memo(
)}
>
<Checkbox
- id={`checkbox-${secret._id}`}
+ id={`checkbox-${secret.id}`}
isChecked={isSelected}
- onCheckedChange={() => onToggleSecretSelect(secret._id)}
+ onCheckedChange={() => onToggleSecretSelect(secret.id)}
className={twMerge("ml-3 hidden group-hover:flex", isSelected && "flex")}
/>
<FontAwesomeIcon
@@ -319,7 +319,7 @@ export const SecretItem = memo(
<DropdownMenuContent align="end">
<DropdownMenuLabel>Apply tags to this secrets</DropdownMenuLabel>
{tags.map((tag) => {
- const { _id: tagId, name, tagColor } = tag;
+ const { id: tagId, name, tagColor } = tag;
const isTagSelected = selectedTagsGroupById?.[tagId];
return (
diff --git a/frontend/src/views/SecretMainPage/components/SecretListView/SecretListView.utils.ts b/frontend/src/views/SecretMainPage/components/SecretListView/SecretListView.utils.ts
index 6dcf6110a9..fc8a745d5c 100644
--- a/frontend/src/views/SecretMainPage/components/SecretListView/SecretListView.utils.ts
+++ b/frontend/src/views/SecretMainPage/components/SecretListView/SecretListView.utils.ts
@@ -31,7 +31,7 @@ export const formSchema = z.object({
tags: z
.object({
- _id: z.string(),
+ id: z.string(),
name: z.string(),
slug: z.string(),
tagColor: z.string().optional()
diff --git a/frontend/src/views/SecretMainPage/components/SnapshotView/SecretItem.tsx b/frontend/src/views/SecretMainPage/components/SnapshotView/SecretItem.tsx
index 8b661415ef..2b0110ee77 100644
--- a/frontend/src/views/SecretMainPage/components/SnapshotView/SecretItem.tsx
+++ b/frontend/src/views/SecretMainPage/components/SnapshotView/SecretItem.tsx
@@ -151,10 +151,10 @@ export const SecretItem = ({ mode, preSecret, postSecret }: Props) => {
<Td className="border-r border-mineshaft-600">Tags</Td>
{isModified && (
<Td className="border-r border-mineshaft-600">
- {preSecret?.tags?.map(({ name, _id: tagId, tagColor }) => (
+ {preSecret?.tags?.map(({ name, id: tagId, tagColor }) => (
<Tag
className="flex items-center space-x-2 w-min"
- key={`${preSecret._id}-${tagId}`}
+ key={`${preSecret.id}-${tagId}`}
>
<div
className="w-3 h-3 rounded-full"
@@ -166,10 +166,10 @@ export const SecretItem = ({ mode, preSecret, postSecret }: Props) => {
</Td>
)}
<Td>
- {postSecret?.tags?.map(({ name, _id: tagId, tagColor }) => (
+ {postSecret?.tags?.map(({ name, id: tagId, tagColor }) => (
<Tag
className="flex items-center space-x-2 w-min"
- key={`${postSecret._id}-${tagId}`}
+ key={`${postSecret.id}-${tagId}`}
>
<div
className="w-3 h-3 rounded-full"
diff --git a/frontend/src/views/SecretMainPage/components/SnapshotView/SnapshotView.tsx b/frontend/src/views/SecretMainPage/components/SnapshotView/SnapshotView.tsx
index bf6523b4e4..9c2ea32d16 100644
--- a/frontend/src/views/SecretMainPage/components/SnapshotView/SnapshotView.tsx
+++ b/frontend/src/views/SecretMainPage/components/SnapshotView/SnapshotView.tsx
@@ -93,12 +93,12 @@ export const SnapshotView = ({
const secretDiffView = useMemo(() => {
const secretGroupById = secrets.reduce<Record<string, DecryptedSecret>>(
- (prev, curr) => ({ ...prev, [curr._id]: curr }),
+ (prev, curr) => ({ ...prev, [curr.id]: curr }),
{}
);
const diffView: Array<TDiffView<DecryptedSecret>> = [];
rollingSecrets.forEach((rollSecret) => {
- const { _id: id } = rollSecret;
+ const { id: id } = rollSecret;
const doesExist = Boolean(secretGroupById?.[id]);
if (doesExist) {
diffView.push({
diff --git a/frontend/src/views/SecretOverviewPage/SecretOverviewPage.tsx b/frontend/src/views/SecretOverviewPage/SecretOverviewPage.tsx
index f63350ca71..99c1678903 100644
--- a/frontend/src/views/SecretOverviewPage/SecretOverviewPage.tsx
+++ b/frontend/src/views/SecretOverviewPage/SecretOverviewPage.tsx
@@ -74,14 +74,14 @@ export const SecretOverviewPage = () => {
const { currentWorkspace, isLoading: isWorkspaceLoading } = useWorkspace();
const { currentOrg } = useOrganization();
- const workspaceId = currentWorkspace?._id as string;
+ const workspaceId = currentWorkspace?.id as string;
const { data: latestFileKey } = useGetUserWsKey(workspaceId);
const [searchFilter, setSearchFilter] = useState("");
const secretPath = (router.query?.secretPath as string) || "/";
useEffect(() => {
if (!isWorkspaceLoading && !workspaceId && router.isReady) {
- router.push(`/org/${currentOrg?._id}/overview`);
+ router.push(`/org/${currentOrg?.id}/overview`);
}
}, [isWorkspaceLoading, workspaceId, router.isReady]);
diff --git a/frontend/src/views/SecretOverviewPage/components/ProjectIndexSecretsSection/ProjectIndexSecretsSection.tsx b/frontend/src/views/SecretOverviewPage/components/ProjectIndexSecretsSection/ProjectIndexSecretsSection.tsx
index af2edb0ceb..bdb63e0211 100644
--- a/frontend/src/views/SecretOverviewPage/components/ProjectIndexSecretsSection/ProjectIndexSecretsSection.tsx
+++ b/frontend/src/views/SecretOverviewPage/components/ProjectIndexSecretsSection/ProjectIndexSecretsSection.tsx
@@ -19,16 +19,16 @@ type Props = {
export const ProjectIndexSecretsSection = ({ decryptFileKey }: Props) => {
const { currentWorkspace } = useWorkspace();
const { data: isBlindIndexed, isLoading: isBlindIndexedLoading } = useGetWorkspaceIndexStatus(
- currentWorkspace?._id ?? ""
+ currentWorkspace?.id ?? ""
);
const [isIndexing, setIsIndexing] = useToggle();
const nameWorkspaceSecrets = useNameWorkspaceSecrets();
const onEnableBlindIndices = async () => {
- if (!currentWorkspace?._id) return;
+ if (!currentWorkspace?.id) return;
setIsIndexing.on();
try {
- const encryptedSecrets = await fetchWorkspaceSecrets(currentWorkspace._id);
+ const encryptedSecrets = await fetchWorkspaceSecrets(currentWorkspace.id);
const key = decryptAssymmetric({
ciphertext: decryptFileKey.encryptedKey,
@@ -47,11 +47,11 @@ export const ProjectIndexSecretsSection = ({ decryptFileKey }: Props) => {
return {
secretName,
- _id: encryptedSecret._id
+ id: encryptedSecret.id
};
});
await nameWorkspaceSecrets.mutateAsync({
- workspaceId: currentWorkspace._id,
+ workspaceId: currentWorkspace.id,
secretsToUpdate
});
} catch (err) {
diff --git a/frontend/src/views/SecretOverviewPage/components/SecretOverviewTableRow/SecretOverviewTableRow.tsx b/frontend/src/views/SecretOverviewPage/components/SecretOverviewTableRow/SecretOverviewTableRow.tsx
index 8671d2da94..08774535b5 100644
--- a/frontend/src/views/SecretOverviewPage/components/SecretOverviewTableRow/SecretOverviewTableRow.tsx
+++ b/frontend/src/views/SecretOverviewPage/components/SecretOverviewTableRow/SecretOverviewTableRow.tsx
@@ -149,7 +149,7 @@ export const SecretOverviewTableRow = ({
isVisible={isSecretVisible}
secretName={secretKey}
defaultValue={secret?.value}
- secretId={secret?._id}
+ secretId={secret?.id}
isCreatable={isCreatable}
onSecretDelete={onSecretDelete}
onSecretCreate={onSecretCreate}
diff --git a/frontend/src/views/SecretRotationPage/SecretRotationPage.tsx b/frontend/src/views/SecretRotationPage/SecretRotationPage.tsx
index 3a502a35d0..cdce4f0b12 100644
--- a/frontend/src/views/SecretRotationPage/SecretRotationPage.tsx
+++ b/frontend/src/views/SecretRotationPage/SecretRotationPage.tsx
@@ -70,7 +70,7 @@ export const SecretRotationPage = withProjectPermission(
"deleteRotation",
"upgradePlan"
] as const);
- const workspaceId = currentWorkspace?._id || "";
+ const workspaceId = currentWorkspace?.id || "";
const canCreateRotation = permission.can(
ProjectPermissionActions.Create,
ProjectPermissionSub.SecretRotation
@@ -145,11 +145,11 @@ export const SecretRotationPage = withProjectPermission(
const handleUserAcceptBotCondition = async () => {
const provider = popUp.activeBot?.data as TSecretRotationProvider;
try {
- if (bot?._id) {
+ if (bot?.id) {
const botKey = generateBotKey(bot.publicKey, userWsKey!);
await updateBotActiveStatus({
isActive: true,
- botId: bot._id,
+ botId: bot.id,
workspaceId,
botKey
});
@@ -232,16 +232,16 @@ export const SecretRotationPage = withProjectPermission(
secretPath,
outputs,
provider,
- _id,
+ id,
lastRotatedAt,
status,
statusMessage
}) => {
- const isDeleting = deleteSecretRotationVars?.id === _id && isDeletingRotation;
+ const isDeleting = deleteSecretRotationVars?.id === id && isDeletingRotation;
const isRestarting =
- restartSecretRotationVar?.id === _id && isRestartingRotation;
+ restartSecretRotationVar?.id === id && isRestartingRotation;
return (
- <Tr key={_id}>
+ <Tr key={id}>
<Td>
{outputs
.map(({ key }) => key)
@@ -291,7 +291,7 @@ export const SecretRotationPage = withProjectPermission(
colorSchema="danger"
ariaLabel="delete-rotation"
isDisabled={isDeleting || !isAllowed}
- onClick={() => handleRestartRotation(_id)}
+ onClick={() => handleRestartRotation(id)}
>
{isRestarting ? (
<Spinner size="xs" />
@@ -313,7 +313,7 @@ export const SecretRotationPage = withProjectPermission(
colorSchema="danger"
ariaLabel="delete-rotation"
isDisabled={isDeleting || !isAllowed}
- onClick={() => handlePopUpOpen("deleteRotation", { id: _id })}
+ onClick={() => handlePopUpOpen("deleteRotation", { id: id })}
>
{isDeleting ? (
<Spinner size="xs" />
diff --git a/frontend/src/views/SecretRotationPage/components/CreateRotationForm/steps/RotationOutputForm.tsx b/frontend/src/views/SecretRotationPage/components/CreateRotationForm/steps/RotationOutputForm.tsx
index e11038f7c8..e41bac258f 100644
--- a/frontend/src/views/SecretRotationPage/components/CreateRotationForm/steps/RotationOutputForm.tsx
+++ b/frontend/src/views/SecretRotationPage/components/CreateRotationForm/steps/RotationOutputForm.tsx
@@ -23,7 +23,7 @@ type Props = {
export const RotationOutputForm = ({ onSubmit, onCancel, outputSchema = {} }: Props) => {
const { currentWorkspace } = useWorkspace();
const environments = currentWorkspace?.environments || [];
- const workspaceId = currentWorkspace?._id || "";
+ const workspaceId = currentWorkspace?.id || "";
const {
control,
handleSubmit,
@@ -117,11 +117,11 @@ export const RotationOutputForm = ({ onSubmit, onCancel, outputSchema = {} }: Pr
{!isSecretsLoading &&
secrets
?.filter(
- ({ _id }) =>
- value === _id || !Object.values(selectedSecrets || {}).includes(_id)
+ ({ id }) =>
+ value === id || !Object.values(selectedSecrets || {}).includes(id)
)
- ?.map(({ key, _id }) => (
- <SelectItem value={_id} key={_id}>
+ ?.map(({ key, id }) => (
+ <SelectItem value={id} key={id}>
{key}
</SelectItem>
))}
diff --git a/frontend/src/views/SecretScanning/components/SecretScanningLogsTable.tsx b/frontend/src/views/SecretScanning/components/SecretScanningLogsTable.tsx
index 4add118352..ad60f9a7f9 100644
--- a/frontend/src/views/SecretScanning/components/SecretScanningLogsTable.tsx
+++ b/frontend/src/views/SecretScanning/components/SecretScanningLogsTable.tsx
@@ -83,7 +83,7 @@ export const SecretScanningLogsTable = () => {
</Td>
<Td>{risk.isResolved ? "Resolved" : "Needs Attention"}</Td>
<Td>
- <RiskStatusSelection riskId={risk._id} currentSelection={risk.status} />
+ <RiskStatusSelection riskId={risk.id} currentSelection={risk.status} />
</Td>
</Tr>
);
diff --git a/frontend/src/views/Settings/BillingSettingsPage/components/BillingCloudTab/CurrentPlanSection.tsx b/frontend/src/views/Settings/BillingSettingsPage/components/BillingCloudTab/CurrentPlanSection.tsx
index 75fdf2f992..a3135d85f0 100644
--- a/frontend/src/views/Settings/BillingSettingsPage/components/BillingCloudTab/CurrentPlanSection.tsx
+++ b/frontend/src/views/Settings/BillingSettingsPage/components/BillingCloudTab/CurrentPlanSection.tsx
@@ -17,7 +17,7 @@ import { useGetOrgPlanTable } from "@app/hooks/api";
export const CurrentPlanSection = () => {
const { currentOrg } = useOrganization();
- const { data, isLoading } = useGetOrgPlanTable(currentOrg?._id ?? "");
+ const { data, isLoading } = useGetOrgPlanTable(currentOrg?.id ?? "");
const displayCell = (value: null | number | string | boolean) => {
if (value === null) return "-";
diff --git a/frontend/src/views/Settings/BillingSettingsPage/components/BillingCloudTab/ManagePlansTable.tsx b/frontend/src/views/Settings/BillingSettingsPage/components/BillingCloudTab/ManagePlansTable.tsx
index f057f7ff0b..2aa552f520 100644
--- a/frontend/src/views/Settings/BillingSettingsPage/components/BillingCloudTab/ManagePlansTable.tsx
+++ b/frontend/src/views/Settings/BillingSettingsPage/components/BillingCloudTab/ManagePlansTable.tsx
@@ -24,7 +24,7 @@ export const ManagePlansTable = ({ billingCycle }: Props) => {
const { currentOrg } = useOrganization();
const { subscription } = useSubscription();
const { data: tableData, isLoading: isTableDataLoading } = useGetOrgPlansTable({
- organizationId: currentOrg?._id ?? "",
+ organizationId: currentOrg?.id ?? "",
billingCycle
});
const createCustomerPortalSession = useCreateCustomerPortalSession();
@@ -110,11 +110,11 @@ export const ManagePlansTable = ({ billingCycle }: Props) => {
<Td>
<Button
onClick={async () => {
- if (!currentOrg?._id) return;
+ if (!currentOrg?.id) return;
if (tier !== 3) {
const { url } = await createCustomerPortalSession.mutateAsync(
- currentOrg._id
+ currentOrg.id
);
window.location.href = url;
return;
diff --git a/frontend/src/views/Settings/BillingSettingsPage/components/BillingCloudTab/PreviewSection.tsx b/frontend/src/views/Settings/BillingSettingsPage/components/BillingCloudTab/PreviewSection.tsx
index 579730ec30..e833692631 100644
--- a/frontend/src/views/Settings/BillingSettingsPage/components/BillingCloudTab/PreviewSection.tsx
+++ b/frontend/src/views/Settings/BillingSettingsPage/components/BillingCloudTab/PreviewSection.tsx
@@ -22,7 +22,7 @@ import { ManagePlansModal } from "./ManagePlansModal";
export const PreviewSection = () => {
const { currentOrg } = useOrganization();
const { subscription } = useSubscription();
- const { data, isLoading } = useGetOrgPlanBillingInfo(currentOrg?._id ?? "");
+ const { data, isLoading } = useGetOrgPlanBillingInfo(currentOrg?.id ?? "");
const getOrgTrialUrl = useGetOrgTrialUrl();
const createCustomerPortalSession = useCreateCustomerPortalSession();
@@ -58,7 +58,7 @@ export const PreviewSection = () => {
if (!subscription.has_used_trial) {
// direct user to start pro trial
const url = await getOrgTrialUrl.mutateAsync({
- orgId: currentOrg._id,
+ orgId: currentOrg.id,
success_url: window.location.href
});
@@ -124,8 +124,8 @@ export const PreviewSection = () => {
<button
type="button"
onClick={async () => {
- if (!currentOrg?._id) return;
- const { url } = await createCustomerPortalSession.mutateAsync(currentOrg._id);
+ if (!currentOrg?.id) return;
+ const { url } = await createCustomerPortalSession.mutateAsync(currentOrg.id);
window.location.href = url;
}}
disabled={!isAllowed}
diff --git a/frontend/src/views/Settings/BillingSettingsPage/components/BillingSelfHostedTab/LicensesSection.tsx b/frontend/src/views/Settings/BillingSettingsPage/components/BillingSelfHostedTab/LicensesSection.tsx
index 1603d4486b..706975dd40 100644
--- a/frontend/src/views/Settings/BillingSettingsPage/components/BillingSelfHostedTab/LicensesSection.tsx
+++ b/frontend/src/views/Settings/BillingSettingsPage/components/BillingSelfHostedTab/LicensesSection.tsx
@@ -18,7 +18,7 @@ import {
export const LicensesSection = () => {
const { currentOrg } = useOrganization();
- const { data, isLoading } = useGetOrgLicenses(currentOrg?._id ?? "");
+ const { data, isLoading } = useGetOrgLicenses(currentOrg?.id ?? "");
return (
<div className="mb-6 rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4">
@@ -35,7 +35,7 @@ export const LicensesSection = () => {
</THead>
<TBody>
{!isLoading && data && data?.length > 0 && data.map(({
- _id,
+ id,
licenseKey,
isActivated,
createdAt,
@@ -44,7 +44,7 @@ export const LicensesSection = () => {
const formattedCreatedAt = new Date(createdAt).toISOString().split("T")[0];
const formattedExpiresAt = new Date(expiresAt).toISOString().split("T")[0];
return (
- <Tr key={`license-${_id}`} className="h-10">
+ <Tr key={`license-${id}`} className="h-10">
<Td>{licenseKey}</Td>
<Td>{isActivated ? "Active" : "Inactive"}</Td>
<Td>{formattedCreatedAt}</Td>
diff --git a/frontend/src/views/Settings/OrgSettingsPage/components/OrgAuthTab/OrgSSOSection.tsx b/frontend/src/views/Settings/OrgSettingsPage/components/OrgAuthTab/OrgSSOSection.tsx
index cfa773f25a..784788ae33 100644
--- a/frontend/src/views/Settings/OrgSettingsPage/components/OrgAuthTab/OrgSSOSection.tsx
+++ b/frontend/src/views/Settings/OrgSettingsPage/components/OrgAuthTab/OrgSSOSection.tsx
@@ -25,7 +25,7 @@ export const OrgSSOSection = (): JSX.Element => {
const { currentOrg } = useOrganization();
const { subscription } = useSubscription();
const { createNotification } = useNotificationContext();
- const { data, isLoading } = useGetSSOConfig(currentOrg?._id ?? "");
+ const { data, isLoading } = useGetSSOConfig(currentOrg?.id ?? "");
const { mutateAsync } = useUpdateSSOConfig();
const { popUp, handlePopUpOpen, handlePopUpClose, handlePopUpToggle } = usePopUp([
"upgradePlan",
@@ -36,10 +36,10 @@ export const OrgSSOSection = (): JSX.Element => {
const handleSamlSSOToggle = async (value: boolean) => {
try {
- if (!currentOrg?._id) return;
+ if (!currentOrg?.id) return;
await mutateAsync({
- organizationId: currentOrg?._id,
+ organizationId: currentOrg?.id,
isActive: value
});
@@ -63,7 +63,7 @@ export const OrgSSOSection = (): JSX.Element => {
// case: SAML SSO is not configured
// -> initialize empty SAML SSO configuration
await createMutateAsync({
- organizationId: currentOrg._id,
+ organizationId: currentOrg.id,
authProvider: "okta-saml",
isActive: false,
entryPoint: "",
@@ -118,7 +118,7 @@ export const OrgSSOSection = (): JSX.Element => {
)}
<div className="mb-4">
<h3 className="text-mineshaft-400 text-sm">SSO identifier</h3>
- <p className="text-gray-400 text-md">{data && data._id !== "" ? data._id : "-"}</p>
+ <p className="text-gray-400 text-md">{data && data.id !== "" ? data.id : "-"}</p>
</div>
<div className="mb-4">
<h3 className="text-mineshaft-400 text-sm">Type</h3>
diff --git a/frontend/src/views/Settings/OrgSettingsPage/components/OrgAuthTab/SSOModal.tsx b/frontend/src/views/Settings/OrgSettingsPage/components/OrgAuthTab/SSOModal.tsx
index 813c1741dd..98191cf73c 100644
--- a/frontend/src/views/Settings/OrgSettingsPage/components/OrgAuthTab/SSOModal.tsx
+++ b/frontend/src/views/Settings/OrgSettingsPage/components/OrgAuthTab/SSOModal.tsx
@@ -57,7 +57,7 @@ export const SSOModal = ({
const { createNotification } = useNotificationContext();
const { mutateAsync: createMutateAsync, isLoading: createIsLoading } = useCreateSSOConfig();
const { mutateAsync: updateMutateAsync, isLoading: updateIsLoading } = useUpdateSSOConfig();
- const { data } = useGetSSOConfig(currentOrg?._id ?? "");
+ const { data } = useGetSSOConfig(currentOrg?.id ?? "");
const {
control,
@@ -93,7 +93,7 @@ export const SSOModal = ({
if (!data) {
await createMutateAsync({
- organizationId: currentOrg._id,
+ organizationId: currentOrg.id,
authProvider,
isActive: false,
entryPoint,
@@ -102,7 +102,7 @@ export const SSOModal = ({
});
} else {
await updateMutateAsync({
- organizationId: currentOrg._id,
+ organizationId: currentOrg.id,
authProvider,
isActive: false,
entryPoint,
@@ -209,7 +209,7 @@ export const SSOModal = ({
<>
<div className="mb-4">
<h3 className="text-mineshaft-400 text-sm">{renderLabels(authProvider).acsUrl}</h3>
- <p className="text-gray-400 text-md break-all">{`${window.origin}/api/v1/sso/saml2/${data._id}`}</p>
+ <p className="text-gray-400 text-md break-all">{`${window.origin}/api/v1/sso/saml2/${data.id}`}</p>
</div>
<div className="mb-4">
<h3 className="text-mineshaft-400 text-sm">{renderLabels(authProvider).entityId}</h3>
diff --git a/frontend/src/views/Settings/OrgSettingsPage/components/OrgDeleteSection/OrgDeleteSection.tsx b/frontend/src/views/Settings/OrgSettingsPage/components/OrgDeleteSection/OrgDeleteSection.tsx
index a336355db5..3e0f52ba21 100644
--- a/frontend/src/views/Settings/OrgSettingsPage/components/OrgDeleteSection/OrgDeleteSection.tsx
+++ b/frontend/src/views/Settings/OrgSettingsPage/components/OrgDeleteSection/OrgDeleteSection.tsx
@@ -21,10 +21,10 @@ export const OrgDeleteSection = () => {
const handleDeleteOrgSubmit = async () => {
try {
- if (!currentOrg?._id) return;
+ if (!currentOrg?.id) return;
await mutateAsync({
- organizationId: currentOrg?._id
+ organizationId: currentOrg?.id
});
createNotification({
diff --git a/frontend/src/views/Settings/OrgSettingsPage/components/OrgIncidentContactsSection/AddOrgIncidentContactModal.tsx b/frontend/src/views/Settings/OrgSettingsPage/components/OrgIncidentContactsSection/AddOrgIncidentContactModal.tsx
index e28bbc384e..6aef9ffc7a 100644
--- a/frontend/src/views/Settings/OrgSettingsPage/components/OrgIncidentContactsSection/AddOrgIncidentContactModal.tsx
+++ b/frontend/src/views/Settings/OrgSettingsPage/components/OrgIncidentContactsSection/AddOrgIncidentContactModal.tsx
@@ -37,10 +37,10 @@ export const AddOrgIncidentContactModal = ({
const onFormSubmit = async ({ email }: TAddContactForm) => {
try {
- if (!currentOrg?._id) return;
+ if (!currentOrg?.id) return;
await mutateAsync({
- orgId: currentOrg._id,
+ orgId: currentOrg.id,
email
});
diff --git a/frontend/src/views/Settings/OrgSettingsPage/components/OrgIncidentContactsSection/OrgIncidentContactsTable.tsx b/frontend/src/views/Settings/OrgSettingsPage/components/OrgIncidentContactsSection/OrgIncidentContactsTable.tsx
index 97c1b4c14c..df5ab5f5cb 100644
--- a/frontend/src/views/Settings/OrgSettingsPage/components/OrgIncidentContactsSection/OrgIncidentContactsTable.tsx
+++ b/frontend/src/views/Settings/OrgSettingsPage/components/OrgIncidentContactsSection/OrgIncidentContactsTable.tsx
@@ -25,7 +25,7 @@ import { useDeleteIncidentContact, useGetOrgIncidentContact } from "@app/hooks/a
export const OrgIncidentContactsTable = () => {
const { createNotification } = useNotificationContext();
const { currentOrg } = useOrganization();
- const { data: contacts, isLoading } = useGetOrgIncidentContact(currentOrg?._id ?? "");
+ const { data: contacts, isLoading } = useGetOrgIncidentContact(currentOrg?.id ?? "");
const [searchContact, setSearchContact] = useState("");
const { handlePopUpToggle, popUp, handlePopUpOpen, handlePopUpClose } = usePopUp([
"removeContact",
@@ -37,9 +37,9 @@ export const OrgIncidentContactsTable = () => {
try {
const incidentContactEmail = (popUp?.removeContact?.data as { email: string })?.email;
- if (!currentOrg?._id) return;
+ if (!currentOrg?.id) return;
await mutateAsync({
- orgId: currentOrg._id,
+ orgId: currentOrg.id,
email: incidentContactEmail
});
diff --git a/frontend/src/views/Settings/OrgSettingsPage/components/OrgNameChangeSection/OrgNameChangeSection.tsx b/frontend/src/views/Settings/OrgSettingsPage/components/OrgNameChangeSection/OrgNameChangeSection.tsx
index ec433f34e2..edf30e296a 100644
--- a/frontend/src/views/Settings/OrgSettingsPage/components/OrgNameChangeSection/OrgNameChangeSection.tsx
+++ b/frontend/src/views/Settings/OrgSettingsPage/components/OrgNameChangeSection/OrgNameChangeSection.tsx
@@ -31,10 +31,10 @@ export const OrgNameChangeSection = (): JSX.Element => {
const onFormSubmit = async ({ name }: FormData) => {
try {
- if (!currentOrg?._id) return;
+ if (!currentOrg?.id) return;
if (name === "") return;
- await mutateAsync({ orgId: currentOrg?._id, newOrgName: name });
+ await mutateAsync({ orgId: currentOrg?.id, newOrgName: name });
createNotification({
text: "Successfully renamed organization",
type: "success"
diff --git a/frontend/src/views/Settings/PersonalSettingsPage/APIKeyV2Section/APIKeyV2Table.tsx b/frontend/src/views/Settings/PersonalSettingsPage/APIKeyV2Section/APIKeyV2Table.tsx
index 132723915e..9361e3be63 100644
--- a/frontend/src/views/Settings/PersonalSettingsPage/APIKeyV2Section/APIKeyV2Table.tsx
+++ b/frontend/src/views/Settings/PersonalSettingsPage/APIKeyV2Section/APIKeyV2Table.tsx
@@ -50,13 +50,13 @@ export const APIKeyV2Table = ({
data &&
data.length > 0 &&
data.map(({
- _id,
+ id,
name,
lastUsed,
createdAt
}) => {
return (
- <Tr className="h-10" key={`api-key-v2-${_id}`}>
+ <Tr className="h-10" key={`api-key-v2-${id}`}>
<Td>{name}</Td>
<Td>{lastUsed ? format(new Date(lastUsed), "yyyy-MM-dd") : "-"}</Td>
<Td>{format(new Date(createdAt), "yyyy-MM-dd")}</Td>
@@ -64,7 +64,7 @@ export const APIKeyV2Table = ({
<IconButton
onClick={async () => {
handlePopUpOpen("apiKeyV2", {
- apiKeyDataId: _id,
+ apiKeyDataId: id,
name
});
}}
@@ -78,7 +78,7 @@ export const APIKeyV2Table = ({
<IconButton
onClick={() => {
handlePopUpOpen("deleteAPIKeyV2", {
- apiKeyDataId: _id
+ apiKeyDataId: id
});
}}
size="lg"
diff --git a/frontend/src/views/Signup/components/UserInfoSSOStep/UserInfoSSOStep.tsx b/frontend/src/views/Signup/components/UserInfoSSOStep/UserInfoSSOStep.tsx
index 23353d7d88..81828a8974 100644
--- a/frontend/src/views/Signup/components/UserInfoSSOStep/UserInfoSSOStep.tsx
+++ b/frontend/src/views/Signup/components/UserInfoSSOStep/UserInfoSSOStep.tsx
@@ -187,14 +187,14 @@ export const UserInfoSSOStep = ({
});
const userOrgs = await fetchOrganizations();
- const orgId = userOrgs[0]?._id;
+ const orgId = userOrgs[0]?.id;
const project = await ProjectService.initProject({
organizationId: orgId,
projectName: "Example Project"
});
localStorage.setItem("orgData.id", orgId);
- localStorage.setItem("projectData.id", project._id);
+ localStorage.setItem("projectData.id", project.id);
setStep(1);
} catch (error) {
diff --git a/frontend/src/views/admin/DashboardPage/DashboardPage.tsx b/frontend/src/views/admin/DashboardPage/DashboardPage.tsx
index 6c7e18740b..cbf5f9ce86 100644
--- a/frontend/src/views/admin/DashboardPage/DashboardPage.tsx
+++ b/frontend/src/views/admin/DashboardPage/DashboardPage.tsx
@@ -22,8 +22,8 @@ export const AdminDashboardPage = () => {
useEffect(() => {
if (isNotAllowed && !isUserLoading) {
if (orgs?.length) {
- localStorage.setItem("orgData.id", orgs?.[0]?._id);
- router.push(`/org/${orgs?.[0]?._id}/overview`);
+ localStorage.setItem("orgData.id", orgs?.[0]?.id);
+ router.push(`/org/${orgs?.[0]?.id}/overview`);
}
}
}, [isNotAllowed, isUserLoading]);