SAS.java 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. /*
  2. * Feel free to copy/use it for your own project.
  3. * Keep in mind that it took me several days/weeks, beers and asperines to make this.
  4. * So be nice, and give me some credit, I won't bite and it won't hurt you.
  5. */
  6. import java.io.IOException;
  7. import java.io.PrintWriter;
  8. import java.sql.ResultSet;
  9. import java.sql.SQLException;
  10. import java.util.HashMap;
  11. import java.util.logging.Level;
  12. import java.util.logging.Logger;
  13. import javax.naming.NamingException;
  14. import javax.servlet.ServletException;
  15. import javax.servlet.annotation.WebServlet;
  16. import javax.servlet.http.HttpServlet;
  17. import javax.servlet.http.HttpServletRequest;
  18. import javax.servlet.http.HttpServletResponse;
  19. import org.json.simple.JSONObject;
  20. import org.json.simple.parser.ParseException;
  21. /**
  22. *
  23. * @author Deben Oldert
  24. */
  25. @WebServlet(urlPatterns = {"/SAS"})
  26. public class SAS extends HttpServlet {
  27. Function function = new Function();
  28. ErrorCode code = new ErrorCode();
  29. int ldapError;
  30. SQL sql;
  31. ResultSet result;
  32. //final Object T3 = new Object();
  33. //final Object T2 = new Object();
  34. //final Object T1 = new Object();
  35. String req;
  36. String reqBody;
  37. int i;
  38. int timeout = 30;
  39. boolean finished = false;
  40. public SAS() throws ClassNotFoundException, SQLException, InstantiationException, IllegalAccessException {
  41. this.sql = (new SQL());
  42. }
  43. /**
  44. * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
  45. * methods.
  46. *
  47. * @param request servlet request
  48. * @param response servlet response
  49. * @throws ServletException if a servlet-specific error occurs
  50. * @throws IOException if an I/O error occurs
  51. * @throws java.sql.SQLException
  52. * @throws java.lang.InstantiationException
  53. * @throws java.lang.IllegalAccessException
  54. * @throws java.lang.ClassNotFoundException
  55. */
  56. protected void processRequest(HttpServletRequest request, HttpServletResponse response)
  57. throws ServletException, IOException, SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException {
  58. response.setContentType("application/json;charset=UTF-8");
  59. }
  60. // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
  61. /**
  62. * Handles the HTTP <code>GET</code> method.
  63. *
  64. * @param request servlet request
  65. * @param response servlet response
  66. * @throws ServletException if a servlet-specific error occurs
  67. * @throws IOException if an I/O error occurs
  68. */
  69. @Override
  70. protected void doGet(HttpServletRequest request, HttpServletResponse response)
  71. throws ServletException, IOException {
  72. response.setContentType("application/json;charset=UTF-8");
  73. JSONObject json = new JSONObject();
  74. json.put("result", 900);
  75. json.put("resultText", code.getCodeText(900));
  76. try (PrintWriter out = response.getWriter()) {
  77. out.println(json);
  78. }
  79. }
  80. @Override
  81. protected void doPost(HttpServletRequest request, HttpServletResponse response)
  82. throws ServletException, IOException {
  83. response.setContentType("application/json;charset=UTF-8");
  84. try {
  85. reqBody = function.getBody(request.getReader());
  86. HashMap json = function.defragJSON(reqBody);
  87. LDAP ldap = new LDAP((String) json.get("username"), (String) json.get("password"));
  88. String requestId = (String) json.get("requestId");
  89. String answer;
  90. req = requestId;
  91. System.out.println("============= "+req+" ============= << SAS");
  92. System.out.print(json);
  93. System.out.println("********************************************************");
  94. switch((String) json.get("function")) {
  95. case "authenticate":
  96. sql.threadUpdate(requestId, "birth", null);
  97. System.out.println("##### SAS >> AUTHENTICATE");
  98. String tmpBody;
  99. JSONObject tmpJSON = new JSONObject();
  100. tmpJSON.put("function", "authenticate");
  101. tmpJSON.put("requestId", requestId);
  102. tmpJSON.put("username", (String) json.get("username"));
  103. tmpJSON.put("password", (String) json.get("password"));
  104. tmpBody = tmpJSON.toJSONString();
  105. HashMap jsonAnswer = function.defragJSON(function.makeRequest("POST", function.getURL("APS"), tmpBody));
  106. if(jsonAnswer.get("result").equals("0")) {
  107. if(jsonAnswer.containsKey("serviceType")) {
  108. System.out.println("SENDING PUSH NOTIFICATION");
  109. String[] info = {
  110. "deviceId",
  111. "serviceNumber",
  112. "serviceType",
  113. "notificationId",
  114. "apiKey"};
  115. HashMap userInfo = ldap.getUserInfo(info);
  116. JSONObject exData = new JSONObject();
  117. exData.put("requestId", requestId);
  118. JSONObject data = new JSONObject();
  119. data.put("data", exData);
  120. data.put("to", userInfo.get("notificationId"));
  121. answer = function.makeRequest("POST", function.getURL(jsonAnswer.get("serviceType").toString()), data.toJSONString());
  122. sql.threadUpdate(requestId, "request", answer);
  123. for(i = 1; i<=timeout && !finished; i++) {
  124. result = sql.stmt.executeQuery("SELECT `state`, `data` FROM `thread` WHERE `threadId`='"+requestId+"'");
  125. if(result.first()) {
  126. if(result.getString("state").equals("reply")) {
  127. if(result.getString("data") == null || result.getString("data").equals("") || result.getString("data").equals("null")) {
  128. outputResult(response, 601, requestId, null, true);
  129. finished = true;
  130. } else {
  131. HashMap sqlResult = function.defragJSON(result.getString("data"));
  132. if(sqlResult.get("confirmation").equals("approved")) {
  133. outputResult(response, 0, requestId, function.defragJSON(result.getString("data")), false);
  134. }
  135. else {
  136. outputResult(response, 1, requestId, function.defragJSON(result.getString("data")), false);
  137. }
  138. sql.threadUpdate(requestId, "done", "{\"result\":0}");
  139. finished = true;
  140. break;
  141. }
  142. }
  143. else {
  144. System.out.println("WAITING "+i+" SECONDS");
  145. Thread.sleep(1000);
  146. }
  147. }
  148. else {
  149. outputResult(response, 602, requestId, null, true);
  150. finished = true;
  151. break;
  152. }
  153. result = null;
  154. }
  155. System.out.println("WAITED "+i+" SECONDS");
  156. if(i > timeout) {
  157. outputResult(response, 950, requestId, null, true);
  158. }
  159. } else {
  160. outputResult(response, 2, requestId, null, false);
  161. System.out.println("SENDING EMAIL");
  162. tmpJSON = new JSONObject();
  163. tmpJSON.put("function", "sendmail");
  164. tmpJSON.put("requestId", requestId);
  165. tmpJSON.put("username", (String) json.get("username"));
  166. tmpJSON.put("password", (String) json.get("password"));
  167. tmpJSON.put("subject", "Enrollment for TFA");
  168. tmpJSON.put("text", "Dear Employee,<br><br>"
  169. + "In order to login to our VPN server you need to download our app to verify your connection request.<br><br>"
  170. + "For Android:<br><ol>"
  171. + "<li>Download and install our app at: "+function.getURL("STORE")+"</li>"
  172. + "<li>Start it: "+function.getURL("APP")+"</li></ol>"
  173. + "We currently don't support iPhone. Sorry for the inconvience.<br><br>"
  174. + "Your registration code is: <b>"+function.genRegCode(json.get("username").toString())+"</b>.<br><br>"
  175. + "Regards,<br>"
  176. + "The IT Security department");
  177. tmpBody = tmpJSON.toJSONString();
  178. jsonAnswer = function.defragJSON(function.makeRequest("POST", function.getURL("APS"), tmpBody));
  179. System.out.println(jsonAnswer);
  180. if(jsonAnswer.get("result").equals("0")) {
  181. String state;
  182. String data;
  183. for(i=1; i<=300 && !finished; i++) {
  184. result = sql.stmt.executeQuery("SELECT state,data FROM thread WHERE threadId='"+requestId+"'");
  185. if(result.first()) {
  186. state = result.getString("state");
  187. data = result.getString("data");
  188. if(state.equals("request")) {
  189. System.out.println("Got response");
  190. sql.threadUpdate(requestId, "reply", function.makeRequest("POST", function.getURL("APS"), data));
  191. finished = true;
  192. } else {
  193. System.out.println("WAITING "+i+" SECONDS");
  194. Thread.sleep(1000);
  195. }
  196. } else {
  197. outputResult(response, 602, requestId, null, true);
  198. finished = true;
  199. }
  200. }
  201. System.out.println("WAITED "+i+" SECONDS");
  202. if(i > 300) {
  203. outputResult(response, 950, requestId, null, true);
  204. }
  205. } else {
  206. outputResult(response, (int) jsonAnswer.get("result"), requestId, null, true);
  207. }
  208. }
  209. } else {
  210. outputResult(response, Integer.parseInt((String)jsonAnswer.get("result")), requestId, null, true);
  211. }
  212. break;
  213. case "register":
  214. System.out.println("##### SAS >> REGISTER");
  215. if((ldapError = ldap.userCheck()) == 0) {
  216. String username = json.get("username").toString();
  217. String regCode = json.get("registerCode").toString();
  218. if(username != null && regCode != null) {
  219. if(function.checkRegCode(regCode, username)) {
  220. System.out.println("REGCODE PASSED");
  221. sql.threadUpdate(req, "request", reqBody);
  222. String state;
  223. HashMap data;
  224. for(i=1; i<=10; i++) {
  225. System.out.println("LOOP STARTED");
  226. result = sql.stmt.executeQuery("SELECT state,data FROM thread WHERE threadId='"+requestId+"'");
  227. if(result.first()) {
  228. System.out.println("GOT SQL");
  229. state = result.getString("state");
  230. System.out.println(state);
  231. if(state.equals("reply")) {
  232. System.out.println("Got final response");
  233. data = function.defragJSON(result.getString("data"));
  234. outputResult(response, Integer.parseInt(data.get("result").toString()), requestId, null, true);
  235. System.out.println("OUTPUT");
  236. return;
  237. } else {
  238. System.out.println("REG WAITING "+i+" SECONDS");
  239. Thread.sleep(1000);
  240. }
  241. } else {
  242. outputResult(response, 602, requestId, null, true);
  243. }
  244. }
  245. if(i > 10) {
  246. outputResult(response, 950, requestId, null, true);
  247. }
  248. }
  249. else {
  250. outputResult(response, 5, requestId, null, true);
  251. }
  252. }
  253. else {
  254. outputResult(response, 560, requestId, null, true);
  255. }
  256. } else {
  257. outputResult(response, ldapError, requestId, null, true);
  258. }
  259. break;
  260. case "confirm":
  261. System.out.println("##### SAS >> CONFIRM");
  262. sql.threadUpdate(requestId, "reply", reqBody);
  263. String state;
  264. HashMap data;
  265. for(i=1; i<=10; i++){
  266. result = sql.stmt.executeQuery("SELECT state,data FROM thread WHERE threadId='"+requestId+"'");
  267. if(result.first()) {
  268. System.out.println("GOT SQL");
  269. state = result.getString("state");
  270. System.out.println(state);
  271. if(state.equals("done")) {
  272. System.out.println("Got final response");
  273. data = function.defragJSON(result.getString("data"));
  274. System.out.println(data);
  275. outputResult(response, Integer.parseInt(data.get("result").toString()), requestId, null, true);
  276. System.out.println("OUTPUT");
  277. return;
  278. } else {
  279. System.out.println("REG WAITING "+i+" SECONDS");
  280. Thread.sleep(1000);
  281. }
  282. } else {
  283. outputResult(response, 602, requestId, null, true);
  284. }
  285. }
  286. if(i > 10) {
  287. outputResult(response, 950, requestId, null, true);
  288. }
  289. outputResult(response, 0, requestId, null, false);
  290. break;
  291. case "clean":
  292. sql.clean();
  293. outputResult(response, 0, requestId, null, false);
  294. break;
  295. default:
  296. outputResult(response, 555, requestId, null, true);
  297. }
  298. } catch (ParseException | NamingException | SQLException | ClassNotFoundException | InterruptedException ex) {
  299. Logger.getLogger(SAS.class.getName()).log(Level.SEVERE, null, ex);
  300. }
  301. }
  302. private void outputResult(HttpServletResponse response, int errorCode, String requestId, HashMap extra, boolean terminate) throws IOException, SQLException, ClassNotFoundException {
  303. JSONObject array = new JSONObject();
  304. array.put("result", errorCode);
  305. array.put("resultText", code.getCodeText(errorCode));
  306. array.put("requestId", requestId);
  307. if(extra != null) {
  308. if(extra.containsKey("confirmation")) {
  309. array.put("confirmation", extra.get("confirmation"));
  310. } else {
  311. JSONObject userinfo = new JSONObject();
  312. extra.forEach((k, v) -> userinfo.put(k, v));
  313. array.put("userInfo", userinfo);
  314. }
  315. }
  316. System.out.println("============= "+req+" ============= >> SAS");
  317. System.out.print(array);
  318. System.out.println("********************************************************");
  319. if(terminate) {
  320. sql.threadUpdate(requestId, "terminate", null);
  321. }
  322. try (PrintWriter out = response.getWriter()) {
  323. out.println(array);
  324. }
  325. }
  326. }