AngularJS and ExpressJS session management? AngularJS and ExpressJS session management? angularjs angularjs

AngularJS and ExpressJS session management?


So i had the same problem and to be fair i might have read the approach somewhere i don't remember anymore.

Problem: Angular builds single page apps. After refresh, you loose scope and with it the authenticated user.

Approach

AngularJS modules offer a startup function called run which is called always when the page is loaded. Perfect for refresh/reload.

myApp.run(function ($rootScope, $location, myFactory) {    $http.get('/confirm-login')        .success(function (user) {            if (user && user.userId) {                $rootScope.user = user;            }        });}

express-session saves the sessions for you and authenticates you with the sessionId your browser sends. So it always knows if you are authenticated or not.

router.get('/confirm-login', function (req, res) {        res.send(req.user)    });

All i had to do is, after refreshing and all dependencies were loaded, ask if i am authenticated and set $rootScope.user = authenticatedUserFromExpress;


There are two different concepts here - server side session state and the user state on the client side in Angular. In express you can use the session via req.session to manage session based data.

On the angular side, there is only scope in your controllers. If you want to keep track of some data across multiple controllers, you need to create a service to store the data in and inject the service into the controllers you need.

A typical lifecycle is to first check if there is data already in the service, if so use it. If not, wait for the data to be populated (by the user or app or whatever) then detect those changes and synchronize with your service.


signup controller

function SignupCtrl($scope, $http, $location) {    $scope.form = {}; // to capture data in form     $scope.errorMessage = ''; // to display error msg if have any  $scope.submitPost = function() { // this is to submit your form can't do on                                    //traditional way because it against angularjs SPA    $http.post('/signup', $scope.form).      success(function(data) {    // if success then redirect to "/" status code 200        $location.path('/');      }).error(function(err) {   // if error display error message  status code 400                                 // the form can't be submitted until get the status code 200        $scope.errorMessage = err;      });  };}

sessionHandler.handleSignup

 this.handleSignup = function(req, res, next) {        "use strict";          // if you have a validate function pass the data from your          // Signup controller to the function in my case is validateSignup          // req.body is what you need         validateSignup(req.body, function(error, data) {         if(error) {            res.send(400, error.message); // if error send error message to angularjs        }else {            // do something else            // rmb to res.send(200)         }    });}

validatesignup

function validateSignup(data,callback) {        "use strict";   // the data is req.body            //so now you can access your data on your form            // e.g you have 2 fields name="password" and name="confirmPassword on your form"          var pass = data.password,              comPass = data.confirmPassword;           if(pass != comPass){               callback(new Error('Password must match'), null);                   // then show the error msg on the form by using                   //angular ng-if like <div ng-if="errorMessage">{{errorMessage}}</div>           }else{               callback(null, data);            }  }

hope this help