简体   繁体   English

|已解决| 从 Firebase 获取用户身份验证数据并将其添加到 Firebase DB

[英]|SOLVED| Get User Auth data from Firebase & add it to Firebase DB

Hello!你好!

EDIT~ I've eventually managed to do this and wanted to share it just in case anyone else needs it.编辑~我最终设法做到了这一点,并想分享它,以防其他人需要它。 Most tutorials I've found were outdated and none of them seemed to work for me.我发现的大多数教程都已经过时了,而且它们似乎都不适合我。 But I've finally got everything to work so Here it is!但我终于让一切正常工作,所以它来了!


Sign Up - (I've created a sign up form with input fields for the username, extra info, password and email)注册 - (我创建了一个注册表单,其中包含用户名、额外信息、密码和电子邮件的输入字段)

Make sure you import all firebase scripts you want to use and ABOVE all of them, the firebase app main script.确保导入所有要使用的 firebase 脚本,并且在所有这些脚本之上,即 firebase 应用程序主脚本。 In my case I only needed Auth & Database - And BELOW all of this you put your Firebase App config and import either an external .js file where you'll be using firebase functions or write it all down there.在我的情况下,我只需要身份验证和数据库 - 在所有这些之下,您将您的 Firebase 应用配置放入一个外部 .js 文件中,您将在其中使用 firebase 函数,或者将其全部写在那里。 This was a very silly mistake I did myself and I kept getting errors on the console.这是我自己犯的一个非常愚蠢的错误,我一直在控制台上出错。 This is because I've been trying to call my external .js file BEFORE importing the firebase main scripts, which makes no sense right?这是因为我一直在尝试在导入 firebase 主脚本之前调用我的外部 .js 文件,这没有意义,对吗?

So here's my .js file for the sign up function:所以这是我用于注册功能的.js文件:

//On a different .js file where I make use of most of my functions I've added this part 
//(just because I've defined more const for all my functions and I wanted to have them all 
//in one place):

//getting all elements -- I've only put in this example the ones that I've used for Sign Up
const signupBtn = document.getElementById("btnsignUp");

const txtEmail = document.getElementById('txtEmail');
const txtPassword = document.getElementById('txtPassword');
const userId = document.getElementById('txtName');
const discord = document.getElementById('txtDiscord');
const bday = document.getElementById('txtBday');
const gender = document.getElementById('txtGender');
const imgURL = document.getElementById('txtimgURL');

//getting references to the apps
const auth = firebase.auth();
const database = firebase.database();
const rootRef = database.ref('users');


//------------------------------------------------//


//firebase SIGN UP.js
signupBtn.addEventListener("click", function(){

    var email = txtEmail.value;
    var pass = txtPassword.value;

    //Signing up
    auth.createUserWithEmailAndPassword(email, pass)
    .then(() => {

      //send verification email
      sendVerificationEmail();
    }) 
    .catch(function(error) {
    // Handle Errors here.
    //var errorCode = error.code;
    var errorMessage = error.message;
    alert("Error :" + errorMessage);
    });

  });
  //verification email function
  var sendVerificationEmail = () => {
    auth.currentUser.sendEmailVerification()
    .then(() => {
      alert("Verification Email Sent! Check your mailbox.")
    })
    .catch(error => {
      alert("Error :" + errorMessage);
    })
  }      

  //DATABASE
  //'set' adds new data to he db
  signupBtn.addEventListener('click', (e) => {
    e.preventDefault();
    rootRef.child(userId.value).set({
        Email: txtEmail.value,
        Discord: discord.value,
        Gender: gender.value,
        Birthday: bday.value,
        ImgURL: imgURL.value,
        CC: 0,//Here I've added some more info that's be stored too along with 
        RS: 0,//the data that the user has provided
        Rupreets: 0,
        Bag: 1,//1: small, 2: medium, 3: big
    })    
  }); 
//And that's all!

In my case, what I did with the database part is something like this:就我而言,我对数据库部分所做的事情是这样的:

-App name-
|
+--Users:
 |
 +--username1
  |
  +-info1
  |
  +-info2
  |
  +-info2
 |
 +--username2
  |
  +-info1
  |
  +-info2
  |
  +-info2

Well, I hope this will help somebody else too nn嗯,我希望这也能帮助其他人nn

welcome to Stack Overflow!欢迎使用堆栈溢出!

A couple of things:几件事:

  1. You never actually call writeUserData in your code snippet;您实际上writeUserData在代码片段中调用writeUserData you just define it.你只是定义它。 If you don't call it, nothing will be written.如果您不调用它,则不会写入任何内容。

  2. userId is never defined, so even if you called writeUserData , your database path would be be undefined . userId从未定义,因此即使您调用writeUserData ,您的数据库路径也将是undefined You'd need to get the userId from firebase.auth().currentUser.uid .您需要从firebase.auth().currentUser.uid获取 userId 。 For more on that, see this Firebase doc: https://firebase.google.com/docs/auth/unity/manage-users#get_a_users_profile .有关更多信息,请参阅此 Firebase 文档: https ://firebase.google.com/docs/auth/unity/manage-users#get_a_users_profile 。

-- Edit -- - 编辑 -

Here's a code sample.这是一个代码示例。 I haven't put in absolutely everything, just the relevant omissions:我没有把所有的东西都放进去,只是相关的遗漏:

//Signing up
    firebase.auth().createUserWithEmailAndPassword(email, pass)
    .then((data) => {

// createUserWithEmailAndPassWord returns a promise, which, when resolved will contain various user-related properties, so 
let id = data.User.uid;

      function writeUserData(userId, name, email, imageURL) {
        firebase.database().ref('Users/' + userId).set({
          Username: name,
          Email: email,
          Profile_pic: imageURL,
        });
      }

// call your function, referencing the id above
writeUserData(id, name, email, imageURL)

If the idea of promises and calling functions isn't comfortable, you might look at a Javascript learning resource like javascript.info如果承诺和调用函数的想法不舒服,您可以查看 Javascript 学习资源,如javascript.info

Good luck!祝你好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM