具有路由限制的AngularFire身份验证

时间:2015-02-26 04:44:33

标签: javascript angularjs authentication firebase angularfire

我目前正在开发第一个Angular应用程序。我克服的每一个障碍都真正帮助我理解Angular中的所有内容,以及一般的编程。

目前,我正在尝试将AngularFire和Firebase作为应用程序的后端。接下来,我将在Firebase中存储其他数据,但现在我专注于将用户身份验证部分关闭。

目前,该应用程序由index.html页面组成,该页面将导航HTML元素作为标题加载,然后在ng-view元素中加载部分内容。这使得导航保持不变并且页面是动态的(大部分内容是通过各种JSON对象的Angular生成的)。它还包括一个完全独立的login.html,不包括主应用程序中的导航元素,但使用与应用程序其余部分相同的控制器和模块。我已经设法凑齐了一个工作登录,它与Firebase成功连接。这可以验证现有的电子邮件/密码组合或注册新用户。我真正想要的是成功登录以重定向到index.html,如果有人试图在未登录的情况下访问index.html或任何部分,则重定向到login.html。我不完全确定如何解决这个问题,但我相信它会与路由器有关。我还希望将身份验证信息附加到持久用户对象,以便以后可以用它来控制导航选项的可见性和功能。

我正在使用的Angular代码:

var profileApp = angular.module('profileApp', ['ngRoute', 'firebase']);

  profileApp.controller('LoginCtrl', ['$scope', '$rootScope', '$firebaseAuth', function($scope, $rootScope, $firebaseAuth) {
    var ref = new Firebase('https://FIREBASEURL.firebaseio.com/');
    $rootScope.auth = $firebaseAuth(ref);

    $scope.signIn = function () {
        $rootScope.auth.$login('password', {
            email: $scope.email,
            password: $scope.password
        }).then(function(user) {
            $rootScope.alert.message = '';
        }, function(error) {
            if (error = 'INVALID_EMAIL') {
                console.log('email invalid or not signed up — trying to sign you up!');
                 $scope.signUp();
                } else if (error = 'INVALID_PASSWORD') {
                console.log('wrong password!');
                } else {
                console.log(error);
                }   
        });
    }

    $scope.signUp = function() {
        $rootScope.auth.$createUser($scope.email, $scope.password, function(error, user) {
            if (!error) {
                $rootScope.alert.message = '';
            } else {
                $rootScope.alert.class = 'danger';
                $rootScope.alert.message = 'The username and password combination you entered is invalid.';
            }
        });
    }
  }
  ]);

profileApp.controller('AlertCtrl', [
    '$scope', '$rootScope', function($scope, $rootScope) {
    $rootScope.alert = {};
    }
]);

profileApp.controller('HistoryCtrl', function ($scope, $http){
    $http.get('patient.json').success(function(data) {
      $scope.historyItems = data;
    });
  });

profileApp.controller('FaceCtrl', function ($scope, $http){
    $http.get('patient.json').success(function(data) {
      $scope.faceItems = data;
    });
  });     
profileApp.controller('PhysicalCtrl', function ($scope, $http){
    $http.get('patient.json').success(function(data) {
      $scope.physicalItems = data;
    });
  });
profileApp.controller('MenuCtrl', function ($scope, $http){
    $http.get('profile.json').success(function(data) {
      $scope.profileItems = data;
    });
  });
profileApp.controller('ContentCtrl', function ($scope, $http){
    $http.get('content.json').success(function(data) {
      $scope.contentItems = data;
    });
  });
profileApp.controller('OrdersCtrl', function ($scope, $http){
    $http.get('patient.json').success(function(data) {
      $scope.ordersItems = data;
    });
  });
profileApp.controller('MedAdminCtrl', function ($scope, $http){
    $http.get('patient.json').success(function(data) {
      $scope.medadminItems = data;
    });
  });
profileApp.controller('LabsCtrl', function ($scope, $http){
    $http.get('patient.json').success(function(data) {
      $scope.labItems = data;
    });
  });
profileApp.controller('VitalsCtrl', function ($scope, $http){
    $http.get('patient.json').success(function(data) {
      $scope.vitalItems = data;
    });
  });
profileApp.controller('AssessmentCtrl', function ($scope, $http){
    $http.get('patient.json').success(function(data) {
      $scope.asessmentItems = data;
    });
  });
profileApp.controller('IoCtrl', function ($scope, $http){
    $http.get('patient.json').success(function(data) {
      $scope.ioItems = data;
    });
  });

profileApp.config(['$routeProvider', function ($routeProvider) {
    __insp.push(["virtualPage"]);
    $routeProvider
    // Home
    .when("/", {
                    templateUrl: "partials/face.html", 
                    controller: "FaceCtrl"
            })
    .when("/face", {
                    templateUrl: "partials/face.html", 
                    controller: "FaceCtrl"
                })
    // Pages
    .when("/medicalHistory", {
                    templateUrl: "partials/medicalhistory.html", 
                    controller: "HistoryCtrl"
                })
    .when("/physicalExam", {
                    templateUrl: "partials/physicalexam.html", 
                    controller: "PhysicalCtrl"
                })
    .when("/orders", {
                    templateUrl: "partials/orders.html", 
                    controller: "OrdersCtrl"
                })
    .when("/medAdmin", {
                    templateUrl: "partials/medadmin.html", 
                    controller: "MedAdminCtrl"
                })
    .when("/labs", {
                    templateUrl: "partials/labs.html", 
                    controller: "LabsCtrl"
                })
    .when("/vitals", {
                    templateUrl: "partials/vitals.html", 
                    controller: "VitalsCtrl"
                })
    .when("/assessment", {
                    templateUrl: "partials/assessment.html", 
                    controller: "AssessmentCtrl"
                })
    .when("/io", {
                    templateUrl: "partials/io.html", 
                    controller: "IoCtrl"
                })
    //.when("/contact", {templateUrl: "partials/contact.html", controller: "PageCtrl"})
    // else 404
    .otherwise("/404", {templateUrl: "partials/404.html", controller: "PageCtrl"});
}]);

1 个答案:

答案 0 :(得分:0)

在这里!,Iv改变了代码....检查出来,让我知道这是否解决了这个问题!

登录并注册:

profileApp.controller('LoginCtrl', ['$scope', '$location', '$firebase',
function($scope, $location, $firebase) {

    $scope.message = "";
    var username = "";
    var password = "";

    var ref = new Firebase("https://FIREBASEURL.firebaseio.com/");
    $scope.signIn = function() {

        username = $scope.username;
        password = $scope.password;

        ref.authWithPassword({
            email: username,
            password: password
        }, function(error, authData) {
            if (error) {
                switch (error.code) {
                    case "INVALID_EMAIL":
                        alert("The specified user account email is invalid.");
                        break;
                    case "INVALID_PASSWORD":
                        alert("The specified user account password is incorrect.");
                        break;
                    case "INVALID_USER":
                        alert("The specified user account does not exist.");
                        break;
                    default:
                        alert("Error logging user in:", error)
                }
                $scope.message = "Wrong Username/Password;";
            } else {
                $location.path("/home");
            }
        }, {
            remember: "sessionOnly"
        });
    };
};

$scope.signUp = function () {
    $rootScope.auth.$createUser($scope.email, $scope.password, function (error, user) {
        if (!error) {
            $rootScope.alert.message = '';
        } else {
            $rootScope.alert.class = 'danger';
            $rootScope.alert.message = 'The username and password combination you entered is invalid.';
        }
    });
};
]);

退出:

profileApp.controller('home', ['$scope', '$location', '$firebase',
function($scope, $location, $firebase) {

    function authDataCallback(authData) {
        if (authData) {
            alert("Logged in...");
        } else {
            $location.path("/login");
            alert("Log in to access this page");
        }
    };

    var ref = new Firebase("https://FIREBASEURL.firebaseio.com/");
    ref.onAuth(authDataCallback);
    $scope.logoutUser = function() {
        ref.unauth();
        $location.path("/login");
    };
    //        Authentication Code

还有一件事!单击“提交”按钮,您将无法在正确的用户名/密码上导航到另一个所需视图。在这里你会做什么:

1-点击提交按钮后等待5-10秒。 2-之后再次单击“提交”按钮。暂时尝试一下。

干杯!