【问题标题】:Allow user to access only his/her dashboard只允许用户访问他/她的仪表板
【发布时间】:2017-07-09 03:56:46
【问题描述】:

我有四种不同的布局。

  • HomeLayout - 主页

  • 管理布局

  • 用户布局

  • 代理布局

AdminLayout 是管理相关页面的父级,而 UserLayout 是用户的父级 相关的等等。我已经使用高阶组件来检查是否 用户未经身份验证,将他们重定向到主页。还有一个条件。也就是说,如果用户通过了身份验证,但如果用户的角色不是管理员并且用户尝试访问 AdminDashboard,他/她应该被重定向到主页,并且与其他人类似。但是 Agent 可以访问 UserDashboard。

我得到的角色是形式

user_role = ['superadmin'] or ['enduser'] or ['agent'] or 
['enduser', 'agent'].

不应访问其他仪表板,除了代理也可以访问代理仪表板和用户仪表板。对于未经身份验证的用户,我可以在不登录的情况下访问仪表板时重定向到主页

重定向到未经身份验证的用户的代码正在工作,我已经完成了以下方式

const Redirection = prop => WrappedComponent => {
  return class Redirection extends React.PureComponent {
    render() {
      const user_instance = JSON.parse(localStorage.getItem("user"));
      if (!user_instance) {
        return <Redirect to="/" />;
      } else {
        return <WrappedComponent {...this.props} />;
      }
    }
  };
};

export default props => WrappedComponent =>
  connect(null, mapDispatchToProps)(Redirection(props)(WrappedComponent));

管理布局

class AdminLayout extends React.Component {
  render() {
    return (
      <div>
        {this.props.children}
      </div>
    );
  }
}

export default Redirection()(AdminLayout);

我从 localStorage 得到的 user_role 是 JSON.parse(localStorage.getItem("user"))['userInfo]['user_role']

【问题讨论】:

    标签: javascript reactjs redux higher-order-functions higher-order-components


    【解决方案1】:

    您可以使用 lodash intersection 执行此操作。这是它的链接

    https://lodash.com/docs/4.17.4#intersection

    在你的情况下,检查将如下

    if (
            user_instance &&
            intersection(prop, user_instance["userInfo"]["user_role"])
              .length > 0
          ) {
            return <WrappedComponent {...this.props} />;
          } else {
            return <Redirect to="/" />;
          }
    

    您可以粘贴以下 sn-p。此外,不要忘记检查 lodash 文档,因为它对您很有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-21
      • 1970-01-01
      • 1970-01-01
      • 2019-02-16
      • 2017-07-28
      • 1970-01-01
      • 2019-11-13
      • 1970-01-01
      相关资源
      最近更新 更多