Day 23: Simple Login System

Objective

Today, you’ll build a simple login system where users can register and then log in by entering their username and password. This task will introduce you to concepts such as storing user data, validating input, and ensuring security basics.

For example:

  1. Registration:
    • Input: Username: john123, Password: password123
    • Output: User registered successfully!
  2. Login:
    • Input: Username: john123, Password: password123
    • Output: Login successful!
    • Input: Username: john123, Password: wrongpass
    • Output: Incorrect password.

Why This Challenge Is Important

A login system is a fundamental part of many applications, such as websites, mobile apps, and games. Building a basic version will help you understand:

  • How to store and retrieve data.
  • Validating input to ensure user credentials are correct.
  • Fundamental concepts in authentication systems.

This challenge is also a stepping stone to more advanced topics like secure password hashing and managing user sessions.


Steps to Solve

1. Understand the Problem

The system should have two main features:

  • Registration: Store the username and password.
  • Login: Validate the username and password against the stored data.

2. Plan Your Solution

  1. Create a data structure (e.g., a dictionary) to store user credentials.
  2. Implement a registration system:
    • Allow users to enter a unique username and password.
    • Store the credentials in the data structure.
  3. Implement a login system:
    • Prompt the user for their username and password.
    • Check if the username exists and if the password matches.
  4. Display appropriate messages for successful or failed login attempts.

3. Enhancements to Consider

  • Prevent registration with duplicate usernames.
  • Allow users to retry login if it fails.
  • Add options to view or clear all registered users (for testing purposes).

Code Examples

Python Example

Basic Login System:

# Initialize an empty dictionary to store user data
user_database = {}

print("Welcome to the Simple Login System!")

while True:
    print("\nChoose an option:")
    print("1. Register")
    print("2. Login")
    print("3. Exit")
    choice = input("Enter your choice: ")

    if choice == "1":
        # Registration
        username = input("Enter a username: ")
        if username in user_database:
            print("Username already exists. Please choose a different one.")
        else:
            password = input("Enter a password: ")
            user_database[username] = password
            print("User registered successfully!")

    elif choice == "2":
        # Login
        username = input("Enter your username: ")
        if username in user_database:
            password = input("Enter your password: ")
            if user_database[username] == password:
                print("Login successful!")
            else:
                print("Incorrect password.")
        else:
            print("Username not found. Please register first.")

    elif choice == "3":
        print("Exiting the program. Goodbye!")
        break
    else:
        print("Invalid choice. Please try again.")

Java Example

Basic Login System:

import java.util.HashMap;
import java.util.Scanner;

public class SimpleLoginSystem {
    public static void main(String[] args) {
        HashMap<String, String> userDatabase = new HashMap<>();
        Scanner scanner = new Scanner(System.in);

        System.out.println("Welcome to the Simple Login System!");

        while (true) {
            System.out.println("\nChoose an option:");
            System.out.println("1. Register");
            System.out.println("2. Login");
            System.out.println("3. Exit");
            System.out.print("Enter your choice: ");
            String choice = scanner.nextLine();

            if (choice.equals("1")) {
                // Registration
                System.out.print("Enter a username: ");
                String username = scanner.nextLine();
                if (userDatabase.containsKey(username)) {
                    System.out.println("Username already exists. Please choose a different one.");
                } else {
                    System.out.print("Enter a password: ");
                    String password = scanner.nextLine();
                    userDatabase.put(username, password);
                    System.out.println("User registered successfully!");
                }
            } else if (choice.equals("2")) {
                // Login
                System.out.print("Enter your username: ");
                String username = scanner.nextLine();
                if (userDatabase.containsKey(username)) {
                    System.out.print("Enter your password: ");
                    String password = scanner.nextLine();
                    if (userDatabase.get(username).equals(password)) {
                        System.out.println("Login successful!");
                    } else {
                        System.out.println("Incorrect password.");
                    }
                } else {
                    System.out.println("Username not found. Please register first.");
                }
            } else if (choice.equals("3")) {
                System.out.println("Exiting the program. Goodbye!");
                break;
            } else {
                System.out.println("Invalid choice. Please try again.");
            }
        }
    }
}

JavaScript Example

Basic Login System:

const userDatabase = {};

console.log("Welcome to the Simple Login System!");

while (true) {
    const choice = prompt("Choose an option:\n1. Register\n2. Login\n3. Exit");

    if (choice === "1") {
        // Registration
        const username = prompt("Enter a username:");
        if (userDatabase[username]) {
            console.log("Username already exists. Please choose a different one.");
        } else {
            const password = prompt("Enter a password:");
            userDatabase[username] = password;
            console.log("User registered successfully!");
        }
    } else if (choice === "2") {
        // Login
        const username = prompt("Enter your username:");
        if (userDatabase[username]) {
            const password = prompt("Enter your password:");
            if (userDatabase[username] === password) {
                console.log("Login successful!");
            } else {
                console.log("Incorrect password.");
            }
        } else {
            console.log("Username not found. Please register first.");
        }
    } else if (choice === "3") {
        console.log("Exiting the program. Goodbye!");
        break;
    } else {
        console.log("Invalid choice. Please try again.");
    }
}

Edge Cases to Consider

  1. Duplicate Usernames: Prevent multiple users from registering with the same username.
  2. Empty Input: Handle cases where the username or password is left blank.
  3. Case Sensitivity: Decide if usernames and passwords should be case-sensitive.
  4. Invalid Input: Ensure the program doesn’t crash if an invalid option is entered.

Extensions to Explore

  1. Password Strength: Add a check for password strength (e.g., require at least 8 characters, a mix of letters, numbers, and symbols).
  2. Persistent Storage: Store user data in a file or database so it’s available across program runs.
  3. Forgot Password: Implement a feature to reset passwords for existing users.

What You’ve Learned

  • How to store and retrieve data using a dictionary or map.
  • How to validate user input.
  • Basic implementation of a login system.

Next Steps

In Day 24: Leap Year Checker, you’ll write a program that determines whether a given year is a leap year.