Add currentUser and isAuthenticated to authcontext

This commit is contained in:
rui hildt 2020-08-22 18:33:42 +02:00
parent a52bc8f7ab
commit 3356c380d7
7 changed files with 72 additions and 15 deletions

View File

@ -15,10 +15,16 @@ import {
Schedule, Schedule,
} from './screens'; } from './screens';
const existingToken = localStorage.getItem('token'); const existingToken = JSON.parse(localStorage.getItem('token'));
// const existingUser = JSON.parse(localStorage.getItem('user')); const existingUser = JSON.parse(localStorage.getItem('user'));
export default function App() { export default function App() {
const [isAuthenticated, setIsAuthenticated] = useState(!!existingToken);
const [currentUser, setCurrentUser] = useState(existingUser || '');
const [possibleDates, setPossibleDates] = useState();
// const [currentMeeting, setCurrentMeeting] = useState();
const [authToken, setAuthToken] = useState(existingToken || ''); const [authToken, setAuthToken] = useState(existingToken || '');
const setToken = (data) => { const setToken = (data) => {
@ -26,8 +32,30 @@ export default function App() {
setAuthToken(data); setAuthToken(data);
}; };
const setUser = (data) => {
localStorage.setItem('user', JSON.stringify(data));
setCurrentUser(data);
};
const setAuthentication = (boolean) => {
if (!boolean) {
localStorage.removeItem('token');
localStorage.removeItem('user');
}
setIsAuthenticated(boolean);
};
return ( return (
<AuthContext.Provider value={{ authToken, setAuthToken: setToken }}> <AuthContext.Provider
value={{
authToken,
setAuthToken: setToken,
isAuthenticated,
setIsAuthenticated: setAuthentication,
currentUser,
setCurrentUser: setUser,
}}
>
<Router> <Router>
<Switch> <Switch>
<Route path='/' exact component={Home} /> <Route path='/' exact component={Home} />
@ -35,7 +63,12 @@ export default function App() {
<Route path='/register' component={Register} /> <Route path='/register' component={Register} />
<PrivateRoute path='/dashboard' component={Dashboard} /> <PrivateRoute path='/dashboard' component={Dashboard} />
<PrivateRoute path='/schedule' component={Schedule} /> <PrivateRoute
path='/schedule'
component={Schedule}
possibleDates={possibleDates}
setPossibleDates={setPossibleDates}
/>
<PrivateRoute path='/invite' component={Invite} /> <PrivateRoute path='/invite' component={Invite} />
<PrivateRoute <PrivateRoute
path='/availability' path='/availability'

View File

@ -2,7 +2,11 @@ import React from 'react';
import { useHistory } from 'react-router-dom'; import { useHistory } from 'react-router-dom';
import { Nav, Icon, Dropdown, Popover, Whisper } from 'rsuite'; import { Nav, Icon, Dropdown, Popover, Whisper } from 'rsuite';
import { useAuth } from '../../helpers/authContext';
export default function MenuDropdown() { export default function MenuDropdown() {
const { setIsAuthenticated } = useAuth();
const history = useHistory(); const history = useHistory();
const triggerRef = React.createRef(); const triggerRef = React.createRef();
@ -12,8 +16,7 @@ export default function MenuDropdown() {
} }
function handleLogout() { function handleLogout() {
localStorage.removeItem('token'); setIsAuthenticated(false);
localStorage.removeItem('user');
history.push('/'); history.push('/');
} }

View File

@ -4,13 +4,17 @@ import { Redirect, Route } from 'react-router-dom';
import { useAuth } from '../helpers/authContext'; import { useAuth } from '../helpers/authContext';
const PrivateRoute = ({ component: Component, ...rest }) => { const PrivateRoute = ({ component: Component, ...rest }) => {
const { authToken } = useAuth(); const { isAuthenticated } = useAuth();
return ( return (
<Route <Route
{...rest} {...rest}
render={(props) => render={(props) =>
authToken ? <Component {...props} /> : <Redirect to='/login' /> isAuthenticated ? (
<Component {...props} />
) : (
<Redirect to='/login' />
)
} }
/> />
); );

View File

@ -5,14 +5,16 @@ import { useAuth } from '../helpers/authContext';
import { NavBar } from '../components'; import { NavBar } from '../components';
export default function Dashboard() { export default function Dashboard() {
const { authToken } = useAuth(); const { authToken, isAuthenticated, currentUser } = useAuth();
return ( return (
<> <>
<NavBar title='Meeting Planner' /> <NavBar title='Meeting Planner' />
<Panel header={<h3>Dashboard</h3>} bordered > <Panel header={<h3>Dashboard</h3>} bordered>
<p>This is just experimenting with stuff.</p> <p>This is just experimenting with stuff.</p>
<p>{authToken}</p> <p>{authToken}</p>
<p>Authenticated: {isAuthenticated.toString()}</p>
<p>Current user: {currentUser.username}</p>
</Panel> </Panel>
</> </>
); );

View File

@ -5,7 +5,7 @@ import { useAuth } from '../helpers/authContext';
import { NavBar } from '../components'; import { NavBar } from '../components';
export default function Home() { export default function Home() {
const { authToken } = useAuth(); const { authToken, isAuthenticated } = useAuth();
return ( return (
<> <>
@ -13,6 +13,7 @@ export default function Home() {
<Panel header={<h3>Home</h3>} bordered> <Panel header={<h3>Home</h3>} bordered>
<p>This will be the home page</p> <p>This will be the home page</p>
<p>{authToken}</p> <p>{authToken}</p>
<p>Authenticated: {isAuthenticated.toString()}</p>
</Panel> </Panel>
</> </>
); );

View File

@ -22,7 +22,12 @@ export default function Login() {
password: '', password: '',
}); });
const { setAuthToken, authToken } = useAuth(); const {
setAuthToken,
setIsAuthenticated,
setCurrentUser,
isAuthenticated,
} = useAuth();
const handleChange = (value, evt) => { const handleChange = (value, evt) => {
setCredentials({ setCredentials({
@ -36,6 +41,8 @@ export default function Login() {
.post('/auth/login', credentials) .post('/auth/login', credentials)
.then((response) => { .then((response) => {
setAuthToken(response.data.token); setAuthToken(response.data.token);
setCurrentUser(response.data.user);
setIsAuthenticated(true);
}) })
.catch((error) => { .catch((error) => {
if (error.response.status === 401) { if (error.response.status === 401) {
@ -45,7 +52,7 @@ export default function Login() {
}); });
}; };
if (authToken) { if (isAuthenticated) {
return <Redirect to='/dashboard' />; return <Redirect to='/dashboard' />;
} }

View File

@ -26,7 +26,12 @@ export default function Register() {
timezone: '', timezone: '',
}); });
const { setAuthToken, authToken } = useAuth(); const {
setAuthToken,
setIsAuthenticated,
setCurrentUser,
isAuthenticated,
} = useAuth();
const handleChange = (value, evt) => { const handleChange = (value, evt) => {
setNewUser({ setNewUser({
@ -54,13 +59,15 @@ export default function Register() {
.post('/auth/register', newUser) .post('/auth/register', newUser)
.then((response) => { .then((response) => {
setAuthToken(response.data.token); setAuthToken(response.data.token);
setCurrentUser(response.data.user);
setIsAuthenticated(true);
}) })
.catch((error) => { .catch((error) => {
setError('Failed to add new account.'); setError('Failed to add new account.');
}); });
}; };
if (authToken) { if (isAuthenticated) {
return <Redirect to='/dashboard' />; return <Redirect to='/dashboard' />;
} }