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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
| import {NextAuthOptions} from "next-auth";
import {PrismaAdapter} from "@next-auth/prisma-adapter";
import {PrismaClient} from "@prisma/client";
import CredentialsProvider from "next-auth/providers/credentials";
import GitHubProvider from "next-auth/providers/github";
import bcrypt from "bcryptjs";
// 创建 Prisma 客户端实例
const prisma = new PrismaClient();
// 定义 NextAuth 的配置选项
export const authOptions: NextAuthOptions = {
// 使用 Prisma 适配器来处理数据库操作
adapter: PrismaAdapter(prisma),
// 配置身份验证提供者
providers: [
// 使用邮箱密码的凭证提供者
CredentialsProvider({
name: "Credentials",
credentials: {
email: {label: "Email", type: "text"},
password: {label: "Password", type: "password"}
},
// 验证用户凭证
async authorize(credentials) {
if (!credentials?.email || !credentials?.password) {
throw new Error("Missing credentials");
}
// 在数据库中查找用户
const user = await prisma.user.findUnique({
where: {email: credentials.email}
});
if (!user || !user.password) {
throw new Error("User not found");
}
// 验证密码
const isPasswordValid = await bcrypt.compare(credentials.password, user.password);
if (!isPasswordValid) {
throw new Error("Invalid password");
}
return user;
}
}),
// GitHub OAuth 提供者
GitHubProvider({
clientId: process.env.GITHUB_ID!,
clientSecret: process.env.GITHUB_SECRET!,
}),
],
// 自定义认证页面路径
pages: {
signIn: '/auth/signin',
signOut: '/auth/signout',
error: '/auth/error',
verifyRequest: '/auth/verify-request',
},
// 使用 JWT 策略管理会话
session: {
strategy: "jwt",
},
// 回调函数配置
callbacks: {
// 登录回调
async signIn({user, account, profile, email, credentials}) {
try {
console.log("Sign In Callback:", {user, account, profile, email});
// 处理 GitHub 登录
if (account && account.provider === 'github' && profile) {
// 查找现有用户
const existingUser = await prisma.user.findFirst({
where: {
OR: [
{email: profile.email},
{accounts: {some: {providerAccountId: account.providerAccountId}}}
]
},
include: {accounts: true}
});
if (existingUser) {
// 如果用户存在但没有 GitHub 账号,则添加 GitHub 账号
if (!existingUser.accounts.some(acc => acc.provider === 'github')) {
await prisma.account.create({
data: {
userId: existingUser.id,
type: account.type,
provider: account.provider,
providerAccountId: account.providerAccountId,
access_token: account.access_token,
token_type: account.token_type,
scope: account.scope,
}
});
}
return true;
}
// 如果用户不存在,创建新用户
await prisma.user.create({
data: {
name: profile.name || (profile as any).login || 'Unknown',
email: profile.email || `${account.providerAccountId}@github.com`,
accounts: {
create: {
type: account.type,
provider: account.provider,
providerAccountId: account.providerAccountId,
access_token: account.access_token,
token_type: account.token_type,
scope: account.scope,
}
}
}
});
}
return true;
} catch (error) {
console.error("Error in signIn callback:", error);
return false;
}
},
// JWT 回调
async jwt({token, user, account}) {
if (user) {
token.id = user.id;
}
if (account && account.access_token) {
token.accessToken = account.access_token;
}
return token;
},
// 会话回调
async session({session, token}) {
if (session.user) {
(session.user as any).id = token.id as string;
(session as any).accessToken = token.accessToken;
}
return session;
},
// 重定向回调
async redirect({url, baseUrl}) {
// 允许相对回调 URL
if (url.startsWith("/")) return `${baseUrl}${url}`
// 允许同源的回调 URL
else if (new URL(url).origin === baseUrl) return url
return baseUrl
},
},
// 认证事件处理
events: {
async signIn(message) {
console.log("User signed in:", message)
},
async signOut(message) {
console.log("User signed out:", message)
},
async createUser(message) {
console.log("User created:", message)
},
async linkAccount(message) {
console.log("Account linked:", message)
},
async session(message) {
console.log("Session created:", message)
},
},
// 开发环境启用调试模式
debug: process.env.NODE_ENV === 'development',
// 日志配置
logger: {
error(code, metadata) {
console.error(code, metadata);
},
warn(code) {
console.warn(code);
},
debug(code, metadata) {
console.log(code, metadata);
},
},
};
|