Skip to content

Commit

Permalink
fix: only validate
Browse files Browse the repository at this point in the history
  • Loading branch information
JimmyLv committed Mar 3, 2023
1 parent ee5ea7e commit 51a7044
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 4 deletions.
6 changes: 3 additions & 3 deletions middleware.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import { Redis } from "@upstash/redis";
import type { NextFetchEvent, NextRequest } from "next/server";
import { NextResponse } from "next/server";
import { activeLicenseKey } from "./utils/3rd/lemon";
import { activateLicenseKey, validateLicenseKey } from "./utils/3rd/lemon";
import { checkOpenaiApiKey } from "./utils/3rd/openai";
import { ratelimit } from "./utils/3rd/upstash";
import { isDev } from "./utils/env";

const redis = Redis.fromEnv();

export async function middleware(req: NextRequest, context: NextFetchEvent) {
const { apiKey, bvId, ...rest } = await req.json();
const { apiKey, bvId } = await req.json();
const result = await redis.get<string>(bvId);
if (!isDev && result) {
console.log("hit cache for ", bvId);
Expand All @@ -23,7 +23,7 @@ export async function middleware(req: NextRequest, context: NextFetchEvent) {
}

// 3. something-invalid-sdalkjfasncs-key
if (!(await activeLicenseKey(apiKey, bvId))) {
if (!(await validateLicenseKey(apiKey, bvId))) {
return NextResponse.redirect(new URL("/shop", req.url));
}
}
Expand Down
22 changes: 21 additions & 1 deletion utils/3rd/lemon.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export async function activeLicenseKey(licenseKey: string, bvId?: string) {
export async function activateLicenseKey(licenseKey: string, bvId?: string) {
// https://docs.lemonsqueezy.com/help/licensing/license-api
const response = await fetch(
`https://api.lemonsqueezy.com/v1/licenses/activate`,
Expand All @@ -17,3 +17,23 @@ export async function activeLicenseKey(licenseKey: string, bvId?: string) {
const result = await response.json();
return result.activated;
}

export async function validateLicenseKey(licenseKey: string, bvId?: string) {
// https://docs.lemonsqueezy.com/help/licensing/license-api
const response = await fetch(
`https://api.lemonsqueezy.com/v1/licenses/validate`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${process.env.LEMON_API_KEY ?? ""}`,
},
body: JSON.stringify({
license_key: licenseKey,
instance_name: bvId || "b.jimmylv.cn",
}),
}
);
const result = await response.json();
return result.valid;
}

1 comment on commit 51a7044

@vercel
Copy link

@vercel vercel bot commented on 51a7044 Mar 3, 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.