Skip to content

gussttaav/g-commerce-springboot-api

Repository files navigation

Spring Boot G-commerce API

Build Status Tests Deploy Status Health Check API Documentation Code Quality Backend Docker Image

The G-Commerce API is a robust, secure, and scalable backend for e-commerce applications, built with Spring Boot. It provides essential features such as JWT authentication with refresh tokens, role-based access control, product management, purchases and history tracking with pagination. Designed for seamless integration with various front-end projects, this API ensures a smooth and efficient e-commerce experience.

πŸš€ Features

  • User Management

    • User registration and authentication
    • Role-based authorization (ADMIN, USER)
    • Profile management and password updates
    • Admin-only user listing with pagination
  • Product Management

    • Full CRUD operations on /api/products
    • Product status management (active/inactive)
    • Public access to active products
    • Role-based access control for product operations
    • Paginated product listing with status filtering
    • Text search across product name and description fields
  • Purchase System

    • Shopping cart functionality
    • Purchase history tracking with pagination
    • Role-specific purchase restrictions
  • JWT Authentication & Authorization

    • OAuth2 Resource Server with RSA-signed JWT tokens
    • Access and refresh token system with automatic token rotation
    • Token blacklisting and secure logout functionality
    • RSA key pair generation, storage, and scheduled rotation
    • OpenID Connect discovery endpoints and JWKS support
  • Security & SSL Support

    • Rate limiting with token bucket algorithm
    • Role-based rate limits (Admin/User/Unauthenticated)
    • Automatic profile detection based on available SSL certificate
    • HTTPS configuration with SSL keystore
    • Environment-based profile activation
    • RSA-based JWT token signing and validation
    • Redis-based token storage and blacklisting
  • Comprehensive Documentation

    • Javadoc for code-level documentation
    • OpenAPI (Swagger) for interactive API documentation
    • Detailed endpoint descriptions and schemas
  • Comprehensive Testing

    • Unit tests for all layers
    • Security tests
    • Mock MVC tests for controllers
    • In-memory H2 database for testing
  • Continuous Integration via GitHub Actions

    • Automated Docker image build and publish to Docker Hub
    • Environment-based configuration management
    • Automated deploy to an AWS EC2 instance pulling the created images
    • Automated availabality monitoring after deployed
  • Monitoring & Management

    • Spring Boot Actuator integration for application monitoring
    • Health checks with readiness and liveness probes
    • Metrics collection and exposure (JVM, system, web, database)
    • Application info endpoint with environment and build details
    • Prometheus metrics support for external monitoring systems

πŸ› οΈ Technologies

  • Java 21
  • Spring Boot 3.4.9
  • Spring Security (OAuth2 Resource Server)
  • NimbusDS JOSE+JWT library
  • Redis (for token storage and blacklisting)
  • Bucket4j (for rate limiting)
  • OpenAPI/Swagger
  • Spring Data JPA
  • MySQL 9
  • H2 Database (for testing)
  • JUnit 5
  • Mockito
  • Docker & Docker Compose
  • Maven
  • Lombok
  • GitHub Actions
  • Spring Boot Actuator
  • Prometheus (metrics)
  • Checkstyle (code style enforcement)
  • PMD (static code analysis)

πŸ“‹ Prerequisites

  • Java 21 or higher
  • Docker and Docker Compose
  • Maven
  • Git

πŸ”§ Installation

  1. Clone the repository:

    git clone https://github.com/gussttaav/g-commerce-springboot-api.git
    cd g-commerce-springboot-api
  2. Create a .env file in the root directory with the following variables:

    # Database Configuration
    MYSQL_ROOT_PASSWORD=your_root_password
    MYSQL_USER=your_database_user
    MYSQL_PASSWORD=your_database_password
    
    # Redis Configuration
    REDIS_PASSWORD=your_redis_password
    
    # Admin User Configuration
    ADMIN_EMAIL=admin@example.com
    ADMIN_PASSWORD=your_admin_password
    
    # JWT Configuration
    JWT_ISSUER=g-commerce-api
    JWT_ACCESS_EXPIRATION_MS=3600000
    JWT_REFRESH_EXPIRATION_MS=86400000
    
    # OAuth2 Key Rotation (optional)
    OAUTH2_KEY_ROTATION_ENABLED=true
    OAUTH2_KEY_ROTATION_CRON=0 0 2 1 * ?

    HTTPS support (optional)

    If you need the application to run with HTTPS, you must add the following environment variables in your .env file and provide a valid SSL certificate in the src/main/resources directory.

    SPRING_PROFILES_ACTIVE=https
    SSL_PASSWORD=your_ssl_password
  3. Start the MySQL database and Redis using Docker Compose:

    docker-compose -f docker-compose.db.yml up -d
  4. Build and run the application:

    mvn clean install
    mvn spring-boot:run

The application will be available at http://localhost:8080 (default) or https://localhost:8443 (if SSL is enabled).

🐳 Docker Images

The application is split into two Docker images:

  1. Backend Application (gussttaav/g-commerce-backend)

    • Spring Boot application
    • API endpoints and business logic
    • Available tags: latest
  2. Database (gussttaav/g-commerce-mysql)

    • MySQL 9 with a pre-configured schema
    • Includes all necessary tables and initial data
    • Available tags: latest

Both images are automatically built and pushed to Docker Hub on every push to this branch using GitHub Actions. Refer to the repository documentation if you want to deploy the full application with docker compose.

After the image is pushed to Docker Hub the application is automatically deployed to an AWS EC2 instance pulling the created images and running the associated containers using Docker Compose.

πŸ“š API Documentation

OpenAPI (Swagger) Documentation

The project uses SpringDoc OpenAPI for interactive API documentation:

  • Swagger UI: http://localhost:8080/swagger-ui

    • Interactive documentation of all API endpoints
    • Ability to test endpoints directly from the browser
    • Detailed request and response schemas
  • API Docs JSON: http://localhost:8080/v3/api-docs

    • Machine-readable OpenAPI specification
    • Can be used for client code generation

JWKS and OpenID Connect Discovery

The API exposes standard discovery endpoints for OAuth2 clients:

  • JWKS Endpoint: /.well-known/jwks.json

    • JSON Web Key Set containing public keys for JWT verification
    • Used by external services to validate JWT signatures
  • OpenID Configuration: /.well-known/openid-configuration

    • OpenID Provider metadata following RFC 8414
    • Configuration information for OAuth2 clients

Javadoc

Comprehensive Javadoc documentation is available for all classes.

To generate Javadoc:

mvn javadoc:javadoc

Health and Monitoring Endpoints

Spring Boot Actuator provides several monitoring endpoints:

  • Health Check: /actuator/health

    • Basic health status available to all users
    • Detailed health information available to authenticated users
    • Includes database connectivity and disk space checks
  • Application Info: /actuator/info

    • Application metadata including version, build info, and environment details
    • Git information and Java/OS details
  • Metrics: /actuator/metrics

    • JVM, system, web, and database metrics
    • Custom application metrics
  • Prometheus: /actuator/prometheus

    • Prometheus-formatted metrics for external monitoring systems

πŸ§ͺ Testing

Test Configuration

The project uses H2 in-memory database for testing.

Test Categories

  • Controller Tests: Using MockMvc to test HTTP endpoints
  • Service Tests: Unit tests for business logic
  • Repository Tests: Database operation tests
  • Security Tests: Authentication and authorization tests
  • Integration Tests: End-to-end functionality tests

Running Tests

# Run all tests
mvn test

# Run specific test class
mvn test -Dtest=UsuarioControllerTest

# Run tests with coverage report
mvn verify

βœ… Code Quality

The project uses Checkstyle and PMD for code quality analysis:

  • Checkstyle: Enforces coding standards (checkstyle-rules.xml)
  • PMD: Static code analysis for best practices (pmd-ruleset.xml)

Run the checks with:

# Checkstyle only
mvn checkstyle:check

# PMD only
mvn pmd:check

# Both (also runs during normal build)
mvn clean verify

πŸ”‘ API Endpoints

Authentication

POST /api/auth/login            # Login β†’ access + refresh tokens
POST /api/auth/refresh          # Refresh access token using refresh token
POST /api/auth/logout           # Logout and blacklist tokens
GET  /api/auth/validate         # Validate JWT token

User Management

POST /api/users                 # Register new user (role: USER or ADMIN if caller is ADMIN)
GET  /api/users/me              # Get current user profile
PATCH /api/users/me             # Update profile or password

# With ADMIN role only:
GET    /api/users               # List all users (paginated)
PATCH  /api/users/{id}/role     # Change user role (ADMIN/USER)

Product Management

GET /api/products               # List active products (search, pagination)

# With ADMIN role only:
GET    /api/products?status=INACTIVE|ALL   # List inactive or all products
POST   /api/products                       # Create product
PUT    /api/products/{id}                  # Update product
DELETE /api/products/{id}                  # Delete product

Purchase Management

POST /api/purchases             # Create new purchase
GET  /api/purchases             # List user purchases (paginated)

Discovery Endpoints

GET  /.well-known/jwks.json                   # JSON Web Key Set
GET  /.well-known/openid-configuration        # OpenID Provider metadata

Monitoring Endpoints

GET  /actuator/health              # Application health status
GET  /actuator/info                # Application information
GET  /actuator/metrics             # Application metrics
GET  /actuator/prometheus          # Prometheus-formatted metrics

