Skip to content

Commit

Permalink
fix: auto check the licenseKeys
Browse files Browse the repository at this point in the history
  • Loading branch information
JimmyLv committed Mar 2, 2023
1 parent d789c4d commit 0829e83
Show file tree
Hide file tree
Showing 3 changed files with 94 additions and 9 deletions.
32 changes: 24 additions & 8 deletions middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,21 +16,33 @@ const ratelimit = new Ratelimit({
analytics: true, // <- Enable analytics
});

export async function middleware(req: NextRequest, ev: NextFetchEvent) {
if (isDev) {
return NextResponse.next();
}
export async function middleware(req: NextRequest, context: NextFetchEvent) {
// if (isDev) {
// return NextResponse.next();
// }

const { bvId, apiKey } = await req.json();
const result = await redis.get<string>(bvId);
if (result) {
if (!result) {
console.log("hit cache for ", bvId);
return NextResponse.json(result);
}

// note: not forgot to set USER_LICENSE_KEYS env var
if (process.env.USER_LICENSE_KEYS?.includes(apiKey)) {
const { remaining } = await ratelimit.limit(apiKey);
const response = await fetch(`https://api.lemonsqueezy.com/v1/license-keys`, {
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${process.env.LEMON_API_KEY ?? ""}`,
},
});
const keysData = await response.json();
const licenseKeys = keysData.data?.map((i: any) => i.attributes.key);

// licenseKeys
if (
!apiKey.startsWith(`sk-`) &&
licenseKeys?.includes(apiKey.toLowerCase())
) {
const { remaining } = await ratelimit.limit(apiKey.toLowerCase());
if (remaining === 0) {
return NextResponse.redirect(new URL("/shop", req.url));
}
Expand All @@ -47,4 +59,8 @@ export async function middleware(req: NextRequest, ev: NextFetchEvent) {

export const config = {
matcher: "/api/summarize",
unstable_allowDynamic: [
"node_modules/undici/lib/core/util.js", // allows a single file
// '/node_modules/function-bind/**', // use a glob to allow anything in the function-bind 3rd party module
],
};
70 changes: 69 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"crisp-sdk-web": "^1.0.13",
"eventsource-parser": "^0.1.0",
"framer-motion": "^9.0.1",
"lemonsqueezy.ts": "^0.1.6",
"next": "latest",
"node-html-parser": "^6.1.4",
"react": "18.2.0",
Expand Down

1 comment on commit 0829e83

@vercel
Copy link

@vercel vercel bot commented on 0829e83 Mar 2, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.