Skip to content

ggmask/zflex

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

ZFlex - Modern Social Media Platform 🚀

A full-featured, modern social media web application built with Node.js, Express, and MySQL

Node.js Express MySQL Socket.io


✨ Features

👥 User Management

  • Secure Authentication: JWT-based authentication with password hashing (bcrypt)
  • User Profiles: Customizable profiles with avatar, cover photo, bio, location, and website
  • Privacy Controls: Public/private account options with granular privacy settings
  • User Verification: Blue checkmark system for verified users
  • Online Status: Real-time online/offline status with privacy controls

📱 Social Features

  • Posts: Create text posts with support for images and videos
  • Interactions: Like, comment, and share posts
  • Nested Comments: Threaded comment system with replies
  • Hashtags: Automatic hashtag extraction and trending hashtags
  • Mentions: Tag users with @mentions and get notified
  • Follow System: Follow/unfollow users to curate your personalized feed

💬 Real-Time Communication

  • Direct Messaging: One-on-one chat with Socket.io
  • Typing Indicators: See when someone is typing in real-time
  • Online Status: Real-time user presence tracking
  • Notifications: Instant notifications for likes, comments, follows, and mentions
  • Unread Counts: Track unread messages and notifications

🔍 Discovery & Search

  • Feed: Personalized feed based on who you follow
  • Explore Page: Discover trending posts and popular content
  • User Search: Find users by username or full name
  • Post Search: Search posts by content
  • Hashtag Search: Browse posts by hashtags
  • Trending: See what's popular with trending hashtags
  • Suggestions: Get personalized user recommendations

🎨 User Experience

  • Dark Mode: Toggle between light and dark themes
  • Responsive Design: Works seamlessly on mobile, tablet, and desktop
  • PWA Support: Install as a progressive web app
  • Infinite Scroll: Smooth content loading
  • Modern UI: Clean design with gradient accents

🛡️ Admin Dashboard

  • Statistics: View total users, posts, comments, likes, and activity metrics
  • User Management: View all users, delete users, toggle verification status
  • Content Moderation: View and delete posts
  • Reports: Handle user reports and complaints
  • Activity Tracking: Monitor active users and recent registrations

🔒 Security Features

  • Password Security: Minimum 8 characters with complexity requirements (uppercase, lowercase, number)
  • File Upload Security: Magic byte validation for uploaded files
  • CSRF Protection: Double-submit cookie pattern for CSRF protection
  • Input Validation: Comprehensive input validation and sanitization
  • SQL Injection Protection: Parameterized queries throughout
  • XSS Prevention: Content sanitization with DOMPurify
  • Rate Limiting: API rate limiting to prevent abuse
  • JWT Authentication: Secure token-based authentication
  • File Access Control: Granular access control for uploaded files
  • Socket.io Authentication: JWT authentication for real-time connections

🚀 Quick Start

Prerequisites

  • Node.js (v18 or higher)
  • XAMPP (for MySQL)
  • npm (comes with Node.js)

Installation

  1. Clone or download the project

    cd C:\Users\USER\Desktop\ZFlex
  2. Install dependencies

    npm install
  3. Set up environment variables

    • Copy env example.md to .env
    • Update database credentials if needed (default works with XAMPP)
  4. Set up database

    • Start XAMPP (Apache + MySQL)
    • Open phpMyAdmin: http://localhost/phpmyadmin
    • Create database: zflex
    • Import database/schema.sql
    • (Optional) Import database/sample_users_fresh.sql for test users
    • (Optional) Import database/sample_posts.sql for sample posts
  5. Start the server

    npm start

    Or for development with auto-restart:

    npm run dev
  6. Open your browser

    http://localhost:3000
    

🏗️ Tech Stack

Frontend

  • HTML5 - Semantic markup
  • CSS3 - Modern styling with gradients and animations
  • Vanilla JavaScript - No frameworks, pure JS
  • Font Awesome 6.4 - Icon library
  • Socket.io Client - Real-time communication

Backend

  • Node.js - JavaScript runtime
  • Express.js - Web framework
  • MySQL2 - Database driver with connection pooling
  • Socket.io - WebSocket library for real-time features
  • bcrypt - Password hashing (10 salt rounds)
  • jsonwebtoken - JWT authentication tokens
  • multer - File upload handling
  • express-validator - Input validation
  • file-type - Magic byte validation for file uploads
  • dompurify - XSS prevention
  • csrf - CSRF protection
  • cookie-parser - Cookie parsing
  • express-rate-limit - API rate limiting
  • winston - Logging
  • morgan - HTTP request logging

Database

  • MySQL - Relational database
  • Optimized Indexes - Fast queries
  • Foreign Keys - Data integrity
  • Cascading Deletes - Clean data management
  • Triggers - Automatic hashtag count updates

📁 Project Structure

ZFlex/
├── config/
│   ├── database.js          # Database connection pool
│   ├── env-validator.js     # Environment variable validation
│   └── logger.js            # Winston logging configuration
├── database/
│   ├── schema.sql           # Database schema (run this first)
│   ├── sample_users_fresh.sql  # Sample users with secure passwords
│   └── sample_posts.sql     # Sample text-only posts
├── middleware/
│   ├── auth.js              # JWT authentication middleware
│   ├── csrf.js              # CSRF protection middleware
│   ├── optionalAuth.js      # Optional authentication
│   ├── security.js          # Security headers, rate limiting, input sanitization
│   └── upload.js            # File upload with magic byte validation
├── routes/
│   ├── admin.js             # Admin dashboard routes
│   ├── auth.js              # Authentication routes (register, login, verify)
│   ├── comments.js          # Comment system routes
│   ├── follow.js            # Follow/unfollow routes
│   ├── hashtags.js          # Hashtag routes
│   ├── likes.js             # Like/unlike routes
│   ├── messages.js          # Direct messaging routes
│   ├── notifications.js     # Notification routes
│   ├── posts.js             # Post CRUD routes
│   └── users.js             # User management routes
├── scripts/
│   ├── generate-hash.js     # Generate bcrypt password hash
│   ├── generate-sample-passwords.js  # Generate sample user passwords
│   └── reconcile-hashtags.js  # Hashtag reconciliation utility
├── public/
│   ├── components/          # Reusable HTML components
│   ├── css/                 # Stylesheets
│   ├── images/              # Default images
│   ├── js/                  # Frontend JavaScript
│   └── *.html               # HTML pages
├── uploads/                 # User-uploaded files
│   ├── covers/              # Cover photos
│   ├── messages/            # Message attachments
│   ├── posts/               # Post media
│   └── profiles/            # Profile pictures
├── logs/                    # Application logs
├── server.js                # Main server file
├── package.json             # Dependencies and scripts
└── README.md                # This file

🔌 API Endpoints

Authentication

  • POST /api/auth/register - Register new user (Rate limited: 3/hour)
  • POST /api/auth/login - Login user (Rate limited: 5/15min)
  • GET /api/auth/verify - Verify JWT token

Users

  • GET /api/users/:id - Get user profile
  • PUT /api/users/profile - Update profile
  • POST /api/users/profile-picture - Upload profile picture
  • POST /api/users/cover-photo - Upload cover photo
  • GET /api/users/search/:query - Search users
  • GET /api/users/suggestions/follow - Get follow suggestions
  • GET /api/users/:id/followers - Get user's followers
  • GET /api/users/:id/following - Get user's following
  • POST /api/users/change-email - Change email
  • POST /api/users/change-password - Change password
  • GET /api/users/status/:userId - Get online status
  • POST /api/users/status/bulk - Get bulk online status

Posts

  • GET /api/posts/feed - Get personalized feed
  • GET /api/posts/explore - Get explore posts
  • GET /api/posts/:id - Get single post
  • GET /api/posts/user/:userId - Get user's posts
  • GET /api/posts/search/:query - Search posts
  • GET /api/posts/hashtag/:tag - Get posts by hashtag
  • GET /api/posts/trending/hashtags - Get trending hashtags
  • POST /api/posts - Create new post (max 5000 chars, supports images/videos)
  • PUT /api/posts/:id - Update post
  • DELETE /api/posts/:id - Delete post

Comments

  • GET /api/comments/post/:postId - Get post comments (nested)
  • POST /api/comments - Add comment (max 1000 chars)
  • PUT /api/comments/:id - Update comment
  • DELETE /api/comments/:id - Delete comment

Likes

  • POST /api/likes/post/:postId - Toggle post like
  • POST /api/likes/comment/:commentId - Toggle comment like
  • GET /api/likes/post/:postId/users - Get users who liked post

Follow

  • POST /api/follow/:userId - Follow/unfollow user
  • GET /api/follow/check/:userId - Check follow status

Messages

  • GET /api/messages/conversations - Get conversations list
  • GET /api/messages/:userId - Get messages with user
  • POST /api/messages - Send message (supports file attachments)
  • PUT /api/messages/:messageId/read - Mark message as read
  • GET /api/messages/unread/count - Get unread count
  • DELETE /api/messages/clear/:userId - Clear chat
  • POST /api/messages/block/:userId - Block/unblock user
  • GET /api/messages/block/:userId - Check block status

Notifications

  • GET /api/notifications - Get notifications (limit 50)
  • GET /api/notifications/unread/count - Get unread count
  • PUT /api/notifications/:id/read - Mark as read
  • PUT /api/notifications/read/all - Mark all as read
  • DELETE /api/notifications/:id - Delete notification

