Esempio n. 1
0
  @With({UserCredentialWrapFilter.class, ConnectToDBFilter.class})
  @BodyParser.Of(BodyParser.Json.class)
  public static Result changePassword() {
    Logger.trace("Method Start");
    Http.RequestBody body = request().body();

    JsonNode bodyJson = body.asJson();
    Logger.trace("changePassword bodyJson: " + bodyJson);
    if (bodyJson == null)
      return badRequest(
          "The body payload cannot be empty. Hint: put in the request header Content-Type: application/json");

    // check and validate input
    if (!bodyJson.has("old")) return badRequest("The 'old' field is missing");
    if (!bodyJson.has("new")) return badRequest("The 'new' field is missing");

    String currentPassword = DbHelper.getCurrentHTTPPassword();
    String oldPassword = (String) bodyJson.findValuesAsText("old").get(0);
    String newPassword = (String) bodyJson.findValuesAsText("new").get(0);

    if (!oldPassword.equals(currentPassword)) {
      return badRequest("The old password does not match with the current one");
    }

    UserService.changePasswordCurrentUser(newPassword);
    Logger.trace("Method End");
    return ok();
  }
Esempio n. 2
0
  @With({
    AdminCredentialWrapFilter.class,
    ConnectToDBFilter.class,
  })
  @BodyParser.Of(BodyParser.Json.class)
  public static Result signUp() {
    Logger.trace("Method Start");
    Http.RequestBody body = request().body();

    JsonNode bodyJson = body.asJson();
    Logger.trace("signUp bodyJson: " + bodyJson);
    if (bodyJson == null)
      return badRequest(
          "The body payload cannot be empty. Hint: put in the request header Content-Type: application/json");
    // check and validate input
    if (!bodyJson.has("username")) return badRequest("The 'username' field is missing");
    if (!bodyJson.has("password")) return badRequest("The 'password' field is missing");

    // extract mandatory fields
    JsonNode nonAppUserAttributes = bodyJson.get(UserDao.ATTRIBUTES_VISIBLE_BY_ANONYMOUS_USER);
    JsonNode privateAttributes = bodyJson.get(UserDao.ATTRIBUTES_VISIBLE_ONLY_BY_THE_USER);
    JsonNode friendsAttributes = bodyJson.get(UserDao.ATTRIBUTES_VISIBLE_BY_FRIENDS_USER);
    JsonNode appUsersAttributes = bodyJson.get(UserDao.ATTRIBUTES_VISIBLE_BY_REGISTERED_USER);
    String username = (String) bodyJson.findValuesAsText("username").get(0);
    String password = (String) bodyJson.findValuesAsText("password").get(0);

    if (privateAttributes != null && privateAttributes.has("email")) {
      // check if email address is valid
      if (!Util.validateEmail((String) privateAttributes.findValuesAsText("email").get(0)))
        return badRequest("The email address must be valid.");
    }

    // try to signup new user
    try {
      UserService.signUp(
          username,
          password,
          nonAppUserAttributes,
          privateAttributes,
          friendsAttributes,
          appUsersAttributes);
    } catch (UserAlreadyExistsException e) {
      Logger.debug("signUp", e);
      return badRequest(username + " already exists");
    } catch (Throwable e) {
      Logger.warn("signUp", e);
      if (Play.isDev()) return internalServerError(ExceptionUtils.getFullStackTrace(e));
      else return internalServerError(e.getMessage());
    }
    Logger.trace("Method End");
    return created();
  }
 public XMLContentProcessor(Http.RequestBody body) {
   String[] parts = body.toString().split("Some\\(");
   if (parts.length > 0) {
     String[] parts2 = parts[1].split("\\)\\,");
     if (parts2.length > 0) {
       this.body = parts2[0];
     }
   }
 }
Esempio n. 4
0
 @Override
 public Map<String, String[]> getRequestParameters() {
   final Http.RequestBody body = request.body();
   final Map<String, String[]> formParameters;
   if (body != null) {
     formParameters = body.asFormUrlEncoded();
   } else {
     formParameters = new HashMap<>();
   }
   final Map<String, String[]> urlParameters = request.queryString();
   final Map<String, String[]> parameters = new HashMap<>();
   if (formParameters != null) {
     parameters.putAll(formParameters);
   }
   if (urlParameters != null) {
     parameters.putAll(urlParameters);
   }
   return parameters;
 }
Esempio n. 5
0
 private static Optional<JsonNode> getValidJson(Http.RequestBody body) {
   JsonNode json = body.asJson();
   logger.debug("received json: {}", json);
   try {
     // validates json
     Json.fromJson(json, Message.class);
   } catch (Exception e) {
     logger.warn("Invalid json ({})", e.getCause().getMessage());
     return Optional.empty();
   }
   return Optional.of(json);
 }
Esempio n. 6
0
  public F.Promise<Result> call(Http.Context ctx) throws Throwable {
    try {
      return delegate.call(ctx);
    } catch (Exception e) {
      e.printStackTrace();
      StringBuilder sb = new StringBuilder();

      sb.append("Error for request at " + ctx.request().uri() + "\n");
      sb.append("Headers: \n");
      Map<String, String[]> headers = ctx.request().headers();
      for (String key : headers.keySet()) {
        sb.append("  " + key + " --> ");
        for (String val : headers.get(key)) {
          sb.append(val + "|||");
        }
        sb.append("\n");
      }

      sb.append("Cookies: \n");
      for (Http.Cookie cookie : ctx.request().cookies()) {
        sb.append("  " + cookie.name() + " --> " + cookie.value() + "\n");
      }

      Http.RequestBody body = ctx.request().body();
      Map<String, String[]> body_vals = body.asFormUrlEncoded();
      if (body_vals != null) {
        sb.append("Body (as form URL encoded): \n");
        for (String key : body_vals.keySet()) {
          sb.append("  " + key + " --> ");
          for (String val : body_vals.get(key)) {
            sb.append(val + "|||");
          }
          sb.append("\n");
        }
      }

      Logger.error(sb.toString());
      throw e;
    }
  }
Esempio n. 7
0
  @With({UserCredentialWrapFilter.class, ConnectToDBFilter.class})
  @BodyParser.Of(BodyParser.Json.class)
  public static Result changeUserName() throws UserNotFoundException {
    Http.RequestBody body = request().body();

    JsonNode bodyJson = body.asJson();
    if (BaasBoxLogger.isTraceEnabled()) BaasBoxLogger.trace("updateuserName bodyJson: " + bodyJson);
    if (bodyJson == null)
      return badRequest(
          "The body payload cannot be empty. Hint: put in the request header Content-Type: application/json");
    if (bodyJson.get("username") == null || !bodyJson.get("username").isTextual())
      return badRequest("'username' field must be a String");
    String newUsername = bodyJson.get("username").asText();
    try {
      UserService.changeUsername(DbHelper.getCurrentHTTPUsername(), newUsername);
    } catch (OpenTransactionException e) {
      return internalServerError(ExceptionUtils.getMessage(e));
    } catch (SqlInjectionException e) {
      return badRequest("Username not valid");
    }
    return ok();
  }
Esempio n. 8
0
  @With({UserCredentialWrapFilter.class, ConnectToDBFilter.class})
  @BodyParser.Of(BodyParser.Json.class)
  public static Result updateProfile() {
    Logger.trace("Method Start");
    Http.RequestBody body = request().body();

    JsonNode bodyJson = body.asJson();
    Logger.trace("updateProfile bodyJson: " + bodyJson);
    if (bodyJson == null)
      return badRequest(
          "The body payload cannot be empty. Hint: put in the request header Content-Type: application/json");

    // extract the profile	 fields
    JsonNode nonAppUserAttributes = bodyJson.get(UserDao.ATTRIBUTES_VISIBLE_BY_ANONYMOUS_USER);
    JsonNode privateAttributes = bodyJson.get(UserDao.ATTRIBUTES_VISIBLE_ONLY_BY_THE_USER);
    JsonNode friendsAttributes = bodyJson.get(UserDao.ATTRIBUTES_VISIBLE_BY_FRIENDS_USER);
    JsonNode appUsersAttributes = bodyJson.get(UserDao.ATTRIBUTES_VISIBLE_BY_REGISTERED_USER);

    if (privateAttributes.has("email")) {
      // check if email address is valid
      if (!Util.validateEmail((String) privateAttributes.findValuesAsText("email").get(0)))
        return badRequest("The email address must be valid.");
    }

    ODocument profile;
    try {
      profile =
          UserService.updateCurrentProfile(
              nonAppUserAttributes, privateAttributes, friendsAttributes, appUsersAttributes);
    } catch (Throwable e) {
      Logger.warn("updateProfile", e);
      if (Play.isDev()) return internalServerError(ExceptionUtils.getFullStackTrace(e));
      else return internalServerError(e.getMessage());
    }
    Logger.trace("Method End");

    return ok(prepareResponseToJson(profile));
  } // updateProfile
Esempio n. 9
0
  // NOTE: this controller is called via a web form by a browser to reset the user's password
  // Filters to extract username/appcode/atc.. from the headers have no sense in this case
  public static Result resetPasswordStep3(String base64) {
    String tokenReceived = "";
    String appCode = "";
    String username = "";
    String tokenId = "";
    Map<String, String[]> bodyForm = null;
    try {
      // loads the received token and extracts data by the hashcode in the url

      tokenReceived = new String(Base64.decodeBase64(base64.getBytes()));
      Logger.debug("resetPasswordStep3 - sRandom: " + tokenReceived);

      // token format should be APP_Code%%%%Username%%%%ResetTokenId
      String[] tokens = tokenReceived.split("%%%%");
      if (tokens.length != 3) return badRequest("The reset password code is invalid.");
      appCode = tokens[0];
      username = tokens[1];
      tokenId = tokens[2];

      String adminUser =
          BBConfiguration.configuration.getString(IBBConfigurationKeys.ADMIN_USERNAME);
      String adminPassword =
          BBConfiguration.configuration.getString(IBBConfigurationKeys.ADMIN_PASSWORD);

      try {
        DbHelper.open(appCode, adminUser, adminPassword);
      } catch (InvalidAppCodeException e1) {
        throw new Exception("The code to reset the password seems to be invalid");
      }

      if (!UserService.exists(username)) throw new Exception("User not found!");

      boolean isTokenValid = ResetPwdDao.getInstance().verifyTokenStep2(base64, username);
      if (!isTokenValid)
        throw new Exception(
            "Reset Code not found or expired! Please repeat the reset password procedure");

      Http.RequestBody body = request().body();

      bodyForm = body.asFormUrlEncoded();
      if (bodyForm == null)
        throw new Exception(
            "Error getting submitted data. Please repeat the reset password procedure");

    } catch (Exception e) {
      ST pageTemplate =
          new ST(PasswordRecovery.PAGE_HTML_FEEDBACK_TEMPLATE.getValueAsString(), '$', '$');
      pageTemplate.add("user_name", username);
      pageTemplate.add("error", e.getMessage());
      pageTemplate.add(
          "application_name",
          com.baasbox.configuration.Application.APPLICATION_NAME.getValueAsString());
      DbHelper.getConnection().close();
      return badRequest(Html.apply(pageTemplate.render()));
    }
    // check and validate input
    String errorString = "";
    if (bodyForm.get("password").length != 1) errorString = "The 'new password' field is missing";
    if (bodyForm.get("repeat-password").length != 1)
      errorString = "The 'repeat password' field is missing";

    String password = (String) bodyForm.get("password")[0];
    String repeatPassword = (String) bodyForm.get("repeat-password")[0];

    if (!password.equals(repeatPassword)) {
      errorString =
          "The new \"password\" field and the \"repeat password\" field must be the same.";
    }
    if (!errorString.isEmpty()) {
      ST pageTemplate = new ST(PasswordRecovery.PAGE_HTML_TEMPLATE.getValueAsString(), '$', '$');
      pageTemplate.add(
          "form_template",
          "<form action='/user/password/reset/"
              + base64
              + "' method='POST' id='reset_pwd_form'>"
              + "<label for='password'>New password</label>"
              + "<input type='password' id='password' name='password' />"
              + "<label for='repeat-password'>Repeat the new password</label>"
              + "<input type='password' id='repeat-password' name='repeat-password' />"
              + "<button type='submit' id='reset_pwd_submit'>Reset the password</button>"
              + "</form>");
      pageTemplate.add("user_name", username);
      pageTemplate.add("link", "/user/password/reset/" + base64);
      pageTemplate.add("password", "password");
      pageTemplate.add("repeat_password", "repeat-password");
      pageTemplate.add(
          "application_name",
          com.baasbox.configuration.Application.APPLICATION_NAME.getValueAsString());
      pageTemplate.add("error", errorString);
      DbHelper.getConnection().close();
      return badRequest(Html.apply(pageTemplate.render()));
    }
    try {
      UserService.resetUserPasswordFinalStep(username, password);
    } catch (Throwable e) {
      Logger.warn("changeUserPassword", e);
      DbHelper.getConnection().close();
      if (Play.isDev()) return internalServerError(ExceptionUtils.getFullStackTrace(e));
      else return internalServerError(e.getMessage());
    }
    Logger.trace("Method End");

    String ok_message = "Password changed";
    ST pageTemplate =
        new ST(PasswordRecovery.PAGE_HTML_FEEDBACK_TEMPLATE.getValueAsString(), '$', '$');
    pageTemplate.add("user_name", username);
    pageTemplate.add("message", ok_message);
    pageTemplate.add(
        "application_name",
        com.baasbox.configuration.Application.APPLICATION_NAME.getValueAsString());
    DbHelper.getConnection().close();
    return ok(Html.apply(pageTemplate.render()));
  }
