Last active
March 26, 2022 08:22
-
-
Save azeezat/32aa126779007b65b2d17bda39fe4d0a to your computer and use it in GitHub Desktop.
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
import { appRoutes } from "../constants"; | |
import { useAuthContext } from "../contexts"; | |
//check if you are on the client (browser) or server | |
const isBrowser = () => typeof window !== "undefined"; | |
const ProtectedRoute = ({ router, children }) => { | |
//Identify authenticated user | |
const { user } = useAuthContext(); | |
const isAuthenticated = user.isLoggedIn; | |
let unprotectedRoutes = [ | |
appRoutes.LOGIN_PAGE, | |
appRoutes.FORGOT_PASSWORD, | |
appRoutes.RESET_PASSWORD, | |
appRoutes.EMAIL_SENT, | |
appRoutes.VERIFY_EMAIL, | |
appRoutes.NEWS_FEED_PAGE, | |
appRoutes.CONTENT_DETAILS_PAGE, | |
appRoutes.ABOUT_US_PAGE, | |
]; | |
/** | |
* @var pathIsProtected Checks if path exists in the unprotectedRoutes routes array | |
*/ | |
let pathIsProtected = unprotectedRoutes.indexOf(router.pathname) === -1; | |
if (isBrowser() && !isAuthenticated && pathIsProtected) { | |
router.push(appRoutes.LOGIN_PAGE); | |
} | |
return children; | |
}; | |
export default ProtectedRoute; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment