mirror of
https://github.com/awatertrevi/infisical.git
synced 2026-09-22 13:39:35 +00:00
feat(infisical-pg): updated names and simplified dal layer using ormify
This commit is contained in:
@@ -1,2 +1 @@
|
||||
.eslintrc.js
|
||||
./scripts
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
/* eslint-disable */
|
||||
import { mkdirSync, writeFileSync } from "fs";
|
||||
import path from "path";
|
||||
import promptSync from "prompt-sync";
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
/* eslint-disable */
|
||||
import { execSync } from "child_process";
|
||||
import path from "path";
|
||||
import promptSync from "prompt-sync";
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
/* eslint-disable */
|
||||
import dotenv from "dotenv";
|
||||
import path from "path";
|
||||
import knex from "knex";
|
||||
import { appendFileSync, readFileSync, writeFileSync } from "fs";
|
||||
import { writeFileSync } from "fs";
|
||||
import promptSync from "prompt-sync";
|
||||
import { TableName } from "@app/db/schemas";
|
||||
|
||||
const prompt = promptSync();
|
||||
|
||||
@@ -96,11 +96,11 @@ const main = async () => {
|
||||
const tableNumbers =
|
||||
selectedTables !== "all" ? selectedTables.split(",").map((el) => Number(el)) : [];
|
||||
|
||||
for (let i = 0; i < tables.length; i++) {
|
||||
for (let i = 0; i < tables.length; i += 1) {
|
||||
// skip if not desired table
|
||||
if (selectedTables !== "all" && !tableNumbers.includes(i)) continue;
|
||||
|
||||
const tableName = tables[i].tableName;
|
||||
const { tableName } = tables[i];
|
||||
const columns = await db(tableName).columnInfo();
|
||||
const columnNames = Object.keys(columns);
|
||||
|
||||
@@ -110,7 +110,7 @@ const main = async () => {
|
||||
const colInfo = columns[columnName];
|
||||
let ztype = getZodPrimitiveType(colInfo.type);
|
||||
if (colInfo.defaultValue) {
|
||||
const defaultValue = colInfo.defaultValue;
|
||||
const { defaultValue } = colInfo;
|
||||
const zSchema = getZodDefaultValue(colInfo.type, defaultValue);
|
||||
if (zSchema) {
|
||||
ztype = ztype.concat(zSchema);
|
||||
|
||||
4
backend-pg/src/@types/fastify.d.ts
vendored
4
backend-pg/src/@types/fastify.d.ts
vendored
@@ -7,7 +7,7 @@ import { TAuthSignupFactory } from "@app/services/auth/auth-signup-service";
|
||||
import { AuthMode } from "@app/services/auth/auth-signup-type";
|
||||
import { TOrgRoleServiceFactory } from "@app/services/org/org-role-service";
|
||||
import { TOrgServiceFactory } from "@app/services/org/org-service";
|
||||
import { TServerCfgServiceFactory } from "@app/services/server-cfg/server-cfg-service";
|
||||
import { TSuperAdminServiceFactory } from "@app/services/super-admin/super-admin-service";
|
||||
import { TAuthTokenServiceFactory } from "@app/services/token/token-service";
|
||||
import { TUserDalFactory } from "@app/services/user/user-dal";
|
||||
import { TUserServiceFactory } from "@app/services/user/user-service";
|
||||
@@ -40,7 +40,7 @@ declare module "fastify" {
|
||||
permission: TPermissionServiceFactory;
|
||||
org: TOrgServiceFactory;
|
||||
orgRole: TOrgRoleServiceFactory;
|
||||
serverCfg: TServerCfgServiceFactory;
|
||||
superAdmin: TSuperAdminServiceFactory;
|
||||
user: TUserServiceFactory;
|
||||
apiKey: TApiKeyServiceFactory;
|
||||
};
|
||||
|
||||
18
backend-pg/src/@types/knex.d.ts
vendored
18
backend-pg/src/@types/knex.d.ts
vendored
@@ -2,6 +2,9 @@ import { Knex } from "knex";
|
||||
|
||||
import {
|
||||
TableName,
|
||||
TApiKeys,
|
||||
TApiKeysInsert,
|
||||
TApiKeysUpdate,
|
||||
TAuthTokens,
|
||||
TAuthTokenSessions,
|
||||
TAuthTokenSessionsInsert,
|
||||
@@ -22,9 +25,9 @@ import {
|
||||
TOrgRoles,
|
||||
TOrgRolesInsert,
|
||||
TOrgRolesUpdate,
|
||||
TServerConfig,
|
||||
TServerConfigInsert,
|
||||
TServerConfigUpdate,
|
||||
TSuperAdmin,
|
||||
TSuperAdminInsert,
|
||||
TSuperAdminUpdate,
|
||||
TUserActions,
|
||||
TUserActionsInsert,
|
||||
TUserActionsUpdate,
|
||||
@@ -35,7 +38,6 @@ import {
|
||||
TUsersInsert,
|
||||
TUsersUpdate
|
||||
} from "@app/db/schemas";
|
||||
import { TApiKeys, TApiKeysInsert, TApiKeysUpdate } from "@app/db/schemas/api-keys";
|
||||
|
||||
declare module "knex/types/tables" {
|
||||
interface Tables extends { [key in TableName]: Knex.CompositeTableType<any> } {
|
||||
@@ -81,10 +83,10 @@ declare module "knex/types/tables" {
|
||||
TUserActionsInsert,
|
||||
TUserActionsUpdate
|
||||
>;
|
||||
[TableName.ServerConfig]: Knex.CompositeTableType<
|
||||
TServerConfig,
|
||||
TServerConfigInsert,
|
||||
TServerConfigUpdate
|
||||
[TableName.SuperAdmin]: Knex.CompositeTableType<
|
||||
TSuperAdmin,
|
||||
TSuperAdminInsert,
|
||||
TSuperAdminUpdate
|
||||
>;
|
||||
[TableName.ApiKey]: Knex.CompositeTableType<TApiKeys, TApiKeysInsert, TApiKeysUpdate>;
|
||||
}
|
||||
|
||||
@@ -4,9 +4,9 @@ import { TableName } from "../schemas";
|
||||
import { createOnUpdateTrigger, dropOnUpdateTrigger } from "../utils";
|
||||
|
||||
export async function up(knex: Knex): Promise<void> {
|
||||
const isTablePresent = await knex.schema.hasTable(TableName.ServerConfig);
|
||||
const isTablePresent = await knex.schema.hasTable(TableName.SuperAdmin);
|
||||
if (!isTablePresent) {
|
||||
await knex.schema.createTable(TableName.ServerConfig, (t) => {
|
||||
await knex.schema.createTable(TableName.SuperAdmin, (t) => {
|
||||
t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
|
||||
t.boolean("initialized").defaultTo(false);
|
||||
t.boolean("allowSignUp").defaultTo(true);
|
||||
@@ -14,10 +14,10 @@ export async function up(knex: Knex): Promise<void> {
|
||||
});
|
||||
}
|
||||
// this is a one time function
|
||||
await createOnUpdateTrigger(knex, TableName.ServerConfig);
|
||||
await createOnUpdateTrigger(knex, TableName.SuperAdmin);
|
||||
}
|
||||
|
||||
export async function down(knex: Knex): Promise<void> {
|
||||
await knex.schema.dropTableIfExists(TableName.ServerConfig);
|
||||
await dropOnUpdateTrigger(knex, TableName.ServerConfig);
|
||||
await knex.schema.dropTableIfExists(TableName.SuperAdmin);
|
||||
await dropOnUpdateTrigger(knex, TableName.SuperAdmin);
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
export * from "./api-keys";
|
||||
export * from "./auth-token-sessions";
|
||||
export * from "./auth-tokens";
|
||||
export * from "./backup-private-key";
|
||||
@@ -6,7 +7,7 @@ export * from "./models";
|
||||
export * from "./org-memberships";
|
||||
export * from "./org-roles";
|
||||
export * from "./organizations";
|
||||
export * from "./server-config";
|
||||
export * from "./super-admin";
|
||||
export * from "./user-actions";
|
||||
export * from "./user-encryption-keys";
|
||||
export * from "./users";
|
||||
|
||||
@@ -11,7 +11,7 @@ export enum TableName {
|
||||
OrgRoles = "org_roles",
|
||||
IncidentContact = "incident_contacts",
|
||||
UserAction = "user_actions",
|
||||
ServerConfig = "server_config",
|
||||
SuperAdmin = "super_admin",
|
||||
ApiKey = "api_keys"
|
||||
}
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ import { z } from "zod";
|
||||
|
||||
import { TImmutableDBKeys } from "./models";
|
||||
|
||||
export const ServerConfigSchema = z.object({
|
||||
export const SuperAdminSchema = z.object({
|
||||
id: z.string().uuid(),
|
||||
initialized: z.boolean().default(false).nullable().optional(),
|
||||
allowSignUp: z.boolean().default(true).nullable().optional(),
|
||||
@@ -15,6 +15,6 @@ export const ServerConfigSchema = z.object({
|
||||
updatedAt: z.date(),
|
||||
});
|
||||
|
||||
export type TServerConfig = z.infer<typeof ServerConfigSchema>;
|
||||
export type TServerConfigInsert = Omit<TServerConfig, TImmutableDBKeys>;
|
||||
export type TServerConfigUpdate = Partial<Omit<TServerConfig, TImmutableDBKeys>>;
|
||||
export type TSuperAdmin = z.infer<typeof SuperAdminSchema>;
|
||||
export type TSuperAdminInsert = Omit<TSuperAdmin, TImmutableDBKeys>;
|
||||
export type TSuperAdminUpdate = Partial<Omit<TSuperAdmin, TImmutableDBKeys>>;
|
||||
@@ -11,7 +11,7 @@ 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(),
|
||||
encryptionVersion: z.number().default(2).nullable().optional(),
|
||||
protectedKey: z.string(),
|
||||
protectedKeyIV: z.string(),
|
||||
protectedKeyTag: z.string(),
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { registerOrgRoleRouter } from "./org-role";
|
||||
import { registerOrgRoleRouter } from "./org-role-router";
|
||||
|
||||
export const registerV1EERoutes = async (server: FastifyZodProvider) => {
|
||||
// org role starts with organization
|
||||
|
||||
@@ -10,8 +10,9 @@ export const permissionDalFactory = (db: TDbClient) => {
|
||||
): Promise<(TOrgMemberships & { permissions: string }) | undefined> => {
|
||||
const membership = await db(TableName.OrgMembership)
|
||||
.leftJoin(TableName.OrgRoles, `${TableName.OrgMembership}.roleId`, `${TableName.OrgRoles}.id`)
|
||||
.select(`${TableName.OrgMembership}.*`, `${TableName.OrgRoles}.permissions`)
|
||||
.where({ userId, [`${TableName.OrgMembership}.orgId`]: orgId })
|
||||
.where("userId", userId)
|
||||
.where(`${TableName.OrgMembership}.orgId`, orgId)
|
||||
.select(`${TableName.OrgMembership}.*`, "permissions")
|
||||
.first();
|
||||
|
||||
return membership;
|
||||
|
||||
@@ -11,16 +11,16 @@ import { authDalFactory } from "@app/services/auth/auth-dal";
|
||||
import { authLoginServiceFactory } from "@app/services/auth/auth-login-service";
|
||||
import { authPaswordServiceFactory } from "@app/services/auth/auth-password-service";
|
||||
import { authSignupServiceFactory } from "@app/services/auth/auth-signup-service";
|
||||
import { tokenDalFactory } from "@app/services/auth-token/auth-token-dal";
|
||||
import { tokenServiceFactory } from "@app/services/auth-token/auth-token-service";
|
||||
import { incidentContactDalFactory } from "@app/services/org/incident-contacts-dal";
|
||||
import { orgDalFactory } from "@app/services/org/org-dal";
|
||||
import { orgRoleDalFactory } from "@app/services/org/org-role-dal";
|
||||
import { orgRoleServiceFactory } from "@app/services/org/org-role-service";
|
||||
import { orgServiceFactory } from "@app/services/org/org-service";
|
||||
import { serverCfgDalFactory } from "@app/services/server-cfg/server-cfg-dal";
|
||||
import { serverCfgServiceFactory } from "@app/services/server-cfg/server-cfg-service";
|
||||
import { TSmtpService } from "@app/services/smtp/smtp-service";
|
||||
import { tokenDalFactory } from "@app/services/token/token-dal";
|
||||
import { tokenServiceFactory } from "@app/services/token/token-service";
|
||||
import { superAdminDalFactory } from "@app/services/super-admin/super-admin-dal";
|
||||
import { superAdminServiceFactory } from "@app/services/super-admin/super-admin-service";
|
||||
import { userDalFactory } from "@app/services/user/user-dal";
|
||||
import { userServiceFactory } from "@app/services/user/user-service";
|
||||
|
||||
@@ -40,7 +40,7 @@ export const registerRoutes = async (
|
||||
const orgDal = orgDalFactory(db);
|
||||
const incidentContactDal = incidentContactDalFactory(db);
|
||||
const orgRoleDal = orgRoleDalFactory(db);
|
||||
const serverCfgDal = serverCfgDalFactory(db);
|
||||
const superAdminDal = superAdminDalFactory(db);
|
||||
const apiKeyDal = apiKeyDalFactory(db);
|
||||
|
||||
// ee db layer ops
|
||||
@@ -77,16 +77,16 @@ export const registerRoutes = async (
|
||||
orgService
|
||||
});
|
||||
const orgRoleService = orgRoleServiceFactory({ permissionService, orgRoleDal });
|
||||
const serverCfgService = serverCfgServiceFactory({
|
||||
const superAdminService = superAdminServiceFactory({
|
||||
userDal,
|
||||
authService: loginService,
|
||||
serverCfgDal
|
||||
serverCfgDal: superAdminDal
|
||||
});
|
||||
const apiKeyService = apiKeyServiceFactory({ apiKeyDal });
|
||||
|
||||
await serverCfgService.initServerCfg();
|
||||
await superAdminService.initServerCfg();
|
||||
// inject all services
|
||||
server.decorate("services", {
|
||||
server.decorate<FastifyZodProvider["services"]>("services", {
|
||||
login: loginService,
|
||||
password: passwordService,
|
||||
signup: signupService,
|
||||
@@ -94,14 +94,14 @@ export const registerRoutes = async (
|
||||
permission: permissionService,
|
||||
org: orgService,
|
||||
orgRole: orgRoleService,
|
||||
serverCfg: serverCfgService,
|
||||
apiKey: apiKeyService,
|
||||
authToken: tokenService
|
||||
} as FastifyZodProvider["services"]);
|
||||
authToken: tokenService,
|
||||
superAdmin: superAdminService
|
||||
});
|
||||
|
||||
server.decorate("store", {
|
||||
server.decorate<FastifyZodProvider["store"]>("store", {
|
||||
user: userDal
|
||||
} as FastifyZodProvider["store"]);
|
||||
});
|
||||
|
||||
await server.register(injectIdentity);
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { ServerConfigSchema, UsersSchema } from "@app/db/schemas";
|
||||
import { SuperAdminSchema, UsersSchema } from "@app/db/schemas";
|
||||
import { getConfig } from "@app/lib/config/env";
|
||||
import { UnauthorizedError } from "@app/lib/errors";
|
||||
import { verifySuperAdmin } from "@app/server/plugins/auth/superAdmin";
|
||||
@@ -14,12 +14,12 @@ export const registerAdminRouter = async (server: FastifyZodProvider) => {
|
||||
schema: {
|
||||
response: {
|
||||
200: z.object({
|
||||
config: ServerConfigSchema
|
||||
config: SuperAdminSchema
|
||||
})
|
||||
}
|
||||
},
|
||||
handler: () => {
|
||||
const config = server.services.serverCfg.getServerCfg();
|
||||
const config = server.services.superAdmin.getServerCfg();
|
||||
return { config };
|
||||
}
|
||||
});
|
||||
@@ -33,7 +33,7 @@ export const registerAdminRouter = async (server: FastifyZodProvider) => {
|
||||
}),
|
||||
response: {
|
||||
200: z.object({
|
||||
config: ServerConfigSchema
|
||||
config: SuperAdminSchema
|
||||
})
|
||||
}
|
||||
},
|
||||
@@ -42,7 +42,7 @@ export const registerAdminRouter = async (server: FastifyZodProvider) => {
|
||||
verifySuperAdmin(req);
|
||||
},
|
||||
handler: async (req) => {
|
||||
const config = await server.services.serverCfg.updateServerCfg(req.body);
|
||||
const config = await server.services.superAdmin.updateServerCfg(req.body);
|
||||
return { config };
|
||||
}
|
||||
});
|
||||
@@ -75,10 +75,10 @@ export const registerAdminRouter = async (server: FastifyZodProvider) => {
|
||||
},
|
||||
handler: async (req, res) => {
|
||||
const appCfg = getConfig();
|
||||
const serverCfg = server.services.serverCfg.getServerCfg();
|
||||
const serverCfg = server.services.superAdmin.getServerCfg();
|
||||
if (serverCfg.initialized)
|
||||
throw new UnauthorizedError({ name: "Admin sign up", message: "Admin has been created" });
|
||||
const { user, token } = await server.services.serverCfg.adminSignUp({
|
||||
const { user, token } = await server.services.superAdmin.adminSignUp({
|
||||
...req.body,
|
||||
ip: req.realIp,
|
||||
userAgent: req.headers["user-agent"] || ""
|
||||
@@ -1,6 +1,6 @@
|
||||
import { registerAdminRouter } from "./admin";
|
||||
import { registerAuthRoutes } from "./auth";
|
||||
import { registerInviteOrgRouter } from "./invite-org";
|
||||
import { registerAdminRouter } from "./admin-router";
|
||||
import { registerAuthRoutes } from "./auth-router";
|
||||
import { registerInviteOrgRouter } from "./invite-org-router";
|
||||
import { registerOrgRouter } from "./organization-router";
|
||||
import { registerPasswordRouter } from "./password-router";
|
||||
import { registerUserActionRouter } from "./user-action-router";
|
||||
|
||||
@@ -5,7 +5,7 @@ import { TableName, TAuthTokens, TAuthTokenSessions } from "@app/db/schemas";
|
||||
import { DatabaseError } from "@app/lib/errors";
|
||||
import { ormify } from "@app/lib/knex";
|
||||
|
||||
import { TDeleteTokenForUserDalDTO } from "./token-types";
|
||||
import { TDeleteTokenForUserDalDTO } from "./auth-token-types";
|
||||
|
||||
export type TTokenDalConfig = {};
|
||||
|
||||
@@ -4,13 +4,13 @@ import bcrypt from "bcrypt";
|
||||
import { TAuthTokens, TAuthTokenSessions } from "@app/db/schemas";
|
||||
import { getConfig } from "@app/lib/config/env";
|
||||
|
||||
import { TTokenDalFactory } from "./token-dal";
|
||||
import { TTokenDalFactory } from "./auth-token-dal";
|
||||
import {
|
||||
TCreateTokenForUserDTO,
|
||||
TIssueAuthTokenDTO,
|
||||
TokenType,
|
||||
TValidateTokenForUserDTO
|
||||
} from "./token-types";
|
||||
} from "./auth-token-types";
|
||||
|
||||
type TAuthTokenServiceFactoryDep = {
|
||||
tokenDal: TTokenDalFactory;
|
||||
@@ -4,9 +4,9 @@ import { TUsers, UserDeviceSchema } from "@app/db/schemas";
|
||||
import { getConfig } from "@app/lib/config/env";
|
||||
import { generateSrpServerKey, srpCheckClientProof } from "@app/lib/crypto";
|
||||
|
||||
import { TAuthTokenServiceFactory } from "../auth-token/auth-token-service";
|
||||
import { TokenType } from "../auth-token/auth-token-types";
|
||||
import { SmtpTemplates, TSmtpService } from "../smtp/smtp-service";
|
||||
import { TAuthTokenServiceFactory } from "../token/token-service";
|
||||
import { TokenType } from "../token/token-types";
|
||||
import { TUserDalFactory } from "../user/user-dal";
|
||||
import {
|
||||
TLoginClientProofDTO,
|
||||
|
||||
@@ -3,9 +3,9 @@ import jwt from "jsonwebtoken";
|
||||
import { getConfig } from "@app/lib/config/env";
|
||||
import { generateSrpServerKey, srpCheckClientProof } from "@app/lib/crypto";
|
||||
|
||||
import { TAuthTokenServiceFactory } from "../auth-token/auth-token-service";
|
||||
import { TokenType } from "../auth-token/auth-token-types";
|
||||
import { SmtpTemplates, TSmtpService } from "../smtp/smtp-service";
|
||||
import { TAuthTokenServiceFactory } from "../token/token-service";
|
||||
import { TokenType } from "../token/token-types";
|
||||
import { TUserDalFactory } from "../user/user-dal";
|
||||
import { TAuthDalFactory } from "./auth-dal";
|
||||
import {
|
||||
|
||||
@@ -5,11 +5,11 @@ import { getConfig } from "@app/lib/config/env";
|
||||
import { BadRequestError } from "@app/lib/errors";
|
||||
import { isDisposableEmail } from "@app/lib/validator";
|
||||
|
||||
import { TAuthTokenServiceFactory } from "../auth-token/auth-token-service";
|
||||
import { TokenType } from "../auth-token/auth-token-types";
|
||||
import { TOrgDalFactory } from "../org/org-dal";
|
||||
import { TOrgServiceFactory } from "../org/org-service";
|
||||
import { SmtpTemplates, TSmtpService } from "../smtp/smtp-service";
|
||||
import { TAuthTokenServiceFactory } from "../token/token-service";
|
||||
import { TokenType } from "../token/token-types";
|
||||
import { TUserDalFactory } from "../user/user-dal";
|
||||
import { TAuthDalFactory } from "./auth-dal";
|
||||
import { TCompleteAccountInviteDTO, TCompleteAccountSignupDTO } from "./auth-signup-type";
|
||||
|
||||
@@ -1,67 +1,7 @@
|
||||
import { Knex } from "knex";
|
||||
|
||||
import { TDbClient } from "@app/db";
|
||||
import { TableName,TOrgRolesInsert, TOrgRolesUpdate } from "@app/db/schemas";
|
||||
import { DatabaseError } from "@app/lib/errors";
|
||||
import { withTransaction } from "@app/lib/knex";
|
||||
import { TableName } from "@app/db/schemas";
|
||||
import { ormify } from "@app/lib/knex";
|
||||
|
||||
export type TOrgRoleDalFactory = ReturnType<typeof orgRoleDalFactory>;
|
||||
|
||||
export const orgRoleDalFactory = (db: TDbClient) => {
|
||||
const find = async (data: TOrgRolesUpdate, tx?: Knex) => {
|
||||
try {
|
||||
const role = await (tx || db)(TableName.OrgRoles).where(data);
|
||||
return role;
|
||||
} catch (error) {
|
||||
throw new DatabaseError({ error, name: "Org role find one" });
|
||||
}
|
||||
};
|
||||
|
||||
const findOne = async (data: TOrgRolesUpdate, tx?: Knex) => {
|
||||
try {
|
||||
const role = await (tx || db)(TableName.OrgRoles).where(data).first();
|
||||
return role;
|
||||
} catch (error) {
|
||||
throw new DatabaseError({ error, name: "Org role find one" });
|
||||
}
|
||||
};
|
||||
|
||||
const create = async (data: TOrgRolesInsert, tx?: Knex) => {
|
||||
try {
|
||||
const [role] = await (tx || db)(TableName.OrgRoles).insert(data).returning("*");
|
||||
return role;
|
||||
} catch (error) {
|
||||
throw new DatabaseError({ error, name: "Org role create" });
|
||||
}
|
||||
};
|
||||
|
||||
const updateOne = async (
|
||||
filter: { id: string; orgId: string },
|
||||
data: TOrgRolesUpdate,
|
||||
tx?: Knex
|
||||
) => {
|
||||
try {
|
||||
const [role] = await (tx || db)(TableName.OrgRoles).where(filter).update(data).returning("*");
|
||||
return role;
|
||||
} catch (error) {
|
||||
throw new DatabaseError({ error, name: "Org role create" });
|
||||
}
|
||||
};
|
||||
|
||||
const deleteOne = async (filter: { id: string; orgId: string }, tx?: Knex) => {
|
||||
try {
|
||||
const [role] = await (tx || db)(TableName.OrgRoles).where(filter).delete().returning("*");
|
||||
return role;
|
||||
} catch (error) {
|
||||
throw new DatabaseError({ error, name: "Org role create" });
|
||||
}
|
||||
};
|
||||
|
||||
return withTransaction(db, {
|
||||
find,
|
||||
findOne,
|
||||
create,
|
||||
updateOne,
|
||||
deleteOne
|
||||
});
|
||||
};
|
||||
export const orgRoleDalFactory = (db: TDbClient) => ormify(db, TableName.OrgRoles);
|
||||
|
||||
@@ -57,7 +57,7 @@ export const orgRoleServiceFactory = ({
|
||||
if (existingRole && existingRole.id !== roleId)
|
||||
throw new BadRequestError({ name: "Update Role", message: "Duplicate role" });
|
||||
}
|
||||
const updatedRole = await orgRoleDal.updateOne({ id: roleId, orgId }, { ...data });
|
||||
const [updatedRole] = await orgRoleDal.update({ id: roleId, orgId }, { ...data });
|
||||
if (!updateRole) throw new BadRequestError({ message: "Role not found", name: "Update role" });
|
||||
return updatedRole;
|
||||
};
|
||||
@@ -68,7 +68,7 @@ export const orgRoleServiceFactory = ({
|
||||
OrgPermissionActions.Delete,
|
||||
OrgPermissionSubjects.Role
|
||||
);
|
||||
const deletedRole = await orgRoleDal.deleteOne({ id: roleId, orgId });
|
||||
const [deletedRole] = await orgRoleDal.delete({ id: roleId, orgId });
|
||||
if (!deleteRole) throw new BadRequestError({ message: "Role not found", name: "Update role" });
|
||||
|
||||
return deletedRole;
|
||||
|
||||
@@ -11,9 +11,9 @@ import { BadRequestError, UnauthorizedError } from "@app/lib/errors";
|
||||
import { isDisposableEmail } from "@app/lib/validator";
|
||||
|
||||
import { AuthTokenType } from "../auth/auth-type";
|
||||
import { TAuthTokenServiceFactory } from "../auth-token/auth-token-service";
|
||||
import { TokenType } from "../auth-token/auth-token-types";
|
||||
import { SmtpTemplates, TSmtpService } from "../smtp/smtp-service";
|
||||
import { TAuthTokenServiceFactory } from "../token/token-service";
|
||||
import { TokenType } from "../token/token-types";
|
||||
import { TUserDalFactory } from "../user/user-dal";
|
||||
import { TIncidentContactsDalFactory } from "./incident-contacts-dal";
|
||||
import { TOrgDalFactory } from "./org-dal";
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
import { TDbClient } from "@app/db";
|
||||
import { TableName } from "@app/db/schemas";
|
||||
import { ormify } from "@app/lib/knex";
|
||||
|
||||
export type TServerCfgDalFactory = ReturnType<typeof serverCfgDalFactory>;
|
||||
|
||||
export const serverCfgDalFactory = (db: TDbClient) => ormify(db, TableName.ServerConfig, {});
|
||||
7
backend-pg/src/services/super-admin/super-admin-dal.ts
Normal file
7
backend-pg/src/services/super-admin/super-admin-dal.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
import { TDbClient } from "@app/db";
|
||||
import { TableName } from "@app/db/schemas";
|
||||
import { ormify } from "@app/lib/knex";
|
||||
|
||||
export type TSuperAdminDalFactory = ReturnType<typeof superAdminDalFactory>;
|
||||
|
||||
export const superAdminDalFactory = (db: TDbClient) => ormify(db, TableName.SuperAdmin, {});
|
||||
@@ -1,25 +1,25 @@
|
||||
import { TServerConfig, TServerConfigUpdate } from "@app/db/schemas";
|
||||
import { TSuperAdmin, TSuperAdminUpdate } from "@app/db/schemas";
|
||||
import { BadRequestError } from "@app/lib/errors";
|
||||
|
||||
import { TAuthLoginFactory } from "../auth/auth-login-service";
|
||||
import { TUserDalFactory } from "../user/user-dal";
|
||||
import { TServerCfgDalFactory } from "./server-cfg-dal";
|
||||
import { TAdminSignUpDTO } from "./server-cfg-types";
|
||||
import { TSuperAdminDalFactory } from "./super-admin-dal";
|
||||
import { TAdminSignUpDTO } from "./super-admin-types";
|
||||
|
||||
type TServerCfgServiceFactoryDep = {
|
||||
serverCfgDal: TServerCfgDalFactory;
|
||||
type TSuperAdminServiceFactoryDep = {
|
||||
serverCfgDal: TSuperAdminDalFactory;
|
||||
userDal: TUserDalFactory;
|
||||
authService: Pick<TAuthLoginFactory, "generateUserTokens">;
|
||||
};
|
||||
|
||||
export type TServerCfgServiceFactory = ReturnType<typeof serverCfgServiceFactory>;
|
||||
export type TSuperAdminServiceFactory = ReturnType<typeof superAdminServiceFactory>;
|
||||
|
||||
export const serverCfgServiceFactory = ({
|
||||
export const superAdminServiceFactory = ({
|
||||
serverCfgDal,
|
||||
userDal,
|
||||
authService
|
||||
}: TServerCfgServiceFactoryDep) => {
|
||||
let serverCfg: TServerConfig;
|
||||
}: TSuperAdminServiceFactoryDep) => {
|
||||
let serverCfg: TSuperAdmin;
|
||||
|
||||
const initServerCfg = async () => {
|
||||
serverCfg = await serverCfgDal.findOne({});
|
||||
@@ -37,7 +37,7 @@ export const serverCfgServiceFactory = ({
|
||||
return serverCfg;
|
||||
};
|
||||
|
||||
const updateServerCfg = async (data: TServerConfigUpdate) => {
|
||||
const updateServerCfg = async (data: TSuperAdminUpdate) => {
|
||||
const cfg = await serverCfgDal.updateById(serverCfg.id, data);
|
||||
return cfg;
|
||||
};
|
||||
@@ -20,25 +20,35 @@ export const userDalFactory = (db: TDbClient) => {
|
||||
|
||||
// USER ENCRYPTION FUNCTIONS
|
||||
// -------------------------
|
||||
const findUserEncKeyByEmail = async (email: string) =>
|
||||
db(TableName.Users)
|
||||
.where({ email })
|
||||
.join(
|
||||
TableName.UserEncryptionKey,
|
||||
`${TableName.Users}.id`,
|
||||
`${TableName.UserEncryptionKey}.userId`
|
||||
)
|
||||
.first();
|
||||
const findUserEncKeyByEmail = async (email: string) => {
|
||||
try {
|
||||
return await db(TableName.Users)
|
||||
.where({ email })
|
||||
.join(
|
||||
TableName.UserEncryptionKey,
|
||||
`${TableName.Users}.id`,
|
||||
`${TableName.UserEncryptionKey}.userId`
|
||||
)
|
||||
.first();
|
||||
} catch (error) {
|
||||
throw new DatabaseError({ error, name: "Find user enc by email" });
|
||||
}
|
||||
};
|
||||
|
||||
const findUserEncKeyByUserId = async (userId: string) =>
|
||||
db(TableName.Users)
|
||||
.where({ [`${TableName.Users}.id`]: userId })
|
||||
.join(
|
||||
TableName.UserEncryptionKey,
|
||||
`${TableName.Users}.id`,
|
||||
`${TableName.UserEncryptionKey}.userId`
|
||||
)
|
||||
.first();
|
||||
const findUserEncKeyByUserId = async (userId: string) => {
|
||||
try {
|
||||
return await db(TableName.Users)
|
||||
.where(`${TableName.Users}.id`, userId)
|
||||
.join(
|
||||
TableName.UserEncryptionKey,
|
||||
`${TableName.Users}.id`,
|
||||
`${TableName.UserEncryptionKey}.userId`
|
||||
)
|
||||
.first();
|
||||
} catch (error) {
|
||||
throw new DatabaseError({ error, name: "Find user enc by user id" });
|
||||
}
|
||||
};
|
||||
|
||||
const createUserEncryption = async (data: TUserEncryptionKeysInsert, tx?: Knex) => {
|
||||
try {
|
||||
@@ -54,11 +64,15 @@ export const userDalFactory = (db: TDbClient) => {
|
||||
data: TUserEncryptionKeysUpdate,
|
||||
tx?: Knex
|
||||
) => {
|
||||
const [userEnc] = await (tx || db)(TableName.UserEncryptionKey)
|
||||
.where({ userId })
|
||||
.update({ ...data })
|
||||
.returning("*");
|
||||
return userEnc;
|
||||
try {
|
||||
const [userEnc] = await (tx || db)(TableName.UserEncryptionKey)
|
||||
.where({ userId })
|
||||
.update({ ...data })
|
||||
.returning("*");
|
||||
return userEnc;
|
||||
} catch (error) {
|
||||
throw new DatabaseError({ error, name: "Update user enc by user id" });
|
||||
}
|
||||
};
|
||||
|
||||
const upsertUserEncryptionKey = async (
|
||||
@@ -66,13 +80,20 @@ export const userDalFactory = (db: TDbClient) => {
|
||||
data: Omit<TUserEncryptionKeysUpdate, "userId">,
|
||||
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 TUserEncryptionKeys)
|
||||
.onConflict("userId")
|
||||
.merge()
|
||||
.returning("*");
|
||||
return userEnc;
|
||||
try {
|
||||
const [userEnc] = await (tx
|
||||
? tx(TableName.UserEncryptionKey)
|
||||
: db(TableName.UserEncryptionKey)
|
||||
)
|
||||
// if user insert make sure to pass all required data
|
||||
.insert({ userId, ...data } as TUserEncryptionKeys)
|
||||
.onConflict("userId")
|
||||
.merge()
|
||||
.returning("*");
|
||||
return userEnc;
|
||||
} catch (error) {
|
||||
throw new DatabaseError({ error, name: "Upsert user enc key" });
|
||||
}
|
||||
};
|
||||
|
||||
// USER ACTION FUNCTIONS
|
||||
|
||||
Reference in New Issue
Block a user