Exemple #1
0
def render_delete(request, model, redirect, whitelist=None, extra_context=None,
                  pre_delete_operation=None, delete_operation=qs_delete, object_id=None):
    """Handles input and rendering of general delete page.
    """

    # GET with single object_id in url or POST with object_ids as POST query
    if not (object_id or request.method == 'POST'):
        return HttpResponseRedirect(reverse(redirect))
    object_ids = request.POST.getlist('object') or [object_id]
    if not object_ids:
        new_message(request,
                    "You need to select at least one object to edit",
                    Messages.ERROR)
        return HttpResponseRedirect(reverse(redirect))
    objects = _get_qs_to_delete(model, object_ids, whitelist)

    if request.POST.get('confirm'):
        did_delete = _try_deleting(request, objects, pre_delete_operation,
                                   delete_operation)
        if did_delete:
            return HttpResponseRedirect(reverse(redirect))

    if not extra_context:
        extra_context = {}
    info_dict = {
        'objects': objects,
        'sub_active': {'list': True},
    }
    extra_context.update(info_dict)
    return render(request, 'seeddb/delete.html', extra_context)
Exemple #2
0
def service_save(request, service_form, property_form):
    service_id = service_form.cleaned_data.get('service')
    if service_id:
        service = Service.objects.select_related(
            'netbox').get(pk=service_id)
        ServiceProperty.objects.filter(service=service).delete()
        netbox = service.netbox
    else:
        netbox = Netbox.objects.get(pk=service_form.cleaned_data['netbox'])
        service = Service.objects.create(
            netbox=netbox,
            handler=service_form.cleaned_data['handler']
        )
    for (prop, value) in property_form.cleaned_data.items():
        if value:
            ServiceProperty.objects.create(
                service=service,
                property=prop,
                value=value
            )
    new_message(request,
                "Saved service for handler %s on %s" % (service.handler,
                                                        netbox),
                Messages.SUCCESS)
    return HttpResponseRedirect(reverse('seeddb-service'))
Exemple #3
0
def prefix_edit(request, prefix_id=None):
    """Controller for editing a prefix"""
    info = PrefixInfo()
    prefix, vlan = get_prefix_and_vlan(prefix_id)
    if request.method == 'POST':
        prefix_form = PrefixForm(request.POST, instance=prefix)
        vlan_form = PrefixVlanForm(request.POST, instance=vlan)
        if prefix_form.is_valid() and vlan_form.is_valid():
            vlan = vlan_form.save()
            prefix = prefix_form.save(commit=False)
            prefix.vlan = vlan
            prefix.save()
            msg = "Saved prefix %s" % prefix.net_address
            new_message(request, msg, Messages.SUCCESS)
            return HttpResponseRedirect(
                reverse('seeddb-prefix-edit', args=(prefix.id,)))
    else:
        prefix_form = PrefixForm(instance=prefix)
        vlan_form = PrefixVlanForm(instance=vlan)
    context = info.template_context
    context.update({
        'object': prefix,
        'form': prefix_form,
        'vlan_form': vlan_form,
        'sub_active': prefix and {'edit': True} or {'add': True},
    })
    return render_to_response('seeddb/edit_prefix.html',
                              context, RequestContext(request))
Exemple #4
0
def save_links(request):
    """ Saves navigation preference links on a user """
    account = get_account(request)
    formset_from_post = None
    context = _create_preference_context(request)

    if request.method == 'POST':
        formset = NavbarLinkFormSet(request.POST)
        if formset.is_valid():
            for form in formset.deleted_forms:
                instance = form.save(commit=False)
                instance.account = account
                instance.save()

            instances = formset.save(commit=False)
            for instance in instances:
                    instance.account = account
                    instance.save()
            new_message(request, 'Your links were saved.',
                        type=Messages.SUCCESS)
        else:
            context['navbar_formset'] = formset

            return direct_to_template(
                request,
                'webfront/preferences.html',
                context
            )

    return HttpResponseRedirect(reverse('webfront-preferences'))
Exemple #5
0
def service_save(request, service_form, property_form):
    """Saves a service based on two form inputs"""
    service_id = service_form.cleaned_data.get('service')
    if service_id:
        service = Service.objects.select_related(
            'netbox').get(pk=service_id)
        ServiceProperty.objects.filter(service=service).delete()
        netbox = service.netbox
    else:
        netbox = Netbox.objects.get(pk=service_form.cleaned_data['netbox'])
        service = Service.objects.create(
            netbox=netbox,
            handler=service_form.cleaned_data['handler']
        )
    for (prop, value) in property_form.cleaned_data.items():
        if value:
            ServiceProperty.objects.create(
                service=service,
                property=prop,
                value=value
            )
    new_message(request,
                "Saved service for handler %s on %s" % (service.handler,
                                                        netbox),
                Messages.SUCCESS)
    return HttpResponseRedirect(reverse('seeddb-service'))
Exemple #6
0
def do_delete_module(request):
    """Executes an actual database deletion after deletion was confirmed by
    the delete_module() view.

    """
    confirm_delete = request.POST.get('confirm_delete', False)
    if request.method != 'POST' or not confirm_delete:
        return HttpResponseRedirect(reverse('devicehistory-module'))

    module_ids = request.POST.getlist('module')
    history = _get_unresolved_module_states(module_ids)

    if not history:
        new_message(request, _('No modules selected'), Messages.NOTICE)
        return HttpResponseRedirect(reverse('devicehistory-module'))

    new_message(request, _('Deleted selected modules.'), Messages.SUCCESS)

    cursor = connection.cursor()
    module_ids = tuple(h.module.id for h in history)
    # Delete modules using raw sql to avoid Django's simulated cascading.
    # AlertHistory entries will be closed by a database trigger.
    cursor.execute("DELETE FROM module WHERE moduleid IN %s", (module_ids,))

    # Delete the entities representing these modules
    for hist in history:
        cursor.execute(
            "DELETE FROM netboxentity WHERE netboxid = %s and deviceid = %s",
            [hist.module.netbox.id, hist.module.device.id])

    return HttpResponseRedirect(reverse('devicehistory-module'))
Exemple #7
0
def do_delete_module(request):
    """Executes an actual database deletion after deletion was confirmed by
    the delete_module() view.

    """
    confirm_delete = request.POST.get('confirm_delete', False)
    if request.method != 'POST' or not confirm_delete:
        return HttpResponseRedirect(reverse('devicehistory-module'))

    module_ids = request.POST.getlist('module')
    history = _get_unresolved_module_states(module_ids)

    if not history:
        new_message(request, _('No modules selected'), Messages.NOTICE)
        return HttpResponseRedirect(reverse('devicehistory-module'))

    new_message(request, _('Deleted selected modules.'), Messages.SUCCESS)

    cursor = connection.cursor()
    module_ids = tuple(h.module.id for h in history)
    # Delete modules using raw sql to avoid Django's simulated cascading.
    # AlertHistory entries will be closed by a database trigger.
    cursor.execute("DELETE FROM module WHERE moduleid IN %s", (module_ids,))
    transaction.set_dirty()

    return HttpResponseRedirect(reverse('devicehistory-module'))
Exemple #8
0
def netbox_edit(request, netbox_id=None):
    """Controller for edit or create of netbox"""
    try:
        step = int(request.POST.get('step', '0'))
    except ValueError:
        step = FORM_STEP

    serial_form = None
    group_form = None
    netbox = get_netbox(netbox_id)
    title = get_title(netbox)
    if request.method == 'POST':
        if step == SERIAL_STEP:
            netbox_form = NetboxForm(request.POST)
            if netbox_form.is_valid():
                netbox_form, serial_form, group_form = netbox_serial_and_type(
                    netbox_form, netbox_id)
                step = SAVE_STEP
        else:
            (forms_are_valid,
             netbox_form,
             serial_form,
             group_form) = netbox_validate_before_save(request)

            if forms_are_valid:
                netbox = netbox_do_save(netbox_form, serial_form, group_form)
                new_message(request, "Saved netbox %s" % netbox.sysname,
                            Messages.SUCCESS)
                return HttpResponseRedirect(reverse('seeddb-netbox'))
    else:
        netbox_form = get_netbox_form(netbox)
        step = SERIAL_STEP
    return netbox_render(request, step, netbox, netbox_form, serial_form,
                         group_form, title)
Exemple #9
0
def render_delete(request, model, redirect, whitelist=None, extra_context=None,
                  pre_delete_operation=None, delete_operation=qs_delete):
    """Handles input and rendering of general delete page.
    """
    if request.method != 'POST':
        return HttpResponseRedirect(reverse(redirect))
    if not request.POST.getlist('object'):
        new_message(request,
                    "You need to select at least one object to edit",
                    Messages.ERROR)
        return HttpResponseRedirect(reverse(redirect))

    if not whitelist:
        whitelist = []
    if not extra_context:
        extra_context = {}

    objects = model.objects.filter(
        pk__in=request.POST.getlist('object')
    ).order_by('pk')
    related = dependencies(objects, whitelist)

    for obj in objects:
        if obj.pk in related:
            obj.related_objects = related[obj.pk]

    if request.POST.get('confirm'):
        try:
            if pre_delete_operation:
                pre_delete_operation(objects)
            if delete_operation:
                delete_operation(objects)
        except IntegrityError as ex:
            # We can't delete.
            # Some of the objects we want to delete is referenced by another
            # table without any ON DELETE rules.
            msg = "Integrity failed: %s" % ex
            new_message(request, msg, Messages.ERROR)
        except Exception as ex:
            # Something else went wrong
            _logger.exception("Unhandled exception during delete: %r", request)
            msg = "Error: %s" % ex
            new_message(request, msg, Messages.ERROR)
        else:
            if delete_operation:
                new_message(request,
                            "Deleted %i rows" % len(objects), Messages.SUCCESS)
                log_deleted(request.account, objects, template=u'{actor} deleted {object}')
            else:
                new_message(request,
                            "Scheduled %i rows for deletion" % len(objects), Messages.SUCCESS)
                log_deleted(request.account, objects, template=u'{actor} scheduled {object} for deletion')
            return HttpResponseRedirect(reverse(redirect))

    info_dict = {
        'objects': objects,
        'sub_active': {'list': True},
    }
    extra_context.update(info_dict)
    return render(request, 'seeddb/delete.html', extra_context)
Exemple #10
0
def netbox_edit(request, netbox_id=None):
    """Controller for edit or create of netbox"""
    try:
        step = int(request.POST.get('step', '0'))
    except ValueError:
        step = FORM_STEP

    serial_form = None
    group_form = None
    netbox = get_netbox(netbox_id)
    title = get_title(netbox)
    if request.method == 'POST':
        if step == SERIAL_STEP:
            netbox_form = NetboxForm(request.POST)
            if netbox_form.is_valid():
                netbox_form, serial_form, group_form = netbox_serial_and_type(
                    netbox_form, netbox_id)
                step = SAVE_STEP
        else:
            (forms_are_valid, netbox_form, serial_form,
             group_form) = netbox_validate_before_save(request)

            if forms_are_valid:
                netbox = netbox_do_save(netbox_form, serial_form, group_form)
                new_message(request, "Saved netbox %s" % netbox.sysname,
                            Messages.SUCCESS)
                return HttpResponseRedirect(reverse('seeddb-netbox'))
    else:
        netbox_form = get_netbox_form(netbox)
        step = SERIAL_STEP
    return netbox_render(request, step, netbox, netbox_form, serial_form,
                         group_form, title)
Exemple #11
0
def prefix_edit(request, prefix_id=None):
    """Controller for editing a prefix"""
    info = PrefixInfo()
    prefix, vlan = get_prefix_and_vlan(prefix_id)
    if request.method == 'POST':
        prefix_form = PrefixForm(request.POST, instance=prefix)
        vlan_form = PrefixVlanForm(request.POST, instance=vlan)
        if prefix_form.is_valid() and vlan_form.is_valid():
            vlan = vlan_form.save()
            prefix = prefix_form.save(commit=False)
            prefix.vlan = vlan
            prefix.save()
            msg = "Saved prefix %s" % prefix.net_address
            new_message(request, msg, Messages.SUCCESS)
            return HttpResponseRedirect(
                reverse('seeddb-prefix-edit', args=(prefix.id,)))
    else:
        prefix_form = PrefixForm(instance=prefix, initial=request.GET.dict())
        vlan_form = PrefixVlanForm(instance=vlan, initial=request.GET.dict())
    context = info.template_context
    context.update({
        'object': prefix,
        'form': prefix_form,
        'vlan_form': vlan_form,
        'sub_active': prefix and {'edit': True} or {'add': True},
    })
    return render(request, 'seeddb/edit_prefix.html', context)
Exemple #12
0
def change_password(request):
    """ Handles POST requests to change a users password """
    context = _create_preference_context(request)
    account = get_account(request)

    if account.is_default_account():
        return direct_to_template(request, 'useradmin/not-logged-in.html', {})

    if request.method == 'POST':
        password_form = ChangePasswordForm(request.POST, my_account=account)

        if password_form.is_valid():
            account.set_password(password_form.cleaned_data['new_password1'])
            account.save()
            new_message(request, 'Your password has been changed.',
                        type=Messages.SUCCESS)
        else:
            context['password_form'] = password_form
            return direct_to_template(
                request,
                'webfront/preferences.html',
                context
            )
            
    return HttpResponseRedirect(reverse('webfront-preferences'))
Exemple #13
0
def save_links(request):
    """ Saves navigation preference links on a user """
    account = get_account(request)
    context = _create_preference_context(request)

    if request.method == 'POST':
        formset = NavbarLinkFormSet(request.POST)
        if formset.is_valid():
            for form in formset.deleted_forms:
                instance = form.save(commit=False)
                instance.account = account
                instance.save()

            instances = formset.save(commit=False)
            for instance in instances:
                instance.account = account
                instance.save()
            new_message(request,
                        'Your links were saved.',
                        type=Messages.SUCCESS)
        else:
            context['navbar_formset'] = formset

            return render(request, 'webfront/preferences.html', context)

    return HttpResponseRedirect(reverse('webfront-preferences'))
Exemple #14
0
def render_edit(request,
                model,
                form_model,
                object_id,
                redirect,
                identifier_attr='pk',
                title_attr='pk',
                template='seeddb/edit.html',
                lon=None,
                lat=None,
                extra_context=None):
    """Handles editing for objects in seeddb."""

    if not extra_context:
        extra_context = {}

    obj = _get_object(model, object_id, identifier_attr)
    (identifier, title) = _get_identifier_title(obj, identifier_attr,
                                                title_attr)
    verbose_name = model._meta.verbose_name

    if not obj and (lat and lon):
        obj = model(position='({0},{1})'.format(lat, lon))

    if request.method == 'POST':
        form = form_model(request.POST, instance=obj)
        if form.is_valid():
            obj = form.save()
            (identifier,
             title) = _get_identifier_title(obj, identifier_attr, title_attr)
            new_message(request, "Saved %s %s" % (verbose_name, title),
                        Messages.SUCCESS)
            try:
                return HttpResponseRedirect(
                    reverse(redirect, args=(identifier, )))
            except NoReverseMatch:
                return HttpResponseRedirect(reverse(redirect))
    else:
        form = form_model(instance=obj)

    context = {
        'object': obj,
        'form': form,
        'title': 'Add new %s' % verbose_name,
        'verbose_name': verbose_name,
        'sub_active': {
            'add': True
        },
    }
    if obj and obj.pk:
        context.update({
            'title': 'Edit %s "%s"' % (verbose_name, title),
            'sub_active': {
                'edit': True
            },
        })
    extra_context.update(context)
    return render_to_response(template, extra_context, RequestContext(request))
Exemple #15
0
def render_edit(request, model, form_model, object_id, redirect,
                template='seeddb/edit.html',
                lon=None, lat=None, extra_context=None):
    """Handles editing for objects in seeddb."""

    if not extra_context:
        extra_context = {}

    obj = _get_object(model, object_id)
    verbose_name = model._meta.verbose_name

    if not obj and (lat and lon):
        obj = model(position='({0},{1})'.format(lat, lon))

    if request.method == 'POST':
        form = form_model(request.POST, instance=obj)
        if form.is_valid():

            # TODO: It's kinda hackish to put this here. Discuss during review
            # Store devices in group when editing a device group (which we
            # have no idea if we are doing or not)
            if model == NetboxGroup:
                netboxes = request.POST.getlist('netboxes')
                _logger.debug('netboxes in group: %s', netboxes)
                # Save model but make sure m2m is not saved. See
                # https://docs.djangoproject.com/en/1.4/topics/db/models
                # /#extra-fields-on-many-to-many-relationships
                obj = form.save(commit=False)
                obj.save()
                _connect_group_to_devices(obj, netboxes)
            else:
                obj = form.save()

            new_message(request, "Saved %s %s" % (verbose_name, obj),
                        Messages.SUCCESS)
            try:
                return HttpResponseRedirect(reverse(redirect, args=(obj.pk,)))
            except NoReverseMatch:
                return HttpResponseRedirect(reverse(redirect))
    else:
        form = form_model(instance=obj)

    context = {
        'object': obj,
        'form': form,
        'title': 'Add new %s' % verbose_name,
        'verbose_name': verbose_name,
        'sub_active': {'add': True},
    }
    if obj and obj.pk:
        context.update({
            'title': 'Edit %s "%s"' % (verbose_name, obj),
            'sub_active': {'edit': True},
        })
    extra_context.update(context)
    return render_to_response(template, extra_context, RequestContext(request))
Exemple #16
0
        def _handler(request, *args, **kwargs):
            error = None
            if request.method == 'POST':
                if _required_args_are_present(request):
                    return func(request, *args, **kwargs)
                else:
                    error = _('Required post-data were not supplied')
            else:
                error = _('There was no post-data')

            new_message(request, error, Messages.ERROR)
            return HttpResponseRedirect(reverse(redirect))
Exemple #17
0
        def _handler(request, *args, **kwargs):
            error = None
            if request.method == 'POST':
                if _required_args_are_present(request):
                    return func(request, *args, **kwargs)
                else:
                    error = _('Required post-data were not supplied')
            else:
                error = _('There was no post-data')

            new_message(request, error, Messages.ERROR)
            return HttpResponseRedirect(reverse(redirect))
Exemple #18
0
def _try_deleting(request, objects, pre_delete_operation=None,
               delete_operation=None):
    try:
        if pre_delete_operation:
            pre_delete_operation(objects)
        if delete_operation:
            delete_operation(objects)
    except IntegrityError as ex:
        # We can't delete.
        # Some of the objects we want to delete is referenced by another
        # table without any ON DELETE rules.
        msg = "Integrity failed: %s" % ex
        new_message(request, msg, Messages.ERROR)
    except Exception as ex:
        # Something else went wrong
        _logger.exception("Unhandled exception during delete: %r", request)
        msg = "Error: %s" % ex
        new_message(request, msg, Messages.ERROR)
    else:
        if delete_operation:
            new_message(request,
                        "Deleted %i rows" % len(objects), Messages.SUCCESS)
            log_deleted(request.account, objects, template=u'{actor} deleted {object}')
        else:
            new_message(request,
                        "Scheduled %i rows for deletion" % len(objects), Messages.SUCCESS)
            log_deleted(request.account, objects, template=u'{actor} scheduled {object} for deletion')
        return True
    return False
Exemple #19
0
def service_add(request):
    info = ServiceInfo()
    box_select = QuickSelect(location=False,
                             room=False,
                             netbox=True,
                             netbox_multiple=False)
    if request.method == 'POST':
        choice_form = ServiceChoiceForm(request.POST)
        netbox_id = request.POST.get('netbox')
        try:
            netbox = Netbox.objects.get(pk=netbox_id)
        except Netbox.DoesNotExist:
            new_message(request, "Netbox does not exist in database",
                        Messages.ERROR)
        else:
            if choice_form.is_valid():
                property_form = ServicePropertyForm(
                    service_args=get_description(
                        choice_form.cleaned_data['service']))
                service_form = ServiceForm(
                    initial={
                        'netbox': netbox.pk,
                        'handler': choice_form.cleaned_data['service'],
                    })
                context = info.template_context
                context.update({
                    'service_form': service_form,
                    'property_form': property_form,
                    'sub_active': {
                        'add': True
                    },
                    'handler': choice_form.cleaned_data['service'],
                    'netbox': netbox,
                })
                return render_to_response('seeddb/service_property_form.html',
                                          context, RequestContext(request))
    else:
        choice_form = ServiceChoiceForm()

    context = info.template_context
    context.update({
        'box_select': box_select,
        'choice_form': choice_form,
        'sub_active': {
            'add': True
        },
    })
    return render_to_response('seeddb/service_netbox_form.html', context,
                              RequestContext(request))
Exemple #20
0
def delete_section(request):
    """Controller for deleting a section"""
    if not request.method == 'POST':
        return HttpResponseRedirect(reverse('status-preferences'))

    account = get_account(request)
    section_ids = request.POST.getlist('delete_checkbox')

    sections = StatusPreference.objects.filter(
        pk__in=section_ids,
        account=account,
    ).delete()

    new_message(request, 'Deleted selected sections', Messages.SUCCESS)
    return HttpResponseRedirect(reverse('status-preferences'))
Exemple #21
0
def delete_section(request):
    """Controller for deleting a section"""
    if not request.method == 'POST':
        return HttpResponseRedirect(reverse('status-preferences'))

    account = get_account(request)
    section_ids = request.POST.getlist('delete_checkbox')

    sections = StatusPreference.objects.filter(
        pk__in=section_ids,
        account=account,
    ).delete()

    new_message(request, 'Deleted selected sections', Messages.SUCCESS)
    return HttpResponseRedirect(reverse('status-preferences'))
Exemple #22
0
def render_edit(request, model, form_model, object_id, redirect,
                identifier_attr='pk', title_attr='pk',
                template='seeddb/edit.html',
                lon=None, lat=None, extra_context=None):
    """Handles editing for objects in seeddb."""

    if not extra_context:
        extra_context = {}

    obj = _get_object(model, object_id, identifier_attr)
    (identifier, title) = _get_identifier_title(
        obj, identifier_attr, title_attr)
    verbose_name = model._meta.verbose_name

    if not obj and (lat and lon):
        obj = model(position='({0},{1})'.format(lat, lon))

    if request.method == 'POST':
        form = form_model(request.POST, instance=obj)
        if form.is_valid():
            obj = form.save()
            (identifier, title) = _get_identifier_title(
                obj, identifier_attr, title_attr)
            new_message(request,
                        "Saved %s %s" % (verbose_name, title),
                        Messages.SUCCESS)
            try:
                return HttpResponseRedirect(
                    reverse(redirect, args=(identifier,)))
            except NoReverseMatch:
                return HttpResponseRedirect(reverse(redirect))
    else:
        form = form_model(instance=obj)

    context = {
        'object': obj,
        'form': form,
        'title': 'Add new %s' % verbose_name,
        'verbose_name': verbose_name,
        'sub_active': {'add': True},
    }
    if obj and obj.pk:
        context.update({
            'title': 'Edit %s "%s"' % (verbose_name, title),
            'sub_active': {'edit': True},
        })
    extra_context.update(context)
    return render_to_response(template, extra_context, RequestContext(request))
Exemple #23
0
def service_add(request):
    info = ServiceInfo()
    box_select = QuickSelect(
        location=False,
        room=False,
        netbox=True,
        netbox_multiple=False)
    if request.method == 'POST':
        choice_form = ServiceChoiceForm(request.POST)
        netbox_id = request.POST.get('netbox')
        try:
            netbox = Netbox.objects.get(pk=netbox_id)
        except Netbox.DoesNotExist:
            new_message(request,
                        "Netbox does not exist in database", Messages.ERROR)
        else:
            if choice_form.is_valid():
                property_form = ServicePropertyForm(
                    service_args=get_description(
                        choice_form.cleaned_data['service']
                    ))
                service_form = ServiceForm(initial={
                    'netbox': netbox.pk,
                    'handler': choice_form.cleaned_data['service'],
                })
                context = info.template_context
                context.update({
                    'service_form': service_form,
                    'property_form': property_form,
                    'sub_active': {'add': True},
                    'handler': choice_form.cleaned_data['service'],
                    'netbox': netbox,
                })
                return render_to_response('seeddb/service_property_form.html',
                    context, RequestContext(request))
    else:
        choice_form = ServiceChoiceForm()

    context = info.template_context
    context.update({
        'box_select': box_select,
        'choice_form': choice_form,
        'sub_active': {'add': True},
    })
    return render_to_response('seeddb/service_netbox_form.html',
        context, RequestContext(request))
Exemple #24
0
def cancel(request, task_id):
    task = get_object_or_404(MaintenanceTask, pk=task_id)
    heading = 'Cancel task'
    if request.method == 'POST':
        task.state = 'canceled'
        task.save()
        new_message(request, "This task is now cancelled.", Messages.SUCCESS)
        return HttpResponseRedirect(reverse('maintenance-view',
                                            args=[task_id]))
    else:
        infodict = infodict_by_state(task)
        return render_to_response(
            'maintenance/cancel.html', {
                'active': infodict['active'],
                'navpath': infodict['navpath'],
                'title': TITLE + " - " + heading,
                'heading': heading,
                'task': task,
            }, RequestContext(request))
Exemple #25
0
def register_error(request):
    """Registers a device error event posted from a form"""
    selection = {
        'netbox': request.POST.getlist('netbox'),
        'module': request.POST.getlist('module'),
    }
    error_comment = request.POST.get('error_comment', None)
    confirmed = request.POST.get('confirm', False)

    if not selection['netbox'] and not selection['module']:
        new_message(request, _("No devices selected."), Messages.WARNING)
        return error_form(request)
    if not error_comment and not confirmed:
        new_message(request, _("There's no error message supplied. Are you "
                               "sure you want to continue?"),
                    Messages.WARNING)
        return confirm_error_form(request)

    register_error_events(request, selection=selection, comment=error_comment)

    return HttpResponseRedirect(reverse('devicehistory-registererror'))
Exemple #26
0
def register_error(request):
    """Registers a device error event posted from a form"""
    selection = {
        'netbox': request.POST.getlist('netbox'),
        'module': request.POST.getlist('module'),
    }
    error_comment = request.POST.get('error_comment', None)
    confirmed = request.POST.get('confirm', False)

    if not selection['netbox'] and not selection['module']:
        new_message(request, _("No devices selected."), Messages.WARNING)
        return error_form(request)
    if not error_comment and not confirmed:
        new_message(request, _("There's no error message supplied. Are you "
                               "sure you want to continue?"),
                    Messages.WARNING)
        return confirm_error_form(request)

    register_error_events(request, selection=selection, comment=error_comment)

    return HttpResponseRedirect(reverse('devicehistory-registererror'))
Exemple #27
0
def group_privilege_remove(request, group_id, privilege_id):
    try:
        group = AccountGroup.objects.get(id=group_id)
    except AccountGroup.DoesNotExist:
        new_message(request, 'Group %s does not exist.' % (group_id),
                    type=Messages.ERROR)
        return HttpResponseRedirect(reverse('useradmin-group_list'))

    try:
        privilege = group.privilege_set.get(id=privilege_id)
    except Privilege.DoesNotExist:
        new_message(request,
                    'Privilege %s does not exist or it is not associated '
                    'with %s.' % (privilege_id, group),
                    type=Messages.WARNING)
        return HttpResponseRedirect(reverse('useradmin-account_detail',
                                            args=[account.id]))

    if request.method == 'POST':
        privilege.delete()
        new_message(request,
                    'Privilege %s has been removed from group %s.' %
                    (privilege, group),
                    type=Messages.SUCCESS)
        return HttpResponseRedirect(reverse('useradmin-group_detail',
                                            args=[group.id]))

    return render_to_response('useradmin/delete.html',
                        {
                            'name': '%s from %s' % (privilege, group),
                            'type': 'privilege',
                            'back': reverse('useradmin-group_detail',
                                            args=[group.id]),
                        }, UserAdminContext(request))
Exemple #28
0
def account_delete(request, account_id):
    try:
        account = Account.objects.get(id=account_id)
    except Account.DoesNotExist:
        new_message(request,
                    'Account %s does not exist.' % (account_id),
                    type=Messages.ERROR)
        return HttpResponseRedirect(reverse('useradmin-account_list'))

    if account.is_system_account():
        new_message(request,
                    'Account %s can not be deleted as it is a system '
                    'account.' % (account.name),
                    type=Messages.ERROR)
        return HttpResponseRedirect(
            reverse('useradmin-account_detail', args=[account.id]))

    if request.method == 'POST':
        account.delete()
        new_message(request,
                    'Account %s has been deleted.' % (account.name),
                    type=Messages.SUCCESS)
        return HttpResponseRedirect(reverse('useradmin-account_list'))

    return render_to_response(
        'useradmin/delete.html', {
            'name': '%s (%s)' % (account.name, account.login),
            'type': 'account',
            'back': reverse('useradmin-account_detail', args=[account.id]),
        }, UserAdminContext(request))
Exemple #29
0
def group_privilege_remove(request, group_id, privilege_id):
    try:
        group = AccountGroup.objects.get(id=group_id)
    except AccountGroup.DoesNotExist:
        new_message(request,
                    'Group %s does not exist.' % (group_id),
                    type=Messages.ERROR)
        return HttpResponseRedirect(reverse('useradmin-group_list'))

    try:
        privilege = group.privilege_set.get(id=privilege_id)
    except Privilege.DoesNotExist:
        new_message(request,
                    'Privilege %s does not exist or it is not associated '
                    'with %s.' % (privilege_id, group),
                    type=Messages.WARNING)
        return HttpResponseRedirect(
            reverse('useradmin-account_detail', args=[account.id]))

    if request.method == 'POST':
        privilege.delete()
        new_message(request,
                    'Privilege %s has been removed from group %s.' %
                    (privilege, group),
                    type=Messages.SUCCESS)
        return HttpResponseRedirect(
            reverse('useradmin-group_detail', args=[group.id]))

    return render_to_response(
        'useradmin/delete.html', {
            'name': '%s from %s' % (privilege, group),
            'type': 'privilege',
            'back': reverse('useradmin-group_detail', args=[group.id]),
        }, UserAdminContext(request))
Exemple #30
0
def account_delete(request, account_id):
    try:
        account = Account.objects.get(id=account_id)
    except Account.DoesNotExist:
        new_message(request, 'Account %s does not exist.' % (account_id),
                    type=Messages.ERROR)
        return HttpResponseRedirect(reverse('useradmin-account_list'))

    if account.is_system_account():
        new_message(request,
                    'Account %s can not be deleted as it is a system '
                    'account.' % (account.name),
                    type=Messages.ERROR)
        return HttpResponseRedirect(reverse('useradmin-account_detail',
                                            args=[account.id]))

    if request.method == 'POST':
        account.delete()
        new_message(request,
                    'Account %s has been deleted.' % (account.name),
                    type=Messages.SUCCESS)
        return HttpResponseRedirect(reverse('useradmin-account_list'))

    return render_to_response('useradmin/delete.html',
                        {
                            'name': '%s (%s)' % (account.name, account.login),
                            'type': 'account',
                            'back': reverse('useradmin-account_detail',
                                            args=[account.id]),
                        }, UserAdminContext(request))
Exemple #31
0
def group_delete(request, group_id):
    try:
        group = AccountGroup.objects.get(id=group_id)
    except AccountGroup.DoesNotExist:
        new_message(request,
                    'Group %s does not exist.' % (group_id),
                    type=Messages.ERROR)
        return HttpResponseRedirect(reverse('useradmin-group_list'))

    if group.is_system_group():
        new_message(request,
                    'Group %s is a system group and can not be '
                    'deleted.' % (group),
                    type=Messages.ERROR)
        return HttpResponseRedirect(
            reverse('useradmin-group_detail', args=[group.id]))

    if request.method == 'POST':
        group.delete()
        new_message(request,
                    'Group %s has been deleted.' % (group),
                    type=Messages.SUCCESS)
        return HttpResponseRedirect(reverse('useradmin-group_list'))

    return render_to_response(
        'useradmin/delete.html', {
            'name': group,
            'type': 'group',
            'back': reverse('useradmin-group_detail', args=[group.id]),
        }, UserAdminContext(request))
Exemple #32
0
def account_organization_remove(request, account_id, org_id):
    try:
        account = Account.objects.get(id=account_id)
    except Account.DoesNotExist:
        new_message(request,
                    'Account %s does not exist.' % (account_id),
                    type=Messages.ERROR)
        return HttpResponseRedirect(reverse('useradmin-account_list'))

    try:
        organization = account.organizations.get(id=org_id)
    except Organization.DoesNotExist:
        new_message(request,
                    'Organization %s does not exist or it is not associated '
                    'with %s.' % (org_id, account),
                    type=Messages.ERROR)
        return HttpResponseRedirect(
            reverse('useradmin-account_detail', args=[account.id]))

    if request.method == 'POST':
        account.organizations.remove(organization)
        new_message(request,
                    'Organization %s has been removed from account %s.' %
                    (organization, account),
                    type=Messages.SUCCESS)
        return HttpResponseRedirect(
            reverse('useradmin-account_detail', args=[account.id]))

    return render_to_response(
        'useradmin/delete.html', {
            'name': '%s from %s' % (organization, account),
            'type': 'organization',
            'back': reverse('useradmin-account_detail', args=[account.id]),
        }, UserAdminContext(request))
Exemple #33
0
def group_delete(request, group_id):
    try:
        group = AccountGroup.objects.get(id=group_id)
    except AccountGroup.DoesNotExist:
        new_message(request, 'Group %s does not exist.' % (group_id),
                    type=Messages.ERROR)
        return HttpResponseRedirect(reverse('useradmin-group_list'))

    if group.is_system_group():
        new_message(request,
                    'Group %s is a system group and can not be '
                    'deleted.' % (group),
                    type=Messages.ERROR)
        return HttpResponseRedirect(reverse('useradmin-group_detail',
                                            args=[group.id]))

    if request.method == 'POST':
        group.delete()
        new_message(request, 'Group %s has been deleted.' % (group),
                    type=Messages.SUCCESS)
        return HttpResponseRedirect(reverse('useradmin-group_list'))

    return render_to_response('useradmin/delete.html',
                        {
                            'name': group,
                            'type': 'group',
                            'back': reverse('useradmin-group_detail',
                                            args=[group.id]),
                        }, UserAdminContext(request))
Exemple #34
0
def account_organization_remove(request, account_id, org_id):
    try:
        account = Account.objects.get(id=account_id)
    except Account.DoesNotExist:
        new_message(request, 'Account %s does not exist.' % (account_id),
                    type=Messages.ERROR)
        return HttpResponseRedirect(reverse('useradmin-account_list'))

    try:
        organization = account.organizations.get(id=org_id)
    except Organization.DoesNotExist:
        new_message(request,
                    'Organization %s does not exist or it is not associated '
                    'with %s.' % (org_id, account),
                    type=Messages.ERROR)
        return HttpResponseRedirect(reverse('useradmin-account_detail',
                                            args=[account.id]))

    if request.method == 'POST':
        account.organizations.remove(organization)
        new_message(request,
                    'Organization %s has been removed from account %s.' %
                    (organization, account),
                    type=Messages.SUCCESS)
        return HttpResponseRedirect(reverse('useradmin-account_detail',
                                            args=[account.id]))

    return render_to_response('useradmin/delete.html',
                        {
                            'name': '%s from %s' % (organization, account),
                            'type': 'organization',
                            'back': reverse('useradmin-account_detail',
                                            args=[account.id]),
                        }, UserAdminContext(request))
Exemple #35
0
def cancel(request, task_id):
    task = get_object_or_404(MaintenanceTask, pk=task_id)
    heading = 'Cancel task'
    if request.method == 'POST':
        task.state = 'canceled'
        task.save()
        new_message(request, "This task is now cancelled.", Messages.SUCCESS)
        return HttpResponseRedirect(reverse('maintenance-view',
                                                args=[task_id]))
    else:
        infodict = infodict_by_state(task)
        return render_to_response(
            'maintenance/cancel.html',
            {
                'active': infodict['active'],
                'navpath': infodict['navpath'],
                'title': TITLE + " - " + heading,
                'heading': heading,
                'task': task,
            },
            RequestContext(request)
        )
Exemple #36
0
def move_section(request):
    """Controller for moving a section up or down"""
    account = get_account(request)

    # Moving up, or moving down?
    if request.POST.get('moveup'):
        movement = -1
        section_id = request.POST.get('moveup')
        direction = 'up'
    elif request.POST.get('movedown'):
        movement = 1
        section_id = request.POST.get('movedown')
        direction = 'down'
    else:
        return HttpResponseRedirect(reverse('status-preferences'))

    # Make sure the ordering is correct before we try to move around
    order_status_preferences(account)

    # Find the section we want to move
    try:
        section = StatusPreference.objects.get(
            id=section_id,
            account=account,
        )
    except StatusPreference.DoesNotExist:
        new_message(request, 'Could not find selected filter', Messages.ERROR)
        return HttpResponseRedirect(reverse('status-preferences'))

    # Find the section we should swap places with.
    # If it's not found we're trying to move the first section up or the last
    # section down.
    try:
        other_section = StatusPreference.objects.get(
            position=section.position + movement,
            account=account,
        )
    except StatusPreference.DoesNotExist:
        new_message(request, 'New position is out of bounds.', Messages.ERROR)
        return HttpResponseRedirect(reverse('status-preferences'))

    # Swap places
    new_position = other_section.position
    other_section.position = section.position
    section.position = new_position

    other_section.save()
    section.save()

    new_message(request,
                'Moved section "%s" %s' % (section.name, direction),
                Messages.SUCCESS)
    return HttpResponseRedirect(reverse('status-preferences'))
Exemple #37
0
def move_section(request):
    """Controller for moving a section up or down"""
    account = get_account(request)

    # Moving up, or moving down?
    if request.POST.get('moveup'):
        movement = -1
        section_id = request.POST.get('moveup')
        direction = 'up'
    elif request.POST.get('movedown'):
        movement = 1
        section_id = request.POST.get('movedown')
        direction = 'down'
    else:
        return HttpResponseRedirect(reverse('status-preferences'))

    # Make sure the ordering is correct before we try to move around
    order_status_preferences(account)

    # Find the section we want to move
    try:
        section = StatusPreference.objects.get(
            id=section_id,
            account=account,
        )
    except StatusPreference.DoesNotExist:
        new_message(request, 'Could not find selected filter', Messages.ERROR)
        return HttpResponseRedirect(reverse('status-preferences'))

    # Find the section we should swap places with.
    # If it's not found we're trying to move the first section up or the last
    # section down.
    try:
        other_section = StatusPreference.objects.get(
            position=section.position + movement,
            account=account,
        )
    except StatusPreference.DoesNotExist:
        new_message(request, 'New position is out of bounds.', Messages.ERROR)
        return HttpResponseRedirect(reverse('status-preferences'))

    # Swap places
    new_position = other_section.position
    other_section.position = section.position
    section.position = new_position

    other_section.save()
    section.save()

    new_message(request, 'Moved section "%s" %s' % (section.name, direction),
                Messages.SUCCESS)
    return HttpResponseRedirect(reverse('status-preferences'))
Exemple #38
0
def render_delete(request,
                  model,
                  redirect,
                  whitelist=None,
                  extra_context=None):
    """Handles input and rendering of general delete page.
    """
    if request.method != 'POST':
        return HttpResponseRedirect(reverse(redirect))
    if not len(request.POST.getlist('object')):
        new_message(request, "You need to select at least one object to edit",
                    Messages.ERROR)
        return HttpResponseRedirect(reverse(redirect))

    if not whitelist:
        whitelist = []
    if not extra_context:
        extra_context = {}

    objects = model.objects.filter(
        pk__in=request.POST.getlist('object')).order_by('pk')
    related = dependencies(objects, whitelist)

    for obj in objects:
        if obj.pk in related:
            obj.related_objects = related[obj.pk]

    if request.POST.get('confirm'):
        try:
            qs_delete(objects)
        except IntegrityError, ex:
            # We can't delete.
            # Some of the objects we want to delete is referenced by another
            # table without any ON DELETE rules.
            msg = "Integrity failed: %s" % ex
            new_message(request, msg, Messages.ERROR)
        except Exception, ex:
            # Something else went wrong
            LOGGER.exception("Unhandled exception during delete: %r", request)
            msg = "Error: %s" % ex
            new_message(request, msg, Messages.ERROR)
Exemple #39
0
def render_delete(request, model, redirect, whitelist=None, extra_context=None):
    """Handles input and rendering of general delete page.
    """
    if request.method != 'POST':
        return HttpResponseRedirect(reverse(redirect))
    if not len(request.POST.getlist('object')):
        new_message(request,
                    "You need to select at least one object to edit",
                    Messages.ERROR)
        return HttpResponseRedirect(reverse(redirect))

    if not whitelist:
        whitelist = []
    if not extra_context:
        extra_context = {}

    objects = model.objects.filter(
        pk__in=request.POST.getlist('object')
    ).order_by('pk')
    related = dependencies(objects, whitelist)

    for obj in objects:
        if obj.pk in related:
            obj.related_objects = related[obj.pk]

    if request.POST.get('confirm'):
        try:
            qs_delete(objects)
        except IntegrityError, ex:
            # We can't delete.
            # Some of the objects we want to delete is referenced by another
            # table without any ON DELETE rules.
            msg = "Integrity failed: %s" % ex
            new_message(request, msg, Messages.ERROR)
        except Exception, ex:
            # Something else went wrong
            LOGGER.exception("Unhandled exception during delete: %r", request)
            msg = "Error: %s" % ex
            new_message(request, msg, Messages.ERROR)
Exemple #40
0
def save_preferences(request):
    """Controller for saving the preferences"""
    if not request.method == 'POST':
        return HttpResponseRedirect(reverse('status-preferences'))

    account = get_account(request)

    type = request.POST.get('type', None)
    section_model = get_section_model(type)
    form_model = section_model.form_class()
    form = form_model(request.POST)

    if type and form.is_valid():
        try:
            section = StatusPreference.objects.get(id=form.cleaned_data['id'])
            type = section.type
        except StatusPreference.DoesNotExist:
            section = StatusPreference()
            section.position = StatusPreference.objects.count()
            type = form.cleaned_data['type']
            section.type = type

        section.name = form.cleaned_data['name']
        section.account = account
        if 'states' in form.cleaned_data:
            section.states = ",".join(form.cleaned_data['states'])
        if type in SERVICE_SECTIONS:
            section.services = ",".join(form.cleaned_data['services'])

        section.save()

        section.organizations = Organization.objects.filter(
            id__in=form.cleaned_data['organizations'])

        if type not in SERVICE_SECTIONS:
            section.categories = Category.objects.filter(
                id__in=form.cleaned_data['categories'])

        new_message(request, 'Saved preferences', Messages.SUCCESS)
        return HttpResponseRedirect(reverse('status-preferences'))
    else:
        if 'id' in request.POST and request.POST.get('id'):
            section = StatusPreference.objects.get(id=request.POST.get('id'))
            name = section.name
            type = section.type
        elif 'type' in request.POST and request.POST.get('type'):
            name = StatusPreference.lookup_readable_type(
                request.POST.get('type'))
            type = None

        new_message(request, 'There were errors in the form below.',
                    Messages.ERROR)
        return render_to_response(
            'status/edit_preferences.html',
            {
                'active': {'preferences': True},
                'title': 'NAV - Add new status section',
                'navpath': [('Home', '/'), ('Status', '')],
                'section_form': form,
                'name': name,
                'type': type,
            },
            RequestContext(request)
        )
Exemple #41
0
def group_detail(request, group_id=None):
    try:
        group = AccountGroup.objects.get(id=group_id)
    except AccountGroup.DoesNotExist:
        group = None

    group_form = AccountGroupForm(instance=group)
    account_form = AccountAddForm(group)
    privilege_form = PrivilegeForm()

    if request.method == 'POST':

        if 'submit_group' in request.POST:
            group_form = AccountGroupForm(request.POST, instance=group)

            if group_form.is_valid():
                # FIXME 
                group = group_form.save()

                new_message(request, '"%s" has been saved.' % (group),
                            type=Messages.SUCCESS)
                return HttpResponseRedirect(reverse('useradmin-group_detail',
                                                    args=[group.id]))

        elif 'submit_privilege' in request.POST:
            privilege_form = PrivilegeForm(request.POST)

            if privilege_form.is_valid():
                type = privilege_form.cleaned_data['type']
                target = privilege_form.cleaned_data['target']

                try:
                    group.privilege_set.get(type=type, target=target)
                    new_message(request,
                                'Privilege was not added as it already exists.',
                                type=Messages.WARNING)
                except Privilege.DoesNotExist:
                    group.privilege_set.create(type=type, target=target)
                    new_message(request, 'Privilege has been added.',
                                type=Messages.SUCCESS)

                return HttpResponseRedirect(reverse('useradmin-group_detail',
                                                    args=[group.id]))
        elif 'submit_account' in request.POST:
            account_form = AccountAddForm(group, request.POST)

            if account_form.is_valid():
                try:
                    account = account_form.cleaned_data['account']
                    group.accounts.get(login=account.login)
                    new_message(request,
                                'Account %s was not added as it is already a '
                                'member of the group.' % account,
                                type=Messages.WARNING)
                except Account.DoesNotExist:
                    group.accounts.add(account)
                    new_message(request,
                                'Account %s has been added.' % account,
                                type=Messages.SUCCESS)

                return HttpResponseRedirect(reverse('useradmin-group_detail',
                                                    args=[group.id]))

    if group:
        active = {'group_detail': True}
    else:
        active = {'group_new': True}

    return render_to_response('useradmin/group_detail.html',
                        {
                            'active': active,
                            'group': group,
                            'group_form': group_form,
                            'account_form': account_form,
                            'privilege_form': privilege_form,
                        }, UserAdminContext(request))
Exemple #42
0
def account_detail(request, account_id=None):
    try:
        account = Account.objects.get(id=account_id)
    except Account.DoesNotExist:
        account = None

    account_form = AccountForm(instance=account)
    org_form = OrganizationAddForm(account)
    group_form = GroupAddForm(account)

    if request.method == 'POST':
        if 'submit_account' in request.POST:
            account_form = AccountForm(request.POST, instance=account)

            if account_form.is_valid():
                account = account_form.save(commit=False)

                if 'password1' in account_form.cleaned_data and \
                account_form.cleaned_data['password1'] and not account.ext_sync:
                    account.set_password(account_form.cleaned_data['password1'])

                account.save()

                new_message(request, '"%s" has been saved.' % (account),
                            type=Messages.SUCCESS)
                return HttpResponseRedirect(reverse('useradmin-account_detail',
                                                    args=[account.id]))

        elif 'submit_org' in request.POST:
            org_form = OrganizationAddForm(account, request.POST)

            if org_form.is_valid():
                organization = org_form.cleaned_data['organization']

                try:
                    account.organizations.get(id=organization.id)
                    new_message(request,
                                'Organization was not added as it has already '
                                'been added.',
                                type=Messages.WARNING)
                except Organization.DoesNotExist:
                    account.organizations.add(organization)
                    new_message(request,
                                'Added organization "%s" to account "%s"' %
                                (organization, account),
                                type=Messages.SUCCESS)

                return HttpResponseRedirect(reverse('useradmin-account_detail',
                                                    args=[account.id]))

        elif 'submit_group' in request.POST:
            group_form = GroupAddForm(account, request.POST)

            if group_form.is_valid():
                group = group_form.cleaned_data['group']

                if ((group.is_admin_group() or group.is_protected_group()) and
                    account.is_default_account()):
                    new_message(request,
                                'Default user may not be added to "%s" '
                                'group.' % group,
                                type=Messages.ERROR)
                else:
                    try:
                        account.accountgroup_set.get(id=group.id)
                        new_message(request,
                                    'Group was not added as it has already '
                                    'been added.',
                                    type=Messages.WARNING)
                    except AccountGroup.DoesNotExist:
                        account.accountgroup_set.add(group)
                        new_message(request,
                                    'Added "%s" to group "%s"' %
                                    (account, group),
                                    type=Messages.SUCCESS)

                return HttpResponseRedirect(reverse('useradmin-account_detail',
                                                    args=[account.id]))

        elif 'submit_sudo' in request.POST:
            sudo_account_id = request.POST.get('account')
            try:
                sudo_account = Account.objects.get(pk=sudo_account_id)
            except Account.DoesNotExist:
                new_message(request, 'Account not found.', type=Message.ERROR)
            else:
                sudo(request, sudo_account)
            return HttpResponseRedirect(reverse('webfront-index'))

    if account:
        active = {'account_detail': True}
        current_user = get_account(request)
    else:
        active = {'account_new': True}

    return render_to_response('useradmin/account_detail.html',
                        {
                            'active': active,
                            'account': account,
                            'account_form': account_form,
                            'org_form': org_form,
                            'group_form': group_form,
                        }, UserAdminContext(request))
Exemple #43
0
def edit(request, task_id=None, start_time=None):
    account = get_account(request)
    quickselect = QuickSelect(service=True)
    component_trail = None
    component_keys = None
    task = None
    num_components = 0

    if task_id:
        task = get_object_or_404(MaintenanceTask, pk=task_id)
    task_form = MaintenanceTaskForm(
                    initial=task_form_initial(task, start_time))

    if request.method == 'POST':
        component_keys = get_component_keys(request.POST)
    elif task:
        component_keys = {'service': [], 'netbox': [],
                          'room': [], 'location': []}
        for key, value in task.maintenancecomponent_set.values_list('key',
                                                                    'value'):
            if key in PRIMARY_KEY_INTEGER:
                value = int(value)
            component_keys[key].append(value)
    else:
        component_keys = get_component_keys(request.GET)

    if component_keys:
        component_data = components_for_keys(component_keys)
        components = structure_component_data(component_data)
        component_trail = task_component_trails(component_keys, components)
        num_components += (len(component_data['service'])
                                + len(component_data['netbox']))
        num_components += (len(component_data['room'])
                                + len(component_data['location']))

    if request.method == 'POST':
        if 'save' in request.POST:
            task_form = MaintenanceTaskForm(request.POST)
            if task_form.is_valid() and num_components > 0:
                start_time = task_form.cleaned_data['start_time']
                end_time = task_form.cleaned_data['end_time']
                no_end_time = task_form.cleaned_data['no_end_time']
                state = MaintenanceTask.STATE_SCHEDULED
                if (start_time < datetime.now() and end_time
                            and end_time <= datetime.now()):
                    state = MaintenanceTask.STATE_SCHEDULED

                new_task = MaintenanceTask()
                new_task.start_time = task_form.cleaned_data['start_time']
                if no_end_time:
                    new_task.end_time = INFINITY
                elif not no_end_time and end_time:
                    new_task.end_time = task_form.cleaned_data['end_time']
                new_task.description = task_form.cleaned_data['description']
                new_task.state = state
                new_task.author = account.login
                if task:
                    new_task.id = task.id
                new_task.save()

                if task:
                    cursor = connection.cursor()
                    sql = """DELETE FROM maint_component
                                WHERE maint_taskid = %s"""
                    cursor.execute(sql, (new_task.id,))
                    transaction.set_dirty()
                for key in component_data:
                    for component in component_data[key]:
                        task_component = MaintenanceComponent(
                            maintenance_task=new_task,
                            key=key,
                            value="%s" % component['id'])
                        task_component.save()
                new_message(request,
                            "Saved task %s" % new_task.description,
                            Messages.SUCCESS)
                return HttpResponseRedirect(reverse('maintenance-view',
                                                    args=[new_task.id]))
            if num_components <= 0:
                new_message(request, "No components selected.", Messages.ERROR)
        else:
            task_form = MaintenanceTaskForm(initial=request.POST)

    if task:
        navpath = NAVPATH + [('Edit', '')]
        heading = 'Editing "%s"' % task.description
        title = TITLE + " - " + heading
    else:
        navpath = NAVPATH + [('New', '')]
        heading = 'New task'
        title = TITLE + " - " + heading
    return render_to_response(
        'maintenance/new_task.html',
        {
            'active': {'new': True},
            'navpath': navpath,
            'title': title,
            'heading': heading,
            'task_form': task_form,
            'task_id': task_id,
            'quickselect': mark_safe(quickselect),
            'components': component_trail,
            'selected': component_keys,
        },
        RequestContext(request)
    )
Exemple #44
0
    if request.POST.get('confirm'):
        try:
            qs_delete(objects)
        except IntegrityError, ex:
            # We can't delete.
            # Some of the objects we want to delete is referenced by another
            # table without any ON DELETE rules.
            msg = "Integrity failed: %s" % ex
            new_message(request, msg, Messages.ERROR)
        except Exception, ex:
            # Something else went wrong
            LOGGER.exception("Unhandled exception during delete: %r", request)
            msg = "Error: %s" % ex
            new_message(request, msg, Messages.ERROR)
        else:
            new_message(request,
                        "Deleted %i rows" % len(objects), Messages.SUCCESS)
            return HttpResponseRedirect(reverse(redirect))

    info_dict = {
        'objects': objects,
        'sub_active': {'list': True},
    }
    extra_context.update(info_dict)
    return render_to_response('seeddb/delete.html',
        extra_context, RequestContext(request))

def dependencies(queryset, whitelist):
    """Looks up related objects for the provided queryset.
    Only looks up models provided in the whitelist.

    Will only display related objects, not what will happen if the user choose
Exemple #45
0
def move(request,
         model,
         form_model,
         redirect,
         title_attr='id',
         extra_context=None):

    if not extra_context:
        extra_context = {}

    # If no post or no objects selected, start over
    if request.method != 'POST':
        return HttpResponseRedirect(reverse(redirect))
    if not request.POST.getlist('object'):
        new_message(request, "You need to select at least one object to edit",
                    Messages.ERROR)
        return HttpResponseRedirect(reverse(redirect))

    data = None
    confirm = False
    verbose_name = model._meta.verbose_name
    objects = model.objects.filter(id__in=request.POST.getlist('object'))

    # Find out what step we are on, or default to start of wizard
    try:
        step = int(request.POST.get('step', '0'))
    except ValueError:
        step = STEP_CHANGEVALUES

    # Choose new values to foreign keys
    if step == STEP_CHANGEVALUES:
        form = form_model()
        step = STEP_CONFIRM

    # Confirm the changes
    elif step == STEP_CONFIRM:
        form = form_model(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            confirm = True
            step = STEP_SAVE

    # Update the objects
    elif step == STEP_SAVE:
        form = form_model(request.POST)
        if form.is_valid():
            foreign_keys = form.cleaned_data.keys()
            data = dict()

            # If nothing is selected, don't update
            for key in foreign_keys:
                if not form.cleaned_data[key] is None:
                    data[key] = form.cleaned_data[key]

            # Update
            objects.update(**data)

            # Generate message based on what was changed and redirect back
            foreign_key_string = ", ".join(
                [get_verbose_name(model, key) for key in data])

            if foreign_key_string == "":
                foreign_key_string = "nothing"

            new_message(
                request, "Changed %s on %i %s models" %
                (foreign_key_string, len(objects), verbose_name),
                Messages.SUCCESS)

            return HttpResponseRedirect(reverse(redirect))

    # Keep values from the form and pass them as context
    if form:
        fields = form.fields.keys()
    else:
        fields = form_model().fields.keys()

    values = objects.values('pk', title_attr, *fields)
    object_list = _parse_value_differences(values, data, title_attr, fields)

    context = {
        'form': form or '',
        'objects': objects,
        'values': object_list,
        'data': data,
        'confirm': confirm,
        'sub_active': {
            'list': True
        },
        'title': 'Move %s' % verbose_name,
        'step': step,
    }

    extra_context.update(context)

    return render(request, 'seeddb/move.html', extra_context)
Exemple #46
0
def edit(request, task_id=None, start_time=None, **_):
    account = get_account(request)
    quickselect = QuickSelect(service=True)
    component_trail = None
    component_keys = None
    task = None

    if task_id:
        task = get_object_or_404(MaintenanceTask, pk=task_id)
    task_form = MaintenanceTaskForm(
        initial=task_form_initial(task, start_time))

    if request.method == 'POST':
        component_keys = get_component_keys(request.POST)
    elif task:
        component_keys = {
            'service': [],
            'netbox': [],
            'room': [],
            'location': [],
            'netboxgroup': [],
        }
        for key, value in task.maintenancecomponent_set.values_list(
                'key', 'value'):
            if key in PRIMARY_KEY_INTEGER:
                value = int(value)
            component_keys[key].append(value)
    else:
        component_keys = get_component_keys(request.GET)

    if component_keys:
        component_data = components_for_keys(component_keys)
        components = structure_component_data(component_data)
        component_trail = task_component_trails(component_keys, components)

    if request.method == 'POST':
        if 'save' in request.POST:
            task_form = MaintenanceTaskForm(request.POST)
            if not any(component_data.values()):
                new_message(request, "No components selected.", Messages.ERROR)
            elif task_form.is_valid():
                start_time = task_form.cleaned_data['start_time']
                end_time = task_form.cleaned_data['end_time']
                no_end_time = task_form.cleaned_data['no_end_time']
                state = MaintenanceTask.STATE_SCHEDULED
                if (start_time < datetime.now() and end_time
                        and end_time <= datetime.now()):
                    state = MaintenanceTask.STATE_SCHEDULED

                new_task = MaintenanceTask()
                new_task.start_time = task_form.cleaned_data['start_time']
                if no_end_time:
                    new_task.end_time = INFINITY
                elif not no_end_time and end_time:
                    new_task.end_time = task_form.cleaned_data['end_time']
                new_task.description = task_form.cleaned_data['description']
                new_task.state = state
                new_task.author = account.login
                if task:
                    new_task.id = task.id
                new_task.save()

                if task:
                    cursor = connection.cursor()
                    sql = """DELETE FROM maint_component
                                WHERE maint_taskid = %s"""
                    cursor.execute(sql, (new_task.id, ))
                for key in component_data:
                    for component in component_data[key]:
                        task_component = MaintenanceComponent(
                            maintenance_task=new_task,
                            key=key,
                            value="%s" % component['id'],
                        )
                        task_component.save()
                new_message(request, "Saved task %s" % new_task.description,
                            Messages.SUCCESS)
                return HttpResponseRedirect(
                    reverse('maintenance-view', args=[new_task.id]))
        else:
            task_form = MaintenanceTaskForm(initial=request.POST)

    if task:
        navpath = NAVPATH + [('Edit', '')]
        heading = 'Editing "%s"' % task.description
        title = TITLE + " - " + heading
    else:
        navpath = NAVPATH + [('New', '')]
        heading = 'New task'
        title = TITLE + " - " + heading
    return render(
        request,
        'maintenance/new_task.html',
        {
            'active': {
                'new': True
            },
            'navpath': navpath,
            'title': title,
            'heading': heading,
            'task_form': task_form,
            'task_id': task_id,
            'quickselect': mark_safe(quickselect),
            'components': component_trail,
            'selected': component_keys,
        },
    )
Exemple #47
0
def group_detail(request, group_id=None):
    try:
        group = AccountGroup.objects.get(id=group_id)
    except AccountGroup.DoesNotExist:
        group = None

    group_form = AccountGroupForm(instance=group)
    account_form = AccountAddForm(group)
    privilege_form = PrivilegeForm()

    if request.method == 'POST':

        if 'submit_group' in request.POST:
            group_form = AccountGroupForm(request.POST, instance=group)

            if group_form.is_valid():
                # FIXME
                group = group_form.save()

                new_message(request,
                            '"%s" has been saved.' % (group),
                            type=Messages.SUCCESS)
                return HttpResponseRedirect(
                    reverse('useradmin-group_detail', args=[group.id]))

        elif 'submit_privilege' in request.POST:
            privilege_form = PrivilegeForm(request.POST)

            if privilege_form.is_valid():
                type = privilege_form.cleaned_data['type']
                target = privilege_form.cleaned_data['target']

                try:
                    group.privilege_set.get(type=type, target=target)
                    new_message(
                        request,
                        'Privilege was not added as it already exists.',
                        type=Messages.WARNING)
                except Privilege.DoesNotExist:
                    group.privilege_set.create(type=type, target=target)
                    new_message(request,
                                'Privilege has been added.',
                                type=Messages.SUCCESS)

                return HttpResponseRedirect(
                    reverse('useradmin-group_detail', args=[group.id]))
        elif 'submit_account' in request.POST:
            account_form = AccountAddForm(group, request.POST)

            if account_form.is_valid():
                try:
                    account = account_form.cleaned_data['account']
                    group.accounts.get(login=account.login)
                    new_message(request,
                                'Account %s was not added as it is already a '
                                'member of the group.' % account,
                                type=Messages.WARNING)
                except Account.DoesNotExist:
                    group.accounts.add(account)
                    new_message(request,
                                'Account %s has been added.' % account,
                                type=Messages.SUCCESS)

                return HttpResponseRedirect(
                    reverse('useradmin-group_detail', args=[group.id]))

    if group:
        active = {'group_detail': True}
    else:
        active = {'group_new': True}

    return render_to_response(
        'useradmin/group_detail.html', {
            'active': active,
            'group': group,
            'group_form': group_form,
            'account_form': account_form,
            'privilege_form': privilege_form,
        }, UserAdminContext(request))
Exemple #48
0
def account_group_remove(request,
                         account_id,
                         group_id,
                         missing_redirect=None,
                         plain_redirect=None):
    try:
        account = Account.objects.get(id=account_id)
    except Account.DoesNotExist:
        new_message(request,
                    'Account %s does not exist.' % (account_id),
                    type=Messages.ERROR)

        if missing_redirect:
            return HttpResponseRedirect(missing_redirect)
        return HttpResponseRedirect(reverse('useradmin-account_list'))

    try:
        group = account.accountgroup_set.get(id=group_id)
    except AccountGroup.DoesNotExist:
        new_message(request,
                    'Group %s does not exist or it is not associated with '
                    '%s.' % (group_id, account),
                    type=Messages.WARNING)

        if plain_redirect:
            return HttpResponseRedirect(plain_redirect)
        return HttpResponseRedirect(
            reverse('useradmin-account_detail', args=[account.id]))

    if group.is_protected_group():
        new_message(request,
                    '%s can not be removed from %s as it is a protected '
                    'group.' % (account, group),
                    type=Messages.ERROR)

        if plain_redirect:
            return HttpResponseRedirect(plain_redirect)
        return HttpResponseRedirect(
            reverse('useradmin-account_detail', args=[account.id]))

    if group.is_admin_group() and account.is_admin_account():
        new_message(request,
                    '%s can not be removed from %s.' % (account, group),
                    type=Messages.ERROR)

        if plain_redirect:
            return HttpResponseRedirect(plain_redirect)
        return HttpResponseRedirect(
            reverse('useradmin-account_detail', args=[account.id]))

    if request.method == 'POST':
        account.accountgroup_set.remove(group)
        new_message(request,
                    '%s has been removed from %s.' % (account, group),
                    type=Messages.SUCCESS)

        if plain_redirect:
            return HttpResponseRedirect(plain_redirect)
        return HttpResponseRedirect(
            reverse('useradmin-account_detail', args=[account.id]))

    return render_to_response(
        'useradmin/delete.html', {
            'name': '%s from the group %s' % (account, group),
            'type': 'account',
            'back': reverse('useradmin-account_detail', args=[account.id]),
        }, UserAdminContext(request))
Exemple #49
0
def account_detail(request, account_id=None):
    try:
        account = Account.objects.get(id=account_id)
    except Account.DoesNotExist:
        account = None

    account_form = AccountForm(instance=account)
    org_form = OrganizationAddForm(account)
    group_form = GroupAddForm(account)

    if request.method == 'POST':
        if 'submit_account' in request.POST:
            account_form = AccountForm(request.POST, instance=account)

            if account_form.is_valid():
                account = account_form.save(commit=False)

                if 'password1' in account_form.cleaned_data and \
                account_form.cleaned_data['password1'] and not account.ext_sync:
                    account.set_password(
                        account_form.cleaned_data['password1'])

                account.save()

                new_message(request,
                            '"%s" has been saved.' % (account),
                            type=Messages.SUCCESS)
                return HttpResponseRedirect(
                    reverse('useradmin-account_detail', args=[account.id]))

        elif 'submit_org' in request.POST:
            org_form = OrganizationAddForm(account, request.POST)

            if org_form.is_valid():
                organization = org_form.cleaned_data['organization']

                try:
                    account.organizations.get(id=organization.id)
                    new_message(request,
                                'Organization was not added as it has already '
                                'been added.',
                                type=Messages.WARNING)
                except Organization.DoesNotExist:
                    account.organizations.add(organization)
                    new_message(request,
                                'Added organization "%s" to account "%s"' %
                                (organization, account),
                                type=Messages.SUCCESS)

                return HttpResponseRedirect(
                    reverse('useradmin-account_detail', args=[account.id]))

        elif 'submit_group' in request.POST:
            group_form = GroupAddForm(account, request.POST)

            if group_form.is_valid():
                group = group_form.cleaned_data['group']

                if ((group.is_admin_group() or group.is_protected_group())
                        and account.is_default_account()):
                    new_message(request,
                                'Default user may not be added to "%s" '
                                'group.' % group,
                                type=Messages.ERROR)
                else:
                    try:
                        account.accountgroup_set.get(id=group.id)
                        new_message(request,
                                    'Group was not added as it has already '
                                    'been added.',
                                    type=Messages.WARNING)
                    except AccountGroup.DoesNotExist:
                        account.accountgroup_set.add(group)
                        new_message(request,
                                    'Added "%s" to group "%s"' %
                                    (account, group),
                                    type=Messages.SUCCESS)

                return HttpResponseRedirect(
                    reverse('useradmin-account_detail', args=[account.id]))

        elif 'submit_sudo' in request.POST:
            sudo_account_id = request.POST.get('account')
            try:
                sudo_account = Account.objects.get(pk=sudo_account_id)
            except Account.DoesNotExist:
                new_message(request, 'Account not found.', type=Message.ERROR)
            else:
                sudo(request, sudo_account)
            return HttpResponseRedirect(reverse('webfront-index'))

    if account:
        active = {'account_detail': True}
        current_user = get_account(request)
    else:
        active = {'account_new': True}

    return render_to_response(
        'useradmin/account_detail.html', {
            'active': active,
            'account': account,
            'account_form': account_form,
            'org_form': org_form,
            'group_form': group_form,
        }, UserAdminContext(request))
Exemple #50
0
def save_preferences(request):
    """Controller for saving the preferences"""
    if not request.method == 'POST':
        return HttpResponseRedirect(reverse('status-preferences'))

    account = get_account(request)

    type = request.POST.get('type', None)
    section_model = get_section_model(type)
    form_model = section_model.form_class()
    form = form_model(request.POST)

    if type and form.is_valid():
        try:
            section = StatusPreference.objects.get(id=form.cleaned_data['id'])
            type = section.type
        except StatusPreference.DoesNotExist:
            section = StatusPreference()
            section.position = StatusPreference.objects.count()
            type = form.cleaned_data['type']
            section.type = type

        section.name = form.cleaned_data['name']
        section.account = account
        if 'states' in form.cleaned_data:
            section.states = ",".join(form.cleaned_data['states'])
        if type in SERVICE_SECTIONS:
            section.services = ",".join(form.cleaned_data['services'])

        section.save()

        section.organizations = Organization.objects.filter(
            id__in=form.cleaned_data['organizations'])

        if type not in SERVICE_SECTIONS:
            section.categories = Category.objects.filter(
                id__in=form.cleaned_data['categories'])

        new_message(request, 'Saved preferences', Messages.SUCCESS)
        return HttpResponseRedirect(reverse('status-preferences'))
    else:
        if 'id' in request.POST and request.POST.get('id'):
            section = StatusPreference.objects.get(id=request.POST.get('id'))
            name = section.name
            type = section.type
        elif 'type' in request.POST and request.POST.get('type'):
            name = StatusPreference.lookup_readable_type(
                request.POST.get('type'))
            type = None

        new_message(request, 'There were errors in the form below.',
                    Messages.ERROR)
        return render_to_response(
            'status/edit_preferences.html', {
                'active': {
                    'preferences': True
                },
                'title': 'NAV - Add new status section',
                'navpath': [('Home', '/'), ('Status', '')],
                'section_form': form,
                'name': name,
                'type': type,
            }, RequestContext(request))
Exemple #51
0
def alertprofiles_response_forbidden(request, message):
    new_message(request, '403 Forbidden', Messages.ERROR)
    new_message(request, message, Messages.ERROR)

    return _alertprofiles_response(request, 403)
Exemple #52
0
def account_group_remove(request, account_id, group_id, missing_redirect=None,
                         plain_redirect=None):
    try:
        account = Account.objects.get(id=account_id)
    except Account.DoesNotExist:
        new_message(request, 'Account %s does not exist.' % (account_id),
                    type=Messages.ERROR)

        if missing_redirect:
            return HttpResponseRedirect(missing_redirect)
        return HttpResponseRedirect(reverse('useradmin-account_list'))

    try:
        group = account.accountgroup_set.get(id=group_id)
    except AccountGroup.DoesNotExist:
        new_message(request,
                    'Group %s does not exist or it is not associated with '
                    '%s.' % (group_id, account),
                    type=Messages.WARNING)

        if plain_redirect:
            return HttpResponseRedirect(plain_redirect)
        return HttpResponseRedirect(reverse('useradmin-account_detail',
                                            args=[account.id]))

    if group.is_protected_group():
        new_message(request,
                    '%s can not be removed from %s as it is a protected '
                    'group.' % (account, group),
                    type=Messages.ERROR)

        if plain_redirect:
            return HttpResponseRedirect(plain_redirect)
        return HttpResponseRedirect(reverse('useradmin-account_detail',
                                            args=[account.id]))

    if group.is_admin_group() and account.is_admin_account():
        new_message(request,
                    '%s can not be removed from %s.' % (account, group),
                    type=Messages.ERROR)

        if plain_redirect:
            return HttpResponseRedirect(plain_redirect)
        return HttpResponseRedirect(reverse('useradmin-account_detail',
                                            args=[account.id]))

    if request.method == 'POST':
        account.accountgroup_set.remove(group)
        new_message(request,
                    '%s has been removed from %s.' % (account, group),
                    type=Messages.SUCCESS)

        if plain_redirect:
            return HttpResponseRedirect(plain_redirect)
        return HttpResponseRedirect(reverse('useradmin-account_detail',
                                            args=[account.id]))

    return render_to_response('useradmin/delete.html',
                        {
                            'name': '%s from the group %s' % (account, group),
                            'type': 'account',
                            'back': reverse('useradmin-account_detail',
                                            args=[account.id]),
                        }, UserAdminContext(request))
Exemple #53
0
def alertprofiles_response_forbidden(request, message):
    new_message(request, '403 Forbidden', Messages.ERROR)
    new_message(request, message, Messages.ERROR)

    return _alertprofiles_response(request, 403)
Exemple #54
0
def alertprofiles_response_not_found(request, message):
    new_message(request, '404 Not Found', Messages.ERROR)
    new_message(request, message, Messages.ERROR)

    return _alertprofiles_response(request, 404)
Exemple #55
0
def alertprofiles_response_not_found(request, message):
    new_message(request, '404 Not Found', Messages.ERROR)
    new_message(request, message, Messages.ERROR)

    return _alertprofiles_response(request, 404)