Skip to content

koniz-dev/restful-guide

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

15 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

RESTful API Guide

A comprehensive RESTful API built with Node.js, Express, TypeScript, and MongoDB. This project demonstrates best practices for building scalable and secure web APIs.

πŸš€ Features

  • Authentication System: Secure user registration and login with session tokens
  • User Management: CRUD operations for user profiles
  • Middleware Protection: Route protection with authentication and ownership validation
  • Environment Configuration: Flexible configuration with environment variables
  • TypeScript: Full type safety and modern JavaScript features
  • MongoDB Integration: Robust database operations with Mongoose
  • Security: Password hashing with salt, secure cookies, and CORS protection

πŸ› οΈ Tech Stack

  • Runtime: Node.js
  • Framework: Express.js
  • Language: TypeScript
  • Database: MongoDB with Mongoose
  • Authentication: Custom JWT-like session tokens
  • Security: bcrypt-style password hashing with crypto
  • Development: Nodemon for hot reloading

πŸ“ Project Structure

src/
β”œβ”€β”€ controllers/          # Request handlers
β”‚   β”œβ”€β”€ authentication.ts # Auth controllers (register, login)
β”‚   └── users.ts         # User CRUD controllers
β”œβ”€β”€ db/                  # Database layer
β”‚   └── user.ts          # User model and database operations
β”œβ”€β”€ helpers/             # Utility functions
β”‚   └── index.ts         # Authentication helpers (salt, hash)
β”œβ”€β”€ middlewares/         # Express middlewares
β”‚   └── index.ts         # Authentication and ownership middlewares
β”œβ”€β”€ router/              # Route definitions
β”‚   β”œβ”€β”€ index.ts         # Main router setup
β”‚   β”œβ”€β”€ authentication.ts # Auth routes
β”‚   └── users.ts         # User routes
└── index.ts             # Application entry point

πŸš€ Getting Started

Prerequisites

  • Node.js (v16 or higher)
  • MongoDB (local or MongoDB Atlas)
  • npm or yarn

Installation

  1. Clone the repository

    git clone https://github.com/koniz-dev/restful-guide.git
    cd restful-guide
  2. Install dependencies

    npm install
  3. Environment Setup

    cp .env.example .env

    Edit .env file with your configuration:

    # Database
    MONGO_URL=mongodb://localhost:27017/restful-guide
    
    # Authentication
    SECRET=your-secret-key-here
    AUTH_TOKEN_NAME=AUTH_TOKEN
    
    # Server
    PORT=8080
  4. Start the development server

    npm start

    The server will start on http://localhost:8080 (or your configured PORT).

πŸ“š API Endpoints

Authentication

Method Endpoint Description Body
POST /auth/register Register a new user { username, email, password }
POST /auth/login Login user { email, password }

Users

Method Endpoint Description Auth Required Body
GET /users Get all users βœ… -
GET /users/:id Get user by ID βœ… -
PATCH /users/:id Update user βœ… + Owner { username }
DELETE /users/:id Delete user βœ… + Owner -

πŸ” Authentication Flow

  1. Registration: User provides username, email, password

    • Password is hashed with salt using HMAC-SHA256
    • User data is stored in MongoDB
  2. Login: User provides email and password

    • System verifies password against stored hash
    • Session token is generated and stored in cookie
    • Token is used for subsequent authenticated requests
  3. Protected Routes: Middleware validates session token

    • Extracts token from cookie
    • Verifies token against database
    • Attaches user data to request object

πŸ›‘οΈ Security Features

  • Password Hashing: HMAC-SHA256 with salt and secret key
  • Session Management: Secure session tokens stored in HTTP-only cookies
  • Route Protection: Authentication middleware for protected endpoints
  • Ownership Validation: Users can only modify their own data
  • CORS Configuration: Cross-origin request handling
  • Environment Variables: Sensitive data stored in environment variables

πŸ§ͺ Testing the API

Register a new user

curl -X POST http://localhost:8080/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "username": "johndoe",
    "email": "john@example.com",
    "password": "password123"
  }'

Login

curl -X POST http://localhost:8080/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "john@example.com",
    "password": "password123"
  }'

Get all users (requires authentication)

curl -X GET http://localhost:8080/users \
  -H "Cookie: AUTH_TOKEN=your-session-token"

πŸ”§ Development

Available Scripts

  • npm start - Start development server with nodemon
  • npm test - Run tests (placeholder)

Code Style

  • TypeScript with strict mode enabled
  • ES2022 modules
  • Consistent 4-space indentation
  • Clear separation of concerns (controllers, services, models)

πŸ“ Environment Variables

Variable Description Default Required
MONGO_URL MongoDB connection string - βœ…
SECRET Secret key for password hashing - βœ…
AUTH_TOKEN_NAME Cookie name for session token AUTH_TOKEN ❌
PORT Server port 8080 ❌

πŸ“š Documentation

Comprehensive documentation is available in the docs/ directory:

🀝 Contributing

  1. Fork the repository: https://github.com/koniz-dev/restful-guide
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

πŸ“„ License

This project is licensed under the ISC License.

πŸ™ Acknowledgments

  • Express.js for the web framework
  • MongoDB for the database
  • TypeScript for type safety
  • The Node.js community for excellent tooling

About

A comprehensive RESTful API guide built with Node.js, Express, TypeScript, and MongoDB. Demonstrates best practices for secure web APIs with authentication, user management, and complete documentation.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors