List of usage examples for io.vertx.core.json JsonArray size
public int size()
From source file:org.entcore.auth.oauth.OAuthDataHandler.java
License:Open Source License
private void getUserIdByLoginAlias(String username, String password, Handler<String> handler) { String query = "MATCH (n:User) " + "WHERE n.loginAlias={loginAlias} AND NOT(n.password IS NULL) " + "AND (NOT(HAS(n.blocked)) OR n.blocked = false) "; query += "OPTIONAL MATCH (p:Profile) " + "WHERE HAS(n.profiles) AND p.name = head(n.profiles) " + "RETURN DISTINCT n.id as userId, n.password as password, p.blocked as blockedProfile"; Map<String, Object> params = new HashMap<>(); params.put("loginAlias", username); neo.execute(query, params, res -> { JsonArray result = res.body().getJsonArray("result"); if ("ok".equals(res.body().getString("status")) && result != null && result.size() == 1) { checkPassword(result, password, username, handler); } else {/* ww w . j a v a 2 s.com*/ handler.handle(null); } }); }
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();//from ww w. j a v a2 s. c o 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 ww .java 2s . c o m*/ 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/*from www .j a va 2s . com*/ * @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.security.SamlValidator.java
License:Open Source License
/** * Build vector(s) representating user according to this profile * * @param userId userId neo4j/* w w w .ja v a 2s. c o m*/ * @param handler handler containing results */ private void createVectors(String userId, final String host, final Handler<Either<String, JsonArray>> handler) { debug("create user Vector(s)"); // browse supported type vector required by the service provider logger.info("createVectors init "); List<AttributeConsumingService> AttributesCS = spSSODescriptor.getAttributeConsumingServices(); if (AttributesCS.size() > 0) { HashMap<String, List<String>> attributes = new HashMap<String, List<String>>(); final JsonArray jsonArrayResult = new fr.wseduc.webutils.collections.JsonArray(); for (final AttributeConsumingService attributeConsumingService : AttributesCS) { for (RequestedAttribute requestedAttribute : attributeConsumingService.getRequestAttributes()) { String vectorName = requestedAttribute.getName(); if (vectorName.equals("FrEduVecteur")) { samlVectorService = new FrEduVecteurService(neo4j); samlVectorService.getVectors(userId, new Handler<Either<String, JsonArray>>() { @Override public void handle(Either<String, JsonArray> stringJsonArrayEither) { if (stringJsonArrayEither.isRight()) { JsonArray jsonArrayResultTemp = ((JsonArray) stringJsonArrayEither.right() .getValue()); for (int i = 0; i < jsonArrayResultTemp.size(); i++) { jsonArrayResult.add(jsonArrayResultTemp.getValue(i)); } // add FrEduUrlRetour vector for (RequestedAttribute requestedAttribute : attributeConsumingService .getRequestAttributes()) { String vectorName = requestedAttribute.getName(); if (vectorName.equals("FrEduUrlRetour")) { JsonObject vectorRetour = new JsonObject().put("FrEduUrlRetour", host); jsonArrayResult.add(vectorRetour); } } handler.handle(new Either.Right<String, JsonArray>(jsonArrayResult)); } } }); } else if (requestedAttribute.isRequired() && vectorName.equals("FrEduUrlRetour")) { String error = "vector " + vectorName + " not implemented yet"; logger.error(error); handler.handle(new Either.Left<String, JsonArray>(error)); } else if (vectorName.equals("mail")) { String error = "vector " + vectorName + " not implemented yet"; logger.error(error); handler.handle(new Either.Left<String, JsonArray>(error)); } else { if (requestedAttribute.isRequired()) { String error = "vector " + vectorName + " not supported for user " + userId; logger.error(error); handler.handle(new Either.Left<String, JsonArray>(error)); } else { logger.debug("vector " + vectorName + " don't have to be supported."); } } } } } else { String SPid = ((EntityDescriptor) spSSODescriptor.getParent()).getEntityID(); if (SPid.isEmpty() || SPid == null) { logger.error("Service Providor ID is null or empty"); handler.handle(new Either.Left<String, JsonArray>("Service Providor ID is null or empty")); } else { SamlServiceProvider sp = spFactory.serviceProvider(SPid); sp.generate(eb, userId, handler); } } }
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// ww w .ja va 2 s . c o m 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.DefaultOpendIdConnectService.java
License:Open Source License
@Override public void generateIdToken(String userId, final String clientId, final Handler<AsyncResult<String>> handler) { final String query = "MATCH (u:User {id: {id}}) return u.externalId as sub, u.email as email, u.displayName as name"; Neo4j.getInstance().execute(query, new JsonObject().put("id", userId), new Handler<Message<JsonObject>>() { @Override/*from w w w. ja va 2 s. co m*/ public void handle(Message<JsonObject> event) { final JsonArray res = event.body().getJsonArray("result"); if ("ok".equals(event.body().getString("status")) && res != null && res.size() == 1) { generatePayload(res.getJsonObject(0), clientId, handler); } else { handler.handle(new DefaultAsyncResult<String>(new RuntimeException("invalid.userId"))); } } }); }
From source file:org.entcore.auth.services.impl.FrEduVecteurService.java
License:Open Source License
public void getVectors(final String userId, final Handler<Either<String, JsonArray>> handler) { String queryGetUserProfile = "MATCH (u:User) WHERE u.id = {userId} RETURN u.profiles"; neo4j.execute(queryGetUserProfile, new JsonObject().put("userId", userId), Neo4jResult.validUniqueResultHandler(new Handler<Either<String, JsonObject>>() { @Override//from w w w. j a va2 s . co m public void handle(final Either<String, JsonObject> event) { if (event.isRight()) { JsonObject value = event.right().getValue(); if (value == null) { handler.handle(new Either.Left<String, JsonArray>("error : user not found")); } else { JsonArray profiles = value.getJsonArray("u.profiles"); if (profiles != null && profiles.size() > 0) { if (profiles.contains("Student")) { // Get student vectors for saml response : "4|"+u.lastName+"|"+u.firstName+"|"+u.externalId+"|"+s.UAI String query = "MATCH u-[:IN]->()-[:DEPENDS]->(s:Structure) " + "WHERE u.id = {userId} " + "RETURN DISTINCT '4|'+u.lastName+'|'+u.firstName+'|'+u.attachmentId+'|'+s.UAI as FrEduVecteur"; neo4j.execute(query, new JsonObject().put("userId", userId), validResultHandler(handler)); } else if (profiles.contains("Relative")) { // Get parent vectors for saml response : '2|'+u.lastName+'|'+u.firstName+'|'+ child.externalId+'|'+s.UAI" String query = "MATCH (child: User)-[:RELATED]->u-[:IN]->()-[:DEPENDS]->(s:Structure) " + "WHERE u.id = {userId} " + "RETURN DISTINCT '2|'+u.lastName+'|'+u.firstName+'|'+ child.attachmentId+'|'+s.UAI as FrEduVecteur"; neo4j.execute(query, new JsonObject().put("userId", userId), validResultHandler(handler)); } else { // We return null for others profiles handler.handle( new Either.Left<String, JsonArray>("error : profil not supported")); } } } } else { handler.handle(new Either.Left<String, JsonArray>("error : user or profile not found")); } } })); }
From source file:org.entcore.blog.controllers.BlogController.java
License:Open Source License
@Get("/list/all") @SecuredAction("blog.list") public void list(final HttpServerRequest request) { getUserInfos(eb, request, new Handler<UserInfos>() { @Override//from ww w. j ava2s . c om public void handle(final UserInfos user) { if (user != null) { final Integer page; try { page = (request.params().get("page") != null) ? Integer.parseInt(request.params().get("page")) : null; } catch (NumberFormatException e) { badRequest(request, e.getMessage()); return; } final String search = request.params().get("search"); blog.list(user, page, search, new Handler<Either<String, JsonArray>>() { public void handle(Either<String, JsonArray> event) { if (event.isLeft()) { arrayResponseHandler(request).handle(event); ; return; } final JsonArray blogs = event.right().getValue(); if (blogs.size() < 1) { renderJson(request, new JsonArray()); return; } final AtomicInteger countdown = new AtomicInteger(blogs.size()); final Handler<Void> finalHandler = new Handler<Void>() { public void handle(Void v) { if (countdown.decrementAndGet() <= 0) { renderJson(request, blogs); } } }; for (Object blogObj : blogs) { final JsonObject blog = (JsonObject) blogObj; postService.list(blog.getString("_id"), PostService.StateType.PUBLISHED, user, null, 2, null, new Handler<Either<String, JsonArray>>() { public void handle(Either<String, JsonArray> event) { if (event.isRight()) { blog.put("fetchPosts", event.right().getValue()); } finalHandler.handle(null); } }); } } }); } else { unauthorized(request); } } }); }
From source file:org.entcore.blog.controllers.BlogController.java
License:Open Source License
@Get("/linker") public void listBlogsIds(final HttpServerRequest request) { getUserInfos(eb, request, new Handler<UserInfos>() { @Override// w ww . jav a 2 s .c o m public void handle(final UserInfos user) { if (user != null) { blog.list(user, null, null, new Handler<Either<String, JsonArray>>() { public void handle(Either<String, JsonArray> event) { if (event.isLeft()) { arrayResponseHandler(request).handle(event); return; } final JsonArray blogs = event.right().getValue(); if (blogs.size() < 1) { renderJson(request, new JsonArray()); return; } final AtomicInteger countdown = new AtomicInteger(blogs.size()); final Handler<Void> finalHandler = new Handler<Void>() { public void handle(Void v) { if (countdown.decrementAndGet() <= 0) { renderJson(request, blogs); } } }; for (Object blogObj : blogs) { final JsonObject blog = (JsonObject) blogObj; postService.list(blog.getString("_id"), PostService.StateType.PUBLISHED, user, null, 0, null, new Handler<Either<String, JsonArray>>() { public void handle(Either<String, JsonArray> event) { if (event.isRight()) { blog.put("fetchPosts", event.right().getValue()); } finalHandler.handle(null); } }); } } }); } else { unauthorized(request); } } }); }