Implemented private routes

This commit is contained in:
Djeeberjr 2021-09-18 23:36:37 +02:00
parent 4112fd795a
commit 94ab5c3d8f

View File

@ -4,38 +4,48 @@ import { BrowserRouter as Router, Switch, Route, Redirect } from "react-router-d
import NotFound from "./components/NotFound"
import Login from "./components/Login"
import { useIsAuthQuery } from "./generated/graphql"
import { useEffect } from "react"
const App: React.FC = () => {
const {data: isAuth, loading } = useIsAuthQuery()
const [loginSuccessful,setLoginSuccessful] = useState(false)
const { data } = useIsAuthQuery()
const [isAuth,setIsAuth] = useState(false)
const [ready,setReady] = useState(false)
const loginRoutes = ()=>{
if (loginSuccessful || isAuth?.authorized){
// Routes available when logged in
return <>
<Route path="/f/" component={FileBrowser}/>
<Redirect from="/" exact to="/f/" />
</>
}else{
// Routes available when NOT logged in
return <>
<Route path="/login" exact >
<Login onLogin={()=>{
setLoginSuccessful(true)
}} />
</Route>
<Redirect from="*" to="/login" />
</>
useEffect(()=>{
if (data){
setIsAuth(data.authorized)
setReady(true)
}
}
},[data])
return (
<div className="dark:text-gray-300">
{
!loading &&
ready&&
<Router>
<Switch>
{loginRoutes()}
{/* Private only routes */}
{
isAuth && [
<Route path="/f/" component={FileBrowser} key={null} />,
<Redirect from="/" exact to="/f/" key={null} />,
<Redirect from="/login" exact to="/f/" key={null} />,
]
}
{/* Public only routes */}
{
!isAuth && [
<Route path="/login" exact key={1} >
<Login onLogin={()=>{
setIsAuth(true)
}} />
</Route>,
<Redirect from="/f/" to="/login" key={2} />
]
}
{/* Public & private routes */}
<Route path="*" component={NotFound} />
</Switch>
</Router>