server admin enforce 2fa per user

This commit is contained in:
miloschwartz
2025-07-13 21:43:09 -07:00
parent 590296e64d
commit 915ccdc007
32 changed files with 1072 additions and 1123 deletions

View File

@@ -0,0 +1,94 @@
import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import { db } from "@server/db";
import { idp, users } from "@server/db";
import { eq } from "drizzle-orm";
import response from "@server/lib/response";
import HttpCode from "@server/types/HttpCode";
import createHttpError from "http-errors";
import logger from "@server/logger";
import { OpenAPITags, registry } from "@server/openApi";
const adminGetUserSchema = z
.object({
userId: z.string().min(1)
})
.strict();
registry.registerPath({
method: "get",
path: "/user/{userId}",
description: "Get a user by ID.",
tags: [OpenAPITags.User],
request: {
params: adminGetUserSchema
},
responses: {}
});
async function queryUser(userId: string) {
const [user] = await db
.select({
userId: users.userId,
email: users.email,
username: users.username,
name: users.name,
type: users.type,
twoFactorEnabled: users.twoFactorEnabled,
twoFactorSetupRequested: users.twoFactorSetupRequested,
emailVerified: users.emailVerified,
serverAdmin: users.serverAdmin,
idpName: idp.name,
idpId: users.idpId,
dateCreated: users.dateCreated
})
.from(users)
.leftJoin(idp, eq(users.idpId, idp.idpId))
.where(eq(users.userId, userId))
.limit(1);
return user;
}
export type AdminGetUserResponse = NonNullable<
Awaited<ReturnType<typeof queryUser>>
>;
export async function adminGetUser(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
try {
const parsedParams = adminGetUserSchema.safeParse(req.params);
if (!parsedParams.success) {
return next(
createHttpError(HttpCode.BAD_REQUEST, "Invalid user ID")
);
}
const { userId } = parsedParams.data;
const user = await queryUser(userId);
if (!user) {
return next(
createHttpError(
HttpCode.NOT_FOUND,
`User with ID ${userId} not found`
)
);
}
return response<AdminGetUserResponse>(res, {
data: user,
success: true,
error: false,
message: "User retrieved successfully",
status: HttpCode.OK
});
} catch (error) {
logger.error(error);
return next(
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
);
}
}

View File

@@ -37,7 +37,9 @@ async function queryUsers(limit: number, offset: number) {
serverAdmin: users.serverAdmin,
type: users.type,
idpName: idp.name,
idpId: users.idpId
idpId: users.idpId,
twoFactorEnabled: users.twoFactorEnabled,
twoFactorSetupRequested: users.twoFactorSetupRequested
})
.from(users)
.leftJoin(idp, eq(users.idpId, idp.idpId))

View File

@@ -8,32 +8,30 @@ import HttpCode from "@server/types/HttpCode";
import createHttpError from "http-errors";
import logger from "@server/logger";
import { fromError } from "zod-validation-error";
import { ActionsEnum, checkUserActionPermission } from "@server/auth/actions";
import { OpenAPITags, registry } from "@server/openApi";
const updateUser2FAParamsSchema = z
.object({
userId: z.string(),
orgId: z.string()
userId: z.string()
})
.strict();
const updateUser2FABodySchema = z
.object({
twoFactorEnabled: z.boolean()
twoFactorSetupRequested: z.boolean()
})
.strict();
export type UpdateUser2FAResponse = {
userId: string;
twoFactorEnabled: boolean;
twoFactorRequested: boolean;
};
registry.registerPath({
method: "patch",
path: "/org/{orgId}/user/{userId}/2fa",
description: "Update a user's 2FA status within an organization.",
tags: [OpenAPITags.Org, OpenAPITags.User],
method: "post",
path: "/user/{userId}/2fa",
description: "Update a user's 2FA status.",
tags: [OpenAPITags.User],
request: {
params: updateUser2FAParamsSchema,
body: {
@@ -73,73 +71,57 @@ export async function updateUser2FA(
);
}
const { userId, orgId } = parsedParams.data;
const { twoFactorEnabled } = parsedBody.data;
if (!req.userOrg) {
return next(
createHttpError(
HttpCode.FORBIDDEN,
"You do not have access to this organization"
)
);
}
// Check if user has permission to update other users' 2FA
const hasPermission = await checkUserActionPermission(
ActionsEnum.getOrgUser,
req
);
if (!hasPermission) {
return next(
createHttpError(
HttpCode.FORBIDDEN,
"User does not have permission to update other users' 2FA settings"
)
);
}
const { userId } = parsedParams.data;
const { twoFactorSetupRequested } = parsedBody.data;
// Verify the user exists in the organization
const existingUser = await db
.select()
.from(userOrgs)
.where(and(eq(userOrgs.userId, userId), eq(userOrgs.orgId, orgId)))
.from(users)
.where(eq(users.userId, userId))
.limit(1);
if (existingUser.length === 0) {
return next(createHttpError(HttpCode.NOT_FOUND, "User not found"));
}
if (existingUser[0].type !== "internal") {
return next(
createHttpError(
HttpCode.NOT_FOUND,
"User not found or does not belong to the specified organization"
HttpCode.BAD_REQUEST,
"Two-factor authentication is not supported for external users"
)
);
}
// Update the user's 2FA status
const updatedUser = await db
.update(users)
.set({
twoFactorEnabled,
// If disabling 2FA, also clear the secret
twoFactorSecret: twoFactorEnabled ? undefined : null
})
.where(eq(users.userId, userId))
.returning({ userId: users.userId, twoFactorEnabled: users.twoFactorEnabled });
logger.debug(`Updating 2FA for user ${userId} to ${twoFactorSetupRequested}`);
if (updatedUser.length === 0) {
return next(
createHttpError(
HttpCode.NOT_FOUND,
"User not found"
)
);
if (twoFactorSetupRequested) {
await db
.update(users)
.set({
twoFactorSetupRequested: true,
})
.where(eq(users.userId, userId));
} else {
await db
.update(users)
.set({
twoFactorSetupRequested: false,
twoFactorEnabled: false,
twoFactorSecret: null
})
.where(eq(users.userId, userId));
}
return response<UpdateUser2FAResponse>(res, {
data: updatedUser[0],
data: {
userId: existingUser[0].userId,
twoFactorRequested: twoFactorSetupRequested
},
success: true,
error: false,
message: `2FA ${twoFactorEnabled ? 'enabled' : 'disabled'} for user successfully`,
message: `2FA ${twoFactorSetupRequested ? "enabled" : "disabled"} for user successfully`,
status: HttpCode.OK
});
} catch (error) {
@@ -148,4 +130,4 @@ export async function updateUser2FA(
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
);
}
}
}

View File

@@ -7,7 +7,9 @@ export * from "./acceptInvite";
export * from "./getOrgUser";
export * from "./adminListUsers";
export * from "./adminRemoveUser";
export * from "./adminGetUser";
export * from "./listInvitations";
export * from "./removeInvitation";
export * from "./createOrgUser";
export * from "./updateUser2FA";
export * from "./adminUpdateUser2FA";
export * from "./adminGetUser";