如何通过Firebase身份认证获取除用户名以外的用户信息?

问题描述 投票:0回答:1

我是日本的一名英语老师。我正在使用Firebase Hosting开发一个网络应用。

我的学生有Google账户,因为我们使用Gsuite for Education,所以我决定用Firebase Auth获取学生的数据。

function signIn(){
  var provider = new firebase.auth.GoogleAuthProvider();
  firebase.auth().signInWithPopup(provider);
}
function saveMessage() {
  // Add a new message entry to the Firebase database.
  firebase.firestore().collection('messages').add({
      name: firebase.auth().currentUser.displayName,
      text: messageInputElement.value,
      timestamp: firebase.firestore.FieldValue.serverTimestamp()
  })

saveMessage 函数,我用 firebase.auth().currentUser.displayName

是否可以得到更多的用户信息?例如,我想要User的学校名称、班级编号和学生编号,我阅读了Firebase Auth文档。https:/firebase.google.comdocsreferencejsfirebase.User#providerdata。这似乎是好的。但是我不明白如何使用它。

你能告诉我如何用Firebase Auth获取用户名以外的用户信息吗?


这是index.html

<!doctype html>
<html lang="ja">
   <head>
      <title>音読アプリ アドバンス</title>
   </head>

   <body>
      <input id="sign-in" type="submit" value="SignIn">
      <br>
      <textarea id="text"></textarea>
      <br>
      <input id="download" type="submit" value="download">
      <div id='player'></div>

      <!-- Import and configure the Firebase SDK -->
      <!-- These scripts are made available when the app is served or deployed on Firebase Hosting -->
      <script src="/__/firebase/7.14.3/firebase-app.js"></script>
      <script src="/__/firebase/7.14.3/firebase-auth.js"></script>
      <script src="/__/firebase/7.14.3/firebase-storage.js"></script>
      <script src="/__/firebase/7.14.3/firebase-messaging.js"></script>
      <script src="/__/firebase/7.14.3/firebase-firestore.js"></script>
      <script src="/__/firebase/7.14.3/firebase-performance.js"></script>
      <script src="/__/firebase/7.14.3/firebase-functions.js"></script>
      <script src="/__/firebase/init.js"></script>

      <script src="scripts/main.js"></script>
   </body>
</html>

这是main.js(客户端)。

'use strict';
function signIn(){
  var provider = new firebase.auth.GoogleAuthProvider();
  firebase.auth().signInWithPopup(provider);
}
function saveMessage() {
  // Add a new message entry to the Firebase database.
  firebase.firestore().collection('messages').add({
      name: firebase.auth().currentUser.displayName,
      text: messageInputElement.value,
      timestamp: firebase.firestore.FieldValue.serverTimestamp()
  })
      .then(docRef => {

          this.firestoreDocListener = docRef.onSnapshot(doc => {
              if (doc.exists && doc.data().hasOwnProperty('fileName')) {
                  console.log(doc.data().fileName);
                  // Use doc.data().fileName the way you need!
                  // Create a reference from a Google Cloud Storage URI
                  var storage = firebase.storage();
                  var pathReference = storage.ref(doc.data().fileName)
                  pathReference.getDownloadURL().then(function(url) {
                    console.log(url);
                    const audio = document.createElement('AUDIO');
                    audio.controls = true;
                    audio.src = url;
                    const player = document.getElementById('player');
                    player.appendChild(audio);
                  }).catch(function(error) {
                    // A full list of error codes is available at
                    // https://firebase.google.com/docs/storage/web/handle-errors
                    switch (error.code) {
                      case 'storage/object-not-found':
                        console.log('storage/object-not-found')
                        break;

                      case 'storage/unauthorized':
                        console.log('storage/unauthorized')
                        break;

                      case 'storage/canceled':
                        console.log('storage/canceled')
                        break;

                      case 'storage/unknown':
                        console.log('storage/unknown')
                        break;
                    }  
                  });

              }
          });

      })
      .catch(function (error) {
          console.error('Error writing new message to Firebase Database', error);
      });
}

// Checks that the Firebase SDK has been correctly setup and configured.
function checkSetup() {
  if (!window.firebase || !(firebase.app instanceof Function) || !firebase.app().options) {
    window.alert('You have not configured and imported the Firebase SDK. ' +
        'Make sure you go through the codelab setup instructions and make ' +
        'sure you are running the codelab using `firebase serve`');
  }
}

// Checks that Firebase has been imported.
checkSetup();

// Shortcuts to DOM Elements.
var messageInputElement = document.getElementById('text');
var submitButtonElement = document.getElementById('download');
var signInButtonElement =document.getElementById('sign-in');


// Saves message on form submit.
submitButtonElement.addEventListener('click', saveMessage);
signInButtonElement.addEventListener('click', signIn);

这是index.js(服务器端云函数)

const functions = require('firebase-functions');
var admin = require("firebase-admin");
admin.initializeApp();
const textToSpeech = require('@google-cloud/text-to-speech');
require('date-utils');

exports.myFunction = functions.firestore
    .document('messages/{id}')
    .onCreate(async (snap) => {   // See the async here

        try {    //See the "global" try/catch

            const client = new textToSpeech.TextToSpeechClient();

            // The text to synthesize
            const newValue = snap.data();
            const text = newValue.text;

            // Construct the request
            const request = {
                input: { text: text },
                // Select the language and SSML voice gender (optional)
                voice: { languageCode: 'en-US', ssmlGender: 'NEUTRAL' },
                // select the type of audio encoding
                audioConfig: { audioEncoding: 'MP3' },
            };


            var bucket = admin.storage().bucket('adv********.appspot.com');
            var dt = new Date();
            var formatted = dt.toFormat('YYYYMMDDHH24MISS');
            var file = bucket.file('audio/' + formatted + '.mp3');
            // Create the file metadata
            var metadata = {
                contentType: 'audio/mpeg'
            };

            // Performs the text-to-speech request
            const [response] = await client.synthesizeSpeech(request);
            await file.save(response.audioContent, metadata);
            console.log("File written to Firebase Storage.");

            await snap.ref.update({ fileName: 'audio/' + formatted + '.mp3' });

            return null;

        } catch (error) {
            console.error(error);
        }

    });
javascript firebase authentication firebase-authentication gsuite
1个回答
1
投票

你需要在你的前端创建一个自定义的表单,收集这些数据并 保存这些信息 创建用户后,可以用这样的函数。

function writeUserData(userId, name, fav_color, best_friend, best_hero) {
  firebase.database().ref('users/' + userId).set({
    name: name,
    fav_color: fav_color,
    best_friend : best_friend,
    best_hero: best_hero
  });
}

然后,你通常会像这样结构你的数据库。

"users": {
    "$userID": {
        "name": "John",
        "fav_color": "chartruese",
        "best_friend": "James",
        "best_hero": "spiderman"
    }
}

注意一下,你通常会把这个数据发布出去 之后 用户是经过认证的,这样你就可以增加一个 基地法则 来确保只有该用户可以发布和读取这些数据。


2
投票

Firebase Authentication只知道你在User和UserInfo对象中看到的信息,而不是更多。 即使这样,一些数据也可能会丢失。 Auth并不能直接访问提供者可能知道的关于登录者的所有信息。 你将不得不以某种方式使用它自己的API直接查询提供者,或者让学生输入他们的信息并存储在数据库中(Firebase Auth不会存储任意的用户信息)。

© www.soinside.com 2019 - 2024. All rights reserved.