PrivateRoute.js 877 Bytes
Newer Older
Kim, Subin's avatar
Kim, Subin committed
1
import { Redirect, Route } from "react-router-dom";
2
import { useAuth } from "../utils/context.js"
Kim, Subin's avatar
Kim, Subin committed
3
4
import ErrorPage from "../pages/ErrorPage";

Kim, Subin's avatar
Kim, Subin committed
5
const PrivateRoute = ({ component: Component, ...rest }) => {
6
    const { user } = useAuth();
Kim, Subin's avatar
Kim, Subin committed
7
    return (
Kim, Subin's avatar
context    
Kim, Subin committed
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
        <Route
            {...rest}
            render={(props) => {
                if (user) {
                    if (rest.role) {
                        if (rest.role === user.role) {
                            return <Component {...props} />;
                        } else {
                            return <ErrorPage />
                        }
                    } else {
                        return <Component {...props} />
                    }
                } else {
                    return <Redirect to="/login" />;
                }
            }}
        />
    );
Kim, Subin's avatar
Kim, Subin committed
27
28
29
};

export default PrivateRoute;