Table of Contents
- Backend Architecture
Backend Architecture
This page documents the backend architecture of the Casino Gaming Platform.
Tech Stack
- Framework: Spring Boot 3.5.0 with Java 23
- Database: PostgreSQL 17.5 with JPA/Hibernate
- Authentication: Custom JWT implementation + OAuth2 (GitHub, Google)
- Build Tool: Gradle with Kotlin DSL
- API Documentation: SpringDoc OpenAPI (Swagger)
- Payment Processing: Stripe API with webhook support
- Email: Spring Mail with Mailpit for development
- Code Quality: Checkstyle integration
Project Structure
The backend follows a domain-driven design approach with the following structure:
src/
├── main/
│ ├── java/
│ │ └── casino/
│ │ ├── CasinoApplication.java
│ │ ├── auth/
│ │ │ ├── AuthController.java
│ │ │ ├── JwtUtil.java
│ │ │ ├── OAuth2Service.java
│ │ │ └── SecurityConfig.java
│ │ ├── balance/
│ │ │ ├── BalanceController.java
│ │ │ └── BalanceService.java
│ │ ├── blackjack/
│ │ │ ├── BlackjackController.java
│ │ │ ├── BlackjackService.java
│ │ │ └── entities/
│ │ ├── coinflip/
│ │ │ ├── CoinflipController.java
│ │ │ └── CoinflipService.java
│ │ ├── config/
│ │ │ ├── CorsConfig.java
│ │ │ └── OpenApiConfig.java
│ │ ├── dice/
│ │ │ ├── DiceController.java
│ │ │ └── DiceService.java
│ │ ├── deposit/
│ │ │ ├── DepositController.java
│ │ │ └── DepositService.java
│ │ ├── email/
│ │ │ ├── EmailController.java
│ │ │ └── EmailService.java
│ │ ├── exception/
│ │ │ └── GlobalExceptionHandler.java
│ │ ├── lootbox/
│ │ │ ├── LootboxController.java
│ │ │ └── LootboxService.java
│ │ ├── shared/
│ │ │ ├── BettingService.java
│ │ │ ├── RandomizationService.java
│ │ │ └── entities/
│ │ ├── slots/
│ │ │ ├── SlotsController.java
│ │ │ └── SlotsService.java
│ │ ├── transaction/
│ │ │ ├── TransactionController.java
│ │ │ ├── TransactionService.java
│ │ │ └── TransactionEntity.java
│ │ └── user/
│ │ ├── UserController.java
│ │ ├── UserEntity.java
│ │ ├── UserRepository.java
│ │ └── UserService.java
│ └── resources/
│ ├── application.properties
│ └── templates/
│ └── email/
└── test/
└── java/
└── casino/
├── balance/
│ └── BalanceServiceTest.java
├── coinflip/
│ └── CoinflipServiceTest.java
└── dice/
└── DiceServiceTest.java
Key Modules
Game Modules
Blackjack
Full-featured blackjack implementation with:
- Standard casino rules (hit, stand, double down, split)
- Dealer AI logic
- Card deck management
- Betting system integration
Coinflip
Simple heads/tails betting game with:
- 50/50 probability outcomes
- Configurable multipliers
- Instant results
Dice
Dice rolling game featuring:
- Configurable number of dice
- Various betting options
- Statistical outcome tracking
Slots
Slot machine implementation with:
- Multiple symbol types
- Payline calculations
- Configurable payout tables
- Bonus features
Lootbox
Virtual lootbox system with:
- Tier-based reward distribution
- Randomized item generation
- Rarity system
Core Services
Authentication System
Comprehensive authentication handling:
- Custom JWT token generation and validation
- OAuth2 integration (GitHub, Google)
- User registration and email verification
- Password recovery flow
- Session management
Key components:
AuthController
: Authentication endpointsJwtUtil
: JWT token utilitiesOAuth2Service
: Social login integrationSecurityConfig
: Security configuration
User Management
Complete user lifecycle management:
- User registration and profile management
- Balance tracking and updates
- Transaction history
- Account verification
Key components:
UserController
: REST endpoints for user operationsUserService
: Business logic for user operationsUserRepository
: Data access layerUserEntity
: Database entity for user data
Transaction System
Robust transaction handling:
- Betting transaction processing
- Win/loss calculations
- Transaction history tracking
- Balance reconciliation
Key components:
TransactionController
: Transaction endpointsTransactionService
: Transaction business logicTransactionEntity
: Transaction data modelBettingService
: Shared betting logic
Payment Processing
Stripe-integrated payment system:
- Deposit session creation
- Webhook handling for payment confirmation
- Balance updates
- Payment verification
Key components:
DepositController
: Payment endpointsDepositService
: Payment processing logic
Email System
Comprehensive email functionality:
- Email verification
- Password recovery
- HTML email templates
- Development email testing with Mailpit
Key components:
EmailController
: Email operation endpointsEmailService
: Email sending logic
Shared Services
Balance Management
Centralized balance operations:
- Balance updates with atomic transactions
- Insufficient funds validation
- Balance history tracking
Randomization Service
Cryptographically secure randomization:
- Game outcome generation
- Auditable random number generation
- Configurable probability distributions
Exception Handling
Global exception handling for consistent error responses:
GlobalExceptionHandler
: Central exception handler- Standardized error response format
- Custom business logic exceptions
API Endpoints
The backend exposes the following main API endpoints:
Authentication API
POST /api/auth/register
: User registrationPOST /api/auth/login
: User loginPOST /api/auth/logout
: User logoutPOST /api/auth/refresh
: Refresh JWT tokenGET /api/auth/oauth2/{provider}
: OAuth2 social loginPOST /api/auth/verify-email
: Email verificationPOST /api/auth/forgot-password
: Password recoveryPOST /api/auth/reset-password
: Password reset
User API
GET /api/users/me
: Get current authenticated userPUT /api/users/me
: Update user profileGET /api/users/{id}/balance
: Get user balance
Game APIs
Blackjack
POST /api/blackjack/start
: Start new blackjack gamePOST /api/blackjack/hit
: Hit actionPOST /api/blackjack/stand
: Stand actionPOST /api/blackjack/double
: Double downPOST /api/blackjack/split
: Split cards
Coinflip
POST /api/coinflip/flip
: Execute coinflip bet
Dice
POST /api/dice/roll
: Execute dice roll bet
Slots
POST /api/slots/spin
: Execute slot machine spin
Lootbox
GET /api/lootbox/types
: Get available lootbox typesPOST /api/lootbox/open
: Open a lootbox
Transaction API
GET /api/transactions
: Get user transaction historyGET /api/transactions/{id}
: Get specific transaction
Balance API
GET /api/balance
: Get current balancePOST /api/balance/add
: Add to balance (admin)POST /api/balance/subtract
: Subtract from balance (admin)
Deposit API
POST /api/deposits/create-session
: Create Stripe payment sessionPOST /api/deposits/webhook
: Stripe webhook handlerGET /api/deposits/history
: Get deposit history
Email API
POST /api/email/send-verification
: Send verification emailPOST /api/email/resend-verification
: Resend verification email
Authentication Flow
JWT Authentication
- User registers or logs in through the application
- Backend generates JWT access and refresh tokens
- Frontend stores tokens and includes access token in API requests
- Backend validates JWT tokens for protected endpoints
- User info is extracted from validated tokens
- Refresh tokens are used to obtain new access tokens
OAuth2 Social Login
- User clicks social login (GitHub/Google)
- User is redirected to OAuth2 provider
- After authorization, user is redirected back with auth code
- Backend exchanges auth code for user information
- User account is created or linked
- JWT tokens are generated for the session
Email Verification
- User registers with email address
- Verification email is sent with unique token
- User clicks verification link
- Backend validates token and activates account
- User can now fully access the platform
Database Schema
User Table
Column | Type | Description |
---|---|---|
id | BIGINT | Primary key |
username | VARCHAR | User's username |
VARCHAR | User's email address | |
password_hash | VARCHAR | Hashed password |
balance | DECIMAL | User's virtual currency balance |
email_verified | BOOLEAN | Email verification status |
oauth2_provider | VARCHAR | OAuth2 provider (if applicable) |
oauth2_id | VARCHAR | OAuth2 user ID |
created_at | TIMESTAMP | Account creation timestamp |
updated_at | TIMESTAMP | Last update timestamp |
Transaction Table
Column | Type | Description |
---|---|---|
id | BIGINT | Primary key |
user_id | BIGINT | Foreign key to user |
type | VARCHAR | Transaction type (BET, WIN, etc.) |
amount | DECIMAL | Transaction amount |
game_type | VARCHAR | Game associated with transaction |
description | VARCHAR | Transaction description |
created_at | TIMESTAMP | Transaction timestamp |
Blackjack Game Session Table
Column | Type | Description |
---|---|---|
id | BIGINT | Primary key |
user_id | BIGINT | Foreign key to user |
bet_amount | DECIMAL | Bet amount for the game |
player_hand | TEXT | JSON representation of player hand |
dealer_hand | TEXT | JSON representation of dealer hand |
game_status | VARCHAR | Current game status |
result | VARCHAR | Game result (WIN, LOSE, PUSH) |
created_at | TIMESTAMP | Game creation timestamp |
updated_at | TIMESTAMP | Last update timestamp |
Development Workflow
-
Start the backend with:
./gradlew bootRun
-
The API will be available at: http://localhost:8080
-
Swagger documentation: http://localhost:8080/swagger
-
Run tests:
./gradlew test
-
Run specific test class:
./gradlew test --tests "FullyQualifiedClassName"
-
Build the project:
./gradlew build
or for a clean build:
./gradlew clean build
Code Style Guidelines
- Use PascalCase for classes with descriptive suffixes (Controller, Service, Entity)
- Use camelCase for methods and variables
- Follow domain-driven package organization
- Prefix DTOs with domain and suffix with "Dto"
- Use Spring's global exception handling with custom exceptions
Testing
The backend includes:
- Unit tests for service and controller layers
- Integration tests for API endpoints
- Mock tests using Mockito
Run tests with:
./gradlew test
Check code style with:
./gradlew checkstyleMain checkstyleTest