反应登录和注销实施

时间:2018-12-20 23:11:30

标签: node.js reactjs express passport.js mern

当用户通过身份验证成功时,我将后端本地护照用于用户身份验证,会话已存储在数据库中。在前端中,我正在使用react,我可以在前端成功登录,并且当我检查浏览器会话时,会话已保存,但是如果会话仍保存在浏览器中的同时仍然可以导航回登录页面,问题是< / p>

2 个答案:

答案 0 :(得分:0)

不确定我是否理解。您可以检查会话是否存在,如果存在,则不显示登录页面,而是重定向到主页。

答案 1 :(得分:0)

这是我处理护照本地设置重定向或呈现语句的方式:

class App extends Component {
  constructor() {
    super();
    this.state = {
      loggedInUser: null
    };
  }

  componentWillMount() {
    this.fetchLoggedInUser();
  }

  fetchLoggedInUser = () => {
    fetchUser().then(res => {
      if (res.message) {
        this.setState({
          loggedInUser: false
        });
      } else {
        this.setState({
          loggedInUser: true,
          user: res
        });
      }
    });
  };

  isLoggedIn = () => {
    return this.state.loggedInUser;
  };

  isAdmin = () => { // You won't have this, but it's part of my route/middleware
    console.log(this.state.user.accessLevel);
    return this.state.user.accessLevel === "Admin";
  };

  initializeLoad = () => {
    if (this.state.loggedInUser === null) {
      return <h1>Loading...</h1>;
    } else {
      return (
        <React.Fragment>
          // Removed a bunch of routes to shorten things up.
          <Route
            exact
            path="/login"
            render={() =>
              // Determine if logged in // if not redirect
              // Some routes I pass in through props => <SomeView {...props} ... /> so I have access to the user.
              this.isLoggedIn() ? ( 
                <Redirect to="/profile" />
              ) : (
                <LoginView onAuthUpdate={this.handleAuthUpdate} />
              )
            }
          />
        </React.Fragment>
      );
    }
  };

  render() {
    return this.initializeLoad();
  }
}

export default App;
相关问题