Search code examples
javascriptreactjsroutesweb-component

How to make a route in React inaccessible to all users except when certain events happen


I have implemented a Private component in the app I'm building that will redirect the user to the login page if they do not have an account yet. It is a fairly common implementation that can be found in lots of tutorials. This is the Private route:

const Private = ({ component: Component, ...rest }) => {
    const authenticated = reduxStore.getState().auth.isAuthenticated;
    const token = reduxStore.getState().auth.token;
    return (
        <Route
            {...rest}
            render={props =>
                authenticated || token ? (
                    <Component {...props} />
                ) : (
                    <Redirect
                        to={{
                            pathname: "/login",
                            state: { from: props.location }
                        }}
                    />
                )
            }
        />
    );
};

This does a great job of keeping out users who don't have accounts but how would I implement myroute so it cannot be accessed by simply visiting https://example.com/api/myroute once you have user credentials? The use case is that when the user wants to change their password, they click a link that emails them a code. When they enter that code they are directed to a new page (component) that has the change password form.

I would like this form to completely inaccessible, unless the code is entered and they are automatically redirected, so that people cannot just bypass the code verification step. Like I say the Private route is a common part of tutorials but I'm struggling to find anything about totally secure routes.


Solution

  • Usually email link with reset password include the token, which is created during a password change request on server. The token is transmitted in link through query parameter.

    • If the password change page does not have a token in query (from email link), then link is not valid and user accidentally hit the page. You redirect user to login / home page.
    • If there is a token, then we allow the user to use the form and then send a new password and token to the server.