According to comments
If the userstatus
is 0
you can use the account and if the
userstatus = 1
you can't access the account because someone already
used it
we should check for 3
cases:
- user / password not found (let's return
-1
as userstatus
for this)
- user owns the account (
userstatus
is 0
)
- account belongs to some other user (
userstatus
is 1
)
Let's extract method:
// -1 Account does't exist
// 0 Account exists and belongs to the user
// 1 Account exists and belongs to different user
public int UserLogStatus(string login, string password) {
//DONE: do not reuse connection, but create a new one
using (var con = new MySqlConnection(ConnectionStringHere)) {
con.Open();
//DONE: keep sql readable
//DONE: make sql parametrized
string sql =
@"select userstatus
from png_users
where username = @prm_username and
password = @prm_password";
//DONE: wrap IDisposable into using
using (MySqlCommand query = new MySqlCommand(sql, con)) {
//TODO: better create params explicitly, Parameters.Add(name, type).Value = ...
query.Parameters.AddWithValue("@prm_username", login);
query.Parameters.AddWithValue("@prm_password", pasword);
using (var reader = query.ExecuteReader()) {
if (reader.Read())
return Convert.ToInt32(reader[0]);
else
return -1;
}
}
}
}
And then you can use it:
int status = IsUserLogged(txtboxUsername.Text, txtboxPassword.Text);
if (status == 0) {
MessageBox.Show("Either username or password is incorrect.",
"THD FAM",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
return;
}
else if (status == 1) {
MessageBox.Show("This account is currently online, you forgot to logout. Please approach administrator for help. Thank you",
"THD FAM",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
return;
}
Warning! Do not store passwords as plain text. If someone steal the table all the users will be compromised. Store password hashes instead. When logging on, user must provide a string (password
), such that
HashFunction(password) == StoredHash
where HashFunction
is one way function: easy to compute (i.e. it's easy to find HashFunction(password)
value), difficult to reverse (i.e. it's almost impossible to find a sting such that HashFunction(password) == given value
)