13 KiB
HabitForge 🎯
HabitForge is a powerful, self-hosted habit tracking and gamification platform designed to help users build and maintain consistent routines. It combines a robust Python backend with a dynamic, modern frontend to provide a premium user experience.
📖 Overview
HabitForge allows users to create custom challenges (daily, weekly, monthly), track their progress with detailed analytics, and stay motivated through gamification elements like badges and streaks. The application is built with a Mobile-First design philosophy, ensuring a seamless experience across all devices.
Key Features
- 🏆 Gamification: Earn badges for streaks, total reps, and consistency.
- 📊 Analytics: Visual charts (reps, completion rates) and consistency heatmaps.
- 🔁 Flexible Challenges: Support for Daily, Weekly (specific days), and Monthly targets.
- 🧠 Smart Tracking: Tracks reps, completion status, and optional notes per day.
- 🌗 Dark Mode: Fully supported dark/light themes with persistence.
- 📱 Responsive UI: Built with Tailwind CSS for a fluid experience on mobile and desktop.
- 🔐 Authentication: Secure JWT-based user authentication system.
- 🖱️ Drag & Drop: Reorder challenges easily to prioritize your focus.
🛠 Tech Stack
Backend
- Framework: FastAPI (High performance, easy to learn)
- Database ORM: SQLAlchemy
- Database: SQLite (Default, stored in
./data/habitforge.db) - Authentication: OAuth2 with Password (and hashing via Argon2/Passlib)
- Schema Validation: Pydantic Models
Frontend
- Core: Vanilla JavaScript (ES6+)
- Styling: Tailwind CSS (via CDN for simplicity)
- Icons: FontAwesome 6
- Animations: Anime.js
- Charts: Chart.js
- Drag & Drop: SortableJS
Infrastructure
- Containerization: Docker & Docker Compose
- Server: Uvicorn (ASGI)
🚀 Getting Started
Prerequisites
Before you begin, ensure you have the following installed:
- Docker and Docker Compose
- Python 3.9+ (if running locally without Docker)
- Google OAuth Credentials (optional, for health metrics sync)
Environment Setup
HabitForge uses environment variables for configuration.
- Copy the example file:
cp .env.example .env.development # Also create production if needed cp .env.example .env.production - Edit the files: Fill in your
SECRET_KEYand Google API credentials.
🐳 Running with Docker (Recommended)
HabitForge provides several Docker Compose configurations depending on your needs:
1. Simple Mode (SQLite)
Perfect for a quick test or personal use with zero database configuration.
# Uses docker-compose.yml
docker-compose up -d --build
- Database: SQLite stored in
./data/habitforge.db - Access:
http://localhost:8000
2. Development Mode (PostgreSQL)
Ideal for development with a robust database and hot-reloading enabled.
# Uses docker-compose.dev.yml
docker-compose -f docker-compose.dev.yml up -d --build
- Database: PostgreSQL 15
- Features: Auto-reload enabled in the backend.
- Access:
http://localhost:8000
3. Production Mode (Full Stack)
The professional setup with security and performance in mind.
# Uses docker-compose.prod.yml
docker-compose -f docker-compose.prod.yml up -d --build
- Components:
- Nginx: Reverse proxy with SSL/TLS support.
- Gunicorn: Production-grade WSGI server with multiple workers.
- PostgreSQL: Dedicated database container.
- Backup: Automatic daily database backups to
./backups.
- Access:
http://localhost(or your configured domain)
🐍 Local Development (Manual)
If you prefer to run the services directly on your machine:
-
Set up Python Environment:
python -m venv venv # Windows .\venv\Scripts\activate # Linux/Mac source venv/bin/activate -
Install Dependencies:
pip install -r requirements.txt -
Run the Server:
# Ensure your .env file is present or env vars are set uvicorn backend.main:app --reload --host 0.0.0.0 --port 8000
📂 Project Structure
HabitForge/
├── backend/ # Python FastAPI Backend (Modular Architecture)
│ ├── api/v1/ # API Routes (Auth, Challenges, Health)
│ ├── core/ # Configuration, Security, Dependencies
│ ├── models/ # SQLAlchemy Database Models
│ ├── schemas/ # Pydantic Validation Schemas
│ ├── services/ # Business Logic Layer
│ ├── repositories/ # Data Access Layer
│ └── integrations/ # External APIs (Google Fit, Zepp)
├── frontend/ # Static Frontend Assets
│ ├── app.js # Main frontend logic
│ └── index.html # Dashboard
├── data/ # SQLite storage (if used)
├── nginx/ # Nginx configuration and SSL certificates
├── scripts/ # Database migrations and backup scripts
├── docker-compose.yml # Simple SQLite configuration
├── docker-compose.dev.yml # Development (Postgres) configuration
└── docker-compose.prod.yml # Production (Nginx + Postgres + Backup) configuration
🔌 API Documentation
Once the server is running, you can access the automatic interactive API documentation provided by Swagger UI:
- Docs:
http://localhost:8000/docs - Redoc:
http://localhost:8000/redoc
Core Endpoints
- Auth:
/api/auth/register,/api/auth/token - Challenges:
GET /api/challenges: List all user challengesPOST /api/challenges: Create new challengePUT /api/challenges/reorder: Update display order
- Tracking:
POST /api/tracking: Log reps/completion for a date
🔧 Configuration
All configuration is managed via Environment Variables or a .env file.
| Variable | Description | Default |
|---|---|---|
SECRET_KEY |
Key for JWT encryption | Required |
DATABASE_URL |
SQLAlchemy connection string | sqlite:///./data/habitforge.db |
CORS_ORIGINS |
Allowed origins for API | http://localhost:8000 |
GOOGLE_CLIENT_ID |
Google OAuth Client ID | "" |
GOOGLE_CLIENT_SECRET |
Google OAuth Client Secret | "" |
🔐 Google OAuth Setup (Health Metrics Integration)
To enable Google Fit integration for health metrics tracking, you need to create OAuth 2.0 credentials in the Google Cloud Console.
Step 1: Create a Google Cloud Project
- Go to Google Cloud Console
- Click "Select a project" → "New Project"
- Enter a project name (e.g., "HabitForge")
- Click "Create"
Step 2: Enable Required APIs
- In your project, navigate to "APIs & Services" → "Library"
- Search for and enable the following APIs:
- Google Fitness API
- Google OAuth2 API (usually enabled by default)
Step 3: Configure OAuth Consent Screen
- Go to "APIs & Services" → "OAuth consent screen"
- Select "External" (unless you have a Google Workspace)
- Fill in the required information:
- App name: HabitForge
- User support email: Your email
- Developer contact: Your email
- Click "Save and Continue"
- Scopes: Click "Add or Remove Scopes" and add:
.../auth/fitness.activity.read.../auth/fitness.body.read.../auth/fitness.heart_rate.read.../auth/fitness.sleep.read
- Click "Save and Continue"
- Test users: Add your Google account email (for testing)
- Click "Save and Continue"
Step 4: Create OAuth 2.0 Credentials
- Go to "APIs & Services" → "Credentials"
- Click "+ Create Credentials" → "OAuth client ID"
- Select "Web application"
- Configure:
- Name: HabitForge Web Client
- Authorized JavaScript origins:
http://localhost:8000 https://yourdomain.com - Authorized redirect URIs:
http://localhost:8000/api/google/callback https://yourdomain.com/api/google/callback
- Click "Create"
- Copy your credentials:
GOOGLE_CLIENT_ID: The Client ID (looks likexxxxx.apps.googleusercontent.com)GOOGLE_CLIENT_SECRET: The Client Secret
Step 5: Update Your .env File
Add the credentials to your .env file:
GOOGLE_CLIENT_ID=your-client-id-here.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET=your-client-secret-here
Step 6: Test the Integration
- Restart your application
- Navigate to the Health Dashboard
- Click the "Sync" button
- Authorize HabitForge to access your Google Fit data
- Data should sync automatically
🗄️ Database Configuration
HabitForge supports two database backends: SQLite (default, simple) and PostgreSQL (production-ready).
Option 1: SQLite (Default - Recommended for Personal Use)
SQLite requires no additional setup and is perfect for single-user deployments.
Configuration:
# .env file
DATABASE_URL=sqlite:///./data/habitforge.db
Characteristics:
- ✅ Zero configuration required
- ✅ File-based (stored in
./data/habitforge.db) - ✅ Perfect for personal use
- ✅ Automatic backups via file copy
- ⚠️ Not recommended for high-concurrency scenarios
Docker Compose:
# Uses SQLite by default
docker-compose up -d --build
Option 2: PostgreSQL (Recommended for Production)
PostgreSQL provides better performance, concurrency, and scalability.
A. Using Docker Compose (Easiest)
Development Mode:
# Uses docker-compose.dev.yml with PostgreSQL
docker-compose -f docker-compose.dev.yml up -d --build
Production Mode:
# Uses docker-compose.prod.yml with PostgreSQL + Nginx
docker-compose -f docker-compose.prod.yml up -d --build
The database credentials are configured in the respective docker-compose files.
B. Using External PostgreSQL Server
If you have an existing PostgreSQL server:
-
Create a database:
CREATE DATABASE habitforge; CREATE USER habitforge_user WITH PASSWORD 'your_secure_password'; GRANT ALL PRIVILEGES ON DATABASE habitforge TO habitforge_user; -
Configure DATABASE_URL:
# .env file DATABASE_URL=postgresql://habitforge_user:your_secure_password@localhost:5432/habitforgeFormat:
postgresql://[username]:[password]@[host]:[port]/[database_name]Examples:
# Local PostgreSQL DATABASE_URL=postgresql://postgres:password@localhost:5432/habitforge # Remote PostgreSQL DATABASE_URL=postgresql://user:[email protected]:5432/habitforge # With SSL DATABASE_URL=postgresql://user:[email protected]:5432/habitforge?sslmode=require -
Run migrations:
alembic upgrade head
C. PostgreSQL on Cloud Providers
Heroku Postgres:
DATABASE_URL=postgresql://user:[email protected]:5432/dbname
AWS RDS:
DATABASE_URL=postgresql://username:[email protected]:5432/habitforge
Google Cloud SQL:
DATABASE_URL=postgresql://user:pass@/dbname?host=/cloudsql/project:region:instance
DigitalOcean Managed Database:
DATABASE_URL=postgresql://user:[email protected]:25060/habitforge?sslmode=require
Switching Between Databases
To switch from SQLite to PostgreSQL (or vice versa):
- Update DATABASE_URL in your
.envfile - Run migrations:
alembic upgrade head - Restart the application:
docker-compose down docker-compose up -d --build
Note: Data is not automatically migrated between databases. You'll need to export/import data manually if switching with existing data.
Database Migrations
The project includes Alembic for database version control.
alembic upgrade head
🤝 Contributing
Contributions are welcome!
- Fork the project.
- Create your feature branch (
git checkout -b feature/AmazingFeature). - Commit your changes (
git commit -m 'Add some AmazingFeature'). - Push to the branch (
git push origin feature/AmazingFeature). - Open a Pull Request.
📄 License
Distributed under the MIT License. See LICENSE for more information.