taskcafe/frontend/src/App/Routes.tsx

91 lines
2.4 KiB
TypeScript
Raw Normal View History

import React, { useEffect, useState } from 'react';
import { Switch, Route, useHistory, useLocation, Redirect } from 'react-router-dom';
2020-04-10 04:40:22 +02:00
import * as H from 'history';
2020-04-10 18:31:29 +02:00
import Dashboard from 'Dashboard';
import Admin from 'Admin';
2020-12-31 03:56:59 +01:00
import MyTasks from 'MyTasks';
import Confirm from 'Confirm';
2020-04-10 04:40:22 +02:00
import Projects from 'Projects';
import Project from 'Projects/Project';
import Teams from 'Teams';
2020-04-10 04:40:22 +02:00
import Login from 'Auth';
import Register from 'Register';
2020-06-13 00:21:58 +02:00
import Profile from 'Profile';
import styled from 'styled-components';
import { useCurrentUser } from 'App/context';
2020-04-10 04:40:22 +02:00
2020-06-13 00:21:58 +02:00
const MainContent = styled.div`
padding: 0 0 0 0;
2020-06-13 00:21:58 +02:00
background: #262c49;
height: 100%;
2020-06-19 01:12:15 +02:00
display: flex;
flex-direction: column;
flex-grow: 1;
2020-06-13 00:21:58 +02:00
`;
type ValidateTokenResponse = {
valid: boolean;
userID: string;
2020-12-19 03:34:35 +01:00
};
const UserRequiredRoute: React.FC<any> = ({ children }) => {
const { user } = useCurrentUser();
const location = useLocation();
2021-05-03 00:31:24 +02:00
console.log('user required', user);
if (user) {
return children;
}
return (
<Redirect
to={{
pathname: '/login',
state: { redirect: location.pathname },
}}
/>
);
};
2021-05-03 00:31:24 +02:00
const Routes: React.FC = () => {
const [loading, setLoading] = useState(true);
const { setUser } = useCurrentUser();
useEffect(() => {
fetch('/auth/validate', {
method: 'POST',
credentials: 'include',
2021-05-03 00:31:24 +02:00
}).then(async (x) => {
const response: ValidateTokenResponse = await x.json();
const { valid, userID } = response;
2021-05-01 05:55:37 +02:00
if (valid) {
setUser(userID);
}
setLoading(false);
});
}, []);
2021-05-03 00:31:24 +02:00
console.log('loading', loading);
if (loading) return null;
return (
<Switch>
<Route exact path="/login" component={Login} />
<Route exact path="/register" component={Register} />
<Route exact path="/confirm" component={Confirm} />
<Switch>
<MainContent>
<Route path="/projects/:projectID" component={Project} />
<UserRequiredRoute>
<Route exact path="/" component={Dashboard} />
<Route exact path="/projects" component={Projects} />
<Route path="/teams/:teamID" component={Teams} />
<Route path="/profile" component={Profile} />
<Route path="/admin" component={Admin} />
<Route path="/tasks" component={MyTasks} />
</UserRequiredRoute>
</MainContent>
</Switch>
</Switch>
);
};
2020-04-10 04:40:22 +02:00
export default Routes;