SAS.java 20 KB

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