Advertisement
Guest User

Untitled

a guest
Nov 14th, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 5.59 KB | None | 0 0
  1. package pl.codecool.guestbook;
  2.  
  3. import com.sun.net.httpserver.HttpExchange;
  4. import com.sun.net.httpserver.HttpHandler;
  5.  
  6. import java.io.*;
  7. import java.net.HttpCookie;
  8. import java.net.URLDecoder;
  9. import java.sql.Connection;
  10. import java.sql.DriverManager;
  11. import java.sql.ResultSet;
  12. import java.sql.Statement;
  13. import java.util.HashMap;
  14. import java.util.Map;
  15. import java.util.UUID;
  16.  
  17. public class Login implements HttpHandler {
  18.  
  19.     @Override
  20.     public void handle(HttpExchange httpExchange) throws IOException {
  21.         String response = "";
  22.         String cookieStr = httpExchange.getRequestHeaders().getFirst("Cookie");
  23.         HttpCookie cookie;
  24.         System.out.println(cookieStr);
  25.  
  26.  
  27.         if (cookieStr != null) {  // Cookie already exists
  28.             cookie = HttpCookie.parse(cookieStr).get(0);
  29.             System.out.println(cookie.toString());
  30.             String method = httpExchange.getRequestMethod();
  31.             System.out.println(method + "1");
  32.  
  33.             if(method.equals("GET")) {
  34.                 response = "<html><body>" +
  35.                         "<h1>" + getLoginFromDatabase(cookie) + "</h1>" +
  36.                         "<form method=\"POST\">\n<br>" +
  37.                         "<input type=\"submit\" value=\"Logout\">\n" +
  38.                         "</form> " +
  39.                         "</body></html>";
  40.             } else if(method.equals("POST")) {
  41.                 httpExchange.getResponseHeaders().add("Set-cookie", "cookie0=" + cookie.getValue() + "; Max-Age=0");
  42.             }
  43.  
  44.         } else { // Create a new cookie
  45.             String method = httpExchange.getRequestMethod();
  46.             System.out.println(method + "2");
  47.  
  48.             if(method.equals("GET")){
  49.  
  50.                 response = "<html><body>" +
  51.                         "<form method=\"POST\">\n<br>" +
  52.                         "  Login :<br>\n" +
  53.                         "  <input type=\"text\" name=\"login\">\n" +
  54.                         "  <br>\n" +
  55.                         "  Password:<br>\n" +
  56.                         "  <input type=\"password\" name=\"password\" >\n" +
  57.                         "  <br><br>\n" +
  58.                         "  <input type=\"submit\" value=\"Submit\">\n" +
  59.                         "</form> " +
  60.                         "</body></html>";
  61.             }
  62.  
  63.             // If the form was submitted, retrieve it's content.
  64.              else if(method.equals("POST")){
  65.                 InputStreamReader isr = new InputStreamReader(httpExchange.getRequestBody(), "utf-8");
  66.                 BufferedReader br = new BufferedReader(isr);
  67.                 String formData = br.readLine();
  68.  
  69. //                System.out.println(formData);
  70.                 Map inputs = parseFormData(formData);
  71.  
  72.                 String login = String.valueOf(inputs.get("login"));
  73.  
  74.  
  75.                 String sessionId = createSessionId();
  76.                 System.out.println(sessionId);
  77.                
  78.  
  79.                 saveRecordToDatabase(sessionId, login);
  80.                 httpExchange.getResponseHeaders().add("User-agent", "HTTPTool/1.0");
  81.                 httpExchange.getResponseHeaders().add("Set-cookie", "cookie0=" + sessionId + "; Max-Age=360");
  82.             }
  83.         }
  84.  
  85.         httpExchange.sendResponseHeaders(200, response.length());
  86.         OutputStream os = httpExchange.getResponseBody();
  87.         os.write(response.getBytes());
  88.         os.close();
  89.     }
  90.  
  91.     private static Map<String, String> parseFormData(String formData) throws UnsupportedEncodingException {
  92.         Map<String, String> map = new HashMap<>();
  93.         String[] pairs = formData.split("&");
  94.         for(String pair : pairs){
  95.             String[] keyValue = pair.split("=");
  96.             // We have to decode the value because it's urlencoded. see: https://en.wikipedia.org/wiki/POST_(HTTP)#Use_for_submitting_web_forms
  97.             String value = new URLDecoder().decode(keyValue[1], "UTF-8");
  98.             map.put(keyValue[0], value);
  99.         }
  100.         return map;
  101.     }
  102.  
  103.     private static String createSessionId() {
  104.         return UUID.randomUUID().toString();
  105.     }
  106.  
  107.     private void saveRecordToDatabase(String sessionId, String login) {
  108.  
  109.         Statement stmt = null;
  110.  
  111.         try {
  112.             Connection c = DriverManager.getConnection("jdbc:sqlite:src/main/java/pl/codecool/guestbook/cookies.db");
  113.             c.setAutoCommit(false);
  114.  
  115.             stmt = c.createStatement();
  116.  
  117.             stmt.executeUpdate("INSERT INTO cookies (id, login)"
  118.                     + " VALUES ('" + sessionId + "', '" + login + "');");
  119.  
  120.             stmt.close();
  121.             c.commit();
  122.         } catch ( Exception e ) {
  123.             System.err.println( e.getClass().getName() + ": " + e.getMessage() );
  124.         }
  125.     }
  126.  
  127.     private static String getLoginFromDatabase(HttpCookie cookie) {
  128.  
  129.         String login = "";
  130.  
  131.         Connection c = null;
  132.         Statement stmt = null;
  133.         ResultSet rs = null;
  134.         Record.clearRecords();
  135.         try {
  136.  
  137.             Class.forName("org.sqlite.JDBC");
  138.             c = DriverManager.getConnection("jdbc:sqlite:src/main/java/pl/codecool/guestbook/cookies.db");
  139.             c.setAutoCommit(false);
  140.  
  141.             stmt = c.createStatement();
  142.  
  143.  
  144.             rs = stmt.executeQuery("SELECT login FROM cookies WHERE id = '" + cookie.getValue() + "';");
  145.  
  146.             while (rs.next()) {
  147.  
  148.                 login = rs.getString("login");
  149.             }
  150.             stmt.close();
  151.             c.commit();
  152.             c.close();
  153.  
  154.         } catch (Exception e) {
  155.             System.err.println(e.getClass().getName() + ": " + e.getMessage());
  156.         }
  157.         return login;
  158.     }
  159.  
  160. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement