Reputation: 29
void checkOnline()
{
string sql = "select * from png_users where username = '" + txtboxUsername.Text + "' and password = '" + txtboxPassword.Text + "' and userstatus = '1'";
cm = new MySqlCommand(sql, cn);
dr = cm.ExecuteReader();
dr.Read();
if (dr.HasRows)
{
MessageBox.Show("This account is currently online, you forgot to logout. Please approach administrator for help. Thank you", "THD FAM", MessageBoxButtons.OK, MessageBoxIcon.Error);
dr.Close();
this.Close();
return;
}
}
I'm pretty new to database and I am trying to figure out how to use sessions to check and see if a user is logged into a database so that they would have authorization to access specific pages.
Thanks For Help
Upvotes: 1
Views: 1638
Reputation: 186698
According to comments
If the
userstatus
is0
you can use the account and if theuserstatus = 1
you can't access the account because someone already used it
we should check for 3
cases:
-1
as userstatus
for this) userstatus
is 0
)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
)
Upvotes: 3