Проверка имени пользователя и пароля по MySQL возвращается пустым - PullRequest
0 голосов
/ 03 мая 2020

Я проверяю имя пользователя и пароль по базе данных MySQL, но почему-то мой код ничего не возвращает даже для базового случая (адрес электронной почты не существует). У меня есть sh мои пароли на стороне сервера. Что я должен исправить в этом случае?

package GUI_755;

import java.sql.*;
import nonGUI_755.AES;

public class test {
    public static void main(String args[]) throws Exception {
        System.out.println(loginResponse("jordan30@bulls.edu","JordanTheGoat3098"));
    }

       /* The method handles the login's request from the user */
    public static String loginResponse(String email, String password) throws Exception{
        String returnStatement = "";
        Connection connection = null;
        connection = establishConnection();

        /* Similar to the code above, we check whether the email and password match to those we have in the database */
        final String queryCheck = "SELECT * from usersdata WHERE email = ?";        
        final PreparedStatement ps = connection.prepareStatement(queryCheck);
        ps.setString(1, email);
        final ResultSet resultSet = ps.executeQuery();
        try {
            /* First, if we cannot find the user's email, we return this statement */
            if(email.equals(resultSet.getString("email"))) {
                /* Second, if we can find the email but the password do not match then we return that the password is incorrect */
                 String hashedPasswordInput = AES.doHash(password, resultSet.getObject("password").toString().split("\t")[1]);
                if(hashedPasswordInput.equals(resultSet.getObject("password").toString().split("\t")[0])) {
                    returnStatement = "LoginFailure The password that you entered is incorrect. Please try again!";
                    connection.close();
                }
                else {
                    returnStatement = "LoginSuccess You are logged in!";
                }
            }
            else {
                connection.close();
                returnStatement = "LoginFailure We cannot find any account associated with that email. Please try again!";
            }
        }catch(Exception e) {}
        return returnStatement;
    }


    /* This method will connect to MySQL database >> userdata */
    public static Connection establishConnection(){
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/userdata","root","");
            return connection;
        }catch(Exception e)
        {return null;}
    }
}

1 Ответ

2 голосов
/ 03 мая 2020

Вам необходимо проверить, возвращает ли ваш ResultSet resultSet несколько строк. Для этого вы должны использовать next() метод ResultSet. Вы можете использовать if (resultSet.next(), если вас интересует только первая строка (как ваш случай здесь), или while (resultSet.next()), если вы хотите l oop над возвращенными строками результата (не ваш случай).

Так собрать это вместе:

final String queryCheck = "SELECT * from usersdata WHERE email = ?";        
    final PreparedStatement ps = connection.prepareStatement(queryCheck);
    ps.setString(1, email);
    final ResultSet resultSet = ps.executeQuery();
    if (resultSet.next()) {
        /* First, if we cannot find the user's email, we return this statement */
        if(email.equals(resultSet.getString("email"))) {
            /* Second, if we can find the email but the password do not match then we return that the password is incorrect */
             String hashedPasswordInput = AES.doHash(password, resultSet.getObject("password").toString().split("\t")[1]);
            if(hashedPasswordInput.equals(resultSet.getObject("password").toString().split("\t")[0])) {
               // dont do it here
               // returnStatement = "LoginFailure The password that you entered is incorrect. Please try again!";
              //  connection.close();
            }
            else {
                returnStatement = "LoginSuccess You are logged in!";
            }
        }
        else {
           // don't do it here
           // connection.close();
           // returnStatement = "LoginFailure We cannot find any account associated with that email. Please try again!";
        }
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...