I want to use Google's Firestore to save user data, while the backend uses PHP. So far I configured the access rules like this:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.auth != null;
}
}
}
I followed google's official documentation and my code looks like this:
$firestore = new FirestoreClient([
'projectId' => env('firebase.project.id'),
'keyfileName' => env('firebase.key.file')
]);
$collection = $firestore->collection('users');
$document = $collection->document($uid);
//this one triggers the permission error
$secret_key = $document->snaphot->get('secret_key');
Then I get:
PERMISSION_DENIED: Missing or insufficient permissions.
I tried to modify my rules like this:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.auth.uid != null;
}
}
}
No difference. By the way, the firebase authentication part works, I can create users and make them logged in. Furthermore, if I turn of the rules the error vanishes, but obviosly that is not a solution. I'm using CodeIgniter 4.5.5 with the most recent google/cloud-firestore
. When I will be back in my office, I can link all the dependencies. For now, I would appreciate any help.
Finally here is the solution.
I used kreait/firebase-php
implementation of firestore. However make sure you fulfill all requirements listed in google's doc to make it work.
Dependencies in composer.json
:
"firebase/php-jwt": "^6.10",
"google/cloud-firestore": "^1.47",
"google/gax": "1.35.1",
"google/protobuf": "^4.29",
"grpc/grpc": "^1.57",
"kreait/firebase-php": "^7.0"
Firestore:
use Google\Cloud\Firestore\DocumentSnapshot;
use Google\Cloud\Firestore\FirestoreClient;
use Kreait\Firebase\Contract\Auth;
use Kreait\Firebase\Factory;
...
public function __construct()
{
$this->factory = (new Factory())
->withServiceAccount(env('firebase.key.file'))
->withFirestoreDatabase('(default)');
$this->auth = $this->factory->createAuth();
//this one gives the FirestoreClient
$this->firestore = $this->factory->createFirestore()->database();
}
...
public function getUserData(string $uid) : DocumentSnapshot
{
$collection = $this->firestore->collection('users');
$user = $collection->document($uid);
return $user->snapshot();
}
public function saveUserData(string $uid, array $data) : void
{
$collection = $this->firestore->collection('users');
$user = $collection->document($uid);
$user->set($data);
}