使用React Native / Redux和Firebase保持身份验证

时间:2016-12-25 05:35:45

标签: firebase react-native redux firebase-authentication

我有一个相当简单的React native / Redux应用程序,并且最近添加了Redux persist with AsyncStorage以帮助在重新加载时继续运行状态。

但是,我在让Firebase重新验证用户时遇到问题。我想知道是否有人有经验,因为我对Redux和Firebase都很新。为了更清楚,我希望用户登录一次,然后每次打开应用程序时都不再登录。

我的登录用户操作:

export const loginUser = ({ email, password }) => {
  return (dispatch) => {

    dispatch({ type: LOGIN_USER });

    firebase.auth().signInWithEmailAndPassword(email, password)
      .then(user => loginUserSuccess(dispatch, user))
      .catch(() => {
        firebase.auth().createUserWithEmailAndPassword(email, password)
          .then(user => loginUserSuccess(dispatch, user))
          .catch(() => loginUserFail(dispatch));
      });
  };
};

我的App.js:

    class App extends Component {

    constructor() {
      super();
      this.state = {
        rehydrated: false,
        store
      };
    }

  componentDidMount() {

    const persistor = persistStore(
      store,
      {
        storage: AsyncStorage,
        whitelist: ['auth']
      },
      () => { this.setState({ rehydrated: true }); }
    );

    AppState.addEventListener('change', () => this.handleAppLoaded(AppState.currentState));

    const firebase_config = {
    apiKey: Config.FIREBASE_API_KEY,
    authDomain: `${Config.FIREBASE_PROJECT_NAME}.firebaseapp.com`,
    databaseURL: `https://${Config.FIREBASE_PROJECT_NAME}.firebaseio.com`,
    storageBucket: `${Config.FIREBASE_PROJECT_NAME}.appspot.com`,
    messagingSenderId: Config.FIREBASE_MESSAGE_ID
    };

    firebase.initializeApp(firebase_config);
  }

  componentWillUnmount() {
    AppState.removeEventListener('change', () => this.handleAppLoaded(AppState.currentState));
  }

  handleAppLoaded(state) {
    if (state === 'active') {
      store.dispatch(renewToken(store.getState()));
    }
    return null;
  }

  render() {
    if (!this.state.rehydrated)
          return null;
    this.handleAppLoaded(AppState.currentState);

    return (
      <Provider store={store}>
        <RouterWithRedux />
      </Provider>
    );
  }
}

export default App;

有人能指出我正确的方向吗?我尝试过做一个reauthUser操作,但由于我找不到重新验证用户的方法而陷入困境,因为Auth对象没有保存密码(显然是出于安全原因)

1 个答案:

答案 0 :(得分:1)

您使用的是网络SDK吗?如果您是,那么首先您需要使用此代替https://github.com/invertase/react-native-firebase

这些库适用于具有本机支持的react-native项目。

如果您已经在使用它,可以在https://rnfirebase.io/docs/v3.2.x/auth/reference/auth

查看API

设置所有onUserChangedonAuthStateChanged等。然后你的应用程序应该没有问题重新验证的东西。