Skip to content

Commit

Permalink
fix: update copy & middleware try-catch
Browse files Browse the repository at this point in the history
  • Loading branch information
JimmyLv committed Mar 7, 2023
1 parent 4364722 commit d8a84e4
Show file tree
Hide file tree
Showing 3 changed files with 78 additions and 59 deletions.
14 changes: 13 additions & 1 deletion components/ActionsAfterResult.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
import React from "react";

export function ActionsAfterResult({ curVideo }: { curVideo: string }) {
export function ActionsAfterResult({
curVideo,
onCopy,
}: {
curVideo: string;
onCopy: () => void;
}) {
return (
<div className="mx-auto mt-7 flex max-w-3xl flex-row-reverse gap-x-4">
<a
Expand All @@ -19,6 +25,12 @@ export function ActionsAfterResult({ curVideo }: { curVideo: string }) {
>
回到视频
</a>
<button
className="w-24 cursor-pointer rounded-lg bg-sky-400 px-2 py-1 text-center font-medium text-white hover:bg-sky-400/80"
onClick={onCopy}
>
一键复制
</button>
</div>
);
}
7 changes: 4 additions & 3 deletions components/SummaryResult.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,10 @@ export function SummaryResult({
toast({ description: "复制错误 ❌" });
return;
}
// todo: update the timestamp
// todo: add the youtube video id
navigator.clipboard.writeText(
formattedSummary + "\n\n #BibiGPT自动总结 b.jimmylv.cn @吕立青_JimmyLv \nBV1fX4y1Q7Ux"
formattedSummary +
"\n\n #BibiGPT自动总结 b.jimmylv.cn @吕立青_JimmyLv \nBV1fX4y1Q7Ux"
);
toast({ description: "复制成功 ✂️" });
};
Expand Down Expand Up @@ -58,7 +59,7 @@ export function SummaryResult({
</div>
))}
</div>
<ActionsAfterResult curVideo={curVideo} />
<ActionsAfterResult curVideo={curVideo} onCopy={handleCopy} />
</div>
);
}
116 changes: 61 additions & 55 deletions middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,76 +10,82 @@ import { isDev } from "./utils/env";

const redis = Redis.fromEnv();

function redirectAuth() {
// return NextResponse.redirect(new URL("/shop", req.url));
// Respond with JSON indicating an error message
console.error("Authentication Failed");
return new NextResponse(
JSON.stringify({ success: false, message: "Authentication Failed" }),
{ status: 401, headers: { "content-type": "application/json" } }
);
}

export async function middleware(req: NextRequest, context: NextFetchEvent) {
const { userConfig, videoConfig } = (await req.json()) as SummarizeParams;
const { userKey } = userConfig || {};
const { videoId: bvId } = videoConfig || {};
try {
const { userConfig, videoConfig } = (await req.json()) as SummarizeParams;
const { userKey } = userConfig || {};
const { videoId: bvId } = videoConfig || {};

function redirectAuth() {
// return NextResponse.redirect(new URL("/shop", req.url));
// Respond with JSON indicating an error message
console.error("Authentication Failed");
return new NextResponse(
JSON.stringify({ success: false, message: "Authentication Failed" }),
{ status: 401, headers: { "content-type": "application/json" } }
);
}
// licenseKeys
if (userKey) {
if (checkOpenaiApiKeys(userKey)) {
return NextResponse.next();
}

// licenseKeys
if (userKey) {
if (checkOpenaiApiKeys(userKey)) {
return NextResponse.next();
// 3. something-invalid-sdalkjfasncs-key
if (!(await validateLicenseKey(userKey, bvId))) {
return redirectAuth();
}
}

// 3. something-invalid-sdalkjfasncs-key
if (!(await validateLicenseKey(userKey, bvId))) {
return redirectAuth();
}
}
if (!userKey) {
const identifier = req.ip ?? "127.0.0.7";
const { success, remaining } = await ratelimitForIps.limit(identifier);
console.log(
`======== ip ${identifier}, remaining: ${remaining} ========`
);
if (!success) {
// We need to create a response and hand it to the supabase client to be able to modify the response headers.
const res = NextResponse.next();
// TODO: unique to a user (userid, email etc) instead of IP
// Create authenticated Supabase Client.
const supabase = createMiddlewareSupabaseClient({ req, res });
// Check if we have a session
const {
data: { session },
} = await supabase.auth.getSession();
// Check auth condition
const userEmail = session?.user.email;
if (userEmail) {
// Authentication successful, forward request to protected route.
const { success, remaining } = await ratelimitForFreeAccounts.limit(
userEmail
);
console.log(
`======== user ${userEmail}, remaining: ${remaining} ========`
);
if (!success) {
return redirectAuth();
}

if (!userKey) {
const identifier = req.ip ?? "127.0.0.7";
const { success, remaining } = await ratelimitForIps.limit(identifier);
console.log(`======== ip ${identifier}, remaining: ${remaining} ========`);
if (!success) {
// We need to create a response and hand it to the supabase client to be able to modify the response headers.
const res = NextResponse.next();
// TODO: unique to a user (userid, email etc) instead of IP
// Create authenticated Supabase Client.
const supabase = createMiddlewareSupabaseClient({ req, res });
// Check if we have a session
const {
data: { session },
} = await supabase.auth.getSession();
// Check auth condition
const userEmail = session?.user.email;
if (userEmail) {
// Authentication successful, forward request to protected route.
const { success, remaining } = await ratelimitForFreeAccounts.limit(
userEmail
);
console.log(
`======== user ${userEmail}, remaining: ${remaining} ========`
);
if (!success) {
return redirectAuth();
return res;
}

return res;
// todo: throw error to trigger a modal, rather than redirect a page
return redirectAuth();
}

// todo: throw error to trigger a modal, rather than redirect a page
return redirectAuth();
}

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

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

export const config = {
Expand Down

1 comment on commit d8a84e4

@vercel
Copy link

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