Skip to content

Commit

Permalink
chore: simplify next-auth (vercel#80)
Browse files Browse the repository at this point in the history
  • Loading branch information
balazsorban44 authored Jun 27, 2023
1 parent 5912336 commit 012ea40
Show file tree
Hide file tree
Showing 8 changed files with 55 additions and 116 deletions.
12 changes: 5 additions & 7 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,15 @@
## Then get your OpenAI API Key here: https://platform.openai.com/account/api-keys
OPENAI_API_KEY=XXXXXXXX

## Generate a random secret: https://generate-secret.vercel.app/32
NEXTAUTH_SECRET=XXXXXXXX

## Only required for localhost
NEXTAUTH_URL=http://localhost:3000

## Generate a random secret: https://generate-secret.vercel.app/32 or `openssl rand -base64 32`
AUTH_SECRET=XXXXXXXX
## Create a GitHub OAuth app here: https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/creating-an-oauth-app
AUTH_GITHUB_ID=XXXXXXXX
AUTH_GITHUB_SECRET=XXXXXXXX
## Support OAuth login on preview deployments, see: https://authjs.dev/guides/basics/deployment#securing-a-preview-deployment
AUTH_REDIRECT_PROXY_URL=https://auth.example.com/api/auth

# instructions to create kv database here: https://vercel.com/docs/storage/vercel-kv/quickstart and
# Instructions to create kv database here: https://vercel.com/docs/storage/vercel-kv/quickstart and
KV_URL=XXXXXXXX
KV_REST_API_URL=XXXXXXXX
KV_REST_API_TOKEN=XXXXXXXX
Expand Down
1 change: 1 addition & 0 deletions app/api/auth/[...nextauth]/route.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export { GET, POST } from '@/auth'
export const runtime = 'edge'
49 changes: 23 additions & 26 deletions app/api/chat/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ const openai = new OpenAIApi(configuration)
export async function POST(req: Request) {
const json = await req.json()
const { messages, previewToken } = json
const session = await auth()
const userId = (await auth())?.user.id

if (session == null) {
if (!userId) {
return new Response('Unauthorized', {
status: 401
})
Expand All @@ -38,31 +38,28 @@ export async function POST(req: Request) {
const stream = OpenAIStream(res, {
async onCompletion(completion) {
const title = json.messages[0].content.substring(0, 100)
const userId = session?.user?.id
if (userId) {
const id = json.id ?? nanoid()
const createdAt = Date.now()
const path = `/chat/${id}`
const payload = {
id,
title,
userId,
createdAt,
path,
messages: [
...messages,
{
content: completion,
role: 'assistant'
}
]
}
await kv.hmset(`chat:${id}`, payload)
await kv.zadd(`user:chat:${userId}`, {
score: createdAt,
member: `chat:${id}`
})
const id = json.id ?? nanoid()
const createdAt = Date.now()
const path = `/chat/${id}`
const payload = {
id,
title,
userId,
createdAt,
path,
messages: [
...messages,
{
content: completion,
role: 'assistant'
}
]
}
await kv.hmset(`chat:${id}`, payload)
await kv.zadd(`user:chat:${userId}`, {
score: createdAt,
member: `chat:${id}`
})
}
})

Expand Down
63 changes: 17 additions & 46 deletions auth.ts
Original file line number Diff line number Diff line change
@@ -1,64 +1,35 @@
import NextAuth from 'next-auth'
import NextAuth, { type DefaultSession } from 'next-auth'
import GitHub from 'next-auth/providers/github'
import CredentialsProvider from 'next-auth/providers/credentials'
import { NextResponse } from 'next/server'

// We default to using GitHub for authentication for local development and production.
// On Preview deployments, we use a dummy credentials provider. This allows folks to easily
// test the app without having to create a custom GitHub OAuth app or change the callback URL
// just to test the application on previews.
declare module 'next-auth' {
interface Session {
user: {
/** The user's id. */
id: string
} & DefaultSession['user']
}
}

// We have a custom /sign-in page for non-preview environments. In preview environments, the user
// will be redirected to /api/auth/signin instead.
export const {
handlers: { GET, POST },
auth,
CSRF_experimental
// @ts-ignore
} = NextAuth({
// @ts-ignore
providers: [
process.env.VERCEL_ENV === 'preview'
? CredentialsProvider({
name: 'Credentials',
credentials: {
username: {
label: 'Username',
type: 'text',
placeholder: 'jsmith'
},
password: { label: 'Password', type: 'password' }
},
async authorize(credentials) {
return {
id: 1,
name: 'J Smith',
email: '[email protected]',
picture: 'https://i.pravatar.cc/[email protected]'
} as any
}
})
: GitHub
],
providers: [GitHub],
callbacks: {
// @ts-ignore
jwt: async ({ token, profile }) => {
if (profile?.id) {
jwt({ token, profile }) {
if (profile) {
token.id = profile.id
token.image = profile.picture
}
return token
},
// @ts-ignore
authorized({ auth }) {
return !!auth?.user
},
trustHost: true
}
},
...(process.env.VERCEL_ENV === 'preview'
? {}
: {
pages: {
signIn: '/sign-in'
}
})
pages: {
signIn: '/sign-in'
}
})
2 changes: 1 addition & 1 deletion middleware.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
export { auth as middleware } from './auth'

export const config = {
matcher: ['/', '/api/chat']
matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)']
}
13 changes: 0 additions & 13 deletions next-auth.d.ts

This file was deleted.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
"focus-trap-react": "^10.1.1",
"nanoid": "^4.0.2",
"next": "13.4.7-canary.1",
"next-auth": "0.0.0-manual.e65faa1c",
"next-auth": "0.0.0-manual.83c4ebd1",
"next-themes": "^0.2.1",
"openai-edge": "^0.5.1",
"react": "^18.2.0",
Expand Down
29 changes: 7 additions & 22 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 012ea40

Please sign in to comment.