0

In django, I think the better way to handle the XSS injection is when you save the object.
It is inside your models.py, and using strip_tags

If value is "<b>Joel</b> <button>is</button> a <span>slug</span>" the return value will be "Joel is a slug".

from django.db import models
from django.utils.html import strip_tags


class YourModelName(models.Model):

    def save(self, *args, **kwargs):

        # handle the xss injection
        for field in self._meta.fields:
            value = getattr(self, field.name)
            if isinstance(value, str):
                value_clean = strip_tags(value)
                setattr(self, field.name, value_clean)

        return super().save(*args, **kwargs)

Or if you want to specific html text element from rich text editor, you can also create a custom replacer, eg:

# app_name/utils/replacer.py

import re


def content_replacer(content):
    """
    function to clear the content with fixed text.
    :param `content` is string text from text editor
    :return `content` cleaned string.

    """
    if not content:
        return None

    # remove the xss injection
    content = re.sub(r"<script(.*)script>", '', content)
    content = re.sub(r"alert(.*)\)", '', content)
    content = re.sub(r"javascript:", '', content)

    return content

And then, in your models.py

from django.db import models
from app_name.utils.replacer import content_replacer


class YourModelName(models.Model):
    content = models.TextField()

    def save(self, *args, **kwargs):
        # handle the xss injection
        self.content = content_replacer(self.content)

        return super().save(*args, **kwargs)
xss security tricks django solution problem

Your Answer

blog comments powered by Disqus