React Routing, How to Prevent User from Accessing other User's Profiles?

754 views Asked by At

I'm running into a little issue here and very new to React and Redux. I don't want users on my app to have access to others users profiles.

Currently I can type user Ids into the URL and switch from user profile to user profile when I am logged in.

I want to grant a user access to only his/her page. I setup some react routing to prevent users from having access to login and signup pages once logged in and also from going to profile pages when logged out.

Is there a way with react routing to limit a user to only be able to visit the page associated with their user ID?

App.jsx

import React from 'react';
import { Route } from 'react-router-dom';
import GreetingContainer from './session/greeting_container';
import SessionFormContainer from './session/session_form_container';
import { AuthRoute, ProtectedRoute } from '../util/route_util';
import RootRenderContainer from './session/root_render_container';
import LeaderboardContainer from './user/leaderboard_container';
import UserShowContainer from './user/user_show_container';
import ExerciseIndexContainer from './exercise/exercise_index_container';

const App = () => (
  <div>
    <header>
      <GreetingContainer />
    </header>
    <ProtectedRoute exact path='/' component={RootRenderContainer}/>
    <AuthRoute path="/login" component={SessionFormContainer} />
    <AuthRoute path="/signup" component={SessionFormContainer} />
    <Route path='/workouts' component={LeaderboardContainer} />
    <Route path='/users/:userId' component={UserShowContainer} />
    <Route path='/exercises' component={ExerciseIndexContainer} />
  </div>
);

export default App;

Protected and auth routes utility.

import React from 'react';
import { connect } from 'react-redux';
import { withRouter, Route, Redirect } from 'react-router-dom';

const Auth = ({component: Component, path, loggedIn}) => (
  <Route path={path} render={(props) => (
    !loggedIn ? (
      <Component {...props} />
    ) : (
      <Redirect to="/" />
    )
  )}/>
);

 const mapStateToProps = state => {
   return {loggedIn: Boolean(state.session.currentUser),
     currentUser: state.session.currentUser
  };
};

export const AuthRoute = withRouter(connect(mapStateToProps, null)(Auth));

const Protected = ({component: Component, path, loggedIn, currentUser}) => (
  <Route exact path={path} render={(props) => (
    !loggedIn ? (
      <Component {...props} />
    ) : (
      <Redirect to={`/users/${currentUser.id}`} />
    )
  )}/>
);


export const ProtectedRoute = withRouter(connect(mapStateToProps, null)(Protected));
0

There are 0 answers