Firebase onCreate向auth.user添加自定义声明 [英] Firebase onCreate add custom claims to the auth.user
问题描述
我正在尝试添加自定义声明,已注册到Firebase.我的Firestore还有另一个 user
集合,用于保存注册信息记录.现在,我试图保留isRegistered自定义声明,但似乎无法正常工作.
I am trying to add a custom claims, isRegistered to firebase. My firestore has another user
collection to keep register info records. Now I am trying to keep a isRegistered custom claim but I can not seem to get it work.
exports.addRegisteredRole = functions.database.ref('/user')
.onCreate((snap, context) => {
return // **I added this later, but the issue still remains.**
admin.auth()
.setCustomUserClaims(context.auth.uid, {isRegistered: true})
.then(() => {
console.log('done', snap)
return {
message: 'done',
data: snap
}
})
.catch(err => {
console.log('something went wrong', err);
return err
})
});
我正在通过以下方式检查此声明
I am checking this claim by,
currentUser.getIdTokenResult()
.then(res => {
console.log(res.claims.isRegistered)
})
(验证用户对象).即使我重新登录,它仍然是未定义的.我做错什么了吗,我对Firebase还是陌生的.
(auth user object). Even if I re-logged it remains undefined. Am I doing something wrong, I am very new to firebase.
推荐答案
问题出在onCreate触发器上.您以为您在context.auth对象中获取了uid,这是不正确的.
The issue is with your onCreate trigger. You assumed you're getting the uid in the context.auth object, which is not correct.
onCreate触发器将在您的用户"目录中添加新文档时自动触发.收藏.在这种情况下,context.aut.uid是未定义的.您应该在功能日志中对此进行跟踪.
The onCreate trigger will be triggered automatically on the addition of a new document in your "user" collection. In this case, the context.aut.uid is undefined. You should trace this in your function logs.
您可以通过几种方式实现您想要做的事情
- 如果用户记录文档使用用户ID作为文档名称,则可以执行以下操作
exports.addRegisteredRole =
functions.firestore
.document('test/{docId}')
.onCreate((snap, context) => {
admin.auth()
.setCustomUserClaims(snap.id, { isRegistered: true })
.then(() => {
console.log('done', snap)
return {
message: 'done',
data: snap
}
})
.catch(err => {
console.log('something went wrong', err)
return err
})
})
- 如果您要用其他名称命名用户记录文档,或者让firebase为您确定名称,那么您必须将uid作为文档数据中的属性.然后,您使用docSnapshot.data().uid而不是docSnapshot.id,如下所示
exports.addRegisteredRole =
functions.firestore
.document('test/{docId}')
.onCreate((snap, context) => {
admin.auth()
.setCustomUserClaims(snap.data().uid, { isRegistered: true })
.then(() => {
console.log('done', snap)
return {
message: 'done',
data: snap
}
})
.catch(err => {
console.log('something went wrong', err)
return err
})
})
祝你好运
这篇关于Firebase onCreate向auth.user添加自定义声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!