Получите данные о пользователях в Firebase Auth и добавьте их в базу данных Firebase. - PullRequest
1 голос
/ 27 января 2020

Здравствуйте!

Что я сделал: В настоящее время я работаю над сайтом, и я добавил страницы регистрации и входа с помощью Firebase Авт. Мне удалось создать пользователя с помощью метода электронной почты и пароля, и даже отправить письмо с подтверждением и добавить опцию сброса пароля.


Регистрация. html - (Я создал форму регистрации с полями ввода для имени пользователя, пароля и адреса электронной почты - игнорируйте функцию Changevisibility -).

  <!--form-->  
  <div class="container">
    <div align="center"><h3>Welcome to this amazing world!</h3> 
    <p>~ Fill in your email and Password in order to Sign Up. ~</p></div>

          <input id="txtName" type="text" placeholder="Username" required>
          <input id="txtEmail" type="text" placeholder="Email" required>
          <input id="txtPassword" type="password" placeholder="Password" required>

          <label class="ccontainer">I have read and accept the <a href="tos.html">Terms of Services and Pivacy Policy</a>.
            <input type="checkbox" onclick="changeVisibility()" required>
            <span class="checkmark"></span>
          </label>


    <div align="center"><button id="btnsignUp" class="sbutton"><i class="fas fa-door-open"></i> <b>Sign Up!</b></button></div>  

    <div align="center"><a href="login.html">Already an user? Login!</a></div>
   </div>     

Что я хотел бы сделать : Моя проблема в том, что я хотел бы добавить информацию о пользователе в базу данных Firebase. -Также я бы хотел, чтобы пользователь мог загрузить изображение профиля или просто ввести URL-адрес изображения. Как мне это сделать, используя imgURL в firebase auth? -

Я искал документацию и все, что я мог сделать, это:


Полная регистрация код - (прекрасно работает без «части базы данных»)

<!--Sign Up Event-->
<script>
  document.getElementById("btnsignUp").addEventListener("click", function(){

    var txtEmail = document.getElementById('txtEmail');
    var txtPassword = document.getElementById('txtPassword');
    var txtName = document.getElementById('txtName');

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


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

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

      //send verification
      sendVerificationEmail();

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

});

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

</script> 

Я также проверил сообщения здесь, но ни один из них, похоже, не работает с моим кодом или устарели, но я тоже могу что-то делать не так, поэтому прошу помощи. Я также хотел бы добавить дополнительную информацию к данным пользователя, например, биографию, которую пользователь может редактировать, и ссылки в социальных сетях. Поскольку я хочу отобразить ту же информацию на странице профиля, которую я создал.

Как бы я это сделал?

Большое спасибо за чтение этого, и хорошего вам дня.


Для проверки кода:

/*-- signup form --*/
* {
  box-sizing: border-box;
}

/* style the container */
.container {
  position: relative;
  border-radius: 5px;
  background-color: #f2f2f2;
  padding: 30px 80px 60px 80px;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);	
} 

/* style inputs and link buttons */
input,
.btn {
  width: 100%;
  padding: 12px;
  border: none;
  border-radius: 4px;
  margin: 5px 0;
  opacity: 0.85;
  display: inline-block;
  font-size: 17px;
  line-height: 20px;
  text-decoration: none; /* remove underline from anchors */
}

input:hover,
.btn:hover {
  opacity: 1;
}

/* style the submit button */
.sbutton {
  background-color: #ff3856;
  font-family: inherit;
  font-size: 16px;
  border: none;
  color: white;
  padding: 10px 60px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  margin: 4px 2px;
  cursor: pointer;
  border-radius: 16px;
  box-shadow: inset 0px 1px 0px #ff3856, 0px 5px 0px 0px #c91934;
}

.sbutton:hover {
  background-color: #ffe561;
  top: 3px;
  box-shadow: inset 0px -2px 0px 0px #e9901c, 0px 0px 0px #e9901c;
}
 <!-- The core Firebase JS SDK, inserted at the end of <head> --> 
 
 <!--Sign Up Form-->  
  <div class="container">
    <div align="center"><h3>Welcome to this amazing world!</h3> 
    <p>~ Fill in your Email and Password in order to Sign Up. ~</p></div>
  
          <input id="txtName" type="text" placeholder="Username" required>
          <input id="txtEmail" type="text" placeholder="Email" required>
          <input id="txtPassword" type="password" placeholder="Password" required>

          <label class="ccontainer">I have read and accept the <a href="tos.html">Terms of Services and Pivacy Policy</a>.
          </label>


    <div align="center"><button id="btnsignUp" class="sbutton"><i class="fas fa-door-open"></i> <b>Sign Up!</b></button></div>  

    <div align="center"><a href="login.html">Already an user? Login!</a></div>
   </div>	 


<!-- firebase config is inserted here-->

<!--Sign Up Event-->
<script>
  document.getElementById("btnsignUp").addEventListener("click", function(){

    var txtEmail = document.getElementById('txtEmail');
    var txtPassword = document.getElementById('txtPassword');
    var txtName = document.getElementById('txtName');

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


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

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

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

});

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

</script> 

1 Ответ

0 голосов
/ 27 января 2020

добро пожаловать в переполнение стека!

Пара вещей:

  1. На самом деле вы никогда не звоните writeUserData в своем фрагменте кода; Вы просто определяете это. Если вы не позвоните, ничего не будет написано.

  2. userId никогда не определяется, поэтому даже если вы позвоните writeUserData, путь к вашей базе данных будет undefined. Вам нужно получить userId от firebase.auth().currentUser.uid. Подробнее об этом смотрите в Firebase do c: https://firebase.google.com/docs/auth/unity/manage-users#get_a_users_profile.

- Правка -

Вот пример кода. Я не вставил абсолютно все, только соответствующие упущения:

//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)

Если идея обещаний и вызова функций не очень удобна, вы можете взглянуть на Javascript учебный ресурс, подобный javascript .info

Удачи!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...