如何使用 Firebase 身份验证获取除用户名之外的用户信息
我是日本的一名英语老师。我正在使用 Firebase Hosting 开发一个 Web 应用
由于我们使用 Gsuite for Education,所以我的学生有 Google 帐户,因此我决定使用 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()
})
在
是否可以获取更多用户信息?
例如,我想要用户的学校名称、班级编号和学生编号。
我阅读了 Firebase Auth 文档。
https://firebase.google.com/docs/reference/js/firebase.User#providerdata
这似乎不错。但是我不明白如何使用它。
您能告诉我如何使用 Firebase Auth 获取用户名以外的用户信息吗?
这是 index.html
这是 main.js (客户端)
这是 index.js (服务器端云功能)
saveMessage
函数中,我使用
firebase.auth().currentUser.displayName
获取用户名。>
<!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>
'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);
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);
}
});
Firebase 身份验证仅知道您在 User 和 UserInfo 对象中看到的信息,仅此而已。即便如此,某些数据可能仍会丢失。Auth 无法直接访问提供商可能知道的有关登录人员的所有信息。您必须以某种方式直接使用提供商自己的 API 查询提供商,或者让学生输入他们的信息并将其存储在数据库中(Firebase Auth 不会存储任意用户信息。)
您需要在前端创建一个自定义表单来收集这些数据,并在创建用户后 保存这些详细信息 ,可能使用如下函数:
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"
}
}
请注意,您通常会在 用户通过身份验证后 发布这些数据,这样您就可以添加 firebase 规则 ,以确保只有该用户可以发布和读取该数据。