Example usage for io.vertx.core.json JsonArray getJsonObject

List of usage examples for io.vertx.core.json JsonArray getJsonObject

Introduction

In this page you can find the example usage for io.vertx.core.json JsonArray getJsonObject.

Prototype

public JsonObject getJsonObject(int pos) 

Source Link

Document

Get the JsonObject at position pos in the array.

Usage

From source file:org.entcore.archive.services.impl.FileSystemExportService.java

License:Open Source License

private void sendExportEmail(final String exportId, final String locale, final String status,
        final String host) {
    final String userId = getUserId(exportId);
    String query = "MATCH (u:User {id : {userId}}) RETURN u.email as email ";
    JsonObject params = new JsonObject().put("userId", userId);
    Neo4j.getInstance().execute(query, params, new Handler<Message<JsonObject>>() {
        @Override/*from   w  w w.j  a  va 2  s.  co  m*/
        public void handle(Message<JsonObject> event) {
            JsonArray res = event.body().getJsonArray("result");
            if ("ok".equals(event.body().getString("status")) && res != null && res.size() == 1) {
                JsonObject e = res.getJsonObject(0);
                String email = e.getString("email");
                if (email != null && !email.trim().isEmpty()) {
                    HttpServerRequest r = new JsonHttpServerRequest(
                            new JsonObject().put("headers", new JsonObject().put("Accept-Language", locale)));
                    String subject, template;
                    JsonObject p = new JsonObject();
                    if ("ok".equals(status)) {
                        subject = "email.export.ok";
                        template = "email/export.ok.html";
                        p.put("download", host + "/archive/export/" + exportId);
                        if (log.isDebugEnabled()) {
                            log.debug(host + "/archive/export/" + exportId);
                        }
                    } else {
                        subject = "email.export.ko";
                        template = "email/export.ko.html";
                    }
                    notification.sendEmail(r, email, null, null, subject, template, p, true,
                            handlerToAsyncHandler(new Handler<Message<JsonObject>>() {
                                @Override
                                public void handle(Message<JsonObject> event) {
                                    if (event == null || !"ok".equals(event.body().getString("status"))) {
                                        log.error("Error sending export email for user " + userId);
                                    }
                                }
                            }));
                } else {
                    log.info("User " + userId + " hasn't email.");
                }
            } else if (res != null) {
                log.warn("User " + userId + " not found.");
            } else {
                log.error("Error finding user " + userId + " email : " + event.body().getString("message"));
            }
        }
    });
}

From source file:org.entcore.auth.controllers.AuthController.java

License:Open Source License

@Post("/forgot-id")
public void forgetId(final HttpServerRequest request) {
    RequestUtils.bodyToJson(request, new io.vertx.core.Handler<JsonObject>() {
        public void handle(JsonObject data) {
            final String mail = data.getString("mail");
            final String service = data.getString("service");
            final String firstName = data.getString("firstName");
            final String structure = data.getString("structureId");
            if (mail == null || mail.trim().isEmpty()) {
                badRequest(request);/*from www . ja  v  a  2  s  . co  m*/
                return;
            }
            userAuthAccount.findByMailAndFirstNameAndStructure(mail, firstName, structure,
                    new io.vertx.core.Handler<Either<String, JsonArray>>() {
                        @Override
                        public void handle(Either<String, JsonArray> event) {
                            //No user with that email, or more than one found.
                            if (event.isLeft()) {
                                badRequest(request, event.left().getValue());
                                return;
                            }
                            JsonArray results = event.right().getValue();
                            if (results.size() == 0) {
                                badRequest(request, "no.match");
                                return;
                            }
                            JsonArray structures = new fr.wseduc.webutils.collections.JsonArray();
                            if (results.size() > 1) {
                                for (Object ob : results) {
                                    JsonObject j = (JsonObject) ob;
                                    j.remove("login");
                                    j.remove("mobile");
                                    if (!structures.toString().contains(j.getString("structureId")))
                                        structures.add(j);
                                }
                                if (firstName != null && structures.size() == 1)
                                    badRequest(request, "non.unique.result");
                                else
                                    renderJson(request, new JsonObject().put("structures", structures));
                                return;
                            }
                            JsonObject match = results.getJsonObject(0);
                            final String id = match.getString("login", "");
                            final String mobile = match.getString("mobile", "");

                            //Force mail
                            if ("mail".equals(service)) {
                                userAuthAccount.sendForgottenIdMail(request, id, mail,
                                        new io.vertx.core.Handler<Either<String, JsonObject>>() {
                                            public void handle(Either<String, JsonObject> event) {
                                                if (event.isLeft()) {
                                                    badRequest(request, event.left().getValue());
                                                    return;
                                                }
                                                if (smsProvider != null && !smsProvider.isEmpty()) {
                                                    final String obfuscatedMobile = StringValidation
                                                            .obfuscateMobile(mobile);
                                                    renderJson(request,
                                                            new JsonObject().put("mobile", obfuscatedMobile));
                                                } else {
                                                    renderJson(request, new JsonObject());
                                                }
                                            }
                                        });
                            } else if ("mobile".equals(service) && !mobile.isEmpty() && smsProvider != null
                                    && !smsProvider.isEmpty()) {
                                eventStore.createAndStoreEvent(AuthEvent.SMS.name(), id);
                                userAuthAccount.sendForgottenIdSms(request, id, mobile,
                                        DefaultResponseHandler.defaultResponseHandler(request));
                            } else {
                                badRequest(request);
                            }
                        }
                    });
        }
    });
}

From source file:org.entcore.auth.oauth.OAuthDataHandler.java

License:Open Source License

@Override
public void validateClient(String clientId, String clientSecret, String grantType,
        final Handler<Boolean> handler) {

    String query = "MATCH (n:Application) " + "WHERE n.name = {clientId} " + "AND n.secret = {secret} ";
    if (!"refresh_token".equals(grantType)) {
        query += " AND n.grantType = {grantType} ";
    }/*from w  w w  .  j  a v  a  2  s  . co m*/
    query += "RETURN count(n) as nb";
    Map<String, Object> params = new HashMap<>();
    params.put("clientId", clientId);
    params.put("secret", clientSecret);
    params.put("grantType", grantType);
    neo.execute(query, params, new io.vertx.core.Handler<Message<JsonObject>>() {
        @Override
        public void handle(Message<JsonObject> res) {
            JsonArray a = res.body().getJsonArray("result");
            if ("ok".equals(res.body().getString("status")) && a != null && a.size() == 1) {
                JsonObject r = a.getJsonObject(0);
                handler.handle(r != null && r.getInteger("nb") == 1);
            } else {
                handler.handle(false);
            }
        }
    });

}

From source file:org.entcore.auth.oauth.OAuthDataHandler.java

License:Open Source License

private void checkPassword(JsonArray result, String password, String username, Handler<String> handler) {
    JsonObject r = result.getJsonObject(0);
    String dbPassword;//from   w  w w. ja v  a  2 s  .  c  o  m
    if (r != null && (dbPassword = r.getString("password")) != null
            && !getOrElse(r.getBoolean("blockedProfile"), false)) {
        boolean success = false;
        String hash = null;
        try {
            switch (dbPassword.length()) {
            case 32: // md5
                hash = Md5.hash(password);
                break;
            case 64: // sha-256
                hash = Sha256.hash(password);
                break;
            default: // BCrypt
                success = BCrypt.checkpw(password, dbPassword);
            }
            if (!success && hash != null) {
                success = !dbPassword.trim().isEmpty() && dbPassword.equalsIgnoreCase(hash);
                if (success) {
                    upgradeOldPassword(username, password);
                }
            }
        } catch (NoSuchAlgorithmException e) {
            log.error(e.getMessage(), e);
        }
        if (success) {
            handler.handle(r.getString("userId"));
        } else {
            handler.handle(null);
        }
    } else {
        handler.handle(null);
    }
}

From source file:org.entcore.auth.oauth.OAuthDataHandler.java

License:Open Source License

public void createOrUpdateAuthInfo(final String clientId, final String userId, final String scope,
        final String redirectUri, final Handler<AuthInfo> handler) {
    if (clientId != null && userId != null && !clientId.trim().isEmpty() && !userId.trim().isEmpty()) {
        if (scope != null && !scope.trim().isEmpty()) {
            String query = "MATCH (app:`Application` {name:{clientId}}) RETURN app.scope as scope";
            neo.execute(query, new JsonObject().put("clientId", clientId),
                    new io.vertx.core.Handler<Message<JsonObject>>() {
                        @Override
                        public void handle(Message<JsonObject> res) {
                            JsonArray r = res.body().getJsonArray("result");

                            if ("ok".equals(res.body().getString("status")) && r != null && r.size() == 1) {
                                JsonObject j = r.getJsonObject(0);
                                if (j != null && j
                                        .getJsonArray("scope", new fr.wseduc.webutils.collections.JsonArray())
                                        .getList().containsAll(Arrays.asList(scope.split("\\s")))) {
                                    createAuthInfo(clientId, userId, scope, redirectUri, handler);
                                } else {
                                    handler.handle(null);
                                }//from   w w  w.  ja v a2s .  c  o m
                            } else {
                                handler.handle(null);
                            }
                        }
                    });
        } else {
            createAuthInfo(clientId, userId, scope, redirectUri, handler);
        }
    } else {
        handler.handle(null);
    }
}

From source file:org.entcore.auth.oauth.OAuthDataHandler.java

License:Open Source License

@Override
public void validateClientById(String clientId, final Handler<Boolean> handler) {
    if (clientId != null && !clientId.trim().isEmpty()) {
        String query = "MATCH (n:Application) " + "WHERE n.name = {clientId} " + "RETURN count(n) as nb";
        Map<String, Object> params = new HashMap<>();
        params.put("clientId", clientId);
        neo.execute(query, params, new io.vertx.core.Handler<Message<JsonObject>>() {

            @Override/*from ww w . j  a v  a 2s.  c  om*/
            public void handle(Message<JsonObject> res) {
                JsonArray a = res.body().getJsonArray("result");
                if ("ok".equals(res.body().getString("status")) && a != null && a.size() == 1) {
                    JsonObject r = a.getJsonObject(0);
                    handler.handle(r != null && r.getInteger("nb") == 1);
                } else {
                    handler.handle(false);
                }
            }
        });
    } else {
        handler.handle(false);
    }
}

From source file:org.entcore.auth.oauth.OAuthDataHandler.java

License:Open Source License

@Override
public void validateUserById(String userId, final Handler<Boolean> handler) {
    if (userId != null && !userId.trim().isEmpty()) {
        String query = "MATCH (n:User) " + "WHERE n.id = {userId} " + "RETURN count(n) as nb";
        Map<String, Object> params = new HashMap<>();
        params.put("userId", userId);
        neo.execute(query, params, new io.vertx.core.Handler<Message<JsonObject>>() {

            @Override/*from w ww  .  ja v a2 s .c o m*/
            public void handle(Message<JsonObject> res) {
                JsonArray a = res.body().getJsonArray("result");
                if ("ok".equals(res.body().getString("status")) && a != null && a.size() == 1) {
                    JsonObject r = a.getJsonObject(0);
                    handler.handle(r != null && r.getInteger("nb") == 1);
                } else {
                    handler.handle(false);
                }
            }
        });
    } else {
        handler.handle(false);
    }
}

From source file:org.entcore.auth.security.AuthResourcesProvider.java

License:Open Source License

private void isClassTeacher(final HttpServerRequest request, UserInfos user, final Handler<Boolean> handler) {
    request.pause();// w  w w.  j a  va  2s.  co m
    if (user.getFunctions() != null && user.getFunctions().containsKey("SUPER_ADMIN")) {
        request.resume();
        handler.handle(true);
        return;
    }
    String id = request.params().get("userId");
    if (id == null || id.trim().isEmpty()) {
        handler.handle(false);
        return;
    }

    String query = "";
    if (user.getFunctions() != null && user.getFunctions().containsKey(DefaultFunctions.ADMIN_LOCAL)) {
        query = "MATCH (t:User { id : {teacherId}})-[:IN]->(fg:FunctionGroup)-[:DEPENDS]->(s:Structure)"
                + "<-[:DEPENDS]-(og:ProfileGroup)<-[:IN]-(u:User {id : {id}}) "
                + "WHERE fg.name =~ \".*AdminLocal.*\"" + "RETURN count(*) >= 1 as exists ";
    } else {
        query = "MATCH (t:User { id : {teacherId}})-[:IN]->(pg:ProfileGroup)-[:DEPENDS]->(c:Class)"
                + "<-[:DEPENDS]-(og:ProfileGroup)<-[:IN]-(u:User {id : {id}}) "
                + "RETURN count(*) >= 1 as exists ";
    }
    JsonObject params = new JsonObject().put("id", id).put("teacherId", user.getUserId());
    neo.execute(query, params, new Handler<Message<JsonObject>>() {
        @Override
        public void handle(Message<JsonObject> r) {
            JsonArray res = r.body().getJsonArray("result");
            request.resume();
            handler.handle("ok".equals(r.body().getString("status")) && res.size() == 1
                    && (res.getJsonObject(0)).getBoolean("exists", false));
        }
    });
}

