I have my React application working pretty well with authentication using a session cookie from Node Express. Then on refresh, I got logged out. So I added a function to my top level App.js to check if the user is logged in and valid. That worked great. Then I added a custom AuthRoute to my application. It checks the auth context to see if the user is authenticated or not. On refresh, it does not see the updated auth context and kicks the user back to the login.
Here is my AuthRoute.js:
import { Redirect, Route } from 'react-router-dom';
import { NonAuthRoutes } from '../config/AuthRoutesLogic';
import { useGlobalAuthContext } from '../context/authContext';
const AuthRoute = ({
Component,
path,
exact = false,
requiredRoles
}) => {
const isAuthed = !!useGlobalAuthContext().user.email;
console.log({ isAuthed });
console.log(useGlobalAuthContext().user);
const userRole = useGlobalAuthContext().user.type;
const userHasRequiredRole = requiredRoles.includes(userRole);
console.log(userRole, userHasRequiredRole);
const message = 'Please log in to view this page';
return (
<Route
exact={exact}
path={path}
render={(props) =>
isAuthed && userHasRequiredRole ? (
<Component {...props} />
) : (
<Redirect
to={{
// pathname: userHasRequiredRole
// ? NonAuthRoutes.login
// : NonAuthRoutes.unauthorized,
pathname: NonAuthRoutes.login,
state: {
message,
requestedPath: path
}
}}
/>
)
}
/>
);
};
export default AuthRoute;
And here is my function from my App.js that runs on refresh to verify the user:
const checkForLoggedInUser = () => {
axios.get(baseURL + '/users/user').then((res) => {
console.log({ res });
if (res.data.user) {
console.log('there is a logged in user!');
setAuthData((prevState) => {
return {
...prevState,
loading: false,
user: {
email: res.data.user.email,
type: res.data.user.type,
customer: res.data.user.customer
}
};
});
} else {
// we have no valid logged in user
console.log('no logged in user!');
setAuthData((prevState) => {
return {
...prevState,
loading: false,
user: {
email: '',
type: '',
customer: ''
}
};
});
}
});
};
To sum it up: The cookie persists. The user is still logged in. AuthRoute.js is just kicking them back to login page because isAuthed
is false.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…