Issues persist with AngularFire login authentication and redirect

After spending countless hours scouring various websites, documentation, and numerous pages on Stack Overflow, I am still struggling to wrap my head around these issues. Despite my efforts over the past few days, I have made little progress.

My project involves a basic setup of Angular with Firebase, where users can create their own to-do lists on their dashboard.

I have encountered several challenges: * I have successfully implemented user registration, but the redirect from signup.html to login.html is not working.

  • The login.html page does redirect me to dash.html, but I am unable to access database items from there. Instead, I receive an error message stating: "Permission denied: Client doesn't have permission to access the desired data."

    <div id="user">Hello {{users.email}}</div>

Furthermore, dash.html requires authentication to access, which adds another layer of complexity. Additionally, the logout button triggers an error message stating: $scope.auth.$unauth is not a function

  • Moreover, the "Go back to Home" link on my login.html page no longer functions as expected, possibly due to recent changes I made related to the .run-model.

Below are snippets of code that illustrate my current setup. Any assistance in overcoming these obstacles would be greatly appreciated.

Routing:

todoTogo.run(['$rootScope', '$location', function($rootScope, $location){
  $rootScope.$on('$routeChangeStart', function(event, next, current){
    if($rootScope.auth === true){
        $location.path('/dash');
      } else {
        $location.path('/login');
      }
  });
}]);



// Config for routing
todoTogo.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider){
  $routeProvider

  // Route for landing page
  .when('/home', {
    templateUrl: '/home.html',
    controller: 'homeController'
  })

  // Route for sign up page
  .when('/signup', {
    templateUrl: '/signup.html',
    controller: 'signupController'
  })

  // Route for login page
  .when('/login', {
    templateUrl: '/login.html',
    controller: 'loginController'
  })

  // Route for user dashboard
  .when('/dash', {
    templateUrl: '/dash.html',
    controller: 'dashController'
  })


  // Route for create list
  .when('/create', {
    templateUrl: '/create.html',
    controller: 'appController'
  })


  .otherwise({ redirectTo: '/home' });
}])

Controllers:

'use strict';
var todoTogo = angular.module('todoTogo', ['firebase', 'ngRoute']);


todoTogo.controller('appController', ['$scope', '$firebaseArray',
  function($scope, $firebaseArray) {

    var itemsRef = new Firebase('http://URL.firebaseio.com');

    // Start with empty array
    $scope.items = $firebaseArray(itemsRef);

    // Adds item to $scope
    var timestamp = new Date().valueOf();
    $scope.addItem = function() {
        $scope.items.$add({
          id: timestamp,
          name: $scope.itemInput,
          done: false
        });
        $scope.itemInput = '';
      },

      // Check if todoInput-field is empty, if not, run addItem function
      $scope.addPost = function() {
        if (event.keyCode == 13 && $scope.itemInput != "") {
          $scope.addItem();

        }
      },

      // Remove item from scope
      $scope.removeItem = function(index, item) {
        if (item.id === undefined)
          return;
        $scope.items.$remove(item);
      },

      // Edit item in scope and save to Firebase
      $scope.editMode = function() {
        $(event.target).closest('li').toggleClass('editing');
      },
      $scope.editOnEnter = function(item) {
        if (event.keyCode == 13 && item.name) {
          $scope.editMode();
          $scope.items.$save(item);
        }
      }
  }
]);

todoTogo.controller('signupController', ['$scope', '$firebaseArray',
  function($scope, $firebaseArray) {
    var userRef = new Firebase('http://URL.firebaseio.com/');

    // Register function
    document.querySelector('#signup').addEventListener('click', function() {
        var name = document.querySelector('#name').value;
        var email = document.querySelector('#email').value;
        var password = document.querySelector('#password').value;

        userRegister(email, password);
      }),

      userRegister = function(email, password) {
        userRef.createUser({
          name: name,
          email: email,
          password: password
        }, function(error, userData) {
          if (error) {
            $('#signBlock').text(error);
          } else {
            $('#signBlock').text('Yay, account created! Move on to login!');
            userRef.child('users').child(userData.uid).set({
              'email': email,
              'password': password
            });
          }
        })
      }
  }
]);


todoTogo.controller('homeController', ['$scope', '$firebaseArray',
  function($scope, $firebaseArray) {
    $scope.signupComplete = function(input) {
      return input == 1 ? 'Foo' : 'Bar';
    }


  }
]);

todoTogo.controller('dashController', ['$scope', '$firebaseArray', '$firebaseAuth', '$rootScope', 'Auth', '$location',
  function($scope, $firebaseArray, $firebaseAuth, $rootScope, Auth, $location) {
    $rootScope.logoutUser = function() {
        $scope.auth.$unauth();
        $location.path('/home');
        console.log('Logged out user.');
      },

      $scope.createList = function() {

      }
  }
]);

Login controller:

todoTogo.factory('Auth', ['$firebaseAuth',
  function($firebaseAuth) {
    var ref = new Firebase('https://URL.firebaseio.com');
    return $firebaseAuth(ref);
  }
]);

todoTogo.controller('loginController', ['$scope', '$firebaseAuth', 'Auth', '$location', '$rootScope',
  function($scope, $firebaseAuth, Auth, $location, $rootScope) {
    var ref = new Firebase('https://URL.firebaseio.com');
    $scope.auth = $firebaseAuth(ref);

    // Login user, if true redirect to dash.html, if false, don't redirect, show error message
    $scope.loginUser = function() {
      $scope.auth = Auth;
      $scope.auth.$authWithPassword({
        email: $scope.email,
        password: $scope.password
      }, {
        remember: 'sessionOnly'
      }).then(function(authData) {
        console.log('Logged in as: ', authData.uid);
        $scope.auth.$onAuth(function(authData) {
          $rootScope.auth = true;
          $location.path('/dash.html');
        })

        // If error with login, catch it and prompt it
      }).catch(function(error) {
        console.log('There was an error: ', error);
      });
    };
  }


]);

Answer №1

I recently started exploring Firebase and AngularFire, and I managed to set up authentication for one of my apps successfully.

