44 lines
1.1 KiB
TypeScript
44 lines
1.1 KiB
TypeScript
import type { NextAuthConfig } from "next-auth";
|
|
|
|
export const authConfig = {
|
|
pages: {
|
|
signIn: "/login",
|
|
error: "/login",
|
|
},
|
|
callbacks: {
|
|
authorized({ auth, request: { nextUrl } }) {
|
|
const isLoggedIn = !!auth?.user;
|
|
const pathname = nextUrl.pathname;
|
|
const publicPaths = ["/login", "/register", "/api/auth"];
|
|
const isPublic = publicPaths.some(
|
|
(path) => pathname === path || pathname.startsWith("/api/auth/")
|
|
);
|
|
|
|
// 已登录用户在登录/注册页时重定向到首页
|
|
if (isLoggedIn && (pathname === "/login" || pathname === "/register")) {
|
|
return Response.redirect(new URL("/", nextUrl));
|
|
}
|
|
|
|
// 访问受保护页面必须已登录
|
|
if (!isLoggedIn && !isPublic) {
|
|
return false;
|
|
}
|
|
|
|
return true;
|
|
},
|
|
jwt({ token, user }) {
|
|
if (user?.id) {
|
|
token.id = user.id;
|
|
}
|
|
return token;
|
|
},
|
|
session({ session, token }) {
|
|
if (session.user && token.id) {
|
|
session.user.id = token.id as string;
|
|
}
|
|
return session;
|
|
},
|
|
},
|
|
providers: [],
|
|
} satisfies NextAuthConfig;
|