2016-08-16 6 views
1

特定のパスにアクセスする前にユーザーが存在することを確認します。React Router:認証フローが機能しない

私は、ユーザーを取得する機能を持っており、認証を必要とするもの:私は私のコンソールログがある見ることができ、私はその後、必要機能を適用

フォーカス取得時
<Route path="/modules" component={ModulesData} onEnter={requireAuth} /> 

function getUser() { 
    $.ajax({ 
    url: '/getUser', 
    method: 'GET' 
    }).done(data => { 
    if(data.user == "no user"){ 
     console.log('permission denied'); 
     alert('you must be logged in to access this page.') 
     return null 
    } else { 
     console.log('permission granted'); 
     return true 
    } 
    }); 
} 

function requireAuth(nextState, replace) { 
    if (!getUser()) { 
    replace({ 
     pathname: '/login', 
     state: { nextPathname: nextState.location.pathname } 
    }); 
    } 
} 

正しいかどうかに基づいてユーザーがログインしているかどうかにかかわらず、ユーザーのステータスに関係なく、常にログインページに戻されます。

import React from 'react'; 
import { render } from 'react-dom'; 
import { Router, Route, browserHistory, IndexRoute, Redirect } from 'react-router'; 

import App from './App'; 

require('./stylesheets/main.scss'); 



function getUser() { 
    $.ajax({ 
    url: '/getUser', 
    method: 'GET' 
    }).done(data => { 
    if(data.user == "no user"){ 
     console.log('permission denied'); 
     alert('you must be logged in to access this page.') 
     return null 
    } else { 
     console.log('permission granted'); 
     return true 
    } 
    }); 
} 

function requireAuth(nextState, replace) { 
    if (!getUser()) { 
    replace({ 
     pathname: '/login', 
     state: { nextPathname: nextState.location.pathname } 
    }); 
    } 
} 

render((
    <Router history={browserHistory}> 

    <Route path="/" component={App}> 

     <Route path="/modules" component={ModulesData} onEnter={requireAuth} /> 

    </Route> 
    </Router> 
), document.getElementById('app')); 

答えて

0

はcomponentDidMountまたはcomponentWillReceivePropsの代わりに、フォーカス取得時における検証をやってみてください。

は、ここに私のindex.js追加明確にするためです。 また、ユーザーがいない場合はnullの代わりにfalseを返すようにしてください。

+0

私はReact Router - Auth Flowの例(https://github.com/reactjs/react-router/blob/master/examples/auth-flow/app.js)のようにしていました。 I.E .: 多くのルートを保護する必要があるため、実際のコンポーネント内で実行する必要がありますが、理想的ではありません。ルートのパス= "ダッシュボード"コンポーネント= {ダッシュボード} onEnter = {必須} /> – fresh5447

関連する問題