views.py 4.38 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
import base64
import datetime
import json
import re

from django.conf import settings
from django.db import IntegrityError
from django.http import HttpResponse
from django.template.loader import render_to_string
from django.utils import translation
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

from tasks import *

from firewall.fw import *
from firewall.models import *
from one.tasks import SendMailTask

22

23 24 25 26 27 28 29 30 31 32 33 34
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)
            ReloadTask.delay()
        else:
            html = (_("Dear %s, you've signed in!") % request.user.username)
    else:
        html = _("Dear anonymous, you've not signed in yet!")
    return HttpResponse(html)

35

36 37 38 39
@csrf_exempt
@require_POST
def firewall_api(request):
    try:
40
        data = json.loads(base64.b64decode(request.POST["data"]))
41 42 43 44 45 46
        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"])
47 48
            obj.reason = data["reason"]
            obj.snort_message = data["snort_message"]
49 50
            if created:
                try:
51
                    obj.host = Host.objects.get(ipv4=data["ip"])
52 53 54
                    user = obj.host.owner
                    lang = user.person_set.all()[0].language
                    translation.activate(lang)
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
                    msg = render_to_string(
                        'mails/notification-ban-now.txt',
                        {
                            'user': user,
                            'bl': obj,
                            'instance:': obj.host.instance_set.get(),
                            'url': settings.CLOUD_URL
                        })
                    SendMailTask.delay(
                        to=obj.host.owner.email,
                        subject='[IK Cloud] %s' %
                        obj.host.instance_set.get().name,
                        msg=msg, sender=u'cloud@ik.bme.hu')
                except (Host.DoesNotExist, ValidationError,
                        IntegrityError, AttributeError):
70
                    pass
71 72 73 74

            modified = obj.modified_at + datetime.timedelta(minutes=1)
            now = datetime.dateime.utcnow().replace(tzinfo=utc)
            if obj.type == 'tempwhite' and modified < now:
75 76 77 78 79 80 81 82 83 84 85 86
                obj.type = 'tempban'
            obj.save()
            return HttpResponse(unicode(_("OK")))

        if not (data["vlan"] == "vm-net" or data["vlan"] == "war"):
            raise Exception(_("Only vm-net and war can be used."))

        data["hostname"] = re.sub(r' ', '_', data["hostname"])

        if command == "create":
            data["owner"] = "opennebula"
            owner = auth.models.User.objects.get(username=data["owner"])
87 88 89 90
            host = Host(hostname=data["hostname"],
                        vlan=Vlan.objects.get(name=data["vlan"]),
                        mac=data["mac"], ipv4=data["ip"], owner=owner,
                        description=data["description"], pub_ipv4=
91
                        Vlan.objects.get(name=data["vlan"]).snat_ip,
92
                        shared_ip=True)
93 94 95 96 97 98
            host.full_clean()
            host.save()

            host.enable_net()

            for p in data["portforward"]:
99 100
                host.add_port(proto=p["proto"], public=int(p["public_port"]),
                              private=int(p["private_port"]))
101 102 103 104 105

        elif command == "destroy":
            data["owner"] = "opennebula"
            print data["hostname"]
            owner = auth.models.User.objects.get(username=data["owner"])
106 107
            host = Host.objects.get(hostname=data["hostname"],
                                    owner=owner)
108 109 110 111 112 113 114 115 116 117 118

            host.delete()
        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")))