A comprehensive RESTful backend application for managing guest hosting operations, including reservations, clients, and user administration with role-based access control.
- Overview
- Technologies & Architecture
- Key Features
- Getting Started
- API Endpoints
- Authentication & Authorization
- Database Schema
- Documentation
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
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
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
Implements comprehensive security features:
- Authentication: JWT-based stateless authentication
- Authorization: Method-level security with
@PreAuthorizeannotations - 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
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
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
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
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
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
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
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
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
Environment variable management:
- 12-Factor App Compliance: Externalized configuration
- Development Convenience:
.envfile support - Secrets Management: Keep sensitive data out of source control
- Environment Parity: Same codebase, different configurations
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
Bean validation with:
- JSR-303/JSR-380 annotations (
@NotNull,@Valid, etc.) - Automatic request validation
- Custom validation logic support
Testing framework including:
- JUnit 5: Modern testing framework
- Mockito: Mocking framework
- Spring Test: Integration testing support
- AssertJ: Fluent assertions
- 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
- 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
- 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
- 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
- Scheduled Tasks: Automatic checkout processing via
AutomaticCheckoutScheduling - Status Updates: Automatic reservation status management
- Structured Logging: Custom
LoggerUtilfor consistent log formatting - File-Based Logs: Logs written to
logs/application.txt - Operation Tracking: Log important operations with context (IDs, usernames)
- Java 21 or higher
- Maven 3.6+ (or use included Maven wrapper)
- Docker and Docker Compose (for PostgreSQL)
- Git (for cloning the repository)
- Create a
.envfile 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-
Clone the repository
git clone https://github.com/eltonacosta/hosting-system.git cd hosting-system -
Start PostgreSQL with Docker Compose
docker-compose up -d
-
Build the application
./mvnw clean install
Or on Windows:
mvnw.cmd clean install
-
Run the application
./mvnw spring-boot:run
Or on Windows:
mvnw.cmd spring-boot:run
-
Access the API
The application will start on
http://localhost:8080(or your configuredSERVER_PORT)
-
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"}'
-
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"}'
-
Use the returned token in subsequent requests:
curl -X GET http://localhost:8080/api/v1/users \ -H "Authorization: Bearer YOUR_JWT_TOKEN_HERE"
All endpoints are prefixed with /api/v1
POST /auth/login- Authenticate and receive JWT token
POST /users/admin- Create admin user (first one is public)POST /users/employee- Create employee userGET /users- List all usersGET /users/is-admin- Check if current user is adminPATCH /users/update- Update user informationDELETE /users/delete- Delete user by ID or username
POST /client/save- Create new clientGET /client- Get client by ID or document IDGET /clients- List all clientsPATCH /client/update- Update client informationDELETE /client/delete- Delete client
POST /reservation/save- Create new reservationGET /reservation- Get reservation by IDGET /reservations/all- List all reservationsGET /reservations- List reservations with filtersPATCH /reservation/update- Update reservationDELETE /reservation/delete- Delete reservationGET /reservation/guests- Get guests for a reservationGET /reservation/guests/count- Get guest countGET /reservation/days- Get number of days for reservationGET /reservation/prices- Get price information (total or daily)
in-period- Reservations within a date rangeend-date-between- Reservations ending in a date rangestart-date-between- Reservations starting in a date rangeperiod-location- Reservations by date range and location (city/state)
-
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
All protected endpoints require a JWT token in the Authorization header:
Authorization: Bearer <your-jwt-token>
- 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.
The application uses PostgreSQL with Flyway migrations for schema management.
- 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
Located in src/main/resources/db/migration:
V1__INITIAL_CREATION_OF_THE_TABLES.sql- Initial schemaV2__add_reservation_fields.sql- Reservation enhancementsV3__add_user_and_role_tables.sql- User and role tables
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.
Run the test suite:
./mvnw testThe application includes tests for:
- Authentication service
- User management
- Data validation
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
This is a personal project by Elton Costa. Contributions, issues, and feature requests are welcome!
This project is available for personal and educational use.
Built with ❤️ using Java 21 and Spring Boot 3.5.6