package tech.nevets.autoupdater; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import org.apache.http.auth.AUTH; import spark.Request; import static spark.Spark.*; public class Main { public static final Config CONFIG = new Config(); private static final AuthFileHandler AUTH_TOKENS = new AuthFileHandler(); public static boolean isVerbose = false; public static void main(String[] args) { CONFIG.loadFile(); AUTH_TOKENS.loadFile(); isVerbose = CONFIG.getConfig().get("verbose").getAsBoolean(); port(CONFIG.getConfig().get("port").getAsInt()); post("/jenkins", (rq, rs) -> { if (rq.contentType() == null) halt(404, "Invalid content Type!"); if (rq.contentType().equals("application/json")) { if (!isAuthenticated(rq)) { if (isVerbose) System.out.println("Is not authenticated"); halt(401, "{ \"error\":\"Not Authorized\" }"); } Gson gson = new Gson(); JsonObject json = gson.fromJson(rq.body(), JsonObject.class); JsonElement jarFileNameJson = json.get("jarfile-name"); JsonElement dockerContainerNameJson = json.get("docker-container-name"); JsonElement workingDirectoryJson = json.get("working-directory"); JsonElement downloadUrlJson = json.get("download-url"); if (jarFileNameJson == null || dockerContainerNameJson == null || workingDirectoryJson == null || downloadUrlJson == null) { if (isVerbose) System.out.println("Not all params passed"); halt(405, "{ \"error\":\"Not all parameters passed\" }"); } if (UpdateManager.update(jarFileNameJson.getAsString(), dockerContainerNameJson.getAsString(), workingDirectoryJson.getAsString(), downloadUrlJson.getAsString())) { rs.status(200); if (isVerbose) System.out.println("Success"); return "{ \"status\":\"success\" }"; } } else { if (isVerbose) System.out.println("Not found"); notFound("{ \"error\":404 }"); } return "{ \"error\":\"500\" }"; }); } private static boolean isAuthenticated(Request rq) { String authHeader = rq.headers("Authorization"); if (isVerbose) { System.out.println("Auth Header: " + authHeader); System.out.println("All headers: "); for (String header : rq.headers()) { System.out.print(header + ", "); } System.out.print("\n"); System.out.println("Is authenticated: " + AUTH_TOKENS.containsToken(authHeader)); } return AUTH_TOKENS.containsToken(authHeader); } }