-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.ts
More file actions
71 lines (58 loc) · 1.67 KB
/
auth.ts
File metadata and controls
71 lines (58 loc) · 1.67 KB
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
66
67
68
69
70
import NextAuth, { type NextAuthOptions } from "next-auth"
import GitHubProvider from "next-auth/providers/github"
import GoogleProvider from "next-auth/providers/google"
import type { DefaultSession, Session, User } from "next-auth"
import type { JWT } from "next-auth/jwt"
import clientPromise from "@/lib/mongo"
declare module "next-auth" {
interface Session {
user: {
id: string
} & DefaultSession["user"]
}
}
declare module "next-auth/jwt" {
interface JWT {
id?: string
}
}
export const authOptions: NextAuthOptions = {
session: { strategy: "jwt" },
pages: {
signIn: "/auth/signin",
},
providers: [
GitHubProvider({
clientId: process.env.GITHUB_ID!,
clientSecret: process.env.GITHUB_SECRET!,
}),
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID!,
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
}),
],
callbacks: {
async signIn({ user }: { user: User }) {
if (!user?.email) return false
const client = await clientPromise
const db = client.db("cyclectl")
await db.collection("users").updateOne(
{ email: user.email },
{ $set: user },
{ upsert: true }
)
const mongoUser = await db.collection("users").findOne({ email: user.email })
if (mongoUser) user.id = mongoUser._id.toString()
return true
},
async jwt({ token, user }: { token: JWT; user?: User }) {
if (user?.id) token.id = user.id
return token
},
async session({ session, token }: { session: Session; token: JWT }) {
if (token.id) session.user.id = token.id as string
return session
},
},
}
export default NextAuth(authOptions)