yuh and so it beginzzzzz
This commit is contained in:
@@ -11,22 +11,50 @@ import type { ServerError } from "$lib/utils/data.types";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { z } from "zod";
|
||||
import { createTRPCRouter, protectedProcedure } from "../t";
|
||||
import { env } from "$env/dynamic/private";
|
||||
import { logger } from "$lib/server/logger";
|
||||
import fetch from "node-fetch";
|
||||
|
||||
|
||||
export const apiAuthRouter = createTRPCRouter({
|
||||
getCaptcha: protectedProcedure.mutation(async () => {
|
||||
const scrapingbeeApiKey = env.SCRAPINGBEE_API_KEY;
|
||||
|
||||
try {
|
||||
const uuid = getUUID();
|
||||
const res = await fetch(`${constants.PROXY_API_URL}/verify/image?uuid=${uuid}`, {
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
});
|
||||
const bloob = await res.blob();
|
||||
const imageBuffer = Buffer.from(await bloob.arrayBuffer());
|
||||
const targetUrl = `${constants.SCRAP_API_URL}/verify/image?uuid=${uuid}`;
|
||||
|
||||
logger.info(`[getCaptcha] Fetching captcha image for uuid: ${uuid}`);
|
||||
|
||||
// Build ScrapingBee API URL with params
|
||||
const scrapingbeeUrl = new URL("https://app.scrapingbee.com/api/v1");
|
||||
scrapingbeeUrl.searchParams.set("api_key", scrapingbeeApiKey);
|
||||
scrapingbeeUrl.searchParams.set("url", targetUrl);
|
||||
scrapingbeeUrl.searchParams.set("render_js", "false");
|
||||
scrapingbeeUrl.searchParams.set("block_resources", "false");
|
||||
|
||||
const res = await fetch(scrapingbeeUrl.toString());
|
||||
|
||||
if (!res.ok || res.status !== 200) {
|
||||
// Clone response before reading to avoid consuming body
|
||||
const clonedRes = res.clone();
|
||||
const errorText = await clonedRes.text().catch(() => "Unknown error");
|
||||
logger.error(`[getCaptcha] ScrapingBee error ${res.status}: ${errorText.substring(0, 200)}`);
|
||||
throw new TRPCError({
|
||||
code: "INTERNAL_SERVER_ERROR",
|
||||
message: `Failed to fetch captcha image: ${res.status}`,
|
||||
});
|
||||
}
|
||||
|
||||
// Read the response as arrayBuffer (recommended method)
|
||||
const arrayBuffer = await res.arrayBuffer();
|
||||
const imageBuffer = Buffer.from(arrayBuffer);
|
||||
const base64String = imageBuffer.toString("base64");
|
||||
|
||||
logger.info(`[getCaptcha] Successfully fetched captcha image for uuid: ${uuid}, size: ${imageBuffer.length} bytes`);
|
||||
return { id: uuid, image: base64String };
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
logger.error("[getCaptcha] Error getting captcha image", err);
|
||||
throw new TRPCError({
|
||||
code: "INTERNAL_SERVER_ERROR",
|
||||
message: "Error getting captcha image.",
|
||||
@@ -43,15 +71,15 @@ export const apiAuthRouter = createTRPCRouter({
|
||||
}),
|
||||
)
|
||||
.mutation(async ({ input }) => {
|
||||
console.log("[=] Getting new session... ", input);
|
||||
logger.info(`[getNewSession] Getting new session for userId: ${input.userId || "random"}`);
|
||||
try {
|
||||
const { captchaId, captchaAnswer } = input;
|
||||
let { userId, userType, password } = await dbApiUser.getRandomDistributor();
|
||||
|
||||
if (input.userId) {
|
||||
let _user = await dbApiUser.getUserById(input.userId);
|
||||
console.log("[=] User :: ", _user?.userId);
|
||||
if (!_user) {
|
||||
logger.warn(`[getNewSession] User not found: ${input.userId}`);
|
||||
return {
|
||||
success: false,
|
||||
errors: [{ message: "User not found." }],
|
||||
@@ -60,8 +88,10 @@ export const apiAuthRouter = createTRPCRouter({
|
||||
userId = _user.userId;
|
||||
userType = _user.userType;
|
||||
password = _user.password;
|
||||
logger.info(`[getNewSession] Using specific user: ${userId}`);
|
||||
}
|
||||
console.log(`[=] Getting session token for user ${userId}...`);
|
||||
|
||||
logger.info(`[getNewSession] Getting session token for user ${userId}`);
|
||||
const token = await getSessionToken({
|
||||
code: captchaAnswer,
|
||||
verifyToken: captchaId,
|
||||
@@ -69,17 +99,20 @@ export const apiAuthRouter = createTRPCRouter({
|
||||
userType: userType,
|
||||
password: password,
|
||||
});
|
||||
console.log("[=] Token Response :: ", JSON.stringify(token, null, 2));
|
||||
|
||||
if (!token.ok) {
|
||||
logger.warn(`[getNewSession] Failed to get session token: ${token.message}`);
|
||||
return {
|
||||
success: false,
|
||||
errors: [{ message: token.message }],
|
||||
};
|
||||
}
|
||||
|
||||
await setSessionToRedis(token.message, input.userId ?? "");
|
||||
logger.info(`[getNewSession] Successfully created session for user ${userId}`);
|
||||
return { success: true, errors: [] as ServerError };
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
logger.error("[getNewSession] Error getting new session", err);
|
||||
throw new TRPCError({
|
||||
code: "INTERNAL_SERVER_ERROR",
|
||||
message: "Error getting new session.",
|
||||
@@ -102,6 +135,7 @@ export const apiAuthRouter = createTRPCRouter({
|
||||
.input(z.object({ userId: z.string().optional() }))
|
||||
.mutation(async ({ input }) => {
|
||||
const { userId } = input;
|
||||
logger.info(`[logoutUser] Logging out user: ${userId || "all"}`);
|
||||
await removeSessionFromStore(userId);
|
||||
return { success: true, errors: [] as ServerError };
|
||||
}),
|
||||
|
||||
Reference in New Issue
Block a user