Metadata-Version: 2.4
Name: django-sanitizers
Version: 0.1.3
Summary: A Django middleware that sanitizes incoming request data to prevent XSS.
Author-email: Jenil Mistry <jenilmistryhq@users.noreply.github.com>
License: MIT License
        
        Copyright (c) 2025 jenilmistryhq
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
        
Classifier: Programming Language :: Python :: 3
Classifier: Framework :: Django
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: django>=3.2
Requires-Dist: bleach>=6.0.0
Dynamic: license-file


# django-sanitizer

A lightweight, configurable Django middleware that **automatically sanitizes all incoming request data** (JSON, form-data, query params) to protect your application against **XSS, HTML injection, and unsafe attributes**.

Built with **Bleach**, easy to install, easy to extend, and safe by default.

---

## 🛡 How It Works

The middleware intercepts the request before it reaches your views:

1. Extracts request data (JSON, form-data, GET params)
2. Sanitizes all values using allowed tags + attributes
3. Places sanitized result in `request.sanitized_data`
4. Your view receives **only safe data**

This allows **cleaning without modifying Django internals**.

---

## 🚀 Features

* 🔒 Sanitizes **JSON bodies**, **form-data**, and **query parameters**
* 🧼 Removes unsafe HTML tags, scripts, event handlers (e.g., `onerror`)
* 🎯 Fully configurable via Django settings
* 📝 Optional HTML response sanitization
* 🛠 Zero configuration required — works out of the box
* 🧪 Comes with testing utilities and easy middleware integration

---

## 📦 Installation

```bash
pip install django-sanitizer
```

Or install your local dev version:

```bash
pip install -e .
```

---

## ⚙️ Setup

Add the middleware to your Django settings:

```python
MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django_sanitizers.middleware.SanitizerMiddleware",
    "django.middleware.common.CommonMiddleware",
    ...
]
```

---

## 🔧 Configuration Options (Optional)

Add to `settings.py` only if you want customization:

```python
SANITIZER_CONFIG = {
    # Define exactly which tags you want to KEEP
    'ALLOWED_TAGS': ['b', 'i', 'u', 'p', 'br'], 
    
    # Define allowed attributes (optional)
    'ALLOWED_ATTRIBUTES': {
        'a': ['href', 'title'],
        'img': ['src', 'alt']
    },
    
    # Security fields to skip
    'SKIP_FIELDS': {'password', 'password_confirmation', 'token', 'access_token', 'refresh_token','secret_key'},
    
    'STRIP': True
}
```

---

## 🧪 Example

### Request Body:

```json
{
  "bio": "<script>alert(1)</script><b>Hello</b>"
}
```

### Sanitized Output:

```json
{
  "bio": "<b>Hello</b>"
}
```

---

## 🧪 Django Views Example

### JSON Example Endpoint

```python
# views.py
from django.http import JsonResponse

def echo_json(request):
    return JsonResponse(request.sanitized_data)
```

### Form Example Endpoint

```python
def form_view(request):
    return JsonResponse(request.sanitized_data)
```

---

## 🧪 Testing in Postman

### For JSON:

* Method: POST
* URL: `/echo-json/`
* Headers: `Content-Type: application/json`
* Body (raw JSON):

```json
{"bio":"<img src=x onerror=alert(1)>hello"}
```

You should receive:

```json
{"bio":"hello"}
```

---

## 📁 Project Structure (Package Only)

```
django_sanitizer/
│
├── __init__.py
├── sanitizer.py
└── middleware.py
```

---

## 🛠 Development

```bash
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
pip install -e .
```

Run tests:

```bash
pytest
```

---

## ⭐ Support the Project

If this package helps you, please ⭐ star the repository on GitHub once published!
