Firebase 函式
我正在嘗試使用可呼叫函式將我的用戶角色設定為 admin:
export const addAdminRole = functions.https.onCall(async (data, context) => {
admin.auth().setCustomUserClaims(data.uid, {
admin: true,
seller: false,
});
});
客戶
這是我在客戶端上呼叫函式的方式:
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;
// ..
});
};
用戶已創建,但未添加我的管理員角色
uj5u.com熱心網友回復:
問題可能來自于您沒有正確處理setCustomUserClaims()Cloud Function 中方法回傳的承諾,因此 Cloud Function 平臺可能會在 CF 達到終止狀態之前清理您的 CF。如檔案中所述,正確管理 Cloud Functions 的生命周期是關鍵。
以下應該可以解決問題:
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
}
});
此外,您可以按如下方式重構前端代碼以正確鏈接 promises:
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;
// ..
});
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/385227.html
