Skip to content

Repository files navigation

Hosting System

A comprehensive RESTful backend application for managing guest hosting operations, including reservations, clients, and user administration with role-based access control.

📋 Table of Contents

🎯 Overview

Hosting System is a production-ready backend application built with modern Java technologies, designed to handle all aspects of a hosting/accommodation business. The system provides secure APIs for managing clients, reservations, and administrative users with different permission levels.

The application follows industry best practices including:

  • Clean Architecture with separation of concerns (controllers, services, repositories)
  • Secure Authentication using JWT tokens
  • Role-Based Access Control (RBAC) for fine-grained permissions
  • Database Version Control with automated migrations
  • Containerized Deployment with Docker support
  • RESTful API Design following HTTP standards

🛠 Technologies & Architecture

Core Technologies

Java 21

The application leverages the latest LTS version of Java, taking advantage of:

  • Modern language features (pattern matching, records, sealed classes)
  • Improved performance and garbage collection
  • Enhanced security features
  • Virtual threads support for better concurrency

Spring Boot 3.5.6

The foundation of the application, providing:

  • Spring Boot Starter Web: RESTful API development with embedded Tomcat server
  • Auto-configuration: Reduces boilerplate configuration
  • Production-ready features: Health checks, metrics, and monitoring
  • Dependency injection: Loose coupling and testability

Spring Security

Implements comprehensive security features:

  • Authentication: JWT-based stateless authentication
  • Authorization: Method-level security with @PreAuthorize annotations
  • Password Encryption: BCrypt hashing algorithm for secure password storage
  • CSRF Protection: Configured for stateless REST APIs
  • Custom Filters: JWT validation filter (JwtAuthFilter) in the filter chain

Spring Data JPA

Simplifies database operations with:

  • ORM (Object-Relational Mapping): Automatic entity-table mapping
  • Repository Pattern: Clean data access layer
  • Query Methods: Derived queries from method names
  • Transaction Management: Automatic transaction handling
  • Hibernate: Underlying JPA implementation with PostgreSQL dialect

Database Technologies

PostgreSQL

Enterprise-grade relational database chosen for:

  • ACID Compliance: Ensures data integrity
  • Advanced Features: JSON support, full-text search, spatial data
  • Scalability: Handles large datasets efficiently
  • Reliability: Proven in production environments
  • Open Source: No licensing costs

Flyway

Database migration tool providing:

  • Version Control: Track schema changes over time
  • Repeatable Migrations: Consistent database state across environments
  • Rollback Support: Manage schema evolution safely
  • Migration Scripts: Located in src/main/resources/db/migration

Integration Technologies

Spring Cloud OpenFeign

Declarative REST client for:

  • External API Integration: Simplifies HTTP client creation
  • Load Balancing: Built-in client-side load balancing
  • Circuit Breaking: Resilience patterns for distributed systems
  • Prepared for Microservices: Easy integration with service discovery

Security Technologies

java-jwt (Auth0)

JWT token generation and validation:

  • Stateless Authentication: No server-side session storage
  • Claims-Based: Embeds user roles and permissions in tokens
  • HMAC/RSA Signing: Cryptographic signature verification
  • Token Expiration: Configurable token lifetime

BCrypt (Spring Security Crypto)

Password hashing algorithm:

  • Adaptive Hashing: Adjustable work factor for future-proofing
  • Salt Generation: Automatic unique salt per password
  • Rainbow Table Resistance: Protects against pre-computed attacks
  • Industry Standard: Widely adopted and audited

Development Tools

Project Lombok

Reduces boilerplate code with annotations:

  • @Data: Generates getters, setters, toString, equals, hashCode
  • @Builder: Implements builder pattern
  • @Slf4j: Adds logging capabilities
  • @AllArgsConstructor, @NoArgsConstructor: Constructor generation
  • Compile-time code generation for cleaner source code

Maven

Build automation and dependency management:

  • Dependency Resolution: Transitive dependency management
  • Build Lifecycle: Standardized build process
  • Plugin Ecosystem: Extensible build system
  • Multi-Module Support: Scalable project structure

java-dotenv

Environment variable management:

  • 12-Factor App Compliance: Externalized configuration
  • Development Convenience: .env file support
  • Secrets Management: Keep sensitive data out of source control
  • Environment Parity: Same codebase, different configurations

Containerization

Docker Compose

Orchestrates multi-container applications:

  • Service Definition: PostgreSQL database container
  • Network Isolation: Containers communicate over isolated network
  • Volume Management: Persistent data storage
  • Environment Variables: Pass configuration to containers
  • One-Command Setup: docker-compose up -d

Additional Dependencies

Spring Boot Starter Validation

Bean validation with:

  • JSR-303/JSR-380 annotations (@NotNull, @Valid, etc.)
  • Automatic request validation
  • Custom validation logic support

Spring Boot Starter Test

Testing framework including:

  • JUnit 5: Modern testing framework
  • Mockito: Mocking framework
  • Spring Test: Integration testing support
  • AssertJ: Fluent assertions

✨ Key Features

User Management

  • Role-Based Administration: ADMIN and EMPLOYEE roles with distinct permissions
  • First Admin Bootstrap: Create the first admin without authentication
  • User CRUD Operations: Full user lifecycle management (create, read, update, delete)
  • Secure Password Storage: All passwords hashed with BCrypt before storage

Client Management

  • Guest Registration: Store client information (name, document ID, birth date)
  • Unique Identification: Document ID validation and uniqueness constraints
  • Client Search: Find clients by ID or document number
  • Full CRUD Support: Complete client lifecycle management

Reservation System

  • Comprehensive Booking: Track start date, end date, pricing, and location
  • Multi-Guest Support: Associate multiple clients with a single reservation
  • Status Tracking: Monitor reservation status (PENDING, CONFIRMED, CANCELLED, COMPLETED)
  • Payment Management: Track payment status (PAID, WAITING_FOR_PAYMENT, PARTNER)
  • Reservation Types: Support for PRIVATE and PARTNER reservations
  • Price Calculations: Automatic daily and total price calculations
  • Advanced Filtering: Search by date ranges, location, and status
  • Guest Management: Track number of guests and retrieve guest lists

Security Features

  • JWT Authentication: Stateless token-based authentication
  • Authorization Guards: Role-based access control at endpoint level
  • Secure Endpoints: All administrative operations require proper authentication
  • Token Validation: Automatic JWT validation on protected routes

Automated Operations

  • Scheduled Tasks: Automatic checkout processing via AutomaticCheckoutScheduling
  • Status Updates: Automatic reservation status management

Logging & Monitoring

  • Structured Logging: Custom LoggerUtil for consistent log formatting
  • File-Based Logs: Logs written to logs/application.txt
  • Operation Tracking: Log important operations with context (IDs, usernames)

🚀 Getting Started

Prerequisites

  • Java 21 or higher
  • Maven 3.6+ (or use included Maven wrapper)
  • Docker and Docker Compose (for PostgreSQL)
  • Git (for cloning the repository)

Environment Configuration

  1. Create a .env file in the project root:
DB_URL=jdbc:postgresql://localhost:5432/hosting_system
DB_USER=your_db_user
DB_PASSWORD=your_db_password
SERVER_PORT=8080

Installation & Running

  1. Clone the repository

    git clone https://github.com/eltonacosta/hosting-system.git
    cd hosting-system
  2. Start PostgreSQL with Docker Compose

    docker-compose up -d
  3. Build the application

    ./mvnw clean install

    Or on Windows:

    mvnw.cmd clean install
  4. Run the application

    ./mvnw spring-boot:run

    Or on Windows:

    mvnw.cmd spring-boot:run
  5. Access the API

    The application will start on http://localhost:8080 (or your configured SERVER_PORT)

First-Time Setup

  1. Create the first admin user (no authentication required for the first admin):

    curl -X POST http://localhost:8080/api/v1/users/admin \
      -H "Content-Type: application/json" \
      -d '{"username":"admin","password":"securePassword123"}'
  2. Login to get JWT token:

    curl -X POST http://localhost:8080/api/v1/auth/login \
      -H "Content-Type: application/json" \
      -d '{"username":"admin","password":"securePassword123"}'
  3. Use the returned token in subsequent requests:

    curl -X GET http://localhost:8080/api/v1/users \
      -H "Authorization: Bearer YOUR_JWT_TOKEN_HERE"

📡 API Endpoints

All endpoints are prefixed with /api/v1

Authentication

  • POST /auth/login - Authenticate and receive JWT token

User Management (ADMIN only)

  • POST /users/admin - Create admin user (first one is public)
  • POST /users/employee - Create employee user
  • GET /users - List all users
  • GET /users/is-admin - Check if current user is admin
  • PATCH /users/update - Update user information
  • DELETE /users/delete - Delete user by ID or username

Client Management

  • POST /client/save - Create new client
  • GET /client - Get client by ID or document ID
  • GET /clients - List all clients
  • PATCH /client/update - Update client information
  • DELETE /client/delete - Delete client

Reservation Management

  • POST /reservation/save - Create new reservation
  • GET /reservation - Get reservation by ID
  • GET /reservations/all - List all reservations
  • GET /reservations - List reservations with filters
  • PATCH /reservation/update - Update reservation
  • DELETE /reservation/delete - Delete reservation
  • GET /reservation/guests - Get guests for a reservation
  • GET /reservation/guests/count - Get guest count
  • GET /reservation/days - Get number of days for reservation
  • GET /reservation/prices - Get price information (total or daily)

Available Filters for Reservations

  • in-period - Reservations within a date range
  • end-date-between - Reservations ending in a date range
  • start-date-between - Reservations starting in a date range
  • period-location - Reservations by date range and location (city/state)

🔐 Authentication & Authorization

Roles

  • ADMIN: Full system access

    • User management (create, update, delete users)
    • All client and reservation operations
    • System configuration
  • EMPLOYEE: Operational access

    • Client management
    • Reservation management
    • Limited user operations

Token Usage

All protected endpoints require a JWT token in the Authorization header:

Authorization: Bearer <your-jwt-token>

Security Notes

  • First Admin: The first admin can be created without authentication. All subsequent admin creations require an existing admin to be authenticated.
  • Password Security: Passwords are never stored in plain text. BCrypt hashing is applied before database storage.
  • Token Expiration: JWT tokens have a configurable expiration time.
  • Stateless Design: No server-side session storage; all authentication state is in the JWT token.

🗄 Database Schema

The application uses PostgreSQL with Flyway migrations for schema management.

Main Tables

  • users - System users with authentication credentials
  • roles - User roles (ADMIN, EMPLOYEE)
  • user_roles - Many-to-many relationship between users and roles
  • clients - Guest information
  • reservations - Booking records
  • reservation_guests - Many-to-many relationship between reservations and clients

Migration Files

Located in src/main/resources/db/migration:

  • V1__INITIAL_CREATION_OF_THE_TABLES.sql - Initial schema
  • V2__add_reservation_fields.sql - Reservation enhancements
  • V3__add_user_and_role_tables.sql - User and role tables

📚 Documentation

For detailed API documentation, including:

  • Request/response examples
  • Entity schemas
  • Enum values
  • Advanced usage patterns
  • curl command examples

See doc.md for complete API reference.

🧪 Testing

Run the test suite:

./mvnw test

The application includes tests for:

  • Authentication service
  • User management
  • Data validation

📦 Project Structure

hosting-system/
├── src/
│   ├── main/
│   │   ├── java/dev/eltoncosta/hosting_system/
│   │   │   ├── appointments/       # Scheduled tasks
│   │   │   ├── config/            # Configuration classes
│   │   │   ├── controller/        # REST controllers
│   │   │   ├── exception/         # Exception handling
│   │   │   ├── mapper/            # DTO mappers
│   │   │   ├── model/             # Entities and DTOs
│   │   │   ├── repository/        # Data access layer
│   │   │   ├── security/          # Security configuration
│   │   │   ├── service/           # Business logic
│   │   │   └── util/              # Utility classes
│   │   └── resources/
│   │       ├── db/migration/      # Flyway migrations
│   │       └── application.yml    # Configuration
│   └── test/                      # Test files
├── docker-compose.yml             # Docker services
├── pom.xml                        # Maven configuration
└── README.md                      # This file

🤝 Contributing

This is a personal project by Elton Costa. Contributions, issues, and feature requests are welcome!

📄 License

This project is available for personal and educational use.


Built with ❤️ using Java 21 and Spring Boot 3.5.6

About

Welcome to the Hotel System — a backend system for managing guest hosting reservations and client data.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages