def get_icon_for_namespace(namespace):
    """ Return the static path to the icon associated with given namespace
    """
    try:
        if namespace.count(':')>0:
            namespace = namespace.split(':')[0]
        icon = NamespaceIcon.objects.get(namespace=namespace)
    except Exception as e:
        return static('ns_icon/octalpus.png')
    return static('ns_icon/%s' % (icon.icon)) class IncidentForm(ModelForm):
    class Meta:
        model = Incident
        fields = ['incident_number', 'title', 'description', 'status', 'category', 'severity']
        widgets = {
            'incident_number': widgets.NumberInput(attrs={'class': 'form-control', 'readonly': True, 'required': True}),
            'title': widgets.TextInput(attrs={'class': 'form-control', 'placeholder': 'Provide a name for the incident or investigation', 'required': True}),
            'description': widgets.Textarea(attrs={'class': 'form-control', 'placeholder': 'What and when did it happened ...'}),
            'status': widgets.Select(attrs={'class': 'form-control'}),
            'category': widgets.Select(attrs={'class': 'form-control'}),
            'severity': widgets.Select(attrs={'class': 'form-control'}),
        } class ContactForm(ModelForm):
    class Meta:
        model = Contact
        fields = ["firstname", "lastname", "phone", "email", "description"]
        widgets = {
            'firstname': widgets.TextInput(attrs={'id': 'post_contact_firstname', 'class': 'form-control', 'placeholder': ''}),
            'lastname': widgets.TextInput(attrs={'id': 'post_contact_lastname', 'class': 'form-control', 'placeholder': ''}),
            'phone': widgets.TextInput(attrs={'id': 'post_contact_phone', 'class': 'form-control', 'placeholder': ''}),
            'email': widgets.EmailInput(attrs={'id': 'post_contact_email', 'class': 'form-control', 'placeholder': ''}),
            'description': widgets.Textarea(attrs={'id': 'post_contact_description', 'class': 'form-control', 'placeholder': 'What is this contact responsible for ...'}),
        } class HandlerForm(ModelForm):
    class Meta:
        model = Handler
        fields = ["firstname", "lastname", "phone", "email", "description"]
        widgets = {
            'firstname': widgets.TextInput(attrs={'id': 'post_handler_firstname', 'class': 'form-control', 'placeholder': ''}),
            'lastname': widgets.TextInput(attrs={'id': 'post_handler_lastname', 'class': 'form-control', 'placeholder': ''}),
            'phone': widgets.TextInput(attrs={'id': 'post_handler_phone', 'class': 'form-control', 'placeholder': ''}),
            'email': widgets.EmailInput(attrs={'id': 'post_handler_email', 'class': 'form-control', 'placeholder': ''}),
            'description': widgets.Textarea(attrs={'id': 'post_handler_description', 'class': 'form-control', 'placeholder': 'What is this handler responsible for ...'}),
        } class IncidentCommentForm(ModelForm):
    class Meta:
        model = IncidentComment
        fields = ['ctext']

    def __init__(self, *args, **kwargs):
        super(IncidentCommentForm, self).__init__(*args, **kwargs)
        self.fields['ctext'].widget.attrs.update({'class' : 'form-control', 'id': 'incidentComment'}) class Contact(models.Model):
    """Describe a contact person
    """
    firstname = models.CharField(max_length=255)
    lastname = models.CharField(max_length=255)
    phone = models.CharField(max_length=255, blank=True)
    email = models.EmailField(max_length=255)
    description = models.TextField(null=True, blank=True)

    class Meta:
        unique_together = (("firstname", "lastname", "email"),) class Handler(models.Model):
    """Describe an incident handler person
    """
    firstname = models.CharField(max_length=255)
    lastname = models.CharField(max_length=255)
    phone = models.CharField(max_length=255, blank=True)
    email = models.EmailField(max_length=255)
    description = models.TextField(null=True, blank=True)

    class Meta:
        unique_together = (("firstname", "lastname", "email"),) class Incident(models.Model):
    """Describe a security incident
    """
    incident_number = models.IntegerField(unique=True, default=random_incident_number)
    title = models.CharField(max_length=255, default="Unnamed Incident")
    description = models.TextField(null=True, blank=True)
    creation_time = models.DateTimeField(auto_now_add=True)
    last_modified = models.DateTimeField(auto_now=True)
    status = models.ForeignKey(Incident_Status, on_delete=models.CASCADE)
    category = models.ForeignKey(Incident_Category, on_delete=models.CASCADE)
    affected_assets = models.ManyToManyField(Asset, blank=True)
    tasks = models.ManyToManyField(Task, blank=True)
    incident_handler = models.ManyToManyField(Handler, blank=True, related_name="incident_handler")
    contacts = models.ManyToManyField(Contact, blank=True, related_name="contacts")
    severity_choices = (
                ('h', 'High'),
                ('m', 'Medium'),
                ('l', 'Low'),
            )
    severity = models.CharField(max_length=2, choices=severity_choices, default='m')

    def __unicode__(self):
        return u"%s" % (self.title) class IncidentComment(models.Model):
    ctext = models.TextField()
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    creation_time = models.DateTimeField(auto_now_add=True)
    incident_reference = models.ForeignKey(Incident, on_delete=models.CASCADE) class TemplateTask(models.Model):
    """Describe a template for a task to attach to an incident
    """
    name = models.CharField(max_length=255, default="Template Task")
    description = models.TextField(null=True, blank=True, default="Task Description") class Task(models.Model):
    """Describe a task to be performed
    """
    name = models.CharField(max_length=255, default="Yet another task")
    description = models.TextField(null=True, blank=True)
    creation_time = models.DateTimeField(auto_now_add=True)
    finish_time = models.DateTimeField(null=True, blank=True)
    status_choices = (
                ('op', 'Open'),
                ('do', 'Done'),
                ('ab', 'Aborted'),
            )
    status = models.CharField(max_length=2, choices=status_choices, default='op')
    responsible = models.ManyToManyField(Contact, blank=True)

    class Meta:
        ordering = ['-status'] class Incident_Status(models.Model):
    """Describe the status of an incident
    Prefilled with data
    """
    name = models.CharField(max_length=255, unique=True)
    description = models.TextField(null=True, blank=True)

    def __unicode__(self):
        return u"%s" % (self.name) def slicedict(d, s):
    return {k:v for k,v in d.iteritems() if k.startswith(s)}
import json
import datetime
from django.http import HttpResponseRedirect, HttpResponse
from django.urls import reverse
from django.shortcuts import render
from django.template import RequestContext
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from kraut_intel.utils import get_icon_for_namespace
from kraut_incident.forms import IncidentForm, ContactForm, HandlerForm, IncidentCommentForm
from kraut_incident.models import Contact, Handler, Incident, IncidentComment, TemplateTask, Task, Incident_Status
from kraut_incident.utils import slicedict
    if hasattr(request.user.userextension, 'namespaces'):
        context['usernamespace'] = request.user.userextension.namespaces.last().namespace.split(':')[0]
        context['namespaceicon'] = get_icon_for_namespace(request.user.userextension.namespaces.last().namespace)
    else:
        context['usernamespace'] = 'nospace'
        context['namespaceicon'] = static('ns_icon/octalpus.png')
    try:
        comments = IncidentComment.objects.filter(incident_reference=inc).order_by('-creation_time')
    except:
        comments = None
    context['comments'] = comments
    context['commentform'] = IncidentCommentForm()
    context['num_incident_handlers'] = inc.incident_handler.count()
    context['num_incident_contacts'] = inc.contacts.count()
    context['num_incident_tasks'] = inc.tasks.count()
    context['num_affected_assets'] = inc.affected_assets.count()
    if context['num_incident_tasks'] > 0:
        context['tab'] = 'incident_tasks'
    elif context['num_incident_contacts'] > 0:
        context['tab'] = 'incident_contacts'
    else:
        context['tab'] = 'incident_handler'
    return render(request, 'kraut_incident/incident_details.html', context)

