" auth /中用户未找到"使用Firebase登录用户时

时间:2016-08-30 13:34:49

标签: javascript firebase firebase-authentication

我有一个连接到monaca CLI和OnsenUI的firebase应用程序。我正在尝试创建一个用户并在同一个操作中登录它们。 我可以成功创建用户但我无法登录。当我登录时,我收到以下错误

auth/user-not-found 

There is no user record corresponding to this identifier. The User may have been deleted

我确认新用户在db ...这是我的注册和登录代码

//signup function stuff
var login = function() {
  console.log('got to login stuff');
  var email = document.getElementById('username').value;
  var password = document.getElementById('password').value;

  //firebases authentication code
  firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error) {
    // Handle Errors here.
    var errorCode = error.code;
    var errorMessage = error.message;
    console.log('User did not sign up correctly');
    console.log(errorCode);
    console.console.log(errorMessage);
  });

  firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) {
     console.log(error.code);
     console.log(error.message);
  });

  fn.load('home.html');


};

2 个答案:

答案 0 :(得分:4)

你的流程中有一种所谓的竞争条件。

当您致电createUserWithEmailAndPassword() Firebase 启动创建用户帐户时。但这可能需要一些时间,因此浏览器中的代码会继续执行。

它会立即继续signInWithEmailAndPassword()。由于Firebase可能仍在创建用户帐户,因此此调用将失败。

这种情况下的解决方案通常是将调用链接在一起,例如使用then()

firebase.auth().createUserWithEmailAndPassword(email, password).then(function(user) {
  firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) {
     console.log(error.code);
     console.log(error.message);
  });
}).catch(function(error) {
  // Handle Errors here.
  var errorCode = error.code;
  var errorMessage = error.message;
  console.log('User did not sign up correctly');
  console.log(errorCode);
  console.console.log(errorMessage);
});

但AndréKool已经评论过:创建用户已经自动签名,所以在这种情况下你可以这样做:

firebase.auth().createUserWithEmailAndPassword(email, password).then(function(user) {
  // User is created and signed in, do whatever is needed
}).catch(function(error) {
  // Handle Errors here.
  var errorCode = error.code;
  var errorMessage = error.message;
  console.log('User did not sign up correctly');
  console.log(errorCode);
  console.console.log(errorMessage);
});

当他们到达您的网页时,您很快就会想要detect whether the user is already signed。为此你可以使用onAuthStateChanged。来自文档:

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // User is signed in.
  } else {
    // No user is signed in.
  }
});

答案 1 :(得分:0)

异步/等待也可以。

(async () => {

        try {
            const result = await auth().createUserWithEmailAndPassword(email, password).signInWithEmailAndPassword(email, password);
            console.log(result);

        } catch (error) {
            console.error(error);
        }

    })()