Exemple #1
0
def verify_tintri_endpoint(request):
    tintri = Tintri()
    endpoint = tintri.get_connection_info()
    if not endpoint:
        messages.warn(
            request, "No Tintri Connection Endpoint found! Nothing to verify")
        return HttpResponseRedirect(request.META['HTTP_REFERER'])
    try:
        tintri.verify_connection()
    except Exception as err:
        status = 'danger'
        msg = format_html('Could not make a connection to the Tintri Appliance '
                          '<b>"{}"</b>:<br>{}', endpoint, str(err))
    else:
        status = 'success'
        msg = format_html('Successfully connected to the Tintri Appliance at '
                          '<b>"{}"</b>.', endpoint)
    # The alert helper tag will escape the state and msg if they aren't properly
    # marked safe (after any necessary escaping with format_html) here
    content = helper_tags.alert(status, msg)

    return {
        'title': "Verify connection to Tintri Appliance's Connection Endpoint",
        'content': content,
        'submit': None,
        'cancel': "OK",
    }
Exemple #2
0
    def get_queryset(self):
        """
        Ensure that only the complex 'take cut' RDP's are considered.

        Exclude RDP's that only have payouts that are new and unprotected, as
        these will automatically be updated by re-calculating the payout.
        """

        # find RDP's that have project payouts and a 'bad' status
        queryset = RemoteDocdataPayment.objects.filter(
            status=RemoteDocdataPayment.IntegrityStatus.InconsistentChargeback,
            local_payment__order_payment__order__donations__project__projectpayout__isnull=False
        )

        payout_ids = list(queryset.values_list(
            'local_payment__order_payment__order__donations__project__projectpayout', flat=True
        ).distinct())

        if not payout_ids:
            messages.warn(_('There were no payouts for this payment - aborting.'))

        payouts_to_ignore = list(ProjectPayout.objects.filter(id__in=payout_ids).exclude(
            status=StatusDefinition.NEW,
            protected=False
        ).values_list('id', flat=True))

        for pk in payouts_to_ignore:
            payout_ids.remove(pk)

        return queryset.filter(
            local_payment__order_payment__order__donations__project__projectpayout__id__in=payout_ids
        ).distinct()
Exemple #3
0
def create_update(request, title=""):
    """Creates or updates wiki entry

    Arguments:
        request {obj} -- Django request
        title {str} -- Name of Wiki entry to update

    Returns:
        [Django view] -- rendered view template 'edit-entry/'
    """

    context = {"config": "create"}
    previous_title = title
    if request.method == "POST":
        title = request.POST.get("title", "").strip()
        content = request.POST.get("content", "").strip()
        submit = request.POST.get("submit")
        hidden = request.POST.get("config")

        if submit is None:
            # User cancelled request
            if "create" in hidden:
                # Cancelled creating - redirect to index
                return redirect(index)
            else:
                # Cancelled updating - redirect to wiki entry
                return redirect(reverse("wiki_entry", kwargs={"title": title}))
        elif not title or not content:
            # Submitted but no content was added.
            # (mainly for creation since update already have content)
            # Redirect user to the same page to make changes
            messages.warn(
                request, f" You must add a title and content to create entry!")
            return render(request, "encyclopedia/create_edit_entry.html",
                          context)

        # Setup saving the entry
        action = "updated" if "edit" in hidden else "created"
        if action == "updated":
            # delete previous entry
            util.delete_entry(previous_title)
        messages.success(request, f" Your entry was {action} successfully!")
        return saveHandler(request, title=title, content=content)

    else:  # GET Request
        context = {"config": "create"}  # default value
        if title:
            entry = util.get_entry(title)
            if not entry or entry is None:
                return redirect(notFound)
            context["entry"] = entry
            context["config"] = "edit"

        # Convert entry from html to Markdown
        context.update({
            "title": title,
            "unavailable_entry": util.list_entries(),
        })
    return render(request, "encyclopedia/create_edit_entry.html", context)
 def post(self, request, *args, **kwargs):
     txn = self.get_object()
     if txn.confirm():
         messages.success(self.request, _("Cash collection confirmed"))
     else:
         messages.warn(self.request, _("Already confirmed as collected"))
     return HttpResponseRedirect(
         reverse('cashondelivery-transaction-detail',
                 kwargs={'pk': txn.pk}))
Exemple #5
0
def update(request):
    '''
    edit task
    '''
    if request.method == 'GET':
        task_id = int(request.GET['id'])
        result = '任务(id=%d)' % task_id
        try:
            task = Task.objects.get(pk = task_id)
            key = "run_time_"+task.type
            initial = {key : task.run_time}
            form = TaskForm(instance=task, initial=initial)
            form.helper.form_action = '/task/update?id=%d' % task_id 
        except ObjectDoesNotExist:
            logger.warn('edit task %d failed: task does not exist' % (task_id))
            messages.error(request, result + "不存在")
            return HttpResponseRedirect('/task/index')
        except Exception:
            logger.exception('edit task %d failed' % (task_id))
            messages.error(request, result + '编辑失败' )
            return HttpResponseRedirect('/task/index')

        context = {"task":task, 'form':form}
        return render(request, 'task/edit.tpl', context)

    elif request.method != 'POST':
        return HttpResponse(status=400)

    try:
        task_id = int(request.REQUEST.get('id', 0))
        result = '任务(id=%d)' % task_id
        task = Task.objects.get(pk=task_id)
        form = TaskForm(request.POST, instance=task)
        if form.is_valid():
            task = form.save(commit=False)
            task.run_time = form.cleaned_data['run_time']
            task.save()
        else:
            raise ValidationError()
    except ObjectDoesNotExist:
        logger.warn(request, 'update task (id=%d) failed: task not exist' % task_id)
        messages.warn(request, result+"不存在")
        return HttpResponseRedirect('/task/index')
    except ValidationError:
        logger.exception('update task(id=%d) failed: task validate failed' % task_id)
        messages.error(request, result+"验证失败")
        return render('task/edit', {'form':form})
    except Exception:
        logger.exception('update task(id=%d) failed' % (task_id))
        messages.error(request, result+"修改失败")
        return render('task/edit', {'form':form})

    messages.success(request, result+'修改成功')
    return HttpResponseRedirect('/task/show?id=%d' % task_id)
Exemple #6
0
def location_delete(request, loc_id=None):
    if not request.user.is_superuser or not request.user.is_staff:
        messages.warn(request, "Unauthorized")
    elif loc_id is not None:
        if Location.objects.filter(id=loc_id):
            item = Location.objects.get(id=loc_id)
            item.delete()
            messages.info(request, "Location Deleted")
        else:
            messages.warning(request, "No location to delete")
    else:
        messages.warning(request, "No location found")
    return locations(request)
Exemple #7
0
def conference_delete(request, code=None):
    if not request.user.is_superuser:
        messages.warn(request, "Unauthorized")
    elif code is not None:
        if Conference.objects.filter(code=code):
            item = Conference.objects.get(code=code)
            item.delete()
            messages.info(request, "Conference Deleted")
        else:
            messages.warning(request, "No conference to delete")
    else:
        messages.warning(request, "No conference found")
    return conferences(request)
Exemple #8
0
def notification_delete(request, n_id=None):
    if not request.user.is_superuser or not request.user.is_staff:
        messages.warn(request, "Unauthorized")
    elif n_id is not None:
        if Notification.objects.filter(id=n_id):
            a = Notification.objects.get(id=n_id)
            a.delete()
            messages.info(request, "Notification Deleted")
        else:
            messages.warning(request, "No notification to delete")
    else:
        messages.warning(request, "No notification found")
    return notifications(request)
Exemple #9
0
def village_delete(request, vil_id=None):
    if not request.user.is_superuser or not request.user.is_staff:
        messages.warn(request, "Unauthorized")
    elif vil_id is not None:
        if Village.objects.filter(id=vil_id):
            vil = Village.objects.get(id=vil_id)
            vil.delete()
            messages.info(request, "Village Deleted")
        else:
            messages.warning(request, "No village to delete")
    else:
        messages.warning(request, "No village found")
    return villages(request)
Exemple #10
0
def article_delete(request, a_id=None):
    if not request.user.is_superuser or not request.user.is_staff:
        messages.warn(request, "Unauthorized")
    elif a_id is not None:
        if Article.objects.filter(id=a_id):
            a = Article.objects.get(id=a_id)
            a.delete()
            messages.info(request, "Article Deleted")
        else:
            messages.warning(request, "No article to delete")
    else:
        messages.warning(request, "No article found")
    return articles(request)
Exemple #11
0
def faq_delete(request, f_id=None):
    if not request.user.is_superuser or not request.user.is_staff:
        messages.warn(request, "Unauthorized")
    elif f_id is not None:
        if FAQ.objects.filter(id=f_id):
            a = FAQ.objects.get(id=f_id)
            a.delete()
            messages.info(request, "FAQ Item Deleted")
        else:
            messages.warning(request, "No FAQ item to delete")
    else:
        messages.warning(request, "No FAQ item found")
    return faqs(request)
Exemple #12
0
def speaker_delete(request, sp_id=None):
    if not request.user.is_superuser or not request.user.is_staff:
        messages.warn(request, "Unauthorized")
    elif sp_id is not None:
        if Speaker.objects.filter(id=sp_id):
            sp = Speaker.objects.get(id=sp_id)
            sp.delete()
            messages.info(request, "Speaker Deleted")
        else:
            messages.warning(request, "No speaker to delete")
    else:
        messages.warning(request, "No speaker found")
    return speakers(request)
Exemple #13
0
def vendor_delete(request, v_id=None):
    if not request.user.is_superuser or not request.user.is_staff:
        messages.warn(request, "Unauthorized")
    elif v_id is not None:
        if Vendor.objects.filter(id=v_id):
            ven = Vendor.objects.get(id=v_id)
            ven.delete()
            messages.info(request, "Vendor Deleted")
        else:
            messages.warning(request, "No vendor to delete")
    else:
        messages.warning(request, "No vendor found")
    return vendors(request)
Exemple #14
0
def event_type_delete(request, et_id=None):
    if not request.user.is_superuser or not request.user.is_staff:
        messages.warn(request, "Unauthorized")
    elif et_id is not None:
        if EventType.objects.filter(id=et_id):
            item = EventType.objects.get(id=et_id)
            item.delete()
            messages.info(request, "Event Type Deleted")
        else:
            messages.warning(request, "No event type to delete")
    else:
        messages.warning(request, "No event type found")
    return event_types(request)
Exemple #15
0
def send_login_token(request):
    if request.method == 'POST':
        form = LoginTokenRequestForm(request.POST)
        if form.is_valid():
            try:
                user = UserModel.objects.get(email=form.cleaned_data['email'])
            except UserModel.DoesNotExist:
                messages.warn(request, "No such user")
                return redirect(reverse("security.views.send_login_token"))

            m = hashlib.md5()
            m.update(time.asctime())
            user.login_token = m.hexdigest()
            user.login_token_expires = timezone.now() + timedelta(hours=24)

            secret_number = randint(0, 1000000)

            m2 = hashlib.md5()
            m2.update(m.hexdigest())
            m2.update(str(secret_number))
            user.secret_token = m2.hexdigest()

            user.save()

            link = request.build_absolute_uri(
                reverse('security.views.login_with_token',
                        kwargs={"login_token": user.login_token}))

            send_mail(subject="login token",
                      message=LOGIN_MESSAGE.format(link),
                      from_email="noreply",
                      recipient_list=[
                          user.email,
                      ])

            messages.success(request, "login token sent to your email")
            response = HttpResponseRedirect(
                reverse("security.views.send_login_token"))
            response.set_cookie("login_number", value=secret_number)
            return response
    else:
        form = LoginTokenRequestForm()

    return render(request, "send_login_token.html", {"form": form})
Exemple #16
0
def send_login_token(request):
    if request.method == 'POST':
        form = LoginTokenRequestForm(request.POST)
        if form.is_valid():
            try:
                user = UserModel.objects.get(email=form.cleaned_data['email'])
            except UserModel.DoesNotExist:
                messages.warn(request, "No such user")
                return redirect(reverse("security.views.send_login_token"))
            
            m = hashlib.md5()
            m.update(time.asctime())
            user.login_token = m.hexdigest()
            user.login_token_expires = timezone.now() + timedelta(hours=24)
            
            secret_number = randint(0, 1000000)
            
            m2 = hashlib.md5()
            m2.update(m.hexdigest())
            m2.update(str(secret_number))
            user.secret_token = m2.hexdigest()
            
            user.save()
            
            link = request.build_absolute_uri(
                reverse('security.views.login_with_token', 
                        kwargs={"login_token" : user.login_token}))
            
            send_mail(subject="login token", 
                      message=LOGIN_MESSAGE.format(link),
                      from_email="noreply", recipient_list=[user.email,])
            
            messages.success(request, "login token sent to your email")
            response = HttpResponseRedirect(reverse("security.views.send_login_token"))
            response.set_cookie("login_number", value=secret_number)
            return response
    else:
        form = LoginTokenRequestForm()

    return render(request, "send_login_token.html", {"form" : form})
def project_team_invite(request, project_slug):
    project = Project.objects.get(slug=project_slug)
    if not project.viewable(request):
        return HttpResponseForbidden()
    if not project.manageable(request):
        return HttpResponseForbidden()

    username = request.POST['username']
    user = User.objects.get(username=username)

    if request.POST.get("action") == "remove":
        try:
            invite = ProjectInvite.objects.get(user=user, project=project)
        except ProjectInvite.DoesNotExist:
            messages.warn(request, "No invitation to remove!")
            return redirect(project)
        invite.delete()
        messages.info(request, "The invitation has been retracted.")
        return redirect(project)

    if project.has_member(user):
        messages.error(request, "That guy is already a member of this project.")
        return redirect(project)

    try:
        invite = ProjectInvite.objects.get(user=user, project=project)
    except ProjectInvite.DoesNotExist:
        invite = ProjectInvite.objects.create(user=user, project=project,
                                              inviter=request.user)
    else:
        invite.remind(request.POST.get("message"))
        messages.info(request,
                      "A reminder has been sent to %s" % user.username)
        return redirect(project)
    invite.send(request.POST.get("message"))
    messages.success(request,
                     "An invitation has been sent to %s" % user.username)
    return redirect(project)
Exemple #18
0
def verify_veeam_endpoint(request):
    veeam = VeeamManager()
    endpoint = veeam.get_connection_info()
    if not endpoint:
        messages.warn(request, "No Veeam Endpoint found! Nothing to verify")
        return HttpResponseRedirect(request.META['HTTP_REFERER'])
    try:
        veeam.verify_connection()
    except Exception as err:
        msg = format_html(
            'Could not make a connection to the Veeam Server Manager at'
            '<b>"{}"</b>:<br>{}', endpoint, str(err))
    else:
        msg = format_html(
            'Successfully connected to the Veeam Server Manager at '
            '<b>"{}"</b>.', endpoint)

    return {
        'title': 'Verify connection to Veeam Server Manager Endpoint',
        'content': msg,
        'submit': None,
        'cancel': "OK",
    }
Exemple #19
0
def create_language(request,
                    lang=None,
                    fvlist=None,
                    clone=False,
                    *args,
                    **kwargs):
    me = 'language'
    state = 'new'
    user = request.user

    # sort values into categories
    cats = make_feature_list_for_lang(lang=lang, fvlist=fvlist)

    editorform = EditorForm()

    cloned_from_lang = None
    if clone:
        author = request.user.profile.display_name
        name = 'Clone'
        if lang:
            name = 'Clone of %s' % lang
        elif fvlist:
            name = 'Clone of %i features' % len(fvlist)
        background = name
        langform = LanguageForm(initial={
            'name': name,
            'background': background,
            'author': author
        })
        cloned_from_lang = lang
    else:
        langform = LanguageForm()

    if request.method == 'POST':
        langform = LanguageForm(data=request.POST, initial=request.POST)
        if langform.is_valid():
            with transaction.atomic():
                lang = langform.save(commit=False)
                if language_exists(lang.name):
                    url = '/language/%s/' % lang.get_slug()
                    msg = '''A language named <a href="%s">%s</a> already
                    exists, you should edit that one or change the name of
                    this one''' % (url, escape(lang.name))
                    messages.error(request, msg)
                else:
                    # Good, not a dupe
                    lang.added_by = user
                    lang.last_modified_by = user
                    if not lang.manager:
                        lang.manager = user
                    # Must save early since is foreign-key in many other tables
                    lang.save(user=user, solo=False)
                    # Save tags if any
                    lang, tags_changed = set_tags_for_lang(
                        langform.cleaned_data['tags'], lang)
                    # Set editors
                    editorform = EditorForm(data=request.POST, instance=lang)
                    if editorform.is_valid():
                        editorform.save()
                    # greeting
                    if lang.greeting:
                        # use signal instead?
                        greetingexercise = TranslationExercise.objects.get(
                            id=1)
                        trans = Translation(translation=lang.greeting,
                                            language=lang,
                                            translator=user,
                                            exercise=greetingexercise)
                        trans.save()

                    # values
                    lang = set_featurevalues_for_lang(
                        lang, request.POST.getlist('value'))

                    # Final save
                    lang.save(user=user)
                    if cloned_from_lang:
                        streamaction.send(request.user,
                                          verb='cloned the language',
                                          action_object=cloned_from_lang,
                                          target=lang)
                    else:
                        streamaction.send(request.user,
                                          verb='added the language',
                                          action_object=lang)
                    messages.info(
                        request,
                        'You successfully added the language %s to CALS' %
                        lang.name)
                    return HttpResponseRedirect('/language/%s/' % lang.slug)
        else:
            if not clone:
                error = "Couldn't store language-description: " + str(
                    langform.errors)
                messages.error(request, error)
            else:
                help = "Remember to fill out the name and author of the language"
                messages.warn(request, help)
    data = {
        'form': langform,
        'categories': cats,
        'me': me,
        'editorform': editorform,
        'state': state,
        'clone': clone,
    }
    return render(request, 'language_form.html', data)
Exemple #20
0
 def do_delete(self, line):
     u"""Delete line item"""
     line.delete()
     msg = "'%s' has been removed" % line.product
     messages.warn(self.request, msg)
Exemple #21
0
def create_language(request, lang=None, fvlist=None, clone=False, *args, **kwargs):
    me = 'language'
    state = 'new'
    user = request.user

    # sort values into categories
    cats = make_feature_list_for_lang(lang=lang, fvlist=fvlist)

    editorform = EditorForm()

    cloned_from_lang = None
    if clone:
        author = request.user.profile.display_name
        name = 'Clone'
        if lang:
            name = 'Clone of %s' % lang
        elif fvlist:
            name = 'Clone of %i features' % len(fvlist)
        background = name
        langform = LanguageForm(initial={
                'name': name,
                'background': background,
                'author': author})
        cloned_from_lang = lang
    else:
        langform = LanguageForm()

    if request.method == 'POST':
        langform = LanguageForm(data=request.POST, initial=request.POST)
        if langform.is_valid():
            with transaction.atomic():
                lang = langform.save(commit=False)
                if language_exists(lang.name):
                    url = '/language/%s/' % lang.get_slug()
                    msg = '''A language named <a href="%s">%s</a> already
                    exists, you should edit that one or change the name of
                    this one''' % (url, escape(lang.name))
                    messages.error(request, msg)
                else:
                    # Good, not a dupe
                    lang.added_by = user
                    lang.last_modified_by = user
                    if not lang.manager:
                        lang.manager = user
                    # Must save early since is foreign-key in many other tables
                    lang.save(user=user, solo=False)
                    # Save tags if any
                    lang, tags_changed = set_tags_for_lang(langform.cleaned_data['tags'], lang)
                    # Set editors
                    editorform = EditorForm(data=request.POST, instance=lang)
                    if editorform.is_valid():
                        editorform.save()
                    # greeting
                    if lang.greeting:
                        # use signal instead?
                        greetingexercise = TranslationExercise.objects.get(id=1)
                        trans = Translation(translation=lang.greeting, language=lang,
                                translator=user, exercise=greetingexercise)
                        trans.save()

                    # values
                    lang = set_featurevalues_for_lang(lang, request.POST.getlist('value'))

                    # Final save
                    lang.save(user=user)
                    if cloned_from_lang:
                        streamaction.send(request.user, verb='cloned the language', action_object=cloned_from_lang, target=lang)
                    else:
                        streamaction.send(request.user, verb='added the language', action_object=lang)
                    messages.info(request, 'You successfully added the language %s to CALS' % lang.name)
                    return HttpResponseRedirect('/language/%s/' % lang.slug)
        else:
            if not clone:
                error = "Couldn't store language-description: " + str(langform.errors)
                messages.error(request, error)
            else:
                help = "Remember to fill out the name and author of the language"
                messages.warn(request, help)
    data = {'form': langform,
            'categories': cats,
            'me': me,
            'editorform': editorform,
            'state': state,
            'clone': clone,
    }
    return render(request, 'language_form.html', data)