All notes

AI/ML & Data Science / VAuthSys

VAuthSys - Visual Authentication System

A modern, secure visual authentication system that uses image-based passwords for user authentication.

October 29, 202512 min readPython1 stars
Open the full technical write-up

Version Python License

A modern, secure visual authentication system that uses image-based passwords for user authentication.

Features • Installation • Usage • Documentation • Contributing


What this project does

VAuthSys is a desktop application that implements a visual authentication system where users authenticate by selecting images instead of typing traditional passwords. This approach offers several advantages:

  • Enhanced Security: Visual passwords are harder to shoulder-surf than text passwords
  • User-Friendly: No need to remember complex strings or worry about typos
  • Accessibility: Easier for users who struggle with keyboard input
  • Security Through Obscurity: Images are shuffled during login, preventing pattern recognition attacks

The system uses a collection of 90 distinct images. During registration, users select exactly 6 images as their password. During login, these images are mixed with decoy images and shuffled, requiring the user to identify their password images from the selection.

What the project includes

Core workflows

  • Visual Password Authentication: Users select 6 images as their password
  • Secure Storage: Passwords are base64-encoded and stored securely in SQLite database
  • Modern UI: Clean, responsive interface built with Tkinter and sv-ttk
  • Theme Support: direct switching between dark and light themes
  • Performance Optimized: LRU image caching for efficient memory usage
  • Input Validation: Comprehensive validation for security and user experience
  • Error Handling: reliable error handling with comprehensive logging
  • Type Safety: Full type hints throughout the codebase

User Experience

  • Real-time Username Validation: Instant feedback on username availability
  • Visual Selection Feedback: Clear indicators for selected images
  • Intuitive Interface: Easy-to-use registration and login flows
  • Error Messages: User-friendly error messages with helpful guidance
  • Session Management: Proper cleanup and resource management

Security Features

  • Input Sanitization: All inputs are validated and sanitized
  • SQL Injection Protection: Parameterized queries throughout
  • Path Traversal Prevention: Filename validation prevents directory traversal attacks
  • Password Encoding: Base64 encoding for secure storage
  • Image Security: Additional decoy images during login for enhanced security

Installation & Quick Start

Prerequisites

  • Python 3.8 or higher (Python 3.11 recommended)
  • Windows 10/11 (Linux and macOS support planned)
  • At least 90 JPG images named 001.jpg through 090.jpg in the pictures/ directory
  1. Download the repository:

    git clone https://github.com/Tuhin-SnapD/VAuthSys.git
    cd VAuthSys
    
  2. Double-click run.bat - This will automatically:

    • Create and activate a virtual environment
    • Install all required dependencies
    • Start the application

Manual Installation

Step 1: Clone the Repository

git clone https://github.com/Tuhin-SnapD/VAuthSys.git
cd VAuthSys

Step 2: Create Virtual Environment

Windows:

python -m venv venv
venv\Scripts\activate

Linux/macOS:

python3 -m venv venv
source venv/bin/activate

Step 3: Install Dependencies

pip install --upgrade pip
pip install -r requirements.txt

Step 4: Prepare Images

Ensure you have 90 JPG images named sequentially:

  • pictures/001.jpg
  • pictures/002.jpg
  • ...
  • pictures/090.jpg

If you need to process images from another format, use the image processor:

python src/process_images.py

Step 5: Run the Application

python src/app.py

Or use the runner script:

python src/run_app.py

Usage

User Registration

  1. Launch the Application: Run run.bat or python src/app.py
  2. Click "Register New User": Opens the registration window
  3. Enter Username:
    • Must be 3-50 characters
    • Alphanumeric and underscore only
    • Must start with a letter or underscore
    • Real-time validation shows availability
  4. Select Images:
    • Click on exactly 6 images to select them
    • Selected images show a green checkmark
    • Selection counter shows progress (e.g., "Selected: 3/6")
    • Images are shuffled for security
  5. Click "Register User": Creates your account

Important: Remember your selected images! They serve as your password.

User Login

  1. Click "Login" from the main menu
  2. Enter Username: Type your registered username
  3. Click "Check Username": Verifies your username exists
  4. Select Password Images:
    • Your 6 password images are mixed with 12 decoy images
    • All images are shuffled in a random order
    • Click on your 6 password images
    • Selection counter updates as you select (e.g., "3/6 selected")
  5. Click "Login": Authenticates you
  6. Success: A welcome message confirms successful login

Theme Toggle

  • Click "Toggle Theme" from the main menu
  • Switch between dark and light themes instantly
  • Theme preference is maintained during the session

How files are organized

VAuthSys/
├── src/                          # Source code directory
│   ├── __init__.py              # Package initialization (if needed)
│   ├── app.py                   # Main application entry point
│   ├── config.py                # Configuration settings and constants
│   ├── database.py              # Database operations (SQLite)
│   ├── image_manager.py         # Image loading, caching, and management
│   ├── password_manager.py      # Password encoding/decoding utilities
│   ├── validators.py            # Input validation and sanitization
│   ├── login_view.py            # Login window interface
│   ├── registration_view.py     # Registration window interface
│   ├── process_images.py        # Image processing utility
│   ├── setup.py                 # Setup script
│   └── run_app.py               # Application runner script
├── pictures/                    # Source images directory (90 images)
│   ├── 001.jpg
│   ├── 002.jpg
│   └── ... (through 090.jpg)
├── processed/                   # Processed images directory
│   ├── 001.jpg
│   ├── 002.jpg
│   └── ... (processed versions)
├── venv/                        # Virtual environment (git-ignored)
├── database.db                  # SQLite database (git-ignored)
├── vauthsys.log                 # Application logs (git-ignored)
├── requirements.txt             # Python dependencies
├── run.bat                      # One-click startup script (Windows)
├── .gitignore                   # Git ignore rules
└── README.md                    # This file

Configuration

The application can be customized through src/config.py:

Window Settings

MAIN_WINDOW_SIZE = "400x270"              # Main menu window
LOGIN_WINDOW_SIZE = "800x600"             # Login window
REGISTRATION_WINDOW_SIZE = "1200x800"     # Registration window

Image Settings

TOTAL_IMAGES = 90                         # Total number of images
REQUIRED_IMAGE_COUNT = 6                  # Required images for password
IMAGE_SIZE = (80, 80)                     # Display size for login
REGISTRATION_IMAGE_SIZE = (60, 60)        # Display size for registration
IMAGES_PER_ROW = 6                        # Grid layout for login
REGISTRATION_IMAGES_PER_ROW = 15          # Grid layout for registration

Security Settings

MIN_USERNAME_LENGTH = 3                   # Minimum username length
MAX_USERNAME_LENGTH = 50                  # Maximum username length

Performance Settings

IMAGE_CACHE_SIZE = 100                    # LRU cache size
DATABASE_TIMEOUT = 30                     # Database connection timeout

Database Schema

The application uses SQLite for data storage:

CREATE TABLE users (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    username TEXT NOT NULL UNIQUE,
    password TEXT NOT NULL,              -- Base64-encoded JSON
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    last_login TIMESTAMP
);

Password Storage Format

Passwords are stored as base64-encoded JSON strings:

{
    "1": "001.jpg",
    "2": "015.jpg",
    "3": "042.jpg",
    "4": "067.jpg",
    "5": "078.jpg",
    "6": "089.jpg"
}

