3
votes

So I've been through a lot of websites, documentation and a lot of pages here at S.O but I can't seem to wrap my head around these problems. And I've been at it for days without progress now..

I have a basic (latest) Angular + Firebase connection, trying to make some sort of todo app with users creating their own sheets onto their dashboard.

There's a few problems I've stumbled upon: * I've solved the registration part but redirect to login.html doesn't work from signup.html.

  • login.html does fire which routes me to dash.html but I can't seem to access the database items from there. Below gives me "Permission denied: Client doesn't have permission to access the desire data."

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

dash.html is not accessible without auth, so that's always something. Also I can't use the logout button, it gives me an error saying: $scope.auth.$unauth is not a function

  • At my login.html I have a "Go back to Home"-link which doesn't work anymore, I think it did before I added the .run-model.

I'll paste some code and really hope I can get some help getting through. I'll place them in "hidden" boxes because... wall of text etc.

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.html');
        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);
      });
    };
  }


]);
1
did you have an answer for $unauth is not a function? - Omar

1 Answers

0
votes

I'm kind of new to Firebase and AngularFire, but I have this authentication working on one of my apps.

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();
                    }
                });
            }

This solution I think you can find it somewhere in Firebase documentation. I'll try to find the source of this. It's more oriented to pure Firebase, not to AngularFire, but might be of use.

I hope this helps.

Kind Regards!