package Store; import Server.JSONMessage; import com.corundumstudio.socketio.listener.DataListener; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Map; public class User { private int id; private final String userName; private final String password; public User(String userName, String password) { this.userName = userName; this.password = password; } public boolean save() throws SQLException { if (!checkUniqueUsername(userName)) { return false; } String sql = "INSERT INTO User (userName, password) VALUES (?, ?)"; PreparedStatement statement = ConnectionHandler.connection.prepareStatement(sql); statement.setString(1, userName); statement.setString(2, password); statement.executeUpdate(); return true; } private boolean checkUniqueUsername(String userName) throws SQLException { String sql = "SELECT * FROM User WHERE userName = '" + userName + "'"; Statement statement = ConnectionHandler.connection.createStatement(); ResultSet response = statement.executeQuery(sql); while (response.next()) { return false; } return true; } public boolean login() throws SQLException { String sql = "SELECT * FROM User WHERE userName = '" + this.userName + "' AND password = '" + this.password + "'"; Statement statement = ConnectionHandler.connection.createStatement(); boolean loggedIn = false; ResultSet response = statement.executeQuery(sql); while (response.next()) { this.id = response.getInt("ID"); loggedIn = true; } return loggedIn; } public static void createTable() throws SQLException { String sql = "CREATE TABLE IF NOT EXISTS User (" + "ID INTEGER NOT NULL PRIMARY KEY," + "userName TEXT NOT NULL," + "password text NOT NULL" + ");"; Statement statement = ConnectionHandler.connection.createStatement(); statement.execute(sql); } public static DataListener signUpHandler() { return ((client, data, ackSender) -> { Thread t = new Thread(() -> { Map d = data.getData(); User user = new User(d.get("userName"), d.get("password")); try { if (user.save()) { client.sendEvent("signedUp"); } else { client.sendEvent("usernameTaken"); client.sendEvent("signUpFailed"); } } catch (SQLException e) { client.sendEvent("signUpFailed"); System.out.println(e.getMessage()); } }); t.start(); t.join(); }); } public static DataListener loginHandler() { return ((client, data, ackSender) -> { Thread t = new Thread(() -> { Map d = data.getData(); User user = new User(d.get("userName"), d.get("password")); try { user.login(); } catch (SQLException e) { System.out.println(e.getMessage()); } try { if (user.login()) { client.sendEvent("loggedIn", user.id); } else { client.sendEvent("loginFailed"); } } catch (SQLException e) { throw new RuntimeException(e); } }); t.start(); t.join(); }); } public String toJSON() { return "{" + "\"id\": " + id + "," + "\"userName\": " + userName + "," + "\"password\": " + password + " }"; } }