@login_required
def delete_incident(request, incident_id):
    """Delete incident with given ID
    """
    context = {}
    try:
        inc = Incident.objects.get(id=incident_id)
    except Incident.DoesNotExist:
        messages.error(request, 'The requested incident does not exist!')
        return render(request, 'kraut_incident/incident_list.html', context)
    inc.delete()
    messages.info(request, 'The incident was deleted successfully!')
    return HttpResponseRedirect(reverse('incidents:list'))

@login_required
def create_handler(request):
    """This function is called from within the incident creation dialog to instantly add a new incident handler
    """
    context = {}
    if request.method == 'POST':
        handler_form = HandlerForm(request.POST)
        if handler_form.is_valid():
            new_handler = Handler.objects.get_or_create(**handler_form.cleaned_data)
            response_data = {'result': 'info', 'message': json.dumps({'info': [{'message': 'handler succesfully created!'}]})}
        else:
            response_data = {'result': 'danger', 'message': handler_form.errors.as_json()}
        return HttpResponse(json.dumps(response_data), content_type="application/json")
    else:
        return HttpResponse(json.dumps({"nothing to see": "this isn't happening"}), content_type="application/json")

@login_required
def create_contact(request):
    """This function is called from within the incident creation dialog to instantly add a new contact
    """
    context = {}
    if request.method == 'POST':
        contact_form = ContactForm(request.POST)
        if contact_form.is_valid():
            new_contact = Contact.objects.get_or_create(**contact_form.cleaned_data)
            response_data = {'result': 'info', 'message': json.dumps({'info': [{'message': 'contact succesfully created!'}]})}
        else:
            response_data = {'result': 'danger', 'message': contact_form.errors.as_json()}
        return HttpResponse(json.dumps(response_data), content_type="application/json")
    else:
        return HttpResponse(json.dumps({"nothing to see": "this isn't happening"}), content_type="application/json")

@login_required
def new_incident(request):
    context = {}
    if request.method == 'POST':
        ### {'status': <Incident_Status: Open>, 'incident_number': 4976401221, 'category': <Incident_Category: Investigation>, 'description': u'', 'title': u'Unnamed Incident'}
        incident_form = IncidentForm(request.POST)
        if incident_form.is_valid():
            # check if handler and contact given
            handler_dict = slicedict(request.POST, 'HandlerCheckBox')
            contact_dict = slicedict(request.POST, 'ContactCheckBox')
            if len(handler_dict)<=0:
                messages.error(request, 'Missing an incident handler!')
                return HttpResponseRedirect(reverse("incidents:new"))
            if len(contact_dict)<=0:
                messages.error(request, 'Missing an incident contact!')
                return HttpResponseRedirect(reverse("incidents:new"))
            new_incident = Incident(
                incident_number = incident_form.cleaned_data['incident_number'],
                title = incident_form.cleaned_data['title'],
                description = incident_form.cleaned_data['description'],
                status = incident_form.cleaned_data['status'],
                category = incident_form.cleaned_data['category'],
                severity = incident_form.cleaned_data['severity']
            )
            new_incident.save()
            for key in handler_dict:
                handler_id = handler_dict[key]
                try:
                    handler = Handler.objects.get(pk=handler_id)
                    new_incident.incident_handler.add(handler)
                except Handler.DoesNotExist:
                    messages.error(request, 'Failed getting incident handler with ID: %s' % (handler_id))
            for key in contact_dict:
                contact_id = contact_dict[key]
                try:
                    contact = Contact.objects.get(pk=contact_id)
                    new_incident.contacts.add(contact)
                except Contact.DoesNotExist:
                    messages.error(request, 'Failed getting incident contact with ID: %s' % (contact_id))
            new_incident.save()
            messages.info(request, "Incident successfully created!")
        return HttpResponseRedirect(reverse("incidents:new"))
    incident_form = IncidentForm(initial={'status': 1, 'category': 7})
    contact_form = ContactForm()
    handler_form = HandlerForm()
    context['formset'] = incident_form
    context['contact_form'] = contact_form
    context['handler_form'] = handler_form
    if hasattr(request.user.userextension, 'namespaces'):
        context['usernamespace'] = request.user.userextension.namespaces.last().namespace.split(':')[0]

        context['namespaceicon'] = get_icon_for_namespace(request.user.userextension.namespaces.last().namespace)