ddbb79b9f6
单容器 Docker 架构的国土空间规划课程智能问答系统,集成 FastAPI 后端与 Next.js 前端。 Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
85 lines
2.2 KiB
TypeScript
85 lines
2.2 KiB
TypeScript
import { NextAuthOptions } from "next-auth";
|
|
import CredentialsProvider from "next-auth/providers/credentials";
|
|
import { z } from "zod";
|
|
|
|
const loginSchema = z.object({
|
|
username: z.string().min(1, "用户名不能为空"),
|
|
password: z.string().min(1, "密码不能为空"),
|
|
});
|
|
|
|
export const authOptions: NextAuthOptions = {
|
|
providers: [
|
|
CredentialsProvider({
|
|
name: "credentials",
|
|
credentials: {
|
|
username: { label: "用户名", type: "text" },
|
|
password: { label: "密码", type: "password" },
|
|
},
|
|
async authorize(credentials) {
|
|
if (!credentials) return null;
|
|
|
|
try {
|
|
const validatedFields = loginSchema.safeParse(credentials);
|
|
|
|
if (!validatedFields.success) {
|
|
return null;
|
|
}
|
|
|
|
const { username, password } = validatedFields.data;
|
|
|
|
// 调用后端API进行认证
|
|
const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/auth/login`, {
|
|
method: "POST",
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
},
|
|
body: JSON.stringify({ username, password }),
|
|
});
|
|
|
|
if (!response.ok) {
|
|
return null;
|
|
}
|
|
|
|
const user = await response.json();
|
|
|
|
return {
|
|
id: user.id.toString(),
|
|
username: user.username,
|
|
email: user.email,
|
|
name: user.full_name || user.username,
|
|
};
|
|
} catch (error) {
|
|
console.error("认证错误:", error);
|
|
return null;
|
|
}
|
|
},
|
|
}),
|
|
],
|
|
callbacks: {
|
|
async jwt({ token, user }) {
|
|
if (user) {
|
|
token.id = user.id;
|
|
token.username = (user as any).username;
|
|
token.email = user.email;
|
|
}
|
|
return token;
|
|
},
|
|
async session({ session, token }) {
|
|
if (token && session.user) {
|
|
(session.user as any).id = token.id as string;
|
|
(session.user as any).username = token.username as string;
|
|
(session.user as any).email = token.email as string;
|
|
}
|
|
return session;
|
|
},
|
|
},
|
|
pages: {
|
|
signIn: "/login",
|
|
error: "/login",
|
|
},
|
|
session: {
|
|
strategy: "jwt",
|
|
},
|
|
secret: process.env.NEXTAUTH_SECRET,
|
|
};
|