Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - Redirect to Login page and Persistence of Session ID

Tags:

angularjs

I am looking for a way to do these two things, first I want to redirect the user to a login page if no SessionID is found and second I would like to hear your opinion about persisting session ID in memory only (no cookies).

The solution I came up with for the redirect is:

1 - Create a service called OAuth that will check if SessionID exists and if not, redirects to login page, the service is also responsible for the login and logout methods.

app.factory('OAuth', ['$http', function ($http) {

    var _SessionID = '';

    return { 
        login: function () {
            //Do login ans store sessionID in var _SessionID
        },

        logout: function () {
            //Do logout
        },

        isLoggedIn: function () {
            if(_SessionID) {
                return true;
            }
            //redirect to login page if false
        }
    };

}]);

2 - Inject the new OAuth service in each controller and check if user isLoggedIn

app.controller('myCtrl', ['$scope', 'OAuth', function ($scope, OAuth) {

    //check if user is logged
    OAuth.isLoggedIn();

}]);

Questions:

1 - The isLoggedIn() method will be called in all controllers, so I wonder if there is a way to do this without having to inject the service and call it in each controller.

2 - Instead of having a cookie to store the sessionID I want to save it in OAuth's _SessionID variable and for each request send it to the server. Is this a viable/secure approach? Can you give me some ideas for that?

Thanks!

like image 446
Bertrand Avatar asked Nov 20 '12 17:11

Bertrand


3 Answers

I use a similar strategy (intercepting 401 responses from the server). You can check out the full example here : https://github.com/Khelldar/Angular-Express-Train-Seed

It uses node and mobgodb on the backend for session store and a trimmed down http interceptor on the client that doens't retry requests like the one Dan linked above:

 var interceptor = ['$q', '$location', '$rootScope', function ($q, $location, $rootScope) {
        function success(response) {
            return response;
        }

        function error(response) {
            var status = response.status;
            if (status == 401) {
                $location.path('/login');
            }
            return $q.reject(response);
        }

        return function (promise) {
            return promise.then(success, error);
        }
    }];
    $httpProvider.responseInterceptors.push(interceptor);
like image 137
clangager Avatar answered Nov 15 '22 17:11

clangager


I would start here, Witold has created this cool interceptor that works off of http responses. I use it and its been really helpful.

like image 32
Dan Doyon Avatar answered Nov 15 '22 16:11

Dan Doyon


In my case, I used

  1. interceptor with $httpProvider
  2. config
  3. and $window dependency, as $location just appended the path to the existing url. What happened was like "http://www.tnote.me/#/api/auth", and it should have bene like "http://www.tnote.me/auth"

The code snippet is like this.

noteApp = angular.module('noteApp', ['ngRoute', 'ngCookies'])
  .factory('authInterceptor', ['$rootScope', '$q', '$cookies', '$window', 
    function($rootScope, $q, $cookies, $window) {
      return {
        request: function (req) {
          req.headers = req.headers || {};
          if ($cookies.token) {
            req.headers.Authorization = 'Bearer ' + $cookies.token;  
          }

          return req;
        },
        responseError: function (rejection) {
          if (rejection.status == 401) {
            $window.location = '/auth';      
          }

          return $q.reject(rejection);
        }
      }
  }])
  .config(['$routeProvider', '$httpProvider', function($httpProvider) {
    $httpProvider.interceptors.push('authInterceptor');  
    }
  ])
like image 2
Andrew Chaa Avatar answered Nov 15 '22 17:11

Andrew Chaa