При использовании Google SignIn я хочу, чтобы Firestore создал пользователей/документ для нового пользователя, соответствующего имеющемуся у меня user.uid. Я использовал правила Firestore из этого поста.
Обновлено: Однако по-прежнему возникает эта ошибка:
C:\Users\alobre\Documents\Programmieren\BountyHunter\node_modules\react-devtools-core\dist\backend.js:32 Possible Unhandled Promise Rejection (id: 1):
Error: [firestore/permission-denied] The caller does not have permission to execute the specified operation.
NativeFirebaseError: [firestore/permission-denied] The caller does not have permission to execute the specified operation.
at FirestoreCollectionReference.get (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:133094:39)
at _callee$ (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:197066:93)
at tryCatch (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:24879:19)
at Generator.invoke [as _invoke] (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:25052:24)
at Generator.next (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:24922:23)
at tryCatch (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:24879:19)
at invoke (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:24952:22)
at http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:24982:13
at tryCallTwo (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:26948:7)
Вот мой код: Добавить пользователя
export default function addUser(user){
console.info(firestore())
firestore()
.collection('users')
.doc(user.uid)
.set({
user
})
.then(() => {
console.info('User added!');
});
}
вызывается при нажатии кнопки входа
async function onGoogleButtonPress() {
GoogleSignin.signIn()
.then((data) => {
const credential = auth.GoogleAuthProvider.credential(data.idToken, data.accessToken);
return auth().signInWithCredential(credential);
})
.then((user) => {
addUser(user)
})
.catch((error) => {
const { code, message } = error;
});
}
Мои правила Firestore:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
// Allow users to create a document for themselves in the users collection
match /users/{document=**} {
allow create: if request.resource.id == request.auth.uid &&
!("admin" in request.resource.data);
}
// Allow users to read, write, update documents that have the same ID as their user id
match /users/{userId} {
// Allow users to read their own profile (doc id same as user id)
allow read: if request.auth.uid == userId;
// Allow users to write / update their own profile as long as no "admin"
// field is trying to be added or created - unless they are already an admin
allow write, update: if request.auth.uid == userId &&
(
!("admin" in request.resource.data) ||
get(/databases/$(database)/documents/users/$(request.auth.uid)).data.admin == true // allow admin to update their own profile
)
}
}
}
РЕШЕНО: правила пожарного магазина верны. Однако я получил ошибку, что разрешение отклонено. причина:
match /users/{document=**} {
allow create: if request.resource.id == request.auth.uid &&
!("admin" in request.resource.data);
}
request.resource.id не соответствует запросу auth.uid Я пытался создать документ с uid модуля GoogleSignin (у которого даже нет uid, но есть id).
Правильным будет:
.then(
Post(auth().currentUser)
)
Firestore нужен этот auth().currentUser.uid, и я давал GoogleSignin.signIn().uid, который не соответствует request.auth.uid
Что не так с тем, что у вас есть сейчас? Пожалуйста, отредактируйте вопрос, чтобы объяснить, что не работает так, как вы ожидаете. Я заметил, что вы не проверяете наличие ошибок при вызове
set()
документа.