C# how would i add basic validation to my application, so that it displays a messagebox for when incorrect username or passwords are entered [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have connected a sql database to my windows form application in C# visual studio 2012, the database contains one table with three columns for Username, Password and Role.
Picture of my Table
Inside the table is data for username and password, there is also two user types in the role column which determine the form you will be directed to when logging in depending on whether your role is an admin or client.
picture of the data in my form
I now have the code for the login form so that it can detect whether a user is an admin or client when logging in but the problem is that i have no username and password validation which displays a messagebox detailing when a user has entered incorrect information.
Could someone please adapt my code so that it displays a messagebox showing that the user has entered an incorrect username or password if they have unsuccessfully tried to log in.
Here is my code below
private void button3_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|Data.mdf;Integrated Security=True");
SqlDataAdapter sda = new SqlDataAdapter("Select Role from Login Where UserName='" + textBox1.Text + "' and Password='" + textBox2.Text + "' ",con);
DataTable dt = new System.Data.DataTable();
sda.Fill(dt);
if(dt.Rows.Count == 1)
{
if (dt.Rows.Count == 1)
{
switch (dt.Rows[0]["Role"] as string)
{
case "Admin":
{
this.Hide();
AdminMenu ss = new AdminMenu();
ss.Show();
break;
}
case "Client":
{
this.Hide();
MenuForm mf = new MenuForm();
mf.Show();
break;
}
default:
{
// ... handle unexpected roles here...
break;
}
}
}
}
}
private void Login_Load(object sender, EventArgs e)
{
}
private void Login_FormClosing(object sender, FormClosingEventArgs e)
{
Application.ExitThread();
}
}
}

You just need to put a else condition in this case like this
else
{
MessageBox.Show("Login Details are incorrect.");
}
and also I am unable to understand why do you have to if condition like this
if(dt.Rows.Count == 1)
{
if (dt.Rows.Count == 1)
{
Whereas only first one could serve your purpose.
So the code would look something like this
private void button3_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|Data.mdf;Integrated Security=True");
SqlDataAdapter sda = new SqlDataAdapter("Select Role from Login Where UserName='" + textBox1.Text + "' and Password='" + textBox2.Text + "' ",con);
DataTable dt = new System.Data.DataTable();
sda.Fill(dt);
if(dt.Rows.Count == 1)
{
switch (dt.Rows[0]["Role"] as string)
{
case "Admin":
{
this.Hide();
AdminMenu ss = new AdminMenu();
ss.Show();
break;
}
case "Client":
{
this.Hide();
MenuForm mf = new MenuForm();
mf.Show();
break;
}
default:
{
MessageBox.Show("Please contact your administrator");
break;
}
}
}
else
{
MessageBox.Show("Login Details are incorrect.");
}
}
Now if the case is where it is neither a Client nor a Admin you can just show a MessageBox.
And definitely your code need to be prevent from SQL injection

Related

How to display username when you logged on? c# windows forms and mysql database

I'm student and I have one project, to make a program and database for Coffee shop.
I have login window and it's connected with mysql database. You have only textbox for enter password and when you enter correct password(password is in database) you are logged on, and move to another form(main interface). Now I want to only display name of logged user and I don't know how to...
This is the code, I'm from Croatia so some of words are Croatian.
public void button_1_Click(object sender, EventArgs e)
{
string upit = "SELECT * FROM zaposlenik WHERE sifra_z = '" + textbox_prijava.Text+"'";
string manager = "SELECT * FROM manager WHERE sifra_m = '" + textbox_prijava.Text + "'";
MySqlDataAdapter sda = new MySqlDataAdapter(upit, connection);
DataTable tablica = new DataTable();
sda.Fill(tablica);
MySqlDataAdapter sda2 = new MySqlDataAdapter(manager, connection);
DataTable tablica2 = new DataTable();
sda2.Fill(tablica2);
if (tablica.Rows.Count >= 1 || tablica2.Rows.Count >= 1)
{
GlavnoSučelje x = new GlavnoSučelje();
x.Show();
this.Hide();
}
else if (textbox_prijava.Text == "")
{
MessageBox.Show("Niste upisali šifru!", "Greška", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
MessageBox.Show("Kriva šifra konobara!", "Greška", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
textbox_prijava.Clear();
This is what I would do.
Have a static class to save user details:
public class UserDetails
{
private static string _username;
public static string Username
{
get
{
return _username;
}
set
{
_username = value;
}
}
}
Here we are logging in and saving user details.
public partial class Login : Form
{
public Login()
{
InitializeComponent();
}
//Login Button
private void loginBtn(object sender, EventArgs e)
{
//MySQL connection to retrieve user details into a class on successful log in
using (var conn = new MySqlConnection(ConnectionString.ConnString))
{
conn.Open();
//Get count, username
using (var cmd = new MySqlCommand("select count(*), username from users where username = #username and password = MD5(#password)", conn))
{
cmd.Parameters.AddWithValue("#username", usernameTextBox.Text);
cmd.Parameters.AddWithValue("#password", passwordTextBox.Text);
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
//Check whether user exists
if (dt.Rows[0][0].ToString() == "1")
{
//If the user exist - allow to log in
//Store the information from the query to UserDetails class to be used in other forms
UserDetails.Username = dt.Rows[0][1].ToString();
//Hide this form and open the main Dashboard Form
this.Hide();
var dashboard = new Dashboard();
dashboard.Closed += (s, args) => this.Close();
dashboard.Show();
}
//If failed login - show message
else
{
MessageBox.Show("Login failed", "Technical - Login Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}
}
}
To use the username.. just simply use UserDetails.Username

Administrator exclusive page?

I'm currently making a windows form login system and I've worked out how to set up a general everyone can see the main page system but for the admin i want it to open a new form (form3) which will contain customer orders.
i need it to open up from Login Button.Click just like form2 opens to show the store page for generalised users. i don't have a column in my table for user roles either.
I've tried if else statements and run into issues with bools not excepting strings etc.
using System;
using System.Data;
using System.Windows.Forms;
using MySql.Data;
using MySql.Data.MySqlClient;
namespace Aliena_Store
{
public partial class Form1 : Form
{
//string ConnectionState = "";
public Form1()
{
InitializeComponent();
}
MySqlConnection connection = new MySqlConnection("server=localhost;user=root;database=Aliena_Store;port=3306;password=Blackie");
MySqlDataAdapter adapter;
DataTable table = new DataTable();
private void UsernameLogin_TextChanged(object sender, EventArgs e)
{
}
private void PasswordLogin_TextChanged(object sender, EventArgs e)
{
}
private void LoginButton_Click(object sender, EventArgs e)
{
adapter = new MySqlDataAdapter("SELECT `username`, `password` FROM `User_Details` WHERE `username` = '" + UsernameLogin.Text + "' AND `password` = '" + PasswordLogin.Text + "'", connection);
adapter.Fill(table);
var usernameSaved = UsernameLogin.Text;
var passwordSaved = PasswordLogin.Text;
Panel panel1 = new Panel();
if (table.Rows.Count <= 0)
{
panel1.Height = 0;
var result = MessageBox.Show("Username/Password Are Invalid or does not exist. Please sign up or retry your details");
}
else
{
panel1.Height = 0;
this.Hide();
if (table.Rows.Count >= 0)
{
Form nextForm;
var result = MessageBox.Show("Login successful...Now logging in");
this.Hide();
object user = UsernameLogin.Text;
object password = PasswordLogin.Text;
if (user = "root" & password = "Pa$$w0rd")
{
nextForm = new Form3();
}
else
{
nextForm = new Form2();
}
nextForm.ShowDialog();
}
//Form2 f2 = new Form2();
//f2.ShowDialog();
//if login is successful needs to lead to another screen - if matches my account standard store screen or make root account just for the admin page
}
table.Clear();
}
private void EmailSignUp_TextChanged(object sender, EventArgs e)
{
}
private void UsernameSignUp_TextChanged(object sender, EventArgs e)
{
}
private void PasswordSignUp_TextChanged(object sender, EventArgs e)
{
}
private void SignUpButton_Click(object sender, EventArgs e)
{
//connection.Open();
string Query = "insert into User_Details (Email,Username,Password) values('" + this.EmailSignUp.Text + "', '" + this.UsernameSignUp.Text + "','" + this.PasswordSignUp.Text + "');";
//string insertQuery = "INSERT INTO User_Details(Email,Username,Password)VALUES('" + EmailSignUp.Text + "','" + UsernameSignUp.Text + "'," + PasswordSignUp.Text + ")";
MySqlCommand command = new MySqlCommand(Query,connection);
try
{
if (command.ExecuteNonQuery() == 1)
{
MessageBox.Show("Data Inserted");
connection.Close();
}
else
{
MessageBox.Show("Data Not Inserted");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
connection.Close();
}
}
}
}
A couple of things.
You need a User object in your application that stores user properties. This object can have an IsAdmin property that you can use later in your code.
Alternately, if you don't want to create and maintain a User object, you make another call to the database to see whether or not the user is an admin and store the result local to your method.
You then instantiate Form3 instead of Form2 based on whether or not the user is an admin.
Form nextForm;
var result = MessageBox.Show("Login successful...Now logging in");
this.Hide();
if (user.IsAdmin) {
nextForm = new Form3();
} else {
nextForm = new Form2();
}
nextForm.ShowDialog();
PS: I hope you are not storing passwords in plain text in your database like it seems you are.

Retrieving data from a Datatable in C#

I have a data able that has the three columns: Username Password and Name.
I have a login in screen that checks that checks the username and password to allow for access or not. I am trying to display the Name of the user onto another Form, but what I have is not working.
The program runs until i press login and then an IndexOutOfRangeException is shown. I feel like I am not calling the correct cell that the data is located in, but I can not figure it out. I am very new to data tables.
Login Form:
namespace Inventory_Program
{
public partial class Login : Form
{
public string name;
public Login()
{
InitializeComponent();
}
/*
* Used when user accepts to login. username and password must be correct or error message will display
* Using a table in sql form.
*/
private void loginButton_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection(#"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = C:\Users\brand\Documents\Data.mdf; Integrated Security = True;");
SqlDataAdapter adapter = new SqlDataAdapter("Select Count(*) From Login where Username='" + usernameTextfield.Text + "' and Password = '" + passwordTextfield.Text + "'", connection);
DataTable dt = new DataTable();
adapter.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
name = dt.Rows[0][3].ToString();
this.Hide();
MainGUIPanel mainview = new MainGUIPanel();
mainview.Show();
}
else
{
MessageBox.Show("Username or Password Incorrect! Try Again!");
}
} //end of login button
//can canel out of login in screen, closes window.
private void cancelButton_Click(object sender, EventArgs e)
{
this.Close();
} //end of cancel button
public string getName()
{
return name;
}
}
}
MainGuiView:
namespace Inventory_Program
{
public partial class MainGUIPanel : Form
{
Login login = new Login();
public MainGUIPanel()
{
InitializeComponent();
//runs the current time and data
currentTime.Start();
}
//Method is adding a horizontal line to the top panel
private void topControlPanel_Paint(object sender, PaintEventArgs e)
{
Graphics graphics = e.Graphics;
Pen pen = new Pen(Color.Black, 1);
graphics.DrawLine(pen, 1091, 93, 00, 93);
graphics.Dispose();
nameLabel.Text = login.getName();
}
//allows for the current time and date to be displayed in the top panel
private void currentTime_Tick(object sender, EventArgs e)
{
DateTime dateTime = DateTime.Now;
}
private void inventoryButton_Click(object sender, EventArgs e)
{
}
}
}
Select Count(*) From Login where Username='" + usernameTextfield.Text + "' and Password = '" + passwordTextfield.Text + "'"
Puts only one item in your adaptor: a table in it with nothing more than a number (from Count(*) at dt.Rows[0][0].
You would want something like:
Select UserName From Login where Username='" + usernameTextfield.Text + "' and Password = '" + passwordTextfield.Text + "'"
See Below! This is very vulnerable to all them hackers out there!
and
name = dt.Rows[0][0].ToString();
A word of caution, and this is important: I really encourage you to look up sql server injection attacks. Your code is very vulnerable to this. A marginally experienced programmer could log into your application or wipe out your database without credentials, just by typing some code in your username or password field.
The error is located at: name = dt.Rows[0][3].ToString();.
You select: count(*), which only will return
1column.
You need to select the columns you want to show.
you don't need to count the results since your where clause should select distinct results. Instead check if the datatables rows.count is larger than 1.

C# SQL Login that uses somekind of authentication

I'm in the need of some help probably because I can't express very well what I want on google.
private void LogInBt_Click(object sender, EventArgs e)
{
const string conString = #"Data Source=.\SQLEXPRESS;AttachDbFilename=H:\Jogos.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
SqlConnection con = new SqlConnection(conString);
con.Open();
SqlCommand log = new SqlCommand("SELECT * FROM Funcionario WHERE [e-mail] ='" + textBox1.Text + "' and Password ='" + textBox2.Text + "'", con);
SqlDataReader dr;
dr = log.ExecuteReader();
int count = 0;
while (dr.Read())
{
count += 1;
}
if (count == 1)
{
MessageBox.Show("Login Succesfull");
if ()
{
Form menu = new MenuPrincipalAdmin();
menu.Show();
this.Hide();
}
else
{
Form menu = new MenuPrincipalFunc();
menu.Show();
this.Hide();
}
}
else if (count > 0)
MessageBox.Show("Duplicate e-mail and password.");
else
MessageBox.Show("E-mail or Password invalid.");
textBox1.Clear();
textBox2.Clear();
con.Close();
}
After the "Login Sucessfull" message box I wanted to make something like if permission = Admin then opens the AdminMenu else opens the WorkerMenu.
I think it's possible but not sure since I can't get my mind over it.
I would recommend you to learn, how the Auth works on the sample ASP.Net application in Visual Studio (it would be the same in MVC and WinForms).
Then you could use that approach and similar DB in your application. It is really common functionality nowadays so there is no need to invent anything here.
Generally, it shouldn't be possible to store duplicated logins (and of cause login+password) in your database. You should use constraints for it.
For the logic below you should use Roles. For instance, you could use Users-UsersInRoles-Roles DB structure.
if ()
{
Form menu = new MenuPrincipalAdmin();
menu.Show();
this.Hide();
}
else
{
Form menu = new MenuPrincipalFunc();
menu.Show();
this.Hide();
}

Form loading again when the data in the drop down is selected

I have a registration where the user will enter the following details:
Email address,
Password,
Confirm password,
A drop down menu with option Employee or Contractor.
When Employee is selected they are not required to provide start date but for contractor they have to provide start date.
protected void Button1_Click(object sender, EventArgs e)
{
{
{
SqlConnection sqlCon = new SqlConnection(strCon);
SqlCommand cmd = new SqlCommand("UpdateRequest", sqlCon);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "UpdateRequest";
cmd.Connection = sqlCon;
cmd.Parameters.AddWithValue("#EmailAddress", txtEmailAddress.Text);
cmd.Parameters.AddWithValue("#Password", txtPassword.Text);
cmd.Parameters.AddWithValue("#ConfirmPassword", txtConfirmPassword.Text);
cmd.Parameters.AddWithValue("#JobRole", ddJobRole.Text);
cmd.Parameters.AddWithValue("#StartDate", txtStartDate.Text);
SqlParameter rpv = new SqlParameter();
rpv.DbType = DbType.Int32;
rpv.Direction = ParameterDirection.ReturnValue;
cmd.Parameters.Add(rpv);
try
{
sqlCon.Open();
cmd.ExecuteScalar();
int retValue = Convert.ToInt32(rpv.Value);
if (retValue == 10)
lblMessage.Text = "Request was sent successfully!";
if (retValue == 11)
lblMessage.Text = "*Email Address is already registered.";
if (retValue == 12)
lblMessage.Text = "*Passwords do not match.";
if (retValue == 13)
lblMessage.Text = "Sorry, Your application was already denied earlier.";
}
catch (Exception)
{
lblMessage.Text = "";
}
}
}
}
protected void ddJobRole_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddJobRole.SelectedValue == "Contractor")
{
RequiredFieldValidator27.Enabled = true; //Initally disabled it
}
else
{
RequiredFieldValidator27.Enabled = false;
}
}
Here the problem is whenever I select any option from the drop down the form loads again and asks password and confirm password for the second time. Can anyone tell me what the problem is?
The password and the confirmation password fields are not kept their values after the post back for security reasons. This input controls are not have the same behavior as the rest controls.
Now from the code I see, you do not actually need to make full post back for this behavior on code behind, you can easy use javascript and do the same on client side with out post back, and without loose the input of the password.

Categories