Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package pl.codecool.guestbook;
- import com.sun.net.httpserver.HttpExchange;
- import com.sun.net.httpserver.HttpHandler;
- import java.io.*;
- import java.net.HttpCookie;
- import java.net.URLDecoder;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.ResultSet;
- import java.sql.Statement;
- import java.util.HashMap;
- import java.util.Map;
- import java.util.UUID;
- public class Login implements HttpHandler {
- @Override
- public void handle(HttpExchange httpExchange) throws IOException {
- String response = "";
- String cookieStr = httpExchange.getRequestHeaders().getFirst("Cookie");
- HttpCookie cookie;
- System.out.println(cookieStr);
- if (cookieStr != null) { // Cookie already exists
- cookie = HttpCookie.parse(cookieStr).get(0);
- System.out.println(cookie.toString());
- String method = httpExchange.getRequestMethod();
- System.out.println(method + "1");
- if(method.equals("GET")) {
- response = "<html><body>" +
- "<h1>" + getLoginFromDatabase(cookie) + "</h1>" +
- "<form method=\"POST\">\n<br>" +
- "<input type=\"submit\" value=\"Logout\">\n" +
- "</form> " +
- "</body></html>";
- } else if(method.equals("POST")) {
- httpExchange.getResponseHeaders().add("Set-cookie", "cookie0=" + cookie.getValue() + "; Max-Age=0");
- }
- } else { // Create a new cookie
- String method = httpExchange.getRequestMethod();
- System.out.println(method + "2");
- if(method.equals("GET")){
- response = "<html><body>" +
- "<form method=\"POST\">\n<br>" +
- " Login :<br>\n" +
- " <input type=\"text\" name=\"login\">\n" +
- " <br>\n" +
- " Password:<br>\n" +
- " <input type=\"password\" name=\"password\" >\n" +
- " <br><br>\n" +
- " <input type=\"submit\" value=\"Submit\">\n" +
- "</form> " +
- "</body></html>";
- }
- // If the form was submitted, retrieve it's content.
- else if(method.equals("POST")){
- InputStreamReader isr = new InputStreamReader(httpExchange.getRequestBody(), "utf-8");
- BufferedReader br = new BufferedReader(isr);
- String formData = br.readLine();
- // System.out.println(formData);
- Map inputs = parseFormData(formData);
- String login = String.valueOf(inputs.get("login"));
- String sessionId = createSessionId();
- System.out.println(sessionId);
- saveRecordToDatabase(sessionId, login);
- httpExchange.getResponseHeaders().add("User-agent", "HTTPTool/1.0");
- httpExchange.getResponseHeaders().add("Set-cookie", "cookie0=" + sessionId + "; Max-Age=360");
- }
- }
- httpExchange.sendResponseHeaders(200, response.length());
- OutputStream os = httpExchange.getResponseBody();
- os.write(response.getBytes());
- os.close();
- }
- private static Map<String, String> parseFormData(String formData) throws UnsupportedEncodingException {
- Map<String, String> map = new HashMap<>();
- String[] pairs = formData.split("&");
- for(String pair : pairs){
- String[] keyValue = pair.split("=");
- // We have to decode the value because it's urlencoded. see: https://en.wikipedia.org/wiki/POST_(HTTP)#Use_for_submitting_web_forms
- String value = new URLDecoder().decode(keyValue[1], "UTF-8");
- map.put(keyValue[0], value);
- }
- return map;
- }
- private static String createSessionId() {
- return UUID.randomUUID().toString();
- }
- private void saveRecordToDatabase(String sessionId, String login) {
- Statement stmt = null;
- try {
- Connection c = DriverManager.getConnection("jdbc:sqlite:src/main/java/pl/codecool/guestbook/cookies.db");
- c.setAutoCommit(false);
- stmt = c.createStatement();
- stmt.executeUpdate("INSERT INTO cookies (id, login)"
- + " VALUES ('" + sessionId + "', '" + login + "');");
- stmt.close();
- c.commit();
- } catch ( Exception e ) {
- System.err.println( e.getClass().getName() + ": " + e.getMessage() );
- }
- }
- private static String getLoginFromDatabase(HttpCookie cookie) {
- String login = "";
- Connection c = null;
- Statement stmt = null;
- ResultSet rs = null;
- Record.clearRecords();
- try {
- Class.forName("org.sqlite.JDBC");
- c = DriverManager.getConnection("jdbc:sqlite:src/main/java/pl/codecool/guestbook/cookies.db");
- c.setAutoCommit(false);
- stmt = c.createStatement();
- rs = stmt.executeQuery("SELECT login FROM cookies WHERE id = '" + cookie.getValue() + "';");
- while (rs.next()) {
- login = rs.getString("login");
- }
- stmt.close();
- c.commit();
- c.close();
- } catch (Exception e) {
- System.err.println(e.getClass().getName() + ": " + e.getMessage());
- }
- return login;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement