class Assessment(models.Model):
    name = models.CharField(max_length=100)
    project = models.ForeignKey(Project, on_delete=models.CASCADE)
    added = models.DateTimeField(default=datetime.now)

    def __str__(self):  # __unicode__ on Python 2
        return self.name

    class Meta:
        ordering = ('name',) class Project(models.Model):
    name = models.CharField(max_length=100)
    added = models.DateTimeField(default=datetime.now)

    def __str__(self):  # __unicode__ on Python 2
        return self.name

    class Meta:
        ordering = ('name',) class Sh0t(models.Model):
    title = models.CharField(max_length=200)
    body = models.TextField(default="")
    assessment = models.ForeignKey(Assessment, null=True, on_delete=models.CASCADE)
    added = models.DateTimeField(default=datetime.now)
    severity = models.IntegerField(default=5, validators=[MinValueValidator(0), MaxValueValidator(5)])

    def __str__(self):  # __unicode__ on Python 2
        return self.title

    class Meta:
        ordering = ('severity','title',) class Flag(models.Model):
    title = models.CharField(max_length=100)
    note = models.TextField(default="")
    assessment = models.ForeignKey(Assessment, null=True, on_delete=models.CASCADE)
    done = models.BooleanField(default=False)
    added = models.DateTimeField(default=datetime.now)
    order = models.IntegerField(default=1)

    def __str__(self):  # __unicode__ on Python 2
        return self.title

    class Meta:
        ordering = ('title',) class Template(models.Model):
    name = models.CharField(max_length=100)
    body = models.TextField(default="")
    added = models.DateTimeField(default=datetime.now)

    def __str__(self):  # __unicode__ on Python 2
        return self.name

    class Meta:
        ordering = ('name',) class MethodologyMaster(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField(default="")
    order = models.IntegerField(default=0)
    created_by = models.ForeignKey(User, related_name="methodology_created_by", null=True, on_delete=models.CASCADE)
    created = models.DateTimeField(default=datetime.now)
    updated_by = models.ForeignKey(User, related_name="methodology_updated_by", null=True, on_delete=models.CASCADE)
    updated = models.DateTimeField(default=datetime.now)

    def __str__(self):  # __unicode__ on Python 2
        return self.name

    def save(self, *args, **kwargs):
        if not self.id:
            self.created = timezone.now()
        self.updated = timezone.now()
        return super(MethodologyMaster, self).save(*args, **kwargs)

    class Meta:
        ordering = ('name',) class ModuleMaster(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField(default="")
    order = models.IntegerField(default=0)
    methodology = models.ForeignKey(MethodologyMaster, on_delete=models.CASCADE, null=True, default=None)
    created_by = models.ForeignKey(User, related_name="module_created_by", null=True, on_delete=models.CASCADE)
    created = models.DateTimeField(default=datetime.now)
    updated_by = models.ForeignKey(User, related_name="module_updated_by", null=True, on_delete=models.CASCADE)
    updated = models.DateTimeField(default=datetime.now)

    def __str__(self):  # __unicode__ on Python 2
        return self.name

    def save(self, *args, **kwargs):
        if not self.id:
            self.created = timezone.now()
        self.updated = timezone.now()
        return super(ModuleMaster, self).save(*args, **kwargs)

    class Meta:
        ordering = ('name',) class CaseMaster(models.Model):
    name = models.CharField(max_length=100)
    module = models.ForeignKey(ModuleMaster, on_delete=models.CASCADE)
    description = models.TextField(default="")
    order = models.IntegerField(default=0)
    created_by = models.ForeignKey(User, related_name="case_module_created_by", null=True, on_delete=models.CASCADE)
    created = models.DateTimeField(default=datetime.now)
    updated_by = models.ForeignKey(User, related_name="case_module_updated_by", null=True, on_delete=models.CASCADE)
    updated = models.DateTimeField(default=datetime.now)

    def __str__(self):  # __unicode__ on Python 2
        return self.name

    def save(self, *args, **kwargs):
        if not self.id:
            self.created = timezone.now()
        self.updated = timezone.now()
        return super(CaseMaster, self).save(*args, **kwargs)

    class Meta:
        ordering = ('name',) class FlagTable(tables.Table):
    selection = tables.CheckBoxColumn(accessor='pk', attrs={"th__input": {"onclick": "toggle(this)"}}, orderable=False)
    title = tables.TemplateColumn('<a href="/app/flag/{{ record.pk }}"> {{ record.title }}</a>')
    done = tables.BooleanColumn(yesno='done,')
    project = tables.TemplateColumn('<a href="/app/project/{{ record.assessment.project.pk}}">{{ record.assessment.project }}</a>')
    assessment = tables.TemplateColumn('<a href="/app/assessment/{{ record.assessment.pk}}"> '
                                       '{{ record.assessment }}</a>')

    class Meta:
        model = Flag
        template_name = "django_tables2/bootstrap-responsive.html"
        sequence = ('selection', 'id', 'title', 'done', 'assessment', 'added')
        fields = ('id', 'title', 'added', 'done', 'assessment')
        empty_text = "No Flags yet" class OpenFlagTable(tables.Table):
    selection = tables.CheckBoxColumn(accessor='pk', attrs={"th__input": {"onclick": "toggle(this)"}}, orderable=False)
    name = tables.TemplateColumn('<a href="/app/flag/{{ record.pk }}"> {{ record.title }}</a>')
    project = tables.TemplateColumn('<a href="/app/project/{{ record.assessment.project.pk}}">{{ record.assessment.project }}</a>')
    assessment = tables.TemplateColumn('<a href="/app/assessment/{{ record.assessment.pk}}"> '
                                       '{{ record.assessment }}</a>')

    class Meta:
        model = Flag
        template_name = "django_tables2/bootstrap-responsive.html"
        sequence = ('selection', 'id', 'name', 'project', 'assessment', 'added')
        fields = ('id', 'name', 'added', 'project', 'assessment') class Sh0tTable(tables.Table):
    selection = tables.CheckBoxColumn(accessor='pk', attrs={"th__input": {"onclick": "toggle(this)"}}, orderable=False)
    severity = tables.TemplateColumn('<span class="bc-badge bc-badge--p{{ record.severity }}">P{{ record.severity }}</span>')
    title = tables.TemplateColumn('<a href="/app/sh0t/{{ record.pk }}">{{ record.title }}</a>')
    project = tables.TemplateColumn('<a href="/app/project/{{ record.assessment.project.pk}}">{{ record.assessment.project }}</a>')
    assessment = tables.TemplateColumn('<a href="/app/assessment/{{ record.assessment.pk}}">{{ record.assessment }}</a>')

    class Meta:
        model = Sh0t
        template_name = "django_tables2/bootstrap-responsive.html"
        sequence = ('selection','title', 'severity', 'assessment', 'project', 'added')
        fields = ('title', 'severity', 'assessment', 'project', 'added') class AssessmentTable(tables.Table):
    selection = tables.CheckBoxColumn(accessor='pk', attrs={"th__input": {"onclick": "toggle(this)"}}, orderable=False)
    name = tables.TemplateColumn('<a href="/app/assessment/{{ record.pk }}"> {{ record.name }}</a>')
    project = tables.TemplateColumn('<a href="/app/project/{{ record.project.pk}}"> '
                                       '{{ record.project }}</a>')

    class Meta:
        model = Assessment
        template_name = "django_tables2/bootstrap-responsive.html"
        sequence = ('selection', 'name', 'project', 'added')
        fields = ('name', 'project', 'added') class ProjectTable(tables.Table):
    selection = tables.CheckBoxColumn(accessor='pk', attrs={"th__input": {"onclick": "toggle(this)"}}, orderable=False)
    name = tables.TemplateColumn('<a href="/app/project/{{ record.pk }}"> {{ record.name }}</a>')

    class Meta:
        model = Project
        template_name = "django_tables2/bootstrap-responsive.html"
        sequence = ('selection', 'name', 'added')
        fields = ('name', 'added')
from django.shortcuts import render, redirect
from .models import Assessment, Project, Sh0t, Flag, Template
from configuration.models import MethodologyMaster, ModuleMaster, CaseMaster
from django.contrib.auth import logout
from django.contrib.auth.decorators import login_required
from django_tables2 import RequestConfig
from .tables import FlagTable, OpenFlagTable, Sh0tTable, AssessmentTable, ProjectTable
from __future__ import unicode_literals


@login_required
def index(request):
    open_flags = Flag.objects.filter(done=False).order_by('-added')
    recent_flags = Flag.objects.all().order_by('-added')
    recent_sh0ts = Sh0t.objects.all().order_by('-added')
    assessments_count = Assessment.objects.all().count()
    projects_count = Project.objects.all().count()

    context = {
        'open_flags': open_flags,
        'recent_flags': recent_flags,
        'recent_sh0ts': recent_sh0ts,
        'assessments_count': assessments_count,
        'projects_count': projects_count,
    }
    return render(request, 'index.html', context)


@login_required
def flags_new(request):
    submitted = ""
    if "POST" == request.method:
        title = request.POST.get('title', '') or "Flag"
        note = request.POST.get('note', '') or ""
        assessment_id = request.POST.get('assessment', '') or -1
        try:
            the_assessment = Assessment.objects.get(pk=assessment_id)
            new_flag = Flag.objects.create(title=title, note=note, assessment=the_assessment)
            new_flag.save()
            submitted = "success"
        except Assessment.DoesNotExist:
            return redirect('/')

    assessments_list = Assessment.objects.all().order_by('-added')
    recent_flags = Flag.objects.filter(done=False).order_by('-added')[:10]

    context = {'assessments_list': assessments_list, 'recent_flags': recent_flags, 'submitted': submitted}

    return render(request, 'flags.html', context)


@login_required
def flags_all(request):
    all_flags = Flag.objects.all()
    table = FlagTable(all_flags)
    RequestConfig(request).configure(table)
    context = {'table': table, 'count': all_flags.count()}
    return render(request, 'flags-list.html', context)


@login_required
def open_flags(request):
    undone_flags = Flag.objects.filter(done=False)
    table = OpenFlagTable(undone_flags)
    RequestConfig(request).configure(table)
    context = {'table': table, 'count': undone_flags.count()}
    return render(request, 'open-flags.html', context)


@login_required
def flag(request, flag_id):
    submitted = ""
    try:
        the_flag = Flag.objects.get(pk=flag_id)
        if "POST" == request.method:
            if "delete" == request.POST.get('delete', ''):
                the_flag.delete()
                return redirect('/app/flags/all/')

            assessment_id = request.POST.get('assessment', '') or -1
            the_flag.title = request.POST.get('title', '') or "Flag"
            the_flag.note = request.POST.get('note', '') or ""
            if "done" == request.POST.get('done', ''):
                the_flag.done = True
            else:
                the_flag.done = False
            the_flag.assessment = Assessment.objects.get(pk=assessment_id)
            the_flag.save()
            submitted = "success"
            return redirect('/app/flags/all/')
        assessments_list = Assessment.objects.all().order_by('added')
        context = {'flag': the_flag, 'assessments': assessments_list, 'submitted': submitted}
        return render(request, 'flag-single.html', context)
    except Flag.DoesNotExist:
        return redirect('/')
    except Assessment.DoesNotExist:
        return redirect('/')


@login_required
def sh0ts_new(request):
    submitted = ""
    if "POST" == request.method:
        title = request.POST.get('title', '') or "sh0t"
        body = request.POST.get('body', '') or ""
        severity = request.POST.get('severity', '') or 5
        assessment_id = request.POST.get('assessment', '') or -1
        try:
            the_assessment = Assessment.objects.get(pk=assessment_id)
            new_sh0t = Sh0t.objects.create(title=title, body=body, severity=severity, assessment=the_assessment)
            new_sh0t.save()
            submitted = "success"
        except Assessment.DoesNotExist:
            return redirect('/')

    assessments_list = Assessment.objects.all().order_by('-added')
    templates_list = Template.objects.all().order_by('-added')
    recent_sh0ts = Sh0t.objects.all().order_by('-added')[:10]
    context = {'assessments_list': assessments_list, 'templates': templates_list, 'severities': [1,2,3,4,5],
               'recent_sh0ts': recent_sh0ts, 'submitted': submitted}
    return render(request, 'sh0ts.html', context)


@login_required
def sh0ts_all(request):
    all_sh0ts = Sh0t.objects.all()

    table = Sh0tTable(all_sh0ts)