diff --git a/domainManager/Domain/.classpath b/domainManager/Domain/.classpath index f22c249a54ed18ae75ca24f919ba801ee14e1dbc..c9b0006c04ffe492285c66618fb3f19ba3a9b57c 100644 --- a/domainManager/Domain/.classpath +++ b/domainManager/Domain/.classpath @@ -11,7 +11,7 @@ <attribute name="javadoc_location" value="jar:platform:/resource/Domain/org.json-chargebee-1.0-javadoc.jar!/"/> </attributes> </classpathentry> - <classpathentry kind="lib" path="fusionauth-jwt-4.2.0.jar"> + <classpathentry kind="lib" path="/home/ale/Scrivania/ProgettoPissir/pissirsmarthome/domainManager/Domain/fusionauth-jwt-5.2.1.jar"> <attributes> <attribute name="javadoc_location" value="jar:platform:/resource/Domain/fusionauth-jwt-4.2.0-javadoc.jar!/"/> </attributes> diff --git a/domainManager/Domain/bin/.gitignore b/domainManager/Domain/bin/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..d4d38c0b1dae9673434faa16a34b33fcaa070682 --- /dev/null +++ b/domainManager/Domain/bin/.gitignore @@ -0,0 +1,2 @@ +/code/ +/db/ diff --git a/domainManager/Domain/src/code/DeleteHandler.java b/domainManager/Domain/src/code/DeleteHandler.java index 04a5af7b4e9a6dd180df2f3c4f21006a11c8f94b..52bec90de55ffdef9a5b01006e577517b2d5026e 100644 --- a/domainManager/Domain/src/code/DeleteHandler.java +++ b/domainManager/Domain/src/code/DeleteHandler.java @@ -29,38 +29,24 @@ public class DeleteHandler implements HttpHandler { Helper.sendCors(he, 405); return; } - - String user; - if ((user = Helper.checkTokenGetUser(he)) == null) { + String body = Helper.readBody(he.getRequestBody()); + String user= Helper.checkTokenGetUser(he); + if (user == null) { Helper.sendCors(he, 401); return; } - - - String body = Helper.readBody(he.getRequestBody()); try { String dominio = new JSONObject(body).getString("domain"); Dominio d = DBC.getDom(dominio); - // String s = user + "-A"; - /* - * for(Dominio d : doms){ if( (d.getDomain() == dominio) && - * d.getUsers().contains(s)) //something here - * System.out.println("OPERAZIONE NON IMPLEMENTATA"); - * he.sendResponseHeaders(401,response.length()); OutputStream os = - * he.getResponseBody(); os.write("NON AUTORIZZATO".getBytes()); os.close(); - * return; } - */ if (d == null) { Helper.sendCors(he, 404); return; - } ArrayList<String> ad = DBC.getDomainsAdmin(user); if (!ad.contains(dominio)) { Helper.sendCors(he, 401); return; - } DBC.delDom(dominio); @@ -68,64 +54,11 @@ public class DeleteHandler implements HttpHandler { e.printStackTrace(); return; } - - // effettuo chiamata a CloudAppManager - // preso da https://www.baeldung.com/java-http-request - - // è una chiamata annidata nella risposta alla webapp - // -richiesta REST da webApp a /install - // -prendo da DB e poi chiamo CloudAppMng su /install - // -attendo risposta da CloudAppMng e chiudo - // -rispondo a webApp e chiudo - // EZ - - // - // standard per chiamata in slide - // https://www.dir.uniupo.it/pluginfile.php/948883/mod_resource/content/1/FrameworkProgetto5.pdf - // - // http://127.0.0.1:8080/install - - /* - * URL url = new URL(Helper.getCloudappURL()+"delete");//maybe, se CloudAppe è - * in localhost porta 8080 - * //aggiungere 3000/delete - * HttpURLConnection con = (HttpURLConnection) url.openConnection(); - * con.setRequestMethod("POST"); - * con.setRequestProperty("Content-Type", "application/json"); - * con.setRequestProperty("Accept", "application/json"); - * con.setDoOutput(true); - * con.setConnectTimeout(5000); - * con.setReadTimeout(5000); - * - * DataOutputStream out = new - * DataOutputStream(con.getOutputStream());//inserimento param in call - * out.writeBytes(body); - * out.flush(); - * out.close(); - * - * //con.setRequestProperty("Content-Type", "application/json"); - * //String contentType = con.getHeaderField("Content-Type"); - * - * //leggo risposta - * int status = con.getResponseCode(); - * - * BufferedReader in = new BufferedReader(new - * InputStreamReader(con.getInputStream())); - * String inputLine; - * StringBuffer content = new StringBuffer(); - * while ((inputLine = in.readLine()) != null) - * content.append(inputLine); - * - * in.close(); - */ HttpURLConnection con = Helper.sendMessageToCloudapp("install", body); int status = con.getResponseCode(); // FIXME serve avere anche il content? String cloudappResponse = Helper.getResponseFromConnection(con); con.disconnect(); - Helper.sendCors(he, status); - } - -} +} \ No newline at end of file diff --git a/domainManager/Domain/src/code/Domain.java b/domainManager/Domain/src/code/Domain.java index 81678ccc40f5c13eabcbbdaf343a849949cd9e67..5d04b5ef407d4c6fe668daad3abcf4c53da67958 100644 --- a/domainManager/Domain/src/code/Domain.java +++ b/domainManager/Domain/src/code/Domain.java @@ -18,80 +18,56 @@ import db.DBC; public class Domain { - // static public int port=3001; + static public int port=3001; public static void main(String[] args) throws IOException, JSONException { - /*if(args.length>1 && args[0].equals("-port")){ - try { - port = Integer.parseInt(args[1]); - } catch (Exception e) { - e.printStackTrace(); - } - }*/ - ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor)Executors.newCachedThreadPool();////newFixedThreadPool(5) - HttpServer server=HttpServer.create(new InetSocketAddress(3001),0);//port connection set here - - //Connect.connect(); - + + ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor)Executors.newCachedThreadPool(); + HttpServer server=HttpServer.create(new InetSocketAddress(port),0); //chiamata per popolare moduli - URL url = new URL("https://gitlab.di.unipmn.it/alfredo/iotlabgw.edu-al.unipmn.it/-/raw/main/index.json"); HttpURLConnection con = (HttpURLConnection) url.openConnection(); - // 3000/install da inserire + Helper.setConnectionSettings(con,"GET"); -// DataOutputStream out = new DataOutputStream(con.getOutputStream());// inserimento param in call -// out.writeBytes(j.toString());// ParameterStringBuilder.getParamsString(parameters)); -// out.flush(); -// out.close(); - - // con.setRequestProperty("Content-Type", "application/json"); - // String contentType = con.getHeaderField("Content-Type"); - // leggo risposta int status = con.getResponseCode(); - - /*BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); - String inputLine; - StringBuffer content = new StringBuffer(); - while ((inputLine = in.readLine()) != null) { - content.append(inputLine); - } - in.close();*/ + //controllare ToDo String content = Helper.getResponseFromConnection(con); con.disconnect(); -// System.out.println(content); //manipolazione per ottenere i campi dei moduli - JSONObject obj=new JSONObject(content); -// System.out.println(obj.toString()); - //String s=content.toString(); - //ArrayList<String>arr=s. + riempiModuli(content); - //String []s1=s.split(","); - JSONArray jr = obj.getJSONArray("response"); + server.setExecutor(threadPoolExecutor); - //String []s1=(String[]) obj.get("response"); + server.createContext("/install/", new InstallHandler()); + server.createContext("/start/", new StartHandler()); + server.createContext("/stop/", new StopHandler()); + server.createContext("/delete/", new DeleteHandler()); + server.createContext("/secured/domains/", new TokenHandler()); + server.createContext("/secured/services", new ServicesHandler()); + server.createContext("/secured/priviledges", new PriviledgesHandler()); + server.start(); + System.out.println("Domain in ascolto su "+Helper.getSelfURL()); + } + + private static void riempiModuli(String content) throws JSONException { + + JSONObject obj=new JSONObject(content); + JSONArray jr = obj.getJSONArray("response"); String []s1=new String[jr.length()]; + for(int i=0;i<jr.length();i++) { s1[i]=jr.getString(i); } - -// for(int i=0; i<s1.length; i++) -// System.out.println(s1[i]); -// - //ArrayList<String> arr= new ArrayList<String>(); for(int i=0;i<s1.length;i++) { String remZip=s1[i].substring(0, s1[i].length()-4); -// System.out.println("remmZip = "+remZip); - //arr.add(s1[i]); - //String[] curr=s1[i].split("-"); String[] curr=remZip.split("-"); for(int j=0;j<curr.length;j++) { -// System.out.println("curr["+j+"] = "+curr[j]); if(curr.length>1) { String a=curr[0]; String b=curr[1]; @@ -111,26 +87,9 @@ public class Domain { e.printStackTrace(); } - } + } } } - - - server.setExecutor(threadPoolExecutor); - - //server.createContext("/", new RootHandler(port)); - //server.createContext("/index", new IndexHandler()); - //install-start-stop-delete - server.createContext("/install/", new InstallHandler()); - server.createContext("/start/", new StartHandler()); - server.createContext("/stop/", new StopHandler()); - server.createContext("/delete/", new DeleteHandler()); - server.createContext("/secured/domains/", new TokenHandler()); - server.createContext("/secured/services", new ServicesHandler()); - server.createContext("/secured/priviledges", new PriviledgesHandler()); - - server.start(); - System.out.println("Domain in ascolto su "+Helper.getSelfURL()); } } diff --git a/domainManager/Domain/src/code/InstallHandler.java b/domainManager/Domain/src/code/InstallHandler.java index b04532351525ab9a4caf021e7669765ab7c737da..986c3ab929ba3ec465a29969b40a1ec23ef1f469 100644 --- a/domainManager/Domain/src/code/InstallHandler.java +++ b/domainManager/Domain/src/code/InstallHandler.java @@ -27,30 +27,21 @@ public class InstallHandler implements HttpHandler { Helper.sendCors(he, 200); return; } - if (requestMethod.compareToIgnoreCase("POST") != 0) { Helper.sendCors(he, 405); return; } String body = Helper.readBody(he.getRequestBody()); - - String user; - - if ((user = Helper.checkTokenGetUser(he)) == null) { + // verifica user + String user = Helper.checkTokenGetUser(he); + if (user == null) { Helper.sendCors(he, 401); return; } - - // verifica user - - JSONObject j = null; try { j = new JSONObject(body); String dm = j.getString("domain"); - - // try { - Dominio d = DBC.getDom(dm); if (d != null) { Helper.sendCors(he, 403); @@ -63,10 +54,7 @@ public class InstallHandler implements HttpHandler { } // inserisco i dati nel DB - - // String s = user + "-A"; try { - // qui leggo e parsifico i json nel body, inserisco tutti i campi nel db String domain = j.getString("domain"); @@ -74,7 +62,6 @@ public class InstallHandler implements HttpHandler { // questa chiamata serve ad assicurarsi che l'utente che ha effettuato la // chiamata sia anche amministratore del dominio DBC.insertAmministra(user, domain); - JSONArray arrUsers = j.getJSONArray("users"); for (int i = 0; i < arrUsers.length(); i++) { JSONObject userObj = arrUsers.getJSONObject(i); @@ -92,10 +79,6 @@ public class InstallHandler implements HttpHandler { JSONArray arrServ = j.getJSONArray("services");// array con solo il nome dei servizi da installare ArrayList<String> moduleHosts = new ArrayList<String>(); for (int i = 0; i < arrServ.length(); i++) { - - // String modul=((JSONObject) arrUsers.get(i)).getString("service"); - // String host=((JSONObject) arrUsers.get(i)).getString("host"); - // DBC.insertService(domain,host,modul); String modul = arrServ.getString(i); moduleHosts.addAll(DBC.insertService(domain, modul)); } @@ -128,15 +111,12 @@ public class InstallHandler implements HttpHandler { } } j.put("services", arrServiziFinale); - // non ci sono controlli!!!! } catch (SQLException | JSONException e) { e.printStackTrace(); } - // ora bisogna fare la chiamata al CloudApp, non prima! // effettuo chiamata a CloudAppManager - // preso da https://www.baeldung.com/java-http-request // è una chiamata annidata nella risposta alla webapp // -richiesta REST da webApp a /install @@ -145,44 +125,6 @@ public class InstallHandler implements HttpHandler { // -rispondo a webApp e chiudo // EZ - // - // standard per chiamata in slide - // https://www.dir.uniupo.it/pluginfile.php/948883/mod_resource/content/1/FrameworkProgetto5.pdf - // - // http://127.0.0.1:8080/install - - // 3002/install da inserire - /* - * URL url = new URL(Helper.getCloudappURL()+"install");// maybe, se CloudAppe è - * in localhost porta 8080 - * HttpURLConnection con = (HttpURLConnection) url.openConnection(); - * - * con.setRequestMethod("POST"); - * con.setRequestProperty("Content-Type", "application/json"); - * con.setRequestProperty("Accept", "application/json"); - * con.setDoOutput(true); - * con.setConnectTimeout(5000); - * con.setReadTimeout(5000); - * DataOutputStream out = new DataOutputStream(con.getOutputStream());// - * inserimento param - * // in call - * out.writeBytes(j.toString()); - * out.flush(); - * out.close(); - * - * // con.setRequestProperty("Content-Type", "application/json"); - * // String contentType = con.getHeaderField("Content-Type"); - * // leggo risposta - * int status = con.getResponseCode(); - * BufferedReader in = new BufferedReader(new - * InputStreamReader(con.getInputStream())); - * String inputLine; - * StringBuffer content = new StringBuffer(); - * while ((inputLine = in.readLine()) != null) { - * content.append(inputLine); - * } - * in.close(); - */ HttpURLConnection con = Helper.sendMessageToCloudapp("install", j.toString()); int status = con.getResponseCode(); // FIXME serve avere anche il content? @@ -190,11 +132,6 @@ public class InstallHandler implements HttpHandler { con.disconnect(); // finita chiamata a CloudApp - - // f.close(); - // risposta alla webapp Helper.sendCors(he, status); - } - } diff --git a/domainManager/Domain/src/code/PriviledgesHandler.java b/domainManager/Domain/src/code/PriviledgesHandler.java index bde308c61793a554d6439b7b0036677146965b0e..f8a0e9896757f9d2ec6a8d859fe0ab2acd8ea018 100644 --- a/domainManager/Domain/src/code/PriviledgesHandler.java +++ b/domainManager/Domain/src/code/PriviledgesHandler.java @@ -4,9 +4,7 @@ import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.Map; - import org.json.JSONException; - import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; @@ -63,5 +61,4 @@ public class PriviledgesHandler implements HttpHandler{ // the user is not admin or user of this domain Helper.sendCors(he, 404); } - -} +} \ No newline at end of file diff --git a/domainManager/Domain/src/code/ServicesHandler.java b/domainManager/Domain/src/code/ServicesHandler.java index 391b7630006d949cfd1c8f9dc02913c47d418c36..a4b45ab749a8354e88581ab2445d157f4b3e5fd1 100644 --- a/domainManager/Domain/src/code/ServicesHandler.java +++ b/domainManager/Domain/src/code/ServicesHandler.java @@ -1,21 +1,16 @@ package code; - import java.io.IOException; import java.net.URI; import java.sql.SQLException; import java.util.Map; - import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; - import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; - import db.DBC; - public class ServicesHandler implements HttpHandler{ @@ -27,17 +22,14 @@ public class ServicesHandler implements HttpHandler{ Helper.sendCors(he, 200); return; } - if (requestMethod.compareToIgnoreCase("GET") != 0) { Helper.sendCors(he, 405); return; } - if(Helper.checkTokenGetUser(he) == null) { Helper.sendCors(he, 401); return; } - String response = ""; // get the query (if any) String query = requestedUri.getRawQuery(); @@ -46,29 +38,16 @@ public class ServicesHandler implements HttpHandler{ Map<String, Object> parameters = Helper.parseQuery(requestedUri.getRawQuery()); domain=(String) parameters.get("domain"); } - - JSONObject res = new JSONObject(); if(domain != null){ // I have to send only the services used by this domain - JSONArray rs =null; - - //ArrayList<String> modulesList; try { - //modulesList = DBC.getModules(); - - //for (String k : modulesList) { - // rs.put(k); rs= DBC.getServicesInUseByDomain(domain); res.put("response", rs); - } catch (SQLException | JSONException e) { e.printStackTrace(); } - - - } else { // I have to send all available services JSONArray rs = DBC.getAllServices(); @@ -77,19 +56,9 @@ public class ServicesHandler implements HttpHandler{ } catch (JSONException e) { e.printStackTrace(); } - } response = res.toString(); - // questa parte sopra serve anche qui, non solo quando si chiama con OPTIONS Helper.sendCors(he, 200, response); - - // JSONObject j=new JSONObject(); - // j.append("User", DBC.getDomainsUser(user)); - - // j=(""+":"+); - - } - -} +} \ No newline at end of file diff --git a/domainManager/Domain/src/code/StartHandler.java b/domainManager/Domain/src/code/StartHandler.java index c2cc9afe0ce59c9b7783750fd77f5d937f52c83b..5d0b922f97009f3fcbf1a76da7d33cd5b2801961 100644 --- a/domainManager/Domain/src/code/StartHandler.java +++ b/domainManager/Domain/src/code/StartHandler.java @@ -17,21 +17,7 @@ public class StartHandler implements HttpHandler { @Override public void handle(HttpExchange he) throws IOException { - // URI requestedUri = he.getRequestURI(); - // System.out.println(requestedUri.toString()); - /* - * if(he.getRequestHeaders().get("version")==null) { he.sendResponseHeaders(426, - * "VERSIONE NON PRESENTE. (USARE -H version:1.0)".length()); OutputStream os = - * he.getResponseBody(); - * os.write("VERSIONE NON PRESENTE. (USARE -H version:1.0)".getBytes()); - * os.close(); return; } else - * if(he.getRequestHeaders().get("version").get(0).compareTo("1.0")!=0) { - * he.sendResponseHeaders(426, - * "CAMBIA VERSIONE. (USARE -H version:1.0)".length()); OutputStream os = - * he.getResponseBody(); - * os.write("CAMBIA VERSIONE. (USARE -H version:1.0)".getBytes()); os.close(); - * return; } - */ + String requestMethod = he.getRequestMethod(); if (requestMethod.compareToIgnoreCase("options") == 0) { Helper.sendCors(he, 200); @@ -41,30 +27,20 @@ public class StartHandler implements HttpHandler { Helper.sendCors(he, 405); return; } - // String query = requestedUri.getRawQuery(); + String body = Helper.readBody(he.getRequestBody()); - String user; + String user= Helper.checkTokenGetUser(he); - if ((user = Helper.checkTokenGetUser(he)) == null) { + if (user == null) { Helper.sendCors(he, 401); return; } - String domain; try { domain = new JSONObject(body).getString("domain"); - // Dominio d = DBC.getDom(dominio); - // String s = user + "-A"; ArrayList<String> ad = DBC.getDomainsAdmin(user); - /* - * for(Dominio d : doms){ if( (d.getDomain() == dominio) && - * d.getUsers().contains(s)) //something here - * System.out.println("OPERAZIONE NON IMPLEMENTATA"); - * he.sendResponseHeaders(401,response.length()); OutputStream os = - * he.getResponseBody(); os.write("NON AUTORIZZATO".getBytes()); os.close(); - * return; } - */ + if (!ad.contains(domain)) { Helper.sendCors(he, 401); return; @@ -75,43 +51,6 @@ public class StartHandler implements HttpHandler { return; } - /* - * URL url = new URL(Helper.getCloudappURL()+"start");// maybe, se CloudApp è in - * localhost porta 8080 - * HttpURLConnection con = (HttpURLConnection) url.openConnection(); - * con.setRequestMethod("POST"); - * con.setRequestProperty("Content-Type", "application/json"); - * con.setRequestProperty("version", "1.0"); - * - * //Map<String, String> parameters = new HashMap<>(); - * // System.out.println("pino1"); - * // {“domainâ€:â€nome_dominioâ€} check utente chiamante ha permessi su dominio - * // chiamato, chi fa install è admin - * - * // parameters.put("param1", "val");// fix parametri da mandare - * //parameters.put("domain", dominio); - * - * con.setDoOutput(true); - * // System.out.println("pino2"); - * DataOutputStream out = new DataOutputStream(con.getOutputStream());// - * inserimento param in call - * out.writeBytes(body.toString());//(ParameterStringBuilder.getParamsString( - * parameters));//j.toString(); - * - * out.flush(); - * out.close(); - * // System.out.println("pino3"); - * - * // con.setRequestProperty("Content-Type", "application/json"); - * // String contentType = con.getHeaderField("Content-Type"); - * - * con.setConnectTimeout(5000); - * con.setReadTimeout(5000); - * // System.out.println("pino4"); - * - * // leggo risposta - * int status = con.getResponseCode(); - */ HttpURLConnection con = Helper.sendMessageToCloudapp("start", body); int status = con.getResponseCode(); // FIXME serve avere anche il content? @@ -119,9 +58,7 @@ public class StartHandler implements HttpHandler { con.disconnect(); Helper.sendCors(he, status); - // cambio lo stato nel DB - DBC.setStatoDomain(domain, 1); + DBC.setStatoDomain(domain, 1); } - } \ No newline at end of file diff --git a/domainManager/Domain/src/code/StopHandler.java b/domainManager/Domain/src/code/StopHandler.java index 7cb5dddac003ce347eb3896e7bccad1c1b23ba37..cb8d01c2b5f20375a8b4c459c7414f2e7b55ee4e 100644 --- a/domainManager/Domain/src/code/StopHandler.java +++ b/domainManager/Domain/src/code/StopHandler.java @@ -18,7 +18,6 @@ public class StopHandler implements HttpHandler { @Override public void handle(HttpExchange he) throws IOException { - // URI requestedUri = he.getRequestURI(); String requestMethod = he.getRequestMethod(); if (requestMethod.compareToIgnoreCase("options") == 0) { @@ -30,33 +29,19 @@ public class StopHandler implements HttpHandler { return; } - // String requestMethod = he.getRequestMethod(); - // String query = requestedUri.getRawQuery(); String body = Helper.readBody(he.getRequestBody()); - String user;// he.getRequestHeaders().get("user").get(0); + String user= Helper.checkTokenGetUser(he); - if ((user = Helper.checkTokenGetUser(he)) == null) { + if (user == null) { Helper.sendCors(he, 401); return; } - String domain; try { domain = new JSONObject(body).getString("domain"); - // Dominio d = DBC.getDom(dominio); - // String s = user + "-A"; - ArrayList<String> ad = DBC.getDomainsAdmin(user); - /* - * for(Dominio d : doms){ if( (d.getDomain() == dominio) && - * d.getUsers().contains(s)) //something here - * System.out.println("OPERAZIONE NON IMPLEMENTATA"); - * he.sendResponseHeaders(401,response.length()); OutputStream os = - * he.getResponseBody(); os.write("NON AUTORIZZATO".getBytes()); os.close(); - * return; } - */ if (!ad.contains(domain)) { Helper.sendCors(he, 401); return; @@ -66,52 +51,6 @@ public class StopHandler implements HttpHandler { e.printStackTrace(); return; } - // effettuo chiamata a CloudAppManager - // preso da https://www.baeldung.com/java-http-request - - // è una chiamata annidata nella risposta alla webapp - // -richiesta REST da webApp a /install - // -prendo da DB e poi chiamo CloudAppMng su /install - // -attendo risposta da CloudAppMng e chiudo - // -rispondo a webApp e chiudo - // EZ - - // - // standard per chiamata in slide - // https://www.dir.uniupo.it/pluginfile.php/948883/mod_resource/content/1/FrameworkProgetto5.pdf - // - // http://127.0.0.1:8080/install - /* - * URL url = new URL(Helper.getCloudappURL()+"stop");// maybe, se CloudAppe è in - * localhost porta 8080 - * HttpURLConnection con = (HttpURLConnection) url.openConnection(); - * con.setRequestMethod("POST"); - * con.setRequestProperty("Content-Type", "application/json"); - * con.setRequestProperty("Accept", "application/json"); - * - * //Map<String, String> parameters = new HashMap<>(); - * - * // parameters.put("param1", "val");// fix parametri da mandare - * // leggo da DB domini e riempio (magari famo .DAO??) - * //parameters.put("domain", dominio); - * - * con.setDoOutput(true); - * DataOutputStream out = new DataOutputStream(con.getOutputStream());// - * inserimento param in call - * //out.writeBytes(ParameterStringBuilder.getParamsString(parameters)); - * out.writeBytes(body.toString());//era dominio - * out.flush(); - * out.close(); - * - * // con.setRequestProperty("Content-Type", "application/json"); - * // String contentType = con.getHeaderField("Content-Type"); - * - * con.setConnectTimeout(5000); - * con.setReadTimeout(5000); - * - * // leggo risposta - * int status = con.getResponseCode(); - */ HttpURLConnection con = Helper.sendMessageToCloudapp("stop", body); int status = con.getResponseCode(); @@ -119,54 +58,7 @@ public class StopHandler implements HttpHandler { String cloudappResponse = Helper.getResponseFromConnection(con); con.disconnect(); - // if (status > 299) { - // System.out.println("pino5"); - // streamReader = new InputStreamReader(con.getErrorStream()); - // BufferedReader in = new BufferedReader(streamReader); - // String inputLine; - // StringBuffer content = new StringBuffer(); - // while ((inputLine = in.readLine()) != null) { - // content.append(inputLine); - // } - // response = content.toString(); - // in.close(); - // } else { - // System.out.println("pino6"); - // streamReader = new InputStreamReader(con.getInputStream()); - // BufferedReader in = new BufferedReader(streamReader); - // String inputLine; - // StringBuffer content = new StringBuffer(); - // while ((inputLine = in.readLine()) != null) { - // content.append(inputLine); - // } - // response = content.toString(); - // in.close(); - // } - // - // BufferedReader in = new BufferedReader( - // new InputStreamReader(con.getInputStream())); - // String inputLine; - // StringBuffer content = new StringBuffer(); - // while ((inputLine = in.readLine()) != null) { - // content.append(inputLine); - // } - // in.close(); - // - // con.disconnect(); - - // finita chiamata a CloudApp Helper.sendCors(he, status); - // cambio lo stato nel DB DBC.setStatoDomain(domain, 0); - - // else { - // System.out.println("OPERAZIONE NON IMPLEMENTATA"); - // he.sendResponseHeaders(501, 0); - // OutputStream os = he.getResponseBody(); - // os.write("OPERAZIONE NON IMPLEMENTATA".getBytes()); - // os.close(); - // } - } - -} +} \ No newline at end of file diff --git a/domainManager/Domain/src/code/TokenHandler.java b/domainManager/Domain/src/code/TokenHandler.java index 287e8ac00b927e006f4d2c645f0c6caf058410ab..9d5f26c6419b083746aa332075e7efe2352ed35e 100644 --- a/domainManager/Domain/src/code/TokenHandler.java +++ b/domainManager/Domain/src/code/TokenHandler.java @@ -29,7 +29,7 @@ import io.fusionauth.jwt.rsa.RSAVerifier; public class TokenHandler implements HttpHandler { public void handle(HttpExchange he) throws IOException { - // URI requestedUri = he.getRequestURI(); + String requestMethod = he.getRequestMethod(); if (requestMethod.compareToIgnoreCase("options") == 0) { @@ -37,115 +37,18 @@ public class TokenHandler implements HttpHandler { return; } if (requestMethod.compareToIgnoreCase("GET") != 0) { - // send Method not allowed - // exchange.getResponseHeaders().remove("content-type"); - // String response = "{\"message\":\"Method not allowed!\"}"; - // Helper.sendCors(he,405,response); Helper.sendCors(he, 405); return; } - // String query = requestedUri.getRawQuery(); - // String body = readBody(he.getRequestBody()); - String user; - - // String user = he.getRequestHeaders().get("user").get(0); - - // questo e' strano: headers dice { {} } mentre headers.get("Authorization") - // riporta il token correttamente - // System.out.println("Headers: "+he.getRequestHeaders()); - // System.out.println("Auth: "+he.getRequestHeaders().get("Authorization")); - - // System.out.println("token: " + token); - - if ((user = Helper.checkTokenGetUser(he)) == null) { + String user = Helper.checkTokenGetUser(he); + if (user == null) { Helper.sendCors(he, 401); return; } - // System.out.println(body); - - // JSONObject chiave = new JSONObject(); - // chiamo http://localhost:8080/auth/realms/test00/protocol/openid-connect/certs - // //probabilmente https - - // TOKEN____________________________________________________________________ - - // { - // "access_token": - // "eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJXZ2FCRjhidS05dVhhR0pNRzIxQWQtQTV3aW0xZ29oRnhNNXVvNTJrLWhJIn0.eyJleHAiOjE2NjIwMjQwMjgsImlhdCI6MTY2MjAyMzcyOCwiYXV0aF90aW1lIjoxNjYyMDIzNjYyLCJqdGkiOiIzMmUwODFmMi00MmZhLTQ2ZDEtOTliNy05OWY0MTRlNmM4MTciLCJpc3MiOiJodH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JgzzbsTiYhJZZp-jvu05ZyMaQ3Q_wUYazb6VvbAkz9F2-8Uk04SxHVUsHjcinoyYd6jQP5TML3cVvwNk_eX2LavQk9o3XCQeBxsq9tUw7HsnSjtvPnuqHMe7S_Yg7_xp6QLVXdQAkOebFcvAMv8hMUMhXk0RV-RryhvQ85gF5NHgdvFhB6FPoXCO-T-SZpi6Qw", - // "expires_in": 300, - // "refresh_expires_in": 1800, - // "refresh_token": - // "eyJhbGciOiJIUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJkZDIyM2U5NC1mMjUxLTQ4MDAtYTI3Zi1jYzQzZjZhZTQzODEifQ.eyJleHAiOjE2NjIwMjU1MjgsImlhdCI6MTY2MjAyMzcyOCwianRpIjoiOTEwNWViMGUtMGJmMS00ODRlLTk1M2UtOGRmMTRkMzkwMGI4IiwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo4MDgwL3JlYWxtcy90ZXN0MDAiLCJhdWQiOiJodHRwOi8vbG9jYWxob3N0OjgwODAvcmVhbG1zL3Rlc3QwMCIsInN1YiI6IjYwYTgyN2MxLTNkMzctNDg4MS1iNTc3LTM4M2VkNTE2MTcyOCIsInR5cCI6IlJlZnJlc2giLCJhenAiOiJteWNsaWVudCIsIm5vbmNlIjoiYTgxZTFhODQtODg4NS00NzAyLWI4ZDEtZjZjNWEwZDFmYzRkIiwic2Vzc2lvbl9zdGF0ZSI6IjUyOTQwYWYzLTM0MjctNDVkZC04YWNhLWE0ZDYxMjdhNDQxZCIsInNjb3BlIjoib3BlbmlkIHByb2ZpbGUgZW1haWwiLCJzaWQiOiI1Mjk0MGFmMy0zNDI3LTQ1ZGQtOGFjYS1hNGQ2MTI3YTQ0MWQifQ.ZqcOLMUwHPxQY2I0V9bPIy6TBTeUIcHEbxgnxhJrac0", - // "token_type": "Bearer", - // "id_token": - // "eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJXZ2FCRjhidS05dVhhR0pNRzIxQWQ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jRngSQDzTW4aHAL-jQENW2od0N23IXKtTrPCx33gElfeuA9hvyb6c4d8CNFrw6AHKH0YsoGqQ", - // "not-before-policy": 0, - // "session_state": "52940af3-3427-45dd-8aca-a4d6127a441d", - // "scope": "openid profile email" - // } - - // CHIAVE - // PUBBLICA________________________________________________________________ - // { - // "keys": [ - // { - // "kid": "WgaBF8bu-9uXaGJMG21Ad-A5wim1gohFxM5uo52k-hI", - // "kty": "RSA", - // "alg": "RS256", - // "use": "sig", - // "n": - // "qoJMLXqIHoBKq5vE7EYVdvxpwqOjPkeTUSb1rdhJs8ZpfCOQk7PYlNu-ykl4PAjYS5sVs5gQSzEwtTZ3vz1y8Ry0V1Xa3c3wk77NzahMO9QnAXa0cqFWhaIr4l0oKhRy-57hNIthkiRuDDlWBREb5sqk8OWxarznEVRykaC4178ccQrv6T3T5VGzxV1lCcBDzQchx_c9_v-tcQVGeyBhdm9uFARbxGG-91kDxSv3MKQbjdwp9csr2QDwuFgcBSB4Ul-9oMCZiVDpgWuoCy_ZxsI22WYAPT8KyaYts-0v7B89hPPweR7TzbmQHEGMfl0U_qEBdQw0N9P2KRapol7RyQ", - // "e": "AQAB", - // "x5c": [ - // "MIICmzCCAYMCBgGCkqLMcTANBgkqhkiG9w0BAQsFADARMQ8wDQYDVQQDDAZ0ZXN0MDAwHhcNMjIwODEyMTUxNjU4WhcNMzIwODEyMTUxODM4WjARMQ8wDQYDVQQDDAZ0ZXN0MDAwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCqgkwteogegEqrm8TsRhV2/GnCo6M+R5NRJvWt2Emzxml8I5CTs9iU277KSXg8CNhLmxWzmBBLMTC1Nne/PXLxHLRXVdrdzfCTvs3NqEw71CcBdrRyoVaFoiviXSgqFHL7nuE0i2GSJG4MOVYFERvmyqTw5bFqvOcRVHKRoLjXvxxxCu/pPdPlUbPFXWUJwEPNByHH9z3+/61xBUZ7IGF2b24UBFvEYb73WQPFK/cwpBuN3Cn1yyvZAPC4WBwFIHhSX72gwJmJUOmBa6gLL9nGwjbZZgA9PwrJpi2z7S/sHz2E8/B5HtPNuZAcQYx+XRT+oQF1DDQ30/YpFqmiXtHJAgMBAAEwDQYJKoZIhvcNAQELBQADggEBAHF8qo6bVlpt/44OxqnSFDY0wIxcunFIbA05ggox/5oAQvdoTD1LB8sfuLa3dtA/ysnnZDytk+vr8V4feYdSvAbtCWVq3yJgt7Dhe7ueP45v4WPJPcPqv8kMYtbkh0mivF2mYVLsEbZK46kBXN4Gkpv1oRDl2b04rfO7abv0dqb3eFs5QiJtKd1az1ckrTYFHdcB5TiiMaPq8/ikmInYKMvRW5H+NmjRvQf6dhKaSj1+cgcZ5xwVlOuubUyJHABKcK6dfnznwA/Ri3fzYXnG5p7mDazdeOQlNRHMK5SM2D6QRunmufg8ulmM+vhxg5ri8o1WqIkA03z+w44vQFy28Xo=" - // ], - // "x5t": "ip8I56vsh3-VgNBfzigD3oiIwsg", - // "x5t#S256": "1aZ1N3a_PeHLpZeLIbyfyqUjUKJ9NYWMP7-9H2arYWM" - // }, - // { - // "kid": "-0j9GoUrm6Fjs8sxcwaNe9R9mqr7bmgSRQ_nRp72iIs", - // "kty": "RSA", - // "alg": "RSA-OAEP", - // "use": "enc", - // "n": - // "kpxC6pFuQnQVq8KoO3uMaFrfKC00jBbHfkx8HYuCIblQGap3xjcLGfMbd2EP2Hz2c38dmWcCMS6GgxUU10rlnWc4HKZ5jYCVTEdjU4nkmArzVipG03HzVb-3Eftz1hb4z8Qyjw616tjwQtaQRCvtx9o_UhmxG6YIeJhauN_Zh9z6ZHJ8bY6N242vk_ryJmaTsQ-GyOmU5h16mMrGCjMJ_uMiy38dITySNFGKwnJHaKU8H6V25UuGVgNl-Wjpk5L2bAdSkDEblJ7SsvzoYLGYzCUeCHhztWbNOy_sc31awULdTWEgH8SKvOWf3qZY1siItHBqHLHlHo5lNIMzhowGrw", - // "e": "AQAB", - // "x5c": [ - // "MIICmzCCAYMCBgGCkqLNYTANBgkqhkiG9w0BAQsFADARMQ8wDQYDVQQDDAZ0ZXN0MDAwHhcNMjIwODEyMTUxNjU5WhcNMzIwODEyMTUxODM5WjARMQ8wDQYDVQQDDAZ0ZXN0MDAwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCSnELqkW5CdBWrwqg7e4xoWt8oLTSMFsd+THwdi4IhuVAZqnfGNwsZ8xt3YQ/YfPZzfx2ZZwIxLoaDFRTXSuWdZzgcpnmNgJVMR2NTieSYCvNWKkbTcfNVv7cR+3PWFvjPxDKPDrXq2PBC1pBEK+3H2j9SGbEbpgh4mFq439mH3Ppkcnxtjo3bja+T+vImZpOxD4bI6ZTmHXqYysYKMwn+4yLLfx0hPJI0UYrCckdopTwfpXblS4ZWA2X5aOmTkvZsB1KQMRuUntKy/OhgsZjMJR4IeHO1Zs07L+xzfVrBQt1NYSAfxIq85Z/epljWyIi0cGocseUejmU0gzOGjAavAgMBAAEwDQYJKoZIhvcNAQELBQADggEBAE9kzDnbCjywK6QXECR8citVNaqarf3QQYDzSNakWgrGTTjdStASwEsPJvYJJ5Q6tl6ndqv4gflKq8STrmlHd4Ly+QHnXDwzrzjuSydZDAjYVcacMpZ4PAOAci0R6AmXTynIzyxU92LOlOWiF3ChG7uMRq7yLCNWo1jZxUepGo5z9LyIRGO4Pb878nhWL5PvXC95/vnbx2hSN7T6Uft3j3/94+fgIP4rmO2IWsDuc6fza/J07fK42Mtysy6FqBwhrimDMq+3OnTmdhSRL4pVVrRPSpYO/Czw9ra8hgGoAhu4G4FhTKAr8K75QaMdTtShpBMVNrImOq9kHtOoZJCJW0g=" - // ], - // "x5t": "AU5GWMxLtE_hFDiJevWYEql-n4A", - // "x5t#S256": "43Rx3Dsp6j_NLNwVx__Pb6mz07KrCa8xzH0pKOoV06g" - // } - // ] - // } - - // The x5c filed value is copied between —–BEGIN CERTIFICATE—– - // - // —–END CERTIFICATE—– directives . - - // Build an EC verifier using an EC Public Key. A verifier may also be built - // using the PublicKey object. - // Verifier verifier = ECVerifier.newVerifier(Paths.get("public_key.pem")); - // - // // Verify and decode the encoded string JWT to a rich object - // JWT jwt = JWT.getDecoder().decode(encodedJWT, verifier); - // - // // Assert the subject of the JWT is as expected - // assertEquals(jwt.subject, "f1e33ab3-027f-47c5-bb07-8dd8ab37a2d3"); - // verifica token - // if token !ok return - - // try { - // verificaToken(token,signature); - // } catch (NoSuchAlgorithmException | IOException | JSONException e1) { - // e1.printStackTrace(); - // } - // ricavo da token - JSONObject res = new JSONObject(); JSONArray rs = new JSONArray(); @@ -186,10 +89,6 @@ public class TokenHandler implements HttpHandler { String response = res.toString(); Helper.sendCors(he, 200, response); - // JSONObject j=new JSONObject(); - // j.append("User", DBC.getDomainsUser(user)); - - // j=(""+":"+); } public static String verificaToken(String encodedJWT, String signature) @@ -197,44 +96,17 @@ public class TokenHandler implements HttpHandler { URL url = new URL( Helper.getKeycloakURL() + "realms/" + Helper.getKeycloakRealm() + "/protocol/openid-connect/certs");// maybe, - // se - // CloudAppe - // è - // localhost - // porta - // 8080 - HttpURLConnection con = (HttpURLConnection) url.openConnection(); - // 3000/install da inserire - con.setRequestMethod("GET"); - con.setRequestProperty("Content-Type", "application/json"); - con.setRequestProperty("Accept", "application/json"); - con.setDoOutput(true); - con.setConnectTimeout(5000); - con.setReadTimeout(5000); - - // DataOutputStream out = new DataOutputStream(con.getOutputStream());// - // inserimento param in call - // out.writeBytes(j.toString());// - // ParameterStringBuilder.getParamsString(parameters)); - // out.flush(); - // out.close(); - - // con.setRequestProperty("Content-Type", "application/json"); - // String contentType = con.getHeaderField("Content-Type"); + // 8080 + HttpURLConnection con = (HttpURLConnection) url.openConnection(); + Helper.setConnectionSettings(con, "GET"); // leggo risposta int status = con.getResponseCode(); - BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); - String inputLine; - StringBuffer content = new StringBuffer(); - while ((inputLine = in.readLine()) != null) { - content.append(inputLine); - } - in.close(); + String content = Helper.getResponseFromConnection(con); con.disconnect(); - JSONObject j = new JSONObject(content.toString()); + JSONObject j = new JSONObject(content); JSONArray arr = j.getJSONArray("keys"); JSONObject ogg = arr.getJSONObject(0); String chiave = ogg.getJSONArray("x5c").get(0).toString(); @@ -244,7 +116,6 @@ public class TokenHandler implements HttpHandler { try { int index = encodedJWT.lastIndexOf('.'); byte[] message = encodedJWT.substring(0, index).getBytes(StandardCharsets.UTF_8); - // message = token.header + token.body (tokSplit[0]+"."+tokSplit[1]) byte[] signatureBytes = Base64.getUrlDecoder().decode(signature);// signature = tokSplit[2] verifier.verify(Algorithm.RS256, message, signatureBytes); } catch (InvalidJWTSignatureException e) { @@ -252,40 +123,6 @@ public class TokenHandler implements HttpHandler { } // Verify and decode the encoded string JWT to a rich object JWT jwt = JWT.getDecoder().decode(encodedJWT, verifier); - /* - * { - * "aud" : "account", - * "exp" : 1662288513, - * "iat" : 1662288213, - * "iss" : "http://localhost:8080/realms/test00", - * "sub" : "60a827c1-3d37-4881-b577-383ed5161728", - * "jti" : "719379f0-0b22-40fd-ae35-0f523ffd9d4e", - * "auth_time" : 1662285948, - * "typ" : "Bearer", - * "azp" : "myclient", - * "nonce" : "a81e1a84-8885-4702-b8d1-f6c5a0d1fc4d", - * "session_state" : "969cdd2d-07db-4366-8180-d1ff15ddce20", - * "acr" : "0", - * "allowed-origins" : [ "http://localhost:3000" ], - * "realm_access" : { - * "roles" : [ "offline_access", "default-roles-test00", "uma_authorization" ] - * }, - * "resource_access" : { - * "account" : { - * "roles" : [ "manage-account", "manage-account-links", "view-profile" ] - * } - * }, - * "scope" : "openid profile email", - * "sid" : "969cdd2d-07db-4366-8180-d1ff15ddce20", - * "email_verified" : false, - * "name" : "Mario Rossi", - * "preferred_username" : "john", - * "given_name" : "Mario", - * "family_name" : "Rossi", - * "email" : "mario@gmail.com" - * } - */ return jwt.getString("preferred_username"); } - } \ No newline at end of file