Skip to content

AarambhDevHub/ignitia-chat-app

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

4 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Ignitia WebSocket Chat Application

A production-ready real-time chat application built with the Ignitia web framework, featuring WebSocket support, JWT authentication, PostgreSQL database, and a modern web interface.

Rust PostgreSQL WebSocket

πŸš€ Features

  • βœ… Real-time Messaging - WebSocket-based instant messaging
  • βœ… User Authentication - JWT-based secure authentication with Argon2 password hashing
  • βœ… Database Persistence - PostgreSQL with message history
  • βœ… User Search - Find users by username or full name
  • βœ… Message Status - Track read/unread messages
  • βœ… Connection Status - Real-time connection indicators
  • βœ… Auto Reconnection - Automatic WebSocket reconnection on disconnection
  • βœ… Responsive UI - Modern, mobile-friendly interface
  • βœ… Type Safety - Comprehensive type system with Serde serialization
  • βœ… Production Ready - Error handling, logging, and security features

πŸ“ Project Structure

chat-app/
β”œβ”€β”€ Cargo.toml
β”œβ”€β”€ .env
β”œβ”€β”€ README.md
β”œβ”€β”€ migrations/
β”‚   └── 001_initial_schema.sql
β”œβ”€β”€ static/
β”‚   β”œβ”€β”€ index.html           # Landing page
β”‚   β”œβ”€β”€ login.html           # User login
β”‚   β”œβ”€β”€ register.html        # User registration
β”‚   β”œβ”€β”€ chat.html            # Main chat interface
β”‚   └── search.html          # User search page
└── src/
    β”œβ”€β”€ main.rs              # Application entry point
    β”œβ”€β”€ config.rs            # Configuration management
    β”œβ”€β”€ db/
    β”‚   β”œβ”€β”€ mod.rs
    β”‚   β”œβ”€β”€ pool.rs          # Database connection pool
    β”‚   └── models.rs        # Database models
    β”œβ”€β”€ handlers/
    β”‚   β”œβ”€β”€ mod.rs
    β”‚   β”œβ”€β”€ auth.rs          # Authentication handlers
    β”‚   β”œβ”€β”€ user.rs          # User management
    β”‚   β”œβ”€β”€ chat.rs          # Chat & WebSocket handlers
    β”‚   └── static_files.rs  # Static file serving
    β”œβ”€β”€ middleware/
    β”‚   β”œβ”€β”€ mod.rs
    β”‚   └── jwt_auth.rs      # JWT authentication middleware
    β”œβ”€β”€ error/
    β”‚   β”œβ”€β”€ mod.rs
    β”‚   └── app_error.rs     # Custom error types
    β”œβ”€β”€ utils/
    β”‚   β”œβ”€β”€ mod.rs
    β”‚   β”œβ”€β”€ password.rs      # Password hashing utilities
    β”‚   └── token.rs         # JWT token utilities
    └── types/
        β”œβ”€β”€ mod.rs
        β”œβ”€β”€ auth.rs          # Auth request/response types
        β”œβ”€β”€ chat.rs          # Chat message types
        └── user.rs          # User types

πŸ› οΈ Prerequisites

  • Rust 1.70 or higher
  • PostgreSQL 12 or higher
  • Cargo (comes with Rust)

βš™οΈ Installation

1. Clone the Repository

git clone https://github.com/AarambhDevHub/ignitia-chat-app.git
cd ignitia-chat-app

2. Setup PostgreSQL Database

# Create database
createdb chatapp

# Or using psql
psql -U postgres
CREATE DATABASE chatapp;
\q

3. Configure Environment Variables

Create a .env file in the project root:

DATABASE_URL=postgres://postgres:password@localhost/chatapp
JWT_SECRET=your-super-secret-jwt-key-change-this-in-production
JWT_EXPIRATION_HOURS=24
SERVER_HOST=127.0.0.1
SERVER_PORT=8080
RUST_LOG=info

4. Install Dependencies

cargo build --release

πŸš€ Running the Application

Development Mode

cargo run

Production Mode

cargo run --release

The server will start at http://localhost:8080

πŸ“¦ Dependencies

[dependencies]
ignitia = { version = "0.2.4", features = ["websocket"] }
tokio = { version = "1", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
sqlx = { version = "0.7", features = ["runtime-tokio-rustls", "postgres", "uuid", "chrono"] }
argon2 = "0.5"
jsonwebtoken = "9.0"
uuid = { version = "1.0", features = ["v4", "serde"] }
chrono = { version = "0.4", features = ["serde"] }
dotenvy = "0.15"
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
async-trait = "0.1"
once_cell = "1.19"
thiserror = "1.0"
bytes = "1.7"
dashmap = "6.0"
mime_guess = "2.0"

πŸ—„οΈ Database Schema

-- Users table
CREATE TABLE users (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    username VARCHAR(50) UNIQUE NOT NULL,
    email VARCHAR(255) UNIQUE NOT NULL,
    password_hash VARCHAR(255) NOT NULL,
    fullname VARCHAR(100),
    created_at TIMESTAMPTZ DEFAULT NOW(),
    updated_at TIMESTAMPTZ DEFAULT NOW()
);

-- Messages table
CREATE TABLE messages (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    sender_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    receiver_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    content TEXT NOT NULL,
    is_read BOOLEAN DEFAULT FALSE,
    created_at TIMESTAMPTZ DEFAULT NOW(),
    CONSTRAINT different_users CHECK (sender_id != receiver_id)
);

-- Indexes for performance
CREATE INDEX idx_messages_receiver ON messages(receiver_id, created_at DESC);
CREATE INDEX idx_messages_sender ON messages(sender_id, created_at DESC);
CREATE INDEX idx_messages_conversation ON messages(sender_id, receiver_id, created_at DESC);

πŸ” API Endpoints

Authentication

Method Endpoint Description Auth Required
POST /api/auth/register Register new user No
POST /api/auth/login Login user No

Users

Method Endpoint Description Auth Required
GET /api/users/search?q=query Search users Yes
GET /api/users/profile Get current user profile Yes

Messages

Method Endpoint Description Auth Required
POST /api/messages/send Send message Yes
GET /api/messages/:user_id Get message history Yes

WebSocket

Method Endpoint Description Auth Required
WS /ws/chat?token=JWT WebSocket connection Yes (via query param)

πŸ’¬ WebSocket Message Format

Client to Server

{
  "type": "message",
  "from_user_id": "uuid",
  "from_username": "string",
  "to_user_id": "uuid",
  "content": "string",
  "timestamp": "ISO8601"
}

Server to Client

{
  "type": "message",
  "from_user_id": "uuid",
  "from_username": "string",
  "to_user_id": "uuid",
  "content": "string",
  "timestamp": "ISO8601"
}

Online/Offline Events

{
  "type": "online",
  "user_id": "uuid",
  "username": "string"
}

{
  "type": "offline",
  "user_id": "uuid"
}

🎯 Usage Guide

1. Register an Account

  • Navigate to http://localhost:8080
  • Click "Register"
  • Fill in username, email, and password
  • Submit the form

2. Login

  • Enter your credentials
  • You'll be redirected to the chat page

3. Start Chatting

  • Select a user from the sidebar
  • Type your message in the input box
  • Press Enter or click Send
  • Messages are delivered instantly via WebSocket

4. Search Users

  • Use the search box in the sidebar
  • Or click "Find Users" to see all available users
  • Click on any user to start a conversation

πŸ—οΈ Architecture

WebSocket Flow

  1. Connection: Client connects to /ws/chat?token=JWT
  2. Authentication: Server validates JWT token from query parameter
  3. Registration: User connection stored in DashMap<Uuid, Sender>
  4. Broadcasting: Messages broadcast to recipient if online
  5. Persistence: All messages saved to PostgreSQL database
  6. Cleanup: On disconnect, user removed from active connections

Request Flow

Client β†’ Middleware (JWT Auth) β†’ Handler β†’ Database β†’ Response

WebSocket Flow

Client β†’ WebSocket Handler β†’ Verify Token β†’ Store Connection
    ↓
Message β†’ Parse JSON β†’ Validate β†’ Save to DB β†’ Broadcast to Recipient

πŸ”’ Security Features

  • Argon2 Password Hashing - Industry-standard password security
  • JWT Authentication - Stateless authentication with expiration
  • SQL Injection Prevention - Parameterized queries with SQLx
  • XSS Protection - HTML escaping in frontend
  • Path Traversal Prevention - Static file serving validation
  • HTTPS Ready - TLS support via Ignitia framework

πŸ“Š Performance

  • Connection Pooling - 5-20 database connections
  • Async Runtime - Tokio for high concurrency
  • Zero-copy - Efficient WebSocket message handling
  • Database Indexes - Optimized query performance
  • Release Builds - LTO and optimizations enabled

πŸ§ͺ Testing

# Run tests
cargo test

# Run with logging
RUST_LOG=debug cargo run

πŸ› Troubleshooting

Database Connection Issues

# Check PostgreSQL is running
pg_isready

# Test connection
psql -U postgres -d chatapp

WebSocket Not Connecting

  • Check browser console for errors
  • Verify JWT token is valid
  • Ensure WebSocket feature is enabled in Ignitia

Port Already in Use

# Change SERVER_PORT in .env file
SERVER_PORT=8081

🀝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

πŸ“ License

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

πŸ‘¨β€πŸ’» Author

Built with ❀️ using Ignitia - A blazing fast Rust web framework

πŸ™ Acknowledgments

  • Ignitia Framework - Modern Rust web framework with WebSocket support
  • Tokio - Async runtime for Rust
  • SQLx - Compile-time checked SQL queries
  • Argon2 - Password hashing library

πŸ“š Related Projects


Note: This is a demonstration project showcasing Ignitia's WebSocket capabilities with database integration. For production use, consider adding additional features like:

  • Rate limiting
  • Message encryption
  • File/image sharing
  • Group chats
  • Typing indicators
  • Message reactions
  • Push notifications

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Sponsor this project

  •  

Packages

No packages published