Ejemplo n.º 1
0
 private void addDetail(String name, String param, Object value) {
   Label requestLabel = new Label(r.getParameter(param));
   requestLabel.setId(param);
   Label browserLabel = new Label("" + value);
   browserLabel.setId(name);
   l.addComponents(new Label(name), requestLabel, browserLabel);
 }
Ejemplo n.º 2
0
  @SuppressWarnings("deprecation")
  private void prepAttach() {
    when(request.getParameter("v-loc")).thenReturn(baseUri + "/#home");
    ui.getPage().init(request);
    when(session.createConnectorId(Matchers.any(ClientConnector.class)))
        .thenAnswer(new ConnectorIdAnswer());
    when(session.getLocale()).thenReturn(Locale.FRANCE);

    when(session.hasLock()).thenReturn(true);
    ui.setSession(session);
  }
Ejemplo n.º 3
0
  @Override
  protected void init(VaadinRequest request) {
    // setContent(new But-ton("Click me", e -> Notification.show("Hello
    // Spring+Vaadin user!")));

    System.out.println(request);
    String page = request.getParameter("page");
    String size = request.getParameter("size");
    Map<String, String[]> m = request.getParameterMap();
    for (Map.Entry<String, String[]> e : m.entrySet()) {
      System.out.println(e.getKey());
      for (String s : e.getValue()) {
        System.out.println(s);
      }
    }

    VerticalLayout actions = new VerticalLayout(addNewBtn, grid);
    HorizontalLayout mainLayout = new HorizontalLayout(actions, editor);

    // actions.setSpacing(true);
    mainLayout.setMargin(true);
    mainLayout.setSpacing(true);

    setContent(mainLayout);

    // setContent(grid);

    // Connect selected Customer to editor or hide if none is selected
    grid.addSelectionListener(
        e -> {
          if (e.getSelected().isEmpty()) {
            editor.setVisible(false);
          } else {
            editor.editTask((Task) e.getSelected().iterator().next());
          }
        });

    // Instantiate and edit new Customer the new button is clicked
    addNewBtn.addClickListener(e -> editor.editTask(new Task()));

    // Listen changes made by the editor, refresh data from backend
    editor.setChangeHandler(
        () -> {
          editor.setVisible(false);
          listTasks();
        });

    // Initialize listing
    listTasks();
  }
Ejemplo n.º 4
0
  /**
   * Internal initialization method, should not be overridden. This method is not declared as final
   * because that would break compatibility with e.g. CDI.
   *
   * @param request the initialization request
   * @param uiId the id of the new ui
   */
  public void doInit(VaadinRequest request, int uiId) {
    if (this.uiId != -1) {
      throw new IllegalStateException("UI id has already been defined");
    }
    this.uiId = uiId;

    // Actual theme - used for finding CustomLayout templates
    theme = request.getParameter("theme");

    getPage().init(request);

    // Call the init overridden by the application developer
    init(request);

    Navigator navigator = getNavigator();
    if (navigator != null) {
      // Kickstart navigation if a navigator was attached in init()
      navigator.navigateTo(navigator.getState());
    }
  }
  @Override
  public boolean handleRequest(
      VaadinSession session, VaadinRequest request, VaadinResponse response) throws IOException {

    if (data.isCallbackForMe(request)) {

      String verifier = request.getParameter(data.getVerifierParameterName());
      if (verifier != null) {
        // Got verifier!
        data.setVerifier(requestToken, new Verifier(verifier));
        finish(session, response);

        Token t = data.getAccessToken();

        OAuthRequest r = new OAuthRequest(Verb.GET, data.getRequestLink());
        data.signRequest(t, r);
        Response resp = r.send();

        FacebookAnswer answer = new Gson().fromJson(resp.getBody(), FacebookAnswer.class);

        String name = answer.name;
        String picUrl = answer.picture.data.url;
        String oauthId = "facebook" + answer.id;
        saveUser(oauthId, name, "", picUrl);

        VaadinSession.getCurrent().removeRequestHandler(this);
        ((VaadinServletResponse) response)
            .getHttpServletResponse()
            .sendRedirect(data.getRedirectUrl());

        return true;
      }

      // No verifier in the parameters. That's most likely because the user
      // denied the OAuth.

      // TODO: current error message reporting (below) is not very useful

      String error = null;
      for (String errorName : data.getErrorParameterNames()) {
        error = request.getParameter(errorName);
        if (error != null) {
          break;
        }
      }

      String errorMessage;
      if (error == null) {
        errorMessage = "OAuth failed.";
      } else {
        errorMessage = "OAuth denied: " + error;
      }

      data.setDenied(errorMessage);
      finish(session, response);
    } else if (request.getParameter("code") != null) {
      String code = request.getParameter("code");
      Verifier v = new Verifier(code);
      Token t = googleService.getAccessToken(null, v);

      OAuthRequest r = new OAuthRequest(Verb.GET, "https://www.googleapis.com/plus/v1/people/me");
      googleService.signRequest(t, r);
      Response resp = r.send();

      GooglePlusAnswer answer = new Gson().fromJson(resp.getBody(), GooglePlusAnswer.class);

      String name =
          (answer.displayName != null && !answer.displayName.equals(""))
              ? answer.displayName
              : answer.emails[0].value.substring(0, answer.emails[0].value.indexOf("@"));
      String picUrl = answer.image.url;
      String oauthId = "google" + answer.id;
      saveUser(oauthId, name, answer.emails[0].value, picUrl);

      VaadinSession.getCurrent().removeRequestHandler(this);
      ((VaadinServletResponse) response)
          .getHttpServletResponse()
          .sendRedirect(data.getRedirectUrl());
      return true;
    }
    return false;
  }
  @Override
  public void doRegistration(VaadinRequest request) throws UnauthorizedAccessAttemptException {
    String clientId =
        DataManagerSettings.getSingleton().getStringProperty(B2ACCESS_CLIENT_ID_PROPERTY, null);
    String clientSecret =
        DataManagerSettings.getSingleton().getStringProperty(B2ACCESS_CLIENT_SECRET_PROPERTY, null);

    UserData result = new UserData();
    if (request == null) {
      VaadinSession.getCurrent().setAttribute("registration_pending", getLoginIdentifier());
      Page.getCurrent()
          .setLocation(
              "https://unity.eudat-aai.fz-juelich.de:8443/oauth2-as/oauth2-authz?client_id="
                  + clientId
                  + "&response_type=code&scope=write&redirect_uri="
                  + UIHelper.getWebAppUrl().toString());
    } else {
      // delete auth_pending attribute as we'll finish now or never
      VaadinSession.getCurrent().setAttribute("registration_pending", null);
      // obtain remaining information and do redirect
      // do actual login
      LOGGER.debug("Obtaining OAuth2 code from URL parameter.");
      String code = request.getParameter("code");

      MultivaluedMap formData = new MultivaluedMapImpl();
      formData.putSingle("client_id", clientId);
      formData.putSingle("client_secret", clientSecret);
      formData.putSingle("grant_type", "authorization_code");
      formData.putSingle("redirect_uri", UIHelper.getWebAppUrl().toString());
      formData.putSingle("code", code);

      ClientConfig config = new DefaultClientConfig();
      IMetaDataManager mdm = MetaDataManagement.getMetaDataManagement().getMetaDataManager();
      mdm.setAuthorizationContext(AuthorizationContext.factorySystemContext());
      try {
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(null, new TrustManager[] {TRUST_MANAGER}, new SecureRandom());
        config
            .getProperties()
            .put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties(VERIFIER, ctx));
        Client client = Client.create(config);
        WebResource webResource =
            client.resource("https://unity.eudat-aai.fz-juelich.de:8443/oauth2/token");
        webResource.addFilter(new HTTPBasicAuthFilter("KITDM", "0kudH2O."));

        LOGGER.debug("Obtaining access token.");
        ClientResponse response =
            webResource
                .header("Content-Type", "application/x-www-form-urlencoded")
                .accept(MediaType.APPLICATION_JSON)
                .post(ClientResponse.class, formData);

        if (response.getStatus() == 200) {
          String responseData = response.getEntity(String.class);
          JSONObject responseObject = new JSONObject(responseData);
          String access_token = responseObject.getString("access_token");
          webResource =
              client.resource("https://unity.eudat-aai.fz-juelich.de:8443/oauth2/userinfo");

          LOGGER.debug("Accessing B2Access UserInfo at {}." + webResource.getURI());
          response =
              webResource
                  .header("Content-Type", "application/x-www-form-urlencoded")
                  .accept(MediaType.APPLICATION_JSON)
                  .header("Authorization", "Bearer " + access_token)
                  .get(ClientResponse.class);

          if (response.getStatus() == 200) {
            JSONObject userInfoResponse = new JSONObject(response.getEntity(String.class));
            try {
              String userId = userInfoResponse.getString("sub");
              List<UserData> existingUsers =
                  mdm.findResultList(
                      "Select u FROM UserData u WHERE u.distinguishedName=?1",
                      new Object[] {userId},
                      UserData.class);
              if (!existingUsers.isEmpty()) {
                // user for B2Access subject already exists...unable to continue
                throw new UnauthorizedAccessAttemptException(
                    "There is already a user registered for the obtained B2Access id '"
                        + userId
                        + "'.");
              }
              result.setDistinguishedName(userId);
            } catch (JSONException ex) {
              // failed, not enough information to proceed!
            }
          } else {
            // failed, not enough information to proceed!
          }
        } else {
          // failed, not enough information to proceed!
        }
      } catch (NoSuchAlgorithmException | KeyManagementException | JSONException ex) {
        LOGGER.error("Failed to collect information from B2Access service.", ex);
        throw new UnauthorizedAccessAttemptException(
            "Failed to collect information from B2Access service.", ex);
      } finally {
        mdm.close();
      }
      setup(AUTH_MODE.REGISTRATION, result);
    }
  }
  @Override
  public void doLogin(VaadinRequest request) throws UnauthorizedAccessAttemptException {
    String clientId =
        DataManagerSettings.getSingleton().getStringProperty(B2ACCESS_CLIENT_ID_PROPERTY, null);
    String clientSecret =
        DataManagerSettings.getSingleton().getStringProperty(B2ACCESS_CLIENT_SECRET_PROPERTY, null);

    if (request == null) {
      // set auth_pending attribute in order to be able to finish authentication later
      VaadinSession.getCurrent().setAttribute("auth_pending", getLoginIdentifier());
      Page.getCurrent()
          .setLocation(
              "https://unity.eudat-aai.fz-juelich.de:8443/oauth2-as/oauth2-authz?client_id="
                  + clientId
                  + "&response_type=code&scope=/authenticate&redirect_uri="
                  + UIHelper.getWebAppUrl().toString());
    } else {
      // delete auth_pending attribute as we'll finish now or never
      VaadinSession.getCurrent().setAttribute("auth_pending", null);
      // obtain remaining information and do redirect
      // do actual login
      LOGGER.debug("Obtaining OAuth2 code from URL parameter.");
      String code = request.getParameter("code");

      MultivaluedMap formData = new MultivaluedMapImpl();
      formData.putSingle("client_id", clientId);
      formData.putSingle("client_secret", clientSecret);
      formData.putSingle("grant_type", "authorization_code");
      formData.putSingle("redirect_uri", UIHelper.getWebAppUrl().toString());
      formData.putSingle("code", code);

      ClientConfig config = new DefaultClientConfig();
      IMetaDataManager mdm = MetaDataManagement.getMetaDataManagement().getMetaDataManager();
      mdm.setAuthorizationContext(AuthorizationContext.factorySystemContext());
      try {
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(null, new TrustManager[] {TRUST_MANAGER}, new SecureRandom());

        config
            .getProperties()
            .put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties(VERIFIER, ctx));
        Client client = Client.create(config);
        WebResource webResource =
            client.resource("https://unity.eudat-aai.fz-juelich.de:8443/oauth2/token");
        webResource.addFilter(new HTTPBasicAuthFilter("KITDM", "0kudH2O."));

        LOGGER.debug("Obtaining access token.");
        ClientResponse response =
            webResource
                .header("Content-Type", "application/x-www-form-urlencoded")
                .accept(MediaType.APPLICATION_JSON)
                .post(ClientResponse.class, formData);

        if (response.getStatus() == 200) {
          LOGGER.debug("Response status is HTTP 200. Parsing JSON response.");
          String responseData = response.getEntity(String.class);
          JSONObject responseObject = new JSONObject(responseData);
          String access_token = responseObject.getString("access_token");
          webResource =
              client.resource("https://unity.eudat-aai.fz-juelich.de:8443/oauth2/userinfo");
          LOGGER.debug("Accessing B2Access UserInfo at {}." + webResource.getURI());
          response =
              webResource
                  .header("Content-Type", "application/x-www-form-urlencoded")
                  .accept(MediaType.APPLICATION_JSON)
                  .header("Authorization", "Bearer " + access_token)
                  .get(ClientResponse.class);

          if (response.getStatus() == 200) {
            JSONObject userInfoResponse = new JSONObject(response.getEntity(String.class));
            String userId = userInfoResponse.getString("sub");
            UserData result =
                mdm.findSingleResult(
                    "Select u FROM UserData u WHERE u.distinguishedName=?1",
                    new Object[] {userId},
                    UserData.class);
            if (result != null) {
              LOGGER.debug(
                  "User with distinguished name {} found. Logging in and redirecting user.",
                  userId);
              UIHelper.login(
                  new UserId(result.getDistinguishedName()), new GroupId(Constants.USERS_GROUP_ID));
            } else {
              LOGGER.warn("No user found for ORCiD {}. Login denied.", userId);
              throw new UnauthorizedAccessAttemptException(
                  "No user found for ORCiD '" + userId + "'.");
            }
          } else {
            // failed, not enough information to proceed!
          }
        } else {
          throw new HttpException(
              "Failed to obtain access token from ORCiD service. Status is "
                  + response.getStatus()
                  + ", response data is: "
                  + response.getEntity(String.class));
        }

        // {"access_token":"84e8f8d0-1df6-43af-9456-6619ef514aed","token_type":"bearer","refresh_token":"2f5116b4-f046-4f69-99c5-097e6066a132","expires_in":631138518,"scope":"/authenticate","name":"Thomas Jejkal","orcid":"0000-0003-2804-688X"}
        // https://pub.orcid.org/v1.2/0000-0003-2804-688X/orcid-bio
      } catch (NoSuchAlgorithmException | KeyManagementException | HttpException ex) {
        LOGGER.error("Failed to access B2Access service.", ex);
        throw new UnauthorizedAccessAttemptException("Failed to login via B2Access.", ex);
      } finally {
        mdm.close();
      }

      String fromPage = (String) VaadinSession.getCurrent().getAttribute("from");
      if (fromPage != null) {
        VaadinSession.getCurrent().setAttribute("from", null);
        Page.getCurrent().setLocation(fromPage);
      } else {
        Page.getCurrent().setLocation(UIHelper.getWebAppUrl().toString());
      }
    }
  }