Issue validating user credentials in custom authentication form [closed] - c#

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I have problem with my login system here.
I can go to next form when I input the valid username and password.
And when I input wrong username and correct password, still I can go to next form.
And correct username and wrong password I can still go to next form.
What is the correct code for not letting go to next from if my username or password is wrong?
Here's my code.
private void btnEnter_Click(object sender, EventArgs e)
{
if (tbUsername.Text == "username")
{
AdminMainMenu x = new AdminMainMenu();
x.Show();
t.Play();
this.Dispose();
}
else
{
SystemSounds.Hand.Play();
MessageBox.Show("Invalid Username! ", "Error");
}
if (tbPassword.Text == "password")
{
AdminMainMenu x = new AdminMainMenu();
x.Show();
t.Play();
this.Dispose();
}
else
{
SystemSounds.Hand.Play();
MessageBox.Show("Invalid Password! ", "Error");
}
}

I can only hazard a guess at what you are asking, but if you want the username and password to both be correct before showing the form use this instead
if (tbUsername.Text == "username")
{
if(tbPassword.Text == "password")
{
AdminMainMenu x = new AdminMainMenu();
x.Show();
t.Play();
this.Dispose();
}
else
{
MessageBox.Show("Wrong password", "Error");
}
}
else
{
if(tbPassword.Text == "password")
{
MessageBox.Show("Wrong username", "Error");
}
else
{
MessageBox.Show("Wrong username and password", "Error");
}
}

You can nest the password check if block inside the successful username if block:
private void btnEnter_Click(object sender, EventArgs e)
{
if (tbUsername.Text == "username")
{
if (tbPassword.Text == "password")
{
AdminMainMenu x = new AdminMainMenu();
x.Show();
t.Play();
this.Dispose();
}
else
{
SystemSounds.Hand.Play();
MessageBox.Show("Invalid Password! ", "Error");
}
}
else
{
SystemSounds.Hand.Play();
MessageBox.Show("Invalid Username! ", "Error");
}
}
The way you have it the else block for the username check is executing when the username is wrong then the code continues to the password check. You need to make sure the form is shown only after checking both username and password.
Alternatively, you can check both individually and return from the click event if the username or password is incorrect like so:
private void btnEnter_Click(object sender, EventArgs e)
{
if (tbUsername.Text != "username")
{
SystemSounds.Hand.Play();
MessageBox.Show("Invalid Username! ", "Error");
return;
}
if (tbPassword.Text != "password")
{
SystemSounds.Hand.Play();
MessageBox.Show("Invalid Password! ", "Error");
return;
}
//If we got here in code execution, then both username and password are correct
AdminMainMenu x = new AdminMainMenu();
x.Show();
t.Play();
this.Dispose();
}

Related

Give feedback with MessageBox if nothing matches text file C#

I'm making a login system currently and I would like to present feedback when the username or the password are incorrect.
Here is the content of the text file from which I'm reading the details:
Ryan:password
Username:password
When I enter Ryan and password, it works fine and brings me to the next form.
However, when I enter Username and password, it comes up with the 'Username Incorrect' message box first, and then after I close out of that message box, it brings me to the next form.
I would like it to bring me directly to the next form without showing the Username Incorrect MessageBox first, even if I do enter the details on the second line. There would be more lines in the text file in the future.
Any help would be greatly appreciated, thanks!
Here is the code:
private void button1_Click(object sender, EventArgs e)
{
string[] userdetails = File.ReadAllLines(AppDomain.CurrentDomain.BaseDirectory + "UserDetails.txt");
foreach (string user in userdetails)
{
string[] splitDetails = user.Split(':');
Login.username = splitDetails[0];
Login.password = splitDetails[1];
label1.Text = Login.username;
label2.Text = Login.password;
if ((txtUsername.Text == Login.username) && (txtPassword.Text == Login.password))
{
MessageBox.Show("Welcome " + Login.username);
this.Hide();
frmMainMenu menu = new frmMainMenu();
menu.Show();
break;
}
else
{
if ((txtUsername.Text == Login.username) && (txtPassword.Text != Login.password))
{
MessageBox.Show("Password incorrect");
break;
}
if(txtUsername.Text != Login.username)
{
MessageBox.Show("Username incorrect");
}
}
}
}
The logic is incorrect.
Ask yourself, when should you stop going through your list of credentials?
Assuming a username is unique, I see only one situation that could break your loop, and that is "the username has been found".
As soon as you find the input username in your list, you know the loop has to break. You then only have to check whether the password is correct or not.
If the password is correct, you can open your new window and return your function, it has done its job.
And after the loop, you put your MessageBox, with a message depending on if the username has been found or not.
private void button1_Click(object sender, EventArgs e)
{
string[] userdetails = File.ReadAllLines(AppDomain.CurrentDomain.BaseDirectory + "UserDetails.txt");
bool usernameFound = false;
foreach (string user in userdetails)
{
string[] splitDetails = user.Split(':');
Login.username = splitDetails[0];
Login.password = splitDetails[1];
label1.Text = Login.username;
label2.Text = Login.password;
if (txtUsername.Text == Login.username)
{
if (txtPassword.Text == Login.Password)
{
MessageBox.Show("Welcome " + Login.username);
this.Hide();
frmMainMenu menu = new frmMainMenu();
menu.Show();
return; // we're done here, so return instead of break
}
usernameFound = true;
break; // we're not gonna find this username again, so might as well quit the loop
}
}
//we only get there if the credentials were incorrect
//so we check if the username was found, if yes, the
//password was incorrect, if not, the username was
string message = String.Empty;
if (usernameFound)
message = "Password";
else
message = "Username";
message += " incorrect";
MessageBox.Show(message);
//or shorten the above 7 lines with a ternary operator
//MessageBox.Show((usernameFound ? "Password" : "Username") + " incorrect");
}
In your senario if you had 100 users (user1..user100)
your code reads
for each line in file
check if matches
if yes make new form
else complain it isnt a match
So for user100, 99 its not a match messages will appear one for each non match before it.
You would need to code it like this
isfound=false
for each line in file
check if match
if yes set isfound and break
if isfound
show form blah
else
whine not found

Having a blank textbox crashes the program when i press the login button

Beginner programmer. I have a login button, it works completely fine when I enter the right credentials, but when I click the login button while having an empty textbox the program crashes and gives me "An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll". I tried using != null in the else if but that didn't work either. So my question is how would I be able to get an empty textbox displaying "Please enter a valid username and/or password" instead of crashing the program? Thanks!
Additional information: Input string was not in a correct format.
private void btnLogin_Click(object sender, EventArgs e)
{
Entities2 db = new Entities2();
foreach (var usert in db.Teachers)
{
if (usert.TID == Convert.ToInt32(txtLogin.Text) && usert.Password == txtPassword.Text)
{
Teach teacher = new Teach();
teacher.ShowDialog();
}
else if (usert.TID != Convert.ToInt32(txtLogin.Text) && usert.Password != txtPassword.Text)
{
MessageBox.Show("Please Enter a Valid Username and/or Password");
}
}
}
private void btnLogin_Click(object sender, EventArgs e)
{
try
{
if(txtLogin.Text!="" && txtPassword.Text!="")
{
Entities2 db = new Entities2();
foreach (var usert in db.Teachers)
{
if (usert.TID == Convert.ToInt32(txtLogin.Text) && usert.Password == txtPassword.Text)
{
Teach teacher = new Teach();
teacher.ShowDialog();
}
else if (usert.TID != Convert.ToInt32(txtLogin.Text) && usert.Password != txtPassword.Text)
{
MessageBox.Show("Please Enter a Valid Username and/or Password");
}
}
else
{
if(txtLogin.Text=="")
{
MessageBox.Show("Please Enter a Username");
}
else if(txtPassword.Text=="")
{
MessageBox.Show("Please Enter a Password");
}
}
}
Catch(Exception ex)
{
MessageBox.Show("Please Enter a Valid Username and/or Password");
}
}
And moreover this is not proper way to check and match the UserName Password. You can instead use the following approach
if(txtLogin.Text!="")
{
Entities2 db = new Entities2();
Teacher Tobj=db.Teachers.where(x=>x.TID==Convert.ToInt32(txtLogin.Text) && x.Password==txtPassword.Text).SingleOrDefault();
if (Tobj!=null)
{
Teach teacher = new Teach();
teacher.ShowDialog();
}
else
{
MessageBox.Show("Please Enter a Valid Username and/or Password");
}
}
Check if Textbox is "" before anything...
See below:
private void btnLogin_Click(object sender, EventArgs e)
{
if (txtLogin.Text != "")
{
Entities2 db = new Entities2();
foreach (var usert in db.Teachers)
{
if (usert.TID == Convert.ToInt32(txtLogin.Text) && usert.Password == txtPassword.Text)
{
Teach teacher = new Teach();
teacher.ShowDialog();
}
else if (usert.TID != Convert.ToInt32(txtLogin.Text) && usert.Password != txtPassword.Text)
{
MessageBox.Show("Please Enter a Valid Username and/or Password");
}
}
}
}
private void btnLogin_Click(object sender, EventArgs e)
{
try
{
<body of your btnLogin_Click()>
}
catch(FormatException ex)
{
MessageBox.Show("Please Enter a Valid Username and/or Password");
}
catch(Exception ex2)
{
MessageBox.Show("Error: " + ex2.Message);
}
}
You can do a try parse. If it fails to parse, it will return false and you can do some error handling (thanks Phil).
int userId = 0;
if(int.TryParse(txtLogin.Text, out userId)){
// err handling
}
Try to parse the entered user ID first, like this:
private void btnLogin_Click(object sender, EventArgs e)
{
int userId;
if (int.TryParse(txtLogin.Text, out userId))
{
Entities2 db = new Entities2();
foreach (var usert in db.Teachers)
{
if (usert.TID == userId && usert.Password == txtPassword.Text)
{
Teach teacher = new Teach();
teacher.ShowDialog();
}
else
{
MessageBox.Show("Please Enter a Valid Username and/or Password");
}
}
}
else
{
MessageBox.Show("Please Enter a Valid User ID");
}
}

C# Unreachable Code Detected

I've been messing around for over an hour now. I still don't know how to solve it even reading the Stackoverflow solution. The program works with the first username and password (test & password), when I typed in the second username and password (aaa & 123) it doesn't work.
public partial class Form2 : Form
{
String[] username = { "test", "aaa" };
String[] password = { "password", "123" };
private void btnSubmit_Click(object sender, EventArgs e)
{
try
{
for (int i = 0; i < username.Length; i++) // <------- Unreachable Code
{
if ((txtUsername.Text.Trim() == username[i]) && (txtPassword.Text.Trim() == password[i]))
{
MessageBox.Show("Login Successful. Welcome!", "Login Success", MessageBoxButtons.OK, MessageBoxIcon.None);
Form3 frm3 = new Form3();
frm3.Visible = true;
frm3.Activate();
break;
}
else
{
MessageBox.Show("You have entered an invalid input. Do you want to try again?", "Invalid Input", MessageBoxButtons.YesNo, MessageBoxIcon.Hand); break;
}
}
}
catch(Exception x)
{
MessageBox.Show("System Error! Please try again!", "System Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
}
}
}
You have break word in both if-else branches. Remove break from else. But you will get message boxes on every loop. So you need to modify your code: move message box outside the loop.
You have logical flow control issues inside of your code. As a result, you need to move the MessageBox firing outside of your loop.
If you modify your code to use lists instead of arrays and include a bit of LINQ, you can move away from a loop altogether, as well as you can benefit from less nesting.
public partial class Form2 : Form
{
List<string> username = new List<string>{ "test", "aaa" };
List<string> password = new List<string>{ "password", "123" };
private void btnSubmit_Click(object sender, EventArgs e)
{
try
{
if (txtUsername.Text.Length > 0 && txtPassword.Text.Length > 0
&& username.Any(x => x == txtUsername.Text.Trim())
&& password.Any(x => x == txtPassword.Text.Trim()))
{
MessageBox.Show(
"Login Successful. Welcome!",
"Login Success", MessageBoxButtons.OK, MessageBoxIcon.None);
Form3 frm3 = new Form3();
frm3.Visible = true;
frm3.Activate();
}
else
{
MessageBox.Show(
"You have entered an invalid input. Do you want to try again?",
"Invalid Input",
MessageBoxButtons.YesNo, MessageBoxIcon.Hand);
}
}
catch(Exception x)
{
MessageBox.Show(
"System Error! Please try again!", "System Error",
MessageBoxButtons.OK, MessageBoxIcon.Hand);
}
}
}

Login screen to show incorrect credentials [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am making a login screen in c#. How would I make it so it shows specifically if the username or password is incorrect.
private void btnSubmit_Click(object sender, EventArgs e)
{
{
string username = "Tim";
string password = "Hennings";
if ((this.txtUsername.Text == username) && (this.txtPassword.Text == password))
{
if (txtUsername.Text == username && txtPassword.Text == password)
MessageBox.Show("Log in successful");
}
else
{
MessageBox.Show("Wrong Username/Password please try again");
txtUsername.Focus();
}
}
}
How would I make it so it shows specifically if the username or password is incorrect [?]
You shouldn't. It is a security concern, when you give an attacker the details of exactly what went wrong.
For more details see:
“Username and/or Password Invalid” - Why do websites show this kind of message instead of informing the user which one was wrong?
string username = "Tim";
string password = "Hennings";
if(this.txtUsername.Text != username)
{
MessageBox.Show("Wrong Username please try again");
txtUsername.Focus();
}else if(this.txtPassword.Text != password)
{
MessageBox.Show("Wrong Password please try again");
txtPassword.Focus();
}else
{
MessageBox.Show("Log in successful");
}
private void btnSubmit_Click(object sender, EventArgs e)
{
{
string username = "Tim";
string password = "Hennings";
string outputMessage = string.Empty;
if (this.txtUsername.Text != username)
{
outputMessage = "Username incorrect";
}
if (this.txtPassword.Text != password)
{
outputMessage = "Password incorrect";
}
if (!string.IsNullOrEmpty(outputMessage))
{
MessageBox.Show(outputMessage);
}
else
{
// Password and Username matched so log them in.
}
}
}

passing username to form but username returns null c#

This code is to return the value of textbox in the Login form.
public partial class Login : Form
{
public string returnUsername()
{
string username = textBox1.Text;
return username;
}
}
This code is to allow the ChangePass form to show.
public partial class Mainmenu_Employee : Form
{
private void changePasswd_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
this.Hide();
Login login = new Login();
ChangePass passwd = new ChangePass(login);
passwd.Show();
}
}
This code is to take the username from Login form so that I can change the password of the username.
public partial class ChangePass : Form
{
Login login = null; //parent form
Mainmenu_Employee main = new Mainmenu_Employee();
public ChangePass(Login login1)
{
InitializeComponent();
login = login1;
}
private void buttonChangePass_Click(object sender, EventArgs e)
{
Model_DB_Employee emp = new Model_DB_Employee();
//Login login = new Login();
string username = login.returnUsername();
if (textBoxNewPass.Text == string.Empty || textBoxConfirmPass.Text == string.Empty)
{
MessageBox.Show("Field cannot be empty!");
}
else
{
if (textBoxNewPass.Text == textBoxConfirmPass.Text)
{
try
{
emp.changePasswd(username,textBoxConfirmPass.Text);
MessageBox.Show(username);
MessageBox.Show("Password updated!");
this.Hide();
main.Show();
}
catch(SystemException ex)
{
MessageBox.Show("Password not updated" + ex);
}
}
else
{
MessageBox.Show("Passwords do not match!");
}
}
}
Change password function:
public void changePasswd(string username, string newpass) //change password
{
Model_Employee emp = new Model_Employee();
//Hasher hash = new Hasher(); //call hasher class for hashing
//string hashed;
//string salt = emp.generateSalt(); //generate random salt
//newpass = newpass + salt; //append salt to newpass
//hashed = hash.encryption(newpass); //hash newpass
for (int i = 0; i < rows.Count; ++i)
{
if ((string)empTab.Rows[i]["username"] == username)//check if ID matches
{
empTab.Rows[i]["passwd"] = newpass; //set passwd to hash new password
//check if dataset has changes
if (dataset.HasChanges())
{
//update database
dbAdapter.Update(dataset, "employee");
MessageBox.Show("Employee Updated!");
refreshTable();
}
else
{
refreshTable();
}
}
}
}
I am trying to change a user's password when he is logged in.
When he logs in, I want to capture his username through a textbox.
After he logs in, there will be a main menu displayed.
The user needs to click on the change password link and a change password form will appear.
Therefore, I need to pass the username from the login form to the change password form in order to use a change password function. However, the issue I am facing now is that the username does not get passed from the login form to the change password form.
The problem is the line:
Login login = new Login();
This is shadowing the login instance field with a new instance of Login as a local variable, so rather than accessing the Login created earlier that the user has interacted with, you're accessing a blank one. You can just delete the above line of code.
The problem is that with Login login = new Login() you´re shadowing your class instance variable login. Try:
private void buttonChangePass_Click(object sender, EventArgs e)
{
Model_DB_Employee emp = new Model_DB_Employee();
string username = login.returnUsername();
if (textBoxNewPass.Text == string.Empty || textBoxConfirmPass.Text == string.Empty)
{
MessageBox.Show("Field cannot be empty!");
}
else
{
if (textBoxNewPass.Text == textBoxConfirmPass.Text)
{
try
{
emp.changePasswd(username,textBoxConfirmPass.Text);
MessageBox.Show(username);
MessageBox.Show("Password updated!");
this.Hide();
main.Show();
}
catch(SystemException ex)
{
MessageBox.Show("Password not updated" + ex);
}
}
else
{
MessageBox.Show("Passwords do not match!");
}
}
}
When, between these two lines, does the username in the new login get set?
Login login = new Login();
string username = login.returnUsername();
You never show the Login form, how do you suppose that someone sets the textBox1 with an actual username?
You need something like this
string username = string.Empty;
Model_DB_Employee emp = new Model_DB_Employee();
using(Login login = new Login())
{
if(DialogResult.OK == login.ShowDialog())
username = login.returnUsername();
}
if(username == string.Empty)
{
MessageBox.Show("Username required");
return;
}

Categories