The order of selection is preserved, but authentication checks for set equality (order doesn't matter during login for security).

How the system is built

Component Overview

┌─────────────────────────────────────────┐
│           Main Application              │
│            (app.py)                     │
└──────────────┬──────────────────────────┘
               │
    ┌──────────┼──────────┐
    │          │          │
┌───▼───┐ ┌───▼───┐ ┌────▼────┐
│  DB   │ │ Image │ │Password │
│Manager│ │Manager│ │ Manager │
└───┬───┘ └───┬───┘ └────┬────┘
    │         │          │
┌───▼───┐ ┌───▼───┐ ┌────▼────┐
│SQLite │ │  PIL  │ │ Base64  │
│       │ │Cache  │ │  JSON   │
└───────┘ └───────┘ └─────────┘

Key Classes

  • VAuthSysApp: Main application class managing the window and views
  • DatabaseManager: Handles all database operations with connection pooling
  • ImageManager: Manages image loading, caching, and selection operations
  • PasswordManager: Handles password encoding, decoding, and comparison
  • InputValidator: Validates and sanitizes user inputs
  • LoginView: Login window interface and authentication flow
  • RegistrationView: Registration window interface and user creation

Data Flow

Registration Flow:

User Input → Validator → PasswordManager.encode() → DatabaseManager.create_user()

Login Flow:

Username → Validator → DatabaseManager.get_user_password() 
→ PasswordManager.decode() → ImageManager.get_password_images() 
→ User Selection → PasswordManager.compare_passwords()

API Reference

DatabaseManager

class DatabaseManager:
    def create_user(username: str, encoded_password: str) -> bool
    def get_user_password(username: str) -> Optional[str]
    def user_exists(username: str) -> bool
    def update_last_login(username: str) -> bool
    def get_all_users() -> List[Dict[str, Any]]

ImageManager

class ImageManager:
    def load_image(image_name: str, size: Tuple[int, int], processed: bool = True) -> Optional[ImageTk.PhotoImage]
    def get_all_image_names() -> List[str]
    def get_password_images(password_dict: Dict[str, str]) -> List[Dict[str, int]]
    def get_additional_images(password_images: List[Dict[str, int]], count: int = 12) -> List[Dict[str, int]]
    def shuffle_images(images: List[Dict[str, int]]) -> List[Dict[str, int]]
    def validate_image_selection(selected_images: List[Dict[str, int]], required_count: int = 6) -> bool
    def clear_cache() -> None

PasswordManager

class PasswordManager:
    @staticmethod
    def encode_password(selected_images: List[Dict[str, int]]) -> Optional[str]
    @staticmethod
    def decode_password(encoded_password: str) -> Optional[Dict[str, str]]
    @staticmethod
    def compare_passwords(selected_ids: List[int], password_ids: List[int]) -> bool

InputValidator

class InputValidator:
    @staticmethod
    def validate_username(username: str) -> bool
    @staticmethod
    def validate_image_selection(selected_images: List[Dict[str, Any]], required_count: int = 6) -> bool
    @staticmethod
    def sanitize_username(username: str) -> str

Security Considerations

Implemented Security Measures

  1. SQL Injection Prevention: All database queries use parameterized statements
  2. Input Validation: Comprehensive validation before processing any user input
  3. Path Traversal Protection: Filename validation prevents directory traversal
  4. Password Encoding: Base64 encoding provides basic obfuscation
  5. Session Security: Images shuffled during login prevent pattern recognition

Security Recommendations

For production use, consider:

  • Password Encryption: Replace base64 encoding with proper encryption (AES-256)
  • Salt and Hash: Implement proper hashing algorithms
  • Rate Limiting: Prevent brute-force attacks
  • Account Lockout: Lock accounts after failed login attempts
  • Audit Logging: Enhanced logging for security events
  • Network Security: If extending to network, use TLS/SSL

Known Limitations

  • Base64 encoding is not encryption (it's reversible without a key)
  • No rate limiting on login attempts
  • Password order doesn't matter (could be a feature or limitation)
  • Local SQLite database (not suitable for multi-user deployments)

Troubleshooting

Common Issues

Issue: "Python is not installed or not in PATH"

Solution:

  • Install Python 3.8+ from python.org
  • During installation, check "Add Python to PATH"
  • Restart your terminal/command prompt

Issue: "ModuleNotFoundError: No module named 'PIL'"

Solution:

pip install Pillow
# Or reinstall dependencies
pip install -r requirements.txt

Issue: "Image file not found" errors

Solution:

  • Ensure you have exactly 90 images in pictures/ directory
  • Images must be named 001.jpg through 090.jpg
  • Run the image processor: python src/process_images.py

Issue: Application window doesn't appear

Solution:

  • Check if another instance is already running
  • Check the log file vauthsys.log for errors
  • Ensure all dependencies are installed

Issue: "Database locked" errors

Solution:

  • Close all instances of the application
  • Delete database.db if corrupted (users will need to re-register)
  • Check file permissions

Logging

Logs are written to vauthsys.log in the project root. Check this file for detailed error information.

Enable debug logging by modifying app.py:

logging.basicConfig(level=logging.DEBUG, ...)

Performance Optimizations

  1. LRU Image Cache: Frequently accessed images are cached in memory
  2. Lazy Loading: Images load only when needed
  3. Database Connection Pooling: Efficient connection management
  4. Optimized Resizing: High-quality LANCZOS resampling for image scaling
  5. Memory Management: Proper cleanup on application exit

Development

Setting Up Development Environment

  1. Clone and Setup: Follow installation instructions above
  2. Install Development Dependencies (if needed):
    pip install pytest black flake8 mypy
    

Code Style

  • Type Hints: All functions include type annotations
  • Docstrings: Comprehensive docstrings for all classes and functions
  • Error Handling: Try-except blocks with proper logging
  • Naming: PEP 8 compliant naming conventions

Running Tests

# Run syntax check
python -m py_compile src/*.py

# Run with Python's built-in doctest (if tests are added)
python -m doctest src/*.py

Adding New Features

  1. Create a feature branch: git checkout -b feature/new-feature
  2. Make your changes
  3. Ensure type hints and docstrings are added
  4. Test thoroughly
  5. Submit a pull request

Logging

The application uses Python's logging module with the following configuration:

  • File Output: vauthsys.log in project root
  • Console Output: Real-time logging to stdout
  • Log Levels: INFO, WARNING, ERROR
  • Format: %(asctime)s - %(name)s - %(levelname)s - %(message)s

Log entries include:

  • Application startup/shutdown
  • User registration and login attempts
  • Database operations
  • Image loading and caching
  • Error conditions

Error Handling

The application implements comprehensive error handling:

  • Graceful Degradation: Application continues functioning with non-critical errors
  • User-Friendly Messages: Clear error messages without exposing internals
  • Comprehensive Logging: All errors logged with context
  • Validation First: Input validation prevents many errors

Requirements

Dependencies

  • Pillow (>=10.0.0): Image processing and manipulation
  • sv-ttk (>=2.6.0): Modern Tkinter theme (Sun Valley)

Python Version

  • Minimum: Python 3.8
  • Recommended: Python 3.11 or higher

System Requirements

  • OS: Windows 10/11 (primary), Linux/macOS (should work with minor adjustments)
  • RAM: 512MB minimum, 2GB recommended
  • Disk: ~50MB for application + images
  • Display: 1280x720 minimum resolution recommended

Roadmap

Planned Features

  • Linux and macOS native support
  • Password reset functionality
  • Account management interface
  • Enhanced encryption for passwords
  • Multi-language support
  • Export/import user data
  • Image upload functionality
  • Custom image sets
  • Password strength indicators
  • Login attempt tracking

Future Enhancements

  • Web-based version
  • Mobile app support
  • Cloud synchronization
  • Advanced analytics
  • Two-factor authentication integration

Contributing

Contributions are welcome! Here's how you can help:

How to Contribute

  1. Fork the Repository: Click the "Fork" button on GitHub
  2. Create a Branch: git checkout -b feature/your-feature-name
  3. Make Changes: Implement your feature or fix
  4. Test Thoroughly: Ensure everything works
  5. Commit: git commit -m "Add your feature"
  6. Push: git push origin feature/your-feature-name
  7. Pull Request: Open a PR on GitHub

Contribution Guidelines

  • Follow existing code style and conventions
  • Add type hints to all new functions
  • Include docstrings for new classes/functions
  • Update README if adding features
  • Test on Windows (primary platform)
  • Ensure backward compatibility when possible

Reporting Issues

When reporting bugs, please include:

  • Python version
  • Operating system
  • Steps to reproduce
  • Expected vs actual behavior
  • Relevant log entries from vauthsys.log

License

This project is licensed under the MIT License - see the LICENSE file for details.

Acknowledgments

  • Pillow: For excellent image processing capabilities
  • sv-ttk: For the beautiful Sun Valley theme
  • Tkinter: For the GUI framework
  • SQLite: For lightweight database functionality

Author

Tuhin-SnapD

Support

For support, questions, or suggestions:

  • Issues: Open an issue on GitHub Issues
  • Discussions: Use GitHub Discussions for questions
  • Email: Check repository for contact information

Made by Tuhin-SnapD

⭐ Star this repo if you find it helpful!

Related notes

AI/ML & Data Science

AI Lab

A hands-on AI, machine learning, deep learning, computer vision, and data analytics lab built for learners who want practical projects, readable code, and a clear roadmap.

AI/ML & Data Science

CNN

Pure NumPy implementation of a tiny convolutional neural network (CNN) designed for education and experimentation.

AI/ML & Data Science

Emotion Detection Chatbot

An intelligent chatbot system that detects emotions from user text input using advanced Machine Learning, Deep Learning, and Natural Language Processing techniques.