I'm using reactjs there, when the user logout, the localstorage and session was cleared normally
But when user click the back button on the browser, the user can still accessed the dashboard even can manage it
How to prevent this?
Logout Action:
export const logoutUserAction = () => dispatch => {
//! Loading
dispatchLoading(dispatch, LOGOUT_USER_ACTION);
firebase
.auth()
.signOut()
.then(() => {
window.localStorage.removeItem('user');
dispatchSuccess(dispatch, LOGOUT_USER_ACTION, 'Success Logout!!!');
})
.catch(() => {
window.localStorage.removeItem('user');
dispatchError(dispatch, LOGOUT_USER_ACTION, 'Failed Logout!!!');
});
};
Check Login Action:
export const checkLoginAction = history => dispatch => {
//! Loading
dispatchLoading(dispatch, CHECK_LOGIN_ACTION);
const user = JSON.parse(window.localStorage.getItem('user'));
if (user) {
firebase
.database()
.ref(`users/${user.uid}`)
.once('value')
.then(snapshot => {
if (snapshot.val()) {
window.localStorage.setItem('user', JSON.stringify(snapshot.val()));
history.push('/dashboard');
dispatchSuccess(dispatch, CHECK_LOGIN_ACTION, snapshot.val());
};
};
Private Route Config:
function ConfigRoute({ component: Component, dispatch, checkLoginLoading, checkLoginResult, ...rest }) {
const history = useHistory();
useEffect(() => {
dispatch(checkLoginAction(history));
}, [dispatch, history]);
return (
<Route
{...rest}
render={(props) => {
if (checkLoginLoading) {
return <LoadingIndicator />
} else {
return <Component {...props} />
}
}}
/>
);
};
Router:
<Switch>
<ConfigRoute exact path="/dashboard" component={Dashboard} />
<ConfigRoute exact path="/product" component={ProductList} />
<Redirect to="/auth/login" />
</Switch>
The problem is that your routes don't check if the user is signed in or not. You only reroute when you login or logout. But if someone enters the route manually he could access it.
You would need to create custom routes that check in them self if the user is signed in or not and redirect to the signin page if the user is not signed in. Check out this example from one of my projects.
I would also recommend to create a provider for Auth state so the Custom routes can access it from there. Here is also an example for that. Just on login and logout change the auth state using the Provider.
The last thing I would recommend is to use onAuthStateChanged to actualy capture the auth state itself. That way you can just login and logout without doing anything after that manually. Just listen to the auth state changes using that listener and change the auth provider state with it.