3 Backend
Jan K9f edited this page 2025-06-04 09:36:55 +02:00

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 endpoints
  • JwtUtil: JWT token utilities
  • OAuth2Service: Social login integration
  • SecurityConfig: 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 operations
  • UserService: Business logic for user operations
  • UserRepository: Data access layer
  • UserEntity: 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 endpoints
  • TransactionService: Transaction business logic
  • TransactionEntity: Transaction data model
  • BettingService: 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 endpoints
  • DepositService: 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 endpoints
  • EmailService: 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 registration
  • POST /api/auth/login: User login
  • POST /api/auth/logout: User logout
  • POST /api/auth/refresh: Refresh JWT token
  • GET /api/auth/oauth2/{provider}: OAuth2 social login
  • POST /api/auth/verify-email: Email verification
  • POST /api/auth/forgot-password: Password recovery
  • POST /api/auth/reset-password: Password reset

User API

  • GET /api/users/me: Get current authenticated user
  • PUT /api/users/me: Update user profile
  • GET /api/users/{id}/balance: Get user balance

Game APIs

Blackjack

  • POST /api/blackjack/start: Start new blackjack game
  • POST /api/blackjack/hit: Hit action
  • POST /api/blackjack/stand: Stand action
  • POST /api/blackjack/double: Double down
  • POST /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 types
  • POST /api/lootbox/open: Open a lootbox

Transaction API

  • GET /api/transactions: Get user transaction history
  • GET /api/transactions/{id}: Get specific transaction

Balance API

  • GET /api/balance: Get current balance
  • POST /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 session
  • POST /api/deposits/webhook: Stripe webhook handler
  • GET /api/deposits/history: Get deposit history

Email API

  • POST /api/email/send-verification: Send verification email
  • POST /api/email/resend-verification: Resend verification email

Authentication Flow

JWT Authentication

  1. User registers or logs in through the application
  2. Backend generates JWT access and refresh tokens
  3. Frontend stores tokens and includes access token in API requests
  4. Backend validates JWT tokens for protected endpoints
  5. User info is extracted from validated tokens
  6. Refresh tokens are used to obtain new access tokens

OAuth2 Social Login

  1. User clicks social login (GitHub/Google)
  2. User is redirected to OAuth2 provider
  3. After authorization, user is redirected back with auth code
  4. Backend exchanges auth code for user information
  5. User account is created or linked
  6. JWT tokens are generated for the session

Email Verification

  1. User registers with email address
  2. Verification email is sent with unique token
  3. User clicks verification link
  4. Backend validates token and activates account
  5. User can now fully access the platform

Database Schema

User Table

Column Type Description
id BIGINT Primary key
username VARCHAR User's username
email 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

  1. Start the backend with:

    ./gradlew bootRun
    
  2. The API will be available at: http://localhost:8080

  3. Swagger documentation: http://localhost:8080/swagger

  4. Run tests:

    ./gradlew test
    
  5. Run specific test class:

    ./gradlew test --tests "FullyQualifiedClassName"
    
  6. 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