限制访问(流星+反应路由器+角色)

NOa*_*MTL 7 meteor reactjs react-router meteor-react

我正试图在我的Meteor应用程序中使用react-router实现alanning Meteor-roles.一切都工作得很好,除了我无法正确管理使用alanning角色限制路线或事实Meteor.user()

我尝试过流星角色:

我正在尝试使用onEnter={requireVerified}我的路线.这是代码:

const requireVerified = (nextState, replace) => {
    if (!Roles.userIsInRole(Meteor.userId(), ['verified'],'user_default')) {
        replace({
            pathname: '/account/verify',
            state: { nextPathname: nextState.location.pathname },
        });
    }
};
Run Code Online (Sandbox Code Playgroud)

我试过Meteor.user():

const requireVerified = (nextState, replace) => {
  if (!Meteor.user().isverified == true) {
    replace({
      pathname: '/account/verify',
      state: { nextPathname: nextState.location.pathname },
    });
  }
};
Run Code Online (Sandbox Code Playgroud)

所以当我点击路线链接时这是有效的,但是当我手动刷新(F5)时,它不起作用.在深入研究之后,我发现Meteor.user()在手动刷新页面时还没有准备好.

我知道Meteor.userid()或Meteor.logginIn()正在运行,但我想验证的不仅是它们已被记录,而且它们是"已经过验证"还是有角色.

我还尝试用反应来检查组件内部,componentDidMount()或者componentWillMount(),在两种情况下它都是相同的,手动新鲜不会Meteor.user()在安装功能之前加载.

那么使用meteor/alaning角色+反应路由器来限制组件/路由的最佳方法是什么?(我在TheMeteorChef的基地内使用react-komposer)

谢谢.

小智 1

注意我还没有尝试过,这只是一个建议

您可以尝试的一件事是与“react-meteor-data”中的 createContainer 一起使用,componentWillReceiveProps如下所示:

import React, { Component, PropTypes } from 'react';
import { Meteor } from 'meteor/meteor';
import { createContainer } from 'meteor/react-meteor-data';
import { Roles } from 'meteor/alanning:roles';

class MyComponent extends Component {
  componentWillReceiveProps(nextProps) {
    const { user } = nextProps;
    if (user && !Roles.userIsInRole(user._id, ['verified'], 'user_default')) {
      browserHistory.push('/account/verify');
    }
    // If Meteor.user() is not ready, this will be skipped.
  }
}

MyComponent.propTypes = {
  user: PropTypes.object,
};

export default createContainer(() => {
  const user = Meteor.user() || null;
  return { user };
}, MyComponent);
Run Code Online (Sandbox Code Playgroud)

为了解释流程,当加载页面时,正如您所说,Meteor.user() 未定义,因此您无法检查权限。然而,当 Meteor.user() 被定义时,这将触发模板的刷新,并且新的 props 将被传递到componentWillReceiveProps. 此时您可以检查是否user已定义并根据需要进行重定向。

为了真正确保不会错过任何内容,我实际上也会将验证放在 中constructor()(定义一个将 props 作为参数的函数,并在 和 中调用它constructor()componentWillReceiveProps()