Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

62 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

⚑ ActiveCore β€” Backend API

Premium Workout Wear E-Commerce Platform

Django DRF PostgreSQL Stripe AWS EC2 CI/CD


πŸ“– Overview

ActiveCore is a full-featured, production-ready REST API backend for a premium workout wear e-commerce platform. Built with Django and Django REST Framework, it handles everything from authentication and product management to real-time order notifications and Stripe-powered payments β€” deployed on AWS EC2 with automated CI/CD.

✨ Features

πŸ” Authentication & Users

  • Cookie-based JWT authentication β€” secure HttpOnly cookies (no localStorage exposure)
  • Google OAuth 2.0 social login
  • OTP verification via Email (SMTP) and WhatsApp (Twilio) for account verify & password reset
  • Role-based access control β€” customer and admin roles with custom permission classes
  • Custom AbstractUser model with UUID primary keys and Cloudinary profile images
  • WebSocket authentication via JWT middleware for Django Channels

πŸ›οΈ Products

  • Full product catalog with categories, product types, variants (size-based), and inventory tracking
  • Cloudinary-powered product image management (primary + secondary images with DB constraints)
  • Product ratings (1–5 stars) with automatic ProductMetrics recalculation via signals
  • Featured products list (max 8 enforced at serializer level)
  • Advanced product list with filtering by category, size, price range, and sorting (newest, price asc/desc)
  • Global search across name, description, category, and product type
  • Separate admin and public serializers for fine-grained response control

πŸ›’ Cart

  • Per-user persistent cart with atomic stock validation using select_for_update
  • Real-time subtotal, 18% GST, shipping, and total recalculation
  • Pre-checkout cart validation β€” detects stale prices and stock issues before payment
  • Full CRUD: add, update quantity, remove item, clear cart, item count

πŸ’³ Orders & Payments

  • Stripe Payment Intent integration with webhook event handling
  • Support for ONLINE and COD (Cash on Delivery) payment methods
  • Full order lifecycle: PENDING β†’ CONFIRMED β†’ PROCESSING β†’ SHIPPED β†’ DELIVERED β†’ CANCELLED / FAILED / REFUNDED
  • Order status history tracking with changed_by audit trail
  • Order expiry management via custom management command (cancel_expired_orders)
  • Per-user account overview with order statistics