Hashtags

  • GET /api/hashtags/trending - Get trending hashtags
  • GET /api/hashtags/:tag - Get hashtag details
  • GET /api/hashtags/search/:query - Search hashtags

Admin (requires admin role)

  • GET /api/admin/stats - Get statistics
  • GET /api/admin/users - Get all users (paginated)
  • GET /api/admin/posts - Get all posts (paginated)
  • DELETE /api/admin/users/:id - Delete user
  • DELETE /api/admin/posts/:id - Delete post
  • PUT /api/admin/users/:id/verify - Toggle verification
  • GET /api/admin/reports - Get reports
  • PUT /api/admin/reports/:id - Update report status

🔐 Security Features

Authentication & Authorization

  • JWT token-based authentication
  • Password hashing with bcrypt (10 salt rounds)
  • Password requirements: 8+ chars, uppercase, lowercase, number
  • Admin role verification
  • Socket.io authentication for real-time connections

Input Validation & Sanitization

  • Express-validator for input validation
  • DOMPurify for XSS prevention
  • SQL injection protection via parameterized queries
  • File upload validation (magic bytes, not just extensions)

File Security

  • Magic byte validation for uploaded files
  • File type restrictions (images: JPEG, PNG, GIF, WebP; videos: MP4, MOV, AVI)
  • File size limits (50MB max)
  • Filename sanitization
  • Granular file access control

Rate Limiting

  • Login: 5 attempts per 15 minutes
  • Registration: 3 attempts per hour
  • API: 200 requests per minute
  • Upload: 10 uploads per 15 minutes

CSRF Protection

  • Double-submit cookie pattern
  • CSRF tokens for state-changing requests
  • httpOnly cookies with SameSite attribute

Security Headers

  • X-Content-Type-Options: nosniff
  • X-Frame-Options: DENY
  • X-XSS-Protection: 1; mode=block
  • Strict-Transport-Security
  • X-Powered-By header removed

Error Handling

  • No stack traces in production
  • Generic error messages for users
  • Detailed logging server-side only

🎨 Design

ZFlex uses a modern gradient color scheme:

  • Primary Gradient: #7A00FF#FF5AD9
  • Background: #FAFAFA (light) / #0F0F0F (dark)
  • Text: #1A1A1A (light) / #FFFFFF (dark)

The design features:

  • Rounded corners and soft shadows
  • Smooth transitions and animations
  • Gradient buttons and accents
  • Clean, minimal interface
  • Responsive mobile-first design

📱 Responsive Design

  • Mobile (< 768px): Single column, vertical scroll, mobile navigation
  • Tablet (768px - 1200px): Two columns, optimized layout
  • Desktop (> 1200px): Three columns with sidebars, full feature set

🌐 Browser Support

  • Chrome (recommended)
  • Firefox
  • Safari
  • Edge
  • Opera

🧪 Testing with Sample Data

After setting up the database, you can import sample data:

  1. Sample Users (15 users including 1 admin):

    • Admin: admin@zflex.com / Admin123!
    • Regular users: Any email from the list / User123!
    • See database/sample_users_fresh.sql for all credentials
  2. Sample Posts (23 text-only posts):

    • Import database/sample_posts.sql for sample content

🛠️ Development

Run in development mode (auto-restart):

npm run dev

Generate password hash:

node scripts/generate-hash.js yourpassword

Generate sample user passwords:

node scripts/generate-sample-passwords.js

Reconcile hashtags:

node scripts/reconcile-hashtags.js

📝 Environment Variables

Create a .env file in the root directory:

PORT=3000
DB_HOST=localhost
DB_USER=root
DB_PASSWORD=
DB_NAME=zflex
JWT_SECRET=your-secret-key-here-minimum-32-characters
JWT_EXPIRE=7d
NODE_ENV=development
ALLOWED_ORIGINS=https://yourdomain.com,https://www.yourdomain.com
CSRF_SECRET=your-csrf-secret-here

Important:

  • Change JWT_SECRET to a strong random string (minimum 32 characters)
  • In production, set NODE_ENV=production and configure ALLOWED_ORIGINS
  • CSRF_SECRET should be different from JWT_SECRET for better security

📄 License

ISC License - feel free to use this project for learning or commercial purposes.


👨‍💻 Author

AR Rahim-- Built with ❤️


⭐ Star this project if you find it useful!

About

A full-stack social media platform built with Node.js and Express, featuring a mobile-first design and Progressive Web App (PWA) capabilities. It includes comprehensive features such as user authentication, real-time notifications, private messaging, post/reel discovery, and hashtag-based content organization.

Topics

Resources

Stars

Watchers

Forks

Contributors