Comprehensive Technical Documentation
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:
express-session with dotenv for secret management.app.js): The main application file receives the request./admin or /).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)
package.json)The package.json file defines the project's identity and dependencies.
Key Dependencies:
express: The core web framework.mongoose: Object Data Modeling (ODM) library for MongoDB and Node.js. Used to define schemas and interact with the database.express-session: Middleware to manage user sessions (login states).nocache: Middleware to disable client-side caching, ensuring users can't click "Back" to view protected pages after logging out.dotenv: Loads environment variables from a .env file into process.env.app.js)This is the "brain" of the application.
Detailed Walkthrough:
import express from 'express';
import path from 'path';
// ... imports for db, routes, config
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.
const app = express();
connectDB(); // Establishes connection to MongoDB
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
express.urlencoded, express.json, sessionMiddleware, and nocache().app.use('/admin', adminRoute); // All admin URLs start with /admin
app.use(userRoute); // User URLs are at the root level
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.
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
});
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:
email: Authenticates the user.password: Stores the user's password.isBlocked: Controlled by Admins. If true, the user is denied access.middleware/adminauth.js)isLogin: Prevents logged-in admins from seeing login page. Redirects to /admin/home.checkSession: Protects dashboard. If not logged in, redirects to /admin/login.middleware/userauth.js)loginCheckSession: Protects home page. If not logged in, redirects to /login.isLogin: Redirects logged-in users away from Login/Signup pages.routes/user.js)| Method | Path | Middleware | Purpose |
|---|---|---|---|
| GET | /login | isLogin | Render login page |
| POST | /login | None | Process login |
| GET | /signup | isLogin | Render signup page |
| POST | /signup | None | Process signup |
| GET | /home | loginCheckSession | Render dashboard |
controller/ucontroller.js)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.
Finds user by email. Checks if isBlocked is true (security feature). Verifies password. If valid, sets session and redirects to home.
routes/admin.js)Routes include /login, /home, /edit-user, /delete-user, /user-restrict, and /search-user.
controller/acontroller.js)userModel.find().findByIdAndUpdate.isBlocked boolean flag and saves.{ $regex: search, $options: 'i' } for partial case-insensitive matching.Uses Handlebars (HBS) for Templating.
{{ variable }}: For injecting dynamic data (emails, messages).{{#if ...}}: For conditional rendering (alerts, error messages).{{#each users}}: For iterating over user lists in the admin dashboard.Lifecycle Example - Blocking a User:
/admin/user-restrict/:id.isBlocked to true.ucontroller.loadHome checks the database, sees isBlocked: true, destroys their session, and kicks them out.