Skip to content

Commit

Permalink
feat: actually fix protected route
Browse files Browse the repository at this point in the history
  • Loading branch information
KevinWu098 committed Sep 2, 2024
1 parent 7f750fc commit bf8a2da
Show file tree
Hide file tree
Showing 9 changed files with 27 additions and 101 deletions.
10 changes: 1 addition & 9 deletions src/components/BusinessForm/BusinessForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ const ADDITIONAL_INFO_ITEMS = [
export const BusinessForm = ({ edit = true }) => {
const { id } = useParams();
const { backend } = useBackend();
const { isAdmin, currentUser } = useAuth();
const { currentUser } = useAuth();
const navigate = useNavigate();

const deleteDisclosure = useDisclosure();
Expand Down Expand Up @@ -108,14 +108,6 @@ export const BusinessForm = ({ edit = true }) => {
const [notification, setNotification] = useState([]);

useEffect(() => {
const checkIsAdmin = async () => {
if (!(await isAdmin())) {
navigate('/BusinessDashboard');
}
};

checkIsAdmin();

const fetchNotifications = async () => {
const response = await backend.get('/notification/0');
setNotification(response.data);
Expand Down
2 changes: 1 addition & 1 deletion src/components/BusinessSetup/SetupSignup.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ export const SetupSignup = ({ admin, nextStep }: SetUpFirstFormProps) => {
setLoading(true);

if (admin) {
if (await isAdmin()) {
if (isAdmin) {
await signup({ email, password });
navigate('/AdminDashboard');
} else {
Expand Down
14 changes: 5 additions & 9 deletions src/components/CatchAll.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,11 @@ export const CatchAll = () => {
const navigate = useNavigate();

useEffect(() => {
const checkIsAdmin = async () => {
if (await isAdmin()) {
navigate('/AdminDashboard');
} else {
navigate('/BusinessDashboard');
}
};

checkIsAdmin();
if (isAdmin) {
navigate('/AdminDashboard');
} else {
navigate('/BusinessDashboard');
}
}, []);

return <p>Route not found... redirecting...</p>;
Expand Down
11 changes: 0 additions & 11 deletions src/components/DonationItemsTable/DonationItemsTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,7 @@ import {
Tr,
useDisclosure,
} from '@chakra-ui/react';
import { useNavigate } from 'react-router-dom';

import { useAuth } from '../../contexts/AuthContext';
import { useBackend } from '../../contexts/BackendContext';
import { pageStyle, pageTitleStyle } from '../../styles/sharedStyles';
import { Donation } from '../../types/donation';
Expand All @@ -32,24 +30,15 @@ import DonationsDeleteConfirmationModal from './DonationsDeleteConfirmationModal
import { DonationsModal } from './DonationsModal';

export const DonationItemsTable = () => {
const { isAdmin } = useAuth();
const [notifications, setNotifications] = useState([]);
const { backend } = useBackend();
const navigate = useNavigate();

useEffect(() => {
const checkIsAdmin = async () => {
if (!(await isAdmin())) {
navigate('/BusinessDashboard');
}
};

const fetchNotifications = async () => {
const response = await backend.get('/notification/0');
setNotifications(response.data);
};

checkIsAdmin();
fetchNotifications();
}, [backend]);

Expand Down
12 changes: 0 additions & 12 deletions src/components/DonationTrackingTable/DonationTrackingTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,7 @@ import {
Tr,
useToast,
} from '@chakra-ui/react';
import { useNavigate } from 'react-router-dom';

import { useAuth } from '../../contexts/AuthContext';
import { useBackend } from '../../contexts/BackendContext';
import { pageStyle, pageTitleStyle } from '../../styles/sharedStyles';
import { Donation } from '../../types/donation';
Expand All @@ -51,9 +49,7 @@ const TAB_HEADERS = ['month', 'quarter', 'year', 'all'];

export const DonationTrackingTable = () => {
const { backend } = useBackend();
const { isAdmin } = useAuth();
const toast = useToast();
const navigate = useNavigate();

const [donationTrackingTableData, setDonationTrackingTableData] = useState<Donation[]>([]);
const [checkedSet, setCheckedSet] = useState<Set<number>>(new Set());
Expand All @@ -74,12 +70,6 @@ export const DonationTrackingTable = () => {
};

useEffect(() => {
const checkIsAdmin = async () => {
if (!(await isAdmin())) {
navigate('/BusinessDashboard');
}
};

const getNotifications = async () => {
try {
const notificationResponse = await backend.get(`/notification/0`);
Expand All @@ -89,8 +79,6 @@ export const DonationTrackingTable = () => {
}
};

checkIsAdmin();

try {
getNotifications();
} catch (error) {
Expand Down
17 changes: 3 additions & 14 deletions src/components/Sidebar/Sidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,19 +46,8 @@ const ADMIN_SIDEBAR = [
export const Sidebar = () => {
const { backend } = useBackend();

const [isAdminUser, setIsAdminUser] = useState(false);
const { isOpen, onOpen, onClose } = useDisclosure();

useEffect(() => {
const checkIsAdmin = async () => {
if (await isAdmin()) {
setIsAdminUser(true);
}
};

checkIsAdmin();
}, []);

useEffect(() => {
getBusinessName();
}, [backend]);
Expand All @@ -83,7 +72,7 @@ export const Sidebar = () => {
}
};

const navList = isAdminUser ? ADMIN_SIDEBAR : BUSINESS_SIDEBAR;
const navList = isAdmin ? ADMIN_SIDEBAR : BUSINESS_SIDEBAR;

return (
<>
Expand All @@ -109,7 +98,7 @@ export const Sidebar = () => {

{/* fix me */}
<Text color="teal" fontWeight="bold">
{isAdminUser ? 'Feeding Pets of the Homeless' : businessName}
{isAdmin ? 'Feeding Pets of the Homeless' : businessName}
</Text>
</HStack>

Expand All @@ -131,7 +120,7 @@ export const Sidebar = () => {

<Flex flexDirection="column" w="100%">
<VStack>
{!isAdminUser && (
{!isAdmin && (
<Button
onClick={onOpen}
width="full"
Expand Down
10 changes: 0 additions & 10 deletions src/components/ViewBusiness/ViewBusiness.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@ import {
import { BiEnvelope, BiPackage, BiPencil, BiTrash } from 'react-icons/bi';
import { useNavigate, useParams } from 'react-router-dom';

import { useAuth } from '../../contexts/AuthContext';
import { useBackend } from '../../contexts/BackendContext';
import { pageStyle, pageTitleStyle } from '../../styles/sharedStyles';
import { Business } from '../../types/business';
Expand Down Expand Up @@ -75,7 +74,6 @@ const formatCreatedBy = (createdBy: string) => {
};

export const ViewBusiness = () => {
const { isAdmin } = useAuth();
const { backend } = useBackend();
const { id } = useParams();
const navigate = useNavigate();
Expand Down Expand Up @@ -220,14 +218,6 @@ export const ViewBusiness = () => {
};

useEffect(() => {
const checkIsAdmin = async () => {
if (!(await isAdmin())) {
navigate('/BusinessDashboard');
}
};

checkIsAdmin();

if (id) {
fetchBusiness();
}
Expand Down
21 changes: 15 additions & 6 deletions src/contexts/AuthContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,12 @@ import { useBackend } from './BackendContext';

interface AuthContextType {
currentUser?: User | null;
isAdmin: boolean;
signup: (credentials: EmailPassword) => Promise<UserCredential>;
login: (credentials: EmailPassword) => Promise<UserCredential>;
logout: () => Promise<void>;
resetPassword: (email: { email: string }) => Promise<void>;
isAdmin: (user?: User | null) => Promise<boolean | undefined>;
getIsAdmin: () => Promise<boolean | undefined>;
}

type EmailPassword = {
Expand All @@ -38,8 +39,9 @@ export function useAuth() {
}

export function AuthProvider({ children }: { children: ReactNode }) {
const [currentUser, setCurrentUser] = useState<User>();
const [currentUser, setCurrentUser] = useState<User | null>(null);
const [loading, setLoading] = useState(true);
const [isAdmin, setIsAdmin] = useState<boolean | undefined>(undefined);

const { backend } = useBackend();

Expand All @@ -66,22 +68,28 @@ export function AuthProvider({ children }: { children: ReactNode }) {
return sendPasswordResetEmail(auth, email);
};

const isAdmin = async (user = currentUser) => {
const getIsAdmin = async (user = currentUser) => {
if (user !== null) {
try {
const response = await backend.get(`/adminUser/${user.email}`);

return response.data.length > 0;
} catch (error) {
console.error('Error checking isAdmin', error);
return false;
}
}
return false;
};

useEffect(() => {
const unsubscribe = auth.onAuthStateChanged((user) => {
const unsubscribe = auth.onAuthStateChanged(async (user) => {
setCurrentUser(user);
if (user) {
const adminStatus = await getIsAdmin(user);
setIsAdmin(adminStatus);
} else {
setIsAdmin(false);
}
setLoading(false);
});

Expand All @@ -90,11 +98,12 @@ export function AuthProvider({ children }: { children: ReactNode }) {

const value: AuthContextType = {
currentUser,
isAdmin,
signup,
login,
logout,
resetPassword,
isAdmin,
getIsAdmin,
};

return <AuthContext.Provider value={value}>{!loading && children}</AuthContext.Provider>;
Expand Down
31 changes: 2 additions & 29 deletions src/utils/ProtectedRoute.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { useEffect, useState } from 'react';
import { Navigate } from 'react-router-dom';

import { useAuth } from '../contexts/AuthContext';
Expand All @@ -11,35 +10,9 @@ interface ProtectedRouteProps {
export const ProtectedRoute = ({ Component, isAdminRoute = false }: ProtectedRouteProps) => {
const { currentUser, isAdmin } = useAuth();

const [isLoading, setIsLoading] = useState(true);
const [isAuthenticated, setIsAuthenticated] = useState(false);
const [isNonAdminOnAdminRoute, setIsNonAdminOnAdminRoute] = useState(false);

useEffect(() => {
const checkAuth = async () => {
setIsAuthenticated(currentUser !== null);

const isUserAdmin = await isAdmin(currentUser);

if (!isUserAdmin && isAdminRoute) {
setIsNonAdminOnAdminRoute(true);
}

setIsLoading(false);
};

checkAuth();
setIsAuthenticated(currentUser !== null);
setIsLoading(false);
}, []);

if (isLoading) {
return <h1>Loading...</h1>;
}

if (isNonAdminOnAdminRoute) {
if (!isAdmin && isAdminRoute) {
return <Navigate to={'/BusinessDashboard'} />;
}

return isAuthenticated ? <Component /> : <Navigate to={'/login'} />;
return currentUser ? <Component /> : <Navigate to={'/login'} />;
};

0 comments on commit bf8a2da

Please sign in to comment.