Skip to main content
Title improved, minor fixes in the question body, tags "jdbc" and "authentication" added
Source Link

Small program that register a user to an JavaFX app with User Authentication and SQL database or logs them in based on the correct credentialsPersistence

This JavaFX program is just supposesupposed to allow a user to register a username and password and then have it stored in an SQL database. 

There's been some criticism that it's not clean, readable or maintainable, but it still seems to work, so I was looking for criticism from people that are actually in the Software development industry and not just high school teachers.

Small program that register a user to an SQL database or logs them in based on the correct credentials

This JavaFX program is just suppose to allow a user to register a username and password and then have it stored in an SQL database. There's been some criticism that it's not clean, readable or maintainable, but it still seems to work so I was looking for criticism from people that are actually in the Software development industry and not just high school teachers.

JavaFX app with User Authentication and SQL Persistence

This JavaFX program is just supposed to allow a user to register a username and password and then have it stored in an SQL database. 

There's been some criticism that it's not clean, readable or maintainable, but it still seems to work, so I was looking for criticism from people that are actually in the Software development industry and not just high school teachers.

Became Hot Network Question
edited title
Link
Soco
  • 153
  • 4

Is this code readable and maintainable? Small program that register a user to an SQL database or logs them in based on the correct credentials

edited tags
Source Link
Reinderien
  • 71.1k
  • 5
  • 76
  • 256
public class MainController {
    // region Variables
    @FXML
    private Label formText, welcomeText;
    @FXML
    private Button login, signup;
    @FXML
    private TextField username, email, password, confirmPassword;
    @FXML
    private Button forgotPassword, formButton, resetPasswordButton;
    @FXML
    private AnchorPane formPage, dashboardPage;
    // endregion

    // region Form
    @FXML
    private void ChangeForm() {
        ObservableList<String> shortLogin = login.getStyleClass(), shortSignUp = signup.getStyleClass();
        if (shortLogin.contains("active")) { // switching to signup
            formText.setText("Signup Form");
            shortLogin.remove("active");
            shortLogin.add("notActive");
            shortSignUp.remove("notActive");
            shortSignUp.add("active");
            confirmPassword.setVisible(true);
            formButton.setText("Sign Up");
            forgotPassword.setVisible(false);
        } else /*if (shortSignUp.contains("active"))*/ { // switching to login
            formText.setText("Login Form");
            formButton.setText("Login");
            shortSignUp.remove("active");
            if(!shortSignUp.contains("notActive"))
                shortSignUp.add("notActive");
            shortLogin.remove("notActive");
            shortLogin.add("active");
            confirmPassword.setVisible(false);
            formButton.setText("Login");
            password.setPromptText("Password:");
            forgotPassword.setVisible(true);
        }
        ClearForm();
    }

    @FXML
    private void FormSubmit() {
        if (ValidForm()) {
            try {
                String name = (signup.getStyleClass().contains("active")) ? SQLUtils.Register(username.getText(), password.getText(), email.getText()) : SQLUtils.Login(username.getText(), password.getText(), email.getText());
                formPage.setVisible(false);
                dashboardPage.setVisible(true);
                welcomeText.setText("Welcome, " + name);
                ClearForm();
            } catch (Exception ignored) {
                ErrorAlert(Alert.AlertType.ERROR, "SQL Error", "Error Retrieving SQL Information from MainController", "There was an error retrieving the SQL information, or that user doesn't exist.");
            }
        }
    }
    
    @FXML
    private void Forgot() {
        forgotPassword.setVisible(false);
        resetPasswordButton.setVisible(true);
        forgotPassword.setVisible(true);
        formText.setText("Forgot Password");
        formButton.setVisible(false);
        password.setPromptText("Enter New Password:");
        
        ObservableList<String> shortLogin = login.getStyleClass();
        if(shortLogin.contains("active") && !shortLogin.contains("notActive")) {
            shortLogin.remove("active");
            shortLogin.add("notActive");
        }
    }
    @FXML
    private void ResetPassword() {
        if(ValidForm()) {
            resetPasswordButton.setVisible(false);
            formButton.setVisible(true);
            forgotPassword.setVisible(true);
            formButton.setVisible(true);
            password.setPromptText("Password:");
            
            ObservableList<String> shortLogin = login.getStyleClass();
            formText.setText("Login Form");
            shortLogin.remove("notActive");
            shortLogin.add("active");
            SQLUtils.ResetPassword(username.getText(), password.getText(), email.getText());
            ClearForm();
        }
    }

    // endregion
    // region Utils
    private void ClearForm() {
        username.clear();
        email.clear();
        password.clear();
        confirmPassword.clear();
    }
    
    private boolean ValidForm() {       
        String emailRegex = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9._]+\\.[a-zA-Z]{2,6}$";
        String passwordRegex = "^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[/~`!@#$%^&*()_+{};:',<.>? =]).{8,}$";

        if (username.getText().isEmpty() || email.getText().isEmpty() || password.getText().isEmpty() || (signup.getStyleClass().contains("active") && confirmPassword.getText().isEmpty())) {
            ErrorAlert(Alert.AlertType.INFORMATION, "Form Validation", "Invalid Fields", "All Fields Must Be Filled In");
            return false;
        } else if (!Pattern.compile(emailRegex).matcher(email.getText()).matches()) {
            ErrorAlert(Alert.AlertType.INFORMATION, "Form Validation", "Invalid Email", "Please Enter A Valid Email That Contains An '@' And A '.com'");
            return false;
        } else if (!Pattern.compile(passwordRegex).matcher(password.getText()).matches()) {
            ErrorAlert(Alert.AlertType.INFORMATION, "Form Validation", "Invalid Password", "Please Enter A Valid Password That Contains At Least 8 Characters, 1 Uppercase, 1 Lowercase, 1 Number, and 1 Special Character");
            return false;
        } else if (signup.getStyleClass().contains("active") && !password.getText().equals(confirmPassword.getText())) {
            ErrorAlert(Alert.AlertType.INFORMATION, "Form Validation", "Passwords Must Match", "Password And Confirm Password Must Match");
            return false;
        } else if (!SQLUtils.ValidInfo(username.getText(), password.getText(), email.getText())) {
            ErrorAlert(Alert.AlertType.ERROR, "Invalid Info", "That User Does Not Exist", "Please enter valid information for a user that does already exist.");
            return false;
        }
        return true;
    }
    public static void ErrorAlert(Alert.AlertType type, String title, String headerText, String contentText) {
        Alert alert = new Alert(type);
        alert.setTitle(title);
        alert.setHeaderText(headerText);
        alert.setContentText(contentText);
        alert.showAndWait();
    }
    @FXML
    private void LogOut() {
        formPage.setVisible(true);
        dashboardPage.setVisible(false);
        welcomeText.setText("Welcome, NAME HERE");
    }

    // endregion
    // region Window Settings
    @FXML
    private void Minimize(ActionEvent event) {
        ((Stage) ((Button) event.getSource()).getScene().getWindow()).setIconified(true);
    }

    @FXML
    private void Close() {
        System.exit(0);
    }

    // endregion
}

public class SQLUtils {
    // region Main Methods
    public static String Login(String username, String password, String email) {
        String sql = "select * from users_table where username = ? and password = ? and email = ?";
        RunSQL(sql, username, password, email, true);
        return username;
    }
    public static String Register(String username, String password, String email) {
        String sql = "insert into users_table (username, password, email) values (?, ?, ?)";
        RunSQL(sql, username, password, email, false);
        return username;
    }
    public static void ResetPassword(String username, String newPassword, String email) {
        String sql = "update users_table set password=? where username=? and email=?;";
        RunSQL(sql, newPassword, username, email, false);
    }
    // endregion
    // region Utils
    private static Connection ConnectDB() {
        try {
            return DriverManager.getConnection("jdbc:mysql://localhost:3306/login_and_register", "root", "password");
        } catch (Exception ignored) {
            MainController.ErrorAlert(Alert.AlertType.ERROR, "SQL Error", "Error Retrieving SQL Information", "Information could not be retrieved");
        }
        return null;
    }
    public static boolean ValidInfo(String username, String password, String email) {
        String sql = "select * from users_table where username = ? and password = ? and email = ?";
        Connection connect = ConnectDB();
        if (connect == null)
            return false;
        
        try (PreparedStatement prepared = connect.prepareStatement(sql)) {
            prepared.setString(1, username);
            prepared.setString(2, password);
            prepared.setString(3, email);
            prepared.executeQuery();
            System.out.println("working");
            // FORM ALWAYS RESULTS IN WORKING, EVEN WHEN USER IS INVALID, DOES NOT ADD TO TABLE THO
            return true;
        } catch (Exception ignored) {
            MainController.ErrorAlert(Alert.AlertType.ERROR, "Error", "Error Running SQL", "There was an error running the SQL information, or that user doesn't exist.");
        }
        System.out.println("not working");
        return false;
    }
    private static void RunSQL(String sql, String username, String password, String email, boolean query) {
        Connection connect = ConnectDB();
        if (connect == null)
            return;
        
        try (PreparedStatement prepared = connect.prepareStatement(sql)) {
            prepared.setString(1, username);
            prepared.setString(2, password);
            prepared.setString(3, email);
            if (query)
                prepared.executeQuery();
            else
                prepared.executeUpdate();
        } catch (SQLException ignored) {
            MainController.ErrorAlert(Alert.AlertType.ERROR, "SQL Error", "Error Retrieving SQL Information, from RUNSQL", "There was an error retrieving the SQL information.");
        } catch (Exception ignored) {
            MainController.ErrorAlert(Alert.AlertType.ERROR, "Error", "Error Running SQL", "There was an error running the SQL information, or that user doesn't exist.");
        }
    }
    // endregion
}
public class MainController {
    // region Variables
    @FXML
    private Label formText, welcomeText;
    @FXML
    private Button login, signup;
    @FXML
    private TextField username, email, password, confirmPassword;
    @FXML
    private Button forgotPassword, formButton, resetPasswordButton;
    @FXML
    private AnchorPane formPage, dashboardPage;
    // endregion

    // region Form
    @FXML
    private void ChangeForm() {
        ObservableList<String> shortLogin = login.getStyleClass(), shortSignUp = signup.getStyleClass();
        if (shortLogin.contains("active")) { // switching to signup
            formText.setText("Signup Form");
            shortLogin.remove("active");
            shortLogin.add("notActive");
            shortSignUp.remove("notActive");
            shortSignUp.add("active");
            confirmPassword.setVisible(true);
            formButton.setText("Sign Up");
            forgotPassword.setVisible(false);
        } else /*if (shortSignUp.contains("active"))*/ { // switching to login
            formText.setText("Login Form");
            formButton.setText("Login");
            shortSignUp.remove("active");
            if(!shortSignUp.contains("notActive"))
                shortSignUp.add("notActive");
            shortLogin.remove("notActive");
            shortLogin.add("active");
            confirmPassword.setVisible(false);
            formButton.setText("Login");
            password.setPromptText("Password:");
            forgotPassword.setVisible(true);
        }
        ClearForm();
    }

    @FXML
    private void FormSubmit() {
        if (ValidForm()) {
            try {
                String name = (signup.getStyleClass().contains("active")) ? SQLUtils.Register(username.getText(), password.getText(), email.getText()) : SQLUtils.Login(username.getText(), password.getText(), email.getText());
                formPage.setVisible(false);
                dashboardPage.setVisible(true);
                welcomeText.setText("Welcome, " + name);
                ClearForm();
            } catch (Exception ignored) {
                ErrorAlert(Alert.AlertType.ERROR, "SQL Error", "Error Retrieving SQL Information from MainController", "There was an error retrieving the SQL information, or that user doesn't exist.");
            }
        }
    }
    
    @FXML
    private void Forgot() {
        forgotPassword.setVisible(false);
        resetPasswordButton.setVisible(true);
        forgotPassword.setVisible(true);
        formText.setText("Forgot Password");
        formButton.setVisible(false);
        password.setPromptText("Enter New Password:");
        
        ObservableList<String> shortLogin = login.getStyleClass();
        if(shortLogin.contains("active") && !shortLogin.contains("notActive")) {
            shortLogin.remove("active");
            shortLogin.add("notActive");
        }
    }
    @FXML
    private void ResetPassword() {
        if(ValidForm()) {
            resetPasswordButton.setVisible(false);
            formButton.setVisible(true);
            forgotPassword.setVisible(true);
            formButton.setVisible(true);
            password.setPromptText("Password:");
            
            ObservableList<String> shortLogin = login.getStyleClass();
            formText.setText("Login Form");
            shortLogin.remove("notActive");
            shortLogin.add("active");
            SQLUtils.ResetPassword(username.getText(), password.getText(), email.getText());
            ClearForm();
        }
    }

    // endregion
    // region Utils
    private void ClearForm() {
        username.clear();
        email.clear();
        password.clear();
        confirmPassword.clear();
    }
    
    private boolean ValidForm() {       
        String emailRegex = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9._]+\\.[a-zA-Z]{2,6}$";
        String passwordRegex = "^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[/~`!@#$%^&*()_+{};:',<.>? =]).{8,}$";

        if (username.getText().isEmpty() || email.getText().isEmpty() || password.getText().isEmpty() || (signup.getStyleClass().contains("active") && confirmPassword.getText().isEmpty())) {
            ErrorAlert(Alert.AlertType.INFORMATION, "Form Validation", "Invalid Fields", "All Fields Must Be Filled In");
            return false;
        } else if (!Pattern.compile(emailRegex).matcher(email.getText()).matches()) {
            ErrorAlert(Alert.AlertType.INFORMATION, "Form Validation", "Invalid Email", "Please Enter A Valid Email That Contains An '@' And A '.com'");
            return false;
        } else if (!Pattern.compile(passwordRegex).matcher(password.getText()).matches()) {
            ErrorAlert(Alert.AlertType.INFORMATION, "Form Validation", "Invalid Password", "Please Enter A Valid Password That Contains At Least 8 Characters, 1 Uppercase, 1 Lowercase, 1 Number, and 1 Special Character");
            return false;
        } else if (signup.getStyleClass().contains("active") && !password.getText().equals(confirmPassword.getText())) {
            ErrorAlert(Alert.AlertType.INFORMATION, "Form Validation", "Passwords Must Match", "Password And Confirm Password Must Match");
            return false;
        } else if (!SQLUtils.ValidInfo(username.getText(), password.getText(), email.getText())) {
            ErrorAlert(Alert.AlertType.ERROR, "Invalid Info", "That User Does Not Exist", "Please enter valid information for a user that does already exist.");
            return false;
        }
        return true;
    }
    public static void ErrorAlert(Alert.AlertType type, String title, String headerText, String contentText) {
        Alert alert = new Alert(type);
        alert.setTitle(title);
        alert.setHeaderText(headerText);
        alert.setContentText(contentText);
        alert.showAndWait();
    }
    @FXML
    private void LogOut() {
        formPage.setVisible(true);
        dashboardPage.setVisible(false);
        welcomeText.setText("Welcome, NAME HERE");
    }

    // endregion
    // region Window Settings
    @FXML
    private void Minimize(ActionEvent event) {
        ((Stage) ((Button) event.getSource()).getScene().getWindow()).setIconified(true);
    }

    @FXML
    private void Close() {
        System.exit(0);
    }

    // endregion
}

public class SQLUtils {
    // region Main Methods
    public static String Login(String username, String password, String email) {
        String sql = "select * from users_table where username = ? and password = ? and email = ?";
        RunSQL(sql, username, password, email, true);
        return username;
    }
    public static String Register(String username, String password, String email) {
        String sql = "insert into users_table (username, password, email) values (?, ?, ?)";
        RunSQL(sql, username, password, email, false);
        return username;
    }
    public static void ResetPassword(String username, String newPassword, String email) {
        String sql = "update users_table set password=? where username=? and email=?;";
        RunSQL(sql, newPassword, username, email, false);
    }
    // endregion
    // region Utils
    private static Connection ConnectDB() {
        try {
            return DriverManager.getConnection("jdbc:mysql://localhost:3306/login_and_register", "root", "password");
        } catch (Exception ignored) {
            MainController.ErrorAlert(Alert.AlertType.ERROR, "SQL Error", "Error Retrieving SQL Information", "Information could not be retrieved");
        }
        return null;
    }
    public static boolean ValidInfo(String username, String password, String email) {
        String sql = "select * from users_table where username = ? and password = ? and email = ?";
        Connection connect = ConnectDB();
        if (connect == null)
            return false;
        
        try (PreparedStatement prepared = connect.prepareStatement(sql)) {
            prepared.setString(1, username);
            prepared.setString(2, password);
            prepared.setString(3, email);
            prepared.executeQuery();
            System.out.println("working");
            // FORM ALWAYS RESULTS IN WORKING, EVEN WHEN USER IS INVALID, DOES NOT ADD TO TABLE THO
            return true;
        } catch (Exception ignored) {
            MainController.ErrorAlert(Alert.AlertType.ERROR, "Error", "Error Running SQL", "There was an error running the SQL information, or that user doesn't exist.");
        }
        System.out.println("not working");
        return false;
    }
    private static void RunSQL(String sql, String username, String password, String email, boolean query) {
        Connection connect = ConnectDB();
        if (connect == null)
            return;
        
        try (PreparedStatement prepared = connect.prepareStatement(sql)) {
            prepared.setString(1, username);
            prepared.setString(2, password);
            prepared.setString(3, email);
            if (query)
                prepared.executeQuery();
            else
                prepared.executeUpdate();
        } catch (SQLException ignored) {
            MainController.ErrorAlert(Alert.AlertType.ERROR, "SQL Error", "Error Retrieving SQL Information, from RUNSQL", "There was an error retrieving the SQL information.");
        } catch (Exception ignored) {
            MainController.ErrorAlert(Alert.AlertType.ERROR, "Error", "Error Running SQL", "There was an error running the SQL information, or that user doesn't exist.");
        }
    }
    // endregion
}
public class MainController {
    // region Variables
    @FXML
    private Label formText, welcomeText;
    @FXML
    private Button login, signup;
    @FXML
    private TextField username, email, password, confirmPassword;
    @FXML
    private Button forgotPassword, formButton, resetPasswordButton;
    @FXML
    private AnchorPane formPage, dashboardPage;
    // endregion

    // region Form
    @FXML
    private void ChangeForm() {
        ObservableList<String> shortLogin = login.getStyleClass(), shortSignUp = signup.getStyleClass();
        if (shortLogin.contains("active")) { // switching to signup
            formText.setText("Signup Form");
            shortLogin.remove("active");
            shortLogin.add("notActive");
            shortSignUp.remove("notActive");
            shortSignUp.add("active");
            confirmPassword.setVisible(true);
            formButton.setText("Sign Up");
            forgotPassword.setVisible(false);
        } else /*if (shortSignUp.contains("active"))*/ { // switching to login
            formText.setText("Login Form");
            formButton.setText("Login");
            shortSignUp.remove("active");
            if(!shortSignUp.contains("notActive"))
                shortSignUp.add("notActive");
            shortLogin.remove("notActive");
            shortLogin.add("active");
            confirmPassword.setVisible(false);
            formButton.setText("Login");
            password.setPromptText("Password:");
            forgotPassword.setVisible(true);
        }
        ClearForm();
    }

    @FXML
    private void FormSubmit() {
        if (ValidForm()) {
            try {
                String name = (signup.getStyleClass().contains("active")) ? SQLUtils.Register(username.getText(), password.getText(), email.getText()) : SQLUtils.Login(username.getText(), password.getText(), email.getText());
                formPage.setVisible(false);
                dashboardPage.setVisible(true);
                welcomeText.setText("Welcome, " + name);
                ClearForm();
            } catch (Exception ignored) {
                ErrorAlert(Alert.AlertType.ERROR, "SQL Error", "Error Retrieving SQL Information from MainController", "There was an error retrieving the SQL information, or that user doesn't exist.");
            }
        }
    }
    
    @FXML
    private void Forgot() {
        forgotPassword.setVisible(false);
        resetPasswordButton.setVisible(true);
        forgotPassword.setVisible(true);
        formText.setText("Forgot Password");
        formButton.setVisible(false);
        password.setPromptText("Enter New Password:");
        
        ObservableList<String> shortLogin = login.getStyleClass();
        if(shortLogin.contains("active") && !shortLogin.contains("notActive")) {
            shortLogin.remove("active");
            shortLogin.add("notActive");
        }
    }
    @FXML
    private void ResetPassword() {
        if(ValidForm()) {
            resetPasswordButton.setVisible(false);
            formButton.setVisible(true);
            forgotPassword.setVisible(true);
            formButton.setVisible(true);
            password.setPromptText("Password:");
            
            ObservableList<String> shortLogin = login.getStyleClass();
            formText.setText("Login Form");
            shortLogin.remove("notActive");
            shortLogin.add("active");
            SQLUtils.ResetPassword(username.getText(), password.getText(), email.getText());
            ClearForm();
        }
    }

    // endregion
    // region Utils
    private void ClearForm() {
        username.clear();
        email.clear();
        password.clear();
        confirmPassword.clear();
    }
    
    private boolean ValidForm() {       
        String emailRegex = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9._]+\\.[a-zA-Z]{2,6}$";
        String passwordRegex = "^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[/~`!@#$%^&*()_+{};:',<.>? =]).{8,}$";

        if (username.getText().isEmpty() || email.getText().isEmpty() || password.getText().isEmpty() || (signup.getStyleClass().contains("active") && confirmPassword.getText().isEmpty())) {
            ErrorAlert(Alert.AlertType.INFORMATION, "Form Validation", "Invalid Fields", "All Fields Must Be Filled In");
            return false;
        } else if (!Pattern.compile(emailRegex).matcher(email.getText()).matches()) {
            ErrorAlert(Alert.AlertType.INFORMATION, "Form Validation", "Invalid Email", "Please Enter A Valid Email That Contains An '@' And A '.com'");
            return false;
        } else if (!Pattern.compile(passwordRegex).matcher(password.getText()).matches()) {
            ErrorAlert(Alert.AlertType.INFORMATION, "Form Validation", "Invalid Password", "Please Enter A Valid Password That Contains At Least 8 Characters, 1 Uppercase, 1 Lowercase, 1 Number, and 1 Special Character");
            return false;
        } else if (signup.getStyleClass().contains("active") && !password.getText().equals(confirmPassword.getText())) {
            ErrorAlert(Alert.AlertType.INFORMATION, "Form Validation", "Passwords Must Match", "Password And Confirm Password Must Match");
            return false;
        } else if (!SQLUtils.ValidInfo(username.getText(), password.getText(), email.getText())) {
            ErrorAlert(Alert.AlertType.ERROR, "Invalid Info", "That User Does Not Exist", "Please enter valid information for a user that does already exist.");
            return false;
        }
        return true;
    }
    public static void ErrorAlert(Alert.AlertType type, String title, String headerText, String contentText) {
        Alert alert = new Alert(type);
        alert.setTitle(title);
        alert.setHeaderText(headerText);
        alert.setContentText(contentText);
        alert.showAndWait();
    }
    @FXML
    private void LogOut() {
        formPage.setVisible(true);
        dashboardPage.setVisible(false);
        welcomeText.setText("Welcome, NAME HERE");
    }

    // endregion
    // region Window Settings
    @FXML
    private void Minimize(ActionEvent event) {
        ((Stage) ((Button) event.getSource()).getScene().getWindow()).setIconified(true);
    }

    @FXML
    private void Close() {
        System.exit(0);
    }

    // endregion
}

public class SQLUtils {
    // region Main Methods
    public static String Login(String username, String password, String email) {
        String sql = "select * from users_table where username = ? and password = ? and email = ?";
        RunSQL(sql, username, password, email, true);
        return username;
    }
    public static String Register(String username, String password, String email) {
        String sql = "insert into users_table (username, password, email) values (?, ?, ?)";
        RunSQL(sql, username, password, email, false);
        return username;
    }
    public static void ResetPassword(String username, String newPassword, String email) {
        String sql = "update users_table set password=? where username=? and email=?;";
        RunSQL(sql, newPassword, username, email, false);
    }
    // endregion
    // region Utils
    private static Connection ConnectDB() {
        try {
            return DriverManager.getConnection("jdbc:mysql://localhost:3306/login_and_register", "root", "password");
        } catch (Exception ignored) {
            MainController.ErrorAlert(Alert.AlertType.ERROR, "SQL Error", "Error Retrieving SQL Information", "Information could not be retrieved");
        }
        return null;
    }
    public static boolean ValidInfo(String username, String password, String email) {
        String sql = "select * from users_table where username = ? and password = ? and email = ?";
        Connection connect = ConnectDB();
        if (connect == null)
            return false;
        
        try (PreparedStatement prepared = connect.prepareStatement(sql)) {
            prepared.setString(1, username);
            prepared.setString(2, password);
            prepared.setString(3, email);
            prepared.executeQuery();
            System.out.println("working");
            // FORM ALWAYS RESULTS IN WORKING, EVEN WHEN USER IS INVALID, DOES NOT ADD TO TABLE THO
            return true;
        } catch (Exception ignored) {
            MainController.ErrorAlert(Alert.AlertType.ERROR, "Error", "Error Running SQL", "There was an error running the SQL information, or that user doesn't exist.");
        }
        System.out.println("not working");
        return false;
    }
    private static void RunSQL(String sql, String username, String password, String email, boolean query) {
        Connection connect = ConnectDB();
        if (connect == null)
            return;
        
        try (PreparedStatement prepared = connect.prepareStatement(sql)) {
            prepared.setString(1, username);
            prepared.setString(2, password);
            prepared.setString(3, email);
            if (query)
                prepared.executeQuery();
            else
                prepared.executeUpdate();
        } catch (SQLException ignored) {
            MainController.ErrorAlert(Alert.AlertType.ERROR, "SQL Error", "Error Retrieving SQL Information, from RUNSQL", "There was an error retrieving the SQL information.");
        } catch (Exception ignored) {
            MainController.ErrorAlert(Alert.AlertType.ERROR, "Error", "Error Running SQL", "There was an error running the SQL information, or that user doesn't exist.");
        }
    }
    // endregion
}
public class MainController {
    // region Variables
    @FXML
    private Label formText, welcomeText;
    @FXML
    private Button login, signup;
    @FXML
    private TextField username, email, password, confirmPassword;
    @FXML
    private Button forgotPassword, formButton, resetPasswordButton;
    @FXML
    private AnchorPane formPage, dashboardPage;
    // endregion

    // region Form
    @FXML
    private void ChangeForm() {
        ObservableList<String> shortLogin = login.getStyleClass(), shortSignUp = signup.getStyleClass();
        if (shortLogin.contains("active")) { // switching to signup
            formText.setText("Signup Form");
            shortLogin.remove("active");
            shortLogin.add("notActive");
            shortSignUp.remove("notActive");
            shortSignUp.add("active");
            confirmPassword.setVisible(true);
            formButton.setText("Sign Up");
            forgotPassword.setVisible(false);
        } else /*if (shortSignUp.contains("active"))*/ { // switching to login
            formText.setText("Login Form");
            formButton.setText("Login");
            shortSignUp.remove("active");
            if(!shortSignUp.contains("notActive"))
                shortSignUp.add("notActive");
            shortLogin.remove("notActive");
            shortLogin.add("active");
            confirmPassword.setVisible(false);
            formButton.setText("Login");
            password.setPromptText("Password:");
            forgotPassword.setVisible(true);
        }
        ClearForm();
    }

    @FXML
    private void FormSubmit() {
        if (ValidForm()) {
            try {
                String name = (signup.getStyleClass().contains("active")) ? SQLUtils.Register(username.getText(), password.getText(), email.getText()) : SQLUtils.Login(username.getText(), password.getText(), email.getText());
                formPage.setVisible(false);
                dashboardPage.setVisible(true);
                welcomeText.setText("Welcome, " + name);
                ClearForm();
            } catch (Exception ignored) {
                ErrorAlert(Alert.AlertType.ERROR, "SQL Error", "Error Retrieving SQL Information from MainController", "There was an error retrieving the SQL information, or that user doesn't exist.");
            }
        }
    }
    
    @FXML
    private void Forgot() {
        forgotPassword.setVisible(false);
        resetPasswordButton.setVisible(true);
        forgotPassword.setVisible(true);
        formText.setText("Forgot Password");
        formButton.setVisible(false);
        password.setPromptText("Enter New Password:");
        
        ObservableList<String> shortLogin = login.getStyleClass();
        if(shortLogin.contains("active") && !shortLogin.contains("notActive")) {
            shortLogin.remove("active");
            shortLogin.add("notActive");
        }
    }
    @FXML
    private void ResetPassword() {
        if(ValidForm()) {
            resetPasswordButton.setVisible(false);
            formButton.setVisible(true);
            forgotPassword.setVisible(true);
            formButton.setVisible(true);
            password.setPromptText("Password:");
            
            ObservableList<String> shortLogin = login.getStyleClass();
            formText.setText("Login Form");
            shortLogin.remove("notActive");
            shortLogin.add("active");
            SQLUtils.ResetPassword(username.getText(), password.getText(), email.getText());
            ClearForm();
        }
    }

    // endregion
    // region Utils
    private void ClearForm() {
        username.clear();
        email.clear();
        password.clear();
        confirmPassword.clear();
    }
    
    private boolean ValidForm() {       
        String emailRegex = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9._]+\\.[a-zA-Z]{2,6}$";
        String passwordRegex = "^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[/~`!@#$%^&*()_+{};:',<.>? =]).{8,}$";

        if (username.getText().isEmpty() || email.getText().isEmpty() || password.getText().isEmpty() || (signup.getStyleClass().contains("active") && confirmPassword.getText().isEmpty())) {
            ErrorAlert(Alert.AlertType.INFORMATION, "Form Validation", "Invalid Fields", "All Fields Must Be Filled In");
            return false;
        } else if (!Pattern.compile(emailRegex).matcher(email.getText()).matches()) {
            ErrorAlert(Alert.AlertType.INFORMATION, "Form Validation", "Invalid Email", "Please Enter A Valid Email That Contains An '@' And A '.com'");
            return false;
        } else if (!Pattern.compile(passwordRegex).matcher(password.getText()).matches()) {
            ErrorAlert(Alert.AlertType.INFORMATION, "Form Validation", "Invalid Password", "Please Enter A Valid Password That Contains At Least 8 Characters, 1 Uppercase, 1 Lowercase, 1 Number, and 1 Special Character");
            return false;
        } else if (signup.getStyleClass().contains("active") && !password.getText().equals(confirmPassword.getText())) {
            ErrorAlert(Alert.AlertType.INFORMATION, "Form Validation", "Passwords Must Match", "Password And Confirm Password Must Match");
            return false;
        } else if (!SQLUtils.ValidInfo(username.getText(), password.getText(), email.getText())) {
            ErrorAlert(Alert.AlertType.ERROR, "Invalid Info", "That User Does Not Exist", "Please enter valid information for a user that does already exist.");
            return false;
        }
        return true;
    }
    public static void ErrorAlert(Alert.AlertType type, String title, String headerText, String contentText) {
        Alert alert = new Alert(type);
        alert.setTitle(title);
        alert.setHeaderText(headerText);
        alert.setContentText(contentText);
        alert.showAndWait();
    }
    @FXML
    private void LogOut() {
        formPage.setVisible(true);
        dashboardPage.setVisible(false);
        welcomeText.setText("Welcome, NAME HERE");
    }

    // endregion
    // region Window Settings
    @FXML
    private void Minimize(ActionEvent event) {
        ((Stage) ((Button) event.getSource()).getScene().getWindow()).setIconified(true);
    }

    @FXML
    private void Close() {
        System.exit(0);
    }

    // endregion
}

public class SQLUtils {
    // region Main Methods
    public static String Login(String username, String password, String email) {
        String sql = "select * from users_table where username = ? and password = ? and email = ?";
        RunSQL(sql, username, password, email, true);
        return username;
    }
    public static String Register(String username, String password, String email) {
        String sql = "insert into users_table (username, password, email) values (?, ?, ?)";
        RunSQL(sql, username, password, email, false);
        return username;
    }
    public static void ResetPassword(String username, String newPassword, String email) {
        String sql = "update users_table set password=? where username=? and email=?;";
        RunSQL(sql, newPassword, username, email, false);
    }
    // endregion
    // region Utils
    private static Connection ConnectDB() {
        try {
            return DriverManager.getConnection("jdbc:mysql://localhost:3306/login_and_register", "root", "password");
        } catch (Exception ignored) {
            MainController.ErrorAlert(Alert.AlertType.ERROR, "SQL Error", "Error Retrieving SQL Information", "Information could not be retrieved");
        }
        return null;
    }
    public static boolean ValidInfo(String username, String password, String email) {
        String sql = "select * from users_table where username = ? and password = ? and email = ?";
        Connection connect = ConnectDB();
        if (connect == null)
            return false;
        
        try (PreparedStatement prepared = connect.prepareStatement(sql)) {
            prepared.setString(1, username);
            prepared.setString(2, password);
            prepared.setString(3, email);
            prepared.executeQuery();
            System.out.println("working");
            // FORM ALWAYS RESULTS IN WORKING, EVEN WHEN USER IS INVALID, DOES NOT ADD TO TABLE THO
            return true;
        } catch (Exception ignored) {
            MainController.ErrorAlert(Alert.AlertType.ERROR, "Error", "Error Running SQL", "There was an error running the SQL information, or that user doesn't exist.");
        }
        System.out.println("not working");
        return false;
    }
    private static void RunSQL(String sql, String username, String password, String email, boolean query) {
        Connection connect = ConnectDB();
        if (connect == null)
            return;
        
        try (PreparedStatement prepared = connect.prepareStatement(sql)) {
            prepared.setString(1, username);
            prepared.setString(2, password);
            prepared.setString(3, email);
            if (query)
                prepared.executeQuery();
            else
                prepared.executeUpdate();
        } catch (SQLException ignored) {
            MainController.ErrorAlert(Alert.AlertType.ERROR, "SQL Error", "Error Retrieving SQL Information, from RUNSQL", "There was an error retrieving the SQL information.");
        } catch (Exception ignored) {
            MainController.ErrorAlert(Alert.AlertType.ERROR, "Error", "Error Running SQL", "There was an error running the SQL information, or that user doesn't exist.");
        }
    }
    // endregion
}
Source Link
Soco
  • 153
  • 4
Loading