2016-08-26 116 views
7

我想在我的Meteor應用程序中實現alanning流星角色與react-router。一切工作正常,除了事實上,我將無法正常管理使用我跟流星角色試圖alanning角色或Meteor.user()限制訪問(流星+反應路由器+角色)

限制路線:

我想我的路線上使用的onEnter={requireVerified}。這是代碼:

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

所以這是工作,當我點擊路線鏈接,但是當我手動刷新(F5:

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

我Meteor.user()嘗試), 這是行不通的。深入挖掘後,我發現Meteor.user()沒有準備好,當我手動刷新頁面。

我知道Meteor.userid()或Meteor.logginIn()的工作,但我想 不只是驗證他們登錄,但如果他們是「驗證」或 有一定作用。

我還試圖檢查與反應組分的內部,與componentDidMount()componentWillMount(),在這兩種情況下它是相同的,手動新鮮不加載Meteor.user()被安裝在compenent之前。

那麼什麼是最好的方式來限制組件/路線與流星/ alaning角色+反應路由器? (我在TheMeteorChef的基地裏面使用了反應堆)

謝謝。

+0

這個'驗證者'的要求是否與電子郵件驗證有關? – Ankit

+0

不,我正在驗證外部API調用帳戶(此應用程序正在與第三方提供商合作)。在這個例子中,我沒有精確地顯示用戶對象是如何構建的,但是一旦在外部Web站點上完成了驗證,我使用回調來更新流星中的用戶對象,在數據庫中添加isverified = true(與電子郵件驗證無關由流星提供) – NOaMTL

+0

@NOaMTL你找到了解決方案嗎?我遇到了同樣的問題... – cocacrave

回答

1

注我還沒有嘗試過,它只是一個建議

有一兩件事你可以嘗試是使用componentWillReceiveProps一起createContainer從「反應 - 流星數據」這樣的:

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); 

爲了解釋流程,在加載頁面時,如您所說Meteor.user()沒有定義,因此您無法檢查權限。但是,當Meteor.user()被定義時,這將觸發模板的刷新,新的道具將被傳遞給componentWillReceiveProps。此時你可以檢查是否已經定義了user,如果需要的話重定向。

爲了真正確保不會錯過任何東西,我真的把覈查的constructor()以及(定義一個函數,它的道具作爲參數,把它在這兩個constructor()componentWillReceiveProps())。