v0.11.1: 权限体系重构 + AI管线优化 + 内容整理
This commit is contained in:
+103
@@ -0,0 +1,103 @@
|
||||
import NextAuth from "next-auth";
|
||||
import CredentialsProvider from "next-auth/providers/credentials";
|
||||
import GithubProvider from "next-auth/providers/github";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import bcrypt from "bcryptjs";
|
||||
|
||||
export const authOptions = {
|
||||
providers: [
|
||||
CredentialsProvider({
|
||||
name: "credentials",
|
||||
credentials: {
|
||||
email: { label: "邮箱", type: "email" },
|
||||
password: { label: "密码", type: "password" },
|
||||
},
|
||||
async authorize(credentials) {
|
||||
if (!credentials?.email || !credentials?.password) return null;
|
||||
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { email: credentials.email },
|
||||
});
|
||||
|
||||
if (!user || !user.passwordHash) return null;
|
||||
|
||||
const isValid = await bcrypt.compare(
|
||||
credentials.password,
|
||||
user.passwordHash
|
||||
);
|
||||
if (!isValid) return null;
|
||||
|
||||
return {
|
||||
id: user.id.toString(),
|
||||
email: user.email,
|
||||
name: user.name,
|
||||
role: user.role,
|
||||
};
|
||||
},
|
||||
}),
|
||||
GithubProvider({
|
||||
clientId: process.env.GITHUB_CLIENT_ID!,
|
||||
clientSecret: process.env.GITHUB_CLIENT_SECRET!,
|
||||
}),
|
||||
],
|
||||
callbacks: {
|
||||
async signIn({ user, account, profile }: any) {
|
||||
if (account?.provider === "github" && profile) {
|
||||
const oauthId = profile.id?.toString();
|
||||
const email = profile.email || user.email;
|
||||
|
||||
if (!oauthId) return false;
|
||||
|
||||
const existing = await prisma.user.findFirst({
|
||||
where: {
|
||||
oauthProvider: "github",
|
||||
oauthId,
|
||||
},
|
||||
});
|
||||
|
||||
if (!existing) {
|
||||
const newUser = await prisma.user.create({
|
||||
data: {
|
||||
email: email || `github_${oauthId}@placeholder.com`,
|
||||
name: profile.name || user.name || null,
|
||||
avatarUrl: profile.avatar_url || user.image || null,
|
||||
oauthProvider: "github",
|
||||
oauthId,
|
||||
role: "user",
|
||||
},
|
||||
});
|
||||
user.id = newUser.id.toString();
|
||||
user.role = newUser.role;
|
||||
} else {
|
||||
user.id = existing.id.toString();
|
||||
user.role = existing.role;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
},
|
||||
async jwt({ token, user }: any) {
|
||||
if (user) {
|
||||
token.id = user.id;
|
||||
token.role = user.role;
|
||||
}
|
||||
return token;
|
||||
},
|
||||
async session({ session, token }: any) {
|
||||
if (session.user) {
|
||||
session.user.id = token.id;
|
||||
session.user.role = token.role;
|
||||
}
|
||||
return session;
|
||||
},
|
||||
},
|
||||
pages: {
|
||||
signIn: "/admin/login",
|
||||
},
|
||||
session: {
|
||||
strategy: "jwt" as const,
|
||||
},
|
||||
secret: process.env.NEXTAUTH_SECRET,
|
||||
};
|
||||
|
||||
const handler = NextAuth(authOptions);
|
||||
export { handler as GET, handler as POST };
|
||||
Reference in New Issue
Block a user