@BeforeClass
  public static void initTestser() {
    running(
        fakeApplication(),
        () -> {
          try {
            DbHelper.open("1234567890", "admin", "admin");
            ODocument user =
                UserService.signUp(TEST_USER, TEST_USER, new Date(), null, null, null, null, false);
            assertNotNull(user);
            ODocument alt =
                UserService.signUp(
                    TEST_ALT_USER, TEST_ALT_USER, new Date(), null, null, null, null, false);
            assertNotNull(alt);

            CollectionService.create(TEST_COLLECTION);
            DbHelper.close(DbHelper.getConnection());
            DbHelper.open("1234567890", TEST_USER, TEST_USER);
            sGenIds = createRandomDocuments(10);
            DbHelper.close(DbHelper.getConnection());
          } catch (Throwable e) {
            fail(ExceptionUtils.getFullStackTrace(e));
          } finally {
            DbHelper.close(DbHelper.getConnection());
          }
        });
  }
  @Test
  public void testCreateDocument() {
    running(
        fakeApplication(),
        () -> {
          try {
            DbHelper.open("1234567890", TEST_USER, TEST_USER);
            ObjectNode params = MAPPER.createObjectNode();
            ObjectNode doc = MAPPER.createObjectNode();
            doc.put("fresh", "fresh");
            params.put("collection", TEST_COLLECTION);
            params.put("data", doc);
            ObjectNode cmd = ScriptCommands.createCommand("documents", "post", params);

            JsonNode exec = CommandRegistry.execute(cmd, null);
            assertNotNull(exec);
            assertTrue(exec.isObject());
            assertNotNull(exec.get("id"));
            assertEquals(TEST_COLLECTION, exec.get("@class").asText());

          } catch (Throwable t) {
            fail(ExceptionUtils.getFullStackTrace(t));
          } finally {
            DbHelper.close(DbHelper.getConnection());
          }
        });
  }
  @Test
  public void testCommandGetFilteredCollection() {
    running(
        fakeApplication(),
        () -> {
          try {
            DbHelper.open("1234567890", TEST_USER, TEST_USER);
            ObjectNode cmd = MAPPER.createObjectNode();
            ObjectNode p = MAPPER.createObjectNode();
            ObjectNode q = MAPPER.createObjectNode();
            q.put("where", "idx < ?");
            ArrayNode params = MAPPER.createArrayNode();
            params.add("5");
            q.put("params", params);
            p.put("collection", TEST_COLLECTION);
            p.put("query", q);

            cmd.put(ScriptCommand.RESOURCE, "documents");
            cmd.put(ScriptCommand.NAME, "list");
            cmd.put(ScriptCommand.PARAMS, p);

            JsonNode node = CommandRegistry.execute(cmd, null);
            assertNotNull(node);
            assertTrue(node.isArray());
            assertEquals(5, node.size());
          } catch (Throwable t) {
            fail(ExceptionUtils.getFullStackTrace(t));
          } finally {
            DbHelper.close(DbHelper.getConnection());
          }
        });
  }
  @Test
  public void testCommandGetSingleDocument() {
    running(
        fakeApplication(),
        () -> {
          try {
            DbHelper.open("1234567890", TEST_USER, TEST_USER);
            ObjectNode cmd = MAPPER.createObjectNode();
            ObjectNode p = MAPPER.createObjectNode();
            p.put("collection", TEST_COLLECTION);
            p.put("id", sGenIds.get(0));
            cmd.put(ScriptCommand.RESOURCE, "documents");
            cmd.put(ScriptCommand.NAME, "get");
            cmd.put(ScriptCommand.PARAMS, p);

            JsonNode node = CommandRegistry.execute(cmd, null);

            assertNotNull(node);
            assertTrue(node.isObject());
            assertNotNull(node.get("generated"));
            assertNotNull(node.get("id"));
            assertEquals(node.get("id").asText(), sGenIds.get(0));
            assertEquals(node.get("@class").asText(), TEST_COLLECTION);
          } catch (Throwable t) {
            fail(ExceptionUtils.getFullStackTrace(t));
          } finally {
            DbHelper.close(DbHelper.getConnection());
          }
        });
  }
  @Test
  public void testCommandAlterDocument() {
    running(
        fakeApplication(),
        () -> {
          try {
            DbHelper.open("1234567890", TEST_USER, TEST_USER);
            ObjectNode cmd = MAPPER.createObjectNode();
            ObjectNode p = MAPPER.createObjectNode();
            p.put("id", sGenIds.get(0));
            p.put("collection", TEST_COLLECTION);

            cmd.put(ScriptCommand.RESOURCE, "documents");
            cmd.put(ScriptCommand.NAME, "get");

            cmd.put(ScriptCommand.PARAMS, p);

            JsonNode node = CommandRegistry.execute(cmd, null);
            assertNotNull(node);
            assertTrue(node.isObject());
            ObjectNode doc = node.deepCopy();
            doc.put("extra", "extra");

            ObjectNode upd = MAPPER.createObjectNode();
            upd.put(ScriptCommand.RESOURCE, "documents");
            upd.put(ScriptCommand.NAME, "put");

            ObjectNode params = MAPPER.createObjectNode();
            params.put("collection", TEST_COLLECTION);
            params.put("id", doc.get("id").asText());
            params.put("data", doc);
            upd.put(ScriptCommand.PARAMS, params);
            JsonNode res = CommandRegistry.execute(upd, null);
            assertNotNull(res);
            assertTrue(res.isObject());
            assertNotNull(res.get("extra"));
            assertEquals(res.get("id"), doc.get("id"));
            assertEquals("extra", res.get("extra").asText());
          } catch (Throwable t) {
            fail(ExceptionUtils.getFullStackTrace(t));
          } finally {
            DbHelper.close(DbHelper.getConnection());
          }
        });
  }
Exemplo n.º 6
0
  /**
   * * Login the user. parameters: username password appcode: the App Code (API KEY) login_data:
   * json serialized string containing info related to the device used by the user. In particular,
   * for push notification, must by supplied: deviceId os: (android|ios)
   *
   * @return
   * @throws SqlInjectionException
   */
  @With({NoUserCredentialWrapFilter.class})
  @BodyParser.Of(BodyParser.FormUrlEncoded.class)
  public static Result login() throws SqlInjectionException {
    Map<String, String[]> body = request().body().asFormUrlEncoded();
    if (body == null) return badRequest("missing data: is the body x-www-form-urlencoded?");
    String username = "";
    String password = "";
    String appcode = "";
    String loginData = null;
    if (body.get("username") == null) return badRequest("The 'username' field is missing");
    else username = body.get("username")[0];
    if (body.get("password") == null) return badRequest("The 'password' field is missing");
    else password = body.get("password")[0];
    if (body.get("appcode") == null) return badRequest("The 'appcode' field is missing");
    else appcode = body.get("appcode")[0];
    Logger.debug("Username " + username);
    Logger.debug("Password " + password);
    Logger.debug("Appcode" + appcode);
    if (username.equalsIgnoreCase(BBConfiguration.getBaasBoxAdminUsername())
        || username.equalsIgnoreCase(BBConfiguration.getBaasBoxAdminUsername()))
      return forbidden(username + " cannot login");

    if (body.get("login_data") != null) loginData = body.get("login_data")[0];
    Logger.debug("LoginData" + loginData);

    /* other useful parameter to receive and to store...*/
    // validate user credentials
    OGraphDatabase db = null;
    try {
      db = DbHelper.open(appcode, username, password);
      if (loginData != null) {
        JsonNode loginInfo = null;
        try {
          loginInfo = Json.parse(loginData);
        } catch (Exception e) {
          Logger.debug("Error parsong login_data field");
          Logger.debug(ExceptionUtils.getFullStackTrace(e));
          return badRequest("login_data field is not a valid json string");
        }
        Iterator<Entry<String, JsonNode>> it = loginInfo.getFields();
        HashMap<String, Object> data = new HashMap<String, Object>();
        while (it.hasNext()) {
          Entry<String, JsonNode> element = it.next();
          String key = element.getKey();
          Object value = element.getValue().asText();
          data.put(key, value);
        }
        UserService.registerDevice(data);
      }
    } catch (OSecurityAccessException e) {
      Logger.debug("UserLogin: "******"user " + username + " unauthorized");
    } catch (InvalidAppCodeException e) {
      Logger.debug("UserLogin: "******"user " + username + " unauthorized");
    } finally {
      if (db != null && !db.isClosed()) db.close();
    }
    ImmutableMap<SessionKeys, ? extends Object> sessionObject =
        SessionTokenProvider.getSessionTokenProvider().setSession(appcode, username, password);
    response()
        .setHeader(SessionKeys.TOKEN.toString(), (String) sessionObject.get(SessionKeys.TOKEN));
    ObjectNode result = Json.newObject();
    result.put(SessionKeys.TOKEN.toString(), (String) sessionObject.get(SessionKeys.TOKEN));
    return ok(result);
  }
Exemplo n.º 7
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()));
  }
Exemplo n.º 8
0
  // NOTE: this controller is called via a web link by a mail client to reset the user's password
  // Filters to extract username/appcode/atc.. from the headers have no sense in this case
  public static Result resetPasswordStep2(String base64) throws ResetPasswordException {
    // loads the received token and extracts data by the hashcode in the url
    String tokenReceived = "";
    String appCode = "";
    String username = "";
    String tokenId = "";
    String adminUser = "";
    String adminPassword = "";

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

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

      adminUser = BBConfiguration.configuration.getString(IBBConfigurationKeys.ADMIN_USERNAME);
      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. Please repeat the reset password procedure");
      }

      boolean isTokenValid = ResetPwdDao.getInstance().verifyTokenStep1(base64, username);
      if (!isTokenValid)
        throw new Exception(
            "Reset password procedure is expired! 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()));
    }
    String tokenStep2 = ResetPwdDao.getInstance().setTokenStep2(username, appCode);

    ST pageTemplate = new ST(PasswordRecovery.PAGE_HTML_TEMPLATE.getValueAsString(), '$', '$');
    pageTemplate.add(
        "form_template",
        "<form action='/user/password/reset/"
            + tokenStep2
            + "' 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/" + tokenStep2);
    pageTemplate.add("password", "password");
    pageTemplate.add("repeat_password", "repeat-password");
    pageTemplate.add(
        "application_name",
        com.baasbox.configuration.Application.APPLICATION_NAME.getValueAsString());
    DbHelper.getConnection().close();
    return ok(Html.apply(pageTemplate.render()));
  }
  @Test
  public void testGrantAndRevokeUpdate() {
    running(
        fakeApplication(),
        () -> {
          try {
            // initial check. user TEST_ALT_USER cannot update the doc
            try {
              DbHelper.open("1234567890", TEST_ALT_USER, TEST_ALT_USER);
              ObjectNode paramsUpdate = MAPPER.createObjectNode();
              paramsUpdate.put("collection", TEST_COLLECTION);
              paramsUpdate.put("id", sGenIds.get(0));
              paramsUpdate.put("data", MAPPER.readTree("{\"upd\":\"updValue\"}"));
              ObjectNode cmdUpdate = ScriptCommands.createCommand("documents", "put", paramsUpdate);
              JsonNode nodeUpdate = CommandRegistry.execute(cmdUpdate, null);

              DbHelper.close(DbHelper.getConnection());
              fail("The user should not update the doc, but it dit it!");
            } catch (CommandExecutionException e) {

            } catch (Exception e) {
              Logger.debug("OOOPS! something went wrong! ", e);
              fail(ExceptionUtils.getFullStackTrace(e));
              throw e;
            } finally {
              DbHelper.close(DbHelper.getConnection());
            }

            // use TEST_USER grant permission to update the doc to the user TEST_ALT_USER
            DbHelper.open("1234567890", TEST_USER, TEST_USER);
            ObjectNode params = MAPPER.createObjectNode();
            ObjectNode users = MAPPER.createObjectNode();
            ArrayNode update = MAPPER.createArrayNode();
            update.add(TEST_ALT_USER);
            users.put("update", update);
            users.put("read", update);
            params.put("collection", TEST_COLLECTION);
            params.put("id", sGenIds.get(0));
            params.put("users", users);
            ObjectNode grant = ScriptCommands.createCommand("documents", "grant", params);
            JsonNode node = CommandRegistry.execute(grant, null);
            DbHelper.close(DbHelper.getConnection());

            // now user TEST_ALT_USER can update the doc
            DbHelper.open("1234567890", TEST_ALT_USER, TEST_ALT_USER);
            ObjectNode paramsUpdate = MAPPER.createObjectNode();
            paramsUpdate.put("collection", TEST_COLLECTION);
            paramsUpdate.put("id", sGenIds.get(0));
            paramsUpdate.put(
                "data",
                MAPPER.readTree(
                    "{\"generated\":\"generated-123\",\"rand\":123,\"idx\":0,\"upd\":\"updValue\"}"));
            ObjectNode cmdUpdate = ScriptCommands.createCommand("documents", "put", paramsUpdate);
            JsonNode nodeUpdate = CommandRegistry.execute(cmdUpdate, null);
            DbHelper.close(DbHelper.getConnection());

            // now the grant is revoked
            DbHelper.open("1234567890", TEST_USER, TEST_USER);
            params = MAPPER.createObjectNode();
            users = MAPPER.createObjectNode();
            update = MAPPER.createArrayNode();
            update.add(TEST_ALT_USER);
            users.put("update", update);
            users.put("read", update);
            params.put("collection", TEST_COLLECTION);
            params.put("id", sGenIds.get(0));
            params.put("users", users);
            grant = ScriptCommands.createCommand("documents", "revoke", params);
            node = CommandRegistry.execute(grant, null);
            DbHelper.close(DbHelper.getConnection());
          } catch (Throwable tr) {
            Logger.debug(ExceptionUtils.getFullStackTrace(tr));
            fail(ExceptionUtils.getFullStackTrace(tr));
          } finally {
            DbHelper.close(DbHelper.getConnection());
          }
        });
  }
  @Test
  public void testGrantAndRevokeRead() {
    running(
        fakeApplication(),
        () -> {
          try {
            DbHelper.open("1234567890", TEST_ALT_USER, TEST_ALT_USER);
            ObjectNode coll = MAPPER.createObjectNode();
            coll.put("collection", TEST_COLLECTION);
            ObjectNode cmd = ScriptCommands.createCommand("documents", "list", coll);
            JsonNode exec = CommandRegistry.execute(cmd, null);
            assertNotNull(exec);
            assertTrue(exec.isArray());
            assertEquals(0, exec.size());
            DbHelper.close(DbHelper.getConnection());

            DbHelper.open("1234567890", TEST_USER, TEST_USER);

            ObjectNode params = MAPPER.createObjectNode();
            ObjectNode users = MAPPER.createObjectNode();
            ArrayNode read = MAPPER.createArrayNode();
            read.add(TEST_ALT_USER);
            users.put("read", read);
            params.put("collection", TEST_COLLECTION);
            params.put("id", sGenIds.get(0));
            params.put("users", users);
            ObjectNode grant = ScriptCommands.createCommand("documents", "grant", params);
            JsonNode node = CommandRegistry.execute(grant, null);
            assertNotNull(node);
            assertTrue(node.isBoolean());
            assertTrue(node.asBoolean());

            DbHelper.close(DbHelper.getConnection());

            DbHelper.open("1234567890", TEST_ALT_USER, TEST_ALT_USER);

            JsonNode execWithGrants = CommandRegistry.execute(cmd, null);
            assertNotNull(execWithGrants);
            assertTrue(execWithGrants.isArray());
            assertEquals(1, execWithGrants.size());

            DbHelper.close(DbHelper.getConnection());

            DbHelper.open("1234567890", TEST_USER, TEST_USER);
            ObjectNode revoke = ScriptCommands.createCommand("documents", "revoke", params);
            JsonNode revoked = CommandRegistry.execute(revoke, null);
            assertNotNull(revoked);
            assertTrue(revoked.isBoolean());
            assertTrue(revoked.asBoolean());
            DbHelper.close(DbHelper.getConnection());

            DbHelper.open("1234567890", TEST_ALT_USER, TEST_ALT_USER);

            JsonNode execWithoutGrants = CommandRegistry.execute(cmd, null);
            assertNotNull(execWithoutGrants);
            assertTrue(execWithoutGrants.isArray());
            assertEquals(0, execWithoutGrants.size());

            DbHelper.close(DbHelper.getConnection());

          } catch (Throwable tr) {
            fail(ExceptionUtils.getFullStackTrace(tr));
          } finally {
            DbHelper.close(DbHelper.getConnection());
          }
        });
  }
Exemplo n.º 11
0
  /**
   * * Login the user. parameters: username password appcode: the App Code (API KEY) login_data:
   * json serialized string containing info related to the device used by the user. In particular,
   * for push notification, must by supplied: deviceId os: (android|ios)
   *
   * @return
   * @throws SqlInjectionException
   * @throws IOException
   * @throws JsonProcessingException
   */
  @With({NoUserCredentialWrapFilter.class})
  public static Result login() throws SqlInjectionException, JsonProcessingException, IOException {
    String username = "";
    String password = "";
    String appcode = "";
    String loginData = null;

    RequestBody body = request().body();
    // BaasBoxLogger.debug ("Login called. The body is: {}", body);
    if (body == null)
      return badRequest(
          "missing data: is the body x-www-form-urlencoded or application/json? Detected: "
              + request().getHeader(CONTENT_TYPE));
    Map<String, String[]> bodyUrlEncoded = body.asFormUrlEncoded();
    if (bodyUrlEncoded != null) {
      if (bodyUrlEncoded.get("username") == null)
        return badRequest("The 'username' field is missing");
      else username = bodyUrlEncoded.get("username")[0];
      if (bodyUrlEncoded.get("password") == null)
        return badRequest("The 'password' field is missing");
      else password = bodyUrlEncoded.get("password")[0];
      if (bodyUrlEncoded.get("appcode") == null)
        return badRequest("The 'appcode' field is missing");
      else appcode = bodyUrlEncoded.get("appcode")[0];
      if (BaasBoxLogger.isDebugEnabled()) BaasBoxLogger.debug("Username " + username);
      if (BaasBoxLogger.isDebugEnabled()) BaasBoxLogger.debug("Password " + password);
      if (BaasBoxLogger.isDebugEnabled()) BaasBoxLogger.debug("Appcode " + appcode);
      if (username.equalsIgnoreCase(BBConfiguration.getBaasBoxAdminUsername())
          || username.equalsIgnoreCase(BBConfiguration.getBaasBoxUsername()))
        return forbidden(username + " cannot login");

      if (bodyUrlEncoded.get("login_data") != null) loginData = bodyUrlEncoded.get("login_data")[0];
      if (BaasBoxLogger.isDebugEnabled()) BaasBoxLogger.debug("LoginData" + loginData);
    } else {
      JsonNode bodyJson = body.asJson();
      if (bodyJson == null)
        return badRequest(
            "missing data : is the body x-www-form-urlencoded or application/json? Detected: "
                + request().getHeader(CONTENT_TYPE));
      if (bodyJson.get("username") == null) return badRequest("The 'username' field is missing");
      else username = bodyJson.get("username").asText();
      if (bodyJson.get("password") == null) return badRequest("The 'password' field is missing");
      else password = bodyJson.get("password").asText();
      if (bodyJson.get("appcode") == null) return badRequest("The 'appcode' field is missing");
      else appcode = bodyJson.get("appcode").asText();
      if (BaasBoxLogger.isDebugEnabled()) BaasBoxLogger.debug("Username " + username);
      if (BaasBoxLogger.isDebugEnabled()) BaasBoxLogger.debug("Password " + password);
      if (BaasBoxLogger.isDebugEnabled()) BaasBoxLogger.debug("Appcode " + appcode);
      if (username.equalsIgnoreCase(BBConfiguration.getBaasBoxAdminUsername())
          || username.equalsIgnoreCase(BBConfiguration.getBaasBoxUsername()))
        return forbidden(username + " cannot login");

      if (bodyJson.get("login_data") != null) loginData = bodyJson.get("login_data").asText();
      if (BaasBoxLogger.isDebugEnabled()) BaasBoxLogger.debug("LoginData" + loginData);
    }
    /* other useful parameter to receive and to store...*/
    // validate user credentials
    ODatabaseRecordTx db = null;
    String user = null;
    try {
      db = DbHelper.open(appcode, username, password);
      user = prepareResponseToJson(UserService.getCurrentUser());

      if (loginData != null) {
        JsonNode loginInfo = null;
        try {
          loginInfo = Json.parse(loginData);
        } catch (Exception e) {
          if (BaasBoxLogger.isDebugEnabled()) BaasBoxLogger.debug("Error parsong login_data field");
          if (BaasBoxLogger.isDebugEnabled())
            BaasBoxLogger.debug(ExceptionUtils.getFullStackTrace(e));
          return badRequest("login_data field is not a valid json string");
        }
        Iterator<Entry<String, JsonNode>> it = loginInfo.fields();
        HashMap<String, Object> data = new HashMap<String, Object>();
        while (it.hasNext()) {
          Entry<String, JsonNode> element = it.next();
          String key = element.getKey();
          Object value = element.getValue().asText();
          data.put(key, value);
        }
        UserService.registerDevice(data);
      }
    } catch (OSecurityAccessException e) {
      if (BaasBoxLogger.isDebugEnabled())
        BaasBoxLogger.debug("UserLogin: "******"user " + username + " unauthorized");
    } catch (InvalidAppCodeException e) {
      if (BaasBoxLogger.isDebugEnabled())
        BaasBoxLogger.debug("UserLogin: "******"user " + username + " unauthorized");
    } finally {
      if (db != null && !db.isClosed()) db.close();
    }
    ImmutableMap<SessionKeys, ? extends Object> sessionObject =
        SessionTokenProvider.getSessionTokenProvider().setSession(appcode, username, password);
    response()
        .setHeader(SessionKeys.TOKEN.toString(), (String) sessionObject.get(SessionKeys.TOKEN));

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

    return ok(jn);
  }