mirror of
https://github.com/fosrl/pangolin.git
synced 2025-08-04 18:14:53 +02:00
server admin enforce 2fa per user
This commit is contained in:
parent
590296e64d
commit
915ccdc007
32 changed files with 1072 additions and 1123 deletions
|
@ -56,6 +56,8 @@ export enum ActionsEnum {
|
|||
// removeUserAction = "removeUserAction",
|
||||
// removeUserSite = "removeUserSite",
|
||||
getOrgUser = "getOrgUser",
|
||||
updateUser = "updateUser",
|
||||
getUser = "getUser",
|
||||
setResourcePassword = "setResourcePassword",
|
||||
setResourcePincode = "setResourcePincode",
|
||||
setResourceWhitelist = "setResourceWhitelist",
|
||||
|
|
|
@ -121,6 +121,7 @@ export const users = pgTable("user", {
|
|||
}),
|
||||
passwordHash: varchar("passwordHash"),
|
||||
twoFactorEnabled: boolean("twoFactorEnabled").notNull().default(false),
|
||||
twoFactorSetupRequested: boolean("twoFactorSetupRequested").default(false),
|
||||
twoFactorSecret: varchar("twoFactorSecret"),
|
||||
emailVerified: boolean("emailVerified").notNull().default(false),
|
||||
dateCreated: varchar("dateCreated").notNull(),
|
||||
|
|
|
@ -125,6 +125,9 @@ export const users = sqliteTable("user", {
|
|||
twoFactorEnabled: integer("twoFactorEnabled", { mode: "boolean" })
|
||||
.notNull()
|
||||
.default(false),
|
||||
twoFactorSetupRequested: integer("twoFactorSetupRequested", {
|
||||
mode: "boolean"
|
||||
}).default(false),
|
||||
twoFactorSecret: text("twoFactorSecret"),
|
||||
emailVerified: integer("emailVerified", { mode: "boolean" })
|
||||
.notNull()
|
||||
|
|
10
server/lib/totp.ts
Normal file
10
server/lib/totp.ts
Normal file
|
@ -0,0 +1,10 @@
|
|||
import { alphabet, generateRandomString } from "oslo/crypto";
|
||||
|
||||
export 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;
|
||||
}
|
|
@ -1,179 +0,0 @@
|
|||
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,8 +3,6 @@ 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";
|
||||
|
|
|
@ -21,10 +21,7 @@ import { UserType } from "@server/types/UserTypes";
|
|||
|
||||
export const loginBodySchema = z
|
||||
.object({
|
||||
email: z
|
||||
.string()
|
||||
.toLowerCase()
|
||||
.email(),
|
||||
email: z.string().toLowerCase().email(),
|
||||
password: z.string(),
|
||||
code: z.string().optional()
|
||||
})
|
||||
|
@ -38,8 +35,6 @@ export type LoginResponse = {
|
|||
twoFactorSetupRequired?: boolean;
|
||||
};
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export async function login(
|
||||
req: Request,
|
||||
res: Response,
|
||||
|
@ -110,18 +105,20 @@ 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 (
|
||||
existingUser.twoFactorSetupRequested &&
|
||||
!existingUser.twoFactorEnabled
|
||||
) {
|
||||
return response<LoginResponse>(res, {
|
||||
data: { twoFactorSetupRequired: true },
|
||||
success: true,
|
||||
error: false,
|
||||
message: "Two-factor authentication setup required",
|
||||
status: HttpCode.ACCEPTED
|
||||
});
|
||||
}
|
||||
|
||||
if (existingUser.twoFactorEnabled) {
|
||||
if (!code) {
|
||||
return response<{ codeRequested: boolean }>(res, {
|
||||
data: { codeRequested: true },
|
||||
|
@ -134,7 +131,7 @@ export async function login(
|
|||
|
||||
const validOTP = await verifyTotpCode(
|
||||
code,
|
||||
existingUser.twoFactorSecret,
|
||||
existingUser.twoFactorSecret!,
|
||||
existingUser.userId
|
||||
);
|
||||
|
||||
|
|
|
@ -7,16 +7,19 @@ import HttpCode from "@server/types/HttpCode";
|
|||
import { response } from "@server/lib";
|
||||
import { db } from "@server/db";
|
||||
import { User, users } from "@server/db";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { eq, and } from "drizzle-orm";
|
||||
import { createTOTPKeyURI } from "oslo/otp";
|
||||
import logger from "@server/logger";
|
||||
import { verifyPassword } from "@server/auth/password";
|
||||
import { unauthorized } from "@server/auth/unauthorizedResponse";
|
||||
import { UserType } from "@server/types/UserTypes";
|
||||
import { verifySession } from "@server/auth/sessions/verifySession";
|
||||
import config from "@server/lib/config";
|
||||
|
||||
export const requestTotpSecretBody = z
|
||||
.object({
|
||||
password: z.string()
|
||||
password: z.string(),
|
||||
email: z.string().email().optional()
|
||||
})
|
||||
.strict();
|
||||
|
||||
|
@ -43,9 +46,42 @@ export async function requestTotpSecret(
|
|||
);
|
||||
}
|
||||
|
||||
const { password } = parsedBody.data;
|
||||
const { password, email } = parsedBody.data;
|
||||
|
||||
const user = req.user as User;
|
||||
const { user: sessionUser, session: existingSession } = await verifySession(req);
|
||||
|
||||
let user: User | null = sessionUser;
|
||||
if (!existingSession) {
|
||||
if (!email) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
"Email is required for two-factor authentication setup"
|
||||
)
|
||||
);
|
||||
}
|
||||
const [res] = await db
|
||||
.select()
|
||||
.from(users)
|
||||
.where(
|
||||
and(eq(users.type, UserType.Internal), eq(users.email, email))
|
||||
);
|
||||
user = res;
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
if (config.getRawConfig().app.log_failed_attempts) {
|
||||
logger.info(
|
||||
`Username or password incorrect. Email: ${email}. IP: ${req.ip}.`
|
||||
);
|
||||
}
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.UNAUTHORIZED,
|
||||
"Username or password is incorrect"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if (user.type !== UserType.Internal) {
|
||||
return next(
|
||||
|
@ -57,7 +93,10 @@ export async function requestTotpSecret(
|
|||
}
|
||||
|
||||
try {
|
||||
const validPassword = await verifyPassword(password, user.passwordHash!);
|
||||
const validPassword = await verifyPassword(
|
||||
password,
|
||||
user.passwordHash!
|
||||
);
|
||||
if (!validPassword) {
|
||||
return next(unauthorized());
|
||||
}
|
||||
|
|
|
@ -1,127 +0,0 @@
|
|||
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"
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
|
@ -6,18 +6,22 @@ import HttpCode from "@server/types/HttpCode";
|
|||
import { response } from "@server/lib";
|
||||
import { db } from "@server/db";
|
||||
import { twoFactorBackupCodes, User, users } from "@server/db";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { alphabet, generateRandomString } from "oslo/crypto";
|
||||
import { hashPassword } from "@server/auth/password";
|
||||
import { eq, and } from "drizzle-orm";
|
||||
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";
|
||||
import { generateBackupCodes } from "@server/lib/totp";
|
||||
import { verifySession } from "@server/auth/sessions/verifySession";
|
||||
import { unauthorized } from "@server/auth/unauthorizedResponse";
|
||||
|
||||
export const verifyTotpBody = z
|
||||
.object({
|
||||
email: z.string().email().optional(),
|
||||
password: z.string().optional(),
|
||||
code: z.string()
|
||||
})
|
||||
.strict();
|
||||
|
@ -45,38 +49,83 @@ export async function verifyTotp(
|
|||
);
|
||||
}
|
||||
|
||||
const { code } = parsedBody.data;
|
||||
|
||||
const user = req.user as User;
|
||||
|
||||
if (user.type !== UserType.Internal) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
"Two-factor authentication is not supported for external users"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if (user.twoFactorEnabled) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
"Two-factor authentication is already enabled"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if (!user.twoFactorSecret) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
"User has not requested two-factor authentication"
|
||||
)
|
||||
);
|
||||
}
|
||||
const { code, email, password } = parsedBody.data;
|
||||
|
||||
try {
|
||||
const { user: sessionUser, session: existingSession } =
|
||||
await verifySession(req);
|
||||
|
||||
let user: User | null = sessionUser;
|
||||
if (!existingSession) {
|
||||
if (!email || !password) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
"Email and password are required for two-factor authentication"
|
||||
)
|
||||
);
|
||||
}
|
||||
const [res] = await db
|
||||
.select()
|
||||
.from(users)
|
||||
.where(
|
||||
and(
|
||||
eq(users.type, UserType.Internal),
|
||||
eq(users.email, email)
|
||||
)
|
||||
);
|
||||
user = res;
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
if (config.getRawConfig().app.log_failed_attempts) {
|
||||
logger.info(
|
||||
`Username or password incorrect. Email: ${email}. IP: ${req.ip}.`
|
||||
);
|
||||
}
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.UNAUTHORIZED,
|
||||
"Username or password is incorrect"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const validPassword = await verifyPassword(
|
||||
password,
|
||||
user.passwordHash!
|
||||
);
|
||||
if (!validPassword) {
|
||||
return next(unauthorized());
|
||||
}
|
||||
|
||||
if (user.type !== UserType.Internal) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
"Two-factor authentication is not supported for external users"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if (user.twoFactorEnabled) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
"Two-factor authentication is already enabled"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if (!user.twoFactorSecret) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
"User has not requested two-factor authentication"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const valid = await verifyTotpCode(
|
||||
code,
|
||||
user.twoFactorSecret,
|
||||
|
@ -89,7 +138,9 @@ export async function verifyTotp(
|
|||
await db.transaction(async (trx) => {
|
||||
await trx
|
||||
.update(users)
|
||||
.set({ twoFactorEnabled: true })
|
||||
.set({
|
||||
twoFactorEnabled: true
|
||||
})
|
||||
.where(eq(users.userId, user.userId));
|
||||
|
||||
const backupCodes = await generateBackupCodes();
|
||||
|
@ -153,12 +204,3 @@ export async function verifyTotp(
|
|||
);
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
|
|
@ -476,6 +476,7 @@ unauthenticated.get("/resource/:resourceId/auth", resource.getResourceAuthInfo);
|
|||
unauthenticated.get("/user", verifySessionMiddleware, user.getUser);
|
||||
|
||||
authenticated.get("/users", verifyUserIsServerAdmin, user.adminListUsers);
|
||||
authenticated.get("/user/:userId", verifyUserIsServerAdmin, user.adminGetUser);
|
||||
authenticated.delete(
|
||||
"/user/:userId",
|
||||
verifyUserIsServerAdmin,
|
||||
|
@ -490,11 +491,10 @@ authenticated.put(
|
|||
);
|
||||
|
||||
authenticated.get("/org/:orgId/user/:userId", verifyOrgAccess, user.getOrgUser);
|
||||
authenticated.patch(
|
||||
"/org/:orgId/user/:userId/2fa",
|
||||
verifyOrgAccess,
|
||||
verifyUserAccess,
|
||||
verifyUserHasAction(ActionsEnum.getOrgUser),
|
||||
|
||||
authenticated.post(
|
||||
"/user/:userId/2fa",
|
||||
verifyUserIsServerAdmin,
|
||||
user.updateUser2FA
|
||||
);
|
||||
|
||||
|
@ -719,14 +719,8 @@ authRouter.post("/login", auth.login);
|
|||
authRouter.post("/logout", auth.logout);
|
||||
authRouter.post("/newt/get-token", getToken);
|
||||
|
||||
authRouter.post("/2fa/enable", verifySessionUserMiddleware, auth.verifyTotp);
|
||||
authRouter.post(
|
||||
"/2fa/request",
|
||||
verifySessionUserMiddleware,
|
||||
auth.requestTotpSecret
|
||||
);
|
||||
authRouter.post("/2fa/setup", auth.setupTotpSecret);
|
||||
authRouter.post("/2fa/complete-setup", auth.completeTotpSetup);
|
||||
authRouter.post("/2fa/enable", auth.verifyTotp);
|
||||
authRouter.post("/2fa/request", auth.requestTotpSecret);
|
||||
authRouter.post("/2fa/disable", verifySessionUserMiddleware, auth.disable2fa);
|
||||
authRouter.post("/verify-email", verifySessionMiddleware, auth.verifyEmail);
|
||||
|
||||
|
|
|
@ -381,6 +381,20 @@ authenticated.get(
|
|||
user.getOrgUser
|
||||
);
|
||||
|
||||
authenticated.post(
|
||||
"/user/:userId/2fa",
|
||||
verifyApiKeyIsRoot,
|
||||
verifyApiKeyHasAction(ActionsEnum.updateUser),
|
||||
user.updateUser2FA
|
||||
);
|
||||
|
||||
authenticated.get(
|
||||
"/user/:userId",
|
||||
verifyApiKeyIsRoot,
|
||||
verifyApiKeyHasAction(ActionsEnum.getUser),
|
||||
user.adminGetUser
|
||||
);
|
||||
|
||||
authenticated.get(
|
||||
"/org/:orgId/users",
|
||||
verifyApiKeyOrgAccess,
|
||||
|
|
94
server/routers/user/adminGetUser.ts
Normal file
94
server/routers/user/adminGetUser.ts
Normal 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")
|
||||
);
|
||||
}
|
||||
}
|
|
@ -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))
|
||||
|
|
|
@ -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")
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -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";
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue