public OAuthUserInfo getUserInfo()

in src/main/java/com/googlesource/gerrit/plugins/oauth/CasOAuthService.java [80:155]


  public OAuthUserInfo getUserInfo(OAuthToken token) throws IOException {
    OAuthRequest request =
        new OAuthRequest(Verb.GET, String.format(PROTECTED_RESOURCE_URL, rootUrl));
    OAuth2AccessToken t = new OAuth2AccessToken(token.getToken(), token.getRaw());
    service.signRequest(t, request);

    try (Response response = service.execute(request)) {
      if (response.getCode() != HttpServletResponse.SC_OK) {
        throw new IOException(
            String.format(
                "Status %s (%s) for request %s",
                response.getCode(), response.getBody(), request.getUrl()));
      }

      if (log.isDebugEnabled()) {
        log.debug("User info response: {}", response.getBody());
      }

      JsonElement userJson = JSON.newGson().fromJson(response.getBody(), JsonElement.class);
      if (!userJson.isJsonObject()) {
        throw new IOException(String.format("Invalid JSON '%s': not a JSON Object", userJson));
      }
      JsonObject jsonObject = userJson.getAsJsonObject();

      JsonElement id = jsonObject.get("id");
      if (id == null || id.isJsonNull()) {
        throw new IOException(String.format("CAS response missing id: %s", response.getBody()));
      }

      JsonElement attrListJson = jsonObject.get("attributes");
      if (attrListJson == null) {
        throw new IOException(
            String.format("CAS response missing attributes: %s", response.getBody()));
      }

      String email = null, name = null, login = null;
      if (attrListJson.isJsonArray()) {
        // It is possible for CAS to be configured to not return any attributes (email, name,
        // login),
        // in which case,
        // CAS returns an empty JSON object "attributes":{}, rather than "null" or an empty JSON
        // array
        // "attributes": []

        JsonArray attrJson = attrListJson.getAsJsonArray();
        for (JsonElement elem : attrJson) {
          if (elem == null || !elem.isJsonObject()) {
            throw new IOException(String.format("Invalid JSON '%s': not a JSON Object", elem));
          }
          JsonObject obj = elem.getAsJsonObject();

          String property = getStringElement(obj, "email");
          if (property != null) {
            email = property;
          }
          property = getStringElement(obj, "name");
          if (property != null) {
            name = property;
          }
          property = getStringElement(obj, "login");
          if (property != null) {
            login = property;
          }
        }
      }

      return new OAuthUserInfo(
          CAS_PROVIDER_PREFIX + id.getAsString(),
          login,
          email,
          name,
          fixLegacyUserId ? id.getAsString() : null);
    } catch (ExecutionException | InterruptedException e) {
      throw new RuntimeException("Cannot retrieve user info resource", e);
    }
  }