From c8aefcab04897ea5e22dfc9050587be7c2c330d9 Mon Sep 17 00:00:00 2001 From: Jared Palmer Date: Thu, 22 Jun 2023 10:37:35 -0700 Subject: [PATCH] Force auth --- app/api/chat/route.ts | 8 ++++---- app/sign-in/page.tsx | 9 ++++++++- auth.ts | 8 ++++---- components/chat.tsx | 6 ++++++ middleware.ts | 4 ++++ 5 files changed, 26 insertions(+), 9 deletions(-) diff --git a/app/api/chat/route.ts b/app/api/chat/route.ts index b39b26c..594925c 100644 --- a/app/api/chat/route.ts +++ b/app/api/chat/route.ts @@ -18,10 +18,10 @@ export async function POST(req: Request) { const { messages, previewToken } = json const session = await auth() - if (process.env.VERCEL_ENV === 'preview') { - if (session == null) { - return new Response('Unauthorized', { status: 401 }) - } + if (session == null) { + return new Response('Unauthorized', { + status: 401 + }) } if (previewToken) { diff --git a/app/sign-in/page.tsx b/app/sign-in/page.tsx index 00891e7..280333e 100644 --- a/app/sign-in/page.tsx +++ b/app/sign-in/page.tsx @@ -1,6 +1,13 @@ +import { auth } from '@/auth' import { LoginButton } from '@/components/login-button' +import { redirect } from 'next/navigation' -export default function SignInPage() { +export default async function SignInPage() { + const session = await auth() + // redirect to home if user is already logged in + if (session?.user) { + redirect('/') + } return (
diff --git a/auth.ts b/auth.ts index 5c7c1dd..c6562d5 100644 --- a/auth.ts +++ b/auth.ts @@ -17,11 +17,11 @@ export const { token.image = profile.picture } return token + }, + // @ts-ignore + authorized({ auth }) { + return !!auth?.user } - // @TODO - // authorized({ request, auth }) { - // return !!auth?.user - // } }, pages: { signIn: '/sign-in' diff --git a/components/chat.tsx b/components/chat.tsx index b3a8394..a9ecafe 100644 --- a/components/chat.tsx +++ b/components/chat.tsx @@ -19,6 +19,7 @@ import { import { useState } from 'react' import { Button } from './ui/button' import { Input } from './ui/input' +import { toast } from 'react-hot-toast' const IS_PREVIEW = process.env.VERCEL_ENV === 'preview' export interface ChatProps extends React.ComponentProps<'div'> { @@ -40,6 +41,11 @@ export function Chat({ id, initialMessages, className }: ChatProps) { body: { id, previewToken + }, + onResponse(response) { + if (response.status === 401) { + toast.error(response.statusText) + } } }) return ( diff --git a/middleware.ts b/middleware.ts index 4afe145..d70f753 100644 --- a/middleware.ts +++ b/middleware.ts @@ -1 +1,5 @@ export { auth as middleware } from './auth' + +export const config = { + matcher: ['/', '/api/chat'] +}