gpt4 book ai didi

firebase - 如何将身份验证用户链接到 Firestore 中的集合?

转载 作者:行者123 更新时间:2023-12-02 19:38:34 24 4
gpt4 key购买 nike

我正在尝试将用户连接到 firestore 中的用户集合。我正在使用云函数,但我认为我没有正确实现它。

firebase.auth().createUserWithEmailAndPassword(email, password)
.then(() => {
console.log('user created')
exports.createUserDoc = functions.auth.user().onCreate((user) => {
console.log("hi")
const userId = user.uid;

const account = {
posts: []
}
return admin.firestore().collection("Users").doc(userId).add(account)
})

但是我的 console.log(hi) 没有显示。我的做法正确吗?任何建议都有帮助!

最佳答案

现在我所做的是当用户创建帐户时我会将登录信息记录到数据库中。
文档名称设置为 firebase 为用户提供的用户 UID。现在您可以简单地使用用户 UID 从数据库请求数据:是您的 .doc(user.uid)

这是完整的代码。

      var htmlEmail = document.getElementById('email').value;
var htmlPass = document.getElementById('password').value;
var htmlUser = document.getElementById('username').value.toLowerCase();
var auth = firebase.auth();


var promise = auth.createUserWithEmailAndPassword(htmlEmail, htmlPass);
// If there is any error stop the process.
promise.catch(function (error) {
var errorCode = error.code;
console.log(`GOT ERROR: ` + errorCode)
if (errorCode == 'auth/weak-password') return // password to weak. Minimal 6 characters
if (errorCode == 'auth/email-already-in-use') return // Return a email already in use error
});

// When no errors create the account
promise.then(function () {
var userUid = auth.currentUser.uid;
var db = firebase.firestore();

db.collection('users').doc(userUid).set({
email: htmlEmail,
emailVertified: false,
name: htmlUser,
online: false,
onlock: false,
password: htmlPass
});
});

然后,当用户登录时,您可以简单地通过 user.uid 请求数据。

    var auth = firebase.auth();
firebase.auth().onAuthStateChanged(function (user) {

// Lay connection with the database.
var firestore = firebase.firestore();
var db = firestore.collection('users').doc(user.uid);

// Get the user data from the database.
db.get().then(function (db) {
// Catch error if exists.
promise.catch(function (error) {
// Return error
});

promise.then(function () {
// continue when success
});
});
});

可能有更好的方法。 (自己还在学习)。但这对我来说很有效,而且效果很好。

有两件事需要记住!

  1. 与实时数据库相比,我更推荐 Firestore,因为它更快、更安全。
  2. 确保您的数据库规则设置正确,以便任何人都无法查看/泄露您的数据库信息。 (当您记录用户个人信息时)。如果设置不正确,用户将能够查看您的数据库,甚至清除所有数据。

希望有帮助:)

如果您自己找到更好的方法,请在这里告诉我们。我们也可以从中学习!

关于firebase - 如何将身份验证用户链接到 Firestore 中的集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54485656/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com