var ref = new Firebase('https://xxxxxxxxxx.firebaseio.com');


        function authHandler(error, authData) {
            if (error) {
                console.log("Login Failed!", error);
            } else {
                console.log("Authenticated successfully with payload:", authData);
            }
        }

        function login() {
            ref.authWithPassword({
                email: vm.email,
                password: vm.password
            }, authHandler);
        }

        function loginFacebook() {
            ref.authWithOAuthPopup("facebook", authHandler, {scope: 'email'});
        }

        function loginGoogle() {
            ref.authWithOAuthPopup("google", authHandler, {scope: 'email'});            
}

        ref.onAuth(function (authData) {

            if (authData) {
                var userRef = new Firebase('https://xxxxxxx.firebaseio.com/users/' + authData.uid);
                userRef.once("value", function (snapshot) {
                    var exist = snapshot.exists();


                    if (!exist) {
                        // save the user's profile into the database so we can list users,
                        // use them in Security and Firebase Rules, and show profiles
                        ref.child("users").child(authData.uid).set({
                            provider: authData.provider,
                            name: getName(authData),
                            email: getEmail(authData),
                            rol: 1
                        });
                    }
                    $location.path('/dash');
                    if (!$scope.$$phase) {
                        $scope.$apply();
                    }
                });
            }

I believe this solution is documented somewhere in the Firebase documentation. It leans more towards traditional Firebase usage rather than AngularFire, but it might still be helpful.

I hope you find this information useful.

Best Regards!

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

The Art of Checkbox Design

Seeking help in replacing the default check mark on a checkbox with an image. Here is the code snippet I am currently using: <html> <head> <style> .bl { background:-webkit-gradient(linear, left top, left bottom, color-stop(0, #175899), c ...

Do global variables in a node.js server apply across the entire server or exclusively to individual sessions or users?

I have a question that may seem basic, so I apologize in advance - are global variables in node.js applicable server-wide or is their scope limited to the session or user? For example, if I create a global boolean variable in a routes.js file to track whet ...

Tips for sending routeparams value to model window in AngularJS

In the current project, I am working on implementing a modal window for the edit screen functionality. The process involves displaying a list of items on the screen, from which users can select one row and then click on the modify button to open the edit s ...

Error message thrown: "The reference to $ is undefined. Are you using Jsfiddle?"

As a newcomer to javascript, I decided to experiment with creating a navigation bar that only appears when the user scrolls down using JSFiddle. However, when I transferred the code to Dreamweaver, it stopped functioning. Why is this happening? I've ...

Show text on Canvas when hovering

Recently, I've been working on a project inspired by this example where I made adjustments to the code in order to display it on a canvas. var canvas = document.getElementById('nokey'); var ctx = canvas.getContext('2d'); ctx ...

AngularJS issue: Form submission does not trigger the controller function

I am currently learning AngularJS and I am experimenting with the sample code below to send my form data to the server. <!doctype html> <html lang=''> <head> <meta charset="utf-8"> <script src="../js/angular.min.v1 ...

The Django REST framework is sending the 'u prefix to Angular when retrieving data from the database

I'm currently using Django Rest Framework along with AngularJS to develop a website that collects information for hair stylists and stores it in a database. On another page, this information is retrieved from the database and displayed on a profile pa ...

connect validation of the form to a separate component from the current one

Currently, I am working on creating a searchable-dropdown component that I intend to use in multiple components. However, I am facing an issue with binding form validation to this component. For instance, I have a form for creating a user and I need to bi ...

leveraging the v-modeled information from vue's two variables

When I v-model a data in my Vue HTML to validate it in my form, I also want to use it in another variable. Here is my HTML code: <input class="input-style px-3" :class="{'border-red-error':v$.categoryTitle.$errors.length>0}&q ...

Managing multiple arrays in asynchronous functions in node.js

I am facing an issue with a large array (10K) that I need to split. I tried following this method: and it worked perfectly. However, I now need to pass the separated arrays to a request function and await the response before passing it to savetodb. Could ...

AngularJS text area not displaying HTML content

In my Ionic's App, I have a textarea that is used for creating or editing messages. However, I am encountering an issue where the textarea does not render HTML tags when trying to edit a message. I attempted solutions such as setting ng-bind-html and ...

Modifying source dynamically in Javascript file through web.config during runtime

I have the following code snippet: <script type="text/javascript" src="path?key=1234567890"> </script> Additionally, I included the following in my web.config file: <appSettings> <add key="key" value="1234567890"/> Now, ho ...

The useEffect function is failing to execute when deploying on Vercel with Vite and React Router

After successfully deploying a React site using Vite on Vercel, with React Router for routing and a separate backend service, everything seemed to be working fine on my local machine. However, when testing the deployment on Vercel, I encountered an issue w ...

Access a file from an npm module using an executable command

I have a npm module called @jcubic/lips, which includes an executable file. I need to open a file located within the module's directory. This module is installed globally. The specific file I want to access is ../examples/helpers.lips, relative to th ...

JavaScript: unable to locate information within JSON reply

Looking to develop a Twitter bot utilizing the Twitter and Spotify APIs. Making progress, but encountered an issue I can't tackle alone: Seeking the artist and song name of the top 1 track from the top 50 Spotify songs. Upon sending a request to the ...

What is the method to assign an initial value to React.createRef()?

Scrolling management in my component is handled through a ref that represents the current scroll value. I've chosen to use refs instead of state and setState because using setState while the user is scrolling would result in a choppy and unresponsive ...

To properly document the results, I must utilize a button to record the identification of a specific color

I'm working on a code that creates a clickable box which changes colors from black to green to white by going through different shades of green whenever the mouse is clicked. What I now need to do is implement a feature that displays the current shade ...

Why does i18next only function on http://localhost:3000/de (landing page) in NextJS and not on http://localhost:3000/de/about?

I'm new to this and feeling lost on how to tackle this issue. I tried following the instructions on https://github.com/i18next/next-i18next, but I'm struggling with index.js. When I toggle /de on my landing page, it translates correctly in the UR ...

What is the best way to stylize a date using Bootstrap-datepicker?

While this topic is well-known, I have a slightly more complex question regarding it. I have gone through the documentation here. My goal is to display the date in French format (dd/mm/yyyy) and save the value in US format (yyyy-mm-dd). Additionally, I nee ...

Searching through data fields in MongoDB that have been filled with information

In my Mongoose queries, I am dealing with models known as "Activities" that have a specific schema structure. This schema includes fields such as actor, recipient, timestamp, activity, event, and comment. var activitySchema = new mongoose.Schema({ act ...