The user and password are correct but are returning as incorrect. What can it be?
Importantly, the password and encrypted in md5.
public static bool logarUsuario(string user, string pw)
{
try
{
const string checkUser = "SELECT COUNT(*) FROM tbUsuario WHERE userName = '#user'";
SqlConnection con = Banco.con();
con.Open();
SqlCommand cmd = new SqlCommand(checkUser, con);
int temp = Convert.ToInt32(cmd.ExecuteNonQuery().ToString());
cmd.Parameters.AddWithValue("#user", user);
con.Close();
if (temp == 1)
{
con.Open();
string checkPw = "SELECT pw FROM tbUsuario WHERE userName = '#user'";
SqlCommand passConn = new SqlCommand(checkPw, con);
cmd.Parameters.AddWithValue("#user", user);
string password = passConn.ExecuteScalar().ToString();
Registrar criptografia = new Registrar();
if (password == pw)
{
return true;
}
}
}
catch (SqlException ex)
{
Console.WriteLine("Erro " + ex.Message);
}
return false;
}
Within the btnLogar click event:
Already checked the database and the username and password are correct, but this as incorrect password.
protected void bntLogar_Click(object sender, EventArgs e)
{
Registrar criptografia = new Registrar();
if (Login.logarUsuario(txtUser.Text, criptografia.CriptografiaMD5(txtSenha.Text)))
{
//Cria um cookie do lado do servidor
HttpCookie cookie = new HttpCookie("estado", "conectado");
//Define a validade do cookie (10 dias a partir de hoje)
cookie.Expires = DateTime.Now.AddMonths(12);
//Envia o cookie para o cliente
Response.Cookies.Set(cookie);
//Redireciona para a pagina inicial
Response.Redirect("Admin.aspx");
}
else
{
lblErro.Text = "Usuário ou Senha Incorretos";
lblErro.Visible = true;
lblErro.CssClass = "alert alert-danger";
}
}
'#user' is incorrect. Do not surround a parameter name with a single quote. It should look like
SELECT pw FROM tbUsuario WHERE userName = #user
Also MD5 is no longer considered secure, I suggest using SHA-256.
You can do this with a single SELECT statement
public static bool logarUsuario(string user, string pw)
{
const string checkUser =
#"SELECT COUNT(*) FROM tbUsuario
WHERE userName = #u AND pw = #p";
using (SqlConnection con = Banco.con())
{
con.Open();
SqlCommand cmd = new SqlCommand(checkUser, con);
cmd.Parameters.AddWithValue("#u", user);
cmd.Parameters.AddWithValue("#p", pw);
return 1 == (int) cmd.ExecuteNonQuery();
}
}
This assumes that pw is already hashed.
Related
When I run my code and I input the correct details the first time, the code works perfectly and logs the user in and passes through the id.
However, when I get the details incorrect, and I have to click login again then I get an error:
The ConnectionString property has not been initialised
It gets to the con.Open() and then crashes without opening the database.
Any thoughts?
readonly SqlConnection con = new SqlConnection(#"data source=myPC;initial catalog=cafeDB;trusted_connection=true");
int loginChance = 3;
private void Btn_Login_Click(object sender, EventArgs e)
{
int staffID;
int account;
string user = txt_username.Text;
string pass = txt_password.Text;
using (con) // This will automatically close the connection when the brackets are exited
{
try
{
// THE CODE GETS TO HERE BEFORE BREAKING
con.Open();
// This SQL Command selects the data from the database
using (SqlCommand cmd = new SqlCommand("SELECT username, password FROM tbl_staff WHERE username = #user AND password = #pass", con))
{
cmd.Parameters.AddWithValue("#user", user);
cmd.Parameters.AddWithValue("#pass", pass);
account = Convert.ToInt32(cmd.ExecuteScalar());
if (loginChance == 0)
{
MessageBox.Show("Your out of login attempts");
}
else
{
if (account == 1)
{
// SQL Statement to get staffID so it can be passed to the other users
using (SqlCommand cmdGetStaffID = new SqlCommand("SELECT staffID FROM tbl_staff WHERE username = #username", con))
{
cmdGetStaffID.Parameters.AddWithValue("#username", user);
staffID = Convert.ToInt32(cmdGetStaffID.ExecuteScalar());
}
var menu = new Main_Menu
{
StaffIDMenu = staffID,
StaffUsernameMenu = user
};
menu.Show();
this.Hide();
}
else
{
loginChance--;
lbl_Incorrect.Text = "Incorrect Username and Password\n" + loginChance + " chance(s) left";
lbl_Incorrect.Show();
this.txt_username.Clear();
this.txt_password.Clear();
}
}
}
}
catch (Exception problem)
{
// This is error checking
MessageBox.Show(problem.Message);
}
}
}
I want to set isLogged to 1 after login, login work but query doesn't work.
Query :
//
public static string loginUpdate = #"UPDATE users SET isLogged = #isLogged WHERE username = #username";
//
public bool userLogin(string userName, string password)
{
SqlConnection conn = db.initializare();
UserModel user = null;
int userId ;
int isLogged = 1;
try
{
cmd = new SqlCommand(Query.loginCheck, conn);
//cmd = new SqlCommand(Query.loginUpdate, conn);
cmd.Parameters.Add(new SqlParameter("username", userName));
cmd.Parameters.Add(new SqlParameter("password", password));
cmd.Parameters.AddWithValue("#isLogged", isLogged);
reader = cmd.ExecuteReader();
while (reader.Read())
{
userName = reader["username"].ToString();
password = reader["password"].ToString();
userId = Int32.Parse(reader["userID"].ToString());
user = new UserModel(userName, password,userId);
if (user != null)
{
cmd = new SqlCommand(Query.loginUpdate, conn);
return true;
}
}
}
catch (Exception ex)
{
var mesajEroare = ex.Message + "-" + ex.InnerException; ;
}
finally
{
conn.Dispose();
conn.Close();
}
return false;
}
You may need to write two separate SqlCommands to perform two operations:
For login check
For login update
Also, always make it a habit to use the using statement when dealing with an object that eats resources such as SqlConnection and SqlCommand. so objects will be automatically disposed after using them.
This will make your code cleaner without explicitly calling the Dispose() call.
Finally, I would suggest you place your SQL operation outside your Button Click event to avoid getting your code more complex. That way it's clean and easy to manage.
To summarize that, here's how your code is going to look like:
private string GetUserPassword(string userName){
using (SqlConnection connection = db.initializare()) {
string sqlQuery = "SELECT password FROM users WHERE username = #UserName";
using (SqlCommand cmd = new SqlCommand(sqlQuery, connection)) {
connection.Open();
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#UserName", userName);
var result = cmd.ExecuteScalar();
return (result == DBNull.Value) ? string.Empty : result;
}
}
}
private void UpdateLogin(string userName, int isLogged){
using (SqlConnection connection = db.initializare()) {
string sqlQuery = "UPDATE users SET isLogged = #isLogged WHERE username = #username";
using (SqlCommand cmd = new SqlCommand(sqlQuery, connection)) {
connection.Open();
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#UserName", userName);
cmd.Parameters.AddWithValue("#isLogged", isLogged);
cmd.ExecuteNonQuery();
}
}
}
public bool UserLogin(string userName, string password)
{
string userPassword = GetUserPassword(userName);
if (password.Equals(userPassword)){
UpdateLogin(userName,1);
return true;
}
else{
//username or password is incorrect
}
return false;
}
i am trying to encrypt a password and be able to log in with it. here is my hash code inside my businesslayer folder under shopping cart class.
public static string CreateSHAHash(string Phrase)
{
SHA512Managed HashTool = new SHA512Managed();
Byte[] PhraseAsByte = System.Text.Encoding.UTF8.GetBytes(string.Concat(Phrase));
Byte[] EncryptedBytes = HashTool.ComputeHash(PhraseAsByte);
HashTool.Clear();
return Convert.ToBase64String(EncryptedBytes);
}
and here is my registration code where i included the hash with the password. i am successful in registering an account and having an encrypted password in my database with this:
protected void btn_Registration_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string insertQuery = "insert into UserData(Username,Firstname,Lastname,Email,Password,CustomerType,DeliveryAddress,Zip,ContactNumber)values(#Username,#Firstname,#Lastname,#Email,#Password,#CustomerType,#DeliveryAddress,#Zip,#ContactNumber)";
SqlCommand scm = new SqlCommand(insertQuery, conn);
scm.Parameters.AddWithValue("#Username", txtUser.Text);
scm.Parameters.AddWithValue("#Firstname", txtFN.Text);
scm.Parameters.AddWithValue("#Lastname", txtLN.Text);
scm.Parameters.AddWithValue("#Email", txtEmail.Text);
scm.Parameters.AddWithValue("#Password", BusinessLayer.ShoppingCart.CreateSHAHash(txtPW.Text));
scm.Parameters.AddWithValue("#CustomerType", RadioButtonList1.SelectedItem.ToString());
scm.Parameters.AddWithValue("#DeliveryAddress", txtAddress.Text);
scm.Parameters.AddWithValue("#Zip", txtZip.Text);
scm.Parameters.AddWithValue("#ContactNumber", txtContact.Text);
scm.ExecuteNonQuery();
Session["Contact"]= txtContact.Text;
Session["Email"] = txtEmail.Text;
Session["DeliveryAddress"] = txtAddress.Text;
label_register_success.Text = ("Registration Successful!");
//Response.Redirect("Home.aspx");
conn.Close();
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
}
However, when i try to log in with the password that i have registered, its not letting me in. here is the code:
protected void btn_Login_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source = 'PAULO'; Initial Catalog=ShoppingCartDB;Integrated Security =True");
conn.Open();
string checkuser = "select count(*) from UserData where Username = '" + txtUser.Text + "'";
SqlCommand scm = new SqlCommand(checkuser, conn);
int temp = Convert.ToInt32(scm.ExecuteScalar().ToString());
conn.Close();
if (temp == 1)
{
conn.Open();
string checkPassword = "select Password from UserData where Username ='" + txtUser.Text + "'";
SqlCommand passCom = new SqlCommand(checkPassword, conn);
string password = passCom.ExecuteScalar().ToString();
if (password == BusinessLayer.ShoppingCart.CreateSHAHash(txtPassword.Text))
{
Session["New"] = txtUser.Text;
Response.Write("<script>alert('Logged In')</script>");
Response.Redirect("OrderNow.aspx");
}
else
{
lblcrederror.Text = ("Credentials dont match");
}
}
else
{
lblcrederror.Text = ("Credentials dont match");
}
}
what am i missing here? thank you
I have created asp.net WebService. I want to update user's info after validating him , means if new UserName entered by him is not already exist than only he can update new UserName otherwise not .
The problem is that it validates the user successfully but when i am trying to specify new UserName which is not exist than it gives me an error like ;
Request format is unrecognized for URL unexpectedly ending in '/UpdateUserInfo'.
Following is my code :
public int UpdateUserInfo(string oldusername, string newusername, string mailid, string password)
{
string validateUser = "Select UserName from tbl_UserInfo where UserName='" + newusername + "' ";
con = new MySqlConnection(conString);
con.Open();
MySqlCommand cmd1 = new MySqlCommand(validateUser, con);
string User = cmd1.ExecuteScalar().ToString();
con.Close();
if (User == newusername)
{
return 0;
}
else
{
string updateUser = "Update tbl_UserInfo SET UserName='" + newusername + "',Password='" + password + "',Email_ID='" + mailid + "' where UserName='" + oldusername + "' ";
con = new MySqlConnection(conString);
con.Open();
MySqlCommand cmd = new MySqlCommand(updateUser, con);
int success = cmd.ExecuteNonQuery();
con.Close();
if (success > 0)
{
return success;
}
else
return 0;
}
}
NOTE : I want result as ;
IF my UserName is A and when i update that UserName with same name
i.e A than it should not be updated but when i give another name as B
than it should be updated by B i.e now UserName A becomes the B
what can be problem ?
Please give solution.
Thanks..
Oh, please use parametrized queries. Ah, and dispose your IDisposable resources. You wil save yourself headaches, SQL injections, improperly formatted data, ...
public int UpdateUserInfo(
string oldusername,
string newusername,
string mailid,
string password
)
{
using (var con = new MySqlConnection(conString))
using (var cmd = con.CreateCommand())
{
con.Open();
cmd.CommandText = "SELECT count(UserName) from tbl_UserInfo where UserName = #newusername";
cmd.Parameters.AddWithValue("#newusername", newusername);
var count = (long)cmd.ExecuteScalar();
if (count < 1)
{
return 0;
}
}
using (var con = new MySqlConnection(conString))
using (var cmd = con.CreateCommand())
{
con.Open();
cmd.CommandText = "UPDATE tbl_UserInfo SET UserName = #newusername, Password = #password, Email_ID = #mailid WHERE UserName = #oldusername";
cmd.Parameters.AddWithValue("#newusername", newusername);
cmd.Parameters.AddWithValue("#password", password);
cmd.Parameters.AddWithValue("#mailid", mailid);
cmd.Parameters.AddWithValue("#oldusername", oldusername);
return cmd.ExecuteNonQuery();
}
}
or you could also split those into separate methods:
public bool UsernameExists(string username)
{
using (var con = new MySqlConnection(conString))
using (var cmd = con.CreateCommand())
{
con.Open();
cmd.CommandText = "SELECT count(UserName) from tbl_UserInfo where UserName = #newusername";
cmd.Parameters.AddWithValue("#newusername", username);
return (long)cmd.ExecuteScalar() > 0;
}
}
public int Update(string oldusername, string newusername, string mailid, string password)
{
using (var con = new MySqlConnection(conString))
using (var cmd = con.CreateCommand())
{
con.Open();
cmd.CommandText = "UPDATE tbl_UserInfo SET UserName = #newusername, Password = #password, Email_ID = #mailid WHERE UserName = #oldusername";
cmd.Parameters.AddWithValue("#newusername", newusername);
cmd.Parameters.AddWithValue("#password", password);
cmd.Parameters.AddWithValue("#mailid", mailid);
cmd.Parameters.AddWithValue("#oldusername", oldusername);
return cmd.ExecuteNonQuery();
}
}
public int UpdateUserInfo(string oldusername, string newusername, string mailid, string password)
{
if (!UsernameExists(newusername))
{
return Update(oldusername, newusername, mailid, password);
}
return 0;
}
I am trying to change the user password. I am not able to update the password :(. The message i am getting is password changed where as its not getting changed. .
My code is as follow.. Please if anyone can suggest where i am going wrong . I am just a beginner ...
protected void Button1_Click(object sender, EventArgs e)
{
DatabaseLayer data = new DatabaseLayer();
string username = Session["Authenticate"].ToString();
string password = TextBox1.Text;
string newpass = TextBox2.Text;
string confirm = TextBox3.Text;
string flag = "";
if (newpass.ToString() == confirm.ToString())
{
flag = data.passwordChange(username, password, newpass);
Literal1.Text = flag.ToString();
}
else
{
Literal1.Text = "New Password does not match the Confirm Password ";
}
}
The above click event must change my password, and the function passwordChange is as follows..
public string passwordChange(string username, string password, string newPasswd)
{
string SQLQuery = "SELECT password FROM LoginAccount WHERE username = '" + username + "'";
string SQLQuery1 = "UPDATE LoginAccount SET password = ' " + newPasswd + " ' WHERE username = ' " + username + "'";
SqlCommand command = new SqlCommand(SQLQuery, sqlConnection);
SqlCommand command1 = new SqlCommand(SQLQuery1, sqlConnection);
sqlConnection.Open();
string sqlPassword = "";
SqlDataReader reader;
try
{
reader = command.ExecuteReader();
if (reader.Read())
{
if (!reader.IsDBNull(0))
{
sqlPassword = reader["password"].ToString();
}
}
reader.Close();
if (sqlPassword.ToString() == password.ToString())
{
try
{
int flag = 0;
flag = command1.ExecuteNonQuery();
if (flag > 0)
{
sqlConnection.Close();
return "Password Changed Successfully";
}
else
{
sqlConnection.Close();
return "User Password could not be changed";
}
}
catch (Exception exr)
{
sqlConnection.Close();
return "Password Could Not Be Changed Please Try Again";
}
}
else
{
sqlConnection.Close();
return "User Password does not Match";
}
}
catch (Exception exr)
{
sqlConnection.Close();
return "User's Password already exists";
}
}
I had put a break point near
if(flag>0)
it still shows that executeNonquery aint returning the updated rows value and also in the Back end of SQL server, its not changing,
Please if anyone could correct me... Should i use other execute command or something?
I am doing this with VS 2008 and SQL server 2005..
1: It's your spacing between your single and double quotes: (Like: ' " + username + " ')
2) You are begging for SQL Injection.
Try this in your PasswordChange method:
public string PasswordChange(string userName, string oldPass, string newPass)
{
using(SqlConnection sqlConnection = new SqlConnection(
ConfigurationManager.ConnectionStrings["LoginDb"].ConnectionString))
{
string sqlToConfirmOldPass =
"SELECT password FROM LoginAccount WHERE username = #userName";
string sqlToUpdatePassword =
"UPDATE LoginAccount SET password = #newPass WHERE username = #userName";
SqlCommand confirmOldPass = new SqlCommand(sqlToConfirmOldPass, sqlConnection);
confirmOldPass.Parameters.AddWithValue("#userName", userName);
SqlCommand updatePassword = new SqlCommand(sqlToUpdatePassword, sqlConnection);
updatePassword.Parameters.AddWithValue("#newPass", newPass);
updatePassword.Parameters.AddWithValue("#userName", userName);
[Rest of your code goes here]
}
}
I also didn't see where you set your SqlConnection, so I've added a line for that. You'll need to modify it according to your needs.
Maybe try this code instead.
public string passwordChange(string username, string password, string newPasswd)
{
string SQLQuery = "SELECT password FROM LoginAccount WHERE username = #username";
string SQLQuery1 = "UPDATE LoginAccount SET password = #newPassword WHERE username = #username";
SqlCommand command = new SqlCommand(SQLQuery, sqlConnection);
command.Parameters.AddWithValue("#username", username);
SqlCommand command1 = new SqlCommand(SQLQuery1, sqlConnection);
command1.Parameters.AddWithValue("#username", username);
command1.Parameters.AddWithValue("#newPassword", newPasswd);
sqlConnection.Open();
string sqlPassword = "";
SqlDataReader reader;
try
{
reader = command.ExecuteReader();
if (reader.Read())
{
if (!reader.IsDBNull(0))
{
sqlPassword = reader["password"].ToString();
}
}
reader.Close();
if (sqlPassword.ToString() == password.ToString())
{
try
{
int flag = 0;
flag = command1.ExecuteNonQuery();
if (flag > 0)
{
sqlConnection.Close();
return "Password Changed Successfully";
}
else
{
sqlConnection.Close();
return "User Password could not be changed";
}
}
catch (Exception exr)
{
sqlConnection.Close();
return "Password Could Not Be Changed Please Try Again";
}
}
else
{
sqlConnection.Close();
return "User Password does not Match";
}
}
catch (Exception exr)
{
sqlConnection.Close();
return "User's Password already exists";
}
}
If you're getting zero rows affected double check that your WHERE clause actually works. I'd bet that if you SELECTed WHERE username = '" + username + "'", you won't find the row you're looking for. That'd, at least, be the first thing I would confirm.