0
v-firecrawl/apps/api/src/controllers/auth.ts

149 lines
4.3 KiB
TypeScript
Raw Normal View History

2024-04-20 19:38:05 -04:00
import { parseApi } from "../../src/lib/parseApi";
2024-05-14 17:08:31 -04:00
import { getRateLimiter, crawlRateLimit, scrapeRateLimit } from "../../src/services/rate-limiter";
import { AuthResponse, RateLimiterMode } from "../../src/types";
2024-04-20 19:38:05 -04:00
import { supabase_service } from "../../src/services/supabase";
import { withAuth } from "../../src/lib/withAuth";
2024-05-14 17:08:31 -04:00
import { RateLimiterRedis } from "rate-limiter-flexible";
export async function authenticateUser(req, res, mode?: RateLimiterMode) : Promise<AuthResponse> {
return withAuth(supaAuthenticateUser)(req, res, mode);
}
export async function supaAuthenticateUser(
2024-04-20 19:38:05 -04:00
req,
res,
mode?: RateLimiterMode
): Promise<{
success: boolean;
team_id?: string;
error?: string;
status?: number;
}> {
const authHeader = req.headers.authorization;
if (!authHeader) {
return { success: false, error: "Unauthorized", status: 401 };
}
const token = authHeader.split(" ")[1]; // Extract the token from "Bearer <token>"
if (!token) {
return {
success: false,
error: "Unauthorized: Token missing",
status: 401,
};
}
2024-05-14 17:08:31 -04:00
const incomingIP = (req.headers["x-forwarded-for"] ||
req.socket.remoteAddress) as string;
const iptoken = incomingIP + token;
let rateLimiter: RateLimiterRedis;
let subscriptionData: { team_id: string, plan: string } | null = null;
let normalizedApi: string;
if (token == "this_is_just_a_preview_token") {
rateLimiter = await getRateLimiter(RateLimiterMode.Preview, token);
} else {
normalizedApi = parseApi(token);
const { data, error } = await supabase_service.rpc(
2024-05-14 17:47:21 -04:00
'get_key_and_price_id_2', { api_key: normalizedApi }
);
2024-05-14 17:08:31 -04:00
if (error) {
console.error('Error fetching key and price_id:', error);
} else {
console.log('Key and Price ID:', data);
}
if (error || !data || data.length === 0) {
return {
success: false,
error: "Unauthorized: Invalid token",
status: 401,
};
}
subscriptionData = {
team_id: data[0].team_id,
plan: getPlanByPriceId(data[0].price_id)
}
switch (mode) {
case RateLimiterMode.Crawl:
rateLimiter = crawlRateLimit(subscriptionData.plan);
break;
case RateLimiterMode.Scrape:
rateLimiter = scrapeRateLimit(subscriptionData.plan);
break;
2024-05-14 17:47:36 -04:00
case RateLimiterMode.CrawlStatus:
rateLimiter = await getRateLimiter(RateLimiterMode.CrawlStatus, token);
break;
default:
rateLimiter = await getRateLimiter(RateLimiterMode.Crawl, token);
break;
2024-05-14 17:08:31 -04:00
// case RateLimiterMode.Search:
// rateLimiter = await searchRateLimiter(RateLimiterMode.Search, token);
// break;
}
}
2024-04-20 19:38:05 -04:00
try {
2024-05-14 17:08:31 -04:00
rateLimiter.consume(iptoken);
2024-04-20 19:38:05 -04:00
} catch (rateLimiterRes) {
console.error(rateLimiterRes);
return {
success: false,
error: "Rate limit exceeded. Too many requests, try again in 1 minute.",
status: 429,
};
}
if (
token === "this_is_just_a_preview_token" &&
2024-04-26 15:57:49 -04:00
(mode === RateLimiterMode.Scrape || mode === RateLimiterMode.Preview || mode === RateLimiterMode.Search)
2024-04-20 19:38:05 -04:00
) {
return { success: true, team_id: "preview" };
2024-04-26 15:57:49 -04:00
// check the origin of the request and make sure its from firecrawl.dev
// const origin = req.headers.origin;
// if (origin && origin.includes("firecrawl.dev")){
// return { success: true, team_id: "preview" };
// }
// if(process.env.ENV !== "production") {
// return { success: true, team_id: "preview" };
// }
// return { success: false, error: "Unauthorized: Invalid token", status: 401 };
2024-04-20 19:38:05 -04:00
}
// make sure api key is valid, based on the api_keys table in supabase
2024-05-14 17:08:31 -04:00
if (!subscriptionData) {
normalizedApi = parseApi(token);
const { data, error } = await supabase_service
2024-04-20 19:38:05 -04:00
.from("api_keys")
.select("*")
.eq("key", normalizedApi);
2024-05-14 17:08:31 -04:00
if (error || !data || data.length === 0) {
return {
success: false,
error: "Unauthorized: Invalid token",
status: 401,
};
}
subscriptionData = data[0];
2024-04-20 19:38:05 -04:00
}
2024-05-14 17:08:31 -04:00
return { success: true, team_id: subscriptionData.team_id };
2024-04-20 19:38:05 -04:00
}
2024-05-14 17:08:31 -04:00
function getPlanByPriceId(price_id: string) {
switch (price_id) {
case process.env.STRIPE_PRICE_ID_STANDARD:
return 'standard';
case process.env.STRIPE_PRICE_ID_SCALE:
return 'scale';
default:
return 'starter';
}
}