Angular& Firebase $ _SESSION喜欢php?

时间:2016-01-28 12:01:05

标签: angularjs firebase firebase-authentication firebasesimplelogin

我尝试使用angular和firebase进行会员处理。

是否有其他解决方案,而不是将用户信息保存在本地存储和会话存储中?

我不想保留本地存储等sessionStorage。我认为这是因为它不安全。当然,我不保留敏感信息。我需要更多关于这个主题的信息。

当前登录和注册编码.. 你认为这是正确的方法吗? "抱歉我的英语不好......"

app.controller('SignuP',function($scope, $timeout,$sessionStorage, $window, Sessions){

$scope.success = false; 

$scope.SignuP = function(){
    var ref = new Firebase('https://<myfirebase>.firebaseio.com/');
    ref.createUser({
      email    : $scope.LoginEmail,
      password : $scope.LoginPass
    }, function(error, userData) {
      if (error) {
        console.log("Error creating user:", error);
        $scope.error = true;
        $scope.errortext = error;
        alert(error);
      } else {
        console.log("Successfully created user account with uid:", userData.uid);
        $scope.success = true;
            $timeout(function(){
                $scope.success = false;
            },4000);            
      }
    });
}   

$scope.Login = function(){
    var ref = new Firebase("https://<myfirebase>.firebaseio.com/");
    ref.authWithPassword({
      email    : $scope.LoginEmail,
      password : $scope.LoginPass
    }, function(error, authData) {
      if (error) {
        console.log("Login Failed!", error);
      } else {
        console.log("Authenticated successfully with payload:", authData);
         $window.sessionStorage.userid = authData.uid;
         $window.sessionStorage.login = true;

      }
    });     
}
$scope.online = $window.sessionStorage.getItem('login');
});

1 个答案:

答案 0 :(得分:0)

您需要创建用于存储用户数据的服务,

AuthService.js

(function(){
    'use strict';

    angular
            .module('app.auth')
      /**
       * AuthService is going to handle all of our auth functions, so we don't need to write them inside the controllers.
       */
            .factory('AuthService', AuthService);

    function AuthService($firebaseAuth, $firebaseObject, $firebaseArray, $state, $firebaseRef){

    var authUser = $firebaseAuth($firebaseRef.default);
return {
            /*
                The function receives an email, password, name and creates a new user
                After the user is created it stores the user details in the DB.
            */
            signupEmail: function(newEmail, newPassword, newFullName){

        /**
         * Here we're using angular-fire $createUser to create a new user, just passing the email, password and
         * full name.
         *
         * After that we're creating the record in the DB in a "userProfile" node, remember,
         * creating a user doesn't show him/her in the DB, so we need to create that record ourselves.
         *
         * And then we are catching any errors that might happen :P
         */    
                authUser.$createUser({
                    email: newEmail,
                    password: newPassword,
                    fullName: newFullName,
                }).then(function(authData){
            authUser.$authWithPassword({
              "email": newEmail,
              "password": newPassword
            }).then (function(authData){
                $firebaseRef.default.child("userProfile").child(authData.uid).set({
                name: newFullName,
                email: newEmail,
              });
              $state.go('menu.inicio');
            });                     
                }).catch(function(error){
                        switch (error.code) {
                      case "EMAIL_TAKEN":
                        alert("Bro, someone's using that email!");
                        break;
                      case "INVALID_EMAIL":
                        alert("Dude, that is not an email address!");
                        break;
                      default:
                        alert("Error creating user:", error);
                    }
                });
            },

      /**
       * Here we are login our user in, we user angular-fire $authWithPassword assing the email and password.
       * After that we send the user to our dashboard.
       */
            loginUser: function(email, password){
                authUser.$authWithPassword({
                    "email": email,
                    "password": password
                }).then (function(authData){
                    $state.go('menu.inicio');
                }).catch(function(error){
                    console.log(error);
                });
            },

            logoutUser: function(){
                authUser.$unauth();
                $state.go('login');
            },
userProfileData: function(userId){
                var userProfileRef = $firebaseRef.default.child('userProfile').child(userId);
                return $firebaseObject(userProfileRef);
            }

        }

    }
})();

使用authController.js调用此方法:

(function(){
    'use strict';

    angular
            .module('app.auth')
            .controller('LoginCtrl', LoginCtrl);
  /**
   * We create our controller and inject the AuthService so we can connect to Firebase.
   */
    LoginCtrl.$inject = ['$scope', '$state', 'AuthService'];

  function LoginCtrl($scope, $state, AuthService){
    // We create a variable called 'data', we asign it to an empty object and bind it to scope, to handle the form data.
        $scope.data = {};

    /**
     * Our function is pretty simple, get the username and password from the form, and send it to our auth service, that's it.
     * The auth service will take care of everything else for you!
     * @return {[type]} [description]
     */
        $scope.loginEmail = function(loginForm){
            if (loginForm.$valid) {
                var email = $scope.data.email;
                var password = $scope.data.password;
                AuthService.loginUser(email, password);
            };
        }
    }
})();

配置您的路线和应用模块: mainmodule.js

(function(){
  'use strict';

  angular
    .module('app', [

            /*
            This is the place for the core and shared modules
            */
            'app.core',

            /*
            This is the place for the features modules, like auth.
            */
            'app.auth',
]);

})();

coremodule.js

(function(){
  'use strict';

  angular
    .module('app.core', [
            'firebase',
    ]);

angular
    .module('app.core')
    .run(['$rootScope', '$state',
         function( $rootScope, $state) {
                /*Cath the stateError for un-authenticated users
                */
                $rootScope.$on("$stateChangeError", function(event, toState, toParams, fromState, fromParams, error){
                if (error === "AUTH_REQUIRED") {
                    $state.go('login');
                };
            });
        }])
  .config(function($firebaseRefProvider) {
    $firebaseRefProvider.registerUrl('https://<url>.firebaseio.com/');
  });

})();

最后,当您调用路由时,声明resolve语句:

routes.js

(function(){

  angular
    .module('app.core')
    .config(['$stateProvider', '$urlRouterProvider',
        function($stateProvider, $urlRouterProvider) {

            $stateProvider
                .state('login', {
                    url: '/login',
                    templateUrl: 'app/auth/login/login.html',
                    controller: 'LoginCtrl',
                })
              .state('MytablewithInfo', {
                url: '/mwinfo',
                resolve: {
                user: function($firebaseAuthService) {
                  return $firebaseAuthService.$requireAuth();
              }
              },
                views: {
                  'my-view-name': {
                    templateUrl: 'app/core/templates/mypage.html',
                    controller: 'myCtrl',
                  }
                }
              })


            ;
            $urlRouterProvider.otherwise('login');
    }]);
})();

当您创建服务调用OnAuth以获取“$ _SESSION”信息

ref.onAuth(function(authData) {
  if (authData) {
      // User signed in!
  uid = authData.uid;
}
  });