public UserProfile providerSignIn(String username, String providerId, String providerUserId) {
    UserProfile existingUser =
        context.getUserProfileDao().loadUserByProviderUserId(providerId, providerUserId);
    if (existingUser != null) {
      return existingUser;
    } else {
      String email = null;

      if (username.matches("^\\S+@\\S+\\.\\S+$")) {
        email = username;
        username = username.substring(0, username.indexOf('@'));
      }

      String initialUsername = username;

      for (int i = 1; !usernameIsAvailable(initialUsername); i++) {
        initialUsername = String.format("%s_%d", username, i);
      }

      UserProfile user =
          context.getUserProfileDao().createUser(initialUsername, null, email, email != null);
      newUser(user.getUsername());
      return user;
    }
  }
  private boolean initSession(
      UserProfile user,
      String password,
      boolean requirePassword,
      HttpServletRequest request,
      HttpServletResponse response) {

    Authentication auth;

    try {
      if (requirePassword) {
        UsernamePasswordAuthenticationToken token =
            new UsernamePasswordAuthenticationToken(user.getUsername(), password);
        auth = authenticationManager.authenticate(token);
      } else {
        auth = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
      }

      context.getLogManager().loggedIn(user);
      SecurityContextHolder.getContext().setAuthentication(auth);
      securityContextRepository.saveContext(SecurityContextHolder.getContext(), request, response);
      rememberMeServices.loginSuccess(request, response, auth);
      request
          .getSession()
          .setAttribute("nquire-it-token", new BigInteger(260, random).toString(32));
    } catch (Exception ex) {
      auth = null;
    }

    return auth != null
        && auth.getPrincipal() != null
        && auth.getPrincipal() instanceof UserProfile;
  }
 public boolean currentUserIsNew() {
   UserProfile user = currentUser();
   if (user != null && newUsers.contains(user.getUsername())) {
     newUsers.remove(user.getUsername());
     return true;
   } else {
     return false;
   }
 }
  private void checkUser(int index, String username, String providerId, String providerUserId) {
    List<UserProfile> users =
        em.createQuery("SELECT u FROM UserProfile u", UserProfile.class).getResultList();
    assertTrue(users.size() > index);

    UserProfile user = users.get(index);
    assertEquals(user.getUsername(), username);

    if (providerId != null) {
      assertEquals(1, user.getAuthorities().size());
      assertEquals(
          String.format("%s:%s", providerId, providerUserId),
          user.getAuthorities().get(0).getAuthority());
    } else {
      assertEquals(0, user.getAuthorities().size());
    }
  }
  public PublicProfileResponse getPublicProfile(Long userId) {
    PublicProfileResponse response = new PublicProfileResponse();
    UserProfile profile = context.getUserProfileDao().loadUserById(userId);

    if (profile != null) {
      response.setId(profile.getId());
      response.setUsername(profile.getUsername());
      response.setImage(profile.getImage());

      if (profile.getVisibility().get("metadata") && profile.getMetadata() != null) {
        response.getMetadata().putAll(profile.getMetadata());
      }

      boolean joined = profile.getVisibility().get("projectsJoined");
      boolean created = profile.getVisibility().get("projectsCreated");
      response.setProjects(context.getProjectDao().getMyProjects(profile, joined, created));
    }

    return response;
  }
  public Boolean testLogin(UserProfile user, HttpSession session, String sessionToken) {

    Authentication auth;

    try {
      auth = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
      SecurityContextHolder.getContext().setAuthentication(auth);
      session.setAttribute("nquire-it-token", sessionToken);
    } catch (Exception ex) {
      auth = null;
    }

    return auth != null
        && auth.getPrincipal() != null
        && auth.getPrincipal() instanceof UserProfile;
  }
  public StatusResponse remindUser(
      RegisterRequest data,
      HashMap<String, Connection<?>> connections,
      HttpServletRequest request,
      HttpServletResponse response) {
    StatusResponse result = new StatusResponse();
    String string = new String();

    try {
      UserProfile userProfile = loadUserByUsernameOrEmail(data.getEmail());

      System.out.println("ProxyHost=" + this.proxyHost);
      System.out.println("ProxyPort=" + this.proxyPort);
      System.out.println("recaptchaSecretKey=" + this.recaptchaSecretKey);
      // Newer versions of Java need a "http." prefix on the system properties
      System.setProperty("proxyHost", this.proxyHost);
      System.setProperty("proxyPort", this.proxyPort);
      System.setProperty("http.proxyHost", this.proxyHost);
      System.setProperty("http.proxyPort", this.proxyPort);
      URL url =
          new URL(
              "https://www.google.com/recaptcha/api/siteverify?secret="
                  + this.recaptchaSecretKey
                  + "&response="
                  + data.getRecaptcha());
      System.out.println(url.toString());
      Scanner scanner = new Scanner(url.openStream());
      while (scanner.hasNext()) {
        string += scanner.nextLine();
      }
      scanner.close();

      result.setLogged(false);
      result.setProfile(null);
      result.getResponses().put("reminder", "reminder_sent");

      if (string.indexOf("true") == -1) {
        result.setLogged(false);
        result.setProfile(null);
        result.getResponses().put("reminder", "bad_recaptcha");
        return result;
      }

      // Simple random password with 16 hex digits
      String newPassword = Long.toHexString(Double.doubleToLongBits(Math.random()));

      context.getUserProfileDao().setPassword(userProfile, newPassword);

      List<UserProfile> recipients = new ArrayList<UserProfile>();
      recipients.add(userProfile);

      Mailer mailer = new Mailer();
      mailer.sendMail(
          "Account information",
          "Hello nQuire-it user,\n\n"
              + "You (or someone claiming to be you) has requested a new password for your account.\n\n"
              + "Your username is "
              + userProfile.getUsername()
              + "\n"
              + "Your new password is "
              + newPassword
              + "\n\n"
              + "You should login and change this to something more memorable as soon as possible.\n\n"
              + "Warm regards,\nnQuire-it team",
          recipients,
          false);

      return result;
    } catch (UsernameNotFoundException e) {
      result.setLogged(false);
      result.setProfile(null);
      result.getResponses().put("reminder", "email_not_exists");
      return result;
    } catch (java.io.IOException e3) {
      System.out.println("!!!!!" + e3.toString() + "!!!!!");
      result.setLogged(false);
      result.setProfile(null);
      result.getResponses().put("reminder", "bad_recaptcha");
      return result;
    }
  }