[英]how to get user information other than user name with Firebase Authentification
我是日本的英語老師。 我正在使用 Firebase 托管開發 web 應用程序
我的學生有 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
function 我用firebase.auth().currentUser.displayName
得到用戶名
是否可以獲得更多用戶信息? 例如,我想要用戶的學校名稱、class 編號和學生編號。 我閱讀了 Firebase Auth 文檔。 https://firebase.google.com/docs/reference/js/firebase.User#providerdata這似乎很好。 但是我無法理解如何使用它。
你能告訴我如何使用 Firebase Auth 獲取用戶名以外的用戶信息嗎?
這是索引。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);
}
});
Firebase 身份驗證只知道您在 User 和 UserInfo 對象中看到的信息,僅此而已。 即使這樣,也可能會丟失一些數據。 Auth 無法直接訪問提供商可能知道的有關登錄者的所有信息。您必須以某種方式直接使用其自己的 API 查詢提供商,或者讓學生輸入他們的信息並將其存儲在數據庫中(Firebase Auth 不會存儲任意用戶信息。)
您需要在前端創建一個自定義表單,用於收集該數據並在創建用戶后保存這些詳細信息,可能在 function 中,如下所示:
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 規則以確保只有該用戶可以發布和讀取該數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.