Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

12 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

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.js Express MongoDB License

🎯 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

Technology Purpose
Node.js JavaScript runtime environment
Express.js 5.2 Web application framework
MongoDB NoSQL document database
Mongoose MongoDB ODM with schema validation
bcrypt Password hashing library
jsonwebtoken JWT creation and verification
helmet Security HTTP headers
express-rate-limit Rate limiting middleware
express-mongo-sanitize NoSQL injection prevention
dotenv Environment 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-here
    MONGO_URI=mongodb://localhost:27017/secure
    PORT=3000
  4. Start the server

    npm run dev

    Server will run on http://localhost:3000

πŸ“š API Endpoints

Authentication

Method Endpoint Auth Role Description
POST /auth/signup ❌ - Register new user (default: employee)
POST /auth/login ❌ - Authenticate and receive JWT
GET /auth/profile βœ… Any Get current user info
GET /auth/admin βœ… Admin Access admin dashboard
PUT /auth/promote/:id βœ… Admin Promote user to admin role

Assets

Method Endpoint Auth Role Description
POST /asset/create βœ… Admin Create new asset
GET /asset/fetch βœ… Any Get assets assigned to current user
PUT /asset/update/:id βœ… Admin Update asset details
DELETE /asset/delete/:id βœ… Admin Delete 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/profile
Headers:
    Authorization: Bearer <your-token-here>

4. Create Asset (Admin Only)

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

πŸ”’ Security Implementation

Defense in Depth

Layer Protection Purpose
1 Helmet Security HTTP headers
2 Input Validation Validate data format and constraints
3 Mongo Sanitize Prevent NoSQL injection
4 Rate Limiting Prevent brute force attacks
5 JWT Authentication Verify user identity
6 Role Authorization Enforce access control
7 bcrypt Hashing Protect 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