@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());
          }
        });
  }
Esempio n. 2
0
 public static void changePasswordCurrentUser(String newPassword) {
   ODatabaseRecordTx db = DbHelper.getConnection();
   String username = db.getUser().getName();
   db = DbHelper.reconnectAsAdmin();
   db.getMetadata().getSecurity().getUser(username).setPassword(newPassword).save();
   // DbHelper.removeConnectionFromPool();
 }
  @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 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 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());
          }
        });
  }
Esempio n. 6
0
 public static void dropOrientDefault() {
   Logger.trace("Method Start");
   OGraphDatabase db = DbHelper.getConnection();
   db.getMetadata().getSecurity().dropUser("reader");
   db.getMetadata().getSecurity().dropUser("writer");
   db.getMetadata().getSecurity().dropRole("reader");
   db.getMetadata().getSecurity().dropRole("writer");
   Logger.trace("Method End");
 }
Esempio n. 7
0
 public static void changePassword(String username, String newPassword)
     throws SqlInjectionException, UserNotFoundException {
   ODatabaseRecordTx db = DbHelper.getConnection();
   db = DbHelper.reconnectAsAdmin();
   UserDao udao = UserDao.getInstance();
   ODocument user = udao.getByUserName(username);
   if (user == null) {
     if (Logger.isDebugEnabled()) Logger.debug("User " + username + " does not exist");
     throw new UserNotFoundException("User " + username + " does not exist");
   }
   db.getMetadata().getSecurity().getUser(username).setPassword(newPassword).save();
 }
Esempio n. 8
0
 public static OCommandRequest selectCommandBuilder(
     String from, boolean count, QueryParams criteria) throws SqlInjectionException {
   OGraphDatabase db = DbHelper.getConnection();
   OCommandRequest command =
       db.command(
           new OSQLSynchQuery<ODocument>(selectQueryBuilder(from, count, criteria))
               .setFetchPlan(fetchPlan.replace("?", criteria.getDepth().toString())));
   if (!command.isIdempotent()) throw new SqlInjectionException();
   Logger.debug("commandBuilder: ");
   Logger.debug("  " + criteria.toString());
   Logger.debug("  " + command.toString());
   return command;
 }
Esempio n. 9
0
 public static void createDefaultUsers() throws Exception {
   Logger.trace("Method Start");
   // the baasbox default user used to connect to the DB like anonymous user
   String username = BBConfiguration.getBaasBoxUsername();
   String password = BBConfiguration.getBaasBoxPassword();
   UserService.signUp(
       username, password, DefaultRoles.ANONYMOUS_USER.toString(), null, null, null, null);
   OGraphDatabase db = DbHelper.getConnection();
   OUser admin = db.getMetadata().getSecurity().getUser("admin");
   admin.setPassword(BBConfiguration.configuration.getString(BBConfiguration.ADMIN_PASSWORD));
   admin.save();
   Logger.trace("Method End");
 }
Esempio n. 10
0
  public static ODocument updateProfile(
      String username,
      String role,
      JsonNode nonAppUserAttributes,
      JsonNode privateAttributes,
      JsonNode friendsAttributes,
      JsonNode appUsersAttributes)
      throws Exception {
    try {
      ORole newORole = RoleDao.getRole(role);
      if (newORole == null) throw new InvalidParameterException(role + " is not a role");
      if (!RoleService.isAssignable(newORole))
        throw new RoleIsNotAssignableException("Role " + role + " is not assignable");
      ORID newRole = newORole.getDocument().getIdentity();
      UserDao udao = UserDao.getInstance();
      ODocument profile = udao.getByUserName(username);
      if (profile == null) throw new InvalidParameterException(username + " is not a user");
      profile =
          updateProfile(
              profile,
              nonAppUserAttributes,
              privateAttributes,
              friendsAttributes,
              appUsersAttributes);

      Set<OIdentifiable> roles =
          (Set<OIdentifiable>) ((ODocument) profile.field("user")).field("roles");
      // extracts the role skipping the friends ones
      String oldRole = null;
      for (OIdentifiable r : roles) {
        oldRole = ((String) ((ODocument) r.getRecord()).field("name"));
        if (!oldRole.startsWith(RoleDao.FRIENDS_OF_ROLE)) {
          break;
        }
      }
      ORole oldORole = RoleDao.getRole(oldRole);
      // TODO: update role
      OUser ouser = DbHelper.getConnection().getMetadata().getSecurity().getUser(username);
      ouser.getRoles().remove(oldORole);
      ouser.addRole(newORole);
      ouser.save();
      profile.save();
      profile.reload();

      return profile;
    } catch (Exception e) {
      throw e;
    }
  } // updateProfile with role
  @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());
          }
        });
  }
  @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());
          }
        });
  }
