Well, I've been trying to build a simple login (Nothing that complicated), everything is working correctly, but not the part when u need to compare the database results and the user input. Here's the problem:
if (item.user == User && item.password == Password) {
itExists = true;
break;
}
item.usuario is working correctly, the user input is saving correctly too, I know this, because when I try to compare with this:
if (item.user.Contains(User) && item.password.Contains(Password)) {
itExists= true;
break;
}
It works "fine", the problem with "Contains" is that when the user type a single letter (For example, imagine if in database, the user/password is admin/admin and the user types a/a) it will let him sign in, because "a" is contained in "admin"
So, I've searched almost all the comparison methods and I've tried this:
// Isn't working directly. ToString(item.user) == Convert.ToString(User) && Convert.ToString(item.password) == Convert.ToString(Password)
// Isn't working directly. item.user== User && item.password == Password
// Isn't working directly. item.user.Equals(User) && item.password.Equals(Password)
// Isn't working directly. String.Equals(item.user, User) && String.Equals(item.password, Password)
// Is working, but if u write a single letter that is in the string,
// It let u sign in. item.user.Contains(User) && item.password.Contains(Password)
I know those don't work because with .Contains() it let u sign in with a correct user/password, but with the issue I've told
I want to know why this happens, and, how to do it then.
Each variable contains:
The complete controller code is here:
public ActionResult Index(string User, string Password) {
var UsersList= db.Users;
bool itExists= false;
foreach (var item in UserList) {
if (item.user.Contains(User) && item.password.Contains(Password)) {
itExists= true;
break;
}}
(I think I've explained myself really fine, sorry if I didn't)
Thank u in advance :)
Edit: If it matters, I'm using ASP.NET (.Net Framework 4.7.2)
For the password you should stick to an "==" comparaison. The password sent by the user should match exactly what is in database (by the way you should use an hash and not the actual password but it's not the issue here).
For the username you can be more flexible (by example the user will maybe use capital letter or adding a blank space behind) so you should take care of that :
item.usuario.Trim().Equals(User, StringComparison.CurrentCultureIgnoreCase);
With the Trim() you will remove all whitespace before/after and the Equals parameter will ensure the comparison will be case insensitive.
You should also trim the "User" if if what not done before adding it to the database.
You also should use LINQ instead of a for each :
var trimmedUserName = item.usuario.Trim();
var exists = UserList.Any(u => trimmedUserName.Equals(User,
StringComparison.CurrentCultureIgnoreCase) && item.password == Password);
And I'm sure you know it but using the ".Contains" would be a huge security issue.