Admins can enable 2FA

Added the feature for admins to force 2FA on accounts. The next time the
user logs in they will have to setup 2FA on their account.
This commit is contained in:
J. Newing 2025-07-07 16:02:42 -04:00
parent f11fa4f32d
commit 2a6298e9eb
12 changed files with 843 additions and 20 deletions

View file

@ -0,0 +1,179 @@
import { Request, Response, NextFunction } from "express";
import createHttpError from "http-errors";
import { z } from "zod";
import { fromError } from "zod-validation-error";
import HttpCode from "@server/types/HttpCode";
import { response } from "@server/lib";
import { db } from "@server/db";
import { twoFactorBackupCodes, users } from "@server/db";
import { eq, and } from "drizzle-orm";
import { alphabet, generateRandomString } from "oslo/crypto";
import { hashPassword, verifyPassword } from "@server/auth/password";
import { verifyTotpCode } from "@server/auth/totp";
import logger from "@server/logger";
import { sendEmail } from "@server/emails";
import TwoFactorAuthNotification from "@server/emails/templates/TwoFactorAuthNotification";
import config from "@server/lib/config";
import { UserType } from "@server/types/UserTypes";
export const completeTotpSetupBody = z
.object({
email: z.string().email(),
password: z.string(),
code: z.string()
})
.strict();
export type CompleteTotpSetupBody = z.infer<typeof completeTotpSetupBody>;
export type CompleteTotpSetupResponse = {
valid: boolean;
backupCodes?: string[];
};
export async function completeTotpSetup(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
const parsedBody = completeTotpSetupBody.safeParse(req.body);
if (!parsedBody.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedBody.error).toString()
)
);
}
const { email, password, code } = parsedBody.data;
try {
// Find the user by email
const [user] = await db
.select()
.from(users)
.where(and(eq(users.email, email), eq(users.type, UserType.Internal)))
.limit(1);
if (!user) {
return next(
createHttpError(
HttpCode.UNAUTHORIZED,
"Invalid credentials"
)
);
}
// Verify password
const validPassword = await verifyPassword(password, user.passwordHash!);
if (!validPassword) {
return next(
createHttpError(
HttpCode.UNAUTHORIZED,
"Invalid credentials"
)
);
}
// Check if 2FA is enabled but not yet completed
if (!user.twoFactorEnabled) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"Two-factor authentication is not required for this user"
)
);
}
if (!user.twoFactorSecret) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"User has not started two-factor authentication setup"
)
);
}
// Verify the TOTP code
const valid = await verifyTotpCode(
code,
user.twoFactorSecret,
user.userId
);
if (!valid) {
if (config.getRawConfig().app.log_failed_attempts) {
logger.info(
`Two-factor authentication code is incorrect. Email: ${email}. IP: ${req.ip}.`
);
}
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"Invalid two-factor authentication code"
)
);
}
// Generate backup codes and finalize setup
let codes: string[] = [];
await db.transaction(async (trx) => {
// Note: We don't set twoFactorEnabled to true here because it's already true
// We just need to generate backup codes since the setup is now complete
const backupCodes = await generateBackupCodes();
codes = backupCodes;
for (const code of backupCodes) {
const hash = await hashPassword(code);
await trx.insert(twoFactorBackupCodes).values({
userId: user.userId,
codeHash: hash
});
}
});
// Send notification email
sendEmail(
TwoFactorAuthNotification({
email: user.email!,
enabled: true
}),
{
to: user.email!,
from: config.getRawConfig().email?.no_reply,
subject: "Two-factor authentication enabled"
}
);
return response<CompleteTotpSetupResponse>(res, {
data: {
valid: true,
backupCodes: codes
},
success: true,
error: false,
message: "Two-factor authentication setup completed successfully",
status: HttpCode.OK
});
} catch (error) {
logger.error(error);
return next(
createHttpError(
HttpCode.INTERNAL_SERVER_ERROR,
"Failed to complete two-factor authentication setup"
)
);
}
}
async function generateBackupCodes(): Promise<string[]> {
const codes = [];
for (let i = 0; i < 10; i++) {
const code = generateRandomString(6, alphabet("0-9", "A-Z", "a-z"));
codes.push(code);
}
return codes;
}

View file

@ -3,6 +3,8 @@ export * from "./signup";
export * from "./logout";
export * from "./verifyTotp";
export * from "./requestTotpSecret";
export * from "./setupTotpSecret";
export * from "./completeTotpSetup";
export * from "./disable2fa";
export * from "./verifyEmail";
export * from "./requestEmailVerificationCode";

View file

