Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS and ExpressJS session management?

I would like to keep session across all the page. For this project, I am using expressJs, nodeJS as server side. AngularJS in front end.

I am not sure, how to handle session when view changes or url changes. Because I need to take care of both expressJS router or angularJs router.

What approach should I follow?

angularJS router

     myApp.config(['$routeProvider', function($routeProvider) {

    $routeProvider.when('/welcome', {templateUrl: 'partials/welcome.html', controller: 'MyCtrl2'});
    $routeProvider.when('/login', {templateUrl: 'partials/login.html', controller: 'MyCtrl2'});
    $routeProvider.when('/signup', {templateUrl: 'partials/signup.html', controller: 'singupController'});
    $routeProvider.otherwise({redirectTo: '/'});
  }]);

Signup controller

myApp.controller('singupController',function($scope,$rootScope,$http){

    $scope.doSingnup = function() {

       var formData = {
          'username' : this.username,
          'password' : this.password,
           'email' : null
      };

      var jdata = JSON.stringify(formData);

      $http({method:'POST',url:'/signup',data:jdata})
      .success(function(data,status,headers,config){

                console.log(data);

      }).
      error(function(data,status,headers,config){

        console.log(data)

      });
    }
  })

ExpressJS router

    module.exports = exports = function(app, db) {

    var sessionHandler = new SessionHandler(db);
    var contentHandler = new ContentHandler(db);

    // Middleware to see if a user is logged in
    app.use(sessionHandler.isLoggedInMiddleware);

    app.get('/', contentHandler.displayMainPage);

    app.post('/login', sessionHandler.handleLoginRequest);

    app.get('/logout', sessionHandler.displayLogoutPage);

    app.get("/welcome", sessionHandler.displayWelcomePage);

    app.post('/signup', sessionHandler.handleSignup);

    app.get('*', contentHandler.displayMainPage);

    // Error handling middleware
    app.use(ErrorHandler);
}

After signup, I would like to redirect to the login page. How can I do that in the above router. which one of the following should I use to change the view of app
1) $location of angularJS
2) redirect of ExpressJS

like image 981
niran Avatar asked Aug 28 '13 16:08

niran


People also ask

What is session in ExpressJS?

HTTP is stateless; in order to associate a request to any other request, you need a way to store user data between HTTP requests. Cookies and URL parameters are both suitable ways to transport data between the client and the server. But they are both readable and on the client side. Sessions solve exactly this problem.

What is the difference between NodeJS and ExpressJS?

NodeJS is an event-driven, non-blocking I/O model using JavaScript as its main language. It helps to build scalable network applications. Express is a minimal and flexible Node. js web application framework that provides a robust set of features for web and mobile applications.


2 Answers

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;

like image 80
alknows Avatar answered Sep 20 '22 22:09

alknows


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.

like image 42
BoxerBucks Avatar answered Sep 18 '22 22:09

BoxerBucks