Firebase函数
我正在尝试使用一个可调用的函数将我的用户角色设置为管理员:
export const addAdminRole = functions.https.onCall(async (data, context) => {
admin.auth().setCustomUserClaims(data.uid, {
admin: true,
seller: false,
});
});
Cient
以下是我在客户端上调用函数的方式:
const register = (email: string, password: string) => {
createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
// Signed in
const user = userCredential.user;
const addAdminRole = httpsCallable(functions, "addAdminRole");
addAdminRole({ email: user.email, uid: user.uid })
.then((result) => {
console.log(result);
})
.catch((error) => console.log(error));
history.push(`/home/${user.uid}`);
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
// ..
});
};
用户已创建,但我的管理员角色未添加
问题可能源于您没有正确处理云函数中setCustomUserClaims()
方法返回的promise,因此云函数平台可能会在CF达到终止状态之前对其进行清理。正如文档中所解释的,正确管理云功能的生命周期是关键。
以下应该可以解决问题:
export const addAdminRole = functions.https.onCall(async (data, context) => {
try {
await admin.auth().setCustomUserClaims(data.uid, {
admin: true,
seller: false,
});
return {result: "Success"}
} catch (error) {
// See https://firebase.google.com/docs/functions/callable#handle_errors
}
});
此外,您可以如下重构前端代码,以正确地链接承诺:
const register = (email: string, password: string) => {
createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
// Signed in
const user = userCredential.user;
const addAdminRole = httpsCallable(functions, "addAdminRole");
return addAdminRole({ email: user.email, uid: user.uid });
})
.then((result) => {
console.log(result);
history.push(`/home/${user.uid}`);
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
// ..
});
};