In my application I have a login system. It's basic so I don't need any encryption. The problem is that when I want to login, I insert the credentials (username and password) but it doesn't make anything. My code is:
public void iniciarsessaobutton_Click(object sender, EventArgs e)
{
string txtuser = textusername.Text;
string txtpass = textlogin.Text;
MySqlCommand cmd = new MySqlCommand("SELECT password FROM empregados WHERE user='" + txtuser + "';", mConn);
mConn.Open();
MySqlDataReader login = cmd.ExecuteReader();
login.Read();
string getpass = login["password"].ToString();
if (getpass == txtpass)
{
mConn.Close();
MessageBox.Show("Sessão iniciada");
Admin adm = new Admin();
this.Hide();
adm.Show();
}
else
{
mConn.Close();
MessageBox.Show("Não foi possivel iniciar sessão. Insira a password corretamente.");
}
}
I'd like to propose some fixes mentioned in the comments along with some general improvements. See my comments in the code for the issues addressed:
public void iniciarsessaobutton_Click(object sender, EventArgs e)
{
string txtuser = textusername.Text;
string txtpass = textlogin.Text;
// Put your connection into a using() block
using (MySqlConnection conn = new MySqlConnection(variableWithYourConnectionStringHere))
{
// Put your commend into a using() block
// enclose your column names in backticks to avoid conflict with MySql reserved keywords
// add a placeholder (#username) for your parameter
// use LIMIT 1 if you only expect 1 row matching your condition
using(MySqlCommand cmd = new MySqlCommand("SELECT `password` FROM empregados WHERE `user` = #username LIMIT 1", conn))
{
mConn.Open();
// add a parameter with your TextBox value
cmd.Parameters.AddWithValue("#username", txtuser);
// If you only retrieve 1 value, use ExecuteScalar to return only 1 value
// cast the returned object as string
string getpass = cmd.ExecuteScalar() as string;
if (getpass == txtpass)
{
MessageBox.Show("Sessão iniciada");
Admin adm = new Admin();
this.Hide();
adm.Show();
}
else
{
MessageBox.Show("Não foi possivel iniciar sessão. Insira a password corretamente.");
}
}
}
}
Related
So i have been trying to resolve this issue for a while now, with no awail. Everything works but when i try to login with a "succesfully registered user", it still shows invalid credentials, meaning that the save didn't succeed,
This is my code:
using System;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace SchoolManagementApplication
{
public partial class LoginDialog : Form
{
public LoginDialog()
{
InitializeComponent();
}
private bool VerifyUserCredentials(string username, string password)
{
bool isValidUser = false;
// Connection string
string connectionString = Properties.Settings.Default.UnPConnectionString;
// SQL query
string query = "SELECT COUNT(*) FROM [Table2] WHERE Username = #Username AND Password = #Password";
// Create a new connection
using (SqlConnection connection = new SqlConnection(connectionString))
{
// Create a new command
using (SqlCommand command = new SqlCommand(query, connection))
{
// Add parameters to the query
command.Parameters.AddWithValue("#Username", username);
command.Parameters.AddWithValue("#Password", password);
// Open the connection
connection.Open();
// Execute the query
int result = (int)command.ExecuteScalar();
// Check if the result is greater than 0
if (result > 0)
{
isValidUser = true;
}
connection.Close();
}
}
return isValidUser;
}
public void AddUser(string username, string password)
{
string connectionString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\shayan.homaiesfahan\\Desktop\\SchoolManagementApplication\\SchoolManagementApplication\\bin\\Debug\\Unp.mdf;Integrated Security=True";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
// insert the new user into the table
string insertSql = "INSERT INTO [Table2] (Username, Password) VALUES (#Username, #Password)";
using (SqlCommand insertCommand = new SqlCommand(insertSql, connection))
{
insertCommand.Parameters.AddWithValue("#Username", username);
insertCommand.Parameters.AddWithValue("#Password", password);
insertCommand.ExecuteNonQuery();
}
connection.Close();
}
}
private void BtnOK_Click(object sender, EventArgs e)
{
// Get the entered username and password
string username = tbxUsername.Text;
string password = tbxPassword.Text;
// Verify the user credentials
if (VerifyUserCredentials(username, password))
{
MessageBox.Show(string.Format("Welcome: {0}", username));
// Code to open the main application goes here
this.Hide();
MainInterface MI = new MainInterface();
MI.Show();
}
else
{
MessageBox.Show("Invalid credentials. Please try again.");
//// Clear the textboxes
tbxUsername.Text = "";
tbxPassword.Text = "";
}
}
private void Btn_register_Click(object sender, EventArgs e)
{
string username = tbxUsername.Text;
string password = tbxPassword.Text;
// Verify that the username and password are not empty
if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
{
// Call the AddUser method
AddUser(username, password);
// Show a message that the user has been registered
MessageBox.Show("You have been successfully registered!");
// Clear the textboxes
tbxUsername.Text = "";
tbxPassword.Text = "";
}
else
{
// Show a message that the username and password are required
MessageBox.Show("Username and password are required.");
}
}
private void btnCancel2_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
It did work in one point, but somehow it stopped working.
I'm trying to get my LoginButton to work, it isn't really doing what I want it to do.
I already have a RegisterButton which works perfectly and creates the account without any problems, but when trying to do my LoginButton it connects to the database but doesn't really check if the account exists using selectQuery and it should change WarningLabel.Text to "Wrong Name or Password". it does go through the first try and changes the WarningLabel.Text to "Welcome " + NameInput.Text;
private void LoginButton_Click(object sender, System.EventArgs e)
{
string selectQuery = $"SELECT * FROM bank.user WHERE Name='{NameInput.Text}' AND Password='{GetHashString(PasswordInput.Text)}';";
MySqlCommand cmd;
connection.Open();
cmd = new MySqlCommand(selectQuery, connection);
try
{
cmd.ExecuteNonQuery();
WarningLabel.Text = "Welcome " + NameInput.Text;
} catch
{
WarningLabel.Text = "Wrong Name or Password";
}
connection.Close();
}
Best Regards - Nebula.exe
The ExecuteNonQuery is not intented to be used with SQL statements that return data, you should use ExecuteReader or ExecuteScalar, you can check the MySqlCommand.ExecuteReader documentation
Warning: Your code does have a SQL Injection vulnerability in this part of the SQL statement Name='{NameInput.Text}' Check this SQL Injection explanation
Usage example (from the documentation, slightly modified):
using (MySqlConnection myConnection = new MySqlConnection(connStr))
{
using (MySqlCommand myCommand = new MySqlCommand(mySelectQuery, myConnection))
{
myConnection.Open();
MySqlDataReader myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
Console.WriteLine(myReader.GetString(0));
}
}
}
You should check if there are records returned. cmd.ExecuteNonQuery(); won't tell you if records are returned because it will just execute the query. You should use ExecuteScalar or a MySQL Data Reader ExecuteReader and track the results.
Note : Your code is prone to SQL Injections, you might want to use Parameters in your query like #name and #password.
Your Query goes something like this.
string selectQuery = $"SELECT IFNULL(COUNT(*),0) FROM bank.user WHERE Name=#name AND Password=#password;";
Then use parameters
cmd.parameters.AddWithValue(#name, NameInput.Text);
cmd.parameters.AddWithValue(#password, GetHashString(PasswordInput.Text));
Then verify if the query returns result
If cmd.ExecuteScalar() > 0
//If count is > 0 then Welcome
//Else Wrong username or password
End If
Your life, made easy:
private void LoginButton_Click(object sender, System.EventArgs e)
{
var cmd = "SELECT * FROM bank.user WHERE Name=#name AND Password=#pw";
using var da = new MySqlDataAdapter(cmd, connection);
da.SelectCommand.Parameters.AddWithValue("#name", NameInput.Text);
da.SelectCommand.Parameters.AddWithValue("#pw",GetHashString(PasswordInput.Text));
var dt = new DataTable();
da.Fill(dt);
if(dt.Rows.Count == 0)
WarningLabel.Text = "Wrong Name or Password";
else
WarningLabel.Text = $"Welcome {dt.Rows[0]["FullName"]}, your last login was at {dt.Rows[0]["LastLoginDate"]}";
}
Your life, made easier (with Dapper):
class User{
public string Name {get;set;} //username e.g. fluffybunny666
public string FullName {get;set;} //like John Smith
public string Password {get;set;} //hashed
public DateTime LastLoginDate {get;set;}
}
//or you could use a record for less finger wear
record User(string Name, string FullName, string Password, DateTime LastLoginDate);
...
using var c = new MySqlConnection(connection):
var u = await c.QuerySingleOrDefaultAsync(
"SELECT * FROM bank.user WHERE Name=#N AND Password=#P",
new { N = NameInput.Text, P = GetHashString(PasswordInput.Text)}
);
if(u == default)
WarningLabel.Text = "Wrong Name or Password";
else
WarningLabel.Text = $"Welcome {u.FullName}, your last login was at u.LastLoginDate";
Hello im trying to create login form that saves your UserID to Userdetails class. But for some reason log in doesnt work.I think there is somewhere mistake in if (login.Read()) in validate_login but im not sure. If i put messagebox to if (r.valid) it doesnt work so thats why i think somewhere in if (login.Read()) . Any form of help would be welcome. Thanks.
I have tryed rewriting mysql query, ( cmd.CommandText = )
If i remove if (r != null) i get this error System.NullReferenceException: 'Object reference not set to an instance of an object.'
r was null.
private void db_connection()
{
try
{
conn = "..connection string..";
connect = new MySqlConnection(conn);
connect.Open();
}
catch (MySqlException e)
{
throw;
}
}
private LoginUser validate_login(string user, string pass)
{
db_connection();
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = "Select * from table2 where username=#user and password=#pass";
cmd.Parameters.AddWithValue("#user", user);
cmd.Parameters.AddWithValue("#pass", pass);
cmd.Connection = connect;
LoginUser usr = null;
MySqlDataReader login = cmd.ExecuteReader();
if (login.Read())
{
usr = new LoginUser();
usr.UserID = login["UserID"].ToString();
usr.valid = true;
}
return usr;
}
private void button1_Click(object sender, EventArgs e)
{
{
string user = username.Text;
string pass = password.Text;
var r = validate_login(user, pass);
if (r != null)
{
if (r.valid)
{
MessageBox.Show("validated");
MySqlCommand cmd = new MySqlCommand();
MySqlDataReader reader = cmd.ExecuteReader();
Console.WriteLine(String.Format("{0}", r.UserID));
UserDetails.m_gnUserId = Convert.ToInt32(r.UserID);
}
}
}
}
validate_login should work as follows:validate_login should run query and search for username and password that is same as textbox #user and #pass.
button1_Click should start that validate_login
Note:I know i need to hash passwords in my db and i currently dont. Its my next step after this.
Your problem is probably because you return null, if there were no such record in database.
LoginUser usr = null;
If that's not what you want, you should return new LoginUser with field valid set to false.
var usr = new LoginUser(){ valid = false };
And don't forget to check for that in your button's event handler.
So I'm trying to create simple button that decides if you are admin or user.
But I cant get it to work properly. I'm connected to MySQL db but when I click button with either admin/user account (stored in db) I get:
"you are an admin"
So I guess I have mistake somewhere but cant see where:
private void button1_Click(object sender, EventArgs e)
{
MySqlConnection cn = new MySqlConnection("Server=;Database=;Uid=;Pwd=;");
MySqlCommand cmd = new MySqlCommand("SELECT usertype FROM table1 ", cn);
cmd.Parameters.AddWithValue("usertype", usertype.Text);
cn.Open();
string usertype123 = cmd.ExecuteScalar()?.ToString();
if (usertype123 == "admin")
{
MessageBox.Show("you are an admin");
}
else
{
MessageBox.Show("You are an user ");
}
cn.Close();
}
If you don't add a WHERE statement to your sql command you will always retrieve the value from the first column of the first row returned by the database engine. You should change your code to something like this
private void button1_Click(object sender, EventArgs e)
{
// I assume you have a field named UserID as the primary key of your table1
string sqlCmd = #"SELECT usertype FROM table1 WHERE UserID=#id";
using(MySqlConnection cn = new MySqlConnection("....."))
using(MySqlCommand cmd = new MySqlCommand(sqlCmd, cn))
{
cmd.Parameters.Add("#id", MySqlDbType.Int32).Value = currentUserid;
cn.Open();
string usertype123 = cmd.ExecuteScalar()?.ToString();
if (usertype123 == "admin")
{
MessageBox.Show("you are an admin");
}
else
{
MessageBox.Show("You are an user ");
}
}
}
Now the problem is how to define the variable currentUserId This is something that you need to retrieve when the user logs in and conserve at the class level to reuse when needed. Notice also that connections are disposable objects and as such your need to dispose them as soon as you have finished to use them. The using statement helps to do this
I Retrive values from admin table and then i store in String variable and finally i compare values my code is not redirect to another page
protected void Button1_Click(object sender, EventArgs e)
{
String uname = (String)txtuser.Text;
String upass = (String)txtp.Text;
String cuser = "";
String cpass = "";
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["HMSS"].ToString());
conn.Open();
String query = "select username,password from admin where username=#username";
SqlCommand cmd = new SqlCommand(query,conn);
cmd.Parameters.AddWithValue("username", uname);
cmd.Parameters.AddWithValue("password", upass);
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
cuser = rdr["username"].ToString();
cpass = rdr["password"].ToString();
}
if (cuser==uname && cpass==upass)
{
Session["user"] = cuser;
Response.Redirect("admin.aspx",true);
}
}
}
Can you check following code lines?
String uname = (String)txtuser.Text;
(string) implicit cast is not necessary: Text property is already a string.
conn.Open();
missing conn.Close(); it's better to add also try/catch
String query = "select username,password from admin where username=#username";
cmd.Parameters.AddWithValue("password", upass);
why don't you check also password in the query?
cuser = rdr["username"].ToString();
It means null value not allowed
if (cuser==uname && cpass==upass)
Problem with case sensitive/trim. In debug do you arrive on Response.Redirect?
Response.Redirect("admin.aspx",true);
Maybe ~/admin.aspx
try to change your condition to below
if (cuser.ToLower() == uname.ToLower() && cpass.ToLower() == upass.ToLower())