Locohost
Locohost

Reputation: 1702

Google Cloud Firestore: FirebaseError: [code=permission-denied]: Missing or insufficient permissions

It seems you can only make Firestore rules work, calling .add from client code, if you use the completely open/allow-all rule.

This is a VueJS app. In my main.js...

// You MUST import these 2 lines exactly so
// to get firebase/firestore loaded and working
import firebase from 'firebase';
import 'firebase/firestore';

import config from '../config/firebase.config.json';
firebase.initializeApp(config);

Vue.config.productionTip = false;
// Define some globals: Available to ALL page vues
Vue.prototype.$http = require('axios');
Vue.prototype.$firebase = firebase;

In my Login.vue I have...

methods: {
    loadFirebaseUIAuth() {
        const firebaseUIConfig = {
            'signInSuccessUrl': '/',
            'signInOptions': [
                // Leave the lines as is for the providers you want to offer your users.
                this.$firebase.auth.GoogleAuthProvider.PROVIDER_ID,
                this.$firebase.auth.FacebookAuthProvider.PROVIDER_ID,
                this.$firebase.auth.TwitterAuthProvider.PROVIDER_ID,
                this.$firebase.auth.GithubAuthProvider.PROVIDER_ID
                // firebase.auth.EmailAuthProvider.PROVIDER_ID
            ],
            // Terms of service url.
            'tosUrl': '/tos'
        };
        // Initialize the FirebaseUI Widget using Firebase.
        const firebaseUI = new firebaseui.auth.AuthUI(this.$firebase.auth());
        // The start method will wait until the DOM is loaded.
        firebaseUI.start('#firebaseui-auth-container', firebaseUIConfig);
    },
    initFirebaseAuthHandler() {
        this.$firebase.auth().onAuthStateChanged(function(user) {
            if (user) {
                // User is signed in.
                userData.displayName = user.displayName;
                userData.email = user.email;
                userData.emailVerified = user.emailVerified;
                userData.photoURL = user.photoURL;
                userData.uid = user.uid;
                userData.phoneNumber = user.phoneNumber;
                userData.providerData = user.providerData;
                user.getIdToken().then((accessToken) => {
                    console.log('Login.vue: FirebaseAuthHandler: sign-in-status:', 'Signed in!');
                    userData.accessToken = accessToken;
                    // Store User info, mainly to pass accessToken in request headers
                    localStorage.clear('userData');
                    localStorage.setItem('userData', JSON.stringify(userData));
                });
                console.log('Login.vue: userData: ', userData);
            } else {
                // User is signed out.
                console.log('Login.vue: FirebaseAuthHandler: sign-in-status: ', 'Signed out');
            }
        }, function(error) {
            console.error('Login.vue: FirebaseAuthHandler: ', error);
        });
    }
}

I'm not (not that I can see) doing anything to connect the user login info to the Firestore collection.add(...).then(...) call. Am I missing this connect-user-info-to-firestore step? Is this a manual or automatic thing?

My client Base.data-context.js create method looks like...

create(collection, model, doneSuccess, doneError) {
    const doneCreate = (doc) => {
        model.attribs = doc;
        return doneSuccess(model);
    };
    delete model.attribs.id; // Do not allow id when creating
    model.attribs.createdby = 'WebUI';
    model.attribs.createdon = new Date();
    model.attribs.modifiedby = 'WebUI';
    model.attribs.modifiedon = new Date();
    model.attribs.modifiedlastip = '';
    collection.add(model.attribs).then(doneCreate).catch(doneError);
}

It's very generic. Calling .add on the player collection.

In my Firestore rules, I have...

service cloud.firestore {
    match /databases/{database}/documents {
        match /{document=**} {
            // Any user can read or write this data
            allow read: if true;
            allow write: if true;
        }
        //match /{article=**} {
        //  // Only signed in users can write this data
        //  allow read: if true;
        //  allow write: if request.auth.uid != null;
        //}
        //match /{player=**} {
        //  // Only signed in users can read or write this data
        //  allow read: if request.auth.uid != null;
        //  allow write: if request.auth.uid != null;
        //}
        //match /{character=**} {
        //  // Only signed in users can read or write this data
        //  allow read: if request.auth.uid != null;
        //  allow write: if request.auth.uid != null;
        //}
    }
}

If I flip the comments to eliminate the first allow-all block, and enable the individual documents that should only allow request.auth.uid != null, you can no longer write. You get the permissions error in post title. So this tells me the rules are being processed because the comments flip enables/disables writing to the player collection.

Upvotes: 1

Views: 7416

Answers (1)

Locohost
Locohost

Reputation: 1702

Ok, so not too many firebase/firestore users on SO in Oct2017 :-) I finally found the answer. 99.9% of the code above is fine. You need 1 more line inside the this.$firebase.auth().onAuthStateChanged(function(user) {... auth event handler then inside user.getIdToken().then((accessToken) => {: You need to tell firebase what the user accessToken is: this.$firebase.auth(accessToken);. After this, all my Firestore rules worked as expected.

Make sure you store your firebase ref in Vue.prototype.$firebase in your main.js. This will give you access to firebase in all your components.

Hope this helps someone later :-)

Upvotes: 5

Related Questions