2017-08-10 25 views
8

花了一段時間尋找解決方案,看起來似乎是一個簡單的問題,但...我怎樣才能得到當前用戶的詳細信息在一個雲功能(當不使用functions.auth觸發器)?我確信必須有一個簡單的解決方案。 (我希望)Firebase雲端函數 - 獲取當前用戶ID

感謝您的回覆......剛剛完成,但是如何從存儲觸發事件中獲取Firebase數據庫中的/ user/uid?例如

exports.addUploadInfoToDatabase = functions.storage.object().onChange(event => { 
    console.log("firebase storage has been changed"); 
    // need to find the uid in here somehow 
    admin.database().ref(`/user/uid`).push({testKey:"testData"}); 
}) 

Applogies如果我錯過了答覆中的觀點。

謝謝...

+0

嗨,歡迎來到SO!請顯示你已經嘗試過的。目前的問題可能不會得到很好的答案,可能會被關閉。請[參觀](https://stackoverflow.com/tour)並閱讀[如何問](https://stackoverflow.com/help/how-to-ask)和[如何創建一個最小的,可驗證的例如](https://stackoverflow.com/help/mcve)以獲得更好的使用本網站的結果。 – vatavale

+0

這個問題的答案如何標記爲重複解決OP的問題並不清楚。 –

回答

3

首先,您可以獲得當前通過在用戶調用getIdToken()登錄用戶tokenId:https://firebase.google.com/docs/reference/js/firebase.User#getIdToken

firebase.auth().currentUser.getIdToken(true) 
.then(function (token) { 
    // You got the user token 
}) 
.catch(function (err) { 
    console.error(err); 
}); 

然後將其發送給您的雲功能。

然後在你的雲功能,您可以使用:https://firebase.google.com/docs/auth/admin/verify-id-tokens

例子:

admin.auth().verifyIdToken(idToken) 
    .then(function(decodedToken) { 
    var uid = decodedToken.uid; 
    // ... 
    }).catch(function(error) { 
    // Handle error 
    }); 

爲decodedToken的文檔是在這裏:https://firebase.google.com/docs/reference/admin/node/admin.auth.DecodedIdToken#uid

DecodedIdToken包含用戶的UID,那麼你就可以得到用戶通過調用此:https://firebase.google.com/docs/reference/admin/node/admin.auth.Auth#getUser

其中返回一個UserRecord https://firebase.google.com/docs/reference/admin/node/admin.auth.UserRecord

+0

感謝您的回覆......「首先,您可以將當前登錄的用戶tokenId從客戶端發送到您的雲端功能」....您的意思是將值傳遞給雲端功能嗎?我找不到任何文件來實現這一目標... –

+0

添加了Javascript示例以獲取客戶端中的用戶令牌。 – Kim

+0

如何訪問'firebase.auth()。currentUser'?我沒有定義'firebase'。如果你已經有了'currentUser',爲什麼不直接拿到'.uid? – Francescu