Firebase的云功能:使用电子邮件和密码登录用户(服务器端)

时间:2017-11-15 11:22:15

标签: node.js firebase firebase-authentication google-cloud-functions firebase-admin

我想让用户通过REST登录。我的应用程序向我发送了一个电子邮件地址和密码,我希望Firebase检查这是否是有效的凭据组合。然后将JWT发送回客户端以验证所有请求。

但是,Firebase Admin SDK似乎没有像admin.auth.loginWithEmailAndPassword()之类的功能。如何在完全服务器端登录用户?

服务器正在Fire Functions for Firebase上运行。

2 个答案:

答案 0 :(得分:1)

通常的做法是让客户端验证电子邮件/密码,然后将生成的令牌发送到您的服务器。这样server can validate the token,而不必验证凭据。

答案 1 :(得分:0)

我的做法有点不同。我有一个云函数,它创建调用 createUser() 的用户帐户,它接收我想在身份验证和 Firestore 中添加到帐户的所有信息。当帐户存在或存在数据库问题时,我会抛出 HttpsError。当我回到前端时,我会调用 signInWithEmailAndPassword 来在前端登录用户。这使我可以轻松地使用我想要的数据填充帐户,同时使该方法在函数中更加安全。我完全理解有很多方法可以完成,只是分享我所做的。另请注意,此代码未清除,也未正确捕获所有错误。我相信它可以大大改进。

Firebase 函数:

const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
const db = admin.firestore();
// http callable function createUser
exports.createUser = functions.https.onCall(async (data, context) => {
  const firstName = data.firstName;
  const lastName = data.lastName;
  const email = data.email;
  const password = data.password;
  await admin.auth().createUser({
    email: email,
    password: password,
    displayName: firstName + " " + lastName,
    disabled: false,
    customClaims: {roleId: 1},
  }).then(function(userRecord) {
      db.collection("users").doc(userRecord.uid).set({
      firstname: firstName,
      lastname: lastName,
    }).catch((err) => {
      console.log("Failure to save user in DB.  Error was " + err.message);
      throw new functions.https.HttpsError('already-exists','Unable to create account.  Contact support.');
    });
  }).catch(function(error) {
    console.log("Error creating new user in Authentication.  Error was ", error.message);
    throw new functions.https.HttpsError('already-exists','Email account already exists');
  });
  return "success";
});

我的前端 JavaScript

        const registerForm = document.querySelector('.register');    
        registerForm.addEventListener('submit', (e) => {
                e.preventDefault();
                const password = registerForm.password.value;
                const confirm = registerForm.confirm.value;
                if (password == confirm){
                    const firstName = registerForm.first_name.value;
                    const lastName = registerForm.last_name.value;
                    const email = registerForm.email.value;
                    const createUser = functions.httpsCallable('createUser');
                    const data = {
                        firstName: firstName,
                        lastName: lastName,
                        email: email,
                        password: password
                    };
                    createUser(data).then(response => {
                        // Now lets try to log the user in
    firebase.auth().signInWithEmailAndPassword(email,password).then(userRecord => {
                            console.log("successfully logged in " + email);
                        }).catch((err) => {
                            console.log("Failure to log in user.  Error was " + err.message);
                        });
                        // Do something here to manage UI
                    }).catch((e)=> {
                        console.log(e.message);
// Handle Errors in UI
                    });
                } else {
// Handle Errors in UI
                };
            });