Keep session alive after a page refresh in AngularJS

2,943 views
Skip to first unread message

Federico Vázquez

unread,
May 28, 2015, 10:53:40 PM5/28/15
to ang...@googlegroups.com

Basically, I want to learn a good practice for this implementation in my angularjs web application. I want to be able to display some greeting and logout button for logged users, even after the refresh the whole page until they logout or close the browser. And to show a "Sign in/Sign up" button if the user is not authenticated yet. I need to use the same logic with some "private" states of my application, for example: if user is not logged and he accesses this url account/options then he's forced to log in in order to proceed.

Example: Not logged user

 enter image description here

Logged user, no matter if page was refreshed after login

 enter image description here

Limitation: API

The api I was provided with only responds with this

 enter image description here

So I think I should build somehow a method like Auth.isLogged() that triggers with the application initialization (through the Auth service maybe?) and then use the condition to include some views, and also in router for the "private views".

But the problem here is that I'm just learning angularjs, and I never developed a login system before, so I don't know how can I create that method in which the application checks for a valid session.

Actually API is creating a cookie at api.aog.com.uy domain, which I think it's useless because I can't access that cookie under my web app domain...

The code:

App.js

'use strict';

angular
  .module('webapp', [
    'ngCookies',
    'ngResource',
    'ui.router',
  ])
  .run(
  [          '$rootScope', '$state', '$stateParams',
    function ($rootScope,   $state,   $stateParams) {
    $rootScope.$state = $state;
    $rootScope.$stateParams = $stateParams;
    }
  ]
)
  .config(['$stateProvider', function ($stateProvider) {

  /*
  MAYBE I SHOULD INITIALIZE Auth.isLogged() HERE?
  */

    $stateProvider
      .state('inicio', {
        url: '/',
        templateUrl: 'views/main.html',
        controller: 'MainCtrl',
      })
      .state('panel', {
        url: '/panel',
        title: 'Panel de usuario -',
        templateUrl: 'views/panel.html',
        controller: 'PanelCtrl'
      })
      .state('login', {
        url: '/login',
        title: 'Iniciar sesión -',
        templateUrl: 'views/login.html',
        controller: 'LoginCtrl'
      });
  }]);

Auth.js

'use strict';

angular.module('webapp')
    .service('Auth', function($http) {
        return {
          isLogged: function(cookieORsomethingElse){
            //some magic
            if (sessionAlive) {
               return true;
            } else {
               destroyOldCookieIfPresent();
               return false;
            }
          },
          login: function(credencial) {
            return $http.post('http://api.aog.com.uy/login/login', credencial);
          },
          logout: function() {

          },
          registro: function() {

          }
        };
  });

Login.js

'use strict';

angular.module('webapp')
  .controller('LoginCtrl', function ($scope, Auth, $rootScope, $state) {

    $scope.credencial = {servidor: 'alpha'};

    $scope.login = function() {
            Auth.login({
        user_id: $scope.credencial.username,
        password: $scope.credencial.password,
        server: $scope.credencial.servidor
      }).success(function(data, status) {
        console.log(data, status);
        $state.go('panel');
      }).error(function() {
        console.log('error: you suck');
      });
    };
  });

Live demo in case you want to check headers. This is the example i'm trying to follow. Thanks in advance! I'll really appreciate any kind of help :)

Sander Elias

unread,
May 29, 2015, 12:00:36 AM5/29/15
to ang...@googlegroups.com
HiFederico,


$http.post('http://api.aog.com.uy/login/login', credencial), will give you back some result. You can examine that result and see if the users is indeed logged in. 
Then you need a function that can checks if there is an existing session. This is dependent on your auth service, but I assume that is in the docs of your grails server.
depending on that outcome, you can simply store a value in your service that you can check from anywhere you need it.

Regards
Sander

Reply all
Reply to author
Forward
0 new messages