<commit_before>'use strict';

var osApp = angular.module('openspecimen', [
  'os.common',
  'os.biospecimen',
  'os.administrative',
  'os.query',

  'ngMessages',
  'ngCookies',
  'ngSanitize', 
  'ngGrid',
  'ui.router', 
  'ui.bootstrap', 
  'ui.mask', 
  'ui.keypress', 
  'ui.select',
  'ui.sortable',
  'ui.autocomplete',
  'mgcrea.ngStrap.popover',
  'angular-loading-bar',
  'pascalprecht.translate',
  'chart.js'
  ]);

osApp.config(function(
    $stateProvider, $urlRouterProvider, $httpProvider, $controllerProvider,
    $compileProvider, $filterProvider, $provide,
    $translateProvider, $translatePartialLoaderProvider,
    uiSelectConfig, ApiUrlsProvider) {

    osApp.providers = {
      controller : $controllerProvider.register,
      state      : $stateProvider.state,
      directive  : $compileProvider.directive,
      filter     : $filterProvider.register,
      factory    : $provide.factory,
      service    : $provide.service
    };

    $translatePartialLoaderProvider.addPart('modules');
    $translateProvider.useSanitizeValueStrategy(null);
    $translateProvider.useLoader('$translatePartialLoader', {  
      urlTemplate: '{part}/i18n/{lang}.js',
      loadFailureHandler: 'i18nErrHandler'
    });
 
    $stateProvider
      .state('default', {
        abstract: true,
        templateUrl: 'modules/common/default.html',
        controller: function($scope, Alerts) {
          $scope.alerts = Alerts.messages;
        }
      })
      .state('alert-msg', {
        url: '/alert?redirectTo&type&msg',
        controller: function($state, $stateParams, Alerts) {
          Alerts.add($stateParams.msg, $stateParams.type);
          $state.go($stateParams.redirectTo || 'home');
        },
        parent: 'default'
      })
      .state('signed-in', {
        abstract: true,
        templateUrl: 'modules/common/appmenu.html',
        resolve: {
          currentUser: function(User) {
            return User.getCurrentUser();
          },
          authInit: function(currentUser, AuthorizationService) {
            return AuthorizationService.initializeUserRights(currentUser);
          }
        },
        controller: 'SignedInCtrl'
      })
      .state('home', {
        url: '/home',
        templateUrl: 'modules/common/home.html',
        controller: function() {
        },
        parent: 'signed-in'
      })
      .state('admin-view', {
        abstract: true,
        template: '<div ui-view></div>',
        resolve: {
          isAdmin: function(currentUser, Util) {
            return Util.booleanPromise(currentUser.admin);
          }
        },
        parent: 'signed-in'
      });

    $urlRouterProvider.otherwise('/');

    $httpProvider.interceptors.push('httpRespInterceptor');

    ApiUrlsProvider.urls = {
      'sessions': 'rest/ng/sessions',
      'sites': 'rest/ng/sites',
      'form-files': 'rest/ng/form-files'
    };

    uiSelectConfig.theme = 'bootstrap';
  })
  .factory('i18nErrHandler', function($q) {
    return function(part, lang) {
      return $q.when({});
    }
  })
  .factory('httpRespInterceptor', function(
    $rootScope, $q, $injector, $window, $templateCache,
    Alerts, LocationChangeListener) {

    var qp = '?_buildVersion=' + ui.os.appProps.build_version + '&_buildDate=' + ui.os.appProps.build_date;

    function displayErrMsgs(errors) {
      var errMsgs = errors.map(
        function(err) {
          return err.message + " (" + err.code + ")";
        }
      );
      Alerts.errorText(errMsgs);
    }

    return {
      request: function(config) {
        if (config.method == 'GET' && $templateCache.get(config.url) == null) {
          if (config.url.indexOf('modules') == 0 || config.url.indexOf('plugin-ui-resources') == 0) {
            config.url += qp;
          }
        }

        return config || $q.when(config);
      },

      requestError: function(rejection) {
        $q.reject(rejection);
      },

      response: function(response) {
        var httpMethods = ['POST', 'PUT', 'PATCH'];
        if (response.status == 200 && httpMethods.indexOf(response.config.method) != -1) {
          LocationChangeListener.allowChange();
        }
        return response || $q.when(response);
      },

      responseError: function(rejection) {
        if (rejection.status == 0) {
          Alerts.error("common.server_connect_error");
        } else if (rejection.status == 401) {
          $rootScope.loggedIn = false;
          delete $window.localStorage['osAuthToken'];
          delete $injector.get("$http").defaults.headers.common['X-OS-API-TOKEN'];
          $injector.get('$state').go('login'); // using injector to get rid of circular dependencies
        } else if (rejection.status / 100 == 5) {
          if (rejection.data instanceof Array) {
            displayErrMsgs(rejection.data);
          } else {
            Alerts.error("common.server_error");
          }
        } else if (rejection.status / 100 == 4) {
          if (rejection.data instanceof Array) {
            displayErrMsgs(rejection.data);
          } else if (rejection.config.method != 'HEAD') {
            Alerts.error('common.ui_error');
          }
        } 

        return $q.reject(rejection);
      }
    };
  })
  .factory('ApiUtil', function($window, $http) {
    return {
      processResp: function(result) {
        var response = {};
        if (result.status / 100 == 2) {
          response.status = "ok";
        } else if (result.status / 100 == 4) {
          response.status = "user_error";
        } else if (result.status / 100 == 5) {
          response.status = "server_error";
        }

        response.data = result.data;
        return response;
      },

      initialize: function(token) {
        $http.defaults.headers.common['X-OS-API-CLIENT'] = "webui";

        if (!token) {
          token = $window.localStorage['osAuthToken'];
          if (!token) {
            return;
          }
        }

        $http.defaults.headers.common['X-OS-API-TOKEN'] = token;
        $http.defaults.withCredentials = true;
      }
    };
  })
  .provider('ApiUrls', function() {
    var that = this;
    var server = ui.os.server;

    this.urls = {};

    this.$get = function() {
      return {
        hostname: server.hostname,
        port    : server.port,
        secure  : server.secure,
        app     : server.app,
        urls    : that.urls,

        getBaseUrl: function() {
          return server.url + 'rest/ng/';
        },

        getUrl: function(key) {
          var url = '';
          if (key) {
            url = this.urls[key];
          }
          return server.url + url;
        }
      };
    }
  })
  .run(function(
    $rootScope, $window, $document, $http, $cookies, $q,  $state, $translate, $translatePartialLoader,
    LocationChangeListener, ApiUtil, Setting, PluginReg, Util) {

    if (!angular.merge) {
      angular.merge = function(dst, src) {
        return Util.merge(src, dst);
      }
    }

    $document.on('click', '.dropdown-menu.dropdown-menu-form', function(e) {
      e.stopPropagation();
    });

    if ($window.localStorage['osAuthToken']) {
      $cookies['osAuthToken'] = $window.localStorage['osAuthToken'];
      $rootScope.loggedIn = true;
    } else if ($cookies['osAuthToken']) {
      $window.localStorage['osAuthToken'] = $cookies['osAuthToken'];
      $http.defaults.headers.common['X-OS-API-TOKEN'] = $cookies['osAuthToken'];
      $rootScope.loggedIn = true;
    }

    ApiUtil.initialize();

    $rootScope.$on('$stateChangeSuccess',
      function(event, toState, toParams, fromState, fromParams) {
        $rootScope.state = toState;
      });

    $rootScope.$on('$stateChangeStart',
      function(event, toState, toParams, fromState, fromParams) {
        LocationChangeListener.onChange(event);

        if (toState.parent != 'default') {
          $rootScope.reqState = {
            name: toState.name,
            params: toParams
          };
        } else if ($rootScope.loggedIn && toState.name != "login") {
          event.preventDefault();<commit_msg>Fixed the broken sign-in workflow.<commit_after>'use strict';

var osApp = angular.module('openspecimen', [
  'os.common',
  'os.biospecimen',
  'os.administrative',
  'os.query',

  'ngMessages',
  'ngCookies',
  'ngSanitize', 
  'ngGrid',
  'ui.router', 
  'ui.bootstrap', 
  'ui.mask', 
  'ui.keypress', 
  'ui.select',
  'ui.sortable',
  'ui.autocomplete',
  'mgcrea.ngStrap.popover',
  'angular-loading-bar',
  'pascalprecht.translate',
  'chart.js'
  ]);

osApp.config(function(
    $stateProvider, $urlRouterProvider, $httpProvider, $controllerProvider,
    $compileProvider, $filterProvider, $provide,
    $translateProvider, $translatePartialLoaderProvider,
    uiSelectConfig, ApiUrlsProvider) {

    osApp.providers = {
      controller : $controllerProvider.register,
      state      : $stateProvider.state,
      directive  : $compileProvider.directive,
      filter     : $filterProvider.register,
      factory    : $provide.factory,
      service    : $provide.service
    };

    $translatePartialLoaderProvider.addPart('modules');
    $translateProvider.useSanitizeValueStrategy(null);
    $translateProvider.useLoader('$translatePartialLoader', {  
      urlTemplate: '{part}/i18n/{lang}.js',
      loadFailureHandler: 'i18nErrHandler'
    });
 
    $stateProvider
      .state('default', {
        abstract: true,
        templateUrl: 'modules/common/default.html',
        controller: function($scope, Alerts) {
          $scope.alerts = Alerts.messages;
        }
      })
      .state('alert-msg', {
        url: '/alert?redirectTo&type&msg',
        controller: function($state, $stateParams, Alerts) {
          Alerts.add($stateParams.msg, $stateParams.type);
          $state.go($stateParams.redirectTo || 'home');
        },
        parent: 'default'
      })
      .state('signed-in', {
        abstract: true,
        templateUrl: 'modules/common/appmenu.html',
        resolve: {
          currentUser: function(User) {
            return User.getCurrentUser();
          },
          authInit: function(currentUser, AuthorizationService) {
            return AuthorizationService.initializeUserRights(currentUser);
          }
        },
        controller: 'SignedInCtrl'
      })
      .state('home', {
        url: '/home',
        templateUrl: 'modules/common/home.html',
        controller: function() {
        },
        parent: 'signed-in'
      })
      .state('admin-view', {
        abstract: true,
        template: '<div ui-view></div>',
        resolve: {
          isAdmin: function(currentUser, Util) {
            return Util.booleanPromise(currentUser.admin);
          }
        },
        parent: 'signed-in'
      });

    $urlRouterProvider.otherwise('/');

    $httpProvider.interceptors.push('httpRespInterceptor');

    ApiUrlsProvider.urls = {
      'sessions': 'rest/ng/sessions',
      'sites': 'rest/ng/sites',
      'form-files': 'rest/ng/form-files'
    };

    uiSelectConfig.theme = 'bootstrap';
  })
  .factory('i18nErrHandler', function($q) {
    return function(part, lang) {
      return $q.when({});
    }
  })
  .factory('httpRespInterceptor', function(
    $rootScope, $q, $injector, $window, $templateCache,
    Alerts, LocationChangeListener) {

    var qp = '?_buildVersion=' + ui.os.appProps.build_version + '&_buildDate=' + ui.os.appProps.build_date;

    function displayErrMsgs(errors) {
      var errMsgs = errors.map(
        function(err) {
          return err.message + " (" + err.code + ")";
        }
      );
      Alerts.errorText(errMsgs);
    }

    return {
      request: function(config) {
        if (config.method == 'GET' && $templateCache.get(config.url) == null) {
          if (config.url.indexOf('modules') == 0 || config.url.indexOf('plugin-ui-resources') == 0) {
            config.url += qp;
          }
        }

        return config || $q.when(config);
      },

      requestError: function(rejection) {
        $q.reject(rejection);
      },

      response: function(response) {
        var httpMethods = ['POST', 'PUT', 'PATCH'];
        if (response.status == 200 && httpMethods.indexOf(response.config.method) != -1) {
          LocationChangeListener.allowChange();
        }
        return response || $q.when(response);
      },

      responseError: function(rejection) {
        if (rejection.status == 0) {
          Alerts.error("common.server_connect_error");
        } else if (rejection.status == 401) {
          $rootScope.loggedIn = false;
          delete $window.localStorage['osAuthToken'];
          delete $injector.get("$http").defaults.headers.common['X-OS-API-TOKEN'];
          $injector.get('$state').go('login'); // using injector to get rid of circular dependencies
        } else if (rejection.status / 100 == 5) {
          if (rejection.data instanceof Array) {
            displayErrMsgs(rejection.data);
          } else {
            Alerts.error("common.server_error");
          }
        } else if (rejection.status / 100 == 4) {
          if (rejection.data instanceof Array) {
            displayErrMsgs(rejection.data);
          } else if (rejection.config.method != 'HEAD') {
            Alerts.error('common.ui_error');
          }
        } 

        return $q.reject(rejection);
      }
    };
  })
  .factory('ApiUtil', function($window, $http) {
    return {
      processResp: function(result) {
        var response = {};
        if (result.status / 100 == 2) {
          response.status = "ok";
        } else if (result.status / 100 == 4) {
          response.status = "user_error";
        } else if (result.status / 100 == 5) {
          response.status = "server_error";
        }

        response.data = result.data;
        return response;
      },

      initialize: function(token) {
        $http.defaults.headers.common['X-OS-API-CLIENT'] = "webui";

        if (!token) {
          token = $window.localStorage['osAuthToken'];
          if (!token) {
            return;
          }
        }

        $http.defaults.headers.common['X-OS-API-TOKEN'] = token;
        $http.defaults.withCredentials = true;
      }
    };
  })
  .provider('ApiUrls', function() {
    var that = this;
    var server = ui.os.server;

    this.urls = {};

    this.$get = function() {
      return {
        hostname: server.hostname,
        port    : server.port,
        secure  : server.secure,
        app     : server.app,
        urls    : that.urls,

        getBaseUrl: function() {
          return server.url + 'rest/ng/';
        },

        getUrl: function(key) {
          var url = '';
          if (key) {
            url = this.urls[key];
          }
          return server.url + url;
        }
      };
    }
  })
  .run(function(
    $rootScope, $window, $document, $http, $cookies, $q,  $state, $translate, $translatePartialLoader,
    LocationChangeListener, ApiUtil, Setting, PluginReg, Util) {

    if (!angular.merge) {
      angular.merge = function(dst, src) {
        return Util.merge(src, dst);
      }
    }

    $document.on('click', '.dropdown-menu.dropdown-menu-form', function(e) {
      e.stopPropagation();
    });

    if ($window.localStorage['osAuthToken']) {
      $cookies['osAuthToken'] = $window.localStorage['osAuthToken'];
      $rootScope.loggedIn = true;
    } else if ($cookies['osAuthToken']) {
      $window.localStorage['osAuthToken'] = $cookies['osAuthToken'];
      $http.defaults.headers.common['X-OS-API-TOKEN'] = $cookies['osAuthToken'];
      $rootScope.loggedIn = true;
    }

    ApiUtil.initialize();

    $rootScope.$on('$stateChangeSuccess',
      function(event, toState, toParams, fromState, fromParams) {
        $rootScope.state = toState;
      });

    $rootScope.$on('$stateChangeStart',
      function(event, toState, toParams, fromState, fromParams) {
        LocationChangeListener.onChange(event);

        if (toState.parent != 'default-nav-buttons') {
          $rootScope.reqState = {
            name: toState.name,
            params: toParams
          };
        } else if ($rootScope.loggedIn && toState.name != "login") {
          event.preventDefault();
{'fraction_non_alphanumeric': 0.1488268433108401, 'fraction_numerical': 0.004457376338760602, 'mean_word_length': 2.234034034034034, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2076685', 'n_tokens_mistral': 4974, 'n_tokens_neox': 4840, 'n_words': 825}