How to validate username and password using array in - c#

Hi I would like to make a login screen wherein the user will input a username and password.but how do I validate it using an array? please help thank you
int[] username = { 807301, 992032, 123144 ,123432};
string[] password = {"Miami", "LosAngeles" ,"NewYork" ,"Dallas"};
if (username[0].ToString() == password[0])
{
MessageBox.Show("equal");
}
else
{
MessageBox.Show("not equal");
}

You need to find the index of the username first from your array username. Then based on that index compare the password from password array.
int[] username = { 807301, 992032, 123144, 123432 };
string[] password = { "Miami", "LosAngeles", "NewYork", "Dallas" };
int enteredUserName = 123144;
string enteredPassword = "NewYork";
//find the index from the username array
var indexResult = username.Select((r, i) => new { Value = r, Index = i })
.FirstOrDefault(r => r.Value == enteredUserName);
if (indexResult == null)
{
Console.WriteLine("Invalid user name");
return;
}
int indexOfUserName = indexResult.Index;
//Compare the password from that index.
if (indexOfUserName < password.Length && password[indexOfUserName] == enteredPassword)
{
Console.WriteLine("User authenticated");
}
else
{
Console.WriteLine("Invalid password");
}

Why do you not use a dictionary? A dictionary is some kind of array but it combines matching keys and values. TryGetValue will try to look up the username. If no username is found, the function will return false otherwise it will return true and the matching password. This password can be used to validate the password entered by the user.
Dictionary<int, string> userCredentials = new Dictionary<int, string>
{
{807301, "Miami"},
{992032, "LosAngeles"},
{123144, "NewYork"},
{123432 , "Dallas"},
};
int userName = ...;
string password = ...;
string foundPassword;
if (userCredentials.TryGetValue(userName, out foundPassword) && (foundPassword == password))
{
Console.WriteLine("User authenticated");
}
else
{
Console.WriteLine("Invalid password");
}

Related

Cannot validate properly the username and password using Array.Find()

I'm trying to make a username and login system to validate if the username and password passed by an user by input matches the username and password in an array of objects. I did using Array.Find() but when I run the program, the user and password are asked twice and I have to put them twice correct so I can advance which does not make sense...
Utilizador[] usersIniciais = utilizadoresDefault.UtilizadoresDefault(utilizadoresDefault.GenerateID());
PersonalTrainer[] ptsIniciais = ptsDefault.PTsDefault(utilizadoresDefault.GenerateID());
int option = novoLogin.LoginInicial();
Tuple<string, string> strings = novoLogin.DadosLogin(option);
string username = strings.Item1;
string password = strings.Item2;
novoLogin.ValidacaoDados(username, password, usersIniciais);
Console.ReadLine();
}
}
namespace RSGymPT.Classes
{
internal class Login
{
public static void Log(string Username)
{
Console.WriteLine($"User Logged: {Username}");
}
public int LoginInicial()
{
int option;
do
{
Console.Clear();
Console.WriteLine("Seleciona a opção pretendida: \n");
Console.WriteLine("1. Login");
Console.WriteLine("2. Sair\n");
Console.Write("A tua opção: ");
Int32.TryParse(Console.ReadLine(), out option);
} while (option != 1 && option != 2);
return option;
}
public Tuple<string, string> DadosLogin(int option)
{
if (option == 1)
{
Console.Clear();
Console.WriteLine("Please insert your Login data: \n");
Console.Write("User: ");
Username = Console.ReadLine();
Console.Write("Password: ");
Password = Console.ReadLine();
return Tuple.Create(Username, Password);
}
else if (option == 2)
{
Console.Clear();
Console.WriteLine("See you soon.\n");
Console.ReadKey();
Environment.Exit(0);
}
return Tuple.Create(Username, Password);
}
public void ValidacaoDados(string user, string password, Utilizador[] utilizadores)
{
Utilizador utilizador = Array.Find(utilizadores, element => element.NomeUtilizador == user);
do
{
Console.Clear();
Console.Write("User: ");
Username = Console.ReadLine();
Console.Write("Password: ");
Password = Console.ReadLine();
if (utilizador != null && utilizador.Password.Equals(password))
{
Console.WriteLine("Login correct");
}
else
{
Console.WriteLine("Bye");
Console.ReadKey();
Console.WriteLine();
Environment.Exit(0);
}
} while (Username == null || Password == null);
}
}
namespace RSGymPT.Classes
{
internal class Utilizador
{
public Utilizador[] UtilizadoresDefault(int id)
{
Utilizador[] usersInicial = new Utilizador[]
{
new Utilizador {Id = GenerateID(), Nome = "user1", NomeUtilizador = "user1user", Password = "user1234"},
new Utilizador {Id = GenerateID(), Nome = "user2", NomeUtilizador = "user2user", Password = "user1234"},
};
return usersInicial;
}
#endregion
}
}
I tried a lot of different approaches life foreach loop and array.firstOrDefault() but I keep with the same thing. Can someone kindly help me to find my mistake?

I need the program to stop asking if user name and password are Ok

I have created this user ID and password console application. First, I ask and verify that they enter an ID integer and not a string. Next, I ask for a password; if the user ID and password match Predetermined values I added to the application to verify for, it log the user in. Apparently works good, but If user and password are ok at first time, instead of stop, it continues asking for ID name and password, I have tried break, and it doesn't work. Thanks.
using System;
namespace UserId
{
class Program
{
static void Main(string[] args)
{
string text;
var username = 123;
string password = "valid";
for (int i = 0; i < 3; i++)
{
Console.WriteLine("Please,Enter your user ID number :");
text = Console.ReadLine();
if (!int.TryParse(text, out username))
{
Console.WriteLine("Please, Enter a valid ID number such as a 12345");
}
else
{
Console.WriteLine("Please enter your password:");
password = Console.ReadLine();
}
if (username == 123 && password != "valid")
{
Console.WriteLine("Incorrect user ID and password combination, Try again");
}
}
if (username == 123 && password == "valid")
{
Console.WriteLine("You are now logged in!");
Console.ReadLine();
}
}
}
}
Here is a screen shot of the problem:
You can try this.
if ((username == 123 && password != "valid") || (username != 123 && password == "valid"))
{
Console.WriteLine("Incorrect user ID and password combination, Try again");
}
else
{
break;
}
Simply change your code to this. It will check if either of username or password is incorrect it will prompt error otherwise it will logged in and not ask for the second time
if (username != 123 || password != "valid")
{
Console.WriteLine("Incorrect user ID and password combination, Try again");
}
else
{
break;
}

how to replace existing user and password in Lists?

I'm currently having issue on editing an existing username and password that i stored in a list.
Declarations:
public static Administrator Cadmin = new Administrator("", "", "", "");
public static Staff Cstaff = new Staff("", "", "", "");
public static Administrator Ladmin = new Administrator("", "", "", "");
public static Staff Lstaff = new Staff("", "", "", "");
public static string NCName;
public static string NCPassword;
List<User> UserList = new List<User>();
Executing code:
Console.WriteLine("Which user would you like to edit?");
string ruser = Console.ReadLine();
bool Ustop = false;
while (!Ustop)
{
foreach (User u in UserList)
{
if (ruser == Cadmin.CName)
{
Console.WriteLine("Please key in the existing password of the selected username");
string epass = Console.ReadLine();
if (epass == Cadmin.CPassword)
{
Console.WriteLine("Create new Administrator Username:");
NCName = Console.ReadLine();
Console.WriteLine("\nCreate new Administrator Password: ");
NCPassword = Console.ReadLine();
ruser.Replace(ruser, NCName);
epass.Replace(epass, NCPassword);
}
else
{
Console.WriteLine("Password that you key in is invalid!");
}
}
else
{
Console.WriteLine("Username that you key in did not exist!");
Console.WriteLine("Please key in a valid username");
}
}
}
I understood that you have issues on storing data in currently filled List, so here are one solution, use for instead if foreach, and then you can edit the specific member of the list, using it's index (I considered that CAdmin is inherited from User and User class has properties for CName and CPassword):
bool Ustop = false;
while (!Ustop)
{
for (var i = 0; i< UserList.Count ; i++ )
{
User u = UserList[i];
if (ruser == u.CName)
{
Console.WriteLine("Please key in the existing password of the selected username");
string epass = Console.ReadLine();
if (epass == u.CPassword)
{
Console.WriteLine("Create new Administrator Username:");
NCName = Console.ReadLine();
Console.WriteLine("\nCreate new Administrator Password: ");
NCPassword = Console.ReadLine();
u.CName = NCName;
u.CPassword = NCPassword;
}
else
{
Console.WriteLine("Password that you key in is invalid!");
}
}
else
{
Console.WriteLine("Username that you key in did not exist!");
Console.WriteLine("Please key in a valid username");
}
}
}

SHA512 hashed credentials fail on validation

I got this register form where i get the user email and password and hash the password using SHA512
public Boolean IsRegistered(String email, String pass)
{
SHA512 shaM = new SHA512Managed();
if (pass.Length > 0 && email.Length > 0)
{
byte[] data = Encoding.UTF8.GetBytes(pass);
String encryptedpass = Encoding.UTF8.GetString(shaM.ComputeHash(data));
using (ModelContainer db = new ModelContainer())
{
//User usr = db.UserSet.Where(u => u.PasswordDigest == encryptedpass && u.Email == email).First();
int matches = (from u in bd.UserSet
where u.PasswordDigest == encryptedpass&& u.Email == email
select new
{
Id = u.Id
}
).Count();
if (matches > 0)
{
return true;
}
}
}
return false;
}
I use this method each time the user logs in and it works like a charm (i guess),
thing is when i prompt the user to change his/her password i cannot seem to be able to validate the old one here is what i try
I do the following to retrive the user data on the MyAccount form's constructor
User user;.
public MyAccount()
{
InitializeComponent();
try
{
using (ModelContainer db = new ModelContainer())
{
user = (from u in db.UserSet where u.Id == 2 select u).First();
txtName.Text = user.Name;
txtEmail.Text = user.Email;
}
}
catch (Exception x)
{
ErrorAlert error = new ErrorAlert("Error: " + x.Message);
error.Owner = getParentWindow();
error.ShowDialog();
}
}
then I validate it on the forms button_click
using (ModelContainer db = new ModelContainer())
{
SHA512 shaM = new SHA512Managed();
string oldpass = Encoding.UTF8.GetString(shaM.ComputeHash(Encoding.UTF8.GetBytes(ptxtOldPassword.Password)));
shaM.Dispose();
db.UserSet.Attach(user);
Regex rgx = new Regex(#"\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z");
if (rgx.IsMatch(txtEmail.Text))
{
if (oldpass == user.PasswordDigest)
{
if (ptxtNewPassword.Password.Equals(ptxtNewPassword2.Password))
{
string newpass = Encoding.UTF8.GetString(shaM.ComputeHash(Encoding.UTF8.GetBytes(ptxtNewPassword.Password)));
user.Name = txtName.Text;
user.Email = txtEmail.Text;
user.PasswordDigest = newpass;
db.SaveChanges();
}
else
{
ErrorAlert error = new ErrorAlert("Passwords do not match");
error.Owner = getParentWindow();
error.ShowDialog();
}
When I comapare the old password in the database with the one the user enter they do not match since they are strings I've tried using equals with no luck I thought == would work but I was wrong, i looked into other answers and found this Sha512 not returning equal in c# hash validation sadly it didn't work for me, I need to understand why my first validation work and the second doesnt
so any help is apreciated Have a nice day
You don't really need to compare the final strings, test at the bytes-level. Check this previous question.
Also, if you already validated the existence of the user (by email or any other mechanism), why don't just change / update with the new password? You could validate with the email and re-use the working function for login / signin.

Strings-creating "passwords" and "users" (simple with strings)

I need to create a program that will take the users name and "password". If they match the program will say you are in if not, that you're out. I wrote it for 1 user, but I don't know how to make multiple users in one program. My code is below. Thanks for your help :)
Console.WriteLine("Enter your Name");
Console.WriteLine("Enter your Pswrd");
string name = Console.ReadLine();
string pswrd = Console.ReadLine();
string myname = "John";
string mypswrd = "123456";
if (name == myname & pswrd == mypswrd)
{
Console.WriteLine("You are logged in");
}
else
{
Console.WriteLine("Incorrect name or pswrd");
}
Console.ReadLine();
//building the user "database" each pair is <user,password>
Dictionary<string, string> users = new Dictionary<string, string>();
users.Add("John", "123456");
//Here you should add more users in the same way...
//But i would advise reading them from out side the code (SQL database for example).
Console.Writeline("Enter your Name");
string name = Console.ReadLine();
Console.WriteLine("Enter your Passward");
string password = Console.ReadLine();
if (users.ContainsKey(name) && users[name] == password)
{
Console.WriteLine("You are logged in");
}
else
{
Console.WriteLine("Incorrect name or password");
}
Console.ReadLine();
This should work (contains no checks to see if the entered values are correct or not, you should add this kind of safety yourself :)):
Dictionary<string, string> namesToCheck = new Dictionary<string, string>
{
{"John", "123456"},
{"Harry", "someotherpassword"}
};
Console.WriteLine("Enter your Name");
string name = Console.ReadLine();
Console.WriteLine("Enter your Pswrd");
string pswrd = Console.ReadLine();
if (namesToCheck.ContainsKey(name) && namesToCheck[name] == pswrd)
{
Console.WriteLine("You are logged in");
}
else
{
Console.WriteLine("Incorrect name or pswrd");
}
Console.ReadLine();
Why not use arrays?
Console.WriteLine("Enter your Name");
Console.WriteLine("Enter your Pswrd");
string name = Console.ReadLine();
string pswrd = Console.ReadLine();
string[] names = "James,John,Jude".Split(Convert.ToChar(","));
string[] passes = "Pass1, Word2, Password3".Split(Convert.ToChar(","));
for (int i = 0; i<names.Length, i++)
{
if (names[i] == name && passes[i] == pswrd)
{
Console.WriteLine("You are logged in");
}
else
{
Console.WriteLine("Incorrect name or pswrd");
}
}
This will work with the following name/pswrd combinations:
James/Pass1, John/Word2, Jude/Password3
For a bigger list I suggest you use external text file and read lines in each.

Categories

Resources