-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathauth.ts
More file actions
154 lines (139 loc) · 4.05 KB
/
Copy pathauth.ts
File metadata and controls
154 lines (139 loc) · 4.05 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
import NextAuth from "next-auth"
import Google from "next-auth/providers/google"
import Credentials from "next-auth/providers/credentials"
import bcrypt from "bcryptjs"
import dbConnect from "@/lib/mongodb"
import User from "@/lib/models/User"
export const { handlers, signIn, signOut, auth } = NextAuth({
trustHost: true,
providers: [
Google({
clientId: process.env.AUTH_GOOGLE_ID,
clientSecret: process.env.AUTH_GOOGLE_SECRET,
}),
Credentials({
credentials: {
email: { label: "Email", type: "email" },
password: { label: "Password", type: "password" },
},
authorize: async (credentials) => {
if (!credentials?.email || !credentials?.password) {
throw new Error("Missing credentials")
}
try {
const conn = await dbConnect()
if (!conn) {
throw new Error("Database connection failed")
}
const user = await User.findOne({ email: credentials.email })
if (!user) {
throw new Error("User not found")
}
if (!user.password) {
throw new Error("Please sign in with the provider you used to create your account")
}
const isValidPassword = await bcrypt.compare(credentials.password as string, user.password)
if (!isValidPassword) {
throw new Error("Invalid password")
}
return {
id: user._id.toString(),
email: user.email,
name: user.name,
image: user.image,
role: user.role || "user",
}
} catch (error) {
console.error("Authentication error:", error)
if (error instanceof Error) {
throw error
}
throw new Error("Authentication failed")
}
},
}),
],
pages: {
signIn: "/auth/signin",
},
callbacks: {
authorized: async ({ auth }) => {
return !!auth
},
async signIn({ user, account, profile }) {
if (account?.provider === "google") {
try {
await dbConnect()
let existingUser = await User.findOne({ email: user.email })
if (!existingUser) {
existingUser = await User.create({
name: user.name,
email: user.email,
image: user.image,
provider: "google",
})
}
user.id = existingUser._id.toString()
} catch (error) {
console.error("Error creating user:", error)
return false
}
}
return true
},
async jwt({ token, user, account }) {
if (user) {
token.id = user.id
token.role = user.role || "user"
} else if (account?.provider === "credentials" && !token.id) {
try {
await dbConnect()
const dbUser = await User.findOne({ email: token.email })
if (dbUser) {
token.id = dbUser._id.toString()
token.role = dbUser.role || "user"
}
} catch (error) {
console.error("Error fetching user for token:", error)
}
}
return token
},
async session({ session, token }) {
if (session.user) {
session.user.id = token.id as string
session.user.role = (token.role as "user" | "admin") || "user"
}
return session
},
},
session: {
strategy: "jwt",
},
})
export async function registerUser(name: string, email: string, password: string) {
try {
await dbConnect()
const existingUser = await User.findOne({ email })
if (existingUser) {
throw new Error("User already exists")
}
const hashedPassword = await bcrypt.hash(password, 10)
const newUser = await User.create({
name,
email,
password: hashedPassword,
provider: "credentials",
})
return {
id: newUser._id.toString(),
name: newUser.name,
email: newUser.email,
}
} catch (error) {
if (error instanceof Error) {
throw error
}
throw new Error("Failed to register user")
}
}