(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) { var isUnauthorizedAccess = function(rejection) { console.log('rejection -----------------------'); console.log(rejection); return rejection.status === 401 /* Unauthorized */; } return { '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.log('Configuring routes...'); $routeProvider.when('/login', { templateUrl: 'login.html', controller: 'LoginCtrl' }); $routeProvider.when('/licenses', { templateUrl: 'licenses.html', controller: 'LicensesCtrl' }); $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) { $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'); $location.path('/licenses'); $store.set('user', data.user); } }); } $scope.logout = function() { $store.remove('user'); $store.remove('token'); $location.path('/login'); } }]); })();