Last active
May 30, 2021 04:50
-
-
Save jmaicaaan/e860ea766a8417fce4cd932247ee64d2 to your computer and use it in GitHub Desktop.
Protected Route
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 { RouteProps } from 'react-router-dom'; | |
import { GuardFunction } from '../types/guard'; | |
import { tryCatchSync } from '../utils/tryCatch'; | |
export type GuardFunctionArgs = RouteProps; | |
export type GuardFunction = (args: GuardFunctionArgs) => boolean; | |
type User = { | |
firstName: string; | |
lastName: string; | |
roles: string[]; | |
}; | |
export const AdminGuard: GuardFunction = () => { | |
const [user, err] = tryCatchSync<User>(() => ( | |
// TODO - create a hook | |
JSON.parse(window.localStorage.getItem('user') || '') | |
)); | |
// Error from `JSON.parse` | |
if (err) { | |
return false; | |
} | |
// If no user found in the local storage | |
if (!user) { | |
return false; | |
} | |
// If no roles found in the user data | |
if (!user.roles.length) { | |
return false; | |
} | |
// If the user roles includes `admin` allow to access the route | |
return user.roles.includes('admin'); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment