fosrl.pangolin/server/routers/resource/getResourceAuthInfo.ts

97 lines
2.8 KiB
TypeScript
Raw Normal View History

2024-11-17 23:24:30 -05:00
import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import { db } from "@server/db";
import {
resourcePassword,
resourcePincode,
resources,
} from "@server/db/schema";
import { eq } from "drizzle-orm";
import response from "@server/utils/response";
import HttpCode from "@server/types/HttpCode";
import createHttpError from "http-errors";
import { fromError } from "zod-validation-error";
const getResourceAuthInfoSchema = z.object({
resourceId: z.string().transform(Number).pipe(z.number().int().positive()),
});
export type GetResourceAuthInfoResponse = {
resourceId: number;
resourceName: string;
password: boolean;
pincode: boolean;
sso: boolean;
blockAccess: boolean;
2024-11-23 16:36:07 -05:00
url: string;
2024-11-17 23:24:30 -05:00
};
export async function getResourceAuthInfo(
req: Request,
res: Response,
2024-11-23 16:36:07 -05:00
next: NextFunction,
2024-11-17 23:24:30 -05:00
): Promise<any> {
try {
const parsedParams = getResourceAuthInfoSchema.safeParse(req.params);
if (!parsedParams.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
2024-11-23 16:36:07 -05:00
fromError(parsedParams.error).toString(),
),
2024-11-17 23:24:30 -05:00
);
}
const { resourceId } = parsedParams.data;
const [result] = await db
.select()
.from(resources)
.leftJoin(
resourcePincode,
2024-11-23 16:36:07 -05:00
eq(resourcePincode.resourceId, resources.resourceId),
2024-11-17 23:24:30 -05:00
)
.leftJoin(
resourcePassword,
2024-11-23 16:36:07 -05:00
eq(resourcePassword.resourceId, resources.resourceId),
2024-11-17 23:24:30 -05:00
)
.where(eq(resources.resourceId, resourceId))
.limit(1);
const resource = result?.resources;
const pincode = result?.resourcePincode;
const password = result?.resourcePassword;
2024-11-23 16:36:07 -05:00
const url = `${resource.ssl ? "https" : "http"}://${resource.fullDomain}`;
2024-11-17 23:24:30 -05:00
if (!resource) {
return next(
2024-11-23 16:36:07 -05:00
createHttpError(HttpCode.NOT_FOUND, "Resource not found"),
2024-11-17 23:24:30 -05:00
);
}
return response<GetResourceAuthInfoResponse>(res, {
data: {
resourceId: resource.resourceId,
resourceName: resource.name,
password: password !== null,
pincode: pincode !== null,
sso: resource.sso,
blockAccess: resource.blockAccess,
2024-11-23 16:36:07 -05:00
url,
2024-11-17 23:24:30 -05:00
},
success: true,
error: false,
message: "Resource auth info retrieved successfully",
status: HttpCode.OK,
});
} catch (error) {
return next(
2024-11-23 16:36:07 -05:00
createHttpError(
HttpCode.INTERNAL_SERVER_ERROR,
"An error occurred",
),
2024-11-17 23:24:30 -05:00
);
}
}