Revert "feat: use middleware to auth"

This reverts commit f57cdb5ec1.
This commit is contained in:
shinya
2025-06-30 23:17:05 +08:00
parent afef6d9865
commit 240764e81b
5 changed files with 53 additions and 92 deletions

View File

@@ -0,0 +1,46 @@
'use client';
import { usePathname, useRouter } from 'next/navigation';
import { useEffect } from 'react';
interface Props {
children: React.ReactNode;
}
export default function AuthProvider({ children }: Props) {
const router = useRouter();
const pathname = usePathname();
useEffect(() => {
// 登录页或 API 路径不做校验,避免死循环
if (pathname.startsWith('/login')) return;
const password = localStorage.getItem('password');
const fullPath =
typeof window !== 'undefined'
? window.location.pathname + window.location.search
: pathname;
// 有密码时验证
(async () => {
try {
const res = await fetch('/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ password }),
});
if (!res.ok) {
// 校验未通过,清理并跳转登录
localStorage.removeItem('password');
router.replace(`/login?redirect=${encodeURIComponent(fullPath)}`);
}
} catch (error) {
// 网络错误等也认为未登录
router.replace(`/login?redirect=${encodeURIComponent(fullPath)}`);
}
})();
}, [pathname, router]);
return <>{children}</>;
}