Esempio n. 13
0
 public static OUser getOUserByUsername(String username) {
   return DbHelper.getConnection().getMetadata().getSecurity().getUser(username);
 }
Esempio n. 14
0
  public static ODocument signUp(
      String username,
      String password,
      Date signupDate,
      String role,
      JsonNode nonAppUserAttributes,
      JsonNode privateAttributes,
      JsonNode friendsAttributes,
      JsonNode appUsersAttributes,
      boolean generated)
      throws OSerializationException, Exception {

    ODatabaseRecordTx db = DbHelper.getConnection();
    ODocument profile = null;
    UserDao dao = UserDao.getInstance();
    try {
      // because we have to create an OUser record and a User Object, we need a transaction

      DbHelper.requestTransaction();

      if (role == null) profile = dao.create(username, password);
      else profile = dao.create(username, password, role);

      ORID userRid = ((ODocument) profile.field("user")).getIdentity();
      ORole friendRole = RoleDao.createFriendRole(username);
      friendRole.getDocument().field(RoleService.FIELD_ASSIGNABLE, true);
      friendRole.getDocument().field(RoleService.FIELD_MODIFIABLE, false);
      friendRole.getDocument().field(RoleService.FIELD_INTERNAL, true);
      friendRole
          .getDocument()
          .field(RoleService.FIELD_DESCRIPTION, "These are friends of " + username);

      /*    these attributes are visible by:
       *    Anonymous users
       *    Registered user
       *    Friends
       *    User
       */

      // anonymous
      {
        ODocument attrObj = new ODocument(dao.USER_ATTRIBUTES_CLASS);
        try {
          if (nonAppUserAttributes != null) attrObj.fromJSON(nonAppUserAttributes.toString());
          else attrObj.fromJSON("{}");
        } catch (OSerializationException e) {
          throw new OSerializationException(
              dao.ATTRIBUTES_VISIBLE_BY_ANONYMOUS_USER + " is not a valid JSON object", e);
        }
        PermissionsHelper.grantRead(
            attrObj, RoleDao.getRole(DefaultRoles.REGISTERED_USER.toString()));
        PermissionsHelper.grantRead(
            attrObj, RoleDao.getRole(DefaultRoles.ANONYMOUS_USER.toString()));
        PermissionsHelper.grantRead(attrObj, friendRole);
        PermissionsHelper.changeOwner(attrObj, userRid);
        profile.field(dao.ATTRIBUTES_VISIBLE_BY_ANONYMOUS_USER, attrObj);
        attrObj.save();
      }

      /*    these attributes are visible by:
       *    User
       */
      {
        ODocument attrObj = new ODocument(dao.USER_ATTRIBUTES_CLASS);
        try {
          if (privateAttributes != null) attrObj.fromJSON(privateAttributes.toString());
          else attrObj.fromJSON("{}");
        } catch (OSerializationException e) {
          throw new OSerializationException(
              dao.ATTRIBUTES_VISIBLE_ONLY_BY_THE_USER + " is not a valid JSON object", e);
        }
        profile.field(dao.ATTRIBUTES_VISIBLE_ONLY_BY_THE_USER, attrObj);
        PermissionsHelper.changeOwner(attrObj, userRid);
        attrObj.save();
      }

      /*    these attributes are visible by:
       *    Friends
       *    User
       */
      {
        ODocument attrObj = new ODocument(dao.USER_ATTRIBUTES_CLASS);
        try {
          if (friendsAttributes != null) attrObj.fromJSON(friendsAttributes.toString());
          else attrObj.fromJSON("{}");
        } catch (OSerializationException e) {
          throw new OSerializationException(
              dao.ATTRIBUTES_VISIBLE_BY_FRIENDS_USER + " is not a valid JSON object", e);
        }
        PermissionsHelper.grantRead(attrObj, friendRole);
        PermissionsHelper.changeOwner(attrObj, userRid);
        profile.field(dao.ATTRIBUTES_VISIBLE_BY_FRIENDS_USER, attrObj);
        attrObj.save();
      }

      /*    these attributes are visible by:
       *    Registered user
       *    Friends
       *    User
       */
      {
        ODocument attrObj = new ODocument(dao.USER_ATTRIBUTES_CLASS);
        try {
          if (appUsersAttributes != null) attrObj.fromJSON(appUsersAttributes.toString());
          else attrObj.fromJSON("{}");
        } catch (OSerializationException e) {
          throw new OSerializationException(
              dao.ATTRIBUTES_VISIBLE_BY_REGISTERED_USER + " is not a valid JSON object", e);
        }
        PermissionsHelper.grantRead(
            attrObj, RoleDao.getRole(DefaultRoles.REGISTERED_USER.toString()));
        PermissionsHelper.changeOwner(attrObj, userRid);
        profile.field(dao.ATTRIBUTES_VISIBLE_BY_REGISTERED_USER, attrObj);
        attrObj.save();
      }

      ODocument attrObj = new ODocument(dao.USER_ATTRIBUTES_CLASS);
      attrObj.field(dao.USER_LOGIN_INFO, new ArrayList());
      attrObj.field(UserDao.GENERATED_USERNAME, generated);
      PermissionsHelper.grantRead(
          attrObj, RoleDao.getRole(DefaultRoles.REGISTERED_USER.toString()));
      PermissionsHelper.changeOwner(attrObj, userRid);
      profile.field(dao.ATTRIBUTES_SYSTEM, attrObj);

      PermissionsHelper.grantRead(
          profile, RoleDao.getRole(DefaultRoles.REGISTERED_USER.toString()));
      PermissionsHelper.grantRead(profile, RoleDao.getRole(DefaultRoles.ANONYMOUS_USER.toString()));
      PermissionsHelper.changeOwner(profile, userRid);

      profile.field(dao.USER_SIGNUP_DATE, signupDate == null ? new Date() : signupDate);
      profile.save();

      DbHelper.commitTransaction();
    } catch (OSerializationException e) {
      DbHelper.rollbackTransaction();
      throw e;
    } catch (Exception e) {
      DbHelper.rollbackTransaction();
      throw e;
    }
    return profile;
  } // signUp
Esempio n. 15
0
  public static void createDefaultRoles() {
    Logger.trace("Method Start");
    OGraphDatabase db = DbHelper.getConnection();
    final ORole anonymousUserRole =
        db.getMetadata()
            .getSecurity()
            .createRole(DefaultRoles.ANONYMOUS_USER.toString(), ORole.ALLOW_MODES.DENY_ALL_BUT);
    anonymousUserRole.save();
    final ORole registeredUserRole =
        db.getMetadata()
            .getSecurity()
            .createRole(DefaultRoles.REGISTERED_USER.toString(), ORole.ALLOW_MODES.DENY_ALL_BUT);
    registeredUserRole.save();

    final ORole backOfficeRole =
        db.getMetadata()
            .getSecurity()
            .createRole(DefaultRoles.BACKOFFICE_USER.toString(), ORole.ALLOW_MODES.DENY_ALL_BUT);
    backOfficeRole.save();

    registeredUserRole.addRule(ODatabaseSecurityResources.DATABASE, ORole.PERMISSION_READ);
    registeredUserRole.addRule(
        ODatabaseSecurityResources.SCHEMA,
        ORole.PERMISSION_READ + ORole.PERMISSION_CREATE + ORole.PERMISSION_UPDATE);
    registeredUserRole.addRule(
        ODatabaseSecurityResources.CLUSTER + "." + OMetadata.CLUSTER_INTERNAL_NAME,
        ORole.PERMISSION_READ);
    registeredUserRole.addRule(
        ODatabaseSecurityResources.CLUSTER + ".orole", ORole.PERMISSION_READ);
    registeredUserRole.addRule(
        ODatabaseSecurityResources.CLUSTER + ".ouser", ORole.PERMISSION_READ);
    registeredUserRole.addRule(ODatabaseSecurityResources.ALL_CLASSES, ORole.PERMISSION_ALL);
    registeredUserRole.addRule(ODatabaseSecurityResources.ALL_CLUSTERS, ORole.PERMISSION_ALL);
    registeredUserRole.addRule(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_ALL);
    registeredUserRole.addRule(ODatabaseSecurityResources.RECORD_HOOK, ORole.PERMISSION_ALL);

    backOfficeRole.addRule(ODatabaseSecurityResources.DATABASE, ORole.PERMISSION_READ);
    backOfficeRole.addRule(
        ODatabaseSecurityResources.SCHEMA,
        ORole.PERMISSION_READ + ORole.PERMISSION_CREATE + ORole.PERMISSION_UPDATE);
    backOfficeRole.addRule(
        ODatabaseSecurityResources.CLUSTER + "." + OMetadata.CLUSTER_INTERNAL_NAME,
        ORole.PERMISSION_READ);
    backOfficeRole.addRule(ODatabaseSecurityResources.CLUSTER + ".orole", ORole.PERMISSION_READ);
    backOfficeRole.addRule(ODatabaseSecurityResources.CLUSTER + ".ouser", ORole.PERMISSION_READ);
    backOfficeRole.addRule(ODatabaseSecurityResources.ALL_CLASSES, ORole.PERMISSION_ALL);
    backOfficeRole.addRule(ODatabaseSecurityResources.ALL_CLUSTERS, ORole.PERMISSION_ALL);
    backOfficeRole.addRule(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_ALL);
    backOfficeRole.addRule(ODatabaseSecurityResources.RECORD_HOOK, ORole.PERMISSION_ALL);
    backOfficeRole.addRule(
        ODatabaseSecurityResources.BYPASS_RESTRICTED,
        ORole.PERMISSION_ALL); // the backoffice users can access and manipulate all records

    anonymousUserRole.addRule(ODatabaseSecurityResources.DATABASE, ORole.PERMISSION_READ);
    anonymousUserRole.addRule(ODatabaseSecurityResources.SCHEMA, ORole.PERMISSION_READ);
    anonymousUserRole.addRule(
        ODatabaseSecurityResources.CLUSTER + "." + OMetadata.CLUSTER_INTERNAL_NAME,
        ORole.PERMISSION_READ);
    anonymousUserRole.addRule(ODatabaseSecurityResources.CLUSTER + ".orole", ORole.PERMISSION_READ);
    anonymousUserRole.addRule(ODatabaseSecurityResources.CLUSTER + ".ouser", ORole.PERMISSION_READ);
    anonymousUserRole.addRule(ODatabaseSecurityResources.ALL_CLASSES, ORole.PERMISSION_READ);
    anonymousUserRole.addRule(ODatabaseSecurityResources.ALL_CLUSTERS, 7);
    anonymousUserRole.addRule(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ);
    anonymousUserRole.addRule(ODatabaseSecurityResources.RECORD_HOOK, ORole.PERMISSION_READ);

    anonymousUserRole.save();
    registeredUserRole.save();
    Logger.trace("Method End");
  }
  @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());
          }
        });
  }
Esempio n. 17
0
 /**
  * * Returns an edge (link), belonging to the class @LinkDao.MODEL_NAME, by its id (not RID)
  *
  * @param id
  * @return
  */
 public static ORID getRidLinkByUUID(String id) {
   ODatabaseRecordTx db = DbHelper.getConnection();
   OIndex<?> index = db.getMetadata().getIndexManager().getIndex(LinkDao.MODEL_NAME + ".id");
   ORID rid = (ORID) index.get(id);
   return rid;
 }
Esempio n. 18
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()));
  }
Esempio n. 19
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. 20
0
 public void deleteLink(String linkId) {
   ORID linkRid = getRidLinkByUUID(linkId);
   DbHelper.getConnection().delete(linkRid);
 }