Skip to content

Z4phxr/RivioHabbitTracker

Repository files navigation

Rivio - Habits, Mood & Sleep

A production-ready web application for tracking daily habits, sleep patterns, and mood with intelligent visualizations and performance-optimized backend.

Tests Coverage Django Python Docker License


Live Demo

The application is deployed on Railway:

https://rivio.up.railway.app

Note: This is a demo environment. Data may be reset periodically. For production use, deploy your own instance.


Overview

Rivio is a full-stack web application designed for individuals who want to monitor and improve their daily routines. Built with Django and modern web technologies, it offers:

  • Multi-dimensional tracking: habits, sleep quality, and mood in one unified platform
  • Flexible visualizations: day, week, and month views with color-coded progress indicators
  • Production-grade security: JWT authentication, rate limiting, CSRF protection, and secure headers
  • Performance-optimized: N+1 query elimination, batch operations, and connection pooling
  • Timezone-aware architecture: consistent UTC storage with local timezone display
  • RESTful API: comprehensive API for integrations and mobile apps

Rivio - App Screenshot

✨ Features

Core Functionality

  • Custom Habit Tracking - Create unlimited habits, track daily completion with visual feedback
  • Sleep Quality Logging - Record sleep periods (start/end times), visualize patterns, detect overlaps automatically
  • Mood Tracking - Daily mood logging (0-10 scale) with trend visualization
  • Multi-Period Views - Day, week, and month views for each tracking category
  • Dynamic UI - Color-coded blocks (green=complete, gray=incomplete), gradient backgrounds, dark mode support

Technical Highlights

  • JWT Authentication - Secure API access with token rotation and blacklisting (15-min access tokens, 7-day refresh)
  • Performance Optimized - 94%+ query reduction through select_related/prefetch_related and batch operations
  • Timezone-Aware - All timestamps stored in UTC, converted to user's local timezone for display
  • Security-First - Rate limiting (5 auth attempts/min), CSRF protection, HSTS, secure cookies
  • High Test Coverage - 148 tests with 85% code coverage (models, views, serializers, services, security, API)
  • Docker-Ready - Multi-stage Dockerfile, Docker Compose orchestration for dev and production

API Features

  • RESTful API v1: All endpoints under /api/v1/ prefix for future versioning
  • Interactive Documentation:
    • Swagger UI at /api/docs/- Test endpoints in browser
    • ReDoc at /api/redoc/- Beautiful API reference
    • OpenAPI schema at /api/schema/- Machine-readable spec
  • JWT Authentication: Register, login, refresh, logout with token blacklisting
  • Rate Limiting: 20 req/min (anonymous), 200 req/hour (authenticated)
  • Comprehensive Validation: Clear error messages and field-level feedback
  • Pagination: 100 items per page with next/previous links

Tech Stack

Backend

  • Framework: Django 5.2.11
  • API: Django REST Framework with JWT authentication (djangorestframework-simplejwt 5.5.1)
  • Database: PostgreSQL 15 (production), SQLite (development)
  • Server: Gunicorn 23.0.0 (WSGI)

Security & Middleware

  • Authentication: JWT (access + refresh tokens with rotation and blacklist)
  • Rate Limiting: django-ratelimit 4.1.0 + DRF throttling
  • CORS: django-cors-headers 4.3.1
  • CSP: django-csp 3.8 (Content Security Policy)
  • Environment: django-environ 0.11.2 (.env file support)

Frontend

  • Templates: Django templating engine with custom template tags
  • CSS: Custom CSS with CSS variables for theming (dark mode support)
  • JavaScript: Vanilla JS for dynamic interactions (habit toggling, theme switching)
  • Static Files: WhiteNoise 6.6.0 (compression and caching)

Infrastructure & DevOps

  • Containerization: Docker with multi-stage builds (optimized production images)
  • Orchestration: Docker Compose (dev and prod configurations)
  • CI/CD: GitHub Actions (tests, linting, security scanning with Trivy + Bandit, Docker build verification)
  • Deployment: Railway (PaaS) with automatic deployments from GitHub
  • Monitoring: Sentry SDK 2.8.0 (optional, error tracking)
  • Backups: Automated PostgreSQL backup scripts with S3/R2 cloud upload support

Development Tools

  • Debugging: django-debug-toolbar 4.2.0 (query profiling, SQL inspection)
  • Testing: Django TestCase + DRF APIClient (148 tests, 85% coverage)

Architecture & Key Decisions

Architectural Patterns

  1. Service Layer Pattern

    • Business logic extracted to base/services/sleep_service.py
    • Handles complex operations: overlap detection, batch queries, date range filtering
    • Benefits: Testable in isolation (98% coverage), reusable across views and API
    • Example: SleepService.detect_overlaps() used by both HTML views and API
  2. Timezone-First Design

    • Global setting: TIME_ZONE='UTC', USE_TZ=True
    • Database: All timestamps stored in UTC (prevents timezone bugs)
    • Display: Converted to user's local timezone via JavaScript Date objects and Django utilities
    • Utilities: Centralized helpers in base/utils.py:
      • get_today()timezone.localdate() (replaces date.today())
      • get_now()timezone.now() (replaces datetime.now())
      • parse_date_param() → safe date parsing from query params
  3. N+1 Query Elimination

    • Problem: Original implementation had 50+ queries for week view
    • Solution:
      • select_related('habit') for HabitLog FK traversal
      • Batch queries in SleepService (date__in filters)
      • Prefetch logs in single query, build dict in memory
    • Benchmarks:
      • Habits week (7 habits, 7 days): 50 queries → 3 queries
      • Sleep week: 30 queries → 1 query
      • Mood month (30 days): 32 queries → 2 queries
  4. JWT vs Session Auth

    • API endpoints (/api/*): JWT authentication only
      • Short-lived access tokens (15 minutes) for security
      • Refresh tokens (7 days) for convenience
      • Token rotation on refresh (generates new refresh token)
      • Blacklist on logout (prevents token reuse)
    • HTML views (/): Session authentication (Django's built-in)
      • Secure cookies in production (SESSION_COOKIE_SECURE=True)
      • CSRF protection for all POST forms
    • Why separate? API and web UI have different security requirements; JWT is stateless (no DB lookup per request), sessions are familiar for HTML forms
  5. Defense in Depth (Validation)

    • 3 layers of validation for data integrity:
      1. Database constraints: CheckConstraint(end > start) for SleepLog
      2. Model validation: clean() methods check duration (30min - 24h)
      3. Serializer validation: API-level checks with user-friendly error messages
    • Why? Catches errors at multiple levels, prevents invalid data from edge cases

Security

Production-Grade Security Measures

  1. Authentication & Authorization

    • JWT with token rotation and blacklisting (prevents stolen token reuse)
    • Access tokens expire after 15 minutes (short window for compromise)
    • Refresh tokens expire after 7 days (balance security and UX)
    • Secure password hashing (Django's PBKDF2 with SHA256)
    • Password validation (length, similarity, common passwords, numeric-only checks)
  2. Rate Limiting

    • Auth endpoints: 5 attempts per minute per IP (prevents brute force)
    • Anonymous API: 20 requests per minute (prevents DoS)
    • Authenticated API: 200 requests per hour (generous for normal use)
    • Implementation: django-ratelimit + DRF throttling with cache backend
  3. HTTPS & Secure Headers

    • SECURE_SSL_REDIRECT=True in production (HTTP → HTTPS redirect)
    • HSTS enabled (1 year, includeSubdomains, preload)
    • SECURE_BROWSER_XSS_FILTER=True (XSS protection)
    • X_FRAME_OPTIONS='DENY' (prevents clickjacking)
    • SECURE_CONTENT_TYPE_NOSNIFF=True (MIME sniffing protection)
    • Secure cookies: SESSION_COOKIE_SECURE=True, CSRF_COOKIE_SECURE=True
  4. CSRF & CORS

    • CSRF tokens required for all POST/PUT/DELETE forms
    • CORS strict whitelist in production (CORS_ALLOW_ALL_ORIGINS=False)
    • CORS_ALLOWED_ORIGINS explicitly configured via environment variable
  5. Secrets Management

    • SECRET_KEY required via environment variable (fail-fast if missing)
    • No hardcoded secrets in codebase
    • .env file support for local development (excluded from git)
    • Database credentials via DATABASE_URL or separate env vars
  6. Input Validation

    • Django's built-in SQL injection protection (parameterized queries)
    • XSS prevention (template auto-escaping)
    • Serializer validation for API inputs (max length, range checks)
    • Model-level validation (duration bounds, date constraints)