75 lines
1.7 KiB
TypeScript
75 lines
1.7 KiB
TypeScript
import type { NextAuthOptions } from "next-auth"
|
|
import CredentialsProvider from "next-auth/providers/credentials"
|
|
import { prisma } from "./prisma"
|
|
import bcrypt from "bcryptjs"
|
|
|
|
export const authOptions: NextAuthOptions = {
|
|
providers: [
|
|
CredentialsProvider({
|
|
name: "credentials",
|
|
credentials: {
|
|
email: { label: "Email", type: "email" },
|
|
password: { label: "Password", type: "password" }
|
|
},
|
|
async authorize(credentials) {
|
|
if (!credentials?.email || !credentials?.password) {
|
|
throw new Error("请输入邮箱和密码")
|
|
}
|
|
|
|
const user = await prisma.user.findUnique({
|
|
where: { email: credentials.email }
|
|
})
|
|
|
|
if (!user || !user.password) {
|
|
throw new Error("用户不存在")
|
|
}
|
|
|
|
const isValid = await bcrypt.compare(credentials.password, user.password)
|
|
|
|
if (!isValid) {
|
|
throw new Error("密码错误")
|
|
}
|
|
|
|
return {
|
|
id: user.id,
|
|
email: user.email,
|
|
name: user.name,
|
|
}
|
|
}
|
|
})
|
|
],
|
|
session: {
|
|
strategy: "jwt"
|
|
},
|
|
pages: {
|
|
signIn: "/auth/signin",
|
|
},
|
|
callbacks: {
|
|
async jwt({ token, user }) {
|
|
if (user) {
|
|
token.id = user.id
|
|
}
|
|
return token
|
|
},
|
|
async session({ session, token }) {
|
|
if (session.user) {
|
|
session.user.id = token.id as string
|
|
}
|
|
return session
|
|
}
|
|
},
|
|
// 强制不使用 Secure Cookie,解决代理访问时的协议误判问题
|
|
useSecureCookies: false,
|
|
cookies: {
|
|
sessionToken: {
|
|
name: `next-auth.session-token`,
|
|
options: {
|
|
httpOnly: true,
|
|
sameSite: 'lax',
|
|
path: '/',
|
|
secure: false
|
|
}
|
|
}
|
|
}
|
|
}
|