pollo/src/middleware.ts

62 lines
1.7 KiB
TypeScript
Raw Normal View History

2023-08-17 20:55:56 -06:00
import { authMiddleware, redirectToSignIn } from "@clerk/nextjs";
2023-08-17 16:40:09 -06:00
import { validateRequest } from "./server/unkey";
import { NextResponse } from "next/server";
2023-08-20 01:15:52 -06:00
import { Ratelimit } from "@upstash/ratelimit";
import { Redis } from "@upstash/redis";
import { env } from "./env.mjs";
const rateLimit = new Ratelimit({
redis: Redis.fromEnv(),
limiter: Ratelimit.slidingWindow(
Number(env.UPSTASH_RATELIMIT_REQUESTS),
`${Number(env.UPSTASH_RATELIMIT_SECONDS)}s`
),
analytics: true,
});
2023-08-12 17:12:42 -06:00
export default authMiddleware({
2023-08-17 20:55:56 -06:00
publicRoutes: ["/", "/api/public/(.*)"],
afterAuth: async (auth, req) => {
if (!auth.userId && auth.isPublicRoute) {
2023-08-20 01:15:52 -06:00
const { success } = await rateLimit.limit(req.ip || "");
if (success) {
console.log(success);
return NextResponse.next();
}
return new NextResponse("TOO MANY REQUESTS", {
status: 429,
statusText: "Too many requests!",
});
2023-08-17 20:55:56 -06:00
}
if (
req.nextUrl.pathname.includes("/api/webhooks") ||
req.nextUrl.pathname.includes("/api/private")
) {
2023-08-20 01:15:52 -06:00
const { success } = await rateLimit.limit(req.ip || "");
2023-08-17 16:40:09 -06:00
const isValid = await validateRequest(req);
2023-08-20 01:15:52 -06:00
if (isValid && success) {
2023-08-17 16:40:09 -06:00
return NextResponse.next();
2023-08-20 01:15:52 -06:00
} else if (!success) {
return new NextResponse("TOO MANY REQUESTS", {
status: 429,
statusText: "Too many requests!",
});
} else if (!isValid) {
return new NextResponse("UNAUTHORIZED", {
status: 403,
statusText: "Unauthorized!",
});
2023-08-17 16:40:09 -06:00
}
2023-08-17 20:55:56 -06:00
}
if (!auth.userId && !auth.isPublicRoute) {
2023-08-17 20:58:19 -06:00
redirectToSignIn({ returnBackUrl: req.url });
2023-08-17 16:40:09 -06:00
}
},
2023-08-12 17:12:42 -06:00
});
export const config = {
matcher: ["/((?!.*\\..*|_next).*)", "/", "/(api|trpc)(.*)"],
};