Example usage for io.vertx.core.json JsonObject put

List of usage examples for io.vertx.core.json JsonObject put

Introduction

In this page you can find the example usage for io.vertx.core.json JsonObject put.

Prototype

public JsonObject put(String key, Object value) 

Source Link

Document

Put an Object into the JSON object with the specified key.

Usage

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.ja va 2 s.co m
 * @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);
            }
        }
    });
}

From source file:org.entcore.auth.services.impl.AbstractSSOProvider.java

License:Open Source License

static void executeFederateQuery(String query, JsonObject params, final Assertion assertion,
        final boolean setFederated, Neo4j neo4j, final Handler<Either<String, Object>> handler) {
    query += RETURN_QUERY;//www.  java 2  s.  com
    neo4j.execute(query, params,
            Neo4jResult.validUniqueResultHandler(new Handler<Either<String, JsonObject>>() {
                @Override
                public void handle(final Either<String, JsonObject> event) {
                    if (event.isRight() && (event.right().getValue().getBoolean("blockedProfile", false)
                            || event.right().getValue().getBoolean("blockedUser", false))) {
                        handler.handle(new Either.Left<String, Object>("blocked.profile"));
                    } else if (setFederated && event.isRight()
                            && event.right().getValue().getBoolean("federated") == null
                            && event.right().getValue().getString("id") != null) {
                        String query = "MATCH (u:User {id: {id}}) SET u.federated = true ";
                        JsonObject params = new JsonObject().put("id",
                                event.right().getValue().getString("id"));
                        if (assertion != null && assertion.getIssuer() != null
                                && assertion.getIssuer().getValue() != null
                                && !assertion.getIssuer().getValue().trim().isEmpty()) {
                            query += ", u.federatedIDP = {idp} ";
                            params.put("idp", assertion.getIssuer().getValue());
                        }
                        Neo4j.getInstance().execute(query, params, new Handler<Message<JsonObject>>() {
                            @Override
                            public void handle(Message<JsonObject> event2) {
                                handler.handle(new Either.Right<String, Object>(event.right().getValue()));
                            }
                        });
                    } else if (event.isRight()) {
                        handler.handle(new Either.Right<String, Object>(event.right().getValue()));
                    } else {
                        handler.handle(new Either.Left<String, Object>(event.left().getValue()));
                    }
                }
            }));
}

From source file:org.entcore.auth.services.impl.AbstractSSOProvider.java

License:Open Source License

protected void executeMultiVectorQuery(String query, JsonObject params, final Assertion assertion,
        final Handler<Either<String, Object>> handler) {
    query += (RETURN_QUERY + ", s.name as structureName");
    Neo4j.getInstance().execute(query, params,
            Neo4jResult.validResultHandler(new Handler<Either<String, JsonArray>>() {
                @Override//from   www . j a va 2  s. com
                public void handle(final Either<String, JsonArray> event) {
                    if (event.isRight()) {
                        JsonArray ids = new fr.wseduc.webutils.collections.JsonArray();
                        final Set<String> userIds = new HashSet<>();
                        final JsonArray users = event.right().getValue();
                        for (Object o : users) {
                            if (!(o instanceof JsonObject))
                                continue;
                            JsonObject j = (JsonObject) o;
                            if (j.getBoolean("blockedProfile", false)) {
                                handler.handle(new Either.Left<String, Object>("blocked.profile"));
                                return;
                            }
                            userIds.add(j.getString("id"));
                            if (Utils.isNotEmpty(j.getString("id")) && !j.getBoolean("federated", false)) {
                                ids.add(j.getString("id"));
                            }
                        }
                        if (ids.size() > 0) {
                            String query = "MATCH (u:User) WHERE u.id IN {ids} SET u.federated = true ";
                            JsonObject params = new JsonObject().put("ids", ids);
                            if (assertion != null && assertion.getIssuer() != null
                                    && assertion.getIssuer().getValue() != null
                                    && !assertion.getIssuer().getValue().trim().isEmpty()) {
                                query += ", u.federatedIDP = {idp} ";
                                params.put("idp", assertion.getIssuer().getValue());
                            }
                            Neo4j.getInstance().execute(query, params, new Handler<Message<JsonObject>>() {
                                @Override
                                public void handle(Message<JsonObject> event2) {
                                    if (userIds.size() == 1) {
                                        handler.handle(
                                                new Either.Right<String, Object>(users.getJsonObject(0)));
                                    } else {
                                        handler.handle(new Either.Right<String, Object>(users));
                                    }
                                }
                            });
                        } else {
                            if (userIds.size() == 1) {
                                handler.handle(new Either.Right<String, Object>(users.getJsonObject(0)));
                            } else {
                                handler.handle(new Either.Right<String, Object>(users));
                            }
                        }
                    } else {
                        handler.handle(new Either.Left<String, Object>(event.left().getValue()));
                    }
                }
            }));
}

From source file:org.entcore.auth.services.impl.DefaultConfigurationService.java

License:Open Source License

@Override
public void getWelcomeMessage(String domain, String language,
        final Handler<Either<String, JsonObject>> handler) {
    final JsonObject q = new JsonObject().put("type", WELCOME_MESSAGE_TYPE);
    JsonObject keys = null;
    if (isNotEmpty(domain) && isNotEmpty(language)) {
        keys = new JsonObject();
        keys.put("_id", 0);
        keys.put(domain.replaceAll("\\.", "_") + "." + language, 1);
        keys.put(domain.replaceAll("\\.", "_") + ".enabled", 1);
    } else if (isNotEmpty(domain)) {
        keys = new JsonObject();
        keys.put("_id", 0);
        keys.put(domain.replaceAll("\\.", "_"), 1);
    }/*from  w  w  w  .j  a  va  2s. co m*/
    mongoDb.findOne(PLATEFORM_COLLECTION, q, keys, new Handler<Message<JsonObject>>() {
        @Override
        public void handle(Message<JsonObject> res) {
            if ("ok".equals(res.body().getString("status"))) {
                JsonObject r = res.body().getJsonObject("result", new JsonObject());
                JsonObject j = new JsonObject();
                for (String attr : r.fieldNames()) {
                    j.put(attr.replaceAll("_", "."), r.getValue(attr));
                }
                handler.handle(new Either.Right<String, JsonObject>(j));
            } else {
                handler.handle(new Either.Left<String, JsonObject>(res.body().getString("message", "")));
            }
        }
    });
}

From source file:org.entcore.auth.services.impl.DefaultOpendIdConnectService.java

License:Open Source License

private void generatePayload(JsonObject payload, String clientId, Handler<AsyncResult<String>> handler) {
    if (payload != null) {
        final long iat = System.currentTimeMillis() / 1000;
        payload.put("iss", getIss()).put("aud", clientId).put("iat", iat).put("exp", iat + EXPIRATION_TIME);
        try {//  ww w.  j  a  v  a 2 s .  c  o  m
            handler.handle(new DefaultAsyncResult<>(jwt.encodeAndSign(payload)));
        } catch (Exception e) {
            handler.handle(new DefaultAsyncResult<String>(e));
        }
    } else {
        handler.handle(new DefaultAsyncResult<String>(new RuntimeException("undefined.payload")));
    }
}

From source file:org.entcore.auth.services.impl.FranceConnectServiceProvider.java

License:Open Source License

private void federateWithPivot(JsonObject payload, final Handler<Either<String, Object>> handler) {
    if (!payload.containsKey("preferred_username")) {
        payload.put("preferred_username", "");
    }//from   w  w w. jav  a2  s  . c  om
    payload.put("setFederated", setFederated);
    neo4j.execute(QUERY_PIVOT_FC, payload, validUniqueResultHandler(new Handler<Either<String, JsonObject>>() {
        @Override
        public void handle(final Either<String, JsonObject> event) {
            if (event.isRight() && event.right().getValue().getBoolean("blockedProfile", false)) {
                handler.handle(new Either.Left<String, Object>("blocked.profile"));
            } else if (event.isRight() && event.right().getValue().size() > 0) {
                handler.handle(new Either.Right<String, Object>(event.right().getValue()));
            } else {
                handler.handle(new Either.Left<String, Object>(UNRECOGNIZED_USER_IDENTITY));
            }
        }
    }));
}

From source file:org.entcore.auth.services.impl.FranceConnectServiceProvider.java

License:Open Source License

@Override
public void mappingUser(String login, final String password, final JsonObject payload,
        final Handler<Either<String, Object>> handler) {
    final JsonObject params = new JsonObject().put("login", login).put("password", password);
    neo4j.execute(QUERY_MAPPING_FC, params, validUniqueResultHandler(new Handler<Either<String, JsonObject>>() {
        @Override//  ww  w .  j av  a2s. c o  m
        public void handle(Either<String, JsonObject> event) {
            if (event.isRight()) {
                JsonObject res = event.right().getValue();
                boolean success = password.equals(res.getString("activationCode"));
                if (!success && isNotEmpty(res.getString("password"))) {
                    try {
                        switch (res.getString("password").length()) {
                        case 32: // md5
                            success = res.getString("password").equals(Md5.hash(password));
                            break;
                        case 64: // sha-256
                            success = res.getString("password").equals(Sha256.hash(password));
                            break;
                        default: // BCrypt
                            success = BCrypt.checkpw(password, res.getString("password"));
                        }
                    } catch (NoSuchAlgorithmException e) {
                        handler.handle(new Either.Left<String, Object>(e.getMessage()));
                    }
                }
                if (success) {
                    params.put("setFederated", setFederated);
                    neo4j.execute(QUERY_SET_MAPPING_FC, params.put("sub", payload.getString("sub")),
                            validUniqueResultHandler(new Handler<Either<String, JsonObject>>() {
                                @Override
                                public void handle(final Either<String, JsonObject> event) {
                                    if (event.isRight()
                                            && event.right().getValue().getBoolean("blockedProfile", false)) {
                                        handler.handle(new Either.Left<String, Object>("blocked.profile"));
                                    } else if (event.isRight()) {
                                        handler.handle(
                                                new Either.Right<String, Object>(event.right().getValue()));
                                    } else {
                                        handler.handle(
                                                new Either.Left<String, Object>("invalid.openid.payload"));
                                    }
                                }
                            }));
                }
            } else {
                handler.handle(new Either.Left<String, Object>(event.left().getValue()));
            }
        }
    }));
}

From source file:org.entcore.auth.services.impl.SSOAten.java

License:Open Source License

@Override
public void execute(Assertion assertion, Handler<Either<String, Object>> handler) {
    if (!validConditions(assertion, handler))
        return;// w  w w  .  j  av  a2s . c om

    List<String> vectors = getAttributes(assertion, "FrEduVecteur");
    if (vectors == null || vectors.isEmpty()) {
        handler.handle(new Either.Left<String, Object>("invalid.vector"));
        return;
    }

    if (vectors.size() > 1) {
        JsonArray uais = new fr.wseduc.webutils.collections.JsonArray();
        JsonArray attachmentId = new fr.wseduc.webutils.collections.JsonArray();
        JsonArray firstName = new fr.wseduc.webutils.collections.JsonArray();
        JsonArray lastName = new fr.wseduc.webutils.collections.JsonArray();
        for (String vector : vectors) {
            String values[] = vector.split("\\|");
            if (values.length < 5 || values[3].trim().isEmpty() || values[4].trim().isEmpty()
                    || (!"1".equals(values[0]) && !"2".equals(values[0]))) {
                handler.handle(new Either.Left<String, Object>("invalid.vector"));
                return;
            }
            uais.add(values[4]);
            attachmentId.add(values[3]);
            firstName.add(values[2]);
            lastName.add(values[1]);
        }
        String query = "MATCH (student:User)-[:RELATED]->(u:User)-[:IN]->(:ProfileGroup)"
                + "-[:DEPENDS]->(s:Structure) "
                + "WHERE HEAD(u.profiles) = 'Relative' AND s.UAI IN {UAI} AND student.attachmentId IN {attachmentId} "
                + "AND u.firstName IN {firstName} AND u.lastName IN {lastName} AND NOT(HAS(u.mergedWith)) ";
        JsonObject params = new JsonObject().put("attachmentId", attachmentId).put("UAI", uais)
                .put("firstName", firstName).put("lastName", lastName);
        executeMultiVectorQuery(query, params, assertion, handler);
    } else {
        String values[] = vectors.get(0).split("\\|");
        if (values.length > 4 && !values[3].trim().isEmpty() && !values[4].trim().isEmpty()) { // Eleve, PersRelEleve
            JsonObject params = new JsonObject().put("attachmentId", values[3]).put("UAI", values[4]);
            String query;
            switch (values[0]) {
            case "1": // PersRelEleve 1d
            case "2": // PersRelEleve 2d
                query = "MATCH (:User {attachmentId: {attachmentId}})-[:RELATED]->(u:User)-[:IN]->(:ProfileGroup)"
                        + "-[:DEPENDS]->(s:Structure) "
                        + "WHERE HEAD(u.profiles) = 'Relative' AND s.UAI = {UAI} "
                        + "AND u.firstName = {firstName} AND u.lastName = {lastName} ";
                params.put("firstName", values[2]).put("lastName", values[1]);
                break;
            case "3": // Eleve 1d
            case "4": // Eleve 2d
                query = "MATCH (u:User {attachmentId: {attachmentId}})-[:IN]->(:ProfileGroup)-[:DEPENDS]->(s:Structure) "
                        + "WHERE HEAD(u.profiles) = 'Student' AND s.UAI = {UAI} ";
                break;
            default:
                handler.handle(new Either.Left<String, Object>("invalid.user.profile"));
                return;
            }
            executeQuery(query, params, assertion, handler);
        } else {
            handler.handle(new Either.Left<String, Object>("invalid.vector"));
        }
    }
}

From source file:org.entcore.auth.users.DefaultUserAuthAccount.java

License:Open Source License

private void activateAccount(final String loginFieldName, final String login, String activationCode,
        final String password, String email, String phone, final String theme, final HttpServerRequest request,
        final Handler<Either<String, String>> handler) {
    String query = "MATCH (n:User) " + "WHERE n." + loginFieldName
            + "={login} AND n.activationCode = {activationCode} AND n.password IS NULL "
            + "AND (NOT EXISTS(n.blocked) OR n.blocked = false) " + "OPTIONAL MATCH n-[r:DUPLICATE]-() "
            + "WHERE NOT(head(n.profiles) IN {allowActivateDuplicate}) " + "OPTIONAL MATCH (p:Profile) "
            + "WHERE HAS(n.profiles) AND p.name = head(n.profiles) "
            + "WITH n, LENGTH(FILTER(x IN COLLECT(distinct r.score) WHERE x > 3)) as duplicates, p.blocked as blockedProfile "
            + "WHERE (blockedProfile IS NULL OR blockedProfile = false) "
            + "FOREACH (duplicate IN CASE duplicates WHEN 0 THEN [1] ELSE [] END | "
            + "SET n.password = {password}, n.activationCode = null, n.email = {email}, n.mobile = {phone}) "
            + "RETURN n.password as password, n.id as id, HEAD(n.profiles) as profile, duplicates > 0 as hasDuplicate ";
    Map<String, Object> params = new HashMap<>();
    params.put("login", login);
    params.put("activationCode", activationCode);
    params.put("password", BCrypt.hashpw(password, BCrypt.gensalt()));
    params.put("email", email);
    params.put("phone", phone);
    params.put("allowActivateDuplicate", allowActivateDuplicateProfiles);
    neo.send(query, params, new Handler<Message<JsonObject>>() {

        @Override/*from  w  w w . j  a  v a  2s  . c  o  m*/
        public void handle(Message<JsonObject> res) {
            if ("ok".equals(res.body().getString("status"))
                    && res.body().getJsonObject("result").getJsonObject("0") != null) {
                if (res.body().getJsonObject("result").getJsonObject("0").getBoolean("hasDuplicate")) {
                    handler.handle(new Either.Left<String, String>("activation.error.duplicated"));
                    return;
                }
                JsonObject jo = new JsonObject()
                        .put("userId", res.body().getJsonObject("result").getJsonObject("0").getString("id"))
                        .put("profile",
                                res.body().getJsonObject("result").getJsonObject("0").getString("profile"))
                        .put("request",
                                new JsonObject().put("headers",
                                        new JsonObject().put("Accept-Language", I18n.acceptLanguage(request))
                                                .put("Host", Renders.getHost(request))));
                if (isNotEmpty(theme)) {
                    jo.put("theme", theme);
                }
                Server.getEventBus(vertx).publish("activation.ack", jo);
                handler.handle(new Either.Right<String, String>(
                        res.body().getJsonObject("result").getJsonObject("0").getString("id")));
            } else {
                String q = "MATCH (n:User) " + "WHERE n." + loginFieldName
                        + "={login} AND n.activationCode IS NULL " + "AND NOT(n.password IS NULL) "
                        + "RETURN n.password as password, n.id as id";
                Map<String, Object> p = new HashMap<>();
                p.put("login", login);
                neo.send(q, p, new Handler<Message<JsonObject>>() {
                    @Override
                    public void handle(Message<JsonObject> event) {
                        if ("ok".equals(event.body().getString("status"))
                                && event.body().getJsonObject("result").getJsonObject("0") != null
                                && BCrypt.checkpw(password, event.body().getJsonObject("result")
                                        .getJsonObject("0").getString("password", ""))) {
                            handler.handle(new Either.Right<String, String>(
                                    event.body().getJsonObject("result").getJsonObject("0").getString("id")));
                        } else {
                            handler.handle(new Either.Left<String, String>("activation.error"));
                        }
                    }
                });
            }
        }
    });
}

From source file:org.entcore.auth.users.DefaultUserAuthAccount.java

License:Open Source License

@Override
public void findByMailAndFirstNameAndStructure(final String email, String firstName, String structure,
        final Handler<Either<String, JsonArray>> handler) {
    boolean setFirstname = firstName != null && !firstName.trim().isEmpty();
    boolean setStructure = structure != null && !structure.trim().isEmpty();

    String query = "MATCH (u:User)-[:IN]->(sg:Group)-[:DEPENDS]->(s:Structure) WHERE u.email = {mail} "
            + (setFirstname ? " AND u.firstName =~ {firstName}" : "")
            + (setStructure ? " AND s.id = {structure}" : "")
            + " AND u.activationCode IS NULL RETURN DISTINCT u.login as login, u.mobile as mobile, s.name as structureName, s.id as structureId";
    JsonObject params = new JsonObject().put("mail", email);
    if (setFirstname)
        params.put("firstName", "(?i)" + firstName);
    if (setStructure)
        params.put("structure", structure);
    neo.execute(query, params, Neo4jResult.validResultHandler(handler));
}