Skip to content

Commit

Permalink
Merge pull request #58 from polywrap/namesty/anon-sessions
Browse files Browse the repository at this point in the history
Anon sessions
  • Loading branch information
namesty authored Jan 30, 2024
2 parents 6feac71 + be5888f commit cb7ab39
Show file tree
Hide file tree
Showing 25 changed files with 730 additions and 44 deletions.
2 changes: 2 additions & 0 deletions .env.template
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,7 @@ NEXT_PUBLIC_SUPABASE_URL=
NEXT_PUBLIC_SUPABASE_ANON_KEY=
SUPABASE_SERVICE_ROLE_KEY=
OPENAI_API_KEY=
NEXTAUTH_SECRET=
SUPABASE_JWT_SECRET=
NEXT_PUBLIC_INFURA_PROJECT_ID=
WORKERS_URL=
8 changes: 6 additions & 2 deletions web/app/actions/startWorker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,16 @@ interface StartWorkerResponse {
}

export const startWorker = async (
prompt: string
prompt: string,
supabaseAccessToken: string
): Promise<StartWorkerResponse> => {
const response = await fetch(`${process.env.WORKERS_URL}/api/workers`, {
cache: "no-cache",
method: "POST",
body: JSON.stringify({ prompt }),
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${supabaseAccessToken}`
},
});

Expand All @@ -38,7 +40,8 @@ interface RegenerateRunResponse {

export const regenerateStrategy = async (
prompt: string,
workerId: string
workerId: string,
supabaseAccessToken: string
): Promise<RegenerateRunResponse> => {
const response = await fetch(
`${process.env.WORKERS_URL}/api/workers/${workerId}/runs`,
Expand All @@ -48,6 +51,7 @@ export const regenerateStrategy = async (
body: JSON.stringify({ prompt }),
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${supabaseAccessToken}`
},
}
);
Expand Down
12 changes: 12 additions & 0 deletions web/app/api/auth/[...nextauth]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import NextAuth from "next-auth";
import { NextRequest } from "next/server";

import { authOptions } from "@/utils/authOptions";

export function GET(req: NextRequest, res: any) {
return NextAuth(req, res, authOptions);
}

export function POST(req: NextRequest, res: any) {
return NextAuth(req, res, authOptions);
}
13 changes: 8 additions & 5 deletions web/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import "./globals.css";
import WalletProvider from "./WalletProvider";
import Main from "./main";
import { Logo } from "@/components/Logo";
import AuthProvider from "@/components/Providers";

const sans = Plus_Jakarta_Sans({
subsets: ["latin"],
Expand Down Expand Up @@ -54,11 +55,13 @@ export default function RootLayout({
<html lang='en'>
<body className={sans.className}>
<WalletProvider>
<Main>
<Header />
{children}
<Footer />
</Main>
<AuthProvider>
<Main>
<Header />
{children}
<Footer />
</Main>
</AuthProvider>
</WalletProvider>
</body>
</html>
Expand Down
4 changes: 2 additions & 2 deletions web/app/r/[id]/page.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import Strategy from "@/components/Strategy";
import { StrategyWithProjects } from "@/components/StrategyTable";
import { createSupabaseServerClient } from "@/utils/supabase-server";
import { createSupabaseServerClientWithSession } from "@/utils/supabase-server";

export default async function StrategyPage({
params,
}: {
params: { id: string };
}) {
const supabase = createSupabaseServerClient();
const supabase = await createSupabaseServerClientWithSession()

// Fetch the runs for this worker
const run = await supabase
Expand Down
4 changes: 2 additions & 2 deletions web/app/r/[id]/progress/page.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import Logs from "@/components/Logs";
import TextField from "@/components/TextField";
import { createSupabaseServerClient } from "@/utils/supabase-server";
import { createSupabaseServerClientWithSession } from "@/utils/supabase-server";

async function PromptField(props: { runId: string }) {
const supabase = createSupabaseServerClient()
const supabase = await createSupabaseServerClientWithSession()

const { data: run } = await supabase.from('runs').select(`
id,
Expand Down
5 changes: 3 additions & 2 deletions web/app/r/[id]/transaction/page.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import FundingReview from "@/components/FundingReview";
import { FundingEntry } from "@/components/FundingTable";
import { createSupabaseServerClient } from "@/utils/supabase-server";
import { createSupabaseServerClientWithSession } from "@/utils/supabase-server";

export default async function Page({ params }: { params: { id: string } }) {
const supabase = createSupabaseServerClient();
const supabase = await createSupabaseServerClientWithSession()

const run = await supabase
.from("funding_entries_view")
.select("*")
Expand Down
16 changes: 16 additions & 0 deletions web/app/types/next-auth.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import NextAuth, { DefaultSession } from "next-auth"

declare module "next-auth" {
interface Session {
supabaseAccessToken: string
user: {
address?: string | null
id: string
} & DefaultSession["user"]
}

interface DefaultUser {
id: string
address?: string | null
}
}
4 changes: 2 additions & 2 deletions web/components/Logs.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
"use server"

import { createSupabaseServerClient } from "@/utils/supabase-server";
import { createSupabaseServerClientWithSession } from "@/utils/supabase-server";
import RealtimeLogs from "./RealtimeLogs";

export default async function Logs(props: { runId: string }) {
const supabase = createSupabaseServerClient()
const supabase = await createSupabaseServerClientWithSession()

const { data: run } = await supabase.from('runs').select(`
id,
Expand Down
14 changes: 10 additions & 4 deletions web/components/Prompt.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
"use client";

import { ChangeEvent, useState } from "react";
import TextField from "./TextField";
import ChatInputButton from "./ChatInputButton";
import { useState } from "react";
import { SparkleIcon } from "./Icons";
import { startWorker } from "@/app/actions";
import { useRouter } from "next/navigation";
import LoadingCircle from "./LoadingCircle";
import PromptInput from "./PromptInput";
import useSession from "@/hooks/useSession";

const PROMPT_SUGESTIONS = [
"Ethereum infrastructure",
Expand All @@ -22,13 +21,18 @@ const PROMPT_SUGESTIONS = [
export default function Prompt() {
const [prompt, setPrompt] = useState<string>("");
const [isWaiting, setIsWaiting] = useState(false);
const { data: session } = useSession()

const router = useRouter();

const sendPrompt = async (prompt: string) => {
setIsWaiting(true);
try {
const response = await startWorker(prompt);
if (!session) {
throw new Error("User needs to have a session")
}

const response = await startWorker(prompt, session.supabaseAccessToken);
router.push(`/r/${response.runId}/progress`)
} finally {
setIsWaiting(false);
Expand Down Expand Up @@ -59,6 +63,7 @@ export default function Prompt() {
isWaiting={isWaiting}
sendPrompt={sendPrompt}
prompt={prompt}
disabled={!session}
/>
</div>
<div className='space-y-4'>
Expand All @@ -70,6 +75,7 @@ export default function Prompt() {
<div key={index}>
<button
className='text-xs shadow-sm hover:shadow-md shadow-primary-shadow/20 px-3 py-2 leading-none border-2 border-spacing-2 rounded-full hover:bg-indigo-200 hover:border-indigo-400 hover:text-indigo-800 bg-indigo-500 border-indigo-600 text-indigo-50 transition-colors ease-in-out duration-300'
disabled={!session}
onClick={async () => {
setPrompt(suggestion);
await sendPrompt(suggestion);
Expand Down
11 changes: 11 additions & 0 deletions web/components/Providers.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
"use client"

import { SessionProvider } from "next-auth/react";

export default function AuthProvider({ children }: { children: React.ReactNode }) {
return (
<SessionProvider>
{children}
</SessionProvider>
)
}
9 changes: 8 additions & 1 deletion web/components/RealtimeLogs.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { useState, useEffect } from "react";
import LoadingCircle from "./LoadingCircle";
import ProgressBar from "./ProgressBar";
import Button from "./Button";
import useSession from "@/hooks/useSession";

type StepName = Tables<"logs">["step_name"];

Expand Down Expand Up @@ -53,6 +54,11 @@ const checkIfFinished = (logs: Tables<"logs">[]) => {
return STEPS_ORDER[a.step_name] - STEPS_ORDER[b.step_name]
})
const lastStep = sortedLogs.slice(-1)[0];

if (!lastStep) {
return false
}

const isFinished = lastStep.status === "COMPLETED" && lastStep.step_name === "SYNTHESIZE_RESULTS"

return isFinished
Expand All @@ -66,7 +72,8 @@ export default function RealtimeLogs(props: {
}
}) {
const [logs, setLogs] = useState<Tables<"logs">[]>(props.logs)
const supabase = createSupabaseBrowserClient();
const { data: session } = useSession()
const supabase = createSupabaseBrowserClient(session?.supabaseAccessToken ?? "");
const router = useRouter()

const sortedLogsWithSteps = logs.sort((a, b) => {
Expand Down
23 changes: 23 additions & 0 deletions web/hooks/useSession.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { Session } from "next-auth"
import { signIn, useSession as useNextAuthSession } from "next-auth/react"

const anonSignIn = async () => {
await signIn('credentials', {
redirect: false
})
}

export default function useSession(): {
data: Session | null;
status: "authenticated" | "loading";
} {
const { data, status } = useNextAuthSession({
required: true,
onUnauthenticated: () => anonSignIn()
})

return {
data,
status
}
}
4 changes: 4 additions & 0 deletions web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"db:generate-types": "supabase gen types typescript --local --schema public > supabase/dbTypes.ts"
},
"dependencies": {
"@auth/supabase-adapter": "^0.1.18",
"@headlessui/react": "^1.7.18",
"@phosphor-icons/react": "^2.0.15",
"@supabase/ssr": "0.0.10",
Expand All @@ -21,11 +22,14 @@
"@web3-onboard/react": "^2.8.13",
"clsx": "^2.1.0",
"ethers": "5.7.2",
"jsonwebtoken": "^9.0.2",
"next": "14.0.4",
"next-auth": "4.24.5",
"react": "18.2.0",
"react-dom": "18.2.0"
},
"devDependencies": {
"@types/jsonwebtoken": "^9.0.5",
"@types/node": "20.11.5",
"@types/react": "18.2.48",
"@types/react-dom": "18.2.12",
Expand Down
2 changes: 1 addition & 1 deletion web/supabase/config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ enabled = true
port = 54321
# Schemas to expose in your API. Tables, views and stored procedures in this schema will get API
# endpoints. public and storage are always included.
schemas = ["public", "storage", "graphql_public", "indexing"]
schemas = ["public", "storage", "graphql_public", "indexing", "next_auth"]
# Extra schemas to add to the search_path of every request. public is always included.
extra_search_path = ["public", "extensions"]
# The maximum number of rows returns from a view, table, or stored procedure. Limits payload size
Expand Down
Loading

0 comments on commit cb7ab39

Please sign in to comment.