Source

HackersEdge / he_one / views.py

Kevin Veroneau 8d6c3a4 





















































































































































































from django.views.generic.detail import DetailView
from he_one.models import Host, Mailbox, Message, UserPermission, Log, PCFile,\
    NameSystem, Task
from django.shortcuts import get_object_or_404, redirect
import hashlib
from django.core.cache import cache
from django.contrib import messages
import datetime
from django.views.generic.list import ListView
from django.core.exceptions import MultipleObjectsReturned

class HostDetail(DetailView):
    model = Host
    def get(self, request, *args, **kwargs):
        resp = super(HostDetail, self).get(request, *args, **kwargs)
        if not self.host.is_booted and self.host.owner != self.request.user:
            messages.error(request, "Host is not online.")
            return redirect('overview')
        if self.host.is_booted and self.host.owner != self.request.user:
            if self.host.supports_web:
                return redirect('web-index', ip=self.host.ip)
            else:
                messages.error(self.request, 'Host does not run a web service.')
                return redirect('overview')
        return resp
    def get_context_data(self, **kwargs):
        context = super(HostDetail, self).get_context_data(**kwargs)
        try:
            dns = NameSystem.objects.get(host=self.host)
        except (NameSystem.DoesNotExist, MultipleObjectsReturned):
            dns = self.host.ip
        context.update({'dns':dns, 'host':self.host})
        return context
    def get_object(self, queryset=None):
        self.host = self.get_queryset().get(ip=self.kwargs['ip'])
        return self.host

class MailboxDetail(DetailView):
    model = Mailbox
    def get(self, request, *args, **kwargs):
        host = get_object_or_404(Host, ip=self.kwargs['ip'])
        if not host.is_booted:
            messages.error(request, "Host is not online.")
            return redirect('overview')
        if not host.supports_mail:
            messages.error(request, "Unable to contact the mail service.")
            return redirect(host)
        return super(MailboxDetail, self).get(request, *args, **kwargs)
    def get_object(self, queryset=None):
        log = Log(by_who=self.request.user, logged_at=datetime.datetime.now())
        try:
            mbx = self.get_queryset().get(pk=self.kwargs['pk'], owner=self.request.user)
            log.message = "%s accessed their mailbox" % self.request.user
            log.save()
            mbx.host_set.get().logs.add(log)
            return mbx
        except Mailbox.DoesNotExist:
            mbx = self.get_queryset().get(pk=self.kwargs['pk'])
            log.message = "Attempt to access %s" % mbx
            log.save()
            host = mbx.host_set.get()
            host.logs.add(log)
            if host.owner == self.request.user:
                return mbx
            try:
                perms = self.request.user.userpermission_set.get(host=host)
                if perms.is_superuser:
                    return mbx
            except UserPermission.DoesNotExist:
                pass
            raise Mailbox.DoesNotExist

class MessageDetail(DetailView):
    model = Message

class FileDetail(DetailView):
    model = PCFile
    def get(self, request, *args, **kwargs):
        self.host = get_object_or_404(Host, ip=self.kwargs['ip'])
        if not self.host.is_booted:
            messages.error(request, "Host is not online.")
            return redirect(self.host)
        if request.user == self.host.owner or request.user in self.host.users.all():
            return super(FileDetail, self).get(request, *args, **kwargs)
        self.host.logs.create(by_who=request.user, message="Accessed denied to file.", logged_at=datetime.datetime.now())
        messages.error(request, "Access denied to file.")
        return redirect(self.host)
    def get_object(self, queryset=None):
        log = Log(by_who=self.request.user, logged_at=datetime.datetime.now())
        pcfile = self.get_queryset().get(filename=self.kwargs['filename'], file_type=self.kwargs['file_type'])
        log.message = "Opened file %s" % pcfile
        log.save()
        self.host.logs.add(log)
        return pcfile

class TaskList(ListView):
    model = Task
    def get_queryset(self):
        return super(TaskList, self).get_queryset().filter(owner=self.request.user)

class WebIndex(ListView):
    model = PCFile
    def get(self, request, *args, **kwargs):
        self.host = get_object_or_404(Host, ip=self.kwargs['ip'])
        if not self.host.is_booted:
            messages.error(request, "Host is not online.")
            return redirect('overview')
        if not self.host.supports_web:
            messages.error(request, "Host does not support web service.")
            return redirect('overview')
        return super(WebIndex, self).get(request, *args, **kwargs)
    def get_context_data(self, **kwargs):
        context = super(WebIndex, self).get_context_data(**kwargs)
        try:
            dns = NameSystem.objects.get(host=self.host)
        except (NameSystem.DoesNotExist, MultipleObjectsReturned):
            dns = self.host.ip
        context.update({'dns':dns, 'host':self.host})
        return context
    def get_queryset(self):
        return self.host.files.filter(file_type='HTM', filepermission__deleted=False)

class WebFile(DetailView):
    model = PCFile
    def get(self, request, *args, **kwargs):
        self.host = get_object_or_404(Host, ip=self.kwargs['ip'])
        if not self.host.is_booted:
            messages.error(request, "Host is not online.")
            return redirect('overview')
        return super(WebFile, self).get(request, *args, **kwargs)
    def get_context_data(self, **kwargs):
        context = super(WebFile, self).get_context_data(**kwargs)
        try:
            dns = NameSystem.objects.get(host=self.host)
        except (NameSystem.DoesNotExist, MultipleObjectsReturned):
            dns = self.host.ip
        context.update({'dns':dns, 'host':self.host})
        return context
    def get_queryset(self):
        return self.host.files.filter(file_type='HTM', filepermission__deleted=False)
    def get_object(self, queryset=None):
        return self.get_queryset().get(filename=self.kwargs['filename'])

def delete_message(req, message_id):
    message = get_object_or_404(Message, pk=message_id)
    for mbx in message.mailbox_set.all():
        if mbx.owner == req.user:
            message.delete()
            cache_key = "template.cache.emails.%s" % hashlib.md5(u'%s' % mbx.pk).hexdigest()
            cache.delete(cache_key)
            messages.success(req, "Message deleted successfully.")
            return redirect(mbx)
    messages.error(req, "Permissions denied.")
    return redirect('overview')

def boot_host(req, ip):
    host = get_object_or_404(Host, ip=ip, owner=req.user)
    if host.is_booted:
        messages.info(req, "Host is already booted.")
        return redirect(host)
    sys_files = host.files.filter(file_type='SYS', filepermission__deleted=False)
    if sys_files.count() == 0:
        messages.error(req, "Unable to load system files to boot system.")
        return redirect(host)
    if host.is_router and sys_files.filter(filename='ROUTER').count() == 0:
        router_log = Log.objects.create(by_who=req.user, message="Unable to find ROUTER.SYS, disabling router.", logged_at=datetime.datetime.now())
        host.is_router = False
    if not host.is_router and sys_files.filter(filename='KERNEL').count() == 0:
        messages.error(req, "Unable to load KERNEL.SYS to boot system.")
        return redirect(host)
    if 'router_log' in locals():
        host.logs.add(router_log)
    host.is_booted = True
    if host.supports_mail and host.files.filter(filename='MAILAGNT', file_type='PRG', filepermission__deleted=False).count() == 0:
        host.logs.create(by_who=req.user, message="Unable to find MAILAGNT.PRG, disabling mailboxes.", logged_at=datetime.datetime.now())
        host.supports_mail = False
    if host.supports_web and host.files.filter(filename='HTTPSERV', file_type='PRG', filepermission__deleted=False).count() == 0:
        host.logs.create(by_who=req.user, message="Unable to find HTTPSERV.PRG, disabling web server.", logged_at=datetime.datetime.now())
        host.supports_web = False
    host.save()
    host.logs.create(by_who=req.user, message="System booted.", logged_at=datetime.datetime.now())
    messages.success(req, "Host has been successfully started.")
    return redirect(host)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.