Production-ready banking backend built with FastAPI. Provides complete banking operations including accounts, cards, transfers, and payments with multi-currency support.
- Features
- Technology Stack
- Quick Start
- API Endpoints
- Project Structure
- Database Migrations
- Docker Commands
- Production Deployment
- Security
- Environment Variables
- Monitoring and Maintenance
- Frontend Integration
- Key Features Implementation
- Troubleshooting
- Testing
- Security and Logging
- Production Checklist
- License
- 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
- 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
Copy the example environment file:
cp env.example .envEdit .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.comFor 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 originsDEBUG=False+ noCORS_ORIGINS- uses onlyFRONTEND_URL
Start all services:
docker-compose up -dThe API will be available at http://localhost:8000
API documentation (development only): http://localhost:8000/docs
Install dependencies:
pip install -r requirements.txtRun database migrations:
alembic upgrade headStart the application:
uvicorn app.main:app --reloadThe system provides 26 endpoints across 5 main categories:
POST /auth/register- Register new userPOST /auth/login- Login and receive JWT tokensPOST /auth/2fa/send- Send 2FA code to emailPOST /auth/2fa/verify- Verify 2FA codePOST /auth/2fa/enable- Enable two-factor authenticationPOST /auth/2fa/disable- Disable two-factor authenticationGET /auth/me- Get current user information
POST /accounts/- Create new accountGET /accounts/- List user accountsGET /accounts/{id}- Get account detailsPATCH /accounts/{id}- Update account statusGET /accounts/{id}/balance- Get account balance
POST /cards/- Issue new cardGET /cards/- List user cardsGET /cards/{id}- Get card detailsPATCH /cards/{id}- Update card settingsPOST /cards/{id}/block- Block card
POST /transactions/transfer- Transfer money by account IDPOST /transactions/transfer/email- Transfer money by recipient emailGET /transactions/- List all transactionsGET /transactions/{id}- Get transaction detailsGET /transactions/account/{id}- Get account transactionsPOST /transactions/{id}/cancel- Cancel transaction
POST /payments/- Create paymentGET /payments/- List paymentsGET /payments/{id}- Get payment details
Full endpoint documentation with request/response examples: API_ENDPOINTS.md
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
Create new migration:
alembic revision --autogenerate -m "description"Apply migrations:
alembic upgrade headRollback last migration:
alembic downgrade -1Start services:
docker-compose up -dView logs:
docker-compose logs -f apiStop services:
docker-compose downRebuild containers:
docker-compose up -d --buildAccess PostgreSQL:
docker exec -it cbs_postgres psql -U postgres -d cbs_dbAccess Redis:
docker exec -it cbs_redis redis-cliFor complete production deployment guide with step-by-step instructions, see DEPLOYMENT.md.
Quick checklist:
- Set
DEBUG=Falsein.env - Generate strong
SECRET_KEYwithopenssl 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
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
| 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=FalseandCORS_ORIGINSis set - uses specified comma-separated list - When
DEBUG=FalseandCORS_ORIGINSis empty - uses onlyFRONTEND_URL
Health check endpoint:
curl http://localhost:8000/healthDatabase backup:
docker exec cbs_postgres pg_dump -U postgres cbs_db > backup_$(date +%Y%m%d).sqlCheck Redis connection:
docker exec -it cbs_redis redis-cli pingExample 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}` }
});The system supports RUB, USD, and EUR. Each currency requires a separate account. Transfers are only permitted between accounts of the same currency.
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.
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.
Verify DATABASE_URL in .env file. Ensure PostgreSQL is running:
docker-compose psVerify SMTP credentials in .env file. For Gmail, use an App Password instead of account password.
Check DEBUG setting in .env file. Documentation endpoints are disabled when DEBUG=False.
Run the comprehensive API test suite:
python test_api.pyTest against custom server:
python test_api.py https://api.example.comThe 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
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%
============================================================
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"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
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: nosniffX-Frame-Options: DENYX-XSS-Protection: 1; mode=blockStrict-Transport-Security: max-age=31536000Content-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
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
Watch security logs:
tail -f logs/security.logWatch audit logs:
tail -f logs/audit.log- Set
DEBUG=Falsein 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
All rights reserved.