Created
March 18, 2025 08:45
-
-
Save sirius0486/a801f504e0a853ca7c405ed777420fb8 to your computer and use it in GitHub Desktop.
auth-provider.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"use client"; | |
import { getCookie } from "@/lib/utils"; | |
import { AuthContextType, UserInfo } from "@/types/user"; | |
import { createContext, useContext, useEffect, useState } from "react"; | |
const AuthContext = createContext<AuthContextType>({ | |
userInfo: null, | |
hasRole: () => false, | |
}); | |
export function UserInfoProvider({ children }: { children: React.ReactNode }) { | |
const [userInfo, setUserInfo] = useState<UserInfo | null>(null); | |
useEffect(() => { | |
const cookie = getCookie("user_info"); | |
console.log("user_info cookie", cookie); | |
if (cookie) { | |
try { | |
setUserInfo(JSON.parse(cookie)); | |
} catch (error) { | |
console.error("Error parsing user info cookie:", error); | |
} | |
} | |
// console.log("userInfo", userInfo); | |
}, []); | |
const hasRole = (role: string) => { | |
if (!userInfo) return false; | |
return userInfo.role.split(",").includes(role); | |
}; | |
return ( | |
<AuthContext.Provider value={{ userInfo, hasRole }}> | |
{children} | |
</AuthContext.Provider> | |
); | |
} | |
export const useAuth = () => useContext(AuthContext); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment