Skip to content

Commit

Permalink
Check if user is admin
Browse files Browse the repository at this point in the history
  • Loading branch information
chunweii committed Oct 26, 2023
1 parent 38eefe3 commit ffb99e9
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 8 deletions.
3 changes: 2 additions & 1 deletion frontend/src/components/common/navbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ enum TabsOptions {
}

export default function Navbar() {
const { user: currentUser, authIsReady } = useContext(AuthContext);
const { user: currentUser, authIsReady, isAdmin } = useContext(AuthContext);
const [activeTab, setActiveTab] = useState<TabsOptions>(TabsOptions.NULL);

const { login } = useLogin();
Expand Down Expand Up @@ -79,6 +79,7 @@ export default function Navbar() {
</div>
)}
</div>
{isAdmin && <p>Admin Page</p>}
{!currentUser && (
<div className="grid grid-cols-2 gap-4">
<Button variant={"outline"} onClick={login}>
Expand Down
16 changes: 9 additions & 7 deletions frontend/src/contexts/AuthContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,22 @@ import { auth } from "../firebase-client/firebase_config";
type AuthState = {
user: User | null;
authIsReady: boolean;
isAdmin: boolean;
}

const initial_state : AuthState = {
user: null,
authIsReady: false,
isAdmin: false
};

export var AuthContext = React.createContext<{
user: User | null;
authIsReady: boolean;
isAdmin: boolean;
dispatch: React.Dispatch<any>;
}>({
user: null,
authIsReady: false,
...initial_state,
dispatch: () => null
});

Expand All @@ -29,7 +31,7 @@ const authReducer = (state : AuthState, action : any) : AuthState => {
case "LOGOUT":
return { ...state, user: null };
case "AUTH_IS_READY":
return { ...state, user: action.payload, authIsReady: true };
return { ...state, user: action.payload, isAdmin: action.isAdmin, authIsReady: true };
default:
return state;
}
Expand All @@ -38,11 +40,11 @@ const authReducer = (state : AuthState, action : any) : AuthState => {
const AuthContextProvider = ({ children } : any) => {
const [state, dispatch] = React.useReducer(authReducer, initial_state);

console.log(state);

React.useEffect(() => {
const unsubscribe = onAuthStateChanged(auth, (user) => {
dispatch({ type: "AUTH_IS_READY", payload: user });
const unsubscribe = onAuthStateChanged(auth, async (user) => {
const idTokenResult = await user?.getIdTokenResult();

dispatch({ type: "AUTH_IS_READY", payload: user, isAdmin: idTokenResult?.claims?.admin || false });
});
return unsubscribe;
}, []);
Expand Down

0 comments on commit ffb99e9

Please sign in to comment.