Login and Authentication - lucyberryhub/WPF.Tutorial GitHub Wiki
Title: π Berry Safe Login π
Content:
Secure your berry farm with login/logout! π
Welcome to the world of secure logins! π In this tutorial, we're going to teach you how to set up a basic login and authentication system for your WPF application. Whether you're securing your berry farm π or any other precious data, this guide will show you how to implement a simple yet effective login system. Let's get started!
The first step is to create the user interface (UI) for the login page. Weβll need a TextBox
for the username, a PasswordBox
for the password, and a Button
for submitting the login information.
Hereβs a simple layout in XAML:
<Window x:Class="BerryFarmApp.LoginWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Berry Farm Login" Height="250" Width="400">
<StackPanel VerticalAlignment="Center" HorizontalAlignment="Center" Spacing="15">
<!-- Username Field -->
<TextBox x:Name="Username" Width="200" Height="30" Margin="10" PlaceholderText="Enter Username" />
<!-- Password Field -->
<PasswordBox x:Name="Password" Width="200" Height="30" Margin="10" PlaceholderText="Enter Password" />
<!-- Login Button -->
<Button Content="Login" Width="200" Height="40" Click="Login_Click" />
</StackPanel>
</Window>
Berry Vibe:
- π
TextBox
: Used for entering the username. - π
PasswordBox
: A special box to securely enter the password (the text will be masked). - π
Button
: The login button that, when clicked, will validate the username and password.
Now letβs write the logic behind the login button. This will check if the entered username and password match the correct credentials.
Hereβs the C# code that performs the authentication:
private void Login_Click(object sender, RoutedEventArgs e)
{
// Predefined login credentials (can be replaced with a database or other methods)
string validUsername = "admin";
string validPassword = "1234";
// Check if entered credentials match
if (Username.Text == validUsername && Password.Password == validPassword)
{
// If valid, show a welcome message and close the login window
MessageBox.Show("Welcome to the Berry Farm! π");
this.Close(); // Close the login window (can navigate to the main window)
}
else
{
// If invalid, show an error message
MessageBox.Show("Invalid login! π", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
Berry Vibe:
- π
Username.Text
andPassword.Password
: Access the text from theTextBox
andPasswordBox
controls, respectively. - π
if
condition: If the username and password match the predefined ones ("admin"
and"1234"
), the user is authenticated and welcomed with a message. - π
MessageBox.Show
: Displays a message to the user, either a welcome message or an error message. - π»
this.Close()
: Closes the login window and could navigate to the main window of the application.
It's a good idea to prevent repeated failed login attempts. You can limit the number of failed login attempts and lock the user out after a certain number of incorrect tries.
Hereβs how you can add that functionality:
private int failedAttempts = 0; // Track failed attempts
private void Login_Click(object sender, RoutedEventArgs e)
{
string validUsername = "admin";
string validPassword = "1234";
// Check if entered credentials match
if (Username.Text == validUsername && Password.Password == validPassword)
{
MessageBox.Show("Welcome to the Berry Farm! π");
this.Close(); // Close login window
}
else
{
failedAttempts++;
if (failedAttempts >= 3)
{
MessageBox.Show("Too many failed attempts! Please try again later.", "Login Locked", MessageBoxButton.OK, MessageBoxImage.Warning);
this.Close(); // Close the login window after too many failed attempts
}
else
{
MessageBox.Show($"Invalid login! You have {3 - failedAttempts} attempts left.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
}
Berry Vibe:
- π
failedAttempts
: A counter to keep track of the number of failed login attempts. - π
if (failedAttempts >= 3)
: If there have been 3 or more failed attempts, the system will lock out the user, displaying a warning message and closing the window. - π
MessageBox.Show
: Displays the remaining number of attempts or a warning when the limit is reached.
If you want to authenticate users against a database (for example, using SQLite), you can modify the login logic to query the database and check if the username and password match.
Hereβs an example using SQLite for authentication:
private void Login_Click(object sender, RoutedEventArgs e)
{
using (var conn = new SQLiteConnection("Data Source=users.db"))
{
conn.Open();
var cmd = new SQLiteCommand("SELECT * FROM Users WHERE Username = @Username AND Password = @Password", conn);
cmd.Parameters.AddWithValue("@Username", Username.Text);
cmd.Parameters.AddWithValue("@Password", Password.Password);
using (var reader = cmd.ExecuteReader())
{
if (reader.Read())
{
MessageBox.Show("Welcome to the Berry Farm! π");
this.Close(); // Close login window
}
else
{
MessageBox.Show("Invalid login! π", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
}
}
Berry Vibe:
- π
SQLiteConnection
: Connects to an SQLite database. - π
cmd.Parameters.AddWithValue
: Prevents SQL injection and securely adds the username and password to the query. - π
ExecuteReader()
: Executes the query and checks if thereβs a matching user in the database.
Now that youβve got login set up, letβs add the ability to log out. You can add a Logout
button and an event handler to clear the session or simply navigate to the login screen again.
Hereβs an example:
<Button Content="Logout" Click="Logout_Click" />
private void Logout_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("You have successfully logged out! π");
// Optionally, navigate back to the login screen
this.Close(); // Close the main window (or navigate to login screen)
}
Berry Vibe:
- π
MessageBox.Show
: Displays a message confirming that the user has logged out successfully. - π
this.Close()
: Closes the current window. If you have a main window, you can open the login window again here.
For more complex applications, you might want to keep track of user sessions (who is logged in, their role, etc.). You can store user session data in static variables or use a session manager.
public static class SessionManager
{
public static string CurrentUser { get; set; }
}
private void Login_Click(object sender, RoutedEventArgs e)
{
if (Username.Text == "admin" && Password.Password == "1234")
{
SessionManager.CurrentUser = Username.Text; // Store the current user
MessageBox.Show($"Welcome to the Berry Farm, {SessionManager.CurrentUser}! π");
}
}
Berry Vibe:
- π
SessionManager.CurrentUser
: A static class that stores the current logged-in user. - π
MessageBox.Show
: Displays a personalized welcome message for the logged-in user.
And there you have itβa basic login and authentication system for your WPF app! π Whether youβre keeping your berry farm π safe or securing any sensitive data, this guide provides the foundation for creating a secure and user-friendly login page. You can extend it with a database, add a session manager, or even integrate it with external authentication services like OAuth. Stay safe and enjoy your secure berry farm! πππ