@Override
  @Transactional
  public User createUser(User user) throws UserExistsException, DatabaseException {
    if (userRepository.findByEmailAddress(user.getEmailAddress()) != null) {
      throw new UserExistsException();
    }

    if (user.isNew()) {
      String hash = new Sha512Hash(user.getPassword(), getSalt(), HASH_ITERATIONS).toBase64();
      user.setDbPassword(hash);
      user.setActive(true);
    }

    try {
      userRepository.save(user);
    } catch (Exception e) {
      throw new DatabaseException(e);
    }

    Subject currentUserSubject = SecurityUtils.getSubject();

    if (!currentUserSubject.isAuthenticated()) {
      UsernamePasswordToken token =
          new UsernamePasswordToken(user.getEmailAddress(), user.getPassword());
      token.setRememberMe(false);

      try {
        currentUserSubject.login(token);
      } catch (AuthenticationException ae) {
        throw new LoginException();
      }
    }

    return currentUser = user;
  }
  @Override
  public User getCurrentAuditor() {
    if (currentUser != null) {
      return currentUser;
    } else if (defaultSystemUser == null) {
      defaultSystemUser = userRepository.findByFirstNameAndLastName(SYSTEM_USER, SYSTEM_USER);
    }

    return defaultSystemUser;
  }
  @Override
  @Transactional
  public User login(String username, String password, boolean rememberMe) throws LoginException {
    LOG.info(String.format("Logging User {0} in to the application.", username));

    Subject currentUserSubject = SecurityUtils.getSubject();

    if (!currentUserSubject.isAuthenticated()) {
      UsernamePasswordToken token = new UsernamePasswordToken(username, password);
      token.setRememberMe(rememberMe);

      try {
        currentUserSubject.login(token);
      } catch (AuthenticationException ae) {
        throw new LoginException();
      }
    }

    currentUser = userRepository.findByEmailAddress(username);

    return currentUser;
  }