πŸ”’ Security

  • JWT authentication using OAuth2 Resource Server with RSA-signed tokens
  • Access and refresh token system with secure token rotation
  • RSA key pair generation, storage, and scheduled rotation in Redis
  • Token blacklisting for secure logout functionality
  • Rate limiting implemented using token bucket algorithm
  • HTTPS support to encrypt communication between clients and the server
  • Passwords are encrypted using BCrypt
  • Role-based access control for different endpoints
  • Input validation for all endpoints
  • Comprehensive security documentation in OpenAPI spec

πŸ“ JWT Authentication Flow

1. Login

POST /api/auth/login
Content-Type: application/json

{
    "email": "user@example.com",
    "password": "password123"
}

Response:

{
    "usuario": {
        "id": 1,
        "name": "John Doe",
        "email": "user@example.com",
        "role": "USER"
    },
    "token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...",
    "tokenType": "Bearer",
    "expiresIn": 3600,
    "refreshToken": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...",
    "refreshExpiresIn": 86400
}

2. Authenticated Requests

GET /api/users/me
Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...

3. Token Refresh

POST /api/auth/refresh
Authorization: Bearer <refresh_token>

4. Logout

POST /api/auth/logout
Authorization: Bearer <access_token>
Content-Type: application/json

{
    "refreshToken": "<refresh_token>"
}

πŸ“ Example Requests

Register a User

POST /api/users
Content-Type: application/json

{
  "name": "John Doe",
  "email": "john@example.com",
  "password": "password123"
}

Create a Product (Admin only)

POST /api/products
Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...
Content-Type: application/json

{
  "name": "Laptop",
  "description": "High-performance laptop",
  "price": 999.99
}

Make a Purchase

POST /api/purchases
Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...
Content-Type: application/json

{
  "products": [
    { "productId": 1, "quantity": 2 }
  ]
}

πŸ“ Project Structure

src/
β”œβ”€β”€ main/
β”‚   β”œβ”€β”€ java/
β”‚   β”‚   └── com/gplanet/commerce/api
β”‚   β”‚       β”œβ”€β”€ configs/
β”‚   β”‚       β”‚   β”œβ”€β”€ app/
β”‚   β”‚       β”‚   β”‚   β”œβ”€β”€ data/
β”‚   β”‚       β”‚   β”‚   β”œβ”€β”€ docs/
β”‚   β”‚       β”‚   β”‚   β”œβ”€β”€ health/
β”‚   β”‚       β”‚   β”‚   └── props/
β”‚   β”‚       β”‚   β”œβ”€β”€ security/
β”‚   β”‚       β”‚   β”‚   └── ratelimiting/
β”‚   β”‚       β”‚   └── web/
β”‚   β”‚       β”œβ”€β”€ controllers/
β”‚   β”‚       β”œβ”€β”€ dtos/
β”‚   β”‚       β”‚   β”œβ”€β”€ api/
β”‚   β”‚       β”‚   β”œβ”€β”€ auth/
β”‚   β”‚       β”‚   β”œβ”€β”€ jwks/
β”‚   β”‚       β”‚   β”œβ”€β”€ product/
β”‚   β”‚       β”‚   β”œβ”€β”€ purchase/
β”‚   β”‚       β”‚   └── user/
β”‚   β”‚       β”œβ”€β”€ entities/
β”‚   β”‚       β”œβ”€β”€ exceptions/
β”‚   β”‚       β”œβ”€β”€ repositories/
β”‚   β”‚       β”œβ”€β”€ services/
β”‚   β”‚       └── utilities/
β”‚   └── resources/
β”‚       └── application.yml
β”œβ”€β”€ test/
β”‚   β”œβ”€β”€ java/
β”‚   β”‚   └── com/gplanet/commerce/api/
β”‚   β”‚       β”œβ”€β”€ configs/
β”‚   β”‚       β”œβ”€β”€ integration/
β”‚   β”‚       β”œβ”€β”€ controllers/
β”‚   β”‚       β”œβ”€β”€ repositories/
β”‚   β”‚       β”œβ”€β”€ security/
β”‚   β”‚       β”œβ”€β”€ services/
β”‚   β”‚       └── testutils/
β”‚   └── resources/
β”‚       └── application-test.yml
β”œβ”€β”€ docker-compose.yml
β”œβ”€β”€ docker-compose.db.yml
β”œβ”€β”€ docker-entry.sh
β”œβ”€β”€ Dockerfile
β”œβ”€β”€ Dockerfile.db
β”œβ”€β”€ mysql-init/
β”‚   └── shopping_db.sql
└── pom.xml

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

About

A secure, scalable RESTful API for an e-commerce system, built with Spring Boot. Features include user authentication, role-based access control, product management, shopping cart functionality, and purchase tracking. Fully documented with Swagger/OpenAPI and optimized for Dockerized deployment.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages