User Management System

Comprehensive Technical Documentation

Table of Contents

1. Introduction

This document provides an exhaustive, step-by-step technical analysis of the User Management System. This application is a web-based platform built using Node.js and Express that provides authentication (Login/Signup) for users and a comprehensive dashboard for administrators to manage those users.

The system implements the MVC (Model-View-Controller) architectural pattern, ensuring a clean separation of concerns:

2. Project Architecture & Technology Stack

Technology Stack

Architecture Flow

  1. Request Entry: A client (browser) sends a request to the server.
  2. Application Entry (app.js): The main application file receives the request.
  3. Middleware Processing: Global middleware (Body parsers, Session, NoCache) processes the request.
  4. Routing: The request is routed to the appropriate module (/admin or /).
  5. Controller Action: Specific controller functions execute business logic (querying DB, validating input).
  6. Database Interaction: Mongoose models interact with the MongoDB database.
  7. Response Rendering: The controller renders a View (HBS file) or redirects the user.
  8. Client Response: The final HTML is sent back to the browser.

3. Project Directory Structure

user-admin-full-domain/
├── config/                 # Configuration files
│   └── session.js          # Session middleware configuration
├── controller/             # Business logic handlers
│   ├── acontroller.js      # Admin controller (login, user mgmt)
│   └── ucontroller.js      # User controller (signup, login)
├── middleware/             # Request interceptors
│   ├── adminauth.js        # Admin session checks
│   └── userauth.js         # User session checks
├── models/                 # Mongoose schemas
│   └── userModel.js        # User database schema
├── routes/                 # Route definitions
│   ├── admin.js            # Admin-specific routes
│   └── user.js             # User-specific routes
├── views/                  # Handlebars templates
│   ├── admin/              # Admin views (home, login)
│   └── user/               # User views (home, login, signup)
├── public/                 # Static assets (CSS, JS, Images)
├── app.js                  # Main application entry point
├── db.js                   # Database connection logic
├── package.json            # Project metadata & dependencies
└── .env                    # Environment variables (sensitive data)

4. Dependencies & Configuration (package.json)

The package.json file defines the project's identity and dependencies.

Key Dependencies:

5. Core Infrastructure

5.1 Server Initialization (app.js)

This is the "brain" of the application.

Detailed Walkthrough:

  1. Imports: All necessary libraries and local modules are imported.
    import express from 'express';
    import path from 'path';
    // ... imports for db, routes, config
  2. Path Configuration:
    const __filename = fileURLToPath(import.meta.url);
    const __dirname = path.dirname(__filename);
    Since the project uses ES Modules ("type": "module"), __dirname is not available by default. This reconstructs it.
  3. App & Database:
    const app = express();
    connectDB(); // Establishes connection to MongoDB
  4. View Engine Setup:
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'hbs');
  5. Global Middleware: Use of express.urlencoded, express.json, sessionMiddleware, and nocache().
  6. Custom Cache Control Middleware: Explicitly sets 'no-store' headers to prevent back-button access.
  7. Routes Mounting:
    app.use('/admin', adminRoute); // All admin URLs start with /admin
    app.use(userRoute);            // User URLs are at the root level

5.2 Database Connection (db.js)

const connectDB = async () => {
    try {
        const conn = await mongoose.connect("mongodb://localhost:27017/userA");
        console.log("mongodb connected");
    } catch (error) {
        console.log(error);
    }
}

Connects to local MongoDB instance userA on port 27017.

5.3 Session Management (config/session.js)

const sessionMiddleware = session({
    secret: process.env.sessionpass, // Secret from .env
    resave: false,
    saveUninitialized: false,
    cookie: { maxAge: 1000 * 60 * 60 * 24, httpOnly: true }, // 24 Hours
});

6. Data Layer (models/userModel.js)

const userSchema = new mongoose.Schema({
  email: { type: String, required: true },
  password: { type: String, required: true },
  isBlocked: { type: Boolean, default: false }
});

Field Analysis:

7. Middleware & Security

7.1 Admin Authentication (middleware/adminauth.js)

7.2 User Authentication (middleware/userauth.js)

8. Feature Implementation: User Module

8.1 User Routes (routes/user.js)

Method Path Middleware Purpose
GET/loginisLoginRender login page
POST/loginNoneProcess login
GET/signupisLoginRender signup page
POST/signupNoneProcess signup
GET/homeloginCheckSessionRender dashboard

8.2 User Controller Logic (controller/ucontroller.js)

Signup Logic

Checks if user exists using findOne({ email }). If not, creates new user and saves to DB. Automatically logs user in by setting req.session.user.

Login Logic

Finds user by email. Checks if isBlocked is true (security feature). Verifies password. If valid, sets session and redirects to home.

9. Feature Implementation: Admin Module

9.1 Admin Routes (routes/admin.js)

Routes include /login, /home, /edit-user, /delete-user, /user-restrict, and /search-user.

9.2 Admin Controller Logic (controller/acontroller.js)

10. Presentation Layer (Views)

Uses Handlebars (HBS) for Templating.

Lifecycle Example - Blocking a User:

  1. Admin clicks "Restrict".
  2. Request hits /admin/user-restrict/:id.
  3. Controller toggles isBlocked to true.
  4. User is redirected to Admin Home.
  5. If the blocked user tries to access Home, ucontroller.loadHome checks the database, sees isBlocked: true, destroys their session, and kicks them out.