Skip to content

Commit

Permalink
Added blacklist to avoid web spamming against contact form
Browse files Browse the repository at this point in the history
  • Loading branch information
ruben69695 committed Jun 27, 2022
1 parent 991a9fa commit d8710b7
Show file tree
Hide file tree
Showing 4 changed files with 102 additions and 15 deletions.
14 changes: 13 additions & 1 deletion core/admin.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from django.contrib import admin
from .models import ContactMessage, Technology
from .models import ContactMessage, Technology, BlacklistedWord

# Register your models here.
class ContactMessageAdmin(admin.ModelAdmin):
Expand All @@ -14,5 +14,17 @@ def get_readonly_fields(self, request, obj=None):
defaults = ['name'] + defaults
return defaults

class BlacklistedWordAdmin(admin.ModelAdmin):
readonly_fields = ['created']

def get_readonly_fields(self, request, obj=None):
defaults = super().get_readonly_fields(request, obj=obj)
if obj: # if we are updating an object
defaults = ['word'] + defaults
return defaults



admin.site.register(ContactMessage, ContactMessageAdmin)
admin.site.register(Technology, TechnologyAdmin)
admin.site.register(BlacklistedWord, BlacklistedWordAdmin)
25 changes: 25 additions & 0 deletions core/migrations/0004_blacklistedword.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Generated by Django 4.0.4 on 2022-06-27 13:29

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('core', '0003_remove_technology_updated'),
]

operations = [
migrations.CreateModel(
name='BlacklistedWord',
fields=[
('word', models.CharField(max_length=30, primary_key=True, serialize=False, verbose_name='Word')),
('created', models.DateTimeField(auto_now=True, verbose_name='Created date')),
],
options={
'verbose_name': 'blacklisted word',
'verbose_name_plural': 'blacklisted words',
'ordering': ['word'],
},
),
]
12 changes: 12 additions & 0 deletions core/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,15 @@ class Meta:

def __str__(self):
return self.name

class BlacklistedWord(models.Model):
word = models.CharField(max_length=30, verbose_name="Word", primary_key=True)
created = models.DateTimeField(auto_now=True, verbose_name="Created date")

class Meta:
verbose_name = "blacklisted word"
verbose_name_plural ="blacklisted words"
ordering = ["word"]

def __str__(self):
return self.word
66 changes: 52 additions & 14 deletions core/views.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
import logging
from django.shortcuts import render, HttpResponse
from .forms import ContactMessageForm
from .services.emailService import EmailService
from .services.telegramService import TelegramService
from .models import BlacklistedWord
from django.conf import settings

logger = logging.getLogger(__name__)

# Create your views here.
def home(request):
return render(request, "core/home.html")
Expand All @@ -18,19 +22,53 @@ def createContactMessage(request):
if request.method == 'POST':
form = ContactMessageForm(request.POST)
if form.is_valid():
new_message = form.save()
fromEmail = settings.DEFAULT_FROM_EMAIL
subject = new_message.name + ', with email (' + new_message.email + ') needs your attention'
email_service = EmailService(fromEmail, [fromEmail], subject, new_message.message)
email_service.send()

if email_service.sended:
print('Email sended correctly')

if settings.TG_ACTIVE:
tg_service = TelegramService()
sent_ok = tg_service.sendContactNotification(new_message.name, new_message.email, new_message.message)
if sent_ok:
print('Telegram notification sended correctly')

# Before send check if message has to be banned
blacklist = BlacklistedWord.objects.all()
words = request.POST['name'].split() + request.POST['email'].split() + request.POST['message'].split()
banned, word, blackWord = _blacklistedWordFound(words, blacklist)

if not banned:
new_message = form.save()
fromEmail = settings.DEFAULT_FROM_EMAIL
subject = new_message.name + ', with email (' + new_message.email + ') needs your attention'

email_service = EmailService(fromEmail, [fromEmail], subject, new_message.message)
email_service.send()

if email_service.sended:
print('Email sended correctly')

if settings.TG_ACTIVE:
tg_service = TelegramService()
sent_ok = tg_service.sendContactNotification(new_message.name, new_message.email, new_message.message)
if sent_ok:
print('Telegram notification sended correctly')
else:
logger.warning(f'A contact message has been banned, reason: detected a black listed word (w={word},bw={blackWord})')

return render(request, "core/contact.html")

def _blacklistedWordFound(words: list, blacklistedWords: list):
found = False
word = ''
blackWord = ''
i = 0

while not found and i < len(words):

word = words[i]
j = 0

while not found and j < len(blacklistedWords):

blackWord = blacklistedWords[j].word
found = _findMatch(word, blackWord)
j += 1

i += 1

return (found, word, blackWord)

def _findMatch(word: str, blackWord: str):
return word.lower().strip() == blackWord.lower().strip()

0 comments on commit d8710b7

Please sign in to comment.