mirror of
https://github.com/fosrl/pangolin.git
synced 2025-08-03 09:34:48 +02:00
Merge branch 'dev' into feat/internal-user-passkey-support
This commit is contained in:
commit
c9f5ffae42
24 changed files with 2522 additions and 367 deletions
179
server/routers/auth/completeTotpSetup.ts
Normal file
179
server/routers/auth/completeTotpSetup.ts
Normal 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;
|
||||
}
|
|
@ -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";
|
||||
|
|
|
@ -36,6 +36,7 @@ export type LoginResponse = {
|
|||
codeRequested?: boolean;
|
||||
emailVerificationRequired?: boolean;
|
||||
useSecurityKey?: boolean;
|
||||
twoFactorSetupRequired?: boolean;
|
||||
};
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
@ -127,6 +128,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 },
|
||||
|
@ -139,7 +151,7 @@ export async function login(
|
|||
|
||||
const validOTP = await verifyTotpCode(
|
||||
code,
|
||||
existingUser.twoFactorSecret!,
|
||||
existingUser.twoFactorSecret,
|
||||
existingUser.userId
|
||||
);
|
||||
|
||||
|
|
127
server/routers/auth/setupTotpSecret.ts
Normal file
127
server/routers/auth/setupTotpSecret.ts
Normal 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"
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
|
@ -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);
|
||||
|
||||
|
|
|
@ -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))
|
||||
|
|
|
@ -10,3 +10,4 @@ export * from "./adminRemoveUser";
|
|||
export * from "./listInvitations";
|
||||
export * from "./removeInvitation";
|
||||
export * from "./createOrgUser";
|
||||
export * from "./updateUser2FA";
|
||||
|
|
|
@ -49,7 +49,8 @@ async function queryUsers(orgId: string, limit: number, offset: number) {
|
|||
roleName: roles.name,
|
||||
isOwner: userOrgs.isOwner,
|
||||
idpName: idp.name,
|
||||
idpId: users.idpId
|
||||
idpId: users.idpId,
|
||||
twoFactorEnabled: users.twoFactorEnabled,
|
||||
})
|
||||
.from(users)
|
||||
.leftJoin(userOrgs, eq(users.userId, userOrgs.userId))
|
||||
|
|
151
server/routers/user/updateUser2FA.ts
Normal file
151
server/routers/user/updateUser2FA.ts
Normal 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")
|
||||
);
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue