views.py 2.28 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 14
from .tasks import reloadtask
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()
23 24 25 26 27 28
        else:
            html = (_("Dear %s, you've signed in!") % request.user.username)
    else:
        html = _("Dear anonymous, you've not signed in yet!")
    return HttpResponse(html)

29

30 31 32 33
@csrf_exempt
@require_POST
def firewall_api(request):
    try:
34
        data = json.loads(base64.b64decode(request.POST["data"]))
35 36 37 38 39 40
        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"])
41 42
            obj.reason = data["reason"]
            obj.snort_message = data["snort_message"]
43 44
            if created:
                try:
45 46 47
                    obj.host = Host.objects.get(ipv4=data["ip"])
                except (Host.DoesNotExist, ValidationError,
                        IntegrityError, AttributeError):
48
                    pass
49 50 51 52

            modified = obj.modified_at + datetime.timedelta(minutes=1)
            now = datetime.dateime.utcnow().replace(tzinfo=utc)
            if obj.type == 'tempwhite' and modified < now:
53
                obj.type = 'tempban'
Bach Dániel committed
54 55
            if obj.type != 'whitelist':
                obj.save()
56 57 58 59 60 61 62 63 64 65
            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")))