all files / app/auth/ authHelper.service.js

100% Statements 18/18
100% Branches 2/2
100% Functions 7/7
100% Lines 18/18
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69                            202×                                     208× 208× 208×           208× 25× 25× 25×   17×         208×                  
/**
 * @ngdoc service
 * @name app.auth.authHelper
 * @description
 * Add authorization functionality to a controller
 *
 */
(function () {
  'use strict';
 
  angular
    .module('app.auth')
    .factory('authHelper', factory);
 
  /** @ngInject */
  function factory($log, userCredentials, editInProgress, authHttpInterceptor) {
 
    return activate;
 
    /**
     * @ngdoc function
     * @name activate
     * @methodOf app.auth.authHelper
     * @description
     * Add members to a controller:
     * * loggedIn
     * * username
     * * logOut()
     *
     * @param {Object} vm
     * Controller instance
     * @param {Object} scope
     * Controller scope
     * @param {Function} loggedInChanged
     * Callback when login or logout
     */
    function activate(vm, scope, loggedInChanged) {
      vm.loggedIn = userCredentials.loggedIn;
      vm.username = userCredentials.username;
      vm.logOut = function () {
        // Cancel pending edits, if any
        editInProgress.closeEditors().then(
          function() {
            userCredentials.clearCredentials()
          })
      };
 
      userCredentials.subscribeChanged(scope, function (loading) {
        vm.loggedIn = userCredentials.loggedIn;
        vm.username = userCredentials.username;
        if (loggedInChanged) {
          // Controller can be notified by implementing loggedInChanged()
          loggedInChanged(loading);
        }
      });
 
      // Clear credentials on 403 error
      authHttpInterceptor.subscribeUnauthorized(scope, function () {
        $log.error('unauthorized');
        userCredentials.clearCredentials();
      });
    }
  }
})();