update

Jan K9f 2025-06-04 09:36:55 +02:00
commit a90e821cb7
Signed by: jank
GPG key ID: 22BEAC760B3333D6
12 changed files with 1439 additions and 386 deletions

@ -4,241 +4,403 @@ This page documents the authentication and authorization system of the Casino Ga
## Overview ## Overview
The Casino Gaming Platform uses Keycloak as its identity and access management solution. This provides: The Casino Gaming Platform uses a hybrid authentication system combining custom JWT tokens with OAuth2 social login integration. This provides:
- Secure user authentication - Secure user authentication with email/password
- Single sign-on (SSO) capability - OAuth2 social login (GitHub, Google)
- JWT token-based authorization
- Email verification system
- Password recovery functionality
- User profile management - User profile management
- Role-based access control - Real-time session management
- Token-based authorization
## Architecture ## Architecture
``` ```
┌────────────────┐ ┌────────────────┐ ┌────────────────┐ ┌────────────────┐ ┌──────────────────┐ ┌────────────────┐
│ │ │ │ │ │ │ │ │ │ │ │
│ Frontend │◄──────► Keycloak │◄──────► Backend │ │ Frontend │ │ OAuth2 Providers│ │ Backend │
(Angular) │ │ │ │ (Spring Boot) │ (Angular 20) │ │ (GitHub, Google) │ │ (Spring Boot 3) │
│ │ │ │ │ │ │ │ │ │ │ │
└────────────────┘ └────────────────┘ └────────────────┘ └─────────────────┘ └──────────────────┘ └─────────────────┘
▲ │ │ │ │
│ │ └───────────────────────┼───────────────────────┘
└──────────────────────────────────────────────────┘
(API calls with JWT token) ┌───────────────────────▼───────────────────────┐
│ JWT Token Management │
│ - Access Tokens (15 min) │
│ - Refresh Tokens (7 days) │
│ - Email Verification Tokens │
│ - Password Reset Tokens │
└───────────────────────────────────────────────┘
``` ```
## Keycloak Configuration ## Authentication Configuration
### Realm Setup ### JWT Token Configuration
The platform uses a dedicated Keycloak realm named `lf12-realm`: - **Access Token Lifespan**: 15 minutes
- **Refresh Token Lifespan**: 7 days
- **Email Verification Token**: 24 hours
- **Password Reset Token**: 1 hour
- **Algorithm**: RS256 (RSA + SHA-256)
- **Client ID**: `casino-frontend` ### OAuth2 Provider Configuration
- **Access Type**: Public
- **Valid Redirect URIs**:
- `http://localhost:4200/*`
- `http://casino.example.com/*` (for production)
- **Web Origins**: `+` (allows all origins from Valid Redirect URIs)
### User Roles #### GitHub OAuth2
- **Client Type**: Public
- **Scope**: `user:email`
- **Redirect URI**: `http://localhost:4200/auth/oauth-callback`
#### Google OAuth2
- **Client Type**: Public
- **Scope**: `openid email profile`
- **Redirect URI**: `http://localhost:4200/auth/oauth-callback`
### User Roles and Permissions
The following user roles are defined: The following user roles are defined:
- **user**: Basic authenticated user - **USER**: Basic authenticated user with game access
- **admin**: Administrative user with management capabilities - **ADMIN**: Administrative user with management capabilities
- **vip**: Users with premium access (higher limits, special games) - **MODERATOR**: User with limited admin capabilities
### Token Configuration ### Security Configuration
- **Access Token Lifespan**: 5 minutes - **Password Requirements**: Minimum 8 characters, alphanumeric
- **Refresh Token Lifespan**: 30 days - **Email Verification**: Required for account activation
- **ID Token Lifespan**: 1 hour - **Session Management**: Stateless JWT-based authentication
- **CORS Configuration**: Restricted to frontend domain
## Authentication Flow ## Authentication Flow
### Frontend Authentication ### Email/Password Authentication
1. **Login Initiation**: 1. **User Registration**:
- User clicks "Login" button on the frontend - User fills out registration form
- Application redirects to Keycloak login page - Backend validates email uniqueness
- Account created with `email_verified: false`
- Verification email sent with unique token
- User clicks verification link to activate account
2. **Keycloak Authentication**: 2. **User Login**:
- User enters credentials on Keycloak login page - User enters email and password
- Keycloak authenticates the user - Backend validates credentials
- Keycloak redirects back to the application with authorization code - JWT access and refresh tokens generated
- Tokens returned to frontend and stored in localStorage
- User redirected to home dashboard
3. **Token Exchange**: 3. **Token Management**:
- Frontend exchanges authorization code for tokens - Access token included in API requests via HTTP interceptor
- Frontend stores tokens in secure storage - Automatic token refresh when access token expires
- User is redirected to the home page - Logout clears tokens and invalidates refresh token
4. **Auto-login with Silent Check-SSO**: ### OAuth2 Social Login Flow
- Application uses silent-check-sso.html for quiet refresh
- If user has an active Keycloak session, they're automatically logged in
### Backend Authentication 1. **GitHub/Google Login**:
- User clicks social login button
- Frontend redirects to OAuth2 provider
- User authorizes application
- Provider redirects to callback with authorization code
1. **Token Validation**: 2. **OAuth2 Token Exchange**:
- Frontend includes the JWT token in Authorization header - Frontend sends authorization code to backend
- Backend validates the token signature using Keycloak's public key - Backend exchanges code for user profile data
- Backend extracts user information and roles from the token - Account created or linked if existing
- JWT tokens generated and returned
- User logged in and redirected to home
### Password Recovery Flow
1. **Password Reset Request**:
- User enters email address
- Backend generates password reset token
- Reset email sent with secure link
- User clicks link to access reset form
2. **Password Reset**:
- User enters new password
- Backend validates reset token
- Password updated and tokens invalidated
- User must log in with new password
### Backend Token Validation
1. **Token Verification**:
- Frontend includes JWT token in Authorization header
- Backend validates token signature and expiration
- User information extracted from token claims
- Request proceeds if token valid
2. **Token Refresh**: 2. **Token Refresh**:
- When access token expires, frontend uses refresh token to get a new one - When access token expires, frontend uses refresh token
- If refresh token is invalid, user is redirected to login - Backend validates refresh token and issues new access token
- If refresh token invalid, user redirected to login
## Authorization ## Authorization
### Frontend Authorization ### Frontend Authorization
The Angular application uses route guards to protect routes: The Angular application uses route guards and service-based authentication:
```typescript ```typescript
// auth.guard.ts // auth.guard.ts
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root'
}) })
export class AuthGuard { export class AuthGuard implements CanActivate {
constructor(private router: Router) {} constructor(
private authService: AuthService,
private router: Router
) {}
canActivate(): boolean { canActivate(): boolean {
if (!this.isAuthenticated()) { if (this.authService.isAuthenticated()) {
this.router.navigate(['/landing']);
return false;
}
return true; return true;
} }
this.router.navigate(['/auth/login']);
return false;
}
}
// auth.service.ts
@Injectable({
providedIn: 'root'
})
export class AuthService {
private tokenKey = 'access_token';
private refreshTokenKey = 'refresh_token';
isAuthenticated(): boolean { isAuthenticated(): boolean {
// Check for valid token const token = localStorage.getItem(this.tokenKey);
return token && !this.isTokenExpired(token);
}
getToken(): string | null {
return localStorage.getItem(this.tokenKey);
}
logout(): void {
localStorage.removeItem(this.tokenKey);
localStorage.removeItem(this.refreshTokenKey);
this.router.navigate(['/auth/login']);
} }
} }
``` ```
Protected routes are configured in the routing module: Protected routes are configured with guards:
```typescript ```typescript
const routes: Routes = [ const routes: Routes = [
{ path: '', component: LandingComponent }, { path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: 'auth', loadChildren: () => import('./auth/auth.module') },
{ path: 'home', component: HomeComponent, canActivate: [AuthGuard] }, { path: 'home', component: HomeComponent, canActivate: [AuthGuard] },
{ path: 'games', loadChildren: () => import('./games/games.module'), canActivate: [AuthGuard] },
{ path: 'deposit', component: DepositComponent, canActivate: [AuthGuard] } { path: 'deposit', component: DepositComponent, canActivate: [AuthGuard] }
]; ];
``` ```
### Backend Authorization ### Backend Authorization
The Spring Boot backend uses Spring Security with Keycloak adapter: The Spring Boot backend uses Spring Security with custom JWT authentication:
```java ```java
@Configuration @Configuration
@EnableWebSecurity @EnableWebSecurity
public class KeycloakSecurityConfig extends WebSecurityConfigurerAdapter { public class SecurityConfig {
@Override @Bean
protected void configure(HttpSecurity http) throws Exception { public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http http
.authorizeRequests() .csrf(csrf -> csrf.disable())
.antMatchers("/api/health").permitAll() .cors(cors -> cors.configurationSource(corsConfigurationSource()))
.antMatchers("/api/users/**").hasRole("user") .authorizeHttpRequests(auth -> auth
.antMatchers("/api/admin/**").hasRole("admin") .requestMatchers("/api/auth/**").permitAll()
.requestMatchers("/api/health").permitAll()
.requestMatchers(HttpMethod.POST, "/api/deposits/webhook").permitAll()
.requestMatchers("/api/admin/**").hasRole("ADMIN")
.anyRequest().authenticated() .anyRequest().authenticated()
.and() )
.oauth2ResourceServer().jwt(); .sessionManagement(session ->
session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
)
.addFilterBefore(jwtAuthenticationFilter(),
UsernamePasswordAuthenticationFilter.class);
return http.build();
} }
} }
``` ```
## User Registration ## User Registration and Management
Users can register in two ways: ### Registration Methods
1. **Self-registration through frontend**: 1. **Email/Password Registration**:
- User clicks "Register" on frontend - User fills out registration form with username, email, password
- User completes registration form - Backend validates email uniqueness and password strength
- Account is created in Keycloak - User account created with email verification required
- User profile is created in application database - Verification email sent with activation link
- User must verify email before full account access
2. **Admin-created accounts**: 2. **OAuth2 Social Registration**:
- Admins can create users through Keycloak Admin Console - User initiates social login (GitHub/Google)
- Backend syncs new users from Keycloak to application database - Backend receives user profile from OAuth2 provider
- Account automatically created and verified
- User logged in immediately after authorization
3. **Account Linking**:
- Existing users can link social accounts to their profile
- Multiple login methods for same account
- Profile consolidation and enhanced security
### User Profile Management
- **Profile Updates**: Users can update username, email (requires re-verification)
- **Password Changes**: Secure password update with current password verification
- **Account Deletion**: Soft delete with data retention policy
- **Session Management**: View and revoke active sessions
## Security Considerations ## Security Considerations
### Token Storage ### Token Storage and Security
- Access and refresh tokens are stored in browser's Local Storage - **Access Tokens**: Stored in browser localStorage with 15-minute expiration
- ID token contains user profile information - **Refresh Tokens**: Stored in localStorage with 7-day expiration
- No sensitive information is stored in tokens - **Token Content**: Contains user ID, roles, and expiration (no sensitive data)
- **Automatic Cleanup**: Expired tokens automatically removed
- **Security Headers**: CORS, CSP, and HSTS configured for production
### CSRF Protection ### CSRF Protection
- Angular includes anti-CSRF token with requests - CSRF protection disabled for stateless JWT authentication
- Spring Security validates CSRF tokens on state-changing operations - CORS configured to restrict cross-origin requests
- SameSite cookie policy for enhanced security
### Session Management ### Session Management
- JWT token-based authentication is stateless - **Stateless Authentication**: JWT tokens eliminate server-side session storage
- Keycloak manages session state - **Token Refresh**: Automatic refresh of access tokens using refresh tokens
- Session timeout can be configured in Keycloak - **Session Timeout**: Configurable token expiration times
- **Multi-device Support**: Users can be logged in on multiple devices
- **Logout**: Invalidates refresh token and clears client-side tokens
## Testing Authentication ## API Testing and Development
### Obtaining a Test Token ### Obtaining Test Tokens
For API testing, obtain a bearer token: For API testing, authenticate via the API:
1. Open `requests/getBearerToken.http` 1. **Register Test User**:
2. Click the green arrow next to the request ```bash
3. Copy the `access_token` from the response POST /api/auth/register
{
"username": "testuser",
"email": "test@example.com",
"password": "password123"
}
```
### Using Swagger with Authentication 2. **Login for Token**:
```bash
POST /api/auth/login
{
"email": "test@example.com",
"password": "password123"
}
```
1. Open Swagger UI at http://localhost:8080/swagger 3. **Use Access Token**:
```bash
Authorization: Bearer <access_token>
```
### Swagger API Documentation
1. Open Swagger UI at http://localhost:8080/swagger-ui.html
2. Click "Authorize" button 2. Click "Authorize" button
3. Enter the bearer token 3. Enter the JWT bearer token (include "Bearer " prefix)
4. Test API endpoints with authentication 4. Test authenticated API endpoints
### Development Tools
- **Mailpit**: Email testing at http://localhost:8025
- **Database Console**: H2 console for development database inspection
- **Actuator Endpoints**: Health checks and metrics at `/actuator`
## Logout Flow ## Logout Flow
1. **Frontend Logout**: 1. **User-Initiated Logout**:
- User clicks "Logout" button - User clicks "Logout" button in application
- Frontend clears local tokens - Frontend calls logout API endpoint
- Frontend redirects to Keycloak logout endpoint - Backend invalidates refresh token in database
2. **Keycloak Logout**: 2. **Token Cleanup**:
- Keycloak invalidates the session - Frontend clears access and refresh tokens from localStorage
- Keycloak redirects back to application - HTTP interceptor stops including authorization headers
- User redirected to login page
3. **Backend Logout Handling**: 3. **Automatic Logout**:
- `KeycloakLogoutHandler` processes logout events - When refresh token expires or is invalid
- Any necessary cleanup is performed - When access token cannot be refreshed
- Authentication errors trigger automatic logout
4. **Security Logout**:
- Backend can invalidate all user sessions
- Password changes trigger logout from all devices
- Suspicious activity can trigger forced logout
## Troubleshooting ## Troubleshooting
### Common Issues ### Common Issues
1. **"Invalid token" errors**: 1. **"Invalid token" errors**:
- Check token expiration - Check token expiration time
- Verify Keycloak is running - Verify JWT secret configuration
- Check time synchronization between services - Ensure system clocks are synchronized
- Check token format (Bearer prefix)
2. **"Insufficient permissions" errors**: 2. **"Access denied" errors**:
- Verify user has required roles - Verify user has required roles
- Check role mapping in Keycloak - Check endpoint security configuration
- Ensure token contains correct claims
3. **"Invalid redirect URI" errors**: 3. **OAuth2 authentication failures**:
- Ensure redirect URI is configured in Keycloak client - Verify OAuth2 client credentials
- Check redirect URI configuration
- Ensure OAuth2 provider is accessible
4. **Email verification issues**:
- Check email service configuration
- Verify SMTP settings in development
- Check Mailpit for sent emails
### Debugging Tips ### Debugging Tips
1. **Examine token contents**: 1. **Examine token contents**:
- Use [jwt.io](https://jwt.io) to decode tokens - Use [jwt.io](https://jwt.io) to decode tokens
- Check audience, issuer, and claims - Check claims, expiration, and signature
- Verify issuer and audience values
2. **Check Keycloak logs**: 2. **Check application logs**:
- Use `docker-compose logs keycloak_lf12` - Backend logs show authentication events
- Look for authentication errors - Frontend console shows token errors
- Network tab reveals API response codes
3. **Check browser console**: 3. **Database inspection**:
- Look for authentication errors in browser console - Check user table for account status
- Check network tab for failed token requests - Verify email verification status
- Review refresh token validity
4. **Email testing**:
- Use Mailpit at http://localhost:8025
- Check email templates and delivery
- Verify verification link generation
### Security Monitoring
- **Failed Login Attempts**: Monitor for brute force attacks
- **Token Abuse**: Detect unusual token usage patterns
- **Account Enumeration**: Prevent email/username discovery
- **Rate Limiting**: Implement request rate limiting for auth endpoints

34
Backend-Testing.md Normal file

@ -0,0 +1,34 @@
# Backend Testing
This page provides guidelines and best practices for testing the backend components of the Casino application.
## Unit Testing
Unit tests focus on testing individual components in isolation. Each class, function, or module should have corresponding unit tests.
## Integration Testing
For integration testing between backend components, see the [Integration-Testing](Integration-Testing) page.
## Mock Services
When testing services that interact with external APIs or databases, use mock implementations to isolate tests.
## Test Coverage
Aim for at least 80% code coverage for all backend components.
## Running Tests
```bash
# To run all tests
./gradlew test
# To run specific tests
./gradlew test --tests "com.casino.package.TestClass"
```
## Related Pages
- [Testing-Guidelines](Testing-Guidelines)
- [Integration-Testing](Integration-Testing)

@ -4,12 +4,14 @@ This page documents the backend architecture of the Casino Gaming Platform.
## Tech Stack ## Tech Stack
- **Framework**: Spring Boot (Java) - **Framework**: Spring Boot 3.5.0 with Java 23
- **Database**: PostgreSQL - **Database**: PostgreSQL 17.5 with JPA/Hibernate
- **Authentication**: Keycloak integration - **Authentication**: Custom JWT implementation + OAuth2 (GitHub, Google)
- **Build Tool**: Gradle - **Build Tool**: Gradle with Kotlin DSL
- **API Documentation**: OpenAPI/Swagger - **API Documentation**: SpringDoc OpenAPI (Swagger)
- **Payment Processing**: Stripe API - **Payment Processing**: Stripe API with webhook support
- **Email**: Spring Mail with Mailpit for development
- **Code Quality**: Checkstyle integration
## Project Structure ## Project Structure
@ -19,58 +21,129 @@ The backend follows a domain-driven design approach with the following structure
src/ src/
├── main/ ├── main/
│ ├── java/ │ ├── java/
│ │ └── de/
│ │ └── szut/
│ │ └── casino/ │ │ └── casino/
│ │ ├── CasinoApplication.java │ │ ├── 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/ │ │ ├── config/
│ │ │ └── OpenAPIConfiguration.java │ │ │ ├── CorsConfig.java
│ │ │ └── OpenApiConfig.java
│ │ ├── dice/
│ │ │ ├── DiceController.java
│ │ │ └── DiceService.java
│ │ ├── deposit/ │ │ ├── deposit/
│ │ │ ├── DepositController.java │ │ │ ├── DepositController.java
│ │ │ └── dto/ │ │ │ └── DepositService.java
│ │ │ ├── AmountDto.java │ │ ├── email/
│ │ │ └── SessionIdDto.java │ │ │ ├── EmailController.java
│ │ ├── exceptionHandling/ │ │ │ └── EmailService.java
│ │ │ ├── ErrorDetails.java │ │ ├── exception/
│ │ │ ├── GlobalExceptionHandler.java │ │ │ └── GlobalExceptionHandler.java
│ │ │ └── ResourceNotFoundException.java │ │ ├── lootbox/
│ │ ├── health/ │ │ │ ├── LootboxController.java
│ │ │ └── HealthController.java │ │ │ └── LootboxService.java
│ │ ├── security/ │ │ ├── shared/
│ │ │ ├── KeycloakLogoutHandler.java │ │ │ ├── BettingService.java
│ │ │ └── KeycloakSecurityConfig.java │ │ │ ├── RandomizationService.java
│ │ │ └── entities/
│ │ ├── slots/
│ │ │ ├── SlotsController.java
│ │ │ └── SlotsService.java
│ │ ├── transaction/
│ │ │ ├── TransactionController.java
│ │ │ ├── TransactionService.java
│ │ │ └── TransactionEntity.java
│ │ └── user/ │ │ └── user/
│ │ ├── UserController.java │ │ ├── UserController.java
│ │ ├── UserEntity.java │ │ ├── UserEntity.java
│ │ ├── UserMappingService.java
│ │ ├── UserRepository.java │ │ ├── UserRepository.java
│ │ ├── UserService.java │ │ └── UserService.java
│ │ └── dto/
│ │ ├── CreateUserDto.java
│ │ ├── GetUserDto.java
│ │ └── KeycloakUserDto.java
│ └── resources/ │ └── resources/
│ └── application.properties │ ├── application.properties
│ └── templates/
│ └── email/
└── test/ └── test/
└── java/ └── java/
└── de/
└── szut/
└── casino/ └── casino/
├── Lf8StarterApplicationTests.java ├── balance/
├── health/ │ └── BalanceServiceTest.java
│ └── HealthControllerTest.java ├── coinflip/
└── user/ │ └── CoinflipServiceTest.java
└── UserControllerTest.java └── dice/
└── DiceServiceTest.java
``` ```
## Key Modules ## Key Modules
### User Management ### Game Modules
The user module handles: #### 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 - User registration and profile management
- Balance tracking - Balance tracking and updates
- User data retrieval and updates - Transaction history
- Account verification
Key components: Key components:
- `UserController`: REST endpoints for user operations - `UserController`: REST endpoints for user operations
@ -78,79 +151,195 @@ Key components:
- `UserRepository`: Data access layer - `UserRepository`: Data access layer
- `UserEntity`: Database entity for user data - `UserEntity`: Database entity for user data
### Deposit System #### Transaction System
Robust transaction handling:
The deposit module manages virtual currency deposits: - Betting transaction processing
- Integration with Stripe for payment processing - Win/loss calculations
- Creation of payment sessions - Transaction history tracking
- Verification of successful payments - Balance reconciliation
- Updating user balances
Key components: Key components:
- `DepositController`: REST endpoints for deposit operations - `TransactionController`: Transaction endpoints
- `AmountDto`: Data transfer object for deposit amounts - `TransactionService`: Transaction business logic
- `SessionIdDto`: Data transfer object for Stripe session IDs - `TransactionEntity`: Transaction data model
- `BettingService`: Shared betting logic
### Security #### Payment Processing
Stripe-integrated payment system:
The security module handles authentication and authorization: - Deposit session creation
- Integration with Keycloak for identity management - Webhook handling for payment confirmation
- JWT token validation - Balance updates
- Role-based access control - Payment verification
- Logout handling
Key components: Key components:
- `KeycloakSecurityConfig`: Configuration for Keycloak integration - `DepositController`: Payment endpoints
- `KeycloakLogoutHandler`: Handles user logout flow - `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 ### Exception Handling
Global exception handling for consistent error responses: Global exception handling for consistent error responses:
- `GlobalExceptionHandler`: Central exception handler - `GlobalExceptionHandler`: Central exception handler
- `ErrorDetails`: Standardized error response format - Standardized error response format
- `ResourceNotFoundException`: Custom exception for missing resources - Custom business logic exceptions
## API Endpoints ## API Endpoints
The backend exposes the following main 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 ### User API
- `GET /api/users/{id}`: Get user by ID - `GET /api/users/me`: Get current authenticated user
- `POST /api/users`: Create a new user - `PUT /api/users/me`: Update user profile
- `PUT /api/users/{id}`: Update user information - `GET /api/users/{id}/balance`: Get user balance
- `GET /api/users/me`: Get the current authenticated user
### 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 ### Deposit API
- `POST /api/deposits/create-session`: Create a Stripe payment session - `POST /api/deposits/create-session`: Create Stripe payment session
- `POST /api/deposits/verify`: Verify a completed payment - `POST /api/deposits/webhook`: Stripe webhook handler
- `GET /api/deposits/history`: Get deposit history
### Health API ### Email API
- `GET /api/health`: Health check endpoint - `POST /api/email/send-verification`: Send verification email
- `POST /api/email/resend-verification`: Resend verification email
## Authentication Flow ## Authentication Flow
1. User authenticates through the frontend application ### JWT Authentication
2. Frontend receives JWT tokens from Keycloak 1. User registers or logs in through the application
3. Backend validates tokens for API requests 2. Backend generates JWT access and refresh tokens
4. User info is extracted from validated tokens 3. Frontend stores tokens and includes access token in API requests
5. Authorization is enforced based on token roles 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 ## Database Schema
### User Table ### User Table
| Column | Type | Description | | Column | Type | Description |
|-------------|-------------|-----------------------------------| |------------------|-------------|-----------------------------------|
| id | UUID | Primary key | | id | BIGINT | Primary key |
| username | VARCHAR | User's username | | username | VARCHAR | User's username |
| email | VARCHAR | User's email address | | email | VARCHAR | User's email address |
| password_hash | VARCHAR | Hashed password |
| balance | DECIMAL | User's virtual currency balance | | 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 | | created_at | TIMESTAMP | Account creation timestamp |
| updated_at | TIMESTAMP | Last update 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 ## Development Workflow
1. Start the backend with: 1. Start the backend with:

64
Deployment-Guide.md Normal file

@ -0,0 +1,64 @@
# Deployment Guide
This page provides detailed instructions for deploying the Casino application to various environments.
## Prerequisites
- Docker and Docker Compose
- Access credentials for the deployment environment
- SSL certificates (for production)
## Development Environment
For local development deployment, see [Development-Environment-Setup](Development-Environment-Setup).
## Staging Environment
```bash
# Deploy to staging
./deploy.sh staging
```
## Production Environment
```bash
# Deploy to production
./deploy.sh production
```
## Docker Deployment
The application is containerized using Docker. The main components are:
1. Frontend (Angular)
2. Backend (Spring Boot)
3. Keycloak (Authentication)
4. PostgreSQL (Database)
See the docker-compose files in the `/docker` directory for the complete setup.
## Monitoring
After deployment, verify that all services are running properly:
```bash
# Check container status
docker ps
# View logs
docker-compose logs -f
```
## Rollback Procedure
In case of deployment issues:
```bash
# Rollback to previous version
./deploy.sh rollback
```
## Related Pages
- [Development-Environment-Setup](Development-Environment-Setup)
- [Troubleshooting](Troubleshooting)

63
External-Services.md Normal file

@ -0,0 +1,63 @@
# External Services
This page documents the external services and APIs integrated with the Casino application.
## Payment Processors
### Stripe
The application integrates with Stripe for payment processing.
- API Version: 2023-10-16
- Documentation: [Stripe API Docs](https://stripe.com/docs/api)
- Implementation: See [Payment-System](Payment-System) for details
### PayPal
Alternative payment processing through PayPal.
- API Version: v2
- Documentation: [PayPal Developer](https://developer.paypal.com/docs/api/overview/)
## Authentication
### Keycloak
Keycloak handles authentication and authorization.
- Version: 21.1
- Configuration: See [Authentication-and-Authorization](Authentication-and-Authorization)
## Game Providers
### Slot Provider API
- Endpoint: `https://api.slotprovider.com/v1`
- Integration: See [Game-Modules](Game-Modules) for details
### Table Games API
- Endpoint: `https://api.tablegames.com/v2`
- Integration: See [Game-Modules](Game-Modules) for details
## Monitoring
### Prometheus
- Endpoint: `http://prometheus:9090`
- Metrics exposed at `http://backend:8080/actuator/prometheus`
### Grafana
- Dashboard: `http://grafana:3000`
- Default dashboards for application monitoring
## Configuration
External service credentials are managed through environment variables. See the docker-compose files for reference.
## Related Pages
- [API-Documentation](API-Documentation)
- [Payment-System](Payment-System)
- [Authentication-and-Authorization](Authentication-and-Authorization)

86
Frontend-Testing.md Normal file

@ -0,0 +1,86 @@
# Frontend Testing
This page provides guidelines and best practices for testing the Angular frontend of the Casino application.
## Unit Testing
Unit tests for Angular components, services, and pipes are written using Jasmine and Karma.
### Running Unit Tests
```bash
# Run all unit tests
npm run test
# Run tests with coverage
npm run test:coverage
```
## Component Testing
Component tests verify that components render correctly and respond to user interactions as expected.
```typescript
describe('GameComponent', () => {
let component: GameComponent;
let fixture: ComponentFixture<GameComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [GameComponent]
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(GameComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
```
## End-to-End Testing
E2E tests are written using Cypress to test the application as a whole.
### Running E2E Tests
```bash
# Open Cypress test runner
npm run e2e
# Run all E2E tests headlessly
npm run e2e:ci
```
## Mocking Services
Use Angular's `HttpClientTestingModule` to mock HTTP requests:
```typescript
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [GameService]
});
```
## Test Coverage
Aim for at least 80% code coverage for all frontend components.
## Best Practices
1. Test component outputs and inputs
2. Mock external services
3. Test form validation
4. Verify component state changes
5. Test error handling
## Related Pages
- [Testing-Guidelines](Testing-Guidelines)
- [Frontend](Frontend)

@ -128,33 +128,68 @@ The application uses a consistent set of UI components:
## Development Workflow ## Development Workflow
1. Start the development server with proxy configuration 1. Install dependencies:
```bash
bun install
```
2. Start the development server with proxy configuration:
```bash ```bash
bun run start bun run start
``` ```
or This runs: `bunx @angular/cli serve --proxy-config src/proxy.conf.json`
```bash
bunx @angular/cli serve --proxy-config src/proxy.conf.json
```
2. The application will be available at http://localhost:4200 3. The application will be available at http://localhost:4200
3. API calls are proxied to the backend service running on http://localhost:8080 4. API calls are proxied to the backend service running on http://localhost:8080
4. For formatting code: 5. For code formatting:
```bash ```bash
bun run format bun run format
``` ```
or This runs: `prettier --write "src/**/*.{ts,html,css,scss}"`
```bash
prettier --write "src/**/*.{ts,html,css,scss}"
```
5. For linting: 6. For linting:
```bash ```bash
bun run lint bun run lint
``` ```
or This runs: `ng lint`
7. For building the application:
```bash ```bash
ng lint bun run build
``` ```
This creates an optimized production build
8. For running tests:
```bash
bun run test
```
This runs the Jasmine/Karma test suite
## Environment Configuration
The application uses environment files for configuration:
- `environment.ts`: Development configuration
- `environment.prod.ts`: Production configuration
Key configuration options:
- `apiUrl`: Backend API base URL
- `stripePublishableKey`: Stripe public key
- `oauth2Config`: OAuth2 provider settings
## Proxy Configuration
The `proxy.conf.json` file configures API proxying for development:
```json
{
"/api/*": {
"target": "http://localhost:8080",
"secure": false,
"changeOrigin": true,
"logLevel": "debug"
}
}
```

@ -8,120 +8,121 @@ The Casino Gaming Platform offers a variety of casino-style games, each implemen
## Available Games ## Available Games
### Poker
![Poker](/public/poker.webp)
A classic card game where players bet on the strength of their hands.
**Features:**
- Texas Hold'em variant
- Single player against AI opponents
- Multiple difficulty levels
- Realistic betting system
- Hand strength evaluator
- Game history tracking
**Technical Implementation:**
- Angular component-based UI
- Canvas-based card animation
- WebSocket connectivity for future multiplayer support
- AI logic implemented with configurable strategies
### Blackjack ### Blackjack
![Blackjack](/public/blackjack.webp) A classic card game where players compete against the dealer to get closest to 21 without going over.
Also known as 21, players compete against the dealer to get closest to 21 without going over.
**Features:** **Features:**
- Standard casino rules - Standard casino rules (hit, stand, double down, split)
- Betting system with chips - Real-time betting system with balance integration
- Split, double down, and insurance options - Professional dealer AI logic
- Detailed statistics tracking - Card animation and visual effects
- Adaptive dealer AI - Comprehensive game state management
- Transaction tracking for wins and losses
**Technical Implementation:** **Technical Implementation:**
- SVG-based card rendering - Angular component with TypeScript game logic
- State-based game progression - Card deck management with proper shuffling
- Configurable rule variations - State-based game progression (betting, dealing, playing, resolution)
- Strategy hints system - RESTful API integration for game actions
- Real-time balance updates
- Responsive design for mobile and desktop
**API Endpoints:**
- `POST /api/blackjack/start`: Initialize new game session
- `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
A simple heads or tails betting game with 50/50 odds.
**Features:**
- Simple heads/tails selection
- Configurable bet amounts
- Instant result revelation
- Animated coin flip with sound effects
- 2x multiplier on wins
- Transaction history integration
**Technical Implementation:**
- Lightweight Angular component
- CSS animations for coin flip effect
- Audio service integration for sound effects
- Secure random number generation on backend
- Real-time balance updates
**API Endpoints:**
- `POST /api/coinflip/flip`: Execute coinflip bet
### Dice
A dice rolling game with configurable betting options.
**Features:**
- Multiple dice configuration options
- Various betting strategies
- Animated dice rolling effects
- Statistical outcome tracking
- Configurable payout multipliers
- Sound effects and visual feedback
**Technical Implementation:**
- Angular component with dice animation
- Flexible betting system
- Backend randomization service
- Transaction processing
- Responsive UI design
**API Endpoints:**
- `POST /api/dice/roll`: Execute dice roll bet
### Slots ### Slots
![Slots](/public/slots.webp) A virtual slot machine with symbol-based payouts.
A virtual slot machine with various themes and payout structures.
**Features:** **Features:**
- Multiple slot machine themes - Multiple symbol types with different values
- Variable paylines - Animated reel spinning effects
- Bonus games and free spins - Payline calculation system
- Progressive jackpots - Configurable payout tables
- Animated winning combinations - Sound effects and visual celebrations
- Progressive betting options
**Technical Implementation:** **Technical Implementation:**
- CSS animation for reel spinning - CSS animation for reel spinning
- WebGL effects for special features - Symbol combination logic
- Pseudo-random number generation with auditable results - Payout calculation engine
- Configurable payout tables - Audio integration for immersive experience
- Responsive design for various screen sizes
### Plinko **API Endpoints:**
- `POST /api/slots/spin`: Execute slot machine spin
![Plinko](/public/plinko.webp)
A game where a ball drops through a field of pegs into prize slots.
**Features:**
- Realistic physics simulation
- Adjustable risk levels
- Multiple ball options
- Visual path tracking
- Slow-motion replays
**Technical Implementation:**
- Physics engine for realistic ball movement
- Canvas-based rendering
- Adjustable difficulty parameters
- Verifiable random drop patterns
### Liars Dice
![Liars Dice](/public/liars-dice.webp)
A bluffing dice game where players make increasingly higher bids about the dice in play.
**Features:**
- Single player against AI opponents
- Traditional rules with customizable variations
- Opponent personality types
- Bluff detection AI
- Detailed game history
**Technical Implementation:**
- 3D dice rendering
- Probability-based AI decision making
- Adaptive opponent difficulty
- Social features for future multiplayer support
### Lootboxes ### Lootboxes
![Lootboxes](/public/lootbox.webp) Virtual lootboxes with randomized rewards and rarity system.
A collection of virtual lootboxes with random in-game rewards.
**Features:** **Features:**
- Multiple box tiers and themes - Multiple lootbox tiers and types
- Animated unboxing experience - Animated opening experience
- Collection tracking - Rarity-based reward distribution
- Rare item showcase - Collection and inventory tracking
- Trading system (planned) - Visual reward reveals
- Purchase system integration
**Technical Implementation:** **Technical Implementation:**
- 3D box models with WebGL rendering - Angular component with opening animations
- Probability-based reward distribution - Probability-based reward generation
- Account-linked inventory system - Database inventory system
- Social sharing of rare acquisitions - Visual effects for rare items
- Integration with user balance system
**API Endpoints:**
- `GET /api/lootbox/types`: Get available lootbox types
- `POST /api/lootbox/open`: Open a lootbox
## Game Architecture ## Game Architecture
@ -179,26 +180,38 @@ To add a new game to the platform:
### Game Development Guidelines ### Game Development Guidelines
1. **Fairness**: 1. **Fairness and Security**:
- All games must use the platform's verifiable RNG - All games use server-side randomization service
- Game odds must be transparent and documented - Game odds are transparent and mathematically verified
- House edge must be clearly defined - House edge is clearly documented
- All transactions are atomic and auditable
2. **User Experience**: 2. **User Experience**:
- Consistent UI patterns across games - Consistent UI patterns using shared Angular components
- Clear instructions and help documentation - TailwindCSS for consistent styling
- Responsive design for all device types - Responsive design for mobile and desktop
- Accessibility compliance (WCAG 2.1 AA) - Audio feedback and visual effects
- Clear game instructions and rules
3. **Performance**: 3. **Performance Standards**:
- Games should initialize in under 3 seconds - Games initialize in under 2 seconds
- Animations should maintain 60fps - Animations maintain 60fps on target devices
- Games should gracefully degrade on lower-end devices - Optimized bundle sizes
- Lazy loading for game modules
4. **State Management**: 4. **Technical Requirements**:
- Games must handle disconnections gracefully - TypeScript strict mode compliance
- Game state should be recoverable - Comprehensive error handling
- Critical operations must be atomic - Real-time balance updates
- Transaction rollback capabilities
- Cross-browser compatibility
5. **Code Quality**:
- ESLint and Prettier formatting
- Checkstyle compliance (backend)
- Unit test coverage requirements
- Code review mandatory
- Documentation standards
## Transaction Flow ## Transaction Flow
@ -219,7 +232,22 @@ All game transactions:
- Are cryptographically signed - Are cryptographically signed
- Can be audited by administrators - Can be audited by administrators
## Testing and Validation ## Testing and Quality Assurance
### Current Testing Coverage
Implemented tests for core game functionality:
#### Backend Testing
- **Balance Service Tests**: Atomic transaction testing
- **Coinflip Service Tests**: Randomization and payout validation
- **Dice Service Tests**: Game logic and outcome verification
- **User Service Tests**: Authentication and profile management
#### Frontend Testing
- **Component Unit Tests**: Jasmine/Karma test suite
- **Service Integration Tests**: API interaction testing
- **UI/UX Testing**: Manual testing across devices
### Game Testing Requirements ### Game Testing Requirements
@ -228,41 +256,125 @@ All games must include:
2. **Integration tests** for frontend-backend interactions 2. **Integration tests** for frontend-backend interactions
3. **Performance tests** for animation and rendering 3. **Performance tests** for animation and rendering
4. **Fairness tests** verifying expected return to player (RTP) 4. **Fairness tests** verifying expected return to player (RTP)
5. **Usability tests** with representative users 5. **Security tests** for exploit prevention
### Validation Process ### Quality Assurance Process
Before release, each game undergoes: Before release, each game undergoes:
1. Code review by senior developers 1. Automated test suite execution
2. Mathematical verification of odds 2. Code review by development team
3. Security audit for potential exploits 3. Mathematical verification of odds and payouts
4. Accessibility evaluation 4. Security audit for potential vulnerabilities
5. Performance profiling on target devices 5. Cross-browser and device compatibility testing
6. Performance profiling and optimization
## Game Architecture
### Shared Game Infrastructure
All games share common infrastructure components:
#### Balance Management
- Centralized balance service
- Atomic transaction processing
- Real-time balance updates
- Insufficient funds validation
#### Audio System
- Game-specific sound effects
- Background music support
- Volume controls
- Browser audio API integration
#### Transaction Processing
- Comprehensive transaction logging
- Win/loss calculation
- Historical tracking
- Audit trail maintenance
#### Security Features
- Server-side randomization
- Bet validation
- Balance verification
- Anti-cheat measures
### Game Development Pattern
Each game follows a consistent development pattern:
1. **Frontend Component**:
- Game UI and animations
- User input handling
- State management
- API integration
2. **Backend Service**:
- Game logic implementation
- Random number generation
- Result calculation
- Transaction processing
3. **Database Integration**:
- Game session tracking
- Transaction recording
- User statistics
- Audit logging
## Future Game Roadmap ## Future Game Roadmap
Planned additions to the game library: Planned additions to the game library:
1. **Roulette**: European and American variants 1. **Poker**: Texas Hold'em implementation
2. **Craps**: Full-featured dice game 2. **Roulette**: European and American variants
3. **Baccarat**: Card game with simple betting 3. **Craps**: Full-featured dice game
4. **Video Poker**: Multiple variants 4. **Baccarat**: Card game with banker/player betting
5. **Multiplayer Poker**: Real-time tables with multiple players 5. **Video Poker**: Jacks or Better and variants
6. **Multiplayer Features**: Real-time multiplayer games
7. **Tournament Mode**: Competitive gaming events
## Development Tools and Build Process
### Build System
- **Frontend**: Angular CLI with Bun package manager
- **Backend**: Gradle with Kotlin DSL
- **Code Quality**: ESLint, Prettier, Checkstyle
- **Testing**: Jasmine/Karma (frontend), JUnit 5 (backend)
### Development Workflow
1. Feature development in isolated branches
2. Automated testing with every commit
3. Code review and quality checks
4. Integration testing
5. Deployment through CI/CD pipeline
### Performance Monitoring
- Game performance metrics
- User engagement analytics
- Error tracking and logging
- Real-time system monitoring
## Support and Maintenance ## Support and Maintenance
### Game Updates ### Continuous Integration
Games receive regular updates for: - Automated testing on pull requests
- Bug fixes - Code quality enforcement
- Performance improvements - Security vulnerability scanning
- New features and content - Performance regression testing
- Seasonal themes and events
### Support Process ### Release Management
For issues with specific games: - Semantic versioning
1. Users report issues through the in-game support interface - Automated release notes
2. Support tickets are categorized by game and issue type - Rollback capabilities
3. Development team prioritizes fixes based on impact - Feature flag management
4. Updates are deployed in the next release cycle
### Monitoring and Analytics
- Game session tracking
- User behavior analytics
- Performance metrics
- Error rate monitoring

87
Git-Workflow.md Normal file

@ -0,0 +1,87 @@
# Git Workflow
This page outlines the Git workflow used for the Casino project.
## Branching Strategy
We follow a modified Git Flow strategy:
- `main`: Production-ready code
- `develop`: Integration branch for features
- `feature/*`: Feature branches
- `bugfix/*`: Bug fix branches
- `release/*`: Release preparation branches
- `hotfix/*`: Urgent fixes for production
## Creating a New Feature
```bash
# Start from develop branch
git checkout develop
git pull
# Create a new feature branch
git checkout -b feature/new-feature-name
```
## Commit Guidelines
Follow conventional commits pattern:
```
<type>(<scope>): <description>
[optional body]
[optional footer]
```
Types:
- feat: New feature
- fix: Bug fix
- docs: Documentation only changes
- style: Changes that do not affect the meaning of the code
- refactor: Code change that neither fixes a bug nor adds a feature
- test: Adding or modifying tests
- chore: Changes to the build process or auxiliary tools
Example:
```
feat(auth): add keycloak integration
Implements Keycloak authentication for user management.
Closes #123
```
## Pull Requests
1. Push your branch to the remote repository
2. Create a pull request to the `develop` branch
3. Request reviews from at least two team members
4. Address review comments
5. Merge only when all checks pass
## Code Review Checklist
- Does the code follow our [Coding-Standards](Coding-Standards)?
- Are there sufficient tests?
- Is the documentation updated?
- Do all CI checks pass?
- Does the implementation match the requirements?
## Merge Strategy
We use squash merging for feature branches to keep the history clean:
```bash
# Squash merge a feature branch to develop
git checkout develop
git merge --squash feature/new-feature
git commit -m "feat(component): add new feature"
```
## Related Pages
- [Coding-Standards](Coding-Standards)
- [Development-Environment-Setup](Development-Environment-Setup)

90
Glossary.md Normal file

@ -0,0 +1,90 @@
# Glossary
This page provides definitions for common terms used throughout the Casino application.
## A
### Authentication
The process of verifying the identity of a user, typically through username/password or other credentials.
### Authorization
The process of determining what actions a user is allowed to perform after they are authenticated.
## B
### Backend
The server-side components of the application that handle business logic, data storage, and API endpoints.
### Bet
A wager placed by a user on a game with an uncertain outcome.
## C
### Casino Chip
Virtual currency used within the platform for placing bets and receiving winnings.
### CI/CD
Continuous Integration/Continuous Deployment - automated processes for testing and deploying code changes.
## D
### Docker
A platform used to develop, ship, and run applications inside containers.
### DTO (Data Transfer Object)
Objects used to transfer data between subsystems of the application.
## F
### Frontend
The client-side components of the application that users interact with directly in their browsers.
## G
### Game Module
A self-contained component that implements a specific casino game (slots, poker, etc.).
### GGR (Gross Gaming Revenue)
The difference between the amount of money players wager minus the amount that they win.
## J
### JWT (JSON Web Token)
A compact, URL-safe means of representing claims to be transferred between two parties.
## K
### Keycloak
An open source identity and access management solution used for authentication.
## P
### Payment Processor
A third-party service that handles financial transactions between users and the platform.
### Progressive Jackpot
A jackpot that increases incrementally as players make bets.
## R
### RNG (Random Number Generator)
A system used to generate a sequence of numbers that cannot be reasonably predicted.
### RTP (Return to Player)
The percentage of wagered money that a game returns to players over time.
## S
### Session
A period of continuous user activity on the platform.
## W
### Wallet
A virtual account that holds a user's funds within the platform.
## Related Pages
- [API-Documentation](API-Documentation)
- [Game-Modules](Game-Modules)
- [Payment-System](Payment-System)

42
Home.md

@ -4,36 +4,41 @@ Welcome to the Casino Gaming Platform wiki. This comprehensive guide provides do
## 🎮 Project Overview ## 🎮 Project Overview
The Casino Gaming Platform is an online gaming system offering various casino-style games with virtual currency support. The platform features a modern tech stack with Angular frontend, Spring Boot backend, and complete user authentication via Keycloak. The Casino Gaming Platform is an online gaming system offering various casino-style games with virtual currency support. The platform features a modern tech stack with Angular 20 frontend, Spring Boot 3.5 backend with Java 23, and hybrid authentication system using JWT tokens and OAuth2 integration.
### Features ### Features
- Multiple casino games: Poker, Blackjack, Slots, Plinko, Liars Dice, and Lootboxes - Multiple casino games: Blackjack, Coinflip, Dice, Slots, and Lootboxes
- User authentication and account management via Keycloak - User authentication with JWT tokens and OAuth2 (GitHub, Google)
- Virtual currency deposit system using Stripe payments - Virtual currency deposit system using Stripe payments
- Transaction history tracking - Transaction history tracking with complete audit trail
- Responsive modern UI built with Angular and TailwindCSS - Audio system with sound effects for immersive gameplay
- Responsive modern UI built with Angular 20 and TailwindCSS v4
- Email verification and password recovery system
## 🏗️ Technical Architecture ## 🏗️ Technical Architecture
### Frontend (Angular) ### Frontend (Angular 20)
The frontend is built with Angular 18, providing a responsive and modern user interface for the casino gaming experience. It uses: The frontend is built with Angular 20 (latest), providing a responsive and modern user interface for the casino gaming experience. It uses:
- **TailwindCSS** for styling and consistent design patterns - **TailwindCSS v4.0.3** for styling and consistent design patterns
- **Keycloak Integration** for authentication - **JWT Authentication** with OAuth2 social login support
- **Stripe Payment Integration** for virtual currency deposits - **Stripe.js Integration** for virtual currency deposits
- **Modal Animation Service** for consistent UI transitions - **GSAP & CountUp.js** for animations and enhanced UX
- **FontAwesome** for icons and visual elements
[Frontend Documentation](Frontend) [Frontend Documentation](Frontend)
### Backend (Spring Boot) ### Backend (Spring Boot 3.5)
The backend is built on Spring Boot (Java), providing robust API endpoints for game functionality, user management, and transaction processing. Key components include: The backend is built on Spring Boot 3.5 with Java 23, providing robust API endpoints for game functionality, user management, and transaction processing. Key components include:
- **PostgreSQL Database** for data persistence - **PostgreSQL 17.5** for data persistence with JPA/Hibernate
- **Keycloak Integration** for authentication/authorization - **JWT Authentication** with custom implementation + OAuth2 providers
- **Stripe API** for payment processing - **Stripe API** for payment processing with webhook support
- **SpringDoc OpenAPI** for comprehensive API documentation
- **Spring Mail** with Mailpit for development email testing
[Backend Documentation](Backend) [Backend Documentation](Backend)
@ -41,8 +46,9 @@ The backend is built on Spring Boot (Java), providing robust API endpoints for g
The entire application stack is containerized using Docker, making deployment and scaling straightforward. The infrastructure includes: The entire application stack is containerized using Docker, making deployment and scaling straightforward. The infrastructure includes:
- **PostgreSQL Databases** (application and Keycloak) - **PostgreSQL Database** with persistent volumes
- **Keycloak Authentication Server** - **Mailpit Email Server** for development email testing
- **Gradle Build System** with Kotlin DSL and Checkstyle integration
## 🚀 Getting Started ## 🚀 Getting Started

125
Integration-Testing.md Normal file

@ -0,0 +1,125 @@
# Integration Testing
This page covers the integration testing strategy for the Casino application.
## Overview
Integration tests verify that different components of the system work together correctly. They test the interaction between:
- Backend services
- Database access
- External APIs
- Frontend components (where applicable)
## Backend Integration Tests
Backend integration tests focus on testing the interaction between multiple backend components and external services.
### Spring Boot Integration Tests
```java
@SpringBootTest
@AutoConfigureMockMvc
public class GameServiceIntegrationTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private ExternalGameProvider externalGameProvider;
@Test
public void testCreateGame() throws Exception {
// Arrange
when(externalGameProvider.initialize()).thenReturn(true);
// Act & Assert
mockMvc.perform(post("/api/games")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"gameType\":\"SLOTS\",\"betAmount\":10}"))
.andExpect(status().isCreated())
.andExpect(jsonPath("$.gameId").exists());
}
}
```
## End-to-End Testing
E2E tests simulate real user scenarios across the entire application stack.
### Running E2E Tests
```bash
# Backend and frontend E2E tests
./gradlew e2eTest
```
## Database Integration
Tests involving database operations:
```java
@DataJpaTest
public class UserRepositoryTest {
@Autowired
private UserRepository userRepository;
@Test
public void testFindByUsername() {
// Arrange
User user = new User();
user.setUsername("testuser");
user.setEmail("test@example.com");
userRepository.save(user);
// Act
User found = userRepository.findByUsername("testuser");
// Assert
assertNotNull(found);
assertEquals("test@example.com", found.getEmail());
}
}
```
## API Contract Testing
Using Spring Cloud Contract to ensure API compatibility:
```groovy
Contract.make {
description "Should return a user by ID"
request {
method GET()
url "/api/users/1"
}
response {
status 200
headers {
contentType applicationJson()
}
body([
"id": 1,
"username": "testuser",
"email": "test@example.com"
])
}
}
```
## Test Data Management
Integration tests should:
1. Set up their own test data
2. Clean up after test execution
3. Be independent and idempotent
## Related Pages
- [Backend-Testing](Backend-Testing)
- [Frontend-Testing](Frontend-Testing)
- [Testing-Guidelines](Testing-Guidelines)