检查Firebase用户是否存在而不会出现错误

时间:2018-05-03 12:21:05

标签: node.js promise firebase-authentication firebase-admin

我有一个提供简单消息服务的网站。个人可以支付服务费用,或者企业可以支付每月订阅费用,然后免费添加他们的客户/用户。当企业添加客户端/用户电子邮件时,会触发下面的功能。我正在使用firebase函数和createUser在我的服务器上创建用户(更少)。但是,有时企业会尝试注册用户并且该用户已经存在。在这种情况下,我想向用户发送提醒电子邮件。

我的代码工作正常,但在我的catch /错误中有一个链条感觉很时髦。是否有其他方法可以检测电子邮件是否已在Firebase帐户中注册,但不会引发错误?

exports.newUserRegisteredByBusiness = functions.database.ref('users/{uid}/users/invited/{shortEmail}').onWrite( (data, context) => {

//don't run function if data is null
if (!data.after.val()){
  console.log('SKIP: newUserRegisteredByBusiness null so skipping')
  return null
} else {

  let businessUID = context.params.uid
  let email = data.after.val()
  let shortEmail = context.params.shortEmail
  let password // =  something I randomly generate

  return admin.auth().createUser({ email: email, password: password}).then( (user)=> {

      //write new user data
      let updates = {}
      let userData // = stuff I need for service to run
      updates['users/' + user.uid ] = userData;
      return admin.database().ref().update(updates)
    }).then( () =>{

      //email new user about their new account
      return emailFunctions.newUserRegisteredByBusiness(email, password)

    }).catch( (error) =>{
      //if user already exist we will get error here.
      if (error.code === 'auth/email-already-exists'){
         //email and remind user about account
        return emailFunctions.remindUsersAccountWasCreated(email).then( ()=> {
          //Once email sends, delete the rtbd invite value that triggered this whole function
          //THIS IS WHERE MY CODE FEELS FUNKY! Is it ok to have this chain?
          return admin.database().ref('users/' + businessUID + '/users/invited/' + shortEmail).set(null)
        })
      } else {

        //delete the rtbd value that triggered this whole function
        return admin.database().ref('users/' + businessUID + '/users/invited/' + shortEmail).set(null)

      }


    });

  }
})

2 个答案:

答案 0 :(得分:10)

要查找是否已为给定的电子邮件地址创建了用户帐户,请致电admin.auth().getUserByEmail

admin.auth().getUserByEmail(email).then(user => { 
  // User already exists
}).catch(err => { 
  if (err.code === 'auth/user-not-found') {
    // User doesn't exist yet, create it...
  }
})

当你还在使用catch()时,感觉操作失败的程度要小得多。

答案 1 :(得分:0)

为避免在catch块中进一步实现,您可以将此Firebase函数包装到以下代码中:

async function checkUserInFirebase(email) {
    return new Promise((resolve) => {
        admin.auth().getUserByEmail(email)
            .then((user) => {
                resolve({ isError: false, doesExist: true, user });
            })
            .catch((err) => {
                resolve({ isError: true, err });
            });
    });
}

...

const rFirebase = await checkUserInFirebase('abc@gmail.com');