feat: Enhance NextAuth session management with extended session duration and dynamic token updates

This commit is contained in:
wood chen 2025-02-21 22:42:54 +08:00
parent efc5dd6b39
commit cd62f1589f
2 changed files with 22 additions and 10 deletions

View File

@ -7,7 +7,11 @@ import { prisma } from "./lib/prisma";
export const { handlers, auth, signIn, signOut } = NextAuth({
adapter: PrismaAdapter(prisma),
session: { strategy: "jwt" },
session: {
strategy: "jwt",
maxAge: 30 * 24 * 60 * 60, // 30 days
updateAge: 24 * 60 * 60, // 24 hours
},
pages: {
signIn: "/sign-in",
},
@ -42,7 +46,22 @@ export const { handlers, auth, signIn, signOut } = NextAuth({
session.user.name = token.name;
return session;
},
async jwt({ token }) {
async jwt({ token, user, trigger, session }) {
if (trigger === "update" && session) {
// 当收到更新触发时,重新获取用户信息
const dbUser = await getUserById(token.sub!);
if (dbUser) {
token.username = dbUser.username;
token.email = dbUser.email;
token.picture = dbUser.avatarUrl;
token.name = dbUser.name;
token.role = dbUser.role;
token.moderator = dbUser.moderator;
token.groups = dbUser.groups;
}
return token;
}
if (!token.sub) return token;
const dbUser = await getUserById(token.sub);

View File

@ -21,18 +21,11 @@ import { ThemeToggle } from "../theme-toggle";
import { Button } from "../ui/button";
export function NavBar() {
const { data: session, status, update } = useSession();
const { data: session, status } = useSession();
const router = useRouter();
const pathname = usePathname();
const user = session?.user;
useEffect(() => {
// 当路由变化时,尝试更新 session
if (pathname === "/dashboard" || pathname.startsWith("/dashboard/")) {
update();
}
}, [pathname, update]);
const handleSignOut = async () => {
await signOut({ redirect: false });
router.refresh();