Issue persisting Firebase data

I am currently exploring Firebase and attempting to save the user object (specifically the user's email) into the database using the .then() method after executing

firebase.auth().createUserWithEmailAndPassword(email, password)

However, I encountered an error while trying to do this:

FIREBASE WARNING: set at /users/-KlMikr6xZnfYC6dFJ6f failed: permission_denied

This error message indicates that I do not have the necessary permissions to update the user data in the designated user node.

I have confirmed that the function works as intended. When I temporarily set the security write rules to true, the userobj is successfully created in the database.

I am unsure what mistake I might be making in this process.

Here is a snippet from my controller.js file:

angular.module('app')
  .controller('appCtrl', function($scope){

    //initialize empty user object for storing information
    $scope.user = {};

    //initialize empty object for capturing user password
    $scope.password = {};

    // add sign up event
    $scope.signUp = function(){
      const email = $scope.user.email;
      const password = $scope.password.setup;

      // create new firebase user
      firebase.auth().createUserWithEmailAndPassword(email, password)
        // add user object to database
        .then(function(){
          var userObj = $scope.user;
          console.log($scope.user);

          // set up database references
          let database = firebase.database();
          let ref = database.ref();
          let usersRef = ref.child('users');

          // push user object to database
          usersRef.push(userObj);

        })
        .catch(function(error) {
          // Handle Errors here.
          var errorCode = error.code;
          var errorMessage = error.message;
          console.log(errorCode);
          console.log(errorMessage);
        });   
    };

    firebase.auth().onAuthStateChanged(function(user) {
      if (user) {
        // User is signed in.
        console.log('user signed in');
        var uid = user.uid;
        console.log(uid);
      } else {
        // No user is signed in.
        console.log('user not signed in');
      }
    });

  })

Below are my Firebase database rules:

"rules": {
  "users": {
    "$uid": {
        ".read": true,
        ".write": "(auth.uid === $uid)"
    }
  }
}

Answer №1

, it appears that the issue lies in using .push(), which generates a child element with a new UID each time. To resolve this, ensure that you obtain the recently created user's UID and associate your object with the corresponding reference as shown below:

let uid = firebase.auth().currentUser.uid;
let usersRef = ref.child('users').child(uid);
usersRef.set(userObj);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering a NextJS error with head component

Trying to incorporate the head element into a NextJS page format has proven challenging. Despite consulting the official documentation, implementing next/head to add <head> has resulted in an error within the code block. Code: import Head from &apos ...

typescript warns that an object may be potentially null

interface IRoleAddProps { roles: Array<IRole> } interface IRoleAddState { current: IRole | null } class RoleAdd extends React.Component<IRoleAddProps, IRoleAddState> { state = { current: null, } renderNoneSelect = () ...

Shortcut to prevent false 0 values

When my server responds, it sends back an object structured as follows: { success: integer } Meanwhile, on the client side I'm using: return body && body.success; The issue arises when the integer is zero, causing the above code to return ...

Is it possible for XSS attacks to exploit the HREF attribute when used with jQuery?

Burp suite displaying an error message. The application seems to have a potential vulnerability related to DOM-based cross-site scripting. Data is retrieved from the location and passed to jQuery() using the following statement: jQuery(location). ...

Tips on choosing just the selected checkbox values

In my CodeIgniter view, I am utilizing AJAX to post data to my controller. <script type="text/javascript"> $(document).ready(function(){ // find the input fields and apply the time select to them. $('#sample1 inp ...

Error in template loading

Currently, I am going through the Angular.js tutorial to learn how to incorporate some of its advanced features into my existing applications. Everything has been smooth sailing until I reached the (angular route) section. Unfortunately, I've hit a ro ...

Comparing NodeIntegration, Preload Script, and IPC in Electron Framework

After thoroughly going through Electron's explanations on context isolation, IPC, and security, as well as delving into discussions like this thread about nodeIntegration and this post regarding preload.js, it's clear that there are various appro ...

"Encountering an issue when trying to choose a value from a select list using jQuery and the

What am I missing here or what is the correct approach to solve this? Take a look at the following code snippet: code snippet $(document).ready(function() { $(".metric_div").hide(); $("#solid_radio").click(function() { $("#solid").show(); ...

One-touch dial feature for mobile-friendly website

Currently working on a single page responsive website and looking for guidance on inserting a quick call button that will only be visible when accessed on mobile phones, while remaining hidden on desktops and tablets. Your assistance is greatly valued. Th ...

I am finding my program to be lacking efficiency. Is there a more concise method for solving this issue?

Starting off with my journey in Javascript, I am eager to tackle problems and enhance my skills. One challenge that came my way is the following question. Despite my efforts to solve it step by step, I feel like there might be room for improvement in my co ...

Create a new attribute within the ng-model object once it has been updated through ng-repeat

I am trying to figure out how to add a "discountRate" property to an ng-model object after it has been changed within an ng-repeat block. Check out this example for more information Another example can be found here Although the ng-model is updated as e ...

Please ensure that the data has fully loaded before initializing the component

I am currently working with Angular 1.5 and have a scenario where I have one component nested within another component, as shown below. The issue I am facing is that the data variable is not resolved by the time Angular triggers the component-child, result ...

Conditional jQuery actions based on the selected radio button - utilizing if/else statements

This task seemed simple at first, but I quickly realized it's more challenging than expected. Apologies in advance, as Javascript is not my strong suit. My goal is to have the main button (Get Your New Rate) perform different actions based on whether ...

Transform a string into a property of a JSON object

One of my challenges involves extracting a value from a JSON object called Task, which contains various properties. Along with this, I have a string assigned to var customId = Custom_x005f_f3e0e66125c74ee785e8ec6965446416". My goal is to retrieve the value ...

What is the process for integrating custom event information stored in the {} property of a highchart dataset into highcharts-vue?

Creating charts with Vue using JSON data passed into the :options tag has been my usual approach. However, I am now experimenting with constructing a custom chart by utilizing the renderer and ren.path().attr().add() functions. The load function within th ...

Is it possible to verify that a string exclusively comprises elements from an array?

Hey there, I've got a challenge where I need to verify whether a string consists only of letters from a predefined alphabet. If not, my bot kicks players from the game. I've come up with the following script: var letters = "a b c d e f g ...

Navigating Between Web Pages

Hello there! I'm curious to learn how I can establish routing between multiple pages. Specifically, I have an index page and I'd like to navigate to other HTML pages within my views folder. Is it possible to achieve this without relying on the An ...

I'm encountering difficulty with installing the 'angular/cli' package due to an error in npm that states the HostnameIP doesn't match the certificate altnames

**I have encountered an issue while trying to install angular-cli on an institutional wifi network. Can anyone help me troubleshoot this problem?** C:\Windows\system32>npm install -g angular-cli npm ERR! Windows_NT 6.2.9200 npm ERR! argv "C:& ...

injecting a variable from the configuration service into a TypeScript decorator

I am interested in setting up a scheduled task for my NestJs application to run at regular intervals. I found information on how to use intervals in the NestJs documentation. Since my application uses configuration files, I want to keep the interval value ...

In React Router v6, the homepage is continuously rendered as "/"

I am having issues implementing a router in my react-create-app. It always renders "/" and displays either the Home or SignIn page. How can I resolve this problem? function AppRouter({ isLoggedIn, user }) { return( <Router> <Routes&g ...