Michael Chen 的云功能似乎是从某个地方(外部服务器?)的 HTTP 请求触发的。我的员工写了一个在用户登录时触发的云函数:
// this watches for any updates to the user document in the User's collection (not subcollections)
exports.userLogin = functions.firestore.document('Users/{userID}').onUpdate((change, context) => {
// save the userID ubtained from the wildcard match, which gets put into context.params
let uid = context.params.userID;
// initialize basic values for custom claims
let trusted = false;
let teaches = [];
// check the Trusted_Users doc
admin.firestore().collection('Users').doc('Trusted_Users').get()
.then(function(doc) {
if (doc.data().UIDs.includes(uid)) {
// if the userID is in the UIDs array of the document, set trusted to true.
trusted = true;
}
// Get docs for each language in our dictionary
admin.firestore().collection('Dictionaries').get()
.then(function(docs) {
// for each of those language docs
docs.forEach(function(doc) {
// check if the userID is included in the trustedUIDs array in the doc
if (doc.data().trustedUIDs.includes(uid)) {
// if it is, we push the 2-letter language abbreviation onto the array of what languages this user teaches
teaches.push(doc.data().shortLanguage);
}
});
// finally, set custom claims as we've parsed
admin.auth().setCustomUserClaims(uid, {'trusted': trusted, 'teaches': teaches}).then(() => {
console.log("custom claims set.");
});
});
});
});
首先,我们在用户对象上放入lastLogin 属性,当用户登录时运行 Date.now 并将时间写入数据库位置,触发云功能。
接下来,我们从云函数响应context.params.userID获取userID。
然后初始化两个变量。我们假设用户不被信任,除非另有证明。另一个变量是用户教授的主题数组。在基于角色的数据安全系统中,这些是允许用户访问的集合。
接下来,我们访问列出受信任用户的用户 ID 的文档。然后我们检查最近登录的用户 ID 是否在这个数组中。如果是这样,我们将trusted 设置为true。
接下来,我们进入数据库并遍历集合Dictionaries,其文档包含受信任的用户 ID 数组(即,允许读取和写入这些文档的用户)。如果用户在这些数组中的一个或多个中,他或她会将该文档添加到他或她的用户数据的teaches 属性中,从而使用户可以访问该文档。
最后,我们准备运行setCustomUserClaims 来自定义令牌声明。