Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Authentication completed but redirect not happening.. #6

Closed
ajeetvarma opened this issue Mar 20, 2017 · 4 comments
Closed

Authentication completed but redirect not happening.. #6

ajeetvarma opened this issue Mar 20, 2017 · 4 comments

Comments

@ajeetvarma
Copy link

ajeetvarma commented Mar 20, 2017

I have used this and authentication is happening very fine but after being authenticated page is not being redirected on required route .

I have strictly followed your documentation but i do't know what wrong i m doing .

Please suggest me if any more step has to be taken..

Thanks in advance ..

@bernabe9
Copy link
Owner

@ajeetvarma which function doesn't behave as you expect? checkAuth in the onEnter of react-router?
Which version of react-redux-session and react-router are you using?

Also, if you could show me the part of the code that fails will be very helpful

@ajeetvarma
Copy link
Author

ajeetvarma commented Mar 21, 2017

My package.json like this..

      dependencies": {
         "jquery": "^3.1.1",
         "react": "^15.4.2",
         "react-dom": "^15.4.2",
         "react-loader": "^2.4.0",
         "react-redux": "^5.0.2",
         "react-router": "^3.0.2",
         "react-router-redux": "^4.0.8",
         "redux": "^3.6.0",
         "redux-devtools-extension": "^2.13.0",
          "redux-react-session": "^1.1.0",
         "redux-thunk": "^2.2.0"
       }

My Routes configuration like this..

         import React, { Component } from 'react';\
         import { Router, browserHistory, Route, IndexRoute } from 'react-router';
         import { createStore, applyMiddleware } from 'redux';
         import thunk from 'redux-thunk';
         import reducer from './reducers';
         import { composeWithDevTools } from 'redux-devtools-extension';
         import { Provider } from 'react-redux';
         import { syncHistoryWithStore } from 'react-router-redux';
         import { sessionService } from 'redux-react-session';

         const store = createStore(
           reducer,
                 composeWithDevTools(
                 applyMiddleware(thunk)
              )
             )
        const history = syncHistoryWithStore(browserHistory, store);
        sessionService.initSessionService(store);
       
       class App extends Component {
              render() {
                    return (
                         <Provider store={store}>
                            <Router history={history}>
                                   <Route path="/" component={Index}>
                                        <IndexRoute to="/Index"/>
                                    </Route>
                                    <Route path="/product/:productId" component={SingleProduct} />
                                    <Route path="/profile" onEnter={sessionService.checkAuth} component={Profile} />
                                     <Route path="/login" component={Login} />
                                     <Route path="/logout" component={Logout} />
                                     <Route path="*" component={NotFoundPage} />
                            </Router>
                         </Provider>
                       );
                    }
                 }
             export default App;

api.js is like this..

                import axios from 'axios' ;

                const authentication = {
                            login (email, password) {
                                    const response = axios.post('http://localhost:8000/project/loginapi/' + email + '/password/' + password);
                            return new Promise(resolve => setTimeout(resolve(response), 1000));
                        },

                       logout () {
                            return new Promise(resolve => setTimeout(resolve, 1000));
                        },
                  }

SessionAction.js like this..

                    import { browserHistory, router } from 'react-router';
                    import { sessionService } from 'redux-react-session';
                    import authentication  from './Api.js';
                    
                   export const loginUser = (user) => {
                       return () => {
                             return authentication.login(user.email, user.password).then(response => {
                             sessionService.saveSession(response.token)
  .                          then(() => {
                                  sessionService.saveUser(response.data)
                                  .then(() => {
                                   browserHistory.replace('/profile');
                              });
                           });
                         });
                      };
                    }; 

                    export const logout = () => {
                        return () => {
                               return authentication.logout().then(() => {
                                     sessionService.deleteSession();
                                     sessionService.deleteUser();
                                      browserHistory.replace('/login');
                                 }).catch(err => {
                             throw (err);
                           });
                         };
                     };

Login.js is like this ..

                    import React, { Component, PropTypes } from 'react';
                    import { connect } from 'react-redux';
                    import { bindActionCreators } from 'redux';
                    import * as sessionActions from './SessionActions';
                    inport Input from './Input.js';

                    class Login extends Component {
                             constructor(props, context) {
                                           super(props, context);
                                           this.state = {
                                              user: {
                                                     email: '',
                                                    password: ''
                                                 }
                                             };

                                      this.onSubmit = this.onSubmit.bind(this);
                                      this.onChange = this.onChange.bind(this);
                                   }

                               onSubmit() {
                                  const { user } = this.state;
                                  const { loginUser } = this.props.actions;
                                  loginUser(user);
                               }

                                 onChange(e) {
                                            const { value, name } = e.target;
                                            const { user } = this.state;
                                            user[name] = value;
                                            this.setState({ user });
                                   }
                                 render() {
                                         const { user: { email, password } } = this.state;
                                              return (
                                                    <div>
                                                       <h3>LOGIN</h3>
                                                      <Input
                                                              name="email"
                                                              value={email}
                                                              label="Email"
                                                              type="email"
                                                             onChange={this.onChange}
                                                      />
                                                   <Input
                                                            name="password"
                                                            value={password}
                                                            label="Password"
                                                            type="password"
                                                            onChange={this.onChange}
                                                   />
                                                 <button onClick={this.onSubmit} type="submit">Submit</button>
                                          </div>
                                       );
                                    }
                               }
                                    const { object } = PropTypes;

                                    Login.propTypes = {
                                            actions: object.isRequired
                                      };

                                    const mapDispatch = (dispatch) => {
                                              return {
                                                  actions: bindActionCreators(sessionActions, dispatch)
                                                 };
                                        };

                                  export default connect(null, mapDispatch)(Login);

My Input.js is also just like your package file .. After authentication is completed when i check the inspect element redux options i found token and another results are coming in session storage and also authenticated and checked are displaing as true but it is seeming that the code

                            browserHistory.replace('/profile');

is not working. Also when i am refreshing the same page after authentication the session storage values are deleted automatically i. e. it become logout automatically ..

Thanks a lot for your response and hopes for help from you ..

@bernabe9
Copy link
Owner

bernabe9 commented Mar 21, 2017

@ajeetvarma did you try to put a brake point before the redirect line?

Just like this:

sessionService.saveSession(response.token)
.then(() => {
  sessionService.saveUser(response.data)
  .then(() => {
    debugger; // -------> add this line
    browserHistory.replace('/profile');
  });
});

Then try to login with the inspector open and check if the code stops there. If the code stops there it means that the problem surely is in the Profile component and is not in redux-react-session.

In the case that it doesn't stops there you can try to add a catch statement and print the error.
Just like this:

 sessionService.saveUser(response.data)
  .then(() => {
    browserHistory.replace('/profile');
  }).catch((err) => console.log(err));

If you use the user information saved with sessionService.saveUser in the Profile make sure that you are passing well the response.data in the following line: sessionService.saveUser(response.data).

Let me know if it works, I hope to be helpful

@ajeetvarma
Copy link
Author

ajeetvarma commented Mar 22, 2017

@bernabe9 , Thanks a lot for your suggestion .

I have resolve my problem after making few changes in my code. I used localStorage instead of sessionService. My code was like following line..

             return authentication.login(user.email, user.password).then(response => {
                   localStorage.setItem('userToken', response.data.token);
                   localStorage.setItem('userEmail', response.data.email);
                   localStorage.setItem('userAuthenticated', response.data.authenticated);
                   browserHistory.replace('/dashboard');
                });

And this code working very fine.

Even sessionStorage is also working in place of localStorage.

Again very much thanks a lot to you ..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants