Skip to content

ktsoev/Core-Banking-System

Repository files navigation

Core Banking System

Python FastAPI License Docker

Production-ready banking backend built with FastAPI. Provides complete banking operations including accounts, cards, transfers, and payments with multi-currency support.

Table of Contents

Features

  • User authentication with JWT tokens
  • Two-factor authentication via email
  • Bank accounts (checking, savings, currency)
  • Multi-currency support (RUB, USD, EUR)
  • Debit and credit card management
  • Money transfers by account ID or email
  • Payment processing via card or account
  • Transaction history and management
  • Daily spending limits
  • Account freezing and closing
  • Card blocking
  • Transaction cancellation within 24 hours

Technology Stack

  • FastAPI 0.104.1
  • PostgreSQL with SQLAlchemy ORM
  • Redis for caching and sessions
  • Alembic for database migrations
  • JWT authentication with bcrypt password hashing
  • Docker containerization

Quick Start

Setup

Copy the example environment file:

cp env.example .env

Edit .env file with your configuration:

DATABASE_URL=postgresql://postgres:postgres@localhost:5432/cbs_db
SECRET_KEY=your-secret-key-here
REDIS_URL=redis://localhost:6379/0

SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USER=[email protected]
SMTP_PASSWORD=your-app-password
SMTP_FROM=[email protected]

DEBUG=True

FRONTEND_URL=https://yoursite.com
BACKEND_URL=https://api.yoursite.com
CORS_ORIGINS=https://yoursite.com,https://www.yoursite.com

For production, set DEBUG=False to disable API documentation endpoints.

CORS configuration:

  • DEBUG=True - allows requests from all origins (*)
  • DEBUG=False + CORS_ORIGINS - uses comma-separated list of allowed origins
  • DEBUG=False + no CORS_ORIGINS - uses only FRONTEND_URL

Running with Docker

Start all services:

docker-compose up -d

The API will be available at http://localhost:8000

API documentation (development only): http://localhost:8000/docs

Running without Docker

Install dependencies:

pip install -r requirements.txt

Run database migrations:

alembic upgrade head

Start the application:

uvicorn app.main:app --reload

API Endpoints

The system provides 26 endpoints across 5 main categories:

Authentication (7 endpoints)

  • POST /auth/register - Register new user
  • POST /auth/login - Login and receive JWT tokens
  • POST /auth/2fa/send - Send 2FA code to email
  • POST /auth/2fa/verify - Verify 2FA code
  • POST /auth/2fa/enable - Enable two-factor authentication
  • POST /auth/2fa/disable - Disable two-factor authentication
  • GET /auth/me - Get current user information

Accounts (5 endpoints)

  • POST /accounts/ - Create new account
  • GET /accounts/ - List user accounts
  • GET /accounts/{id} - Get account details
  • PATCH /accounts/{id} - Update account status
  • GET /accounts/{id}/balance - Get account balance

Cards (5 endpoints)

  • POST /cards/ - Issue new card
  • GET /cards/ - List user cards
  • GET /cards/{id} - Get card details
  • PATCH /cards/{id} - Update card settings
  • POST /cards/{id}/block - Block card

Transactions (6 endpoints)

  • POST /transactions/transfer - Transfer money by account ID
  • POST /transactions/transfer/email - Transfer money by recipient email
  • GET /transactions/ - List all transactions
  • GET /transactions/{id} - Get transaction details
  • GET /transactions/account/{id} - Get account transactions
  • POST /transactions/{id}/cancel - Cancel transaction

Payments (3 endpoints)

  • POST /payments/ - Create payment
  • GET /payments/ - List payments
  • GET /payments/{id} - Get payment details

Full endpoint documentation with request/response examples: API_ENDPOINTS.md

Project Structure

CBS/
├── app/
│   ├── api/              # API endpoints
│   ├── core/             # Security and dependencies
│   ├── models/           # Database models
│   ├── schemas/          # Pydantic validation schemas
│   ├── services/         # Business logic layer
│   ├── middleware/       # Custom middleware
│   ├── utils/            # Utility functions
│   ├── config.py         # Application configuration
│   ├── database.py       # Database setup
│   └── main.py           # FastAPI application
├── alembic/              # Database migrations
├── logs/                 # Application logs
├── scripts/              # Helper scripts
├── docker-compose.yml
├── Dockerfile
├── requirements.txt
├── README.md
├── API_ENDPOINTS.md      # Detailed API documentation
├── DEPLOYMENT.md         # Production deployment guide
└── test_api.py           # API testing script

Database Migrations

Create new migration:

alembic revision --autogenerate -m "description"

Apply migrations:

alembic upgrade head

Rollback last migration:

alembic downgrade -1

Docker Commands

Start services:

docker-compose up -d

View logs:

docker-compose logs -f api

Stop services:

docker-compose down

Rebuild containers:

docker-compose up -d --build

Access PostgreSQL:

docker exec -it cbs_postgres psql -U postgres -d cbs_db

Access Redis:

docker exec -it cbs_redis redis-cli

Production Deployment

For complete production deployment guide with step-by-step instructions, see DEPLOYMENT.md.

Quick checklist:

  • Set DEBUG=False in .env
  • Generate strong SECRET_KEY with openssl rand -hex 32
  • Configure PostgreSQL with dedicated user and strong password
  • Configure Redis with authentication
  • Setup SSL/TLS certificates (Let's Encrypt)
  • Configure Nginx as reverse proxy
  • Enable firewall (allow only 80, 443, SSH)
  • Setup automated backups
  • Configure monitoring and alerts
  • Restrict CORS origins to your domain

The deployment guide covers:

  • Server preparation and security hardening
  • Docker-based deployment
  • Database and Redis configuration
  • SSL certificate setup with automatic renewal
  • Nginx configuration with rate limiting
  • Automated backup system
  • Monitoring and logging setup
  • Troubleshooting common issues
  • Performance tuning recommendations

Security

The system implements the following security measures:

  • Password hashing with bcrypt
  • JWT access and refresh tokens
  • Two-factor authentication codes stored in Redis with 10-minute expiration
  • Protected endpoints requiring authentication
  • Transaction authorization checks
  • Daily spending limits on cards
  • CVV hashing for card storage
  • Card number masking in responses

Environment Variables

Variable Description Required Default
DATABASE_URL PostgreSQL connection string Yes -
SECRET_KEY JWT signing key Yes -
REDIS_URL Redis connection string Yes -
SMTP_HOST Email server hostname Yes -
SMTP_PORT Email server port No 587
SMTP_USER Email username Yes -
SMTP_PASSWORD Email password Yes -
SMTP_FROM Sender email address Yes -
DEBUG Enable debug mode No False
FRONTEND_URL Frontend domain for CORS No https://yourdomain.com
BACKEND_URL Backend API domain No https://api.yourdomain.com
CORS_ORIGINS Comma-separated allowed origins No Uses FRONTEND_URL

CORS Behavior:

  • When DEBUG=True - allows all origins (*)
  • When DEBUG=False and CORS_ORIGINS is set - uses specified comma-separated list
  • When DEBUG=False and CORS_ORIGINS is empty - uses only FRONTEND_URL

Monitoring and Maintenance

Health check endpoint:

curl http://localhost:8000/health

Database backup:

docker exec cbs_postgres pg_dump -U postgres cbs_db > backup_$(date +%Y%m%d).sql

Check Redis connection:

docker exec -it cbs_redis redis-cli ping

Frontend Integration

Example authentication flow:

const registerResponse = await fetch('http://localhost:8000/auth/register', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    email: '[email protected]',
    password: 'securepassword',
    first_name: 'John',
    last_name: 'Doe'
  })
});

const loginResponse = await fetch('http://localhost:8000/auth/login', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    email: '[email protected]',
    password: 'securepassword'
  })
});

const { access_token } = await loginResponse.json();

const accountsResponse = await fetch('http://localhost:8000/accounts/', {
  headers: { 'Authorization': `Bearer ${access_token}` }
});

Key Features Implementation

Multi-Currency Support

The system supports RUB, USD, and EUR. Each currency requires a separate account. Transfers are only permitted between accounts of the same currency.

Card Management

Cards are automatically generated with valid card numbers. Card numbers are masked in API responses showing only the first and last four digits. CVV values are hashed and stored securely.

Transaction Processing

All transactions use PostgreSQL ACID guarantees. Balance checks occur before processing. Transfers can be cancelled within 24 hours of completion. Full transaction history is maintained.

Troubleshooting

Database Connection Issues

Verify DATABASE_URL in .env file. Ensure PostgreSQL is running:

docker-compose ps

Email Sending Issues

Verify SMTP credentials in .env file. For Gmail, use an App Password instead of account password.

API Documentation Not Available

Check DEBUG setting in .env file. Documentation endpoints are disabled when DEBUG=False.

Testing

Automated Testing

Run the comprehensive API test suite:

python test_api.py

Test against custom server:

python test_api.py https://api.example.com

The test script validates:

Health Check

  • Server availability and connectivity

Authentication

  • User registration
  • Login flow and JWT token generation
  • Current user retrieval
  • 2FA code sending

Account Management

  • Account creation, listing, details
  • Balance checking
  • Account status updates

Card Operations

  • Card issuance, listing, details
  • Card updates and blocking

Transactions

  • Transaction listing
  • Account-specific transactions
  • Transfer attempts and error handling

Payments

  • Payment listing and creation
  • Error validation

Test Output

Example:

[12:34:56] [PASS] GET /health: 200
[12:34:57] [PASS] POST /auth/register: 201
[12:34:58] [PASS] POST /auth/login: 200
============================================================
Total Tests: 20
Passed: 18
Failed: 2
Success rate: 90.0%
============================================================

Manual Testing with curl

Register user:

curl -X POST http://localhost:8000/auth/register \
  -H "Content-Type: application/json" \
  -d '{"email":"[email protected]","password":"password123","first_name":"Test","last_name":"User"}'

Login:

curl -X POST http://localhost:8000/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email":"[email protected]","password":"password123"}'

Use token:

curl http://localhost:8000/accounts/ \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"

Security and Logging

Security Logging

The system logs all critical security events to logs/ directory:

security.log - Security events (warnings and errors):

  • Failed authentication attempts
  • Invalid token usage
  • Rate limit violations
  • Suspicious activity patterns
  • Unauthorized access attempts

audit.log - All audit events (info level and above):

  • User registration
  • Successful logins
  • 2FA events
  • Transaction creation and cancellation
  • Payment processing
  • Card operations
  • Account status changes

Security Features

Rate Limiting

  • 100 requests per 60 seconds per IP address
  • Applies to all endpoints
  • Exceeded attempts logged
  • Returns 429 Too Many Requests

Security Headers All responses include:

  • X-Content-Type-Options: nosniff
  • X-Frame-Options: DENY
  • X-XSS-Protection: 1; mode=block
  • Strict-Transport-Security: max-age=31536000
  • Content-Security-Policy: default-src 'self'

Suspicious Activity Detection Automatic detection and logging of:

  • Multiple failed login attempts (5+ in 10 minutes)
  • Invalid token patterns
  • Unauthorized resource access
  • Rate limit violations

Data Protection

  • Password hashing with bcrypt
  • JWT access and refresh tokens
  • Card numbers masked in responses
  • CVV values hashed, never returned
  • 2FA codes in Redis with 10-minute expiration

Monitored Security Events

Critical events:

  • Failed login attempts
  • Invalid JWT tokens
  • 2FA failures
  • Unauthorized access attempts
  • Rate limit exceeded
  • Suspicious activity patterns

Audit events:

  • User registration
  • Successful authentication
  • Account creation
  • Card issuance and blocking
  • All financial transactions
  • Payment processing
  • Account status changes
  • Transaction cancellations

Log Monitoring

Watch security logs:

tail -f logs/security.log

Watch audit logs:

tail -f logs/audit.log

Production Checklist

  • Set DEBUG=False in environment
  • Generate new SECRET_KEY
  • Configure SMTP credentials
  • Restrict CORS to specific domains
  • Set up PostgreSQL in production mode
  • Configure Redis persistence
  • Enable SSL/TLS certificates
  • Configure firewall rules
  • Implement database backup strategy
  • Monitor security logs regularly
  • Set up automated alerts for suspicious activity

License

All rights reserved.

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages