Skip to content

Ktripathi2611/EventHub

Repository files navigation

⚡ EventHub — College Event Online Ticket Booking System

A modern, full-stack event marketplace built for college campuses. Students browse and book events; hosts create and manage them; admins moderate the platform.


📋 Table of Contents

  1. Project Overview
  2. Tools & Accounts Required
  3. Folder & File Structure
  4. Detailed Directory Breakdown
  5. Step-by-Step Website Creation
  6. How to Run Website on Computer
  7. How to Upload Code (GitHub)
  8. How to Deploy on Google (Hosting)
  9. Common Errors & Solutions
  10. Final Website Link
  11. Rebuild Checklist
  12. Database Schema
  13. API / Routes Reference
  14. Best Practices for Contributing

1. Project Overview

Item Details
Website Name EventHub — College Event Online Ticket Booking System
Purpose This website is made for college students and campus clubs to discover, browse, and book tickets for college events like hackathons, music festivals, art exhibitions, sports days, and more. Hosts can create and manage events with multiple ticket types, and admins can moderate the entire platform.
Who Will Use It Students (browse and book events), Event Hosts/Organizers (create and manage events), Administrators (moderate and manage the platform)

Key Features

  • 🎫 Browse and book tickets for college events
  • 🔍 Search events by name, category, price, and date
  • 👤 4 User Roles: Guest, Student, Host, Admin
  • 🎤 Host Dashboard — create events with multiple ticket types (Early Bird, General, VIP)
  • 📊 Analytics dashboard with revenue and booking stats
  • 📱 QR Code tickets generated on every booking
  • ⭐ Event reviews and ratings (1–5 stars)
  • 💬 Event discussion/Q&A section with threaded replies
  • 📋 Waitlist system for sold-out events
  • 📅 Google Calendar integration
  • 🛡️ Admin panel — manage users, verify hosts, approve/reject events
  • 🎨 Modern dark-themed UI with Stitch design system (no external animation libraries)

2. Tools & Accounts Required

Software You Must Install

Tool What It Does Download Link
VS Code Code editor to write and edit files https://code.visualstudio.com/
Node.js (v18 or higher) Runs the server-side JavaScript code https://nodejs.org/
MySQL (v8.0 or higher) Database to store users, events, bookings https://dev.mysql.com/downloads/
Google Chrome Web browser to view and test the website https://www.google.com/chrome/
Git (optional) Version control for uploading to GitHub https://git-scm.com/

Accounts You Need

Account Why You Need It
GitHub (optional) To upload and share your code online
Google Account For deploying the website to Google Cloud
MySQL root access To create the database on your computer

How to Check If Node.js Is Installed

Open Command Prompt (Windows) or Terminal (Mac) and type:

node --version

If you see a version number like v18.17.0, it is installed. If not, download and install it.

How to Check If MySQL Is Installed

mysql --version

3. Folder & File Structure

Complete Tree Diagram

College Event Online Ticket Booking System/
│
├── 📄 server.js                  ← Main entry point — starts Express server
├── 📄 package.json               ← NPM dependencies and scripts
├── 📄 package-lock.json          ← Locked dependency versions
├── 📄 .env                       ← Environment secrets (DB password, JWT key)
├── 📄 .gitignore                 ← Files excluded from Git
├── 📄 seed.js                    ← Legacy seed script (root level)
├── 📄 README.md                  ← This documentation file
│
├── 📁 config/                         [1 file]
│   └── 📄 database.js            ← MySQL connection pool configuration
│
├── 📁 controllers/                    [5 files]
│   ├── 📄 adminController.js     ← Admin dashboard, user/event management
│   ├── 📄 authController.js      ← Login, register, logout, profile
│   ├── 📄 bookingController.js   ← Booking flow, reviews, waitlist, discussions
│   ├── 📄 eventController.js     ← Homepage, event listing, event details
│   └── 📄 hostController.js      ← Host dashboard, event CRUD, analytics, scanner
│
├── 📁 db/                             [4 files]
│   ├── 📄 schema.sql             ← Full database schema (9 tables) with seed data
│   ├── 📄 migrate.js             ← Auto-migration script (runs on server start)
│   ├── 📄 migrate.sql            ← Manual SQL migration for existing databases
│   └── 📄 seed.js                ← Creates test users (admin, host, student)
│
├── 📁 middleware/                      [2 files]
│   ├── 📄 authMiddleware.js      ← isAuthenticated, isHost, isAdmin, hasRole
│   └── 📄 adminMiddleware.js     ← Admin-specific route protection
│
├── 📁 models/                         [8 files]
│   ├── 📄 userModel.js           ← User CRUD, host verification, block/unblock
│   ├── 📄 eventModel.js          ← Event CRUD, search, featured, trending
│   ├── 📄 bookingModel.js        ← Booking CRUD, revenue aggregation
│   ├── 📄 ticketTypeModel.js     ← Multi-ticket types per event (VIP, General, etc.)
│   ├── 📄 reviewModel.js         ← Star ratings and review comments
│   ├── 📄 waitlistModel.js       ← Waitlist for sold-out events
│   ├── 📄 discussionModel.js     ← Threaded event discussions/Q&A
│   └── 📄 notificationModel.js   ← User notification system
│
├── 📁 routes/                         [5 files]
│   ├── 📄 authRoutes.js          ← /login, /register, /logout, /profile
│   ├── 📄 eventRoutes.js         ← /, /events, /events/:id, /categories
│   ├── 📄 bookingRoutes.js       ← /book/:id, /my-bookings, /review, /discussion
│   ├── 📄 hostRoutes.js          ← /host/dashboard, /host/create-event, etc.
│   └── 📄 adminRoutes.js         ← /admin/dashboard, /admin/manage-users, etc.
│
├── 📁 utils/                          [3 files]
│   ├── 📄 qrGenerator.js         ← Generates QR code Data URLs for tickets
│   ├── 📄 emailService.js        ← Email notifications (dummy/console logger)
│   └── 📄 helpers.js             ← Calendar links, booking reference generator
│
├── 📁 public/                         [3 subdirs]
│   ├── 📁 css/
│   │   └── 📄 style.css          ← Complete Stitch design system (~1800 lines)
│   ├── 📁 js/
│   │   └── 📄 main.js            ← Frontend JS (IntersectionObserver, ticket logic)
│   └── 📁 uploads/               ← Uploaded event banner images (user content)
│
└── 📁 views/                          [12 files + 3 subdirs]
    ├── 📁 partials/                   [2 files]
    │   ├── 📄 header.ejs          ← <head>, navbar with role-based links
    │   └── 📄 footer.ejs          ← Footer, closing tags, <script> load
    ├── 📄 homepage.ejs            ← Landing page: hero, trending, categories, upcoming
    ├── 📄 events.ejs              ← Events listing with search bar and filters
    ├── 📄 eventDetails.ejs        ← Event page: booking, reviews, discussions, similar
    ├── 📄 login.ejs               ← Login form
    ├── 📄 register.ejs            ← Register with Student/Host role switcher
    ├── 📄 booking.ejs             ← Ticket booking with type selector + price calc
    ├── 📄 bookingSuccess.ejs      ← Booking confirmation with QR code display
    ├── 📄 myBookings.ejs          ← User's tickets (boarding-pass card style)
    ├── 📄 profile.ejs             ← Edit user profile with avatar upload
    ├── 📄 categories.ejs          ← Browse events by category
    ├── 📄 404.ejs                 ← Page not found
    ├── 📄 error.ejs               ← Generic error page
    ├── 📁 host/                       [7 files]
    │   ├── 📄 dashboard.ejs       ← Host stats, upcoming events, quick actions
    │   ├── 📄 createEvent.ejs     ← Create event form with ticket type builder
    │   ├── 📄 manageEvents.ejs    ← Table of host's events with edit/delete
    │   ├── 📄 editEvent.ejs       ← Edit event form (pre-filled)
    │   ├── 📄 bookings.ejs        ← Bookings table for host's events
    │   ├── 📄 analytics.ejs       ← Revenue stats + per-event breakdown table
    │   └── 📄 scanTicket.ejs      ← QR ticket verification (enter booking ref)
    └── 📁 admin/                      [8 files]
        ├── 📄 login.ejs           ← Admin login page
        ├── 📄 dashboard.ejs       ← Platform-wide stats + recent bookings
        ├── 📄 manageUsers.ejs     ← User table: block/unblock, verify hosts
        ├── 📄 manageEvents.ejs    ← Event table (legacy admin event management)
        ├── 📄 moderateEvents.ejs  ← Approve/reject pending events
        ├── 📄 bookings.ejs        ← All-platform bookings table
        ├── 📄 addEvent.ejs        ← Admin add event form (legacy)
        └── 📄 editEvent.ejs       ← Admin edit event form (legacy)

Total: 10 directories, 69 files (excluding node_modules/ and .git/)


4. Detailed Directory Breakdown

4.1 📁 config/ — Database Configuration

Property Details
Purpose Establishes and exports the MySQL connection pool
Files 1 file
Used By All models (models/*.js), migration (db/migrate.js), seed (db/seed.js)
Depends On .env file (for DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
File Size Description
database.js 404 B Creates a mysql2/promise connection pool with 10 max connections. Uses environment variables from .env. All database queries throughout the app use this shared pool.

Usage Notes:

  • Change database credentials in the .env file, NOT in this file
  • The pool automatically handles connection reuse and cleanup
  • If MySQL is not running, the server will crash on first database query

4.2 📁 controllers/ — Business Logic (MVC Controller Layer)

Property Details
Purpose Contains all request handlers — the "brain" that processes user actions
Files 5 files
Used By Route files (routes/*.js) map URLs to these controller functions
Depends On Models (models/*.js), utilities (utils/*.js), middleware
File Size Key Functions Description
authController.js ~108 lines showLogin, login, showRegister, register, logout, showProfile, updateProfile Handles all authentication: password hashing with bcrypt, session management, role-based registration (student vs host), profile updates with avatar upload
eventController.js ~104 lines homepage, listEvents, showEvent, showCategories Renders the homepage (featured, trending, categories, upcoming), event listings with multi-filter search, event detail pages with reviews/discussions/ticket types/calendar links
bookingController.js ~131 lines showBooking, processBooking, myBookings, addReview, joinWaitlist, addDiscussion Handles the full booking flow: ticket type selection, QR code generation, booking reference creation, plus reviews, waitlist, and discussions
hostController.js ~150 lines dashboard, createEvent, manageEvents, editEvent, deleteEvent, analytics, bookings, scanTicket Complete host module: stats dashboard, event CRUD with image upload, per-event analytics, booking list, and QR ticket verification
adminController.js ~120 lines dashboard, manageUsers, blockUser, unblockUser, verifyHost, moderateEvents, approveEvent, rejectEvent Platform administration: user management, host verification workflow, event moderation (approve/reject), platform-wide analytics

Dependency Flow:

routes/*.js  →  controllers/*.js  →  models/*.js  →  config/database.js  →  MySQL
                                  →  utils/*.js

4.3 📁 db/ — Database Scripts

Property Details
Purpose Database schema definition, auto-migration, manual migration, and seeding
Files 4 files
Used By server.js calls migrate.js on startup; seed.js is run manually
Depends On config/database.js
File Size Description
schema.sql ~276 lines Complete SQL schema for all 9 tables with CREATE TABLE, indexes, foreign keys, and seed data for categories, admin user, host user, and sample events. Use this for a fresh database setup.
migrate.js ~100 lines Auto-migration that runs on every server start. Checks INFORMATION_SCHEMA for missing columns, adds them with ALTER TABLE, creates new tables with CREATE TABLE IF NOT EXISTS, and seeds categories. Safe to run multiple times (idempotent).
migrate.sql ~100 lines Manual SQL migration script — same logic as migrate.js but in pure SQL. Run this directly in MySQL Workbench if you prefer manual migration.
seed.js ~50 lines Creates or updates 3 test users (admin, host, student) with bcrypt-hashed passwords. Also fixes the role ENUM to include 'host' if it was missing. Run with node db/seed.js.

Usage Notes:

  • For a brand new database: run schema.sql in MySQL, then node server.js
  • For an existing database: just run node server.js (auto-migration handles upgrades)
  • After first setup: always run node db/seed.js to get test login credentials

4.4 📁 middleware/ — Route Protection

Property Details
Purpose Protects routes by checking authentication and user roles
Files 2 files
Used By Route files (routes/*.js) use these as middleware before controller functions
Depends On req.session.user (set by authController.js on login)
File Size Key Functions Description
authMiddleware.js ~36 lines isAuthenticated, isHost, isAdmin, hasRole(role) Main auth guard. isAuthenticated checks if user is logged in and not blocked. isHost checks role === 'host'. isAdmin checks role === 'admin'. hasRole is a factory function for custom role checks.
adminMiddleware.js ~20 lines isAdmin Legacy admin middleware. Checks if user is an admin and redirects to admin login if not. Used by admin routes.

How Middleware Works (Flow):

User Request  →  Middleware Check  →  Pass? → Controller  →  Response
                                  →  Fail? → Redirect to Login

4.5 📁 models/ — Database Access Layer (MVC Model Layer)

Property Details
Purpose All MySQL queries are here — each model handles one database table
Files 8 files
Used By Controller files (controllers/*.js)
Depends On config/database.js (MySQL connection pool)
File Table Size Key Methods Description
userModel.js users ~61 lines findByEmail, create, findById, createHost, verifyHost, blockUser, unblockUser, countByRole, updateProfile, getHosts, getAll Full user lifecycle: registration, authentication lookup, host management, admin operations
eventModel.js events ~141 lines getAll, getById, create, update, delete, getFeatured, getTrending, search, getByHost, getUpcoming, updateStatus, getPending, getCategories Event CRUD plus specialized queries for homepage (featured, trending), host dashboard, admin moderation, and full-text search with filters
bookingModel.js bookings ~119 lines create, getByUser, getByEvent, getByHost, getById, getByRef, markAttended, hostRevenue, hostTicketsSold, getRecent, countAll Complete booking management with revenue aggregation, host-specific queries, and QR ticket verification
ticketTypeModel.js ticket_types ~59 lines create, getByEvent, getById, update, delete, incrementSold, isAvailable Multi-ticket type system: create different price tiers per event, track sold counts, validate availability
reviewModel.js reviews ~39 lines create, getByEvent, getAvgRating, hasReviewed, update One review per user per event (enforced by UNIQUE KEY). Calculates average ratings for event pages.
waitlistModel.js waitlist ~46 lines add, remove, isOnWaitlist, getPosition, getByEvent, count Manages waitlist for sold-out events. Tracks position and notification status.
discussionModel.js discussions ~48 lines create, getByEvent, getById, delete Threaded comments on event pages. Supports parent-child replies via parent_id. Joins with users table for display names and roles.
notificationModel.js notifications ~33 lines create, getByUser, getUnreadCount, markRead, markAllRead User notification inbox with read/unread tracking. Used for waitlist alerts, booking confirmations, and host notifications.

Important: All queries use parameterized statements (? placeholders) to prevent SQL injection.


4.6 📁 routes/ — URL Routing (MVC Router Layer)

Property Details
Purpose Maps URL paths to controller functions, applying middleware for protection
Files 5 files
Used By server.js mounts these with app.use()
Depends On Controllers (controllers/*.js), middleware (middleware/*.js)
File URL Prefix Key Routes Middleware Used
eventRoutes.js / GET / (homepage), GET /events (listing), GET /events/:id (details), GET /categories None (public)
authRoutes.js / GET/POST /login, GET/POST /register, GET /logout, GET/POST /profile isAuthenticated on profile
bookingRoutes.js / GET/POST /book/:id, GET /my-bookings, GET /booking-success/:id, POST /review/:id, POST /waitlist/:id, POST /discussion/:id isAuthenticated on all
hostRoutes.js /host GET /dashboard, GET/POST /create-event, GET /manage-events, GET/POST /edit-event/:id, POST /delete-event/:id, GET /bookings, GET /analytics, GET/POST /scan-ticket isAuthenticated + isHost on all
adminRoutes.js /admin GET /dashboard, GET /manage-users, POST /block-user/:id, POST /verify-host/:id, GET /moderate-events, POST /approve-event/:id, POST /reject-event/:id isAdmin on all

4.7 📁 utils/ — Utility Functions

Property Details
Purpose Reusable helper functions used across controllers
Files 3 files
Used By Controllers (controllers/bookingController.js, controllers/hostController.js)
Depends On qrcode npm package
File Size Exports Description
qrGenerator.js ~16 lines generateQR(text) Takes a booking reference string, returns a Data URL (base64 PNG image) of the QR code using the qrcode npm library. Used when processing bookings.
emailService.js ~26 lines sendBookingConfirmation(), sendWelcome(), sendReminder(), sendHostNotification() Currently a dummy — all functions log to console instead of sending real emails. Replace with Nodemailer when SMTP credentials are available.
helpers.js ~28 lines generateCalendarLink(event), generateBookingRef() generateCalendarLink builds a Google Calendar URL from event details. generateBookingRef creates unique booking references like EVT-A3F7K2M9.

4.8 📁 public/ — Static Assets (Served to Browser)

Property Details
Purpose Files served directly to the browser — CSS, JavaScript, and uploaded images
Subdirectories 3: css/, js/, uploads/
Used By All EJS view templates reference these via <link> and <script> tags
Depends On Nothing (these are the final browser-facing files)

📁 public/css/

File Size Description
style.css ~1800 lines Complete Stitch-inspired design system. Contains: CSS custom properties (design tokens for colors, spacing, typography, shadows, radii), base/reset styles, component styles (navbar, hero, cards, forms, tables, buttons, badges, modals, alerts), page-specific layouts (auth, event detail, booking success, host dashboard, admin panel), CSS keyframe animations (fadeInUp, slideIn, float, pulse-glow), .reveal class for IntersectionObserver scroll animations, responsive breakpoints for mobile/tablet. No GSAP, AOS, or Lenis.

📁 public/js/

File Size Description
main.js ~200 lines Frontend JavaScript. Handles: page loader dismiss, IntersectionObserver for .reveal scroll animations (replaces GSAP/AOS), navbar background on scroll, mobile hamburger menu toggle, ticket type selection UI with price calculation, dynamic ticket type row builder for event creation form, host role toggle on registration page.

📁 public/uploads/

Contents Description
(empty or user-uploaded images) Event banner images uploaded through the host event creation form. Files are named with timestamps to avoid conflicts (e.g., 1773091234567-123456789.jpg). Served at /uploads/filename.jpg.

4.9 📁 views/ — EJS Templates (MVC View Layer)

Property Details
Purpose HTML templates rendered with dynamic data from controllers
Files 12 files + 3 subdirectories (17 more files) = 29 total
Used By Controllers call res.render('viewName', { data })
Depends On public/css/style.css (styles), public/js/main.js (interactions)

📁 views/partials/ — Shared Components (included in every page)

File Size Description
header.ejs ~1.1 KB <!DOCTYPE html>, <head> with Google Fonts + CSS link, page loader div, navbar with role-based navigation (shows different links for guest/user/host/admin). Included at the top of every page with <%- include('partials/header') %>.
footer.ejs ~1.0 KB Footer with 4 columns (brand, quick links, host links, contact), copyright bar, <script> tag for main.js. Closes </main></body></html>.

📁 views/ (root) — Public Pages

File Size Page URL Description
homepage.ejs 5.2 KB / Hero section with gradient text + stats, trending events (horizontal scroll), category grid, upcoming events grid, CTA buttons
events.ejs 3.6 KB /events Search bar, category/price/sort filter dropdowns (auto-submit), event card grid, empty state for no results
eventDetails.ejs 11.6 KB /events/:id Largest view. Event banner, description, organizer card, calendar add button, reviews section with star form, threaded discussions with reply forms, similar events grid. Sidebar: ticket type selector, quantity input, price calculator, book button, waitlist for sold-out events
login.ejs 1.1 KB /login Email + password form, error/success alerts, link to register
register.ejs 1.9 KB /register Student/Host role switcher (radio buttons), name + email + password + confirm password fields, org name field (shown for hosts only)
booking.ejs 3.4 KB /book/:id Event preview card, ticket type radio selector, quantity input, live price calculation, confirm booking button
bookingSuccess.ejs 2.3 KB /booking-success/:id Green checkmark, booking details (ref, event, date, venue, tickets, total), QR code image display, links to my tickets and explore more
myBookings.ejs 2.2 KB /my-bookings Boarding-pass style ticket cards with date badge, event name, venue, ticket count, type badge, status badge, booking ref, and total price
profile.ejs 2.0 KB /profile Sidebar with avatar + role badge, edit form with name, bio, phone, avatar upload
categories.ejs 683 B /categories Grid of category cards with emoji icons, links to filtered event listing
404.ejs 505 B (any invalid URL) "Page Not Found" with link to homepage
error.ejs 552 B (on server error) Displays error message with link to homepage

📁 views/host/ — Host Dashboard Pages

File Size Page URL Description
dashboard.ejs 2.9 KB /host/dashboard 4-stat grid (events, tickets sold, revenue, upcoming), quick action buttons, upcoming events with status badges
createEvent.ejs 4.1 KB /host/create-event Two-section form: basic details (name, description, date, venue, category, image, price, seats) + dynamic ticket type builder with add/remove rows
manageEvents.ejs 1.6 KB /host/manage-events Data table: event name, date, seats available/total, status badge, edit + delete buttons
editEvent.ejs 3.1 KB /host/edit-event/:id Pre-filled form with existing event data, category dropdown, image re-upload
bookings.ejs 1.3 KB /host/bookings Data table: booking ref, user, event, ticket type, quantity, total, status, date
analytics.ejs 1.6 KB /host/analytics 4-stat grid (revenue, tickets, events, avg per event), per-event breakdown table
scanTicket.ejs 1.8 KB /host/scan-ticket Large booking ref input, verify button, success/error result with attendee details

📁 views/admin/ — Admin Panel Pages

File Size Page URL Description
login.ejs 736 B /admin/login Simple email + password form for admin
dashboard.ejs 2.5 KB /admin/dashboard 6-stat grid (users, hosts, events, revenue, bookings, pending), quick links, recent bookings table
manageUsers.ejs 1.8 KB /admin/manage-users Data table: name, email, role badge, verified status, blocked status, joined date, action buttons (verify host, block, unblock)
moderateEvents.ejs 2.3 KB /admin/moderate-events Two tables: pending events (approve/reject buttons) and all approved events (delete button)
bookings.ejs 904 B /admin/bookings All-platform bookings data table
manageEvents.ejs 2.3 KB /admin/manage-events Legacy admin event management table
addEvent.ejs 3.2 KB /admin/add-event Legacy admin add event form
editEvent.ejs 4.0 KB /admin/edit-event/:id Legacy admin edit event form

4.10 Root Files

File Size Description
server.js 2.8 KB Application entry point. Configures Express, EJS view engine, sessions, multer file uploads, mounts all route groups, runs auto-migration on startup, starts HTTP server on port 3000.
package.json 639 B NPM project metadata. Lists 10 dependencies: express, ejs, mysql2, express-session, bcryptjs, dotenv, multer, jsonwebtoken, qrcode, uuid. Scripts: start, dev, seed.
.env 247 B Environment variables: PORT, DB_HOST, DB_USER, DB_PASSWORD, DB_NAME, JWT_SECRET, SESSION_SECRET. Never commit this file to Git.
.gitignore 38 B Excludes node_modules/ and .env from Git tracking.
seed.js 1.3 KB Legacy root-level seed script (the updated one is in db/seed.js).

5. Step-by-Step Website Creation

Step 1: Create the Project Folder

  1. Open your computer's file explorer
  2. Go to where you want to save the project (e.g., D:\code here\side project\)
  3. Right-click → New Folder
  4. Name it: College Event Online Ticket Booking System

Step 2: Open Project in VS Code

  1. Open VS Code
  2. Click File → Open Folder
  3. Select the project folder
  4. VS Code will open with this folder as your workspace

Step 3: Initialize Node.js Project

Open the Terminal in VS Code (press Ctrl + `) and type:

npm init -y

This creates a package.json file.

Step 4: Install Required Packages

npm install express ejs mysql2 express-session bcryptjs dotenv multer jsonwebtoken qrcode uuid

What each package does:

Package Purpose
express Web server framework
ejs Template engine (renders HTML with data)
mysql2 Connects to MySQL database
express-session Manages user login sessions
bcryptjs Hashes passwords securely
dotenv Loads secret keys from .env file
multer Handles file uploads (event images)
jsonwebtoken JSON Web Token for authentication
qrcode Generates QR code images for tickets
uuid Generates unique IDs

Step 5: Create the .env File

Create a file called .env in the project root with:

# Server Config
PORT=3000

# MySQL Database
DB_HOST=localhost
DB_USER=root
DB_PASSWORD=YOUR_MYSQL_PASSWORD_HERE
DB_NAME=college_events

# JWT
JWT_SECRET=college_events_jwt_secret_key_2024

# Session
SESSION_SECRET=college_events_session_secret_key_2024

⚠️ IMPORTANT: Replace YOUR_MYSQL_PASSWORD_HERE with your actual MySQL root password.

Step 6: Create the MySQL Database

Open MySQL Workbench or MySQL Command Line and run:

CREATE DATABASE IF NOT EXISTS college_events;

The server will automatically create all tables when you start it (auto-migration).

Step 7: Create the Folder Structure

Create these folders inside your project:

config/
controllers/
db/
middleware/
models/
routes/
utils/
public/css/
public/js/
public/uploads/
views/partials/
views/host/
views/admin/

Step 8: Create All Source Files

Copy the source code for each file into the correct location. Follow the file structure shown in Section 3. The key files to create in order:

  1. config/database.js → Database connection
  2. middleware/authMiddleware.js → Route protection
  3. models/*.js → All 8 model files (database queries)
  4. utils/*.js → All 3 utility files
  5. controllers/*.js → All 5 controller files
  6. routes/*.js → All 5 route files
  7. views/partials/header.ejs + footer.ejs → Shared layout
  8. views/*.ejs → All public page templates
  9. views/host/*.ejs → All 7 host page templates
  10. views/admin/*.ejs → All admin page templates
  11. public/css/style.css → Complete design system
  12. public/js/main.js → Frontend JavaScript
  13. db/migrate.js → Auto-migration script
  14. db/seed.js → Test user seeder
  15. server.js → Main application entry point

6. How to Run Website on Computer

Step-by-Step Instructions

Step 1: Open VS Code and open the project folder

Step 2: Open Terminal (press Ctrl + `)

Step 3: Ensure the MySQL database exists:

mysql -u root -p -e "CREATE DATABASE IF NOT EXISTS college_events;"

Step 4: Install packages (only needed once):

npm install

Step 5: Seed test users (only needed once):

node db/seed.js

Expected output:

🌱 Fixing role enum and seeding users...
  ✅ Role enum updated: user/host/admin
  ✅ Admin: admin@college.com / admin123
  ✅ Host: host@college.com / admin123
  ✅ Student: student@college.com / admin123
🌱 Seeding complete!

Step 6: Start the server:

node server.js

Expected output:

🔄 Running database migrations...
  ✅ Added users.bio
  ✅ Added events.status
  ... (more columns if first run)
✅ Migrations complete!
🚀 Server running on http://localhost:3000

Step 7: Open your browser:

http://localhost:3000

🎉 Your website is now running!

Test Accounts

Role Email Password What You Can Do
Admin admin@college.com admin123 Manage users, moderate events, platform analytics
Host host@college.com admin123 Create events, manage bookings, scan tickets
Student student@college.com admin123 Browse events, book tickets, write reviews

7. How to Upload Code (GitHub)

Step-by-Step GitHub Upload

Step 1: Go to https://github.com and sign in

Step 2: Click "+""New repository"

Step 3: Fill in:

  • Repository name: EventHub
  • Description: College Event Online Ticket Booking System
  • Choose Public or Private
  • Click "Create repository"

Step 4: Make sure your .gitignore contains:

node_modules/
.env
public/uploads/*
!public/uploads/.gitkeep

Step 5: Run in terminal:

git init
git add .
git commit -m "Initial commit - EventHub Platform"
git branch -M main
git remote add origin https://github.com/YOUR_USERNAME/EventHub.git
git push -u origin main

Replace YOUR_USERNAME with your GitHub username.

Step 6: Refresh your GitHub page — all files should be visible!

GitHub Repository: https://github.com/Ktripathi2611/EventHub


8. How to Deploy on Google (Hosting)

Option: Google Cloud Run (Recommended for Node.js Apps)

Google Cloud Run runs your Node.js server in the cloud.

Step 1: Go to https://console.cloud.google.com → sign in

Step 2: Create a new project → name: eventhub-platform

Step 3: Install Google Cloud CLI: https://cloud.google.com/sdk/docs/install

Step 4: Create a Dockerfile in project root:

FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
EXPOSE 3000
CMD ["node", "server.js"]

Step 5: Create a .dockerignore file:

node_modules
.git
.env
public/uploads/*

Step 6: Deploy:

gcloud auth login
gcloud config set project eventhub-platform
gcloud run deploy eventhub --source . --region=us-central1 --allow-unauthenticated

What each command does:

Command Purpose
gcloud auth login Signs you into your Google account
gcloud config set project Selects which Google Cloud project to use
gcloud run deploy Builds and deploys your app to the cloud

Step 7: Google will provide a URL like https://eventhub-xxxxx.run.app

⚠️ Note: For production, you also need a cloud MySQL database (Google Cloud SQL, PlanetScale, or Railway).


9. Common Errors & Solutions

# Error What It Means How to Fix
1 Cannot find module 'express' Packages not installed Run npm install
2 ECONNREFUSED 127.0.0.1:3306 MySQL is not running Start your MySQL service
3 Unknown database 'college_events' Database not created Run CREATE DATABASE college_events; in MySQL
4 Unknown column 'status' in where clause Old database schema Restart server — auto-migration fixes it
5 ER_ACCESS_DENIED_ERROR Wrong MySQL password Fix DB_PASSWORD in .env
6 Port 3000 already in use Another app using port Close that app or change PORT=3001 in .env
7 Cannot GET /host/dashboard Not logged in as host Login with host@college.com first
8 Data truncated for column 'role' Role ENUM missing 'host' Run node db/seed.js (fixes the enum)
9 Error: Only image files allowed Wrong file type uploaded Use JPG, PNG, GIF, or WebP only
10 Login not working Users not seeded Run node db/seed.js
11 Blank page / no events No events in database Login as host → create events, or import schema.sql
12 "Something went wrong" page Server error Check terminal for the error stack trace

10. Final Website Link

Item Details
Local URL http://localhost:3000
Live URL (Add your deployed URL here)
GitHub Repo https://github.com/Ktripathi2611/EventHub
Date Created March 2026

11. Rebuild Checklist

✅ Step 1:  Install Node.js (v18+) and MySQL (v8+)
✅ Step 2:  Clone or copy the project folder
✅ Step 3:  Open project in VS Code
✅ Step 4:  Create .env file with your MySQL password
✅ Step 5:  Create MySQL database:  CREATE DATABASE college_events;
✅ Step 6:  Run:  npm install
✅ Step 7:  Run:  node db/seed.js   (creates test users)
✅ Step 8:  Run:  node server.js    (starts server + auto-migrates)
✅ Step 9:  Open browser → http://localhost:3000
✅ Step 10: Login with admin@college.com / admin123

12. Database Schema

9 Tables

Table Columns Purpose
users id, name, email, password, role, bio, avatar, phone, blocked, host_verified, host_org_name, created_at User accounts with 3 roles
events id, host_id, event_name, description, event_date, end_date, venue, ticket_price, total_seats, available_seats, image, category, status, featured, location_lat, location_lng, max_tickets_per_user, created_at Events with host ownership and moderation
bookings id, booking_ref, user_id, event_id, ticket_type_id, tickets, total_price, qr_code, status, booking_date Ticket bookings with QR codes
ticket_types id, event_id, name, price, quantity, sold, sale_start, sale_end, description, created_at Multiple ticket tiers per event
categories id, name, icon, color, created_at Event categories (Technology, Music, etc.)
reviews id, user_id, event_id, rating, comment, created_at 1–5 star ratings with comments
waitlist id, user_id, event_id, status, created_at Waitlist for sold-out events
notifications id, user_id, type, title, message, link, is_read, created_at User notification inbox
discussions id, event_id, user_id, parent_id, message, created_at Threaded event Q&A

Entity Relationships

Entity Relationship Diagram (ERD)

erDiagram
    USERS ||--o{ EVENTS : "host creates"
    USERS ||--o{ BOOKINGS : "student books"
    USERS ||--o{ REVIEWS : "user reviews"
    USERS ||--o{ DISCUSSIONS : "user posts"
    USERS ||--o{ NOTIFICATIONS : "receives"
    
    EVENTS ||--|{ TICKET_TYPES : "has tiers"
    EVENTS ||--o{ BOOKINGS : "receives"
    EVENTS ||--o{ REVIEWS : "receives"
    EVENTS ||--o{ WAITLIST : "has entries"
    EVENTS ||--o{ DISCUSSIONS : "has topics"
    
    TICKET_TYPES ||--o{ BOOKINGS : "selected in"
    BOOKINGS ||--|| PAYMENTS : "simulated"
Loading

13. API / Routes Reference

Public Routes (No Login Required)

Method URL Description
GET / Homepage
GET /events Events listing with search & filters
GET /events/:id Event details page
GET /categories Browse by category
GET /login Login page
GET /register Registration page
POST /login Process login
POST /register Process registration
GET /logout Destroy session

User Routes (Login Required)

Method URL Description
GET /book/:eventId Booking page
POST /book/:eventId Process ticket booking
GET /booking-success/:id Booking confirmation + QR
GET /my-bookings User's booked tickets
GET /profile Profile page
POST /profile Update profile
POST /review/:eventId Submit event review
POST /discussion/:eventId Post discussion comment
POST /waitlist/:eventId Join event waitlist

Host Routes (Host Role Only)

Method URL Description
GET /host/dashboard Host dashboard with stats
GET /host/create-event Create event form
POST /host/create-event Submit new event
GET /host/manage-events List host's events
GET /host/edit-event/:id Edit event form
POST /host/edit-event/:id Update event
POST /host/delete-event/:id Delete event
GET /host/bookings Bookings for host's events
GET /host/analytics Revenue analytics
GET /host/scan-ticket QR ticket scanner page
POST /host/scan-ticket Verify ticket by ref

Admin Routes (Admin Role Only)

Method URL Description
GET /admin/dashboard Platform-wide stats
GET /admin/manage-users User management table
POST /admin/block-user/:id Block a user
POST /admin/unblock-user/:id Unblock a user
POST /admin/verify-host/:id Verify host account
GET /admin/moderate-events Event moderation
POST /admin/approve-event/:id Approve pending event
POST /admin/reject-event/:id Reject pending event
GET /admin/bookings All platform bookings

14. Best Practices for Contributing

Code Style

  1. Follow MVC pattern — Models in models/, controllers in controllers/, views in views/
  2. Use prepared statements — All SQL queries use ? placeholders (prevents SQL injection)
  3. Keep CSS in design system — Add new styles to public/css/style.css using the existing design tokens
  4. No external animation libraries — Use CSS transitions and IntersectionObserver only
  5. Use async/await — All database operations use promises, never callbacks

Adding a New Feature

  1. Create the model in models/ (database queries)
  2. Create or extend a controller in controllers/ (business logic)
  3. Add routes in routes/ (URL mapping)
  4. Create EJS views in views/ (HTML templates)
  5. Add styles to public/css/style.css (use existing design tokens)
  6. Add migration in db/migrate.js if new columns/tables needed
  7. Test by restarting: node server.js

Environment Setup

Requirement Minimum Version
Node.js v18.0.0
MySQL v8.0
npm v9.0

File Naming Conventions

Type Convention Example
Models camelCase + Model userModel.js
Controllers camelCase + Controller authController.js
Routes camelCase + Routes hostRoutes.js
Views camelCase eventDetails.ejs
CSS/JS lowercase style.css, main.js

Tech Stack Summary

Layer Technology
Backend Node.js + Express.js
Database MySQL (9 tables)
Frontend EJS Templates + HTML5 + CSS3 + JavaScript
Auth bcrypt password hashing + express-session
File Upload Multer (images only, 5MB limit)
QR Codes qrcode npm package
Design Stitch-inspired design system (CSS custom properties)
Animations CSS transitions + IntersectionObserver API
Fonts Sora (headings) + Inter (body) from Google Fonts

Built with ❤️ for campus life. © 2026 EventHub.

About

A modern, dark-themed website where students can browse college events and book tickets online. Built using Node.js, Express.js, MySQL, and EJS.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors