Skip to content

Instantly share code, notes, and snippets.

@jmaicaaan
Last active May 30, 2021 04:50
Show Gist options
  • Save jmaicaaan/e860ea766a8417fce4cd932247ee64d2 to your computer and use it in GitHub Desktop.
Save jmaicaaan/e860ea766a8417fce4cd932247ee64d2 to your computer and use it in GitHub Desktop.
Protected Route
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