簡體   English   中英

Angular&Firebase $ _SESSION像PHP?

[英]Angular & Firebase $_SESSION like php?

我試圖與角度和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');
});

您需要創建服務來存儲用戶數據,

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM