PumpkinBreath
PumpkinBreath

Reputation: 925

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.

Upvotes: 1

Views: 494

Answers (2)

Alexander
Alexander

Reputation: 1400

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.

Upvotes: 1

alex067
alex067

Reputation: 3301

Since react uses client side routing, you'd have your app component handle all the routing for you.

Therefore, if someone goes directly to a link that requires authorization, it has to go through your app component, which does all the client side routing. If you secure the route, by requiring authentication first (IE checking jwt tokens, or looking into cookie sessions), then your route will be secured, even if someone visits the url directly.

Upvotes: 1

Related Questions