firebase auth在刷新时延迟

时间:2016-05-22 04:36:16

标签: reactjs firebase react-router firebase-authentication

我的SPA React / Firebase应用程序上的硬刷新在立即执行功能时不会保持身份验证状态。我有一个解决方法,但它是粗略的。

我的反应路由使用onEnter函数来确定用户是否经过身份验证。例如

<Route path="/secure" component={Dashboard} onEnter={requireAuth}/>

此外,我的requireAuth函数如下所示:

function (nextState, replace) {
        console.log('requireAuth', firebase.auth().currentUser);
        if (!firebase.auth().currentUser) {
            console.log('attempting to access a secure route. please login first.');
            replace({
                pathname: '/login',
                state: { nextPathname: nextState.location.pathname }
            });
        }
};

然而,在硬刷新时,firebase.auth().currentUser会有轻微的延迟。它首先为空,然后执行POST到firebase服务器以确定身份验证状态。返回时,填充currentUser对象。但这种延迟会引发问题。

我的hacky解决方案如下:更新:这实际上并没有...

function (nextState, replace) {
    setTimeout(function () {
        console.log('requireAuth', firebase.auth().currentUser);
        if (!firebase.auth().currentUser) {
            console.log('attempting to access a secure route. please login first.');
            replace({
                pathname: '/login',
                state: { nextPathname: nextState.location.pathname }
            });
        }
    }, 50);
};

只需将其包裹在超时时间内。但是,我真的不喜欢这个......有什么想法吗?

更新

我还尝试将其包含在onAuthStateChanged侦听器中,该侦听器应该比具有明确时间延迟的setTimeout更准确。代码如下:

function (nextState, replace) {
    var unsubscribe = firebase.auth().onAuthStateChanged(function (user) {
        if (!user) {
            console.log('attempting to access a secure route');
            replace({
                pathname: '/login',
                state: { nextPathname: nextState.location.pathname }
            })
            console.log('should have called replace');
        }
        unsubscribe();
    });
    // setTimeout(function () {
    //     console.log('requireAuth', firebase.auth().currentUser);
    //     if (!firebase.auth().currentUser) {
    //         console.log('attempting to access a secure route. please login first.');
    //         replace({
    //             pathname: '/login',
    //             state: { nextPathname: nextState.location.pathname }
    //         });
    //     }
    // }, 50);
};

执行了两个日志语句,但似乎没有正确执行react-router replace。也许这对于路由器专家来说是一个不同的问题。

更新2:

我正在做这件事是在深夜。显然setTimeout实际上也不起作用。

4 个答案:

答案 0 :(得分:7)

好。所以,我能够通过利用firebase提供的localStorage变量来存储用户信息来解决这个问题。

function (nextState, replace) {
    if (!firebase.auth().currentUser) {
        let hasLocalStorageUser = false;
        for (let key in localStorage) {
            if (key.startsWith("firebase:authUser:")) {
                hasLocalStorageUser = true;
            }
        }
        if (!hasLocalStorageUser) {
            console.log('Attempting to access a secure route. Please authenticate first.');
            replace({
                pathname: '/login',
                state: { nextPathname: nextState.location.pathname }
            });
        }
    }
};

答案 1 :(得分:3)

虽然这是一篇与ReactJS相关的帖子,但我最近在为AngularJS编写自己的身份验证/授权服务时遇到了同样的问题。在页面刷新时,onAuthStateChanged会传递null的用户,因为firebase仍在初始化(异步)。

对我有用的唯一解决方案是在用户登录后将用户uid存储在localStorage中,并在用户注销后删除该值。

由于我单独使用authServiceuserService,我在authService注册了一个用户登录/注销后被触发的侦听器。

代码示例authService(不是完整的authService):

var loginListeners = [];
var logoutListeners = [];

function addLoginListener(func) {
    loginListeners.push(func);
}

function addLogoutListener(func) {
    logoutListeners.push(func);
}

function login(email, password) {
    return firebase.auth().signInWithEmailAndPassword(email, password).then(function(user) {
        for(var i = 0; i < loginListeners.length; i++) {
            loginListeners[i](user); // call registered listeners for login
        }
    });
}

function logout() {
    return firebase.auth().signOut().then(function() {
        for(var i = 0; i < logoutListeners.length; i++) {
            logoutListeners[i](); // call registered listeners for logout
        }
    });
}

代码示例userService(不是完整的userService):

.provider('userService', ['authServiceProvider',
function UserService(authServiceProvider) {

var usersRefUrl = '/users';
var userInfo = null;
var userDetails = null;

// refreshHack auto-executed when this provider creates the service
var storageId = 'firebase:uid'; // storing uid local because onAuthStateChanged gives null (when async initializing firebase)
(function addRefreshHackListeners() {
    authServiceProvider.addLoginListener(function(user) {
        userInfo = user;
        localStorage.setItem(storageId, user.uid); // store the users uid after login so on refresh we have uid to retreive userDetails
    });
    authServiceProvider.addLogoutListener(function() {
        userInfo = null;
        localStorage.removeItem(storageId);
    });
    firebase.auth().onAuthStateChanged(function(user) {
        if(user) { // when not using refreshHack user is null until async initializing is done (and no uid is available).
            localStorage.setItem(storageId, user.uid);
            userInfo = user;
            resolveUserDetails();
        } else {
            localStorage.removeItem(storageId);
            userInfo = null;
            userDetails = null;
        }
    });
})();

function isLoggedIn() {
    return userInfo ? userInfo.uid : localStorage.getItem(storageId); // check localStorage for refreshHack
}

function resolveUserDetails() {
    var p = null;
    var uid = isLoggedIn();
    if(uid)
        p = firebase.database().ref(usersRefUrl + '/' + uid).once('value').then(function(snapshot) {
            userDetails = snapshot.val();
            return userDetails;
        }).catch(function(error) {
            userDetails = null;
        });

    return p; // resolve by returning a promise or null
}
}]);

在运行块中,您可以全局注册用户并解决每次路由更改时的用户信息/详细信息(使其更安全):

.run(['$rootScope', 'userService', 'authService',
function($rootScope, userService, authService) {

// make user available to $root in every view
$rootScope.user = userService.getUser();

$rootScope.$on('$routeChangeStart',
        function(event, next, current) {

    // make sure we can add resolvers for the next route
    if(next.$$route) {
        if(next.$$route.resolve == null)
            next.$$route.resolve = {};

        // resolve the current userDetails for every view
        var user = userService.resolveUserDetails();
        next.$$route.resolve.userDetails = function() {
            return user;
        }
    }
});
}]);

也许这可以帮助那些正在努力解决同一问题的人。除此之外,您可以随意优化和讨论代码示例。

答案 2 :(得分:1)

通过管理localStorage进行工作。这是我如何做的例子。

  constructor(props) {
    super(props);

    let authUser = null;

    // setting auth from localstorage
    for (let key in localStorage) {
      if (key === storageId) {
        authUser = {};
        break;
      }
    }

    this.state = {authUser};
  }

  componentDidMount() {
    firebase
      .auth
      .onAuthStateChanged(authUser => {

        if (authUser) {
          localStorage.setItem(storageId, authUser.uid);
        } else {
          localStorage.removeItem(storageId);
        }

        // change state depending on listener
        authUser
          ? this.setState({authUser})
          : this.setState({authUser: null});
      });
  }

答案 3 :(得分:0)

这对我来说很有用,请尝试根据firebase.auth的状态将主应用程序包装在if else语句中。

 constructor() {
    super();
    this.state={
    user:{},
    stateChanged:false
    };
  } 
componentDidMount(){
fire.auth().onAuthStateChanged((user)=>{
      this.setState({stateChanged:true})
    });
}
render() { 
    if(this.state.stateChanged==false){
      return(
        <div>
          Loading
        </div>
      )
    }
else{
    
        return(<div>your code goes here...</div> )

}
}