Skip to main content

Django security app - IP/email/country blocking, rate limiting, login tracking, auto-blocking

Project description

NAI Security

Django security package for IP blocking, country blocking, email blocking, rate limiting, and login tracking.

Features

  • IP Blocking - Block specific IPs manually or automatically
  • Country Blocking - Block/allow countries using GeoIP
  • Email Blocking - Block disposable emails and specific addresses
  • Domain Blocking - Block email domains (disposable, spam, etc.)
  • User Agent Blocking - Block bots, scrapers, attack tools
  • Rate Limiting - Custom rate limit rules per endpoint
  • Login History - Track user logins with anomaly detection
  • Auto-Blocking - Automatically block IPs/countries based on attack patterns
  • Security Logs - Comprehensive logging of all security events

Installation

pip install git+https://github.com/nematiai/nai-security.git

Or add to requirements.txt:

git+https://github.com/nematiai/nai-security.git@production#egg=nai-security

Docker Installation for Private Repositories

For a private GitHub repo, you need authentication in Docker. Two options:


Option 1: GitHub Personal Access Token (Recommended)

In requirements.txt:

git+https://${GITHUB_TOKEN}@github.com/nematiai/nai-security.git@main#egg=nai-security

In Dockerfile:

ARG GITHUB_TOKEN
RUN pip install git+https://${GITHUB_TOKEN}@github.com/nematiai/nai-security.git@main#egg=nai-security

In docker-compose.yml:

services:
  backend:
    build:
      args:
        GITHUB_TOKEN: ${GITHUB_TOKEN}

In .env:

GITHUB_TOKEN=ghp_xxxxxxxxxxxxxxxxxxxx

Option 2: SSH Key

In Dockerfile:

RUN mkdir -p /root/.ssh && \
    ssh-keyscan github.com >> /root/.ssh/known_hosts

COPY --from=secrets /run/secrets/ssh_key /root/.ssh/id_rsa
RUN chmod 600 /root/.ssh/id_rsa

RUN pip install git+ssh://git@github.com/nematiai/nai-security.git@main#egg=nai-security

Option 3: Copy Package Locally (Simplest for Private)

In Dockerfile:

COPY ./nai-security /nai-security
RUN pip install /nai-security

In docker-compose.yml:

services:
  backend:
    build:
      context: ..
      dockerfile: docker/Dockerfile

My recommendation: For private packages, use Option 1 (Token) or Option 3 (Copy locally).

Which do you prefer?

Quick Start

1. Add to INSTALLED_APPS

INSTALLED_APPS = [
    ...
    "nai_security",
]

2. Add Middleware

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    ...
    "nai_security.middleware.SecurityMiddleware",  # After SecurityMiddleware
    ...
    "nai_security.middleware.RateLimitLoggingMiddleware",  # Near the end
]

3. Configure Settings

# GeoIP database path
GEOIP_PATH = "/path/to/GeoLite2-Country.mmdb"

# Optional: Enable/disable middleware
SECURITY_MIDDLEWARE_ENABLED = True
RATELIMIT_MIDDLEWARE_ENABLED = True

4. Run Migrations

python manage.py makemigrations nai_security
python manage.py migrate

5. Download GeoIP Database

python manage.py download_geoip

Dependencies

Required:

  • Django >= 4.2
  • geoip2 >= 4.0
  • redis >= 4.0

Optional:

  • django-axes >= 6.0 (login attempt tracking)
  • django-ratelimit >= 4.0 (rate limiting)
  • django-import-export >= 3.0 (admin import/export)
  • django-unfold >= 0.10 (admin theme)

Install all optional dependencies:

pip install nai-security[all]

Install with import/export support:

pip install nai-security[import-export]

Environment Variables

Variable Default Description
GEOIP_PATH ./geoip/GeoLite2-Country.mmdb Path to GeoIP database
SECURITY_MIDDLEWARE_ENABLED True Enable security middleware
RATELIMIT_MIDDLEWARE_ENABLED True Enable rate limit logging

Management Commands

# Download GeoIP database
python manage.py download_geoip

# Sync disposable email domains and bad bot lists
python manage.py sync_security_lists
python manage.py sync_security_lists --domains-only
python manage.py sync_security_lists --bots-only

Celery Tasks

Add to your Celery beat schedule:

CELERY_BEAT_SCHEDULE = {
    'security-auto-blocks': {
        'task': 'security.process_auto_blocks',
        'schedule': crontab(minute='*/5'),  # Every 5 minutes
    },
    'security-cleanup-expired': {
        'task': 'security.cleanup_expired_blocks',
        'schedule': crontab(minute=0, hour='*'),  # Every hour
    },
    'security-sync-lists': {
        'task': 'security.sync_security_lists',
        'schedule': crontab(minute=0, hour=0, day_of_week=0),  # Weekly
    },
    'security-daily-report': {
        'task': 'security.generate_security_report',
        'schedule': crontab(minute=0, hour=6),  # Daily at 6 AM
    },
}

Models

Model Description
BlockedIP Blocked IP addresses
BlockedCountry Blocked countries
AllowedCountry Allowed countries (whitelist mode)
BlockedEmail Blocked email addresses
BlockedDomain Blocked email domains
BlockedUserAgent Blocked user agents
WhitelistedIP IPs that bypass all checks
RateLimitRule Custom rate limit rules
LoginHistory User login tracking
SecurityLog Security event logs
SecuritySettings Global settings (singleton)

License

MIT License

Author

Ali Nemati - NEMATI AI

Contributing

Contributions are welcome! Please open issues and pull requests on GitHub.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

nai_security-1.2.0.tar.gz (33.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

nai_security-1.2.0-py3-none-any.whl (43.1 kB view details)

Uploaded Python 3

File details

Details for the file nai_security-1.2.0.tar.gz.

File metadata

  • Download URL: nai_security-1.2.0.tar.gz
  • Upload date:
  • Size: 33.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.9

File hashes

Hashes for nai_security-1.2.0.tar.gz
Algorithm Hash digest
SHA256 8d517583d6beb9492d181e4890921cbd2e78249affd041e630a11cb876824d9e
MD5 cc419085b476615a6053fd6e1cd89b8a
BLAKE2b-256 ee2302a2df126795dbb389e8b79e6bc55880f19b2902252240c502d5fde37629

See more details on using hashes here.

File details

Details for the file nai_security-1.2.0-py3-none-any.whl.

File metadata

  • Download URL: nai_security-1.2.0-py3-none-any.whl
  • Upload date:
  • Size: 43.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.9

File hashes

Hashes for nai_security-1.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 ca382e613e23918c31e3865eafaa33071fa7d88723d855e294ef87888f06a30c
MD5 b94ce01aea9e369e70c2dcbdf200d0d5
BLAKE2b-256 36ae6e62111157587dc2cd5e43f6b43a2bfc69913de6ddd466544750d9e80b42

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page