πŸ”” Real-Time Notifications & AI Chatbot

  • Django Channels + WebSocket-based push notifications
  • Per-user notification groups; notifications persisted to DB
  • Admin can broadcast global notifications to all users
  • Admin can send targeted notifications to a specific user
  • Triggered automatically on order events via Django signals
  • AI Assistant Chatbot powered by a persistent WebSocket connection (ws://<host>/ws/chat/)
  • Chat interface history persistence via REST APIs

❀️ Wishlist

  • Single wishlist per user (auto-created on registration via signals)
  • Add/remove items, item count, clear all
  • Price-drop detection β€” flags items where current price is below price_at_added
  • Move all wishlist items to cart in one atomic operation

πŸ“Š Admin & Reports

  • Admin APIs for user management: list, search, detail, block/unblock, delete
  • Admin product CRUD with full variant and inventory management
  • Admin order management: list with filters, search, detail, status update, stats
  • Dashboard metrics: total users, revenue, revenue by category, top-selling products/types, order status distribution

πŸ”’ Production Security

  • HTTPS enforced with HSTS preloading (1 year)
  • CSRF and CORS protection with cross-origin cookie support for Vercel frontend
  • X-Frame-Options: DENY, XSS filter, Content-Type-NoSniff
  • SameSite=None; Secure cookies for cross-domain authentication

πŸ—οΈ Tech Stack

Layer Technology
Framework Django 6.0, Django REST Framework
Database PostgreSQL (via dj-database-url)
** Channels** Django Channels
ASGI Server Daphne
Reverse Proxy Nginx + Let's Encrypt SSL
Payments Stripe (Payment Intents + Webhooks)
Media Storage Cloudinary
Auth SimpleJWT (cookie-based, blacklisting), Google OAuth
OTP Twilio WhatsApp API + Django SMTP
API Docs drf-spectacular (OpenAPI 3 β€” Swagger + ReDoc)
Deployment AWS EC2, GitHub Actions CI/CD

πŸ“ Project Structure

activecore-backend/
β”œβ”€β”€ core/                        # Django project settings & routing
β”‚   β”œβ”€β”€ settings/
β”‚   β”‚   β”œβ”€β”€ base.py              # Shared settings (JWT, DRF, Stripe, Cloudinary, etc.)
β”‚   β”‚   β”œβ”€β”€ dev.py               # Development overrides
β”‚   β”‚   └── prod.py              # Production security config (HSTS, secure cookies)
β”‚   β”œβ”€β”€ asgi.py                  # ASGI + WebSocket routing
β”‚   β”œβ”€β”€ pricing.py               # GST + shipping pricing engine
β”‚   └── urls.py                  # Root URL configuration
β”‚
β”œβ”€β”€ apps/
β”‚   β”œβ”€β”€ accounts/                # Auth, users, OTP, Google OAuth, address
β”‚   β”‚   β”œβ”€β”€ authentication.py    # Cookie-based JWT authentication backend
β”‚   β”‚   β”œβ”€β”€ middleware/          # JWT WebSocket auth middleware
β”‚   β”‚   └── api/
β”‚   β”‚       β”œβ”€β”€ serializers/     # 8 purpose-built serializers
β”‚   β”‚       └── views/
β”‚   β”‚           β”œβ”€β”€ admin/       # Admin user management views
β”‚   β”‚           └── public/      # Login, register, OTP, Google auth, me
β”‚   β”‚
β”‚   β”œβ”€β”€ products/                # Catalog, variants, inventory, ratings
β”‚   β”‚   β”œβ”€β”€ models.py            # Category, ProductType, Product, Variant, Inventory, Metrics
β”‚   β”‚   β”œβ”€β”€ signals.py           # Auto-create ProductMetrics on product creation
β”‚   β”‚   └── api/
β”‚   β”‚       β”œβ”€β”€ serializers/     # 14 purpose-built serializers
β”‚   β”‚       └── views/
β”‚   β”‚           β”œβ”€β”€ admin/       # Category, ProductType, Product, Variant CRUD
β”‚   β”‚           └── public/      # List, detail, search, featured, ratings
β”‚   β”‚
β”‚   β”œβ”€β”€ cart/                    # Shopping cart with atomic stock validation
β”‚   β”‚   └── api/views/
β”‚   β”‚       β”œβ”€β”€ cart_read_views.py
β”‚   β”‚       β”œβ”€β”€ cart_write_views.py
β”‚   β”‚       β”œβ”€β”€ cart_meta_views.py
β”‚   β”‚       └── cart_validation_views.py
β”‚   β”‚
β”‚   β”œβ”€β”€ orders/                  # Checkout, Stripe, webhooks, order lifecycle
β”‚   β”‚   β”œβ”€β”€ services.py          # OrderService β€” create, cancel, update status
β”‚   β”‚   └── management/commands/
β”‚   β”‚       └── cancel_expired_orders.py
β”‚   β”‚
β”‚   β”œβ”€β”€ wishlist/                # Single wishlist per user with price-drop detection
β”‚   β”œβ”€β”€ notifications/           # WebSocket real-time notifications
β”‚   β”‚   β”œβ”€β”€ consumers.py         # AsyncWebsocketConsumer
β”‚   β”‚   └── services.py          # notify_user, notify_all_users helpers
β”‚   β”œβ”€β”€ reports/                 # Admin analytics dashboard
β”‚   └── common/                  # Shared pagination (page_size=12, max=100)
β”‚
β”œβ”€β”€ deploy/
β”‚   β”œβ”€β”€ nginx.conf               # Nginx reverse proxy + SSL config
β”‚   β”œβ”€β”€ daphne.service           # Systemd service for Daphne ASGI
β”‚   └── deploy.sh                # Manual deploy script
β”‚
└── .github/
    └── workflows/
        └── deploy.yml           # GitHub Actions CI/CD pipeline

πŸš€ Getting Started

Prerequisites

  • Python 3.11+
  • PostgreSQL 14+
  • Cloudinary account
  • Stripe account (with webhooks configured)
  • Twilio account (for WhatsApp OTP)

1. Clone & Install

git clone https://github.com/adinathmk/activecore-backend.git
cd activecore-backend

python -m venv venv
source venv/bin/activate        # Windows: venv\Scripts\activate

pip install -r requirements.txt

2. Environment Variables

cp .env.example .env
# Django
DJANGO_ENV=development
DEBUG=True
SECRET_KEY=your-secret-key
ALLOWED_HOSTS=127.0.0.1,localhost

# CORS
CORS_ALLOWED_ORIGINS=http://localhost:5173
CSRF_TRUSTED_ORIGINS=http://localhost:5173

# Database
DATABASE_URL=postgresql://user:password@localhost:5432/activecore

# Cloudinary
CLOUDINARY_CLOUD_NAME=...
CLOUDINARY_API_KEY=...
CLOUDINARY_API_SECRET=...

# Email
EMAIL_HOST=smtp.gmail.com
EMAIL_PORT=587
EMAIL_USE_TLS=True
EMAIL_HOST_USER=your@email.com
EMAIL_HOST_PASSWORD=your-app-password
DEFAULT_FROM_EMAIL=your@email.com

# Stripe
STRIPE_SECRET_KEY=sk_test_...
STRIPE_WEBHOOK_SECRET=whsec_...
STRIPE_PUBLISHABLE_KEY=pk_test_...

# Twilio
TWILIO_ACCOUNT_SID=...
TWILIO_AUTH_TOKEN=...
TWILIO_WHATSAPP_NUMBER=whatsapp:+14155238886

# Google OAuth
GOOGLE_CLIENT_ID=...

3. Database & Static Files

python manage.py migrate
python manage.py collectstatic
python manage.py createsuperuser

4. Run Development Server

# HTTP only
python manage.py runserver

# With WebSocket support (recommended)
daphne core.asgi:application

πŸ”Œ API Reference

All endpoints are prefixed with /api/. Interactive docs available at:

  • Swagger UI: /api/docs/
  • ReDoc: /api/redoc/
  • OpenAPI Schema: /api/schema/

Auth legend: ❌ Public Β |Β  βœ… Authenticated Β |Β  πŸ”’ Admin only


πŸ” Auth β€” /api/auth/

Method Endpoint Auth Description
POST /register/ ❌ Register a new user
POST /login/ ❌ Login β€” sets HttpOnly JWT cookies
POST /logout/ βœ… Logout and clear auth cookies
POST /refresh/ ❌ Refresh access token using refresh cookie
GET /me/ βœ… Get current user profile + address
PATCH /me/ βœ… Update profile (name, phone, avatar, address)
POST /send-otp/ ❌ Send account verification OTP to email
POST /verify-otp/ ❌ Verify OTP and activate account
POST /forgot-password/ ❌ Send password reset OTP via email or WhatsApp
POST /reset-password/ ❌ Reset password using OTP
POST /google/ ❌ Sign in / register with Google OAuth2
GET /admin/users/ πŸ”’ List all users (paginated)
GET /admin/users/search/ πŸ”’ Search users by name
GET /admin/users/<uuid>/ πŸ”’ Get detailed user info
POST /admin/users/<uuid>/block/ πŸ”’ Toggle user active/blocked status
DELETE /admin/users/<uuid>/delete/ πŸ”’ Delete a user account

πŸ›οΈ Products β€” /api/products/

Method Endpoint Auth Description
GET / ❌ List products (paginated, 12 per page)
GET /?category=<slug> ❌ Filter by category slug
GET /?size=<S|M|L|XL> ❌ Filter by size
GET /?min_price=&max_price= ❌ Filter by selling price range
GET /?sort=newest|price_asc|price_desc ❌ Sort products
GET /search/?q=<query>&limit=<n> ❌ Full-text product search (max 20 results)
GET /home/featured/ ❌ Get featured products (up to 8)
GET /<slug>/ ❌ Product detail with variants, images, features, ratings
POST /<slug>/rate/ βœ… Submit or update a product rating (1–5 stars)
GET /admin/ πŸ”’ List all products with optional filters
POST /admin/ πŸ”’ Create new product (multipart/form-data with images)
GET /admin/<id>/ πŸ”’ Admin product detail
PATCH /admin/<id>/ πŸ”’ Update product (partial, supports image replacement)
DELETE /admin/<id>/ πŸ”’ Soft-delete product (sets is_active=False)
GET /admin/search/ πŸ”’ Search products across name, category, type
GET /admin/categories/ πŸ”’ List all categories
POST /admin/categories/ πŸ”’ Create new category (auto-generates slug)
GET /admin/product-types/ πŸ”’ List all product types
POST /admin/product-types/ πŸ”’ Create new product type
GET /admin/variants/ πŸ”’ List all variants with inventory
POST /admin/variants/ πŸ”’ Create a new variant + inventory record
GET /admin/variants/<id>/ πŸ”’ Get variant detail
PATCH / PUT /admin/variants/<id>/ πŸ”’ Update variant and stock
DELETE /admin/variants/<id>/ πŸ”’ Deactivate a variant

πŸ›’ Cart β€” /api/cart/

Method Endpoint Auth Description
GET / βœ… Get cart with all items, subtotal, tax, total
GET /count/ βœ… Get total item quantity in cart
POST /add/ βœ… Add a variant to cart (with stock check)
PATCH /items/<id>/ βœ… Update item quantity (set 0 to remove)
DELETE /items/<id>/remove/ βœ… Remove a specific cart item
DELETE /clear/ βœ… Remove all items from cart
POST /validate/ βœ… Validate cart before checkout (stock + price sync)

πŸ“¦ Orders β€” /api/orders/

Method Endpoint Auth Description
POST /checkout/ βœ… Create order from cart (ONLINE or COD)
GET / βœ… List all orders for current user
GET /<uuid>/ βœ… Order detail with items and status history
POST /<uuid>/cancel/ βœ… Cancel an order
GET /account-overview/ βœ… Summary: total orders, delivered, cancelled, total spent
POST /<uuid>/create-payment-intent/ βœ… Create Stripe Payment Intent for an order
POST /payments/webhook/ ❌ Stripe webhook (handles payment success / failure)
GET /admin/ πŸ”’ List all orders with filters and ordering
GET /admin/search/ πŸ”’ Search orders by ID, email, customer name
GET /admin/<uuid>/ πŸ”’ Admin order detail
PATCH /admin/<uuid>/update-status/ πŸ”’ Update order status
GET /admin/stats/ πŸ”’ Order statistics and analytics

❀️ Wishlist β€” /api/wishlist/

Method Endpoint Auth Description
GET / βœ… Get wishlist items (includes is_price_dropped flag)
DELETE / βœ… Clear entire wishlist
GET /count/ βœ… Get wishlist item count
POST /items/ βœ… Add a product variant to wishlist
DELETE /items/<variant_id>/ βœ… Remove a specific item from wishlist
POST /move-to-cart/ βœ… Atomically move all wishlist items to cart

πŸ”” Notifications β€” /api/notifications/

Method Endpoint Auth Description
GET / βœ… Get notifications (admin can pass ?user_id=<uuid>)
POST /send/ πŸ”’ Broadcast notification to all users via WebSocket
POST /send-user/ πŸ”’ Send notification to a specific user via WebSocket

WebSocket Endpoint: ws://<host>/ws/notifications/

  • Requires valid access JWT cookie
  • Joins a per-user channel group (user_<uuid>) on connect
  • Receives real-time JSON messages on order status changes

πŸ’¬ AI Chatbot β€” /api/chat/

Method Endpoint Auth Description
GET /history/ βœ… Get a history of chatbot messages (limit 50)

WebSocket Endpoint: ws://<host>/ws/chat/

  • Requires valid access JWT cookie
  • Receives real-time AI JSON text chunks dynamically streams the response

πŸ“Š Reports β€” /api/reports/

Method Endpoint Auth Description
GET /dashboard/ πŸ”’ Dashboard: users, revenue, top products/types, order status distribution

βš™οΈ Deployment

CI/CD Pipeline

Every push to main triggers a GitHub Actions workflow that SSHs into the EC2 instance and runs:

git pull origin main
pip install -r requirements.txt
python manage.py migrate
python manage.py collectstatic --noinput
sudo systemctl restart daphne

Manual Deploy

bash deploy/deploy.sh

Infrastructure

Internet ──► Nginx (443/SSL) ──► Daphne (127.0.0.1:8001) ──► Django / Channels ->  PostgreSQL
                                   
  • Daphne runs as a systemd service bound to 127.0.0.1:8001
  • Nginx handles HTTPS termination (Let's Encrypt) and proxies all traffic including WebSocket upgrades

πŸ”§ Management Commands

# Cancel unpaid orders that have exceeded their expiry window
python manage.py cancel_expired_orders

Recommended to schedule as a cron job every 5–10 minutes in production.


πŸ§ͺ Running Tests

python manage.py test apps

πŸ“¦ Key Dependencies

Django 6.0
djangorestframework
djangorestframework-simplejwt
django-channels
daphne
drf-spectacular
django-environ
dj-database-url
cloudinary / django-cloudinary-storage
stripe
twilio
phonenumbers
psycopg2-binary

Built with ❀️ for ActiveCore β€” Where performance meets style.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages