https://github.com/simran1002/refer-loop
https://github.com/simran1002/refer-loop
fastapi nodemailer postgresql python rate-limiter smtp
Last synced: 2 months ago
JSON representation
- Host: GitHub
- URL: https://github.com/simran1002/refer-loop
- Owner: simran1002
- Created: 2025-02-27T15:23:08.000Z (over 1 year ago)
- Default Branch: main
- Last Pushed: 2025-02-27T18:45:50.000Z (over 1 year ago)
- Last Synced: 2025-03-07T19:36:40.796Z (over 1 year ago)
- Topics: fastapi, nodemailer, postgresql, python, rate-limiter, smtp
- Language: Python
- Homepage:
- Size: 210 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
Referease
A production-ready SaaS Referral Engine with multi-tiered rewards, real-time updates, fraud detection, and background task processing.
Screenshots •
Features •
Architecture •
Quick Start •
API Reference •
Project Structure
---
## Screenshots
### Login & Registration

### Dashboard

### Leaderboard

### Rewards Store

### How It Works

### Profile & Settings

---
## Features
### Multi-Tiered Reward System
| Tier | Threshold | Reward Rate | Tier Bonus |
|------|-----------|-------------|------------|
| Bronze | 0 – 9 referrals | 10 pts/referral | — |
| Silver | 10 – 49 referrals | 15 pts/referral | +100 pts |
| Gold | 50+ referrals | 25 pts/referral | +500 pts |
**Points Formula:** `Total Points = (Referrals × Reward Rate) + Tier Bonus`
### Fraud Detection Engine
- **IP Rate Limiting** — Blocks excessive sign-ups from the same IP address (configurable threshold)
- **Fuzzy Email Matching** — Uses `difflib.SequenceMatcher` to detect near-duplicate email addresses (e.g., `john@gmail.com` vs `j0hn@gmail.com`)
- **Self-Referral Prevention** — Fuzzy-matches the referrer's email against the new user's email
- **Audit Logging** — All flagged attempts are persisted to `fraud_logs` for review
### Real-Time Updates (WebSockets)
- Live dashboard updates when referrals are processed
- Heartbeat mechanism to keep connections alive
- Auto-reconnect with exponential backoff on the frontend
### Background Task Processing (Celery + Redis)
- **Welcome Email** — Triggered on every new registration
- **Milestone Email** — Triggered when a referrer gains a new referral
- Retry logic with configurable max retries and delays
- Redis as both message broker and result backend
### Frontend (Next.js 14 App Router)
- **6 dedicated pages** — Dashboard, Leaderboard, Rewards, How It Works, Profile, Login
- **Sidebar navigation** with active page highlighting
- **Dark mode** toggle with OS preference detection and localStorage persistence
- **Confetti animation** on tier upgrades
- **Tier celebration modal** with auto-dismiss
- **Social sharing** — Twitter/X, WhatsApp, LinkedIn, Email
- **Responsive design** — Sidebar collapses to hamburger menu on mobile
- **QR code** for referral link sharing
### Security
- **JWT via HttpOnly Cookies** — Tokens are never exposed to JavaScript
- **Password validation** — Min 8 chars, uppercase, lowercase, digit, special character
- **bcrypt hashing** — Passwords hashed with industry-standard bcrypt
- **CORS** — Configurable allowed origins
---
## Architecture
```
┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│ Next.js │────▶│ FastAPI │────▶│ PostgreSQL │
│ Frontend │◀────│ Backend │◀────│ Database │
│ (Port 3001) │ │ (Port 8000) │ │ (Port 55432) │
└──────────────┘ └──────┬───────┘ └──────────────┘
│
┌───────┼───────┐
▼ ▼ ▼
┌─────────┐ ┌───┐ ┌──────────────┐
│ Celery │ │WS │ │ Fraud │
│ Worker │ │ │ │ Detection │
└────┬────┘ └───┘ └──────────────┘
│
┌────▼────┐
│ Redis │
│ Broker │
│(Port 56379)│
└─────────┘
```
**Clean Architecture layers:**
- `models/` — SQLAlchemy ORM entities
- `schemas/` — Pydantic validation & serialization
- `repositories/` — Data access layer (async queries)
- `services/` — Business logic (fraud detection, tier calculation)
- `usecases/` — Application use cases (register user, get stats)
- `api/routes/` — HTTP endpoint handlers
- `api/websockets/` — WebSocket endpoint handlers
- `tasks/` — Celery background tasks
---
## Quick Start
### Prerequisites
- Docker & Docker Compose
- Git
### 1. Clone the repository
```bash
git clone https://github.com/simran1002/refer-loop.git
cd refer-loop
```
### 2. Start all services
```bash
docker-compose up --build -d
```
This spins up 5 containers:
| Service | Internal Port | Host Port |
|---------|--------------|-----------|
| FastAPI Backend | 8000 | 8000 |
| PostgreSQL | 5432 | 55432 |
| Redis | 6379 | 56379 |
| Celery Worker | — | — |
| Next.js Frontend | 3000 | 3001 |
### 3. Open the app
- **Frontend:** http://localhost:3001
- **API Docs (Swagger):** http://localhost:8000/docs
- **Health Check:** http://localhost:8000/health
### 4. Test the referral flow
```bash
# 1. Register a referrer
curl -s -X POST http://localhost:8000/auth/register \
-H "Content-Type: application/json" \
-d '{"username":"alice","email":"alice@example.com","password":"StrongPass1!"}' | python3 -m json.tool
# 2. Note the referral_code from the response, then register a referred user
curl -s -X POST http://localhost:8000/auth/register \
-H "Content-Type: application/json" \
-d '{"username":"bob","email":"bob@different.com","password":"StrongPass1!","referral_code":"ALICE_CODE_HERE"}'
```
---
## API Reference
### Authentication
| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | `/auth/register` | Register a new user (with optional referral code) |
| POST | `/auth/login` | Login and receive HttpOnly JWT cookie |
| POST | `/auth/logout` | Clear the auth cookie |
| GET | `/auth/me` | Get current user profile |
### Referral System
| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/referral/stats` | Dashboard stats (tier, points, rank, recent referrals) |
| GET | `/referral/leaderboard` | Top referrers ranked by points |
### Password Management
| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | `/password/forgot-password` | Request password reset token |
| POST | `/password/reset-password` | Reset password with token |
### System
| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/health` | Health check |
| WS | `/ws/stats/{user_id}` | Real-time referral updates |
---
## Project Structure
```
refer-loop/
├── backend/
│ ├── app/
│ │ ├── api/
│ │ │ ├── dependencies/ # Auth dependency (JWT cookie extraction)
│ │ │ ├── routes/ # HTTP endpoints (auth, referral, leaderboard, profile, password, health)
│ │ │ └── websockets/ # WebSocket endpoint for live stats
│ │ ├── core/
│ │ │ ├── config.py # Pydantic settings (env-based)
│ │ │ ├── database.py # Async SQLAlchemy engine & session
│ │ │ ├── events.py # In-process EventBus for WebSocket pub/sub
│ │ │ └── security.py # JWT, bcrypt, referral code generation
│ │ ├── models/ # SQLAlchemy ORM models (User, Referral, FraudLog)
│ │ ├── repositories/ # Data access layer (async queries)
│ │ ├── schemas/ # Pydantic request/response schemas
│ │ ├── services/ # Business logic (fraud detection, tier engine)
│ │ ├── tasks/ # Celery tasks (welcome email, milestone email)
│ │ ├── usecases/ # Application use cases
│ │ └── main.py # FastAPI app entrypoint
│ ├── Dockerfile
│ └── requirements.txt
├── frontend/
│ ├── app/
│ │ ├── components/ # Reusable UI components
│ │ │ ├── AppShell.tsx # Sidebar layout shell
│ │ │ ├── AuthForm.tsx # Login/Register form
│ │ │ ├── Confetti.tsx # Confetti particle animation
│ │ │ ├── Leaderboard.tsx # Leaderboard table
│ │ │ ├── LiveFeed.tsx # Real-time referral feed
│ │ │ ├── ProgressBar.tsx # Tier progress bar with shimmer
│ │ │ ├── ShareSection.tsx # Referral link + social sharing
│ │ │ ├── StatsCards.tsx # Metric cards with gradients
│ │ │ ├── TierBadge.tsx # Tier indicator badge
│ │ │ └── TierCelebration.tsx # Tier upgrade modal
│ │ ├── hooks/ # Custom React hooks
│ │ │ ├── useAuth.ts # Authentication state
│ │ │ ├── useTheme.ts # Dark mode toggle
│ │ │ └── useWebSocket.ts # WebSocket connection manager
│ │ ├── dashboard/page.tsx # Dashboard page
│ │ ├── leaderboard/page.tsx # Leaderboard page
│ │ ├── rewards/page.tsx # Rewards store page
│ │ ├── how-it-works/page.tsx # Guide & FAQ page
│ │ ├── profile/page.tsx # Profile & settings page
│ │ └── page.tsx # Root (auth redirect)
│ ├── Dockerfile
│ └── package.json
├── docker-compose.yml
├── screenshots/ # README screenshots
└── README.md
```
---
## Environment Variables
| Variable | Default | Description |
|----------|---------|-------------|
| `DATABASE_URL` | `postgresql+asyncpg://...` | Async PostgreSQL connection string |
| `REDIS_URL` | `redis://localhost:6379/0` | Redis connection |
| `SECRET_KEY` | `change-me-...` | JWT signing secret |
| `CORS_ORIGINS` | `["http://localhost:3001"]` | Allowed CORS origins |
| `TIER_SILVER_THRESHOLD` | `10` | Referrals needed for Silver |
| `TIER_GOLD_THRESHOLD` | `50` | Referrals needed for Gold |
| `MAX_SIGNUPS_PER_IP` | `5` | Fraud: max sign-ups per IP |
| `FUZZY_EMAIL_THRESHOLD` | `0.85` | Fraud: email similarity threshold |
See `backend/app/core/config.py` for all configurable settings.
---
## Tech Stack
| Layer | Technology |
|-------|-----------|
| Backend API | FastAPI (Python 3.12, async) |
| Database | PostgreSQL 16 + SQLAlchemy 2.0 (async) |
| Cache / Broker | Redis 7 |
| Background Tasks | Celery 5 |
| Frontend | Next.js 14 (App Router) + React 18 |
| Styling | Tailwind CSS 3 |
| Real-time | WebSockets (native) |
| Auth | JWT (HttpOnly cookies) + bcrypt |
| Containerization | Docker + Docker Compose |
---
## Author
**Simran Yadav**
- GitHub: [@simran1002](https://github.com/simran1002)
- Email: simranyadav464@gmail.com
---
Built with FastAPI, Next.js, Celery & Redis