Skip to content

Commit

Permalink
🐛 fix login logic
Browse files Browse the repository at this point in the history
  • Loading branch information
shezhangzhang committed Apr 2, 2023
1 parent eaa0e7a commit b41a122
Show file tree
Hide file tree
Showing 6 changed files with 60 additions and 31 deletions.
29 changes: 20 additions & 9 deletions components/input.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import * as Sentry from "@sentry/nextjs";
import { Conversation, ROLES } from "../pages";
import { toPng } from "html-to-image";
import download from "downloadjs";
import { useRouter } from "next/router";

interface Props {
conversations: Conversation[];
Expand All @@ -19,6 +20,7 @@ export default function Input(props: Props) {
conversations,
updateSavingStatus,
} = props;
const router = useRouter();
const [isMobile, setIsMobile] = useState(false);
const [submitLoading, setSubmitLoading] = useState(false);
const [input, setInput] = useState("");
Expand All @@ -29,19 +31,20 @@ export default function Input(props: Props) {

async function handleSubmit() {
stop.current = false;

if (!input.trim()) {
return;
}

updateErrMsg("");

const loginCK = localStorage.getItem(LOGIN_CK);

if (loginCK) {
Sentry.captureMessage(`${window.atob(loginCK)}: ${+new Date()}`, {
level: "info",
fingerprint: [window.atob(loginCK)],
});
} else {
router.replace("/login");
return;
}

Expand All @@ -51,7 +54,7 @@ export default function Input(props: Props) {
};
payload = [...conversations, currentQuestion];
updateConversations(payload);
fetchData(payload);
fetchData(payload, window.atob(loginCK));
setInput("");
}

Expand All @@ -69,13 +72,21 @@ export default function Input(props: Props) {
setSubmitLoading(false);
}

function fetchData(payload: any) {
function fetchData(payload: Conversation[], password: string) {
setSubmitLoading(true);

const body = {
messsages: payload,
password,
};
fetch(`${location.origin}/api/chat`, {
method: "POST",
body: JSON.stringify(payload),
body: JSON.stringify(body),
})
.then((response) => {
if (response.status === 401) {
router.replace("/login");
}
if (!response.ok) {
throw new Error("Network response was not ok");
}
Expand Down Expand Up @@ -174,7 +185,7 @@ export default function Input(props: Props) {
onKeyDown={handleKeyDown}
/>
<button
className={`mt-3 h-10 w-40 rounded-md bg-black font-medium text-white hover:bg-slate-700 dark:bg-slate-300 dark:text-black dark:hover:bg-slate-400 sm:mt-0 sm:ml-3 sm:w-48 ${
className={`mt-3 h-10 w-40 rounded-md bg-black font-medium text-white hover:bg-slate-700 dark:bg-slate-300 dark:text-black dark:hover:bg-slate-400 sm:ml-3 sm:mt-0 sm:w-48 ${
submitLoading ? "animate-pulse" : ""
}`}
onClick={handleSubmit}
Expand All @@ -183,7 +194,7 @@ export default function Input(props: Props) {
{submitLoading ? "Waiting" : "Submit"}
</button>
<button
className={`mt-3 ml-3 h-10 w-14 rounded-md border border-black font-medium text-black hover:bg-slate-100 dark:border-slate-500 dark:text-slate-200 dark:hover:bg-slate-700 sm:mt-0 sm:w-28 ${
className={`ml-3 mt-3 h-10 w-14 rounded-md border border-black font-medium text-black hover:bg-slate-100 dark:border-slate-500 dark:text-slate-200 dark:hover:bg-slate-700 sm:mt-0 sm:w-28 ${
submitLoading ? "animate-pulse" : ""
}`}
onClick={handleClear}
Expand All @@ -192,7 +203,7 @@ export default function Input(props: Props) {
Clear
</button>
<button
className="mt-3 ml-3 h-10 w-14 rounded-md border border-black font-medium text-black hover:bg-slate-100 dark:border-slate-500 dark:text-slate-200 dark:hover:bg-slate-700 sm:mt-0 sm:w-28"
className="ml-3 mt-3 h-10 w-14 rounded-md border border-black font-medium text-black hover:bg-slate-100 dark:border-slate-500 dark:text-slate-200 dark:hover:bg-slate-700 sm:mt-0 sm:w-28"
onClick={handleSave}
disabled={saving}
>
Expand All @@ -202,7 +213,7 @@ export default function Input(props: Props) {
{/* The stop button is fixed to the header. */}
{submitLoading ? (
<button
className={`fixed top-5 left-1/2 z-20 h-6 w-14 -translate-x-1/2 rounded border border-black font-normal text-black dark:border-white dark:text-white`}
className={`fixed left-1/2 top-5 z-20 h-6 w-14 -translate-x-1/2 rounded border border-black font-normal text-black dark:border-white dark:text-white`}
onClick={handleStop}
>
Stop
Expand Down
19 changes: 8 additions & 11 deletions pages/_app.tsx
Original file line number Diff line number Diff line change
@@ -1,19 +1,16 @@
import "@/styles/globals.css";
import type { AppProps } from "next/app";
import { Analytics } from "@vercel/analytics/react";
import * as Sentry from "@sentry/nextjs";
import Header from "../components/header";
import { useEffect, useState } from "react";
import { DarkContext } from "../utils/darkContext";
// import * as Sentry from "@sentry/nextjs";

Sentry.init({
dsn: "https://[email protected]/4504841207021568",

// Set tracesSampleRate to 1.0 to capture 100%
// of transactions for performance monitoring.
// We recommend adjusting this value in production
tracesSampleRate: 1.0,
});
// GO: https://sentry.io/
// Sentry.init({
// dsn: "your_own_sentry_dsn",
// tracesSampleRate: 1.0,
// });

const DARK_MODE = "DARK";

Expand All @@ -35,9 +32,9 @@ export default function App({ Component, pageProps }: AppProps) {
<>
<div className={`${dark ? "dark" : ""}`}>
<DarkContext.Provider value={dark}>
<div className="text-slate-900 dark:text-slate-100 min-h-screen dark:bg-slate-900">
<div className="min-h-screen text-slate-900 dark:bg-slate-900 dark:text-slate-100">
<Header dark={dark} setDark={setDark} />
<main className="flex mx-auto flex-col items-center">
<main className="mx-auto flex flex-col items-center">
<Component {...pageProps} />
</main>
</div>
Expand Down
20 changes: 15 additions & 5 deletions pages/api/chat.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,30 @@
import { NextRequest } from "next/server";
import { Stream } from "../../utils/stream";
import { NextRequest, NextResponse } from "next/server";
import { ChatGPTMessage, Stream } from "../../utils/stream";

export const config = {
runtime: "edge",
};

export default async function handler(req: NextRequest) {
interface Body {
messsages: ChatGPTMessage[];
password: string;
}

export default async function handler(req: NextRequest, res: NextResponse) {
if (req.method !== "POST") {
return new Response("Method Not Allowed", { status: 405 });
}

const messsages = await req.json();
const body: Body = await req.json();

const passwords = process.env.PASSWORD?.split(",");
if (!body?.password || !passwords || !passwords.includes(body.password)) {
return new Response("Not Login", { status: 401 });
}

const payload = {
model: process.env.MODEL || "gpt-3.5-turbo",
messages: messsages,
messages: body.messsages,
stream: true,
};

Expand Down
1 change: 0 additions & 1 deletion pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@ export default function Home() {
router.replace("/login");
}
} catch (error) {
console.log(error);
router.replace("/login");
}
}
Expand Down
20 changes: 16 additions & 4 deletions pages/login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,15 @@ export default function Login() {
const [input, setInput] = useState("");
const [isError, setIsError] = useState(false);
const [loading, setLoading] = useState(false);
const [errMsg, setErrMsg] = useState("");
const router = useRouter();

async function handleLogin() {
if (!input) return;

try {
setLoading(true);
setIsError(false);
const res = await fetch(`${location.origin}/api/login?password=${input}`);
if (!res.ok) {
throw Error(res.statusText);
Expand All @@ -26,11 +28,20 @@ export default function Login() {
} else {
setInput("");
setIsError(true);
setErrMsg("wrong password.");
}
setLoading(false);
} catch (error) {
console.log(error);
setLoading(false);
setIsError(true);
setErrMsg(`Something was wrong: ${error}`);
}
}

function handleKeyDown(event: any) {
if (event.key === "Enter") {
event.preventDefault();
handleLogin();
}
}

Expand All @@ -40,12 +51,13 @@ export default function Login() {
<input
value={input}
onChange={(e) => setInput(e.target.value)}
className="mt-5 mb-1 w-full rounded-md border-2 border-gray-300 p-3 shadow-sm focus:border-black focus:outline-0 dark:border-gray-700 dark:bg-slate-900 dark:focus:border-gray-600"
className="mb-1 mt-5 w-full rounded-md border-2 border-gray-300 p-3 shadow-sm focus:border-black focus:outline-0 dark:border-gray-700 dark:bg-slate-900 dark:focus:border-gray-600"
placeholder={"Ask me for the password. "}
type="password"
onKeyDown={handleKeyDown}
/>
<span className="text-sm font-bold text-red-500">
{isError ? <div>wrong password.</div> : ""}
{isError ? errMsg : ""}
</span>
</div>
<button
Expand All @@ -55,7 +67,7 @@ export default function Login() {
onClick={handleLogin}
disabled={loading}
>
GO
{loading ? "Waiting" : "GO"}
</button>
</div>
);
Expand Down
2 changes: 1 addition & 1 deletion utils/stream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {
} from "eventsource-parser";
import * as Sentry from "@sentry/nextjs";

export type ChatGPTAgent = "user" | "system";
export type ChatGPTAgent = "user" | "system" | "assistant";

export interface ChatGPTMessage {
role: ChatGPTAgent;
Expand Down

0 comments on commit b41a122

Please sign in to comment.