(function() { 'use strict'; var m = angular.module('securis', [ 'ngRoute', 'ngResource', 'toaster', 'localytics.directives', 'catalogs', 'i18n' ]); m.service('$store', function() { this.get = function(key, defaultValue) { return store.get(key) || defaultValue; } this.set = this.put = function(key, value) { store.set(key, value); } this.remove = this.delete = function(key) { return store.remove(key); } this.clear = this.clearAll = function() { store.clear(); } this.getAll = function() { return store.getAll(); } }); m.factory('securisHttpInterceptor', function($q, $location, $store, toaster) { var isUnauthorizedAccess = function(rejection) { return rejection.status === 401 /* Unauthorized */; } return { 'request': function(config) { var token = $store.get('token'); if (token) { var la = $store.get('last_access'); var now = new Date().getTime(); if (la !== null) { if (now > (la + 1800000)) { // Session timeout is 1/2 // hour $store.clear(); $location.path('/login'); toaster.pop('warning', 'Session has expired', null, 4000); } else { console.debug('Last access recent'); } } $store.set('last_access', now); } return config || $q.when(config); }, 'responseError': function(rejection) { // do something on error if (isUnauthorizedAccess(rejection)) { if ($location.path() !== '/login') { $store.clear(); $location.path('/login'); console.error('There was an unathorized access to url {0}, method: {1}'.$i18n(rejection.config.url, rejection.config.method)); } else { // console.log('Error on login ...') } } return $q.reject(rejection); } }; }); m.config(function($routeProvider, $locationProvider, $httpProvider) { console.debug('Configuring routes...'); $routeProvider.when('/login', { templateUrl: 'login.html', controller: 'LoginCtrl' }); $routeProvider.when('/licenses', { templateUrl: 'licenses.html', controller: 'PackAndLicensesCtrl' }); $routeProvider.when('/admin', { templateUrl: 'admin.html', controller: 'AdminCtrl' }); // configure html5 to get links working on jsfiddle $locationProvider.html5Mode(true); $httpProvider.interceptors.push('securisHttpInterceptor'); }); m.controller('MainCtrl', ['$scope', '$http', '$location', '$L', '$store', function($scope, $http, $location, $L, $store) { $scope.$location = $location; $location.path('/login'); if ($store.get('token') != null) { $http.get('check', { headers: { 'X-SECURIS-TOKEN': $store.get('token') } }).success(function(data) { if (data.valid) { $http.defaults.headers.common['X-SECURIS-TOKEN'] = $store.get('token'); var location = $store.get('location') || '/licenses'; $location.path(location); $store.set('user', data.user); } }); } $scope.logout = function() { $store.remove('user'); $store.remove('token'); $location.path('/login'); } }]); })();