pangolin/server/routers/user/adminListUsers.ts
2026-11-20 15:31:30 -05:00

322 lines
9.7 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import { db, idp, users } from "@server/db";
import response from "@server/lib/response";
import HttpCode from "@server/types/HttpCode";
import createHttpError from "http-errors";
import { and, asc, desc, eq, like, or, sql, type SQL } from "drizzle-orm";
import logger from "@server/logger";
import { fromZodError } from "zod-validation-error";
import { OpenAPITags, registry } from "@server/openApi";
import {
PaginationSchema,
LimitOffsetPaginationSchema
} from "@server/lib/openapi/pagination";
import { createApiSuccessResponses } from "@server/lib/openapi/createApiResponseSchema";
import type { PaginatedResponse } from "@server/types/Pagination";
import { UserType } from "@server/types/UserTypes";
import { createSelectSchema } from "drizzle-zod";
const listUsersSchema = z.strictObject({
pageSize: z.coerce
.number<string>()
.int()
.positive()
.optional()
.catch(20)
.default(20)
.openapi({
type: "integer",
default: 20,
description: "Number of items per page"
}),
page: z.coerce
.number<string>()
.int()
.min(0)
.optional()
.catch(1)
.default(1)
.openapi({
type: "integer",
default: 1,
description: "Page number to retrieve"
}),
query: z.string().optional(),
sort_by: z
.enum(["username", "email", "name"])
.optional()
.catch(undefined)
.openapi({
type: "string",
enum: ["username", "email", "name"],
description: "Field to sort by"
}),
order: z
.enum(["asc", "desc"])
.optional()
.default("asc")
.catch("asc")
.openapi({
type: "string",
enum: ["asc", "desc"],
default: "asc",
description: "Sort order"
}),
idp_id: z
.preprocess(
(val) => {
if (val === undefined || val === null || val === "") {
return undefined;
}
if (val === "internal") {
return "internal";
}
if (typeof val === "string" && /^\d+$/.test(val)) {
return parseInt(val, 10);
}
return undefined;
},
z
.union([z.literal("internal"), z.number().int().positive()])
.optional()
)
.openapi({
description:
'Filter by identity provider id, or "internal" for internal users'
}),
two_factor: z
.enum(["true", "false"])
.transform((v) => v === "true")
.optional()
.catch(undefined)
.openapi({
type: "boolean",
description:
"Filter by 2FA state matching: enabled if twoFactorEnabled or twoFactorSetupRequested"
}),
server_admin: z
.enum(["true", "false"])
.transform((v) => v === "true")
.optional()
.catch(undefined)
.openapi({
type: "boolean",
description: "Filter by server admin status"
})
});
function queryUsersBase() {
return db
.select({
id: users.userId,
email: users.email,
username: users.username,
name: users.name,
dateCreated: users.dateCreated,
serverAdmin: users.serverAdmin,
type: users.type,
idpName: idp.name,
idpId: users.idpId,
twoFactorEnabled: users.twoFactorEnabled,
twoFactorSetupRequested: users.twoFactorSetupRequested
})
.from(users)
.leftJoin(idp, eq(users.idpId, idp.idpId));
}
/** Row shape returned by `queryUsersBase()` (matches selected columns + join). */
export type AdminListUserRow = AdminListUsersResponse["users"][number];
export type AdminListUsersResponse = z.infer<
typeof AdminListUsersResponseDataSchema
>;
const AdminUserListItemSchema = createSelectSchema(users, {
email: (s) => s.openapi({ description: "Email of the user." }),
username: (s) => s.openapi({ description: "Username of the user." }),
name: (s) => s.openapi({ description: "Display name of the user." }),
type: (s) =>
s.openapi({
description:
"How the user signs in, either an internal account or an identity provider type (e.g. oidc)."
}),
twoFactorEnabled: (s) =>
s.openapi({
description:
"Whether the user has two-factor authentication enabled."
}),
twoFactorSetupRequested: (s) =>
s.openapi({
description:
"Whether an admin has asked the user to set up two-factor authentication."
}),
serverAdmin: (s) =>
s.openapi({ description: "Whether the user is a server admin." }),
idpId: (s) =>
s.openapi({
description:
"ID of the identity provider the user belongs to. Null for internal users."
}),
dateCreated: (s) =>
s.openapi({ description: "ISO timestamp when the user was created." })
})
.pick({
email: true,
username: true,
name: true,
type: true,
twoFactorEnabled: true,
twoFactorSetupRequested: true,
serverAdmin: true,
idpId: true,
dateCreated: true
})
.extend({
idpName: z.string().nullable().openapi({
description:
"Name of the identity provider the user belongs to. Null for internal users."
}),
id: z.string().openapi({ description: "ID of the user." })
});
const AdminListUsersResponseDataSchema = z.object({
users: z.array(AdminUserListItemSchema),
pagination: PaginationSchema
});
registry.registerPath({
method: "get",
path: "/users",
description: "List non–server-admin users (server admin).",
tags: [OpenAPITags.User],
request: {
query: listUsersSchema
},
responses: createApiSuccessResponses(AdminListUsersResponseDataSchema)
});
export async function adminListUsers(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
try {
const parsedQuery = listUsersSchema.safeParse(req.query);
if (!parsedQuery.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromZodError(parsedQuery.error)
)
);
}
const {
page,
pageSize,
query,
sort_by,
order,
idp_id,
two_factor: twoFactorFilter,
server_admin: serverAdminFilter
} = parsedQuery.data;
if (typeof idp_id === "number") {
const idpOk = await db
.select({ one: sql`1` })
.from(idp)
.where(eq(idp.idpId, idp_id))
.limit(1);
if (idpOk.length === 0) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"idp_id does not exist"
)
);
}
}
const conditions: Array<SQL<unknown> | undefined> = [];
if (query) {
const q = "%" + query.toLowerCase() + "%";
conditions.push(
or(
like(sql`LOWER(${users.username})`, q),
like(sql`LOWER(${users.email})`, q),
like(sql`LOWER(${users.name})`, q)
)!
);
}
if (idp_id === "internal") {
conditions.push(eq(users.type, UserType.Internal));
} else if (typeof idp_id === "number") {
conditions.push(eq(users.idpId, idp_id));
}
if (typeof twoFactorFilter === "boolean") {
if (twoFactorFilter) {
conditions.push(
or(
eq(users.twoFactorEnabled, true),
eq(users.twoFactorSetupRequested, true)
)!
);
} else {
conditions.push(
and(
eq(users.twoFactorEnabled, false),
eq(users.twoFactorSetupRequested, false)
)!
);
}
}
if (typeof serverAdminFilter === "boolean") {
conditions.push(eq(users.serverAdmin, serverAdminFilter));
}
const whereClause = and(...conditions);
const countQuery = db.$count(
queryUsersBase().where(whereClause).as("filtered_admin_users")
);
const userListQuery = queryUsersBase()
.where(whereClause)
.limit(pageSize)
.offset(pageSize * (page - 1))
.orderBy(
sort_by
? order === "asc"
? asc(users[sort_by])
: desc(users[sort_by])
: asc(users.username)
);
const [total, rows] = await Promise.all([countQuery, userListQuery]);
return response<AdminListUsersResponse>(res, {
data: {
users: rows,
pagination: {
total,
page,
pageSize
}
},
success: true,
error: false,
message: "Users retrieved successfully",
status: HttpCode.OK
});
} catch (error) {
logger.error(error);
return next(
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
);
}
}