AngularFire,登录身份验证和重定向并不完全有效

AngularFire, login auth and redirect doesn't completely work

本文关键字:不完全 有效 重定向 登录 身份验证 AngularFire      更新时间:2023-09-26

所以我在S.O浏览了很多网站,文档和很多页面,但我似乎无法解决这些问题。而且我已经做了好几天了,现在没有进展。

我有一个基本的(最新的)Angular + Firebase连接,试图制作某种待办事项应用程序,让用户在他们的仪表板上创建自己的工作表。

我偶然发现了几个问题:*我已经解决了注册部分,但重定向到登录.html从注册.html不起作用。

  • 登录.html确实会触发,这将我路由到破折号.html但我似乎无法从那里访问数据库项目。下面给了我"权限被拒绝:客户端没有访问所需数据的权限"。

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

没有身份验证.html 就无法访问,所以这总是一些东西。我也无法使用注销按钮,它给我一个错误说:$scope.auth.$unauth 不是函数

  • 在我登录时.html我有一个"回到主页"链接,它不再有效,我认为在我添加 .run 模型之前它确实有效。

我会粘贴一些代码,真的希望我能得到一些帮助。我会把它们放在"隐藏"的盒子里,因为...文字墙等

路由:

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

控制器:

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

登录控制器:

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

我对Firebase和AngularFire有点陌生,但我在我的一个应用程序上进行了这种身份验证。

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

这个解决方案我想你可以在Firebase文档中的某个地方找到它。我会尝试找到这个的来源。它更面向纯粹的Firebase,而不是AngularFire,但可能会有用。

我希望这有所帮助。

亲切问候!