-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.ts
66 lines (56 loc) · 1.46 KB
/
auth.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import NextAuth , { type DefaultSession } from "next-auth"
import Google from "next-auth/providers/google"
import PostgresAdapter from "@auth/pg-adapter"
import { Pool } from "pg"
import OpenAI from "openai"
const pool = new Pool({
connectionString: process.env.POSTGRES_URL,
})
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
})
declare module "next-auth" {
interface Session {
user: {
thread: string
} & DefaultSession["user"]
}
interface User {
thread: string;
}
}
export const { handlers, signIn, signOut, auth } = NextAuth({
adapter: PostgresAdapter(pool),
providers: [Google],
events: {
async signIn({ user }) {
const client = await pool.connect()
try {
// Check if the user has a thread
const result = await client.query(
'SELECT thread FROM users WHERE id = $1',
[user.id]
)
if (result.rows.length > 0 && result.rows[0].thread) {
// Thread exists, do nothing
return
}
// Create a new thread
const thread = await openai.beta.threads.create()
// Update the user's thread in the database
await client.query(
'UPDATE users SET thread = $1 WHERE id = $2',
[thread.id, user.id]
)
} finally {
client.release()
}
},
},
callbacks: {
async session({ session, user }) {
session.user.thread = user.thread
return session
},
},
})