<commit_before>angular
  .module('Login')
  .factory('UserService', UserService);


UserService.$inject = [
  '$log', '$rootScope', '$http', '$q', '$timeout',
  '$stateParams', '$translate',
  'HeaderService'
];

function UserService (
  $log, $rootScope, $http, $q, $timeout,
  $stateParams, $translate,
  HeaderService
) {
  /// constants
  var _Roles = {
    _isGuest  : 0,
    _isAdmin  : 1,
    _isPlayer : 2,
  };

  // NOTE: these are permissions for Guest users
  var _Permits = {
    // RequestAllStations      : false,
    // RequestCategoryStations : false,
    // EditStation             : false
  };


  /// UserService
  var service = {
    _guestName : $translate.instant('LOGIN'),

    login           : login,
    logout          : logout,
    isLoggedIn      : isLoggedIn,
    register        : register,
    restoreUser     : restoreUser,
    restoreUserRole : restoreUserRole,
    changePassword  : changePassword,
    requestRestore  : requestRestore,

    getEditStationPermit             : getEditStationPermit,
    getRequestAllStationsPermit      : getRequestAllStationsPermit,
    getRequestCategoryStationsPermit : getRequestCategoryStationsPermit,

    Role   : _Roles,
    Permit : _Permits,

    Session : {
      isLoggedIn     : false,
      id             : null,
      username       : null,
      email          : null,
      created_at     : null,
      remember_token : null,

      role           : _Roles._isGuest,

      // NOTE: Remembers a mobidulCode to cache user roles for
      remMobidulCode : ''
    },
  };


  /// construct
  // ...


  /// private functions

  function _checkPermits (role) {
    return {
      // @description - TODO
      RequestAllStations : role == _Roles._isAdmin ||
      true /* editMode permits */ // TODO: see previous (inline-block) comment
      ,
      // @description - TODO
      RequestCategoryStations : role == _Roles._isAdmin ||
      true /* editMode permits */ // TODO: see previous (inline-block) comment
      ,
      // @description - TODO
      EditStation : role == _Roles._isAdmin ||
      ( role == _Roles._isPlayer &&
      true /* editMode permits */ ) // TODO: see previous (inline-block) comment
    };
  }


  function _getRoleForMobidul (mobidulCode) {
    var deferred = $q.defer();

    if ( service.Session.remMobidulCode === mobidulCode ) {
      deferred.resolve(service.Session.role);
    } else {
      $http.get(cordovaUrl + '/RoleForMobidul/' + mobidulCode)
        .success(function (response, status, headers, config) {
          var role = angular.isDefined(response.role) ? response.role : null;

          if ( role !== null ) {
            deferred.resolve(response.role);
          } else {
            deferred.reject({
              msg: 'No user role passed from server !'
            });
          }
        })
        .error(function (response, status, headers, config) {
          deferred.reject(response);
        });
    }

    return deferred.promise;
  }


  function _getPermit (mobidulCode) {
    var deferred = $q.defer();

    // to make sure the permit was initialized
    _getRoleForMobidul(mobidulCode)
      .then(function (role) {
        deferred.resolve(service.Permit);
      }, function (error) {
        deferred.reject(error);
      });

    return deferred.promise;
  }


  /// services

  function login (credentials) {
    var postData = {
      user: credentials.username,
      password: <PASSWORD>
    };

    return $http.post(cordovaUrl + '/login', postData)
      .success(function (response, status, headers, config) {
        $log.debug('login response: ', response);

        if ( response === 'success' ) {
          service.Session.isLoggedIn = true;
          service.Session.username   = credentials.username;
        }
      })
      .error(function (response, status, headers, config) {
        $log.error(response);
        $log.error(status);
      });
  }


  function logout () {
    return $http.get(cordovaUrl + '/logout')
      .success(function (response, status, headers, config) {
        if ( response === 'success' ) {
          var guestName = service._guestName;
          var isGuest   = _Roles._isGuest;

          service.Session.isLoggedIn = false;
          service.Session.username   = guestName;
          service.Session.role       = isGuest;
          service.Session.remMobidulCode = '';

          service.Permit = angular.copy( _Permits );
        }
      })
      .error(function (response, status, headers, config) {
        $log.error(response);
        $log.error(status);
      })
      .then(function (response) {
        // $rootScope.$emit('Header::refresh');
        HeaderService.refresh();

        $rootScope.$emit('UserService::sessionUpdated');

        return response;
      });
  }


  function isLoggedIn () {
    return $http.get(cordovaUrl + '/IsLoggedIn')
      .success(function (data, status, headers, config) {
        if ( data === 'true' ) {
          service.Session.isLoggedIn = true;
        }
      })
      .error(function (data, status, headers, config) {
        $log.error(data);
        $log.error(status);
      });
  }


  function register (credentials) {
    var postData = {
      user     : credentials.username,
      email    : credentials.email,
      password : <PASSWORD>
    };


    return $http.post(cordovaUrl + '/register', postData)
      .success(function (response, status, headers, config) {
        // $log.debug(response);

        service.Session.username = credentials.username;
      })
      .error(function (response, status, headers, config) {
        $log.error(response);
        $log.error(status);
      });
  }


  function restoreUser () {
    return $http.get(cordovaUrl + '/currentUser')
      .success(function (response, status, headers, config) {
        $log.debug('> Restored current user successfully !');
        $log.debug(response);
        // $log.debug(response.guest);

        var isGuest = response.guest === true || response.guest == 1;
        var isGuestNot = ! isGuest;
        // $log.debug('isGuestNot: ' + isGuestNot);

        var email    = isGuestNot ? response.email    : null;
        var guestId  = isGuest    ? response.username : null;
        var username = isGuestNot ? response.username : service._guestName;

        var userData = {
          isLoggedIn     : isGuestNot,
          id             : response.id,
          username       : username,
          email          : email,
          created_at     : response.created_at,
          remember_token : response.remember_token,
        };

        if (isGuest) {
          userData.guestId = response.username;
        }

        service.Session = userData;
      })
      .error(function (response, status, headers, config) {
        $log.error(response);
        $log.error(status);
      });
  }


  function restoreUserRole (mobidulCode) {
    var deferred = $q.defer();

    _getRoleForMobidul(mobidulCode)
      .then(function (role) {
        service.Session.role = role;
        service.Session.remMobidulCode = mobidulCode;
        service.Permit = _checkPermits(role);

        HeaderService.refresh();
        deferred.resolve();
      },
      function (error) {
        $log.error('Error: UserService - restoreUserRole:');
        $log.error(error);

        deferred.reject(error);
      });

    return deferred.promise;
  }


  function changePassword (data) {
    var postData;

    if ( data.resetToken ) {
      postData = {
        route           : 'changePasswordNoAuth',
        resetToken      : data.resetToken,
        newPassword     : <PASSWORD>,
        confirmPassword : data.confirmPassword
      };
    } else {
      postData = {
        route       : 'changePassword',<commit_msg>Rename `remMobidulCode` to `currentMobidulCode` (refs #107)<commit_after>angular
  .module('Login')
  .factory('UserService', UserService);


UserService.$inject = [
  '$log', '$rootScope', '$http', '$q', '$timeout',
  '$stateParams', '$translate',
  'HeaderService'
];

function UserService (
  $log, $rootScope, $http, $q, $timeout,
  $stateParams, $translate,
  HeaderService
) {
  /// constants
  var _Roles = {
    _isGuest  : 0,
    _isAdmin  : 1,
    _isPlayer : 2,
  };

  // NOTE: these are permissions for Guest users
  var _Permits = {
    // RequestAllStations      : false,
    // RequestCategoryStations : false,
    // EditStation             : false
  };


  /// UserService
  var service = {
    _guestName : $translate.instant('LOGIN'),

    login           : login,
    logout          : logout,
    isLoggedIn      : isLoggedIn,
    register        : register,
    restoreUser     : restoreUser,
    restoreUserRole : restoreUserRole,
    changePassword  : changePassword,
    requestRestore  : requestRestore,

    getEditStationPermit             : getEditStationPermit,
    getRequestAllStationsPermit      : getRequestAllStationsPermit,
    getRequestCategoryStationsPermit : getRequestCategoryStationsPermit,

    Role   : _Roles,
    Permit : _Permits,

    Session : {
      isLoggedIn     : false,
      id             : null,
      username       : null,
      email          : null,
      created_at     : null,
      remember_token : null,

      role           : _Roles._isGuest,

      // NOTE: Remembers a mobidulCode to cache user roles for
      currentMobidulCode : ''
    },
  };


  /// construct
  // ...


  /// private functions

  function _checkPermits (role) {
    return {
      // @description - TODO
      RequestAllStations : role == _Roles._isAdmin ||
      true /* editMode permits */ // TODO: see previous (inline-block) comment
      ,
      // @description - TODO
      RequestCategoryStations : role == _Roles._isAdmin ||
      true /* editMode permits */ // TODO: see previous (inline-block) comment
      ,
      // @description - TODO
      EditStation : role == _Roles._isAdmin ||
      ( role == _Roles._isPlayer &&
      true /* editMode permits */ ) // TODO: see previous (inline-block) comment
    };
  }


  function _getRoleForMobidul (mobidulCode) {
    var deferred = $q.defer();

    if ( service.Session.currentMobidulCode === mobidulCode ) {
      deferred.resolve(service.Session.role);
    } else {
      $http.get(cordovaUrl + '/RoleForMobidul/' + mobidulCode)
        .success(function (response, status, headers, config) {
          var role = angular.isDefined(response.role) ? response.role : null;

          if ( role !== null ) {
            deferred.resolve(response.role);
          } else {
            deferred.reject({
              msg: 'No user role passed from server !'
            });
          }
        })
        .error(function (response, status, headers, config) {
          deferred.reject(response);
        });
    }

    return deferred.promise;
  }


  function _getPermit (mobidulCode) {
    var deferred = $q.defer();

    // to make sure the permit was initialized
    _getRoleForMobidul(mobidulCode)
      .then(function (role) {
        deferred.resolve(service.Permit);
      }, function (error) {
        deferred.reject(error);
      });

    return deferred.promise;
  }


  /// services

  function login (credentials) {
    var postData = {
      user: credentials.username,
      password: <PASSWORD>
    };

    return $http.post(cordovaUrl + '/login', postData)
      .success(function (response, status, headers, config) {
        $log.debug('login response: ', response);

        if ( response === 'success' ) {
          service.Session.isLoggedIn = true;
          service.Session.username   = credentials.username;
        }
      })
      .error(function (response, status, headers, config) {
        $log.error(response);
        $log.error(status);
      });
  }


  function logout () {
    return $http.get(cordovaUrl + '/logout')
      .success(function (response, status, headers, config) {
        if ( response === 'success' ) {
          var guestName = service._guestName;
          var isGuest   = _Roles._isGuest;

          service.Session.isLoggedIn = false;
          service.Session.username   = guestName;
          service.Session.role       = isGuest;
          service.Session.currentMobidulCode = '';

          service.Permit = angular.copy( _Permits );
        }
      })
      .error(function (response, status, headers, config) {
        $log.error(response);
        $log.error(status);
      })
      .then(function (response) {
        // $rootScope.$emit('Header::refresh');
        HeaderService.refresh();

        $rootScope.$emit('UserService::sessionUpdated');

        return response;
      });
  }


  function isLoggedIn () {
    return $http.get(cordovaUrl + '/IsLoggedIn')
      .success(function (data, status, headers, config) {
        if ( data === 'true' ) {
          service.Session.isLoggedIn = true;
        }
      })
      .error(function (data, status, headers, config) {
        $log.error(data);
        $log.error(status);
      });
  }


  function register (credentials) {
    var postData = {
      user     : credentials.username,
      email    : credentials.email,
      password : <PASSWORD>
    };


    return $http.post(cordovaUrl + '/register', postData)
      .success(function (response, status, headers, config) {
        // $log.debug(response);

        service.Session.username = credentials.username;
      })
      .error(function (response, status, headers, config) {
        $log.error(response);
        $log.error(status);
      });
  }


  function restoreUser () {
    return $http.get(cordovaUrl + '/currentUser')
      .success(function (response, status, headers, config) {
        $log.debug('> Restored current user successfully !');
        $log.debug(response);
        // $log.debug(response.guest);

        var isGuest = response.guest === true || response.guest == 1;
        var isGuestNot = ! isGuest;
        // $log.debug('isGuestNot: ' + isGuestNot);

        var email    = isGuestNot ? response.email    : null;
        var guestId  = isGuest    ? response.username : null;
        var username = isGuestNot ? response.username : service._guestName;

        var userData = {
          isLoggedIn     : isGuestNot,
          id             : response.id,
          username       : username,
          email          : email,
          created_at     : response.created_at,
          remember_token : response.remember_token,
        };

        if (isGuest) {
          userData.guestId = response.username;
        }

        service.Session = userData;
      })
      .error(function (response, status, headers, config) {
        $log.error(response);
        $log.error(status);
      });
  }


  function restoreUserRole (mobidulCode) {
    var deferred = $q.defer();

    _getRoleForMobidul(mobidulCode)
      .then(function (role) {
        service.Session.role = role;
        service.Session.currentMobidulCode = mobidulCode;
        service.Permit = _checkPermits(role);

        HeaderService.refresh();
        deferred.resolve();
      },
      function (error) {
        $log.error('Error: UserService - restoreUserRole:');
        $log.error(error);

        deferred.reject(error);
      });

    return deferred.promise;
  }


  function changePassword (data) {
    var postData;

    if ( data.resetToken ) {
      postData = {
        route           : 'changePasswordNoAuth',
        resetToken      : data.resetToken,
        newPassword     : <PASSWORD>,
        confirmPassword : <PASSWORD>
      };
    } else {
      postData = {
        route       : 'changePassword',
{'fraction_non_alphanumeric': 0.12225504045203545, 'fraction_numerical': 0.0007063053807628098, 'mean_word_length': 2.056918547595682, 'pattern_counts': {'":': 0, '<': 10, '<?xml version=': 0, '>': 12, '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': '3940722', 'n_tokens_mistral': 4659, 'n_tokens_neox': 4476, 'n_words': 934}