0
我在路由上使用onEnter = {requireAuth}設置了一個基本的react/react-router-v3身份驗證過程。React-router身份驗證在路由更改時重新啓動,增量爲1
一切正常,用戶得到認證,腳本檢查用戶是否有足夠的權利的路線,並重定向就好了。
如果我在我的應用程序中使用任何類型的路由來鏈接到一個不同的組件,然而requireAuth函數似乎每次路由時都會以1的增量重新啓動。
index.js
ReactDOM.render((
<Router history={browserHistory}>
<Route path="/" component={App}>
<IndexRoute
component={ AuthContainer }
socket={socket}
/>
<Route
path="/access-denied"
component={ AccessDeniedContainer }
onEnter={() => requireAuth({socket: socket, role: ['admin', 'editor', 'user']})}
socket={socket}
/>
<Route
path="/dashboard"
component={ DashboardContainer }
onEnter={() => requireAuth({socket: socket, role: ['admin', 'editor']})}
socket={socket}
/>
<Route
path="/digital-sign"
component={ DigitalSignContainer }
onEnter={() => requireAuth({socket: socket, role: ['admin', 'user']})}
socket={socket}
/>
</Route>
</Router>
), document.getElementById('root'));
authService.js
// Checks function if user is logged in
export function requireAuth(authData) {
console.log('doing auth');
isLoggedIn(authData);
}
// Gets JWT token from local storage
export function getToken() {
return localStorage.getItem('jwt');
}
// Checks if a user is logged in && is permitted to see protected routes
export function isLoggedIn(authData) {
const validatedToken = getToken();
const requiredRole = authData.role;
console.log('checking....');
var loggedInSocket = authData.socket;
// Send token to server for validation
loggedInSocket.emit('authToken', validatedToken);
loggedInSocket.on('noToken', function() {
browserHistory.replace('/');
});
// If fake token
loggedInSocket.on('falseToken', function() {
browserHistory.replace('/');
});
// if user validated
loggedInSocket.on('validated', function(userToken) {
if(requiredRole.indexOf(userToken.role) > -1) {
console.log('User is:' + userToken.role);
console.log('Must have:' + requiredRole);
return validatedToken;
}
else {
console.log('User is:' + userToken.role);
console.log('Must have:' + requiredRole);
browserHistory.replace('/access-denied');
}
});
}
內
loggedInSocket.on( '驗證',函數(userToken的的console.log ){}
當我刷新瀏覽器時,觸發就好了。如果我在使用路由的應用程序中導航,它會激發兩次。當我再次導航/路由時,它會發射三次。等我不知所措,不知道從哪裏開始調試。
任何建議將不勝感激。提前致謝。