Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package nl.kingev.LoginSystem.manager;
- import nl.kingev.LoginSystem.utils.HashUtils;
- import sun.nio.cs.StandardCharsets;
- import javax.swing.*;
- import java.io.IOException;
- import java.sql.*;
- import java.util.List;
- /**
- * Created by Jasper on 20-5-2017.
- */
- public class DatabaseManager {
- List<String> conf;
- private Connection connection;
- private String password = "";
- private String host = "";
- private String database = "LoginSystem";
- private String username = "";
- public DatabaseManager(){
- }
- public void setupDatabaseManager(){
- try {
- synchronized (this){
- Class.forName("com.mysql.jdbc.Driver");
- connection = DriverManager.getConnection("jdbc:mysql://" + this.host + ":" + "3306" + "/" + this.database,
- this.username, this.password);
- PreparedStatement st = connection.prepareStatement("CREATE TABLE IF NOT EXISTS `" + database + "`.`users` ( `id` INT(255) NOT NULL AUTO_INCREMENT , `user` VARCHAR(255) NOT NULL , `password` VARCHAR(255) NOT NULL , PRIMARY KEY (`id`)) ENGINE = InnoDB;");
- st.executeUpdate();
- }
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- public Connection getConnection(){
- return connection;
- }
- public boolean testLogin(String username , String password){
- boolean toReturn = false;
- boolean user = false;
- boolean pass = false;
- String hash = HashUtils.sha1(password);
- if(userExists(username)){
- try {
- PreparedStatement st = connection.prepareStatement("SELECT * FROM users WHERE user =?");
- st.setString(1 , username);
- ResultSet rs = st.executeQuery();
- while (rs.next()){
- user = true;
- break;
- }
- if(user){
- st = connection.prepareStatement("SELECT * FROM users WHERE password = ?");
- st.setString(1, hash);
- ResultSet rs2 = st.executeQuery();
- while (rs2.next()){
- pass = true;
- break;
- }
- }
- if(user && pass){
- toReturn = true;
- }
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- return toReturn;
- }
- public boolean userExists(String username){
- boolean toReturn = false;
- try {
- PreparedStatement st = connection.prepareStatement("SELECT * FROM users WHERE user=?" );
- st.setString(1 , username);
- ResultSet rs = st.executeQuery();
- if(rs.next()){
- toReturn = true;
- }
- } catch (SQLException e) {
- e.printStackTrace();
- }
- return toReturn;
- }
- public void registerUser(String username, String phash) throws SQLException {
- PreparedStatement ps = connection.prepareStatement("INSERT INTO users (user, password) VALUES (?,?)");
- ps.setString(1, username);
- ps.setString(2, phash);
- ps.executeUpdate();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement