0

I tried going through my code for hours trying to see where I went wrong and google doesn't seem to have the answer either. Basically I am running this code:

public bool LoginRequest(string ReceivedUsername, string ReceivedPassword)
    {

        bool ValidLogin = false;

        try
        {

            using (SqlConnection myConnection = new SqlConnection(ConnectString))
            {
                myConnection.Open();
                Log.Debug("Succesful sql connection");
                SqlCommand userSELECTcom = new SqlCommand("SELECT username,password FROM users;", myConnection);
                SqlDataReader reader = userSELECTcom.ExecuteReader();

                    //verify login
                    while (reader.Read())
                    {
                        CompareUsername = reader["username"].ToString();
                        ComparePassword = reader["password"].ToString();
                        Log.Debug(ReceivedUsername + " against " + CompareUsername);
                        Log.Debug(ReceivedPassword + " against " + ComparePassword);

                        if (CompareUsername == ReceivedUsername && ComparePassword == ReceivedPassword)
                        {
                            ValidLogin = true;
                            Log.Debug(ReceivedUsername + " has logged in successfully!!!");
                            myConnection.Close();//close sql conn
                            reader.Close();//close sqldatareader
                            return ValidLogin;
                        }

                        else if (CompareUsername != ReceivedUsername || ComparePassword != ReceivedPassword)
                        {
                            if (!reader.Read())
                            {
                                Log.Debug(ReceivedUsername + " has not logged in successfully with password: " + ReceivedPassword);
                                myConnection.Close();//close sql conn
                                reader.Close();//close sql data reader
                                return ValidLogin;
                            }
                        }
                    }
                    //end of verify sequence
            }

        }
        //logging any login request issues
        catch (Exception e)
        {
            Log.Debug(e);
        }
        return ValidLogin;

    }

I have a logging program set up that tells me everything thats happening as the code gets executed. These lines: " Log.Debug(ReceivedUsername + " against " + CompareUsername); Log.Debug(ReceivedPassword + " against " + ComparePassword); "

helps me see which row is being checked by the reader. I tried with six rows each with unique usernames and passwords and the result basically shows that only row 1, 3 and 5 is checked by the reader against the input from the user. So if I tried to log in with my client using a username and password from row 2, 4 or 6 I get an error saying my log in failed. Can anyone explain why this happens?

6
  • 3
    Just a side note for you. If you are using the 'using' keyword around your connection there is NO need for you to call. Close on it. It inherits IDisposable, which using calls for you. Commented Aug 28, 2014 at 4:05
  • Normally it is good practice to query directly from database instead of retrieving all data from Table. Recommended to use where clause. Commented Aug 28, 2014 at 4:06
  • Definitely taking that into account Cubicle.Jockey. And could you explain further Hassan? Commented Aug 28, 2014 at 4:11
  • @Jaja. Yes. I am asking to add where clause into your sql query. Commented Aug 28, 2014 at 4:13
  • @HassanNisar Didn't quite know about this clause so I did some research on it. I may be wrong but wont this sort of statement leave you vulnerable to SQL Injection attacks? SELECT username FROM users WHERE username = 'var_user_input' Commented Aug 28, 2014 at 4:24

4 Answers 4

2

You have an extra Reader.Read() call in your condition where you didn't find the login that time. That's skipping to the next record, then your main loop's Reader.Read() goes to the next.

You don't need to loop like this, though. Build a query that looks for a record by the username. If there are no records, login fails. If there is one, check the password.

Sign up to request clarification or add additional context in comments.

2 Comments

Ahhhh I see....makes sense. But before I try the code, how can I check that the reader still has rows left without the condition !Reader.read()?
Reader.HasRows could be used.
1

You have a 2nd reader.Read() on the if statement inside the while block. That is causing your code to skip a record.

Comments

0

To keep things simple you could directly query from database.

Below is example code to check if the received username and password exists in the db:

string sql = @"SELECT username,password FROM users 
             WHERE username=@username and password = @password";

SqlCommand userSELECTcom = new SqlCommand(sql, myConnection);
userSELECTcom.Parameters.AddWithValue(@username, ReceivedUsername);
userSELECTcom.Parameters.AddWithValue(@password, ReceivedPassword);

using(SqlDataReader reader = userSELECTcom.ExecuteReader())
{
   ValidLogin = reader.HasRows; 
}

6 Comments

Thanks alot...much shorter than the code I used! I'm going to modify my code right away.
@Jaja. Please note that. You could avoid declaration of bool ValidLogin. You could directly use return reader.HasRows;. Also when you use using statement for SqlConnection then you don't have to close the connection, you could skip myConnection.Close().
Yes, I removed all of my connection.Close() statements where they were not needed. I am wondering whether or not now to return false in my catch statement though?
Well you could return false within catch block. Also you could write entry in Log as well.
Thanks...and one last question: is it better to assign the return value of a function to a boolean before using it in an if condition statement or should I just call the function within the if parentheses?
|
0
else if (CompareUsername != ReceivedUsername || ComparePassword != ReceivedPassword)
{
if (!reader.Read())  //remove this condition it will skip the current loop                             
{
Log.Debug(ReceivedUsername + " has not logged in successfully with password: " + ReceivedPassword);
myConnection.Close();//close sql conn
reader.Close();//close sql data reader
return ValidLogin;
}
}

1 Comment

Can you indent your answer properly? It looks very odd.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.