Angular & Firebase $_SESSION like php?

244 Views Asked by At

im trying to membership process with angular and firebase.

Is there another solution, but instead of keeping user information in local storage and session storage?

I do not want to keep the local storage etc. sessionStorage. I think that because it is not safe.Of course,i do not keep sensitive information.I need more information on this subject.

Current login and signup coding.. Do you think this the right way ? "sorry for my bad english.."

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

There are 1 best solutions below

0
Alejandro Alfonzo On

You need to create services to store user data,

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

        }

    }
})();

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

And configure your routes and app modules: 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/');
  });

})();

Finally when you call a route declare the resolve statement:

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

And when you create a service call OnAuth to get "$_SESSION" info

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