From source file:org.entcore.auth.security.AuthResourcesProvider.java

License:Open Source License

private void isClassTeacherByUserLogin(final HttpServerRequest request, final UserInfos user,
        final Handler<Boolean> handler) {
    request.setExpectMultipart(true);/*  w  w w  .j a va 2  s . com*/
    request.endHandler(new Handler<Void>() {
        @Override
        public void handle(Void v) {
            if (user.getFunctions() != null && user.getFunctions().containsKey("SUPER_ADMIN")) {
                handler.handle(true);
                return;
            }
            String login = request.formAttributes().get("login");
            if (login == null || login.trim().isEmpty()) {
                handler.handle(false);
                return;
            }
            String query;
            if (user.getFunctions() != null && user.getFunctions().containsKey(DefaultFunctions.ADMIN_LOCAL)) {
                query = "MATCH (t:User { id : {teacherId}})-[:IN]->(fg:FunctionGroup)-[:DEPENDS]->"
                        + "(:Structure)<-[:HAS_ATTACHMENT*0..]-(s:Structure)"
                        + "<-[:DEPENDS]-(og:ProfileGroup)<-[:IN]-(u:User {login : {login}}) "
                        + "WHERE fg.name =~ \".*AdminLocal.*\"" + "RETURN count(*) >= 1 as exists ";
            } else {
                query = "MATCH (t:User { id : {teacherId}})-[:IN]->(pg:ProfileGroup)-[:DEPENDS]->(c:Class)"
                        + "<-[:DEPENDS]-(og:ProfileGroup)<-[:IN]-(u:User {login : {login}}) "
                        + "RETURN count(*) >= 1 as exists ";
            }
            JsonObject params = new JsonObject().put("login", login).put("teacherId", user.getUserId());
            neo.execute(query, params, new Handler<Message<JsonObject>>() {
                @Override
                public void handle(Message<JsonObject> r) {
                    JsonArray res = r.body().getJsonArray("result");
                    handler.handle("ok".equals(r.body().getString("status")) && res.size() == 1
                            && (res.getJsonObject(0)).getBoolean("exists", false));
                }
            });
        }
    });
}

From source file:org.entcore.auth.security.SamlValidator.java

License:Open Source License

/**
 * Build SAMLResponse and convert it in base64
 *
 * @param serviceProvider serviceProvider name qualifier
 * @param userId neo4j userID/* w w  w.j  a  v a2 s.  c  om*/
 * @param nameId ameId value
 * @param message message
 *
 *
 * @throws SignatureException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws UnsupportedEncodingException
 * @throws MarshallingException
 */
