@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());
          }
        });
  }
Exemple #3
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 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());
          }
        });
  }
Exemple #5
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();
 }
  @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());
          }
        });
  }
  @Override
  public void delete(String name) throws Exception {
    if (!existsCollection(name))
      throw new InvalidCollectionException("Collection " + name + " does not exists");

    // get the helper class
    GenericDao gdao = GenericDao.getInstance();

    // begin transaction
    DbHelper.requestTransaction();

    try {
      // delete all vertices linked to objects in this class
      String deleteVertices = "delete vertex _bb_nodevertex where _node.@class=?";
      Object[] params = {name};
      gdao.executeCommand(deleteVertices, params);

      // delete vertices linked to the collection entry in the _bb_collection class
      // note: the params are equals to the previous one (just the collection name)
      String deleteVertices2 =
          "delete vertex _bb_nodevertex where _node.@class='_bb_collection' and _node.name=?";
      gdao.executeCommand(deleteVertices2, params);

      // delete this collection from the list of declared collections
      // note: the params are equals to the previous one (just the collection name)
      String deleteFromCollections = "delete from _bb_collection where name =?";
      gdao.executeCommand(deleteFromCollections, params);

      // delete all records belonging to the dropping collection....
      // it could be done dropping the class, but in this case we not should be able to perform a
      // rollback
      String deleteAllRecords = "delete from " + name;
      gdao.executeCommand(deleteAllRecords, new Object[] {});

      // commit
      DbHelper.commitTransaction();

      // drop the collection class outside collection
      String dropCollection = "drop class " + name;
      gdao.executeCommand(dropCollection, new Object[] {});

    } catch (Exception e) {
      // rollback in case of error
      DbHelper.rollbackTransaction();
      if (Logger.isDebugEnabled())
        Logger.debug("An error occured deleting the collection " + name, e);
      throw e;
    }
  } // delete
Exemple #8
0
 public static void addUserToRole(String username, String role) {
   boolean admin = true;
   if (!DbHelper.currentUsername().equals(BBConfiguration.getBaasBoxAdminUsername())) {
     DbHelper.reconnectAsAdmin();
     admin = false;
   }
   String sqlAdd = "update ouser add roles = {TO_ROLE} where name = ?";
   ORole toRole = RoleDao.getRole(role);
   ORID toRID = toRole.getDocument().getRecord().getIdentity();
   sqlAdd = sqlAdd.replace("{TO_ROLE}", toRID.toString());
   GenericDao.getInstance().executeCommand(sqlAdd, new String[] {username});
   if (!admin) {
     DbHelper.reconnectAsAuthenticatedUser();
   }
 }
Exemple #9
0
  @With({UserCredentialWrapFilter.class, ConnectToDBFilter.class})
  public static Result follow(String toFollowUsername) {

    String currentUsername = DbHelper.currentUsername();

    try {
      UserService.getOUserByUsername(currentUsername);
    } catch (Exception e) {
      return internalServerError(ExceptionUtils.getMessage(e));
    }
    try {
      ODocument followed = FriendShipService.follow(currentUsername, toFollowUsername);
      return created(prepareResponseToJson(followed));
    } catch (UserToFollowNotExistsException e) {
      return notFound(ExceptionUtils.getMessage(e));
    } catch (UserNotFoundException e) {
      return internalServerError(ExceptionUtils.getMessage(e));
    } catch (AlreadyFriendsException e) {
      return badRequest(ExceptionUtils.getMessage(e));
    } catch (SqlInjectionException e) {
      return badRequest(
          "The username "
              + toFollowUsername
              + " is not a valid username. HINT: check if it contains invalid character, the server has encountered a possible SQL Injection attack");
    } catch (IllegalArgumentException e) {
      return badRequest(ExceptionUtils.getMessage(e));
    } catch (Exception e) {
      return internalServerError(ExceptionUtils.getMessage(e));
    }
  }
Exemple #10
0
 public ODocument getLink(String id) {
   String getLinkById = QUERY_BASE + " where id = ?";
   List<ODocument> result =
       (List<ODocument>) DbHelper.genericSQLStatementExecute(getLinkById, new String[] {id});
   if (result != null && !result.isEmpty()) return result.get(0);
   return null;
 }
Exemple #11
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();
  }
 private void addPermissionsClass(ODatabaseRecordTx db) {
   Logger.info("..creating database permissions class...:");
   DbHelper.execMultiLineCommands(
       db,
       true,
       "create class _BB_Permissions;",
       "create property _BB_Permissions.tag String;",
       "create property _BB_Permissions.enabled boolean;",
       "alter property _BB_Permissions.tag mandatory=true;",
       "alter property _BB_Permissions.tag notnull=true;",
       "alter property _BB_Permissions.enabled mandatory=true;",
       "alter property _BB_Permissions.enabled notnull=true;",
       "create index _BB_Permissions.tag unique;");
   DbHelper.createDefaultPermissionTags();
   Logger.info("...done...");
 }
Exemple #13
0
 public static void removeUserFromRole(String username, String role) {
   boolean admin = false;
   if (!DbHelper.currentUsername().equals(BBConfiguration.getBaasBoxAdminUsername())) {
     DbHelper.reconnectAsAdmin();
     admin = true;
   }
   String sqlRemove =
       "update ouser remove roles = {FROM_ROLE} where roles contains {FROM_ROLE} and name = ?";
   ORole fromRole = RoleDao.getRole(role);
   ORID fromRID = fromRole.getDocument().getRecord().getIdentity();
   sqlRemove = sqlRemove.replace("{FROM_ROLE}", fromRID.toString());
   GenericDao.getInstance().executeCommand(sqlRemove, new String[] {username});
   if (admin) {
     DbHelper.reconnectAsAuthenticatedUser();
   }
 }
Exemple #14
0
 @Override
 public ODocument create() throws Throwable {
   if (Logger.isTraceEnabled()) Logger.trace("Method Start");
   DbHelper.requestTransaction();
   ODocument doc = super.create();
   if (Logger.isTraceEnabled()) Logger.trace("Method End");
   return doc;
 } // getNewModelInstance
  @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());
          }
        });
  }
Exemple #16
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");
 }
Exemple #17
0
 private void setUsernameCaseInsensitive(ODatabaseRecordTx db) {
   Logger.info("..updating ouser.name collate CI..:");
   DbHelper.execMultiLineCommands(
       db,
       Logger.isDebugEnabled(),
       "drop index ouser.name;",
       "alter property ouser.name collate ci;",
       "create index ouser.name unique;");
   Logger.info("...done...");
 }
 private void idOnEdgeClass(ODatabaseRecordTx db) {
   Logger.info("..creating id property on E class...:");
   DbHelper.execMultiLineCommands(
       db,
       true,
       "create property E.id String;",
       "alter property E.id notnull=true;",
       "create index E.id unique;");
   Logger.info("...done...");
 }
Exemple #19
0
 /**
  * * Returns the people those the given user is following
  *
  * @param username
  * @return
  */
 @With({UserCredentialWrapFilter.class, ConnectToDBFilter.class, ExtractQueryParameters.class})
 public static Result following(String username) {
   if (StringUtils.isEmpty(username)) username = DbHelper.currentUsername();
   try {
     Context ctx = Http.Context.current.get();
     QueryParams criteria = (QueryParams) ctx.args.get(IQueryParametersKeys.QUERY_PARAMETERS);
     List<ODocument> following = FriendShipService.getFollowing(username, criteria);
     return ok(prepareResponseToJson(following));
   } catch (SqlInjectionException e) {
     return internalServerError(ExceptionUtils.getFullStackTrace(e));
   }
 }
Exemple #20
0
 public ODocument createLink(String sourceId, String destId, String edgeName)
     throws DocumentNotFoundException {
   DbHelper.requestTransaction();
   OrientEdge edge = null;
   try {
     OrientVertex sourceVertex = StorageUtils.getNodeVertex(sourceId);
     OrientVertex destVertex = StorageUtils.getNodeVertex(destId);
     UUID token = UUID.randomUUID();
     edge = (OrientEdge) sourceVertex.addEdge(edgeName, destVertex);
     edge.getRecord().field(BaasBoxPrivateFields.ID.toString(), token.toString());
     edge.getRecord().field(BaasBoxPrivateFields.AUTHOR.toString(), DbHelper.currentUsername());
     edge.getRecord().field(BaasBoxPrivateFields.CREATION_DATE.toString(), new Date());
     edge.save();
     DbHelper.commitTransaction();
   } catch (DocumentNotFoundException e) {
     DbHelper.rollbackTransaction();
     throw e;
   }
   // edge.getGraph().commit();
   return edge.getRecord();
 }
Exemple #21
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");
 }
Exemple #22
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;
 }
Exemple #23
0
 public static void removeSocialLoginTokens(ODocument user, String socialNetwork)
     throws ODatabaseException {
   DbHelper.requestTransaction();
   try {
     ODocument systemProps = user.field(UserDao.ATTRIBUTES_SYSTEM);
     Map<String, ODocument> ssoTokens = systemProps.field(UserDao.SOCIAL_LOGIN_INFO);
     if (ssoTokens == null) {
       throw new ODatabaseException(socialNetwork + " is not linked with this account");
     } else {
       ssoTokens.remove(socialNetwork);
       systemProps.field(UserDao.SOCIAL_LOGIN_INFO, ssoTokens);
       user.field(UserDao.ATTRIBUTES_SYSTEM, systemProps);
       systemProps.save();
       user.save();
       if (Logger.isDebugEnabled()) Logger.debug("saved tokens for user ");
       DbHelper.commitTransaction();
     }
   } catch (Exception e) {
     e.printStackTrace();
     DbHelper.rollbackTransaction();
     throw new ODatabaseException("unable to add tokens");
   }
 }
Exemple #24
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
Exemple #25
0
  public static void addSocialLoginTokens(ODocument user, UserInfo userInfo)
      throws ODatabaseException {
    DbHelper.requestTransaction();
    try {
      ODocument systemProps = user.field(UserDao.ATTRIBUTES_SYSTEM);
      Map<String, ODocument> ssoTokens = systemProps.field(UserDao.SOCIAL_LOGIN_INFO);
      if (ssoTokens == null) {
        ssoTokens = new HashMap<String, ODocument>();
      }

      String jsonRep = userInfo.toJson();
      ssoTokens.put(userInfo.getFrom(), (ODocument) new ODocument().fromJSON(jsonRep));
      systemProps.field(UserDao.SOCIAL_LOGIN_INFO, ssoTokens);
      user.field(UserDao.ATTRIBUTES_SYSTEM, systemProps);
      systemProps.save();
      user.save();
      if (Logger.isDebugEnabled()) Logger.debug("saved tokens for user ");
      DbHelper.commitTransaction();

    } catch (Exception e) {
      DbHelper.rollbackTransaction();
      throw new ODatabaseException("unable to add tokens");
    }
  }
Exemple #26
0
  @With({UserCredentialWrapFilter.class, ConnectToDBFilter.class})
  public static Result unfollow(String toUnfollowUsername) {
    String currentUsername = DbHelper.currentUsername();

    try {
      boolean success = FriendShipService.unfollow(currentUsername, toUnfollowUsername);
      if (success) {
        return ok();
      } else {
        return notFound("User " + currentUsername + " is not a friend of " + toUnfollowUsername);
      }
    } catch (UserNotFoundException e) {
      return notFound(ExceptionUtils.getMessage(e));
    } catch (Exception e) {
      return internalServerError(ExceptionUtils.getMessage(e));
    }
  }
Exemple #27
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();
  }
 private void setGraphDefaultValues(ODatabaseRecordTx db) {
   Logger.info("..updating graph custom attributes..:");
   //		String[] script=new String[]{
   //				"alter database custom useLightweightEdges=true;",
   //				"alter database custom useClassForEdgeLabel=true",
   //				"alter database custom useClassForVertexLabel=true",
   //				"alter database custom useVertexFieldsForEdgeLabels=true"};
   //		for (String line:script){
   //			Logger.debug(line);
   //			if (!line.startsWith("--") && !line.trim().isEmpty()){ //skip comments
   //				db.command(new OCommandSQL(line.replace(';', ' '))).execute();
   //			}
   //		}
   DbHelper.execMultiLineCommands(
       db,
       true,
       "alter database custom useLightweightEdges=false;",
       "alter database custom useClassForEdgeLabel=false",
       "alter database custom useClassForVertexLabel=true",
       "alter database custom useVertexFieldsForEdgeLabels=true");
   Logger.info("...done...");
 }
Exemple #29
0
 /**
  * * Returns the followers of the current user
  *
  * @return
  */
 @With({UserCredentialWrapFilter.class, ConnectToDBFilter.class, ExtractQueryParameters.class})
 public static Result followers(boolean justCountThem, String username) {
   if (StringUtils.isEmpty(username)) username = DbHelper.currentUsername();
   Context ctx = Http.Context.current.get();
   QueryParams criteria = (QueryParams) ctx.args.get(IQueryParametersKeys.QUERY_PARAMETERS);
   List<ODocument> listOfFollowers = new ArrayList<ODocument>();
   long count = 0;
   try {
     if (justCountThem) count = FriendShipService.getCountFriendsOf(username, criteria);
     else listOfFollowers = FriendShipService.getFriendsOf(username, criteria);
   } catch (InvalidCriteriaException e) {
     return badRequest(ExceptionUtils.getMessage(e));
   } catch (SqlInjectionException e) {
     return badRequest(
         "The parameters you passed are incorrect. HINT: check if the querystring is correctly encoded");
   }
   if (justCountThem) {
     response().setContentType("application/json");
     return ok("{\"count\": " + count + " }");
   } else {
     String ret = prepareResponseToJson(listOfFollowers);
     return ok(ret);
   }
 }
Exemple #30
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);
  }