Skip to content

Instantly share code, notes, and snippets.

@sirius0486
Created March 18, 2025 08:45
Show Gist options
  • Save sirius0486/a801f504e0a853ca7c405ed777420fb8 to your computer and use it in GitHub Desktop.
Save sirius0486/a801f504e0a853ca7c405ed777420fb8 to your computer and use it in GitHub Desktop.
auth-provider.tsx
"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