How can I redirect to my home page when user doesn’t have the required permissions to access a page. I’m using this custom made AuthGuard
import { ReactNode, useEffect, useState } from 'react';
import { useRouter } from 'next/router';
import { useFirebaseAuth } from '@/contexts/FirebaseAuthContext';
import { can } from '@/lib/acl';
import { Loader } from '@/components/Loader';
export type ChildrenType = {
children: ReactNode;
requiredPermission?: { action: string; subject: string };
};
export default function AuthGuard({
children,
requiredPermission
}: ChildrenType) {
const { user, role, loading } = useFirebaseAuth();
const router = useRouter();
const [isAuthorized, setIsAuthorized] = useState(false);
useEffect(() => {
console.log('Loading', loading);
console.log('AuthGuard user', user);
if (!loading) {
if (user && role && requiredPermission) {
if (!can(role, requiredPermission.action, requiredPermission.subject)) {
router.push('/dashboard');
setIsAuthorized(false);
} else {
setIsAuthorized(true);
}
}
// else {
// // Redirect to home if he's not logged in (no user)
// router.push('/home');
// }
}
}, [role, loading, requiredPermission, router, user]);
if (loading || !isAuthorized) {
return <Loader />;
}
return <>{children}</>;
}
Unfortunately with this AuthGuard, if I comment out the router.push to home I always get redirected to the home page when I navigate to the link directly for both authenticated and unauthenticated users, so I commented it out and now it works correctly for authenticated user. I can navigate directly to a link that is protected and not get redirected to home page for an authenticated user, but now the problem is I want to still redirect to home page for unauthenticated user