1

Hello I am trying to make a certain path "/main" only accessible to logged in users. I have a loginUser action that sends the login request then redirects to "/main". However if you just type in "/main" after localhost:3000 without loggin in you can still get to "/main". Any help appreciated.

Here is my action:

export function loginUser(username1, password1) {
const mainPage = (response, dispatch) => {
  if(true) {
    history.push('/main');
  }
  dispatch({
      type: POST_DATA_SUCCESS,
      response,
  });
 };
const promise = fetch('http://localhost:8080/users/login', {
 method: 'POST',
 headers: {
  'Accept': 'application/json',
  'Content-Type': 'application/json',
  'Authorization': 'Basic ' + btoa(username1 + ":" + password1),
 },
 body: JSON.stringify({
   username: username1,
   password: password1,
  })
 });
 return {
    onRequest: POST_DATA_TRIGGERED,
    onSuccess: mainPage,
    onFailure: POST_DATA_FAILURE,
    promise,
  };
  }

Here is my app.js:

import React from 'react';
import {Router, Route, Link} from 'react-router-dom';
import history from '../history'
import Journal from './journal';
import AddForm from './add-form';
import GetSearch from './old-search';
import SignUp from './signup';
import Front from './front';
import { loginUser } from '../actions';

export default function App(props) {
  return(
   <Router history={history}>
    <div>
      <h3><Link className="title-journey" to="/">A Journey of Life</Link>
      </h3>
       <main>
        <Route exact path="/" component={Journal} />
        <Route path="/sign-up" component={SignUp} />
        <Route path="/add" component={AddForm} />
        <Route path="/get" component={GetSearch} />
        <Route path="/main" component={Front} />
       </main>
    </div>
   </Router>
  );
 }

And here is my login.js component:

 import React from 'react';
 import {BrowserRouter as Router, Route, Link} from 'react-router-dom';
 import { loginUser } from '../actions';
 import { connect } from 'react-redux';

 export class Login extends React.Component {
  constructor(props) {
   super(props);
   this.state = {
   //username: '',
   //password: '',
   }
 }

login(e) {
  e.preventDefault();
 const userName = this.username.value;
 const passWord = this.password.value;
 console.log(userName);
 console.log(passWord);
  this.props.loginUser(userName, passWord);
 }

render() {
  return(
    <form>
     <h3>Login to start your Journey</h3>
     <input placeholder="username" ref={input => {this.username = input}}>
     </input>
     <input placeholder="password" type="password"ref={input => 
     {this.password = input}}></input>
     <button onClick={this.login.bind(this)}>Login</button>
    </form>
   )
  }
}

export default connect(null, { loginUser })(Login);

1 Answer 1

1

It looks like you are using react-router v4. They recommend using the render prop on the Route component to render a redirect when the user does not have proper authorization. It is a component that looks like this:

const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route {...rest} render={props => (
    fakeAuth.isAuthenticated ? (
      <Component {...props}/>
    ) : (
      <Redirect to={{
        pathname: '/login',
        state: { from: props.location }
      }}/>
    )
  )}/>

And then your app would look like

   <main>
    <Route exact path="/" component={Journal} />
    <Route path="/sign-up" component={SignUp} />
    <Route path="/add" component={AddForm} />
    <Route path="/get" component={GetSearch} />
    <PrivateRoute path="/main" component={Front} />
   </main>

How you check to see if the user is authenticated is up to you, i.e fakeAuth.isAuthenticated

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.