[javascript] Firebase Permission Denied

I'm relatively new to coding and am having trouble.

I have this code to send data to firebase

app.userid = app.user.uid

var userRef = app.dataInfo.child(app.users);

var useridRef = userRef.child(app.userid);

useridRef.set({
  locations: "",
  theme: "",
  colorScheme: "",
  food: ""
});

However, I keep getting the error:

FIREBASE WARNING: set at /users/(GoogleID) failed: permission_denied 2016-05-23 22:52:42.707 firebase.js:227 Uncaught (in promise) Error: PERMISSION_DENIED: Permission denied(…)

When I try to look this up it talks about rules for Firebase, which seems to be in a language that I haven't learned yet (or it is just going over my head). Can someone explain what is causing the issue? I thought it was that I was asking for it to store email and user display name and you just weren't allowed to do this, but when I took those out I still had the same problem. Is there a way to avoid this error without setting the rules, or are rules something I can teach myself how to write in a day, or am I just way out of my league?

Thanks for any help!

The answer is


By default the database in a project in the Firebase Console is only readable/writeable by administrative users (e.g. in Cloud Functions, or processes that use an Admin SDK). Users of the regular client-side SDKs can't access the database, unless you change the server-side security rules.


You can change the rules so that the database is only readable/writeable by authenticated users:

{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null"
  }
}

See the quickstart for the Firebase Database security rules.

But since you're not signing the user in from your code, the database denies you access to the data. To solve that you will either need to allow unauthenticated access to your database, or sign in the user before accessing the database.

Allow unauthenticated access to your database

The simplest workaround for the moment (until the tutorial gets updated) is to go into the Database panel in the console for you project, select the Rules tab and replace the contents with these rules:

{
  "rules": {
    ".read": true,
    ".write": true
  }
}

This makes your new database readable and writeable by anyone who knows the database's URL. Be sure to secure your database again before you go into production, otherwise somebody is likely to start abusing it.

Sign in the user before accessing the database

For a (slightly) more time-consuming, but more secure, solution, call one of the signIn... methods of Firebase Authentication to ensure the user is signed in before accessing the database. The simplest way to do this is using anonymous authentication:

firebase.auth().signInAnonymously().catch(function(error) {
  // Handle Errors here.
  var errorCode = error.code;
  var errorMessage = error.message;
  // ...
});

And then attach your listeners when the sign-in is detected

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // User is signed in.
    var isAnonymous = user.isAnonymous;
    var uid = user.uid;
    var userRef = app.dataInfo.child(app.users);
    
    var useridRef = userRef.child(app.userid);
    
    useridRef.set({
      locations: "",
      theme: "",
      colorScheme: "",
      food: ""
    });

  } else {
    // User is signed out.
    // ...
  }
  // ...
});

OK, but you don`t want to open the whole realtime database! You need something like this.

{
  /* Visit https://firebase.google.com/docs/database/security to learn more about security rules. */
  "rules": {
    ".read": "auth.uid !=null",
    ".write": "auth.uid !=null"
  }
}

or

{
  "rules": {
    "users": {
      "$uid": {
        ".write": "$uid === auth.uid"
      }
    }
  }
}

I was facing similar issue and found out that this error was due to incorrect rules set for read/write operations for real time database. By default google firebase nowadays loads cloud store not real time database. We need to switch to real time and apply the correct rules.

enter image description here

As we can see it says cloud Firestore not real time database, once switched to correct database apply below rules:

{
   "rules": {
       ".read": true,
       ".write": true
     }
 }

Another solution is to actually create or login the user automatically if you already have the credentials handy. Here is how I do it using Plain JS.

function loginToFirebase(callback)
{
    let email = '[email protected]';
    let password = 'xxxxxxxxxxxxxx';
    let config =
    {
        apiKey: "xxx",
        authDomain: "xxxxx.firebaseapp.com",
        projectId: "xxx-xxx",
        databaseURL: "https://xxx-xxx.firebaseio.com",
        storageBucket: "gs://xx-xx.appspot.com",
    };

    if (!firebase.apps.length)
    {
        firebase.initializeApp(config);
    }

    let database = firebase.database();
    let storage = firebase.storage();

    loginFirebaseUser(email, password, callback);
}

function loginFirebaseUser(email, password, callback)
{
    console.log('Logging in Firebase User');

    firebase.auth().signInWithEmailAndPassword(email, password)
        .then(function ()
        {
            if (callback)
            {
                callback();
            }
        })
        .catch(function(login_error)
        {
            let loginErrorCode = login_error.code;
            let loginErrorMessage = login_error.message;

            console.log(loginErrorCode);
            console.log(loginErrorMessage);

            if (loginErrorCode === 'auth/user-not-found')
            {
                createFirebaseUser(email, password, callback)
            }
        });
}

function createFirebaseUser(email, password, callback)
{
    console.log('Creating Firebase User');

    firebase.auth().createUserWithEmailAndPassword(email, password)
        .then(function ()
        {
            if (callback)
            {
                callback();
            }
        })
        .catch(function(create_error)
        {
            let createErrorCode = create_error.code;
            let createErrorMessage = create_error.message;

            console.log(createErrorCode);
            console.log(createErrorMessage);
        });
}

Go to database, next to title there are 2 options:

Cloud Firestore, Realtime database

Select Realtime database and go to rules

Change rules to true.


Go to the "Database" option you mentioned.

  1. There on the Blue Header you'll find a dropdown which says Cloud Firestore Beta
  2. Change it to "Realtime database"
  3. Go to Rules and set .write .read both to true

Copied from here.


  1. Open firebase, select database on the left hand side.
  2. Now on the right hand side, select [Realtime database] from the drown and change the rules to:
{
  "rules": {
    ".read": true,
    ".write": true
  }
}

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to firebase

How can I solve the error 'TS2532: Object is possibly 'undefined'? Getting all documents from one collection in Firestore FirebaseInstanceIdService is deprecated Failed to resolve: com.google.firebase:firebase-core:16.0.1 NullInjectorError: No provider for AngularFirestore Firestore Getting documents id from collection How to update an "array of objects" with Firestore? firestore: PERMISSION_DENIED: Missing or insufficient permissions Cloud Firestore collection count iOS Swift - Get the Current Local Time and Date Timestamp

Examples related to firebase-realtime-database

Error: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() Firebase Permission Denied how to get all child list from Firebase android Android Firebase, simply get one child object's data Query based on multiple where clauses in Firebase Firebase Storage How to store and Retrieve images

Examples related to firebase-security

Firebase Permission Denied