Reputation: 346
I have to write a code that if you failed 5
login attempts, lock the user for 30
minutes.
This is the code for the login that counts the attempts
int InvalidLoginAttempts = 0;
for (int i = 0; i <5; i++){
Console.WriteLine("Enter username");
string username = Console.ReadLine();
Console.WriteLine("Enter password");
string password = Console.ReadLine();
if (username != "valid" || password != "valid")
InvalidLoginAttempts++;
else
break;
}
if (InvalidLoginAttempts > 5)
Console.WriteLine("Login failure");
else
Console.WriteLine("Login successful");
Console.ReadKey();
How can I say that if InvalidLoginAttempts > 5
the user will be locked?
Upvotes: 0
Views: 251
Reputation: 186833
Why not extract a method? Instead of counting attempts, let's implement a simple loop within a simple method that returns true
or false
:
private static bool TryToLogin(int attempts = 5) {
for (int attempt = 0; attempt < attempts; ++attempt) {
Console.WriteLine("Enter username");
string username = Console.ReadLine();
Console.WriteLine("Enter password");
string password = Console.ReadLine();
if (username == "valid" && password == "valid)
return true;
}
return false;
}
All we have to do now is to check the value returned:
if (!TryToLogin(5)) {
//TODO: Lock user here
Console.WriteLine("Login failure");
}
else {
Console.WriteLine("Login successful");
}
Upvotes: 1