views.py 2.33 KB
Newer Older
1 2 3 4
import base64
import datetime
import json

Bach Dániel committed
5
from django.core.exceptions import ValidationError
6 7 8 9 10 11 12
from django.db import IntegrityError
from django.http import HttpResponse
from django.utils.timezone import utc
from django.utils.translation import ugettext_lazy as _
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST

Bach Dániel committed
13
from .tasks.local_tasks import reloadtask
Bach Dániel committed
14
from .models import Blacklist, Host
15

16

17 18 19 20 21
def reload_firewall(request):
    if request.user.is_authenticated():
        if request.user.is_superuser:
            html = (_("Dear %s, you've signed in as administrator!<br />"
                      "Reloading in 10 seconds...") % request.user.username)
Bach Dániel committed
22
            reloadtask.delay()
Bach Dániel committed
23
            reloadtask.delay('Vlan')
24 25 26 27 28 29
        else:
            html = (_("Dear %s, you've signed in!") % request.user.username)
    else:
        html = _("Dear anonymous, you've not signed in yet!")
    return HttpResponse(html)

30

31 32 33 34
@csrf_exempt
@require_POST
def firewall_api(request):
    try:
35
        data = json.loads(base64.b64decode(request.POST["data"]))
36 37 38 39 40 41
        command = request.POST["command"]
        if data["password"] != "bdmegintelrontottaanetet":
            raise Exception(_("Wrong password."))

        if command == "blacklist":
            obj, created = Blacklist.objects.get_or_create(ipv4=data["ip"])
42 43
            obj.reason = data["reason"]
            obj.snort_message = data["snort_message"]
44 45
            if created:
                try:
46 47 48
                    obj.host = Host.objects.get(ipv4=data["ip"])
                except (Host.DoesNotExist, ValidationError,
                        IntegrityError, AttributeError):
49
                    pass
50 51 52 53

            modified = obj.modified_at + datetime.timedelta(minutes=1)
            now = datetime.dateime.utcnow().replace(tzinfo=utc)
            if obj.type == 'tempwhite' and modified < now:
54
                obj.type = 'tempban'
Bach Dániel committed
55 56
            if obj.type != 'whitelist':
                obj.save()
57 58 59 60 61 62 63 64 65 66
            return HttpResponse(unicode(_("OK")))
        else:
            raise Exception(_("Unknown command."))

    except (ValidationError, IntegrityError, AttributeError, Exception) as e:
        return HttpResponse(_("Something went wrong!\n%s\n") % e)
    except:
        return HttpResponse(_("Something went wrong!\n"))

    return HttpResponse(unicode(_("OK")))