Skip to content

Latest commit

History

12 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Secure Asset Management API

A RESTful API built with Express.js and MongoDB for managing company IT assets with role-based access control, JWT authentication, and comprehensive security hardening.

Node.jsExpressMongoDBLicense

🎯 Overview

This project demonstrates secure backend API development practices, implementing authentication, authorization, input validation, and defense-in-depth security measures. Built as a learning project to master modern backend development and security best practices.

✨ Features

Core Functionality

  • User Authentication - Signup and login with bcrypt password hashing
  • JWT Authorization - Stateless token-based authentication
  • Role-Based Access Control - Admin and employee roles with different permissions
  • Asset Management - Full CRUD operations for IT assets (laptops, monitors, routers, etc.)
  • User Promotion - Admins can promote employees to admin role

Security Features

  • Password Hashing - bcrypt with 12 salt rounds (one-way hashing)
  • JWT Tokens - 1-hour expiry, payload contains only userId and role
  • Security Headers - Helmet middleware sets secure HTTP headers
  • Rate Limiting - Login endpoint limited to 3 attempts per 15 minutes
  • Input Sanitization - Prevents NoSQL injection attacks
  • Input Validation - Validates username, password, and asset fields
  • Defense in Depth - Multiple security layers at every level

🛠️ Tech Stack

TechnologyPurpose
Node.jsJavaScript runtime environment
Express.js 5.2Web application framework
MongoDBNoSQL document database
MongooseMongoDB ODM with schema validation
bcryptPassword hashing library
jsonwebtokenJWT creation and verification
helmetSecurity HTTP headers
express-rate-limitRate limiting middleware
express-mongo-sanitizeNoSQL injection prevention
dotenvEnvironment variable management

📋 Prerequisites

  • Node.js 18+ installed
  • MongoDB 7.0+ running locally or Atlas connection string
  • npm or yarn package manager

🚀 Installation

  1. Clone the repository

    git clone https://github.com/aheedhul/SecureAssetManagementAPI.git
    cd SecureAssetManagementAPI
  2. Install dependencies

    npm install
  3. Configure environment variables

    Create a .env file in the root directory:

    JWT_SECRET=your-super-secret-jwt-key-hereMONGO_URI=mongodb://localhost:27017/securePORT=3000
  4. Start the server

    npm run dev

    Server will run on http://localhost:3000

📚 API Endpoints

Authentication

MethodEndpointAuthRoleDescription
POST/auth/signup-Register new user (default: employee)
POST/auth/login-Authenticate and receive JWT
GET/auth/profileAnyGet current user info
GET/auth/adminAdminAccess admin dashboard
PUT/auth/promote/:idAdminPromote user to admin role

Assets

MethodEndpointAuthRoleDescription
POST/asset/createAdminCreate new asset
GET/asset/fetchAnyGet assets assigned to current user
PUT/asset/update/:idAdminUpdate asset details
DELETE/asset/delete/:idAdminDelete asset

🔐 Authentication Flow

1. POST /auth/signup
→ Password hashed with bcrypt (12 rounds)
→ User saved to database
→ Returns: 201 Created
2. POST /auth/login
→ Verify password against bcrypt hash
→ Generate JWT with { userId, role }
→ Returns: { token: "eyJhbG..." }
3. Protected Routes
→ Send: Authorization: Bearer <token>
→ Middleware verifies JWT
→ Attaches user to req.user
→ Controller executes

🏗️ Project Structure

SecureAssetManagementAPI/
├── app.js # Entry point, middleware setup
├── config/
│ └── database.js # MongoDB connection
├── controllers/
│ ├── authController.js # Auth business logic
│ └── assetController.js # Asset CRUD logic
├── middlewares/
│ ├── authMiddleware.js # JWT verification
│ ├── adminMiddleware.js # Role-based authorization
│ └── validateMiddleware.js # Input validation
├── models/
│ ├── user.js # User schema
│ └── asset.js # Asset schema
├── routes/
│ ├── authRoutes.js # Auth endpoints
│ └── assetRoutes.js # Asset endpoints
├── .env # Environment variables (gitignored)
├── .gitignore
├── package.json
└── README.md

🧪 Testing with Postman

1. Create a User

POST http://localhost:3000/auth/signup
{
"username": "john",
"password": "john1234"
}

2. Login

POST http://localhost:3000/auth/login
{
"username": "john",
"password": "john1234"
}
// Copy the token from response

3. Access Protected Route

GET http://localhost:3000/auth/profileHeaders:Authorization: Bearer <your-token-here>

4. Create Asset (Admin Only)

POST http://localhost:3000/asset/createHeaders:Authorization: Bearer <admin-token>
{
"assetName": "MacBook Pro",
"type": "laptop",
"serialNum": "MBP001",
"assignedTo": "<user-objectid>"
}

🔒 Security Implementation

Defense in Depth

LayerProtectionPurpose
1HelmetSecurity HTTP headers
2Input ValidationValidate data format and constraints
3Mongo SanitizePrevent NoSQL injection
4Rate LimitingPrevent brute force attacks
5JWT AuthenticationVerify user identity
6Role AuthorizationEnforce access control
7bcrypt HashingProtect stored passwords

OWASP Top 10 Coverage

  • Broken Access Control - Role-based middleware
  • Cryptographic Failures - bcrypt hashing, JWT secret in .env
  • Injection - Input sanitization and validation
  • Security Misconfiguration - Helmet security headers
  • Authentication Failures - Password validation, JWT expiry
  • Logging Failures - Error logging (console.error)

🎓 Learning Outcomes

This project demonstrates understanding of:

  • RESTful API design principles
  • JWT-based stateless authentication
  • Password security with bcrypt
  • Role-based access control (RBAC)
  • Middleware chains in Express
  • MongoDB with Mongoose ODM
  • Input validation and sanitization
  • Security best practices (OWASP)
  • Environment variable management
  • Error handling patterns

🚧 Future Enhancements

  • Audit logging for security compliance
  • Asset assignment history tracking
  • Pagination and filtering for large datasets
  • Refresh token rotation
  • Email verification for signup
  • Password reset functionality
  • Comprehensive logging with Winston
  • API documentation with Swagger
  • Unit and integration tests
  • Docker containerization

Built with security-first mindset | Demonstrating backend fundamentals for cybersecurity

About

RESTful API with JWT authentication, role-based access control, and security hardening (bcrypt, helmet, rate limiting, input validation). Built with Express.js and MongoDB.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages