Created
July 5, 2019 20:09
-
-
Save daniilgri/6a73ab85b5f47a72e85b6fe41480860d to your computer and use it in GitHub Desktop.
This file contains 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 React, { Component } from "react"; | |
import Cookies from "js-cookie"; | |
import { Route, Switch } from "react-router"; | |
import { Redirect } from "react-router-dom"; | |
import MessagesPage from "./components/MessagesPage"; | |
import LoginPageContainer from "./containers/loginPageContainer"; | |
import RegisterPageContainer from "./containers/registerPageContainer"; | |
function isLogged() { | |
const cookie = Cookies.get("connect.sid"); | |
if (!cookie) { | |
return 0; | |
} | |
return 1; | |
} | |
const PrivateRoute = ({ component: Component, ...rest }) => { | |
return ( | |
<Route | |
{...rest} | |
render={props => | |
isLogged() ? ( | |
<Component {...props} /> | |
) : ( | |
<Redirect | |
to={{ pathname: "/login", state: { from: props.location } }} | |
/> | |
) | |
} | |
/> | |
); | |
}; | |
const PublicRoute = ({ component: Component, restricted, ...rest }) => { | |
return ( | |
<Route | |
{...rest} | |
render={props => | |
isLogged() && restricted ? ( | |
<Redirect | |
to={{ pathname: "/messages", state: { from: props.location } }} | |
/> | |
) : ( | |
<Component {...props} /> | |
) | |
} | |
/> | |
); | |
}; | |
const routes = ( | |
<Switch> | |
<PublicRoute | |
restricted={true} | |
component={RegisterPageContainer} | |
path="/register" | |
exact | |
/> | |
<PublicRoute | |
restricted={true} | |
component={LoginPageContainer} | |
path="/login" | |
exact | |
/> | |
<PrivateRoute component={MessagesPage} path="/messages" exact /> | |
</Switch> | |
); | |
export default routes; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment