Skip to content

Instantly share code, notes, and snippets.

@pavankjadda
Created August 13, 2021 15:31
Show Gist options
  • Save pavankjadda/18e22c11fbbc6d28497d39c9fb982e24 to your computer and use it in GitHub Desktop.
Save pavankjadda/18e22c11fbbc6d28497d39c9fb982e24 to your computer and use it in GitHub Desktop.
ReadOnly Access Guarded Route
import * as React from 'react';
import {Redirect, Route,} from 'react-router-dom';
import ReactIf from "../components/shared/ReactIf";
import useAuthService from "../hooks/useAuthService";

export function ReadOnlyAccessGuardedRoute(props: { component: any; path: string; isAuthorized: boolean, exact: boolean }): JSX.Element {
    const {component: Component, isAuthorized, ...rest} = props;
    const {isUserLoggedIn} = useAuthService();
    return (
        <Route
            {...rest}
            render={(routeProps) =>
                <div>
                    {/* If not logged in, redirect to Login page */}
                    <ReactIf condition={!isUserLoggedIn()}>
                        <Redirect
                            to={{
                                pathname: '/login',
                                state: {from: routeProps?.location}
                            }}
                        />
                    </ReactIf>

                    {/* If logged in and has Read Only User role, navigate to component */}
                    <ReactIf condition={isUserLoggedIn() && isAuthorized}>
                        <Component {...routeProps} />
                    </ReactIf>

                    {/* If logged in but does not Read Only User role, navigate to Unauthorized page */}
                    <ReactIf condition={isUserLoggedIn() && !isAuthorized}>
                        <Redirect
                            to={{
                                pathname: '/unauthorized',
                                state: {from: routeProps?.location}
                            }}
                        />
                    </ReactIf>
                </div>
            }
        />
    );
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment