-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.ts
More file actions
175 lines (159 loc) · 4.89 KB
/
Copy pathauth.ts
File metadata and controls
175 lines (159 loc) · 4.89 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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
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({
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 {
await dbConnect()
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,
}
} catch (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",
role: "individual", // Default role for new users
})
}
// Set the user ID for JWT
user.id = existingUser._id.toString()
} catch (error) {
console.error("Error creating user:", error)
return false
}
}
return true
},
async redirect({ url, baseUrl }) {
// If URL is relative, use it
if (url.startsWith("/")) return `${baseUrl}${url}`
// If URL is from same site, use it
if (url.startsWith(baseUrl)) return url
// Otherwise go to dashboard (onboarding page will handle redirect if needed)
return baseUrl + "/dashboard"
},
async jwt({ token, user, account }) {
if (user) {
token.id = user.id
} else if (account?.provider === "credentials" && !token.id) {
// For credentials provider, get user from DB to ensure we have the ID
try {
await dbConnect()
const dbUser = await User.findOne({ email: token.email })
if (dbUser) {
token.id = dbUser._id.toString()
token.role = dbUser.role
token.organizationId = dbUser.organizationId
}
} catch (error) {
console.error("Error fetching user for token:", error)
}
}
// Always refresh role and organization from DB
if (token.id && !user) {
try {
await dbConnect()
const dbUser = await User.findById(token.id)
if (dbUser) {
token.role = dbUser.role
token.organizationId = dbUser.organizationId
}
} catch (error) {
console.error("Error refreshing token data:", error)
}
}
return token
},
async session({ session, token }) {
if (session.user) {
session.user.id = token.id as string
session.user.role = (token.role as any) || "individual"
session.user.organizationId = token.organizationId as string | undefined
}
return session
},
},
session: {
strategy: "jwt",
},
})
// Helper function to register new users
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")
}
}