Built a Secure Backend for a Banking App Using Django in 15 Days | by Samuel Getachew | Sep, 2024 | Python in Plain English

Source: How I Built a Secure Backend for a Banking App Using Django in 15 Days | by Samuel Getachew | Sep, 2024 | Python in Plain English

Published in

Python in Plain English

5 min read

Sep 24, 2024

4

How I Built a Secure Backend for a Banking App Using Django in 15 Days

Building a secure backend for a banking application in a short time frame can sound like a daunting task. However, using Django, a high-level Python web framework, I was able to develop a robust and secure backend in just 15 days. In this article, I will walk you through my journey, share some useful tips, and provide detailed code snippets to help you get started if you are aiming for something similar. This article is beginner-friendly but also contains advanced techniques to help more experienced developers.

Why Django for a Banking App?

Django is known for its rapid development capabilities, security features, and its “batteries-included” philosophy. It comes with built-in tools for handling common security issues, such as SQL injection, cross-site scripting (XSS), and cross-site request forgery (CSRF). These are crucial when building applications like banking systems, where security is non-negotiable.

Day 1–3: Planning and Initial Setup

The first three days were dedicated to planning and setting up the project. A secure backend doesn’t just mean securing the code but also thinking through the architecture, identifying potential vulnerabilities, and deciding on the appropriate technologies.

Steps I took:

  1. Defined the App Requirements:
  • User authentication (Login, Logout, Password Reset)
  • Account management (Checking balance, viewing transactions)
  • Secure fund transfers between users
  • Integration with external APIs for financial services
  • Admin dashboard for monitoring transactions

2. Chose Django Rest Framework (DRF) for creating the backend API.

3. Setup Django:

django-admin startproject banking_app
cd banking_app
python manage.py startapp accounts

4. Installed necessary libraries:

  • Django Rest Framework for API development
  • Django REST Auth and allauth for user authentication
  • django-environ for managing environment variables
pip install djangorestframework django-rest-auth django-allauth django-environ

Day 4–6: User Authentication and Authorization

Security begins with a solid authentication system. For this banking app, I implemented a robust user authentication system using Django’s built-in authentication features along with the Django Rest Auth package.

Key Features:

  • Token-Based Authentication using JSON Web Tokens (JWT).
  • Password Reset and Change functionalities using DRF.
  • Role-Based Access Control (RBAC) to assign different permissions to users (e.g., users, admins).

Sample Code: JWT Authentication Setup

# settings.py
INSTALLED_APPS += [
    'rest_framework',
    'rest_framework.authtoken',
    'dj_rest_auth',
]

# Add JWT authentication settings
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ],
}

# In urls.py
from dj_rest_auth.views import LoginView, LogoutView
from django.urls import path

urlpatterns = [
    path('api/login/', LoginView.as_view(), name='login'),
    path('api/logout/', LogoutView.as_view(), name='logout'),
]

Day 7–9: Building Core Features (Account Management & Transactions)

The core of any banking app lies in its ability to manage user accounts securely and handle transactions efficiently. During these days, I focused on building these essential features.

Account Management:

  • Users can view their account balance and transaction history.
  • Users can perform transactions such as transferring money to other users.

Secure Transactions:

  • Implemented strong validation checks to ensure that transfers are secure.
  • Added a Transaction PIN system, requiring users to authenticate sensitive operations with a unique PIN.

Sample Code: Secure Transaction API

from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from .models import Account, Transaction

class TransferFunds(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request):
        sender = request.user
        receiver_account = request.data.get('receiver_account')
        amount = request.data.get('amount')
        pin = request.data.get('pin')

        # Perform secure validation here
        if not sender.check_transaction_pin(pin):
            return Response({"error": "Invalid PIN"}, status=400)

        sender_account = Account.objects.get(user=sender)
        receiver = Account.objects.get(account_number=receiver_account)

        if sender_account.balance < amount:
            return Response({"error": "Insufficient funds"}, status=400)

        # Execute transaction
        sender_account.balance -= amount
        receiver.balance += amount
        Transaction.objects.create(
            sender=sender_account,
            receiver=receiver,
            amount=amount,
            status='completed'
        )
        sender_account.save()
        receiver.save()

        return Response({"message": "Transfer successful"}, status=200)

Day 10–12: Securing the Backend

Security is critical in a banking app, and Django provides many tools to help with this. Here’s what I focused on to secure the backend.

Key Security Measures Implemented:

  1. HTTPS Everywhere: I enforced HTTPS by redirecting all HTTP traffic to HTTPS.
  2. SQL Injection Prevention: Django ORM protects against SQL injection by default, but I added further validation checks for user input.
  3. Cross-Site Scripting (XSS) Protection: I ensured all forms and user inputs were properly sanitized.
  4. Cross-Site Request Forgery (CSRF) Protection: Django comes with built-in CSRF protection, which I configured properly for API endpoints.
  5. Environment Variables: Sensitive credentials like the database password, secret keys, and API tokens were managed using django-environ for secure environment variable handling.

Sample Code: Enforcing HTTPS

# settings.py
SECURE_SSL_REDIRECT = True
CSRF_COOKIE_SECURE = True
SESSION_COOKIE_SECURE = True

Day 13–14: External API Integration

To provide additional banking services like payments or external fund transfers, I integrated with third-party APIs. I chose a secure financial API to process payments and handle secure transfers to other banks.

Best Practices:

  • Used OAuth2 for secure authentication with third-party APIs.
  • Implemented Rate Limiting to prevent abuse of the API endpoints.

Sample Code: API Integration

import requests
from rest_framework.response import Response

class ExternalPayment(APIView):
    def post(self, request):
        payment_data = {
            "account_number": request.data.get('account_number'),
            "amount": request.data.get('amount'),
        }
        
        # Example of a POST request to a third-party API
        response = requests.post('https://api.bank.com/payments', json=payment_data, headers={
            'Authorization': f'Bearer {request.user.oauth_token}'
        })

        if response.status_code == 200:
            return Response({"message": "Payment successful"}, status=200)
        return Response({"error": "Payment failed"}, status=response.status_code)

Day 15: Final Testing and Deployment

The final day was reserved for thorough testing and deployment. I used Postman to test all the API endpoints and ensured that proper error handling was in place.

Steps Taken for Testing:

  1. Unit Tests: Wrote unit tests for all critical functionalities like authentication and transactions.
  2. Security Testing: Conducted penetration testing to ensure the backend was secure against common threats.
  3. Deployment on AWS: Deployed the app on AWS with a PostgreSQL database, ensuring all environment variables were properly configured.

Conclusion

Building a secure backend for a banking app in 15 days is challenging but achievable with the right tools and planning. Django’s robust security features and quick development cycle make it an excellent choice for such projects. Whether you’re a beginner looking to build your first secure app or an advanced developer optimizing your current project, this guide offers actionable insights for your development journey.

Leave a Reply

The maximum upload file size: 500 MB. You can upload: image, audio, video, document, spreadsheet, interactive, other. Links to YouTube, Facebook, Twitter and other services inserted in the comment text will be automatically embedded. Drop file here