4

how can I prevent react routes to be called when a user is not logged in?

Want a single page with a login form be displayed whenn / is called.

every other route should be callable only if a user is logged in.

thanks

index.js

const render = () => {
    ReactDOM.render(
        <Provider store={store}>
            <AppContainer>
                <Router history={createHistory}>
                    <div>
                        <div className={t.topBar}>
                            <TopBarHelper/>
                        </div>

                        <div className={css.sidebararound}>
                    </div>
                   <Route exact path="/" component={Login}/>
                   <PrivateRoute  path="/dashboard" component={Dashboard}/>

....

const fakeAuth = {
    isAuthenticated: false,
    authenticate(cb) {
        this.isAuthenticated = true
        setTimeout(cb, 100) // fake async
    },
    signout(cb) {
        this.isAuthenticated = false
        setTimeout(cb, 100)
    }
}

const AuthButton = withRouter(({ history }) => (
    fakeAuth.isAuthenticated ? (
        <p>Welcome!</p>
    ) : (
        <p>You are not logged in.</p>
    )
))

The login is in a separate file and looks like this:

class Login extends Component {
    constructor(props) {
        super(props);
        this.changeHandler = this.changeHandler.bind(this);
        this.state = {
            activeSnackbar: false,
            snackbarText: '',
            redirectToReferrer: false
        };
    }

    componentDidMount() {
        this.getData()
    };

    /**
     * Fetches all Data needed for this view
     */
    getData() {
        console.log(this.props)
    };

    /**
     * Handle Change
     * @param field
     * @param value
     */
    changeHandler(value, {target: {name, type}}) {
        this.setState({
            [name]: type === 'number' ? parseInt(value, 10) : value,
        });
    }

    /**
     * Submit new Ticket Form
     * @param event
     */
    handleLogin = (event) => {

        this.context.router.push('/dashboard');
        // axios.post(API_URL + '/dashboard')
        //     .then((response) => {
        //     })
        //     .catch(function (error) {
        //         console.log(error);
        //     });
    };



    render() {
        return (
            <div>
                <div className={css.loginpanel}>
                    <div className={css.loginpanellogo}>
                        <img src={logo} width="200px"/>
                    </div>
                    <div className={css.loginpanelform}>

                        <h1><T value="user.login.welcome"/></h1>

                        <form id="login" method="POST" action="">
                            <Input type='email' label={<T value='user.login.email'/>} name='email' value={this.state.email} onChange={this.changeHandler}/>
                            <Input type='password' label={<T value='user.login.password'/>} name='password' value={this.state.password} onChange={this.changeHandler}/>
                            <br />
                            <Button icon='save' onClick={this.AuthButton} label={<T value="user.login.signin"/>} raised primary/>
                            <Button label={<T value="user.login.signup"/>} raised/>
                        </form>
                        <br/>
                    </div>
                </div>
            </div>
        );
    }
}

export default connect()(Login);

But I can't call the AuthButton function from Login

2 Answers 2

2

It could look like this with react-router-4

<PrivateRoute path="/protected" component={Protected}/>

and

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

The basic gist is that you intercept the transition, check for authentication and redirect accordingly.

See full example here.

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

2 Comments

private routing works that loogs good. but login from the example does not work. I add my full code above.
added above, I've got a index.js with routing and the login form in a separate file
2

you can use two options

  1. you can check whether user is logged in or not on
    <Route onChange={requireLogin}></Route>
  2. Or you can check on individual route like

<Route onEnter={requireLogin}/>

/>

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.