@ -35,6 +35,7 @@ export type LoginBody = z.infer<typeof loginBodySchema>;
export type LoginResponse = {
codeRequested?: boolean;
emailVerificationRequired?: boolean;
twoFactorSetupRequired?: boolean;
};
export const dynamic = "force-dynamic";
@ -110,6 +111,17 @@ export async function login(
}
if (existingUser.twoFactorEnabled) {
// If 2FA is enabled but no secret exists, force setup
if (!existingUser.twoFactorSecret) {
return response<LoginResponse>(res, {
data: { twoFactorSetupRequired: true },
success: true,
error: false,
message: "Two-factor authentication setup required",
status: HttpCode.ACCEPTED
});
}
if (!code) {
return response<{ codeRequested: boolean }>(res, {
data: { codeRequested: true },
@ -122,7 +134,7 @@ export async function login(
const validOTP = await verifyTotpCode(
code,
existingUser.twoFactorSecret!,
existingUser.twoFactorSecret,
existingUser.userId
);

View file

@ -0,0 +1,127 @@
import { Request, Response, NextFunction } from "express";
import createHttpError from "http-errors";
import { z } from "zod";
import { fromError } from "zod-validation-error";
import { encodeHex } from "oslo/encoding";
import HttpCode from "@server/types/HttpCode";
import { response } from "@server/lib";
import { db } from "@server/db";
import { User, users } from "@server/db";
import { eq, and } from "drizzle-orm";
import { createTOTPKeyURI } from "oslo/otp";
import logger from "@server/logger";
import { verifyPassword } from "@server/auth/password";
import { UserType } from "@server/types/UserTypes";
export const setupTotpSecretBody = z
.object({
email: z.string().email(),
password: z.string()
})
.strict();
export type SetupTotpSecretBody = z.infer<typeof setupTotpSecretBody>;
export type SetupTotpSecretResponse = {
secret: string;
uri: string;
};
export async function setupTotpSecret(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
const parsedBody = setupTotpSecretBody.safeParse(req.body);
if (!parsedBody.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedBody.error).toString()
)
);
}
const { email, password } = parsedBody.data;
try {
// Find the user by email
const [user] = await db
.select()
.from(users)
.where(and(eq(users.email, email), eq(users.type, UserType.Internal)))
.limit(1);
if (!user) {
return next(
createHttpError(
HttpCode.UNAUTHORIZED,
"Invalid credentials"
)
);
}
// Verify password
const validPassword = await verifyPassword(password, user.passwordHash!);
if (!validPassword) {
return next(
createHttpError(
HttpCode.UNAUTHORIZED,
"Invalid credentials"
)
);
}
// Check if 2FA is enabled but no secret exists (forced setup scenario)
if (!user.twoFactorEnabled) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"Two-factor authentication is not required for this user"
)
);
}
if (user.twoFactorSecret) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"User has already completed two-factor authentication setup"
)
);
}
// Generate new TOTP secret
const hex = crypto.getRandomValues(new Uint8Array(20));
const secret = encodeHex(hex);
const uri = createTOTPKeyURI("Pangolin", user.email!, hex);
// Save the secret to the database
await db
.update(users)
.set({
twoFactorSecret: secret
})
.where(eq(users.userId, user.userId));
return response<SetupTotpSecretResponse>(res, {
data: {
secret,
uri
},
success: true,
error: false,
message: "TOTP secret generated successfully",
status: HttpCode.OK
});
} catch (error) {
logger.error(error);
return next(
createHttpError(
HttpCode.INTERNAL_SERVER_ERROR,
"Failed to generate TOTP secret"
)
);
}
}

View file

@ -490,6 +490,13 @@ authenticated.put(
);
authenticated.get("/org/:orgId/user/:userId", verifyOrgAccess, user.getOrgUser);
authenticated.patch(
"/org/:orgId/user/:userId/2fa",
verifyOrgAccess,
verifyUserAccess,
verifyUserHasAction(ActionsEnum.getOrgUser),
user.updateUser2FA
);
authenticated.get(
"/org/:orgId/users",
@ -718,6 +725,8 @@ authRouter.post(
verifySessionUserMiddleware,
auth.requestTotpSecret
);
authRouter.post("/2fa/setup", auth.setupTotpSecret);
authRouter.post("/2fa/complete-setup", auth.completeTotpSetup);
authRouter.post("/2fa/disable", verifySessionUserMiddleware, auth.disable2fa);
authRouter.post("/verify-email", verifySessionMiddleware, auth.verifyEmail);

View file

@ -23,7 +23,8 @@ async function queryUser(orgId: string, userId: string) {
roleId: userOrgs.roleId,
roleName: roles.name,
isOwner: userOrgs.isOwner,
isAdmin: roles.isAdmin
isAdmin: roles.isAdmin,
twoFactorEnabled: users.twoFactorEnabled,
})
.from(userOrgs)
.leftJoin(roles, eq(userOrgs.roleId, roles.roleId))

View file

@ -10,3 +10,4 @@ export * from "./adminRemoveUser";
export * from "./listInvitations";
export * from "./removeInvitation";
export * from "./createOrgUser";
export * from "./updateUser2FA";

View file

@ -0,0 +1,151 @@
import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import { db } from "@server/db";
import { users, userOrgs } from "@server/db";
import { eq, and } 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 { 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()
})
.strict();
const updateUser2FABodySchema = z
.object({
twoFactorEnabled: z.boolean()
})
.strict();
export type UpdateUser2FAResponse = {
userId: string;
twoFactorEnabled: 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],
request: {
params: updateUser2FAParamsSchema,
body: {
content: {
"application/json": {
schema: updateUser2FABodySchema
}
}
}
},
responses: {}
});
export async function updateUser2FA(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
try {
const parsedParams = updateUser2FAParamsSchema.safeParse(req.params);
if (!parsedParams.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedParams.error).toString()
)
);
}
const parsedBody = updateUser2FABodySchema.safeParse(req.body);
if (!parsedBody.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedBody.error).toString()
)
);
}
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"
)
);
}
// Verify the user exists in the organization
const existingUser = await db
.select()
.from(userOrgs)
.where(and(eq(userOrgs.userId, userId), eq(userOrgs.orgId, orgId)))
.limit(1);
if (existingUser.length === 0) {
return next(
createHttpError(
HttpCode.NOT_FOUND,
"User not found or does not belong to the specified organization"
)
);
}
// 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 });
if (updatedUser.length === 0) {
return next(
createHttpError(
HttpCode.NOT_FOUND,
"User not found"
)
);
}
return response<UpdateUser2FAResponse>(res, {
data: updatedUser[0],
success: true,
error: false,
message: `2FA ${twoFactorEnabled ? 'enabled' : 'disabled'} for user successfully`,
status: HttpCode.OK
});
} catch (error) {
logger.error(error);
return next(
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
);
}
}