public void generateSAMLResponse(final String serviceProvider, final String userId, final String nameId,
        final String host, final Message<JsonObject> message) throws SignatureException,
        NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException, MarshallingException {
    logger.info("start generating SAMLResponse");
    logger.info("SP : " + serviceProvider);

    final JsonObject idp = config.getJsonObject("saml-entng-idp-nq");
    String entngIdpNameQualifierTMP = null;
    if (idp.containsKey(serviceProvider)) {
        entngIdpNameQualifierTMP = idp.getString(serviceProvider);
    } else if (idp.containsKey("default")) {
        entngIdpNameQualifierTMP = idp.getString(serviceProvider);
    }
    final String entngIdpNameQualifier = entngIdpNameQualifierTMP;
    if (entngIdpNameQualifier == null) {
        String error = "entngIdpNameQualifier can not be null. You must specify it in auth configuration (saml-entng-idp-nq properties)";
        logger.error(error);
        JsonObject jsonObject = new JsonObject().put("error", error);
        sendOK(message, jsonObject);
    }
    logger.info("entngIdpNameQualifier : " + entngIdpNameQualifier);

    // -- get spSSODescriptor from serviceProvider id --
    if (spSSODescriptor == null) {
        String error = "error SSODescriptor not found for serviceProvider : " + serviceProvider;
        logger.error(error);
        JsonObject jsonObject = new JsonObject().put("error", error);
        sendOK(message, jsonObject);
    }

    // --- TAG Issuer ---
    final Issuer idpIssuer = createIssuer(entngIdpNameQualifier);

    // --- TAG Status ---
    final Status status = createStatus();

    final AssertionConsumerService assertionConsumerService = spSSODescriptor
            .getDefaultAssertionConsumerService();
    if (assertionConsumerService == null) {
        String error = "error : AssertionConsumerService not found";
        logger.error(error);
        sendError(message, error);
    }

    // --- TAG AttributeStatement ---
    createVectors(userId, host, new Handler<Either<String, JsonArray>>() {
        @Override
        public void handle(Either<String, JsonArray> event) {
            if (event.isRight()) {
                LinkedHashMap<String, List<String>> attributes = new LinkedHashMap<String, List<String>>();

                JsonArray vectors = event.right().getValue();
                if (vectors == null || vectors.size() == 0) {
                    String error = "error building vectors for user " + userId;
                    logger.error(error);
                    sendError(message, error);
                } else {

                    for (int i = 0; i < vectors.size(); i++) {
                        List<String> vectorsValue = new ArrayList<>();
                        String vectorType = "";

                        JsonObject vectorsJsonObject = (vectors.getJsonObject(i));

                        for (Iterator<String> iter = (vectors.getJsonObject(i)).fieldNames().iterator(); iter
                                .hasNext();) {
                            vectorType = iter.next();
                            if (attributes.containsKey(vectorType)) {
                                vectorsValue = attributes.get(vectorType);
                            }
                            vectorsValue.add(((JsonObject) vectorsJsonObject).getString(vectorType));
                        }
                        attributes.put(vectorType, vectorsValue);
                    }
                }

                AttributeStatement attributeStatement = createAttributeStatement(attributes);

                // --- TAG Assertion ---
                Assertion assertion = null;
                try {
                    assertion = generateAssertion(entngIdpNameQualifier, serviceProvider, nameId,
                            assertionConsumerService.getLocation(), userId);
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                    sendError(message, e.getMessage(), e);
                }

                if (assertion == null) {
                    String error = "error building assertion";
                    logger.error(error);
                    sendError(message, error);
                }
                assertion.getAttributeStatements().add(attributeStatement);

                // -- attribute Destination (acs) --
                String destination = assertionConsumerService.getLocation();

                // --- Build response --
                Response response = createResponse(new DateTime(), idpIssuer, status, assertion, destination);

                Signature signature = null;
                try {
                    signature = createSignature();
                } catch (Throwable e) {
                    logger.error(e.getMessage(), e);
                    sendError(message, e.getMessage());
                }
                //response.setSignature(signature);
                assertion.setSignature(signature);

                ResponseMarshaller marshaller = new ResponseMarshaller();
                Element element = null;
                try {
                    element = marshaller.marshall(response);
                } catch (MarshallingException e) {
                    logger.error(e.getMessage(), e);
                    sendError(message, e.getMessage(), e);
                }

                if (signature != null) {
                    try {
                        Signer.signObject(signature);
                    } catch (org.opensaml.xml.signature.SignatureException e) {
                        logger.error(e.getMessage(), e);
                        sendError(message, e.getMessage(), e);
                    }
                }

                StringWriter rspWrt = new StringWriter();
                XMLHelper.writeNode(element, rspWrt);

                debug("response : " + rspWrt.toString());
                JsonObject jsonObject = new JsonObject();

                String base64Response = Base64.getEncoder().encodeToString(rspWrt.toString().getBytes()); //, Base64.DONT_BREAK_LINES);
                debug("base64Response : " + base64Response);
                jsonObject.put("SAMLResponse64", base64Response);

                jsonObject.put("destination", destination);

                sendOK(message, jsonObject);
            } else {
                String error = "error bulding vectors for user " + userId + " :";
                logger.error(error);
                logger.error(event.left().getValue());
                sendError(message, error);
            }
        }
    });
}