Esempio n. 10
0
  public static Result postGenerate(String handler_json) {

    String oper = "";

    RequestBody body = request().body();
    if (body == null) {
      return ok(completeAnnotation.render("Error processing form: form appears to be empty."));
    }

    String textBody = body.asText();
    Properties p = new Properties();
    try {
      p.load(new StringReader(textBody));
    } catch (Exception e) {
      e.printStackTrace();
      return ok(completeAnnotation.render("Error processing form: form appears to be empty."));
    }

    System.out.println("Selection: " + p.getProperty("submitButton"));
    if (p.getProperty("submitButton") != null) oper = p.getProperty("submitButton");

    if (oper.equals(OPER_FINISH)) {
      return ok(completeAnnotation.render("Annotation operation finished."));
    }

    NameSpaces ns = NameSpaces.getInstance();
    String preamble = FRAG_START_PREAMBLE;
    preamble += ns.printNameSpaceList();
    preamble += "\n";

    /*
     * Insert KB
     */

    preamble += FRAG_KB_PART1;
    preamble += Play.application().configuration().getString("hadatac.console.kb");
    preamble += FRAG_KB_PART2;

    try {
      handler_json = URLDecoder.decode(handler_json, "UTF-8");
    } catch (Exception e) {
      e.printStackTrace();
    }
    System.out.println(handler_json);

    ObjectMapper mapper = new ObjectMapper();
    CSVAnnotationHandler handler = null;
    try {
      handler = mapper.readValue(handler_json, CSVAnnotationHandler.class);

      /*
       * Insert Data Set
       */

      preamble += "<" + DataFactory.getNextURI(DataFactory.DATASET_ABBREV) + ">";
      preamble += FRAG_DATASET;
      preamble += handler.getDataCollectionUri() + ">; ";

      int i = 0;
      int timeStampIndex = -1;
      ArrayList<Integer> mt = new ArrayList<Integer>();
      for (String str : handler.getFields()) {
        // System.out.println(str);
        // System.out.println("get " + i + "-characteristic: [" + p.getProperty(i +
        // "-characteristic") + "]");
        // System.out.println("get " + i + "-unit:           [" + p.getProperty(i + "-unit") + "]");
        if ((p.getProperty(i + "-characteristic") != null)
            && (!p.getProperty(i + "-characteristic").equals(""))
            && (p.getProperty(i + "-unit") != null)
            && (!p.getProperty(i + "-unit").equals(""))) {
          if (p.getProperty(i + "-unit").equals(FRAG_IN_DATE_TIME)) {
            timeStampIndex = i;
          } else {
            mt.add(i);
          }
        }
        i++;
      }

      preamble += FRAG_HAS_MEASUREMENT_TYPE;
      int aux = 0;
      for (Integer mt_count : mt) {
        preamble += FRAG_MT + aux++ + "> ";
      }
      preamble += ".\n\n";

      /*
       * Insert measurement types
       */

      aux = 0;
      for (Integer mt_count : mt) {
        preamble += FRAG_MT + aux;
        preamble += FRAG_MEASUREMENT_TYPE_PART1;
        if (timeStampIndex != -1) {
          preamble += FRAG_IN_DATE_TIME;
          preamble += FRAG_IN_DATE_TIME_SUFFIX;
        }
        preamble += FRAG_MEASUREMENT_TYPE_PART2;
        preamble += mt_count;
        preamble += FRAG_MEASUREMENT_TYPE_PART3;
        preamble += "<" + p.getProperty(mt_count + "-characteristic") + ">";
        preamble += FRAG_MEASUREMENT_TYPE_PART4;
        preamble += "<" + p.getProperty(mt_count + "-unit") + ">";
        preamble += " .\n";
      }

      if (timeStampIndex != -1) {
        preamble += "\n";
        preamble += FRAG_IN_DATE_TIME_STATEMENT + " " + timeStampIndex + "  . \n";
      }

      if (textBody == null) {
        badRequest("Expecting text/plain request body");
      }
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      return ok(completeAnnotation.render("Error processing form. Please restart form."));
    }

    preamble += FRAG_END_PREAMBLE;

    if (oper.equals(OPER_PREAMBLE)) {
      return ok(preamble).as("text/turtle");
    }

    if (oper.equals(OPER_CCSV)) {
      File newFile = new File(handler.getDatasetName());
      try {
        preamble += FileUtils.readFileToString(newFile, "UTF-8");
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return ok(completeAnnotation.render("Error reading cached CSV file. Please restart form."));
      }
      return ok(preamble).as("text/turtle");
    }

    if (oper.equals(OPER_UPLOAD)) {}

    return ok(completeAnnotation.render("Error processing form: unspecified download operation."));
  }
Esempio n. 11
0
  @With({AdminCredentialWrapFilter.class, ConnectToDBFilter.class})
  @BodyParser.Of(BodyParser.Json.class)
  public static Result signUp() throws JsonProcessingException, IOException {
    if (BaasBoxLogger.isTraceEnabled()) BaasBoxLogger.trace("Method Start");
    Http.RequestBody body = request().body();

    JsonNode bodyJson = body.asJson();
    if (BaasBoxLogger.isTraceEnabled()) BaasBoxLogger.trace("signUp bodyJson: " + bodyJson);
    if (bodyJson == null)
      return badRequest(
          "The body payload cannot be empty. Hint: put in the request header Content-Type: application/json");
    // check and validate input
    if (!bodyJson.has("username")) return badRequest("The 'username' field is missing");
    if (!bodyJson.has("password")) return badRequest("The 'password' field is missing");

    // extract mandatory fields
    JsonNode nonAppUserAttributes = bodyJson.get(UserDao.ATTRIBUTES_VISIBLE_BY_ANONYMOUS_USER);
    JsonNode privateAttributes = bodyJson.get(UserDao.ATTRIBUTES_VISIBLE_ONLY_BY_THE_USER);
    JsonNode friendsAttributes = bodyJson.get(UserDao.ATTRIBUTES_VISIBLE_BY_FRIENDS_USER);
    JsonNode appUsersAttributes = bodyJson.get(UserDao.ATTRIBUTES_VISIBLE_BY_REGISTERED_USER);
    String username = (String) bodyJson.findValuesAsText("username").get(0);
    String password = (String) bodyJson.findValuesAsText("password").get(0);
    String appcode = (String) ctx().args.get("appcode");
    if (privateAttributes != null && privateAttributes.has("email")) {
      // check if email address is valid
      if (!Util.validateEmail((String) privateAttributes.findValuesAsText("email").get(0)))
        return badRequest("The email address must be valid.");
    }
    if (StringUtils.isEmpty(password)) return status(422, "The password field cannot be empty");

    // try to signup new user
    ODocument profile = null;
    try {
      UserService.signUp(
          username,
          password,
          null,
          nonAppUserAttributes,
          privateAttributes,
          friendsAttributes,
          appUsersAttributes,
          false);
      // due to issue 412, we have to reload the profile
      profile = UserService.getUserProfilebyUsername(username);
    } catch (InvalidJsonException e) {
      if (BaasBoxLogger.isDebugEnabled()) BaasBoxLogger.debug("signUp", e);
      return badRequest("One or more profile sections is not a valid JSON object");
    } catch (UserAlreadyExistsException e) {
      if (BaasBoxLogger.isDebugEnabled()) BaasBoxLogger.debug("signUp", e);
      // Return a generic error message if the username is already in use.
      return badRequest("Error signing up");
    } catch (EmailAlreadyUsedException e) {
      // Return a generic error message if the email is already in use.
      if (BaasBoxLogger.isDebugEnabled()) BaasBoxLogger.debug("signUp", e);
      return badRequest("Error signing up");
    } catch (Throwable e) {
      BaasBoxLogger.warn("signUp", e);
      if (Play.isDev()) return internalServerError(ExceptionUtils.getFullStackTrace(e));
      else return internalServerError(ExceptionUtils.getMessage(e));
    }
    if (BaasBoxLogger.isTraceEnabled()) BaasBoxLogger.trace("Method End");
    ImmutableMap<SessionKeys, ? extends Object> sessionObject =
        SessionTokenProvider.getSessionTokenProvider().setSession(appcode, username, password);
    response()
        .setHeader(SessionKeys.TOKEN.toString(), (String) sessionObject.get(SessionKeys.TOKEN));

    String result = prepareResponseToJson(profile);
    ObjectMapper mapper = new ObjectMapper();
    result =
        result.substring(0, result.lastIndexOf("}"))
            + ",\""
            + SessionKeys.TOKEN.toString()
            + "\":\""
            + (String) sessionObject.get(SessionKeys.TOKEN)
            + "\"}";
    JsonNode jn = mapper.readTree(result);

    return created(jn);
  }