Merge remote-tracking branch 'origin' into org-based-auth

This commit is contained in:
Tuan Dang
2024-02-07 09:49:13 -08:00
26 changed files with 570 additions and 366 deletions
@@ -1,4 +1,5 @@
import { TSuperAdmin, TSuperAdminUpdate } from "@app/db/schemas";
import { getConfig } from "@app/lib/config/env";
import { BadRequestError } from "@app/lib/errors";
import { TAuthLoginFactory } from "../auth/auth-login-service";
@@ -17,11 +18,8 @@ type TSuperAdminServiceFactoryDep = {
export type TSuperAdminServiceFactory = ReturnType<typeof superAdminServiceFactory>;
let serverCfg: Readonly<TSuperAdmin>;
export const getServerCfg = () => {
if (!serverCfg) throw new BadRequestError({ name: "Get server cfg", message: "Server cfg not initialized" });
return serverCfg;
};
// eslint-disable-next-line
export let getServerCfg: () => Promise<TSuperAdmin>;
export const superAdminServiceFactory = ({
serverCfgDAL,
@@ -30,19 +28,18 @@ export const superAdminServiceFactory = ({
orgService
}: TSuperAdminServiceFactoryDep) => {
const initServerCfg = async () => {
serverCfg = await serverCfgDAL.findOne({});
if (!serverCfg) {
const newCfg = await serverCfgDAL.create({ initialized: false, allowSignUp: true });
serverCfg = newCfg;
return newCfg;
}
return serverCfg;
// TODO(akhilmhdh): bad pattern time less change this later to me itself
getServerCfg = () => serverCfgDAL.findOne({});
const serverCfg = await serverCfgDAL.findOne({});
if (serverCfg) return;
const newCfg = await serverCfgDAL.create({ initialized: false, allowSignUp: true });
return newCfg;
};
const updateServerCfg = async (data: TSuperAdminUpdate) => {
const serverCfg = await getServerCfg();
const cfg = await serverCfgDAL.updateById(serverCfg.id, data);
serverCfg = cfg;
Object.freeze(serverCfg);
return cfg;
};
@@ -62,6 +59,7 @@ export const superAdminServiceFactory = ({
ip,
userAgent
}: TAdminSignUpDTO) => {
const appCfg = getConfig();
const existingUser = await userDAL.findOne({ email });
if (existingUser) throw new BadRequestError({ name: "Admin sign up", message: "User already exist" });
@@ -95,7 +93,10 @@ export const superAdminServiceFactory = ({
);
return { user: newUser, enc: userEnc };
});
await orgService.createOrganization(userInfo.user.id, userInfo.user.email, "Admin Org");
const initialOrganizationName = appCfg.INITIAL_ORGANIZATION_NAME ?? "Admin Org";
await orgService.createOrganization(userInfo.user.id, userInfo.user.email, initialOrganizationName);
await updateServerCfg({ initialized: true });
const token = await authService.generateUserTokens({