2025.11.27.17.50
This commit is contained in:
80
src/hooks/useAuth.tsx
Normal file
80
src/hooks/useAuth.tsx
Normal file
@@ -0,0 +1,80 @@
|
||||
import { useState, useEffect, createContext, useContext } from 'react';
|
||||
import { useRouter } from 'next/router';
|
||||
|
||||
interface User {
|
||||
_id: string;
|
||||
用户名: string;
|
||||
邮箱: string;
|
||||
头像: string;
|
||||
角色: string;
|
||||
钱包?: {
|
||||
当前积分: number;
|
||||
历史总消费: number;
|
||||
};
|
||||
会员信息?: {
|
||||
当前等级ID?: {
|
||||
_id: string;
|
||||
套餐名称: string;
|
||||
};
|
||||
过期时间?: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface AuthContextType {
|
||||
user: User | null;
|
||||
loading: boolean;
|
||||
logout: () => Promise<void>;
|
||||
refreshUser: () => Promise<void>;
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthContextType>({
|
||||
user: null,
|
||||
loading: true,
|
||||
logout: async () => { },
|
||||
refreshUser: async () => { },
|
||||
});
|
||||
|
||||
export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
const [user, setUser] = useState<User | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const router = useRouter();
|
||||
|
||||
const fetchUser = async () => {
|
||||
try {
|
||||
const res = await fetch('/api/auth/me');
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
setUser(data.user);
|
||||
} else {
|
||||
setUser(null);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch user', error);
|
||||
setUser(null);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
fetchUser();
|
||||
}, []);
|
||||
|
||||
const logout = async () => {
|
||||
try {
|
||||
await fetch('/api/auth/logout', { method: 'POST' });
|
||||
setUser(null);
|
||||
router.push('/auth/login');
|
||||
} catch (error) {
|
||||
console.error('Logout failed', error);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{ user, loading, logout, refreshUser: fetchUser }}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export const useAuth = () => useContext(AuthContext);
|
||||
Reference in New Issue
Block a user