Skip to content

VortexDevX/AutoSecure

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

58 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ›‘οΈ AutoSecure

  • Automobile Insurance & License Management Platform

A full-stack enterprise application for managing insurance policies, driving license records, analytics, and business operations β€” built with Next.js 16, Express 5, and MongoDB.

TypeScript Next.js Express MongoDB TailwindCSS License


πŸ“‹ Overview

AutoSecure is a production-grade insurance management system designed for agencies and brokers to:

  • Create & track automobile insurance policies end-to-end
  • Manage driving license records with document storage
  • Monitor financial metrics, branch performance, and revenue trends
  • Automate email notifications with customizable templates
  • Copy renewal message templates for WhatsApp/SMS/manual follow-up
  • Export data in Excel/XLSX format for reporting
  • Control access with owner-managed granular permissions and two-factor authentication

✨ Features

πŸ“„ Policy Management

  • Multi-step policy creation wizard
  • Customer, vehicle, nominee, and premium detail capture
  • Previous policy tracking with NCB history
  • Document uploads (Aadhaar, PAN, other docs) to cloud storage
  • Payment tracking with multi-mode split payments
  • Auto-calculated profit and extra amount fields
  • Advanced filtering by status, type, branch, date range
  • Search across policy number, customer, and registration number
  • Renewal email and copy-message workflows

πŸͺͺ License Management

  • Driving license record CRUD
  • Faceless / Non-faceless / Reminder categorization
  • Approval workflow tracking
  • Financial breakdown (fee, agent fee, customer payment, profit)
  • Document attachment support
  • Renewal email and copy-message workflows

πŸ“Š Analytics Dashboard

  • Real-time metric cards (policies, revenue, licenses)
  • Monthly trend charts
  • Revenue trend visualization
  • Policies by status/type distribution
  • Branch performance comparison
  • License analytics breakdown
  • Renewal calendar
  • Date-range selectable analytics

πŸ‘₯ User & Admin

  • Role-based access control: Owner β†’ Admin β†’ User
  • Granular permission grants for policies, licenses, exports, users, audit, settings, templates, and meta data
  • User management (create, activate/deactivate)
  • TOTP-based two-factor authentication (2FA)
  • Password reset via email OTP
  • Audit log tracking for all operations
  • Site kill-switch (enable/disable entire platform)
  • Configurable meta options (branches, insurance types, companies, cities, etc.)
  • Email and message template management with variable substitution

πŸ“€ Data Export

  • Export policies and licenses to XLSX
  • Filtered export support
  • Export reason capture and audit trail
  • Structured Excel reports with formatting

πŸ”” Notifications

  • In-app notification center
  • Email notifications via Brevo / Resend / SMTP
  • Customizable email templates per entity type

πŸ—οΈ Architecture

AutoSecure/
β”œβ”€β”€ backend/              # Express 5 REST API
β”‚   └── src/
β”‚       β”œβ”€β”€ config/       # Database connection
β”‚       β”œβ”€β”€ controllers/  # Route handlers (13 controllers)
β”‚       β”œβ”€β”€ middleware/    # Auth, rate-limit, upload, error, site-check
β”‚       β”œβ”€β”€ models/       # Mongoose schemas (8 models)
β”‚       β”œβ”€β”€ routes/       # Express route definitions (12 routers)
β”‚       β”œβ”€β”€ scripts/      # DB init, seed, migration scripts
β”‚       β”œβ”€β”€ services/     # Business logic (email, storage, JWT, TOTP, audit)
β”‚       β”œβ”€β”€ types/        # TypeScript declarations
β”‚       β”œβ”€β”€ utils/        # Error classes, validators, async handler
β”‚       └── server.ts     # App entry point
β”‚
β”œβ”€β”€ frontend/             # Next.js 16 App Router
β”‚   β”œβ”€β”€ app/
β”‚   β”‚   β”œβ”€β”€ (auth)/       # Login, forgot-password, verify-totp
β”‚   β”‚   └── (dashboard)/  # Dashboard, policies, licenses, exports, admin, profile
β”‚   β”œβ”€β”€ components/
β”‚   β”‚   β”œβ”€β”€ admin/        # User & meta management tables
β”‚   β”‚   β”œβ”€β”€ dashboard/    # Metric cards, charts, calendar, notifications
β”‚   β”‚   β”œβ”€β”€ layout/       # Sidebar, Topbar, SiteStatusBanner
β”‚   β”‚   β”œβ”€β”€ licenses/     # License table, form, filters, email modal
β”‚   β”‚   β”œβ”€β”€ policies/     # Policy table, wizard, filters, email modal
β”‚   β”‚   └── ui/           # 18 reusable UI primitives
β”‚   └── lib/
β”‚       β”œβ”€β”€ api/          # Axios API client modules (12 modules)
β”‚       β”œβ”€β”€ context/      # Auth, Navigation, Privacy, PolicyForm contexts
β”‚       β”œβ”€β”€ hooks/        # Custom React hooks (analytics, auth, meta, etc.)
β”‚       β”œβ”€β”€ theme/        # Theming utilities
β”‚       β”œβ”€β”€ types/        # Frontend type definitions
β”‚       └── utils/        # Constants and helpers
β”‚
β”œβ”€β”€ tsconfig.base.json    # Shared TypeScript config
β”œβ”€β”€ .eslintrc.js          # Root ESLint config
└── .prettierrc           # Prettier config

πŸ› οΈ Tech Stack

Layer Technology
Frontend Next.js 16, React 19, TypeScript 5
Styling Tailwind CSS 3.4, Framer Motion
State React Context, SWR
Forms React Hook Form + Zod validation
Charts Recharts
UI Headless UI, Heroicons
Backend Express 5, TypeScript 5
Database MongoDB via Mongoose 8
Auth httpOnly cookie JWT sessions, refresh rotation, TOTP (Speakeasy), bcrypt
Storage AWS S3 / Cloudflare R2
Email Brevo, Resend, Nodemailer (SMTP)
Security Helmet, exact-origin CORS, rate limiting, field encryption, audit logs
Exports ExcelJS

πŸš€ Getting Started

Prerequisites

  • Node.js β‰₯ 18
  • MongoDB instance (local or Atlas)
  • npm or pnpm

1. Clone

git clone https://github.com/VortexDevX/AutoSecure.git
cd AutoSecure

2. Backend Setup

cd backend
npm install

Create backend/.env from backend/.env.example:

PORT=5000
NODE_ENV=development
FRONTEND_URL=http://localhost:3000
BACKEND_URL=http://localhost:5000
MONGODB_URI=mongodb://localhost:27017/autosecure
JWT_SECRET=your-access-secret
JWT_REFRESH_SECRET=your-refresh-secret
FIELD_ENCRYPTION_KEY=your-field-encryption-key
OWNER_EMAIL=owner@example.com
OWNER_PASSWORD=change-this-password

# Cloudflare R2
R2_ACCOUNT_ID=your-account-id
R2_ACCESS_KEY_ID=your-access-key
R2_SECRET_ACCESS_KEY=your-secret-key
R2_BUCKET_NAME=your-bucket
R2_PUBLIC_URL=https://your-r2-public-url

# Email
BREVO_API_KEY=your-brevo-key
SMTP_FROM_EMAIL=noreply@example.com
SMTP_FROM_NAME=AutoSecure
BACKUP_EMAIL=backup@example.com

# Company info used in templates/messages
COMPANY_PHONE=9999999999
COMPANY_EMAIL=office@example.com
COMPANY_ADDRESS=Your office address

Generate strong secrets:

node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"

Initialize database and seed:

npm run db:init
npm run db:seed
npm run db:seed-message-templates

Start dev server:

npm run dev

3. Frontend Setup

cd frontend
npm install

Create frontend/.env.local if the deployment needs an explicit API URL:

NEXT_PUBLIC_API_URL=http://localhost:5000/api/v1

Start dev server:

npm run dev

App runs at http://localhost:3000.


πŸ“‘ API Reference

Base URL: /api/v1

Module Endpoint Description
Auth POST /auth/login Login with email + password
POST /auth/verify-totp Verify 2FA code
POST /auth/forgot-password Request password reset
POST /auth/refresh Rotate refresh token and issue a new access cookie
GET /auth/me Current authenticated user and permissions
Policies GET /policies List policies (paginated, filterable)
POST /policies Create policy
PATCH /policies/:id Update policy
DELETE /policies/:id Delete policy
GET /policies/:id/message Render policy renewal message
Licenses GET /licenses List license records
POST /licenses Create license record
PATCH /licenses/:id Update license record
GET /licenses/:id/message Render license renewal message
Analytics GET /analytics/summary Dashboard metrics
GET /analytics/trends Monthly trends
GET /analytics/branch-performance Branch comparison
Users GET /users List users (admin)
POST /users Create user (admin)
Exports GET /exports/policies Export policies to XLSX
GET /exports/licenses Export licenses to XLSX
Files POST /files/upload Upload document to S3/R2
Emails POST /emails/send Send email from template
Settings GET /settings Get site settings
PATCH /settings Update site settings (owner)
Audit Logs GET /audit-logs View audit trail (admin)
Meta GET /meta Get dropdown/config options

Auth uses secure httpOnly cookies. Frontend requests must include credentials. Backend permissions remain source of truth.


πŸ”’ Security

Feature Implementation
Authentication Short-lived access cookie + rotated refresh cookie
2FA TOTP via Speakeasy (Google Authenticator compatible)
Password bcrypt hashing (cost factor 12)
Rate Limiting express-rate-limit on all API routes
Headers Helmet with CSP, HSTS, X-XSS-Protection
CORS Exact-origin allowlist via FRONTEND_URL
Input Validation express-validator + Zod schemas
File Upload Multer with type/size and magic-byte restrictions
PII Protection Sensitive fields encrypted with FIELD_ENCRYPTION_KEY; Aadhaar/PAN masked in view
Audit Trail Mutations, exports, permission changes, auth failures, and file access logged
Site Kill-Switch Owner can disable entire platform via settings
Password Reset OTP via email with expiry + attempt limits

Production Safety Notes

  • Never change FIELD_ENCRYPTION_KEY after encrypting production data unless you intentionally decrypt/re-encrypt with a migration.
  • Never deploy with localhost FRONTEND_URL / BACKEND_URL.
  • Keep MongoDB backups before every migration.
  • Run migration dry-run first and only proceed when the target database is correct.
  • Do not run seed scripts blindly on customized production data. db:seed-message-templates is usually safe for missing message templates; db:seed may refresh meta/default template data depending on script behavior.

🚒 Production Deployment

1. Backup Production Data

mongodump --uri="<MONGODB_URI>" --out="./backup-prod-before-deploy"

Also back up R2/S3 files if the bucket is business-critical.

2. Backend Verification

cd backend
npm ci
npm run build
npm audit
npm run db:migrate-security-schema:dry

If the dry-run points at the correct production database and the update counts are expected, run:

npm run db:migrate-security-schema
npm run db:migrate-security-schema:dry

The second dry-run should show usersUpdated: 0, policiesUpdated: 0, and licensesUpdated: 0.

Run message template seed only when needed:

npm run db:seed-message-templates

Avoid npm run db:seed on valuable production data unless you have confirmed the seed behavior is desired.

Start backend:

npm start

3. Frontend Verification

cd frontend
npm ci
npm run lint
npm run build
npm audit
npm start

4. Smoke Test Before Opening Access

  • Login + TOTP works.
  • Refreshing browser keeps session valid.
  • Owner can view /admin/users, /admin/templates, /admin/meta, and audit logs.
  • Normal user cannot open forbidden pages or hidden actions.
  • Policy/license view masks Aadhaar/PAN but shows address.
  • Policy/license edit exposes editable PII only to users with edit permission.
  • Export requires export permission and records audit details.
  • File view/download works for allowed users and fails for unauthorized users.
  • Send email and copy renewal message both work.

πŸ“œ Available Scripts

Backend (/backend)

Script Description
npm run dev Start dev server with hot reload (tsx watch)
npm run build Compile TypeScript to dist/
npm start Run production build
npm run db:init Initialize database collections
npm run db:seed Seed meta options and default templates
npm run db:seed-meta Seed only meta options
npm run db:seed-templates Seed email templates
npm run db:seed-message-templates Seed policy/license message templates
npm run db:migrate-security-schema:dry Preview security schema/PII migration without writes
npm run db:migrate-security-schema Apply security schema/PII migration
npm run test:email Test email service configuration

Frontend (/frontend)

Script Description
npm run dev Start Next.js dev server
npm run build Production build
npm start Serve production build
npm run lint Run ESLint

πŸ—ƒοΈ Data Models

Model Purpose
User Accounts with email, role (owner/admin/user), TOTP, active flag
Policy Insurance policies with full customer, vehicle, premium, payment data
LicenseRecord Driving license records with documents and financial tracking
AuditLog Immutable log of all system operations
EmailLog Record of sent emails
EmailTemplate Customizable email templates with variable placeholders
Meta Dynamic dropdown options (branches, insurance types, companies, cities)
SiteSettings Global platform configuration and kill-switch

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit changes (git commit -m 'Add amazing feature')
  4. Push to branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Built with ❀️ by VortexDevX

About

AutoSecure is a production-grade web application for automobile insurance field agents to manage policies, customers, and documents with robust authentication, role-based access control, and comprehensive audit logging.

Resources

Stars

Watchers

Forks

Contributors

Languages