Change password not working - c#

I have a web page where the user enters their current Username and Password. If they match a user in the database then the password is changed to the new password.
If there is no error and the password is changed the user is redirected to the initial login page. If there is an error then an error message will appear.
However at the moment the password is not changed and when there is supposed to be an error, i.e. when the the password was not changed, it just redirects the user anyway to the login page.
My code:
public static MySqlConnection CreateConnection()
{
String connectionString = "SERVER=127.0.0.1; DATABASE='dbnumericalmethods'; UID='root'; PASSWORD=''";
MySqlConnection SqlConnection = new MySqlConnection(connectionString);
return SqlConnection;
}
protected void btnChange_Click(object sender, EventArgs e)
{
MySqlConnection SqlConnection = CreateConnection();
string OldPassword;
string NewPassword;
string Username;
string ConfirmPassword;
Username = txtUsername2.Text;
OldPassword = txtOldPassword.Text;
NewPassword = txtNewPassword.Text;
ConfirmPassword = txtConfirmPassword.Text;
string SqlString = "update tblLogin set Identification='" + NewPassword + "' WHERE [Identification]='" + OldPassword + "' AND Username='" + Username + "'";
SqlConnection.Open();
MySqlCommand cmd = new MySqlCommand(SqlString, SqlConnection);
SqlConnection.Close();
if (OldPassword != "" && NewPassword != "" && ConfirmPassword != "")
{
Response.Redirect("Login.aspx");
}
else
{
lblErrorMessage2.Text = ("Username ");
}
}

You are not even executing the command, you are just opening the connection, creating a MySqlCommand then immediately close the connection:
MySqlCommand cmd = new MySqlCommand(SqlString, SqlConnection);
int result = cmd.ExecuteNonQuery();
SqlConnection.Close();
BTW, you should use parameterized queries to avoid SQL Injection.

Related

Column 'username' does not belong to table Table

I am trying to do lock user account for Invalid login attempts in Asp.Net C# by using Visual Studio 2019. Database is using MySql Workbench 8.0 CE. But facing the error
C# code shown as below:
using System;
using System.Data;
using MySql.Data.MySqlClient;
namespace Canteen_UAT
{
public partial class LoginDetail : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click1(object sender, EventArgs e)
{
MySqlConnection scon = new MySqlConnection("server = XXX.XXX.XX.XXX; user id = root; password = XXXXX; persistsecurityinfo = True; database = posdbms_uat");
String myquery = "select count(*) from posdbms_uat.logindetail where username='" + TextBox1.Text + "'";
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = myquery;
cmd.Connection = scon;
MySqlDataAdapter da = new MySqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds);
String uname;
String pass;
String status;
//String lockstatus;
int attemptcount = 0;
if (ds.Tables[0].Rows.Count > 0)
{
uname = ds.Tables[0].Rows[0]["username"].ToString();
pass = ds.Tables[0].Rows[0]["password"].ToString();
status = ds.Tables[0].Rows[0]["status"].ToString();
scon.Close();
if (status == "Open")
{
if (uname == TextBox1.Text && pass == TextBox2.Text)
{
Session["username"] = uname;
Response.Redirect("Order.aspx");
}
else
{
Label2.Text = "Invalid Username or Password - Relogin with Correct Username & Password. No of Attempts Remaining : " + (2 - attemptcount);
attemptcount = attemptcount + 1;
}
}
else if (status == "Locked")
{
Label2.Text = "Your Account Locked Already : Contact Administrator";
}
else
{
Label2.Text = "Invalid Username or Password - Relogin wit Correct Username and Password.";
}
if (attemptcount == 3)
{
Label2.Text = "Your Account Has Been Locked Due to Three Invalid Attempts - Contact Administrator.";
setlockstatus(TextBox1.Text);
attemptcount = 0;
}
}
}
private void setlockstatus(String username1)
{
String mycon = "server = xxx; user id = root; password = xxx; persistsecurityinfo = True; database = posdbms_uat";
String updatedata = "Update posdbms_uat.logindetail set status='Locked' where username='" + username1 + "' ";
MySqlConnection con = new MySqlConnection(mycon);
con.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = updatedata;
cmd.Connection = con;
cmd.ExecuteNonQuery();
}
}
}
Not sure what might be causing this.
What I have tried:
I created a table as posdbms_uat, datatable match the column name in the database table and with appropriate datatype. Not sure how this error pops up.
The query:
String myquery = "select count(*) from posdbms_uat.logindetail where username='" + TextBox1.Text + "'";
...only returns the number of rows matching the WHERE condition - not the actual data in the rows. It should be fixed by specifying the columns you want to get:
String myquery = "select username, password, status from posdbms_uat.logindetail where username='" + TextBox1.Text + "'";
Also, you should consider using parametrization to avoid SQL injection (see this SO question). Another thing is, please do not store the password in plain text.

Select MySQL Data in C#

I want to login to the program using c#, with my username and password that's stored to the SQL Database in phpmyadmin.
This is what I have so far.
private void button1_Click(object sender, EventArgs e)
{
MySqlConnection connection;
string server = "localhost";
string database = "login";
string uid = "root";
string password = "";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
try
{
connection.Open();
if (connection.State == ConnectionState.Open)
{
connection.Close();
Form1 frm = new Form1(this);
frm.Show();
Hide();
}
else
{
MessageBox.Show("Database Connection Failed", "Epic Fail", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
}
}
catch (Exception ex)
{
MessageBox.Show("An Error Occured, Try again later.", "Epic Fail", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
}
}
It connects to the database, however I don't want it to show the form1 Until both a valid Username and Password have been entered.
I'm guessing I need to use SELECT * FROM but I'm not exactly sure how to go about it.
You can use this way to see if username and password match
MySqlCommand cmd = dbConn.CreateCommand();
cmd.CommandText = "SELECT count(*) from tbUser WHERE UserName = #username and password=#password";
command.Parameters.Add("#username", txtUserName.Text);
command.Parameters.Add("#password", txtPassword.Text);
var count = cmd.ExecuteScalar();
if(count>0)
//Logged In
Just to say, if you use a query like
cmd.CommandText = "SELECT count(*) from tbUser WHERE UserName = '"+txtusernam +"'";
You will be open to SQL Injection
Warning
As Steve mentioned in comments Passwords in clear text are a vulnerability of the same magnitude of string concatenation
you make try this one
using(var con = new MysqlConnection{ ConnectionString = "your connection string " })
{
using(var command = new MysqlCommand{ Connection = con })
{
con.Open();
command.CommandText = #"SELECT level FROM userTable WHERE username=#username, password=#password";
command.AddWithValue("#username", txtusername.Text);
command.AddWithValue("#password", txtpassword.Text);
var strLevel = myCommand.ExecuteScalar();
if(strLevel == DBNULL.Value || strLevel == Null)
{
MessageBox.Show("Invalid username or password");
return;
}
else
{
MessageBox.Show("Successfully login");
hide(); // hide this form and show another form
}
}
}
use below Query
Select * from UsersTable Where Username='"+username+"' AND password='"+password+"'
Then you can make a if condition that if your query contain a result (rows) then users authenticated (exists in Table)
Note:Select query may fetch multiple users having same userName and
password, its upto you to keep usersname unique in table

How to block user login before activation asp.net c#

I am new to C#. I have Activation Data Type Bit in my database default value 0.
My question is how can I block user to login before activation email send
after registration is completed the activation is null in database but still user can login how can I fix this problem please help.
Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Loginbtn_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegisterConnectionString"].ConnectionString);
conn.Open();
string checkuser = "select count(*) from UserData where UserName='" + UserName.Text + "'";
SqlCommand com = new SqlCommand(checkuser, conn);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
conn.Close();
if (temp == 1)
{
conn.Open();
string checkPasswordQuery = "select password from UserData where UserName='" + UserName.Text + "'";
SqlCommand passComm = new SqlCommand(checkPasswordQuery, conn);
string password = passComm.ExecuteScalar().ToString().Replace(" ", "");
if (password == Password.Text && UserName.Text == "Admin" )
{
Session["New"] = UserName.Text;
Response.Redirect("~/Admin/UserManager.aspx");
}
if (password == Password.Text)
{
Session["New"] = UserName.Text;
Response.Redirect("~/Account/UserPage.aspx");
}
else
{
invalidlbl.Text = "Please check your username and password";
}
}
}
Here is the image of my database:
You said activation is null in database. So, when user tried to login, fetch and check if the activation is still null in database and if so then just so a message to user saying activate your account first and redirect him/her to home page.
EDIT: per your comment, not going to give you full code but here is an example of what I am saying. BTW, consider using SQL Parameter to avoid SQL Injection attack.
string checkuser = "select count(*) from UserData where UserName=#uname and activation != null";
SqlCommand com = new SqlCommand(checkuser, conn);
com.Parameters.Add("#uname", SqlDbType.VarChar).Value = UserName.Text.Trim();
int temp = Convert.ToInt32(com.ExecuteScalar());
if(temp > 0)
{
// do processing
}
else
{
// not activated ... throw alert
}

C# Login screen using sql database not working

I have a simple login screen which, upon user clicking login button, should run the sql query to search for rows where the username == username text box, and password == password text box. This section of my code works fine.
However when I try to run an if statement, which will open a new form and close the login form, it errors, even though I have added some message boxes to check that the statement sting comparison is correct.
Any ideas?
Login Button:
private void btnLogin_Click(object sender, EventArgs e)
{
try
{
string connection = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\DebenhamsProjectOfficeDatabase.mdf;Integrated Security=True;User Instance=True";
SqlConnection cn = new SqlConnection(connection);
cn.Open();
string userText = txtUsername.Text;
string passText = txtPassword.Text;
SqlCommand cmd = new SqlCommand("SELECT ISNULL(Username, '') AS Username, ISNULL(Password,'') AS Password FROM Users WHERE Username='" + userText + "' and Password='" + passText + "'", cn);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
MessageBox.Show(userText + " / " + dr["Username"].ToString());
MessageBox.Show(passText + " / " + dr["Password"].ToString());
if (dr["Username"].ToString() == userText && dr["Password"].ToString() == passText)
{
this.Hide();
Dashboard dashboard = new Dashboard();
dashboard.ShowDialog();
this.Close();
}
else
{
MessageBox.Show("Invalid Username or Password");
}
}
dr.Close();
cn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Login attempt:
With the advice taken from the Answers and Comments below the code has been corrected to the following (using sql parameters in the sql command):
private void btnLogin_Click(object sender, EventArgs e)
{
try
{
string connection = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\DebenhamsProjectOfficeDatabase.mdf;Integrated Security=True;User Instance=True";
SqlConnection cn = new SqlConnection(connection);
cn.Open();
string userText = txtUsername.Text;
string passText = txtPassword.Text;
SqlCommand cmd = new SqlCommand("SELECT ISNULL(Username, '') AS Username, ISNULL(Password,'') AS Password FROM Users WHERE Username = #username and Password = #password", cn);
cmd.Parameters.Add(new SqlParameter("username", userText));
cmd.Parameters.Add(new SqlParameter("password", passText));
SqlDataReader dr = cmd.ExecuteReader();
try
{
dr.Read();
if (dr["Username"].ToString().Trim() == userText && dr["Password"].ToString().Trim() == passText)
{
this.Hide();
Dashboard dashboard = new Dashboard();
dashboard.ShowDialog();
this.Close();
}
}
catch
{
MessageBox.Show("Invalid Username or Password");
}
dr.Close();
cn.Close();
}
try adding a trim() on to the end of the sql return as you check them.
dr["Username"].ToString().trim() and dr["Password"].ToString().trim()
Sometimes the Database will store extra spaces you cant see.
Simply try this: I think it will work
SqlCommand cmd = new SqlCommand("SELECT * FROM Users WHERE Username='" + userText.toString() + "' and Password='" + passText.toString() + "'", cn);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
MessageBox.Show(username + " / " + usertext);
MessageBox.Show(password + " / " + passtext);
this.Hide();
Dashboard dashboard = new Dashboard();
dashboard.ShowDialog();
this.Close();
}
else
{
MessageBox.Show("Invalid Username or Password");
}

Split user name and password credentials

I have created the following WebMethod in the back end of my application where the users login through the front end.
[WebMethod]
public String Login(String userName, String password)
{
OleDbConnection connect = new OleDbConnection(connection);
connect.Open();
OleDbCommand command = new OleDbCommand("Select * from login where userName='" + userName + "' and password ='" + password + "'", connect);
command.CommandType = CommandType.Text;
OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.SelectCommand = command;
DataSet NSNSet = new DataSet();
adapter.Fill(NSNSet);
string username = NSNSet.Tables[0].Rows[0]["firstName"].ToString() + NSNSet.Tables[0].Rows[0]["lastName"].ToString();
int userID = System.Convert.ToInt16(NSNSet.Tables[0].Rows[0]["UID"].ToString());
return username + "," + userID;
}
Currently, I have error handling in place which states -
catch(Exception ex)
{
string error = System.Convert.ToString(ex);
if (error.Contains("There is no row at position 0"))
{
status.Text = "Incorrect Username/Password combination";
}
}
This works fine, however how could I aulter my code so that it brings back a more specific error, i.e. states if the userName or password specifically are incorrect?
Don't give out to much details, just give a simple login error message, but don't say that username is incorrect or password is incorrect, cause a hacker can use that information
a simple text saying login unsuccessful should be ok
You should do like this:
public String Login(String userName, String password)
{
OleDbConnection connect = new OleDbConnection(connection);
connect.Open();
OleDbCommand command = new OleDbCommand("Select UID, firstName, lastName from login where userName=? and password =?", connect);
command.CommandType = CommandType.Text;
//to avoid sql injection
command.Parameters.Add(userName);
command.Parameters.Add(password);
OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.SelectCommand = command;
DataSet NSNSet = new DataSet();
adapter.Fill(NSNSet);
if (NSNSet.Tables[0].Rows.Count == 0)
return "Access denied";
string username = NSNSet.Tables[0].Rows[0]["firstName"].ToString() + NSNSet.Tables[0].Rows[0]["lastName"].ToString();
int userID = int.Parse(NSNSet.Tables[0].Rows[0]["UID"].ToString());
return username + "," + userID;
}
Or a better way, using DataReader for performance:
public String Login(String userName, String password)
{
OleDbConnection connect = new OleDbConnection(connection);
connect.Open();
OleDbCommand command = new OleDbCommand("Select UID, firstName, lastName from login where userName=? and password =?", connect);
command.CommandType = CommandType.Text;
//to avoid sql injection
command.Parameters.Add(userName);
command.Parameters.Add(password);
OleDbDataReader reader=command.ExecuteReader();
if (reader.Read())
{
//that means there's at least one row
string username = reader["firstName"] + " " + reader["lastName"];
int userID = int.Parse(reader["UID"].ToString());
return username + "," + userID;
}
else
{
//no combination username-password found
return "Access denied";
}
}
First, this code is open to SQL injection. Second, if you want to know specifically which element is incorrect, you have to break down your query into two components (ie. query username and password separately)
You can change you select query a little bit to this:
"select * from login where userName='"+userName+"'";
if there is no row in DataSet then write
Invalid UserName
and if user exist then check if password match or not if not match then write
Invalid Password

Categories