コード例 #1
0
ファイル: views.py プロジェクト: jbuck/zamboni
def payments(request, status=None):
    # Note this is not post required, because PayPal does not reply with a
    # POST but a GET, that's a sad face.
    if status:
        pre, created = (PreApprovalUser.objects
                        .safer_get_or_create(user=request.amo_user))

        if status == 'complete':
            # The user has completed the setup at PayPal and bounced back.
            if 'setup-preapproval' in request.session:
                messages.success(request, loc('Pre-approval setup.'))
                paypal_log.info(u'Preapproval key created for user: %s'
                                % request.amo_user)
                data = request.session.get('setup-preapproval', {})
                pre.update(paypal_key=data.get('key'),
                           paypal_expiry=data.get('expiry'))
                del request.session['setup-preapproval']

        elif status == 'cancel':
            # The user has chosen to cancel out of PayPal. Nothing really
            # to do here, PayPal just bounces to this page.
            messages.success(request, loc('Pre-approval changes cancelled.'))

        elif status == 'remove':
            # The user has an pre approval key set and chooses to remove it
            if pre.paypal_key:
                pre.update(paypal_key='')
                messages.success(request, loc('Pre-approval removed.'))
                paypal_log.info(u'Preapproval key removed for user: %s'
                                % request.amo_user)

    context = {'preapproval': request.amo_user.get_preapproval()}
    return jingo.render(request, 'users/payments.html', context)
コード例 #2
0
ファイル: views.py プロジェクト: dbialer/zamboni
def payments(request, status=None):
    # Note this is not post required, because PayPal does not reply with a
    # POST but a GET, that's a sad face.
    if status:
        pre, created = PreApprovalUser.objects.safer_get_or_create(user=request.amo_user)

        if status == "complete":
            # The user has completed the setup at PayPal and bounced back.
            if "setup-preapproval" in request.session:
                messages.success(request, loc("Pre-approval set up."))
                paypal_log.info(u"Preapproval key created for user: %s" % request.amo_user)
                data = request.session.get("setup-preapproval", {})
                pre.update(paypal_key=data.get("key"), paypal_expiry=data.get("expiry"))
                del request.session["setup-preapproval"]

        elif status == "cancel":
            # The user has chosen to cancel out of PayPal. Nothing really
            # to do here, PayPal just bounces to this page.
            messages.success(request, loc("Pre-approval changes cancelled."))

        elif status == "remove":
            # The user has an pre approval key set and chooses to remove it
            if pre.paypal_key:
                pre.update(paypal_key="")
                messages.success(request, loc("Pre-approval removed."))
                paypal_log.info(u"Preapproval key removed for user: %s" % request.amo_user)

        context = {"preapproval": pre}
    else:
        context = {"preapproval": request.amo_user.get_preapproval()}

    return jingo.render(request, "users/payments.html", context)
コード例 #3
0
ファイル: views.py プロジェクト: jbuck/zamboni
def register(request):

    if settings.APP_PREVIEW:
        messages.error(request,
                       loc('Registrations must be through browserid.'))
        form = None

    elif (settings.REGISTER_USER_LIMIT and
          UserProfile.objects.count() > settings.REGISTER_USER_LIMIT
          and not can_override_reg_limit(request)):
        _m = loc('Sorry, no more registrations are allowed. '
                 '<a href="https://developer.mozilla.org/en-US/apps">'
                 'Learn more</a>')
        messages.error(request, _m, title_safe=True, message_safe=True)
        form = None

    elif request.user.is_authenticated():
        messages.info(request, _('You are already logged in to an account.'))
        form = None

    elif request.method == 'POST':

        form = forms.UserRegisterForm(request.POST)

        if form.is_valid():
            try:
                u = form.save(commit=False)
                u.set_password(form.cleaned_data['password'])
                u.generate_confirmationcode()
                u.save()
                u.create_django_user()
                log.info(u'Registered new account for user (%s)', u)
                log_cef('New Account', 5, request, username=u.username,
                        signature='AUTHNOTICE',
                        msg='User created a new account')

                u.email_confirmation_code()

                msg = _('Congratulations! Your user account was successfully '
                        'created.')
                messages.success(request, msg)

                msg = _(u'An email has been sent to your address {0} to '
                         'confirm your account. Before you can log in, you '
                         'have to activate your account by clicking on the '
                         'link provided in this email.').format(u.email)
                messages.info(request, _('Confirmation Email Sent'), msg)
            except IntegrityError, e:
                # I was unable to reproduce this, but I suspect it happens
                # when they POST twice quickly and the slaves don't have the
                # new info yet (total guess).  Anyway, I'm assuming the
                # first one worked properly, so this is still a success
                # case to tne end user so we just log it...
                log.error('Failed to register new user (%s): %s' % (u, e))

            return http.HttpResponseRedirect(reverse('users.login'))

        else:
            messages.error(request, _('There are errors in this form'),
                            _('Please correct them and resubmit.'))
コード例 #4
0
ファイル: views.py プロジェクト: ryandoherty/zamboni
def payments(request, status=None):
    # Note this is not post required, because PayPal does not reply with a
    # POST but a GET, that's a sad face.
    if status:
        pre, created = (PreApprovalUser.objects.safer_get_or_create(
            user=request.amo_user))

        if status == 'complete':
            # The user has completed the setup at PayPal and bounced back.
            messages.success(request, loc('Pre-approval setup.'))
            paypal_log.info(u'Preapproval key created for user: %s' %
                            request.amo_user)
            data = request.session.get('setup-preapproval', {})
            pre.update(paypal_key=data.get('key'),
                       paypal_expiry=data.get('expiry'))
            del request.session['setup-preapproval']

        elif status == 'cancel':
            # The user has chosen to cancel out of PayPal. Nothing really
            # to do here, PayPal just bounces to this page.
            messages.success(request, loc('Pre-approval changes cancelled.'))

        elif status == 'remove':
            # The user has an pre approval key set and chooses to remove it
            if pre.paypal_key:
                pre.update(paypal_key='')
                messages.success(request, loc('Pre-approval removed.'))
                paypal_log.info(u'Preapproval key removed for user: %s' %
                                request.amo_user)

    context = {'preapproval': request.amo_user.get_preapproval()}
    return jingo.render(request, 'users/payments.html', context)
コード例 #5
0
    def check_refund(self):
        """Check that we have the refund permission."""
        test_id = 'refund'
        msg = loc('You have not setup permissions for us to check this '
                  'paypal account.')
        if not self.addon:
            # If there's no addon there's not even any point checking.
            return

        premium = self.addon.premium
        if not premium:
            self.state['permissions'] = False
            self.failure(test_id, msg)
            return

        token = premium.paypal_permissions_token
        if not token:
            self.state['permissions'] = False
            self.failure(test_id, msg)
            return

        try:
            status = paypal.check_permission(token, ['REFUND'])
            if not status:
                self.state['permissions'] = False
                self.failure(test_id, loc('No permission to do refunds.'))
            else:
                self.pass_(test_id)
        except paypal.PaypalError:
            self.state['permissions'] = False
            self.failure(test_id, msg)
            log.info('Refund permission check returned an error '
                     'for %s' % id, exc_info=True)
コード例 #6
0
ファイル: views.py プロジェクト: writefaruq/zamboni
def price_sidebar(request, query, facets):
    qprice = query.get('price')
    free = qprice == 'free'
    paid = qprice == 'paid'
    return [
        FacetLink(loc('Free & Premium'), dict(price=None), not (paid or free)),
        FacetLink(loc('Free Only'), dict(price='free'), free),
        FacetLink(loc('Premium Only'), dict(price='paid'), paid),
    ]
コード例 #7
0
ファイル: views.py プロジェクト: kaiquewdev/zamboni
def price_sidebar(request, query, facets):
    qprice = query.get("price")
    free = qprice == "free"
    paid = qprice == "paid"
    return [
        FacetLink(loc("Free & Premium"), dict(price=None), not (paid or free)),
        FacetLink(loc("Free Only"), dict(price="free"), free),
        FacetLink(loc("Premium Only"), dict(price="paid"), paid),
    ]
コード例 #8
0
    def check_id(self):
        """Check that the paypal id is good."""
        test_id = 'id'
        if not self.paypal_id:
            self.failure(test_id, loc('No PayPal id provided.'))
            return

        valid, msg = paypal.check_paypal_id(self.paypal_id)
        if not valid:
            self.failure(test_id, loc('You do not seem to have'
                                      ' a PayPal account.'))
        else:
            self.pass_(test_id)
コード例 #9
0
    def check_currencies(self):
        """Check that we've got the currencies."""
        test_id = 'currencies'
        if self.addon and self.addon.premium:
            price = self.addon.premium.price
            if not price:
                tiers = [('USD', '1.00')]
            else:
                tiers = [(name, obj.price) for name, obj
                         in self.addon.premium.supported_currencies()]

        else:
            tiers = (('USD', '0.99'),)

        for currency, amount in tiers:
            try:
                self.test_paykey({'currency': currency,
                                  'amount': amount,
                                  'email': self.paypal_id})
                log.info('Get paykey passed in %s' % currency)
            except paypal.PaypalError:
                msg = loc('Failed to make a test transaction '
                          'in %s.' % (currency))
                self.failure(test_id, msg)
                log.info('Get paykey returned an error'
                         'in %s' % currency, exc_info=True)

        # If we haven't failed anything by this point, it's all good.
        if self.state[test_id]['pass'] is None:
            self.pass_(test_id)
コード例 #10
0
ファイル: views.py プロジェクト: beenishkhan/zamboni
def paypal_setup_confirm(request, addon_id, addon, webapp, source='paypal'):
    # If you bounce through paypal as you do permissions changes set the
    # source to paypal.
    if source == 'paypal':
        msg = _('PayPal set up complete.')
        title = _('Confirm Details')
        button = _('Continue')
    # If you just hit this page from the Manage Paypal, show some less
    # wizardy stuff.
    else:
        msg = _('Changes saved.')
        title = loc('Contact Details')
        button = _('Save')

    adp, created = AddonPaymentData.objects.safer_get_or_create(addon=addon)
    form = forms.PaypalPaymentData(request.POST or None, instance=adp)
    if request.method == 'POST' and form.is_valid():
        adp.update(**form.cleaned_data)
        messages.success(request, msg)
        if source == 'paypal' and addon.is_incomplete() and addon.paypal_id:
            addon.mark_done()
        return redirect(addon.get_dev_url('paypal_setup'))

    return jingo.render(request,
                        'developers/payments/paypal-details-confirm.html',
                        {'addon': addon, 'button': button, 'form': form,
                         'title': title})
コード例 #11
0
    def clean_categories(self):
        categories = self.cleaned_data['categories']
        total = categories.count()
        max_cat = amo.MAX_CATEGORIES
        if getattr(self, 'disabled', False) and total:
            if categories[0].type == amo.ADDON_WEBAPP:
                raise forms.ValidationError(loc('Categories cannot be changed '
                    'while your app is featured for this application.'))
            else:
                raise forms.ValidationError(_('Categories cannot be changed '
                    'while your add-on is featured for this application.'))
        if total > max_cat:
            # L10n: {0} is the number of categories.
            raise forms.ValidationError(ngettext(
                'You can have only {0} category.',
                'You can have only {0} categories.',
                max_cat).format(max_cat))

        has_misc = filter(lambda x: x.misc, categories)
        if has_misc and total > 1:
            raise forms.ValidationError(
                _('The miscellaneous category cannot be combined with '
                  'additional categories.'))

        return categories
コード例 #12
0
ファイル: views.py プロジェクト: mnoorenberghe/zamboni
def paypal_setup_confirm(request, addon_id, addon, webapp, source="paypal"):
    # If you bounce through paypal as you do permissions changes set the
    # source to paypal.
    if source == "paypal":
        msg = _("PayPal set up complete.")
        title = _("Confirm Details")
        button = _("Continue")
    # If you just hit this page from the Manage Paypal, show some less
    # wizardy stuff.
    else:
        msg = _("Changes saved.")
        title = loc("Contact Details")
        button = _("Save")

    adp, created = AddonPaymentData.objects.safer_get_or_create(addon=addon)
    form = forms.PaypalPaymentData(request.POST or None, instance=adp)
    if request.method == "POST" and form.is_valid():
        adp.update(**form.cleaned_data)
        messages.success(request, msg)
        if source == "paypal" and addon.is_incomplete() and addon.paypal_id:
            addon.mark_done()
        return redirect(addon.get_dev_url("paypal_setup"))

    return jingo.render(
        request,
        "developers/payments/paypal-details-confirm.html",
        {"addon": addon, "button": button, "form": form, "title": title},
    )
コード例 #13
0
ファイル: views.py プロジェクト: pjajara/zamboni
def ajax(request):
    """Query for a user matching a given email."""

    if 'q' not in request.GET:
        raise http.Http404()

    data = {'status': 0, 'message': ''}

    email = request.GET.get('q', '').strip()
    dev_only = request.GET.get('dev', '1')
    try:
        dev_only = int(dev_only)
    except ValueError:
        dev_only = 1
    dev_only = dev_only and settings.MARKETPLACE

    if not email:
        data.update(message=_('An email address is required.'))
        return data

    user = UserProfile.objects.filter(email=email)
    if dev_only:
        user = user.filter(read_dev_agreement=True)

    msg = _('A user with that email address does not exist.')
    msg_dev = loc('A user with that email address does not exist, or the user '
                  'has not yet accepted the developer agreement.')

    if user:
        data.update(status=1, id=user[0].id, name=user[0].name)
    else:
        data['message'] = msg_dev if dev_only else msg

    return escape_all(data)
コード例 #14
0
    def __init__(self, *args, **kw):
        self.extra = kw.pop('extra')
        self.request = kw.pop('request')
        self.addon = self.extra['addon']
        kw['initial'] = {
            'paypal_id': self.addon.paypal_id,
            'support_email': self.addon.support_email,
            'do_upsell': 0,
        }
        if self.addon.premium:
            kw['initial']['price'] = self.addon.premium.price

        upsell = self.addon.upsold
        if upsell:
            kw['initial'].update({
                'text': upsell.text,
                'free': upsell.free,
                'do_upsell': 1,
            })

        super(PremiumForm, self).__init__(*args, **kw)
        if self.addon.is_webapp():
            self.fields['price'].label = loc('App price')
            self.fields['do_upsell'].choices = APP_UPSELL_CHOICES
        self.fields['free'].queryset = (self.extra['amo_user'].addons
                                        .exclude(pk=self.addon.pk)
                                        .filter(premium_type=amo.ADDON_FREE,
                                                type=self.addon.type))

        # For the wizard, we need to remove some fields.
        for field in self.extra.get('exclude', []):
            del self.fields[field]
コード例 #15
0
ファイル: forms.py プロジェクト: beenishkhan/zamboni
    def clean_categories(self):
        categories = self.cleaned_data['categories']
        total = categories.count()
        max_cat = amo.MAX_CATEGORIES

        if getattr(self, 'disabled', False) and total:
            if categories[0].type == amo.ADDON_WEBAPP:
                raise forms.ValidationError(loc('Categories cannot be changed '
                    'while your app is featured for this application.'))
            else:
                raise forms.ValidationError(_('Categories cannot be changed '
                    'while your add-on is featured for this application.'))
        if total > max_cat:
            # L10n: {0} is the number of categories.
            raise forms.ValidationError(ngettext(
                'You can have only {0} category.',
                'You can have only {0} categories.',
                max_cat).format(max_cat))

        has_misc = filter(lambda x: x.misc, categories)
        if has_misc and total > 1:
            raise forms.ValidationError(
                _('The miscellaneous category cannot be combined with '
                  'additional categories.'))

        return categories
コード例 #16
0
ファイル: forms.py プロジェクト: rafrombrc/zamboni
    def __init__(self, *args, **kw):
        self.extra = kw.pop("extra")
        self.request = kw.pop("request")
        self.addon = self.extra["addon"]
        kw["initial"] = {"paypal_id": self.addon.paypal_id, "support_email": self.addon.support_email, "do_upsell": 0}
        if self.addon.premium:
            kw["initial"]["price"] = self.addon.premium.price

        upsell = self.addon.upsold
        if upsell:
            kw["initial"].update({"text": upsell.text, "free": upsell.free, "do_upsell": 1})

        super(PremiumForm, self).__init__(*args, **kw)
        if self.addon.is_webapp():
            self.fields["price"].label = loc("App price")
            self.fields["do_upsell"].choices = APP_UPSELL_CHOICES
        self.fields["free"].queryset = (
            self.extra["amo_user"]
            .addons.exclude(pk=self.addon.pk)
            .filter(premium_type=amo.ADDON_FREE, type=self.addon.type)
        )

        # For the wizard, we need to remove some fields.
        for field in self.extra.get("exclude", []):
            del self.fields[field]
コード例 #17
0
ファイル: views.py プロジェクト: bebef1987/zamboni
def ajax(request):
    """Query for a user matching a given email."""

    if "q" not in request.GET:
        raise http.Http404()

    data = {"status": 0, "message": ""}

    email = request.GET.get("q", "").strip()
    dev_only = request.GET.get("dev", "1")
    try:
        dev_only = int(dev_only)
    except ValueError:
        dev_only = 1
    dev_only = dev_only and settings.MARKETPLACE

    if not email:
        data.update(message=_("An email address is required."))
        return data

    user = UserProfile.objects.filter(email=email)
    if dev_only:
        user = user.filter(read_dev_agreement=True)

    msg = _("A user with that email address does not exist.")
    msg_dev = loc(
        "A user with that email address does not exist, or the user " "has not yet accepted the developer agreement."
    )

    if user:
        data.update(status=1, id=user[0].id, name=user[0].name)
    else:
        data["message"] = msg_dev if dev_only else msg

    return escape_all(data)
コード例 #18
0
ファイル: forms.py プロジェクト: rafrombrc/zamboni
 def clean(self):
     if any(self.errors):
         return
     form_count = len([f for f in self.forms if not f.cleaned_data.get("DELETE", False)])
     if form_count > 3:
         if addon_parent.is_webapp():
             error = loc("There cannot be more than 3 required apps.")
         else:
             error = _("There cannot be more than 3 required add-ons.")
         raise forms.ValidationError(error)
コード例 #19
0
ファイル: views.py プロジェクト: mnoorenberghe/zamboni
def delete(request, addon_id, addon, webapp=False):
    # Database deletes only allowed for free or incomplete addons.
    if not addon.can_be_deleted():
        msg = loc("App cannot be deleted. Disable this app instead.")
        messages.error(request, msg)
        return redirect(addon.get_dev_url("versions"))

    # TODO: This short circuits the delete form which checks the password. When
    # BrowserID adds re-auth support, update the form to check with BrowserID
    # and remove the short circuit.
    form = forms.DeleteForm(request)
    if True or form.is_valid():
        addon.delete("Removed via devhub")
        messages.success(request, loc("App deleted."))
        # Preserve query-string parameters if we were directed from Dashboard.
        return redirect(request.GET.get("to") or reverse("mkt.developers.apps"))
    else:
        msg = _("Password was incorrect.  App was not deleted.")
        messages.error(request, msg)
        return redirect(addon.get_dev_url("versions"))
コード例 #20
0
 def clean(self):
     if any(self.errors):
         return
     form_count = len([f for f in self.forms
                       if not f.cleaned_data.get('DELETE', False)])
     if form_count > 3:
         if addon_parent.is_webapp():
             error = loc('There cannot be more than 3 required apps.')
         else:
             error = _('There cannot be more than 3 required add-ons.')
         raise forms.ValidationError(error)
コード例 #21
0
ファイル: forms.py プロジェクト: rafrombrc/zamboni
 def clean(self):
     paypal_id = self.cleaned_data.get("paypal_id", "")
     if paypal_id:
         # If we're going to prompt for refund permission, we need to
         # record the PayPal ID first.
         self.addon.paypal_id = paypal_id
         self.addon.save()
     # Check if third-party refund token is properly set up.
     no_token = not self.addon.premium or not self.addon.premium.has_permissions_token()
     invalid_token = self.addon.premium and not self.addon.premium.has_valid_permissions_token()
     if no_token or invalid_token:
         # L10n: We require PayPal users to have a third-party token set up.
         self._show_token_msg(loc("PayPal third-party refund token has not " "been set up or has recently expired."))
     return self.cleaned_data
コード例 #22
0
ファイル: views.py プロジェクト: ryandoherty/zamboni
class PurchasesFilter(BaseFilter):
    opts = (('purchased', loc('Purchase Date')), ('price', _lazy(u'Price')),
            ('name', _lazy(u'Name')))

    def filter(self, field):
        qs = self.base_queryset
        if field == 'purchased':
            return (qs.filter(
                Q(addonpurchase__user=self.request.amo_user)
                | Q(addonpurchase__isnull=True)).order_by(
                    '-addonpurchase__created', 'id'))
        elif field == 'price':
            return qs.order_by('addonpremium__price__price', 'id')
        elif field == 'name':
            return order_by_translation(qs, 'name')
コード例 #23
0
 def clean(self):
     paypal_id = self.cleaned_data.get('paypal_id', '')
     if paypal_id:
         # If we're going to prompt for refund permission, we need to
         # record the PayPal ID first.
         self.addon.paypal_id = paypal_id
         self.addon.save()
     # Check if third-party refund token is properly set up.
     no_token = (not self.addon.premium or
                 not self.addon.premium.has_permissions_token())
     invalid_token = (self.addon.premium and
                      not self.addon.premium.has_valid_permissions_token())
     if no_token or invalid_token:
         # L10n: We require PayPal users to have a third-party token set up.
         self._show_token_msg(loc('PayPal third-party refund token has not '
                                  'been set up or has recently expired.'))
     return self.cleaned_data
コード例 #24
0
ファイル: tasks.py プロジェクト: vdt/zamboni
def _notify(redis, context):
    """
    Notify the admins or the developers what happened. Performing a sanity
    check in case something went wrong.
    """
    log.info('Completed run of paypal addon checks: %s' % context['checked'])
    failure_list = []

    if context['limit'] and context['rate'] > context['limit']:
        # This is too cope with something horrible going wrong like, paypal
        # goes into maintenance mode, or netops changes something and all of
        # a sudden all the apps start failing their paypal checks.
        #
        # It would really suck if one errant current job disabled every app
        # on the Marketplace. So this is an attempt to sanity check this.
        for k in xrange(context['failed']):
            data = json.loads(redis.lindex(failures, k))
            addon = Addon.objects.get(pk=data[0])
            failure_list.append(absolutify(addon.get_url_path()))

        context['failure_list'] = failure_list
        log.info('Too many failed: %s%%, aborting.' % context['limit'])
        template = 'market/emails/check_error.txt'
        send_mail('Cron job error on checking addons',
                  env.get_template(template).render(context),
                  recipient_list=[settings.FLIGTAR],
                  from_email=settings.NOBODY_EMAIL)

    else:
        if not context['failed']:
            return

        for k in xrange(context['failed']):
            data = json.loads(redis.lindex(failures, k))
            addon = Addon.objects.get(pk=data[0])
            url = absolutify(addon.get_url_path())
            # Add this to a list so we can tell the admins who got disabled.
            failure_list.append(url)
            if not context['do_disable']:
                continue

            # Write to the developers log that it failed to pass and update
            # the status of the addon.
            amo.log(amo.LOG.PAYPAL_FAILED, addon, user=get_task_user())
            addon.update(status=amo.STATUS_DISABLED)

            authors = [u.email for u in addon.authors.all()]
            if addon.is_webapp():
                template = 'market/emails/check_developer_app.txt'
                subject = loc('App disabled on the Mozilla Market.')
            else:
                template = 'market/emails/check_developer_addon.txt'
                subject = loc('Add-on disabled on the Mozilla Market.')

            # Now email the developer and tell them the bad news.
            send_mail(subject,
                      env.get_template(template).render({
                          'addon': addon,
                          'errors': data[1:]
                      }),
                      recipient_list=authors,
                      from_email=settings.NOBODY_EMAIL)

        context['failure_list'] = failure_list
        # Now email the admins and tell them what happened.
        template = 'market/emails/check_summary.txt'
        send_mail('Cron job disabled %s add-ons' % context['failed'],
                  env.get_template(template).render(context),
                  recipient_list=[settings.FLIGTAR],
                  from_email=settings.NOBODY_EMAIL)
コード例 #25
0
ファイル: views.py プロジェクト: writefaruq/zamboni
class AppFilter(addons.views.BaseFilter):
    opts = (('downloads', _lazy(u'Weekly Downloads')), ('free',
                                                        loc(u'Top Free')),
            ('paid', loc(u'Top Paid')), ('rating', _lazy(u'Highest Rated')))
    extras = (('created', _lazy(u'Newest')), ('name', _lazy(u'Name')),
              ('price', loc(u'Price')))
コード例 #26
0
ファイル: context_processors.py プロジェクト: atsay/zamboni
def global_settings(request):
    """
    Storing standard AMO-wide information used in global headers, such as
    account links and settings.
    """
    account_links = []
    tools_links = []
    context = {}

    tools_title = _('Tools')

    if request.user.is_authenticated() and hasattr(request, 'amo_user'):
        amo_user = request.amo_user
        account_links.append({
            'text': _('My Profile'),
            'href': request.user.get_profile().get_url_path(),
        })
        account_links.append({'text': _('Account Settings'),
                              'href': reverse('users.edit')})
        if not settings.APP_PREVIEW:
            account_links.append({
                'text': _('My Collections'),
                'href': reverse('collections.user', args=[amo_user.username])})

            if amo_user.favorite_addons:
                account_links.append(
                    {'text': _('My Favorites'),
                     'href': reverse('collections.detail',
                                     args=[amo_user.username, 'favorites'])})

        if waffle.switch_is_active('marketplace'):
            account_links.append({'text': _('My Purchases'),
                                  'href': reverse('users.purchases')})

        if waffle.flag_is_active(request, 'allow-pre-auth'):
            account_links.append({'text': loc('Payment Profile'),
                                  'href': reverse('users.payments')})

        account_links.append({
            'text': _('Log out'),
            'href': remora_url('/users/logout?to=' + urlquote(request.path)),
        })

        if request.amo_user.is_developer:
            tools_links.append({'text': _('Manage My Add-ons'),
                                'href': reverse('devhub.addons')})
        tools_links.append({'text': _('Submit a New Add-on'),
                            'href': reverse('devhub.submit.1')})

        if waffle.flag_is_active(request, 'submit-personas'):
            # TODO(cvan)(fligtar): Do we want this here?
            tools_links.append({'text': 'Submit a New Theme',
                                'href': reverse('devhub.personas.submit')})

        tools_links.append({'text': _('Developer Hub'),
                            'href': reverse('devhub.index')})

        if acl.check_reviewer(request):
            tools_links.append({'text': _('Editor Tools'),
                                'href': reverse('editors.home')})
        if acl.action_allowed(request, 'L10nTools', 'View'):
            tools_links.append({'text': _('Localizer Tools'),
                                'href': '/localizers'})
        if (acl.action_allowed(request, 'Admin', '%') or
            acl.action_allowed(request, 'AdminTools', 'View')):
            tools_links.append({'text': _('Admin Tools'),
                                'href': reverse('zadmin.home')})

        context['amo_user'] = request.amo_user
    else:
        context['amo_user'] = AnonymousUser()

    context.update({'account_links': account_links,
                    'settings': settings, 'amo': amo,
                    'tools_links': tools_links,
                    'tools_title': tools_title,
                    'ADMIN_MESSAGE': get_config('site_notice'),
                    'collect_timings_percent': get_collect_timings()})
    return context
コード例 #27
0
    ('users', _lazy(u'Most Users')),
    ('rating', _lazy(u'Top Rated')),
    ('created', _lazy(u'Newest')),
    # --
    ('name', _lazy(u'Name')),
    ('downloads', _lazy(u'Weekly Downloads')),
    #('price', helpers.loc(u'Price')),
    ('updated', _lazy(u'Recently Updated')),
    ('hotness', _lazy(u'Up & Coming')),
)

APP_SORT_CHOICES = (
    (None, _lazy(u'Relevance')),
    ('downloads', _lazy(u'Weekly Downloads')),
    ('rating', _lazy(u'Top Rated')),
    ('price', helpers.loc(u'Price')),
    # --
    ('name', _lazy(u'Name')),
    ('created', _lazy(u'Newest')),
)


class ESSearchForm(forms.Form):
    q = forms.CharField(required=False)
    tag = forms.CharField(required=False)
    platform = forms.CharField(required=False)
    appver = forms.CharField(required=False)
    atype = forms.TypedChoiceField(required=False, coerce=int,
                                   choices=amo.ADDON_TYPES.iteritems())
    cat = forms.CharField(required=False)
    price = forms.CharField(required=False)
コード例 #28
0
ファイル: notifications.py プロジェクト: writefaruq/zamboni
class app_new_review(new_review):
    app = True
    label = loc('someone writes a review of my app')
コード例 #29
0
ファイル: __init__.py プロジェクト: bebef1987/zamboni
    pass


errors = {'520003': AuthError}
# See http://bit.ly/vWV525 for information on these values.
# Note that if you have and invalid preapproval key you get 580022, but this
# also occurs in other cases so don't assume its preapproval only.
for number in ['579024', '579025', '579026', '579027', '579028',
               '579030', '579031']:
    errors[number] = PreApprovalError
for number in ['580027', '580022']:
    errors[number] = CurrencyError

# Here you can map PayPal error messages into hopefully more useful
# error messages.
messages = {'589023': loc('The amount is too small for conversion '
                          "into the receiver's currency.")}


paypal_log = commonware.log.getLogger('z.paypal')


def should_ignore_paypal():
    """
    Returns whether to skip PayPal communications for development
    purposes or not.
    """
    return settings.DEBUG and 'sandbox' not in settings.PAYPAL_PERMISSIONS_URL


def add_receivers(chains, email, amount, uuid, preapproval=False):
    """
コード例 #30
0
ファイル: views.py プロジェクト: ryandoherty/zamboni
def register(request):

    if settings.APP_PREVIEW:
        messages.error(request,
                       loc('Registrations must be through browserid.'))
        form = None

    elif (settings.REGISTER_USER_LIMIT
          and UserProfile.objects.count() > settings.REGISTER_USER_LIMIT
          and not can_override_reg_limit(request)):
        _m = loc('Sorry, no more registrations are allowed. '
                 '<a href="https://developer.mozilla.org/en-US/apps">'
                 'Learn more</a>')
        messages.error(request, _m, title_safe=True, message_safe=True)
        form = None

    elif request.user.is_authenticated():
        messages.info(request, _('You are already logged in to an account.'))
        form = None

    elif request.method == 'POST':

        form = forms.UserRegisterForm(request.POST)

        if form.is_valid():
            try:
                u = form.save(commit=False)
                u.set_password(form.cleaned_data['password'])
                u.generate_confirmationcode()
                u.save()
                u.create_django_user()
                log.info(u'Registered new account for user (%s)', u)
                log_cef('New Account',
                        5,
                        request,
                        username=u.username,
                        signature='AUTHNOTICE',
                        msg='User created a new account')

                u.email_confirmation_code()

                msg = _('Congratulations! Your user account was successfully '
                        'created.')
                messages.success(request, msg)

                msg = _(u'An email has been sent to your address {0} to '
                        'confirm your account. Before you can log in, you '
                        'have to activate your account by clicking on the '
                        'link provided in this email.').format(u.email)
                messages.info(request, _('Confirmation Email Sent'), msg)
            except IntegrityError, e:
                # I was unable to reproduce this, but I suspect it happens
                # when they POST twice quickly and the slaves don't have the
                # new info yet (total guess).  Anyway, I'm assuming the
                # first one worked properly, so this is still a success
                # case to tne end user so we just log it...
                log.error('Failed to register new user (%s): %s' % (u, e))

            return http.HttpResponseRedirect(reverse('users.login'))

        else:
            messages.error(request, _('There are errors in this form'),
                           _('Please correct them and resubmit.'))
コード例 #31
0
ファイル: views.py プロジェクト: dbialer/zamboni
def register(request):

    if settings.APP_PREVIEW and waffle.switch_is_active("browserid-login"):
        messages.error(request, loc("Registrations must be through browserid."))
        form = None

    elif (
        settings.REGISTER_USER_LIMIT
        and UserProfile.objects.count() > settings.REGISTER_USER_LIMIT
        and not can_override_reg_limit(request)
    ):
        _m = loc(
            "Sorry, no more registrations are allowed. "
            '<a href="https://developer.mozilla.org/en-US/apps">'
            "Learn more</a>"
        )
        messages.error(request, _m, title_safe=True, message_safe=True)
        form = None

    elif request.user.is_authenticated():
        messages.info(request, _("You are already logged in to an account."))
        form = None

    elif request.method == "POST":

        form = forms.UserRegisterForm(request.POST)
        mkt_user = UserProfile.objects.filter(email=form.data["email"], password="")
        if form.is_valid():
            try:
                u = form.save(commit=False)
                u.set_password(form.cleaned_data["password"])
                u.generate_confirmationcode()
                u.save()
                u.create_django_user()
                log.info(u"Registered new account for user (%s)", u)
                log_cef(
                    "New Account",
                    5,
                    request,
                    username=u.username,
                    signature="AUTHNOTICE",
                    msg="User created a new account",
                )

                u.email_confirmation_code()

                msg = _("Congratulations! Your user account was " "successfully created.")
                messages.success(request, msg)

                msg = _(
                    u"An email has been sent to your address {0} to "
                    "confirm your account. Before you can log in, you "
                    "have to activate your account by clicking on the "
                    "link provided in this email."
                ).format(u.email)
                messages.info(request, _("Confirmation Email Sent"), msg)

            except IntegrityError, e:
                # I was unable to reproduce this, but I suspect it happens
                # when they POST twice quickly and the slaves don't have the
                # new info yet (total guess).  Anyway, I'm assuming the
                # first one worked properly, so this is still a success
                # case to the end user so we just log it...
                log.error("Failed to register new user (%s): %s" % (u, e))

            return http.HttpResponseRedirect(reverse("users.login"))

        elif mkt_user.exists():
            # Handle BrowserID
            if mkt_user.count() == 1 and mkt_user[0].source == amo.LOGIN_SOURCE_BROWSERID:
                messages.info(request, _("You already have an account."))
                form = None
            else:
                f = PasswordResetForm()
                f.users_cache = [mkt_user[0]]
                f.save(use_https=request.is_secure(), email_template_name="users/email/pwreset.ltxt", request=request)
                return jingo.render(request, "users/newpw_sent.html", {})
        else:
            messages.error(request, _("There are errors in this form"), _("Please correct them and resubmit."))
コード例 #32
0
def register(request):

    if waffle.switch_is_active('browserid-login'):
        messages.error(request,
                       loc('Registrations must be through browserid.'))
        form = None
        raise http.Http404()

    elif request.user.is_authenticated():
        messages.info(request, _('You are already logged in to an account.'))
        form = None

    elif request.method == 'POST':

        form = forms.UserRegisterForm(request.POST)
        mkt_user = UserProfile.objects.filter(email=form.data['email'],
                                              password='')
        if form.is_valid():
            try:
                u = form.save(commit=False)
                u.set_password(form.cleaned_data['password'])
                u.generate_confirmationcode()
                u.lang = request.LANG
                u.save()
                log.info(u'Registered new account for user (%s)', u)
                log_cef('New Account',
                        5,
                        request,
                        username=u.username,
                        signature='AUTHNOTICE',
                        msg='User created a new account')

                u.email_confirmation_code()

                msg = _('Congratulations! Your user account was '
                        'successfully created.')
                messages.success(request, msg)

                msg = _(u'An email has been sent to your address {0} to '
                        'confirm your account. Before you can log in, you '
                        'have to activate your account by clicking on the '
                        'link provided in this email.').format(u.email)
                messages.info(request, _('Confirmation Email Sent'), msg)

            except IntegrityError, e:
                # I was unable to reproduce this, but I suspect it happens
                # when they POST twice quickly and the slaves don't have the
                # new info yet (total guess).  Anyway, I'm assuming the
                # first one worked properly, so this is still a success
                # case to the end user so we just log it...
                log.error('Failed to register new user (%s): %s' % (u, e))

            return http.HttpResponseRedirect(reverse('users.login'))

        elif mkt_user.exists():
            # Handle BrowserID
            if (mkt_user.count() == 1
                    and mkt_user[0].source in amo.LOGIN_SOURCE_BROWSERIDS):
                messages.info(request, _('You already have an account.'))
                form = None
            else:
                f = PasswordResetForm()
                f.users_cache = [mkt_user[0]]
                f.save(use_https=request.is_secure(),
                       email_template_name='users/email/pwreset.ltxt',
                       request=request)
                return render(request, 'users/newpw_sent.html', {})
        else:
            messages.error(request, _('There are errors in this form'),
                           _('Please correct them and resubmit.'))
コード例 #33
0
ファイル: notifications.py プロジェクト: writefaruq/zamboni
class app_individual_contact(individual_contact):
    app = True
    label = loc('Mozilla needs to contact me about my individual app')
コード例 #34
0
ファイル: helpers.py プロジェクト: bebef1987/zamboni
def mkt_page_title(context, title, force_webapps=False):
    title = smart_unicode(title)
    base_title = loc('Mozilla Marketplace')
    return u'%s | %s' % (title, base_title)
コード例 #35
0
ファイル: notifications.py プロジェクト: writefaruq/zamboni
class app_reply(reply):
    app = True
    label = loc('an app developer replies to my review')
コード例 #36
0
def global_settings(request):
    """
    Storing standard AMO-wide information used in global headers, such as
    account links and settings.
    """
    account_links = []
    tools_links = []
    context = {}

    tools_title = _('Tools')

    if request.user.is_authenticated() and hasattr(request, 'amo_user'):
        amo_user = request.amo_user
        account_links.append({
            'text': _('My Profile'),
            'href': request.user.get_profile().get_url_path(),
        })
        account_links.append({
            'text': _('Account Settings'),
            'href': reverse('users.edit')
        })
        if not settings.APP_PREVIEW:
            account_links.append({
                'text':
                _('My Collections'),
                'href':
                reverse('collections.user', args=[amo_user.username])
            })

            if amo_user.favorite_addons:
                account_links.append({
                    'text':
                    _('My Favorites'),
                    'href':
                    reverse('collections.detail',
                            args=[amo_user.username, 'favorites'])
                })

        if waffle.switch_is_active('marketplace'):
            account_links.append({
                'text': _('My Purchases'),
                'href': reverse('users.purchases')
            })

        if waffle.flag_is_active(request, 'allow-pre-auth'):
            account_links.append({
                'text': loc('Payment Profile'),
                'href': reverse('users.payments')
            })

        account_links.append({
            'text':
            _('Log out'),
            'href':
            remora_url('/users/logout?to=' + urlquote(request.path)),
        })

        if not settings.APP_PREVIEW:
            if request.amo_user.is_developer:
                tools_links.append({
                    'text': _('Manage My Add-ons'),
                    'href': reverse('devhub.addons')
                })
            tools_links.append({
                'text': _('Submit a New Add-on'),
                'href': reverse('devhub.submit.1')
            })

        if waffle.flag_is_active(request, 'accept-webapps'):
            if settings.APP_PREVIEW or request.amo_user.is_developer:
                tools_links.append({
                    'text': _('Manage My Apps'),
                    'href': reverse('devhub.apps')
                })
            tools_links.append({
                'text': _('Submit a New App'),
                'href': reverse('devhub.submit_apps.1')
            })

        if waffle.flag_is_active(request, 'submit-personas'):
            # TODO(cvan)(fligtar): Do we want this here?
            tools_links.append({
                'text': 'Submit a New Persona',
                'href': reverse('devhub.personas.submit')
            })

        if not settings.APP_PREVIEW:
            tools_links.append({
                'text': _('Developer Hub'),
                'href': reverse('devhub.index')
            })

        if acl.action_allowed(request, 'Editors', '%'):
            tools_links.append({
                'text': _('Editor Tools'),
                'href': reverse('editors.home')
            })
        if acl.action_allowed(request, 'Localizers', '%'):
            tools_links.append({
                'text': _('Localizer Tools'),
                'href': '/localizers'
            })
        if acl.action_allowed(request, 'Admin', '%'):
            tools_links.append({
                'text': _('Admin Tools'),
                'href': reverse('zadmin.home')
            })

        context['amo_user'] = request.amo_user
    else:
        context['amo_user'] = AnonymousUser()

    context.update({
        'account_links': account_links,
        'settings': settings,
        'amo': amo,
        'tools_links': tools_links,
        'tools_title': tools_title,
        'ADMIN_MESSAGE': get_config('site_notice'),
        'collect_timings_percent': get_collect_timings()
    })
    return context
コード例 #37
0
ファイル: __init__.py プロジェクト: pjajara/zamboni
    # This currency was bad.
    pass


errors = {"520003": AuthError}
# See http://bit.ly/vWV525 for information on these values.
# Note that if you have and invalid preapproval key you get 580022, but this
# also occurs in other cases so don't assume its preapproval only.
for number in ["579024", "579025", "579026", "579027", "579028", "579030", "579031"]:
    errors[number] = PreApprovalError
for number in ["580027", "580022"]:
    errors[number] = CurrencyError

# Here you can map PayPal error messages into hopefully more useful
# error messages.
messages = {"589023": loc("The amount is too small for conversion " "into the receiver's currency.")}


paypal_log = commonware.log.getLogger("z.paypal")


def should_ignore_paypal():
    """
    Returns whether to skip PayPal communications for development
    purposes or not.
    """
    return settings.DEBUG and "sandbox" not in settings.PAYPAL_PERMISSIONS_URL


def add_receivers(chains, email, amount, uuid, preapproval=False):
    """
コード例 #38
0
ファイル: tasks.py プロジェクト: kaiquewdev/zamboni
def _notify(redis, context):
    """
    Notify the admins or the developers what happened. Performing a sanity
    check in case something went wrong.
    """
    log.info('Completed run of paypal addon checks: %s' % context['checked'])

    if context['limit'] and context['rate'] > context['limit']:
        # This is too cope with something horrible going wrong like, paypal
        # goes into maintenance mode, or netops changes something and all of
        # a sudden all the apps start failing their paypal checks.
        #
        # It would really suck if one errant current job disabled every app
        # on the marketplace. So this is an attempt to sanity check this.
        log.info('Too many failed: %s%%, aborting.' % context['limit'])
        template = 'market/emails/check_error.txt'
        send_mail('Cron job error on checking addons',
                  env.get_template(template).render(context),
                  recipient_list=[settings.FLIGTAR],
                  from_email=settings.NOBODY_EMAIL)

    else:
        if not context['failed']:
            return

        failure_list = []
        for k in xrange(context['failed']):
            data = json.loads(redis.lindex(failures, k))
            addon = Addon.objects.get(pk=data[0])
            url = absolutify(shared_url('detail', addon))
            # Add this to a list so we can tell the admins who got disabled.
            failure_list.append(url)
            if not context['do_disable']:
                continue

            # Write to the developers log that it failed to pass and update
            # the status of the addon.
            amo.log(amo.LOG.PAYPAL_FAILED, addon, user=get_task_user())
            addon.update(status=amo.STATUS_DISABLED)

            authors = [u.email for u in addon.authors.all()]
            if addon.is_webapp():
                template = 'market/emails/check_developer_app.txt'
                subject = loc('App disabled on the Mozilla Market.')
            else:
                template = 'market/emails/check_developer_addon.txt'
                subject = loc('Add-on disabled on the Mozilla Market.')

            # Now email the developer and tell them the bad news.
            url = absolutify(shared_url('detail', addon))
            send_mail(subject,
                      env.get_template(template).render({
                          'addon': addon,
                          'errors': data[1:]
                      }),
                      recipient_list=authors,
                      from_email=settings.NOBODY_EMAIL)

        context['failure_list'] = failure_list
        # Now email the admins and tell them what happened.
        template = 'market/emails/check_summary.txt'
        send_mail('Cron job disabled %s add-ons' % context['failed'],
                  env.get_template(template).render(context),
                  recipient_list=[settings.FLIGTAR],
                  from_email=settings.NOBODY_EMAIL)
コード例 #39
0
ファイル: forms.py プロジェクト: wraithan/zamboni
    ("users", _lazy(u"Most Users")),
    ("rating", _lazy(u"Top Rated")),
    ("created", _lazy(u"Newest")),
    # --
    ("name", _lazy(u"Name")),
    ("downloads", _lazy(u"Weekly Downloads")),
    # ('price', helpers.loc(u'Price')),
    ("updated", _lazy(u"Recently Updated")),
    ("hotness", _lazy(u"Up & Coming")),
)

APP_SORT_CHOICES = (
    (None, _lazy(u"Relevance")),
    ("downloads", _lazy(u"Weekly Downloads")),
    ("rating", _lazy(u"Top Rated")),
    ("price", helpers.loc(u"Price")),
    # --
    ("name", _lazy(u"Name")),
    ("created", _lazy(u"Newest")),
)


class ESSearchForm(forms.Form):
    q = forms.CharField(required=False)
    tag = forms.CharField(required=False)
    platform = forms.CharField(required=False)
    appver = forms.CharField(required=False)
    atype = forms.TypedChoiceField(required=False, coerce=int, choices=amo.ADDON_TYPES.iteritems())
    cat = forms.CharField(required=False)
    price = forms.CharField(required=False)
    sort = forms.CharField(required=False)
コード例 #40
0
ファイル: __init__.py プロジェクト: pennyfx/zamboni

errors = {'520003': AuthError}
# See http://bit.ly/vWV525 for information on these values.
# Note that if you have and invalid preapproval key you get 580022, but this
# also occurs in other cases so don't assume its preapproval only.
for number in [
        '579024', '579025', '579026', '579027', '579028', '579030', '579031'
]:
    errors[number] = PreApprovalError

# Here you can map PayPal error messages into hopefully more useful
# error messages.
messages = {
    '589023':
    loc('The amount is too small for conversion '
        'into the receviers currency.')
}

paypal_log = commonware.log.getLogger('z.paypal')


def should_ignore_paypal():
    """
    Returns whether to skip PayPal communications for development
    purposes or not.
    """
    return settings.DEBUG and 'sandbox' not in settings.PAYPAL_PERMISSIONS_URL


def add_receivers(chains, email, amount, uuid, preapproval=False):
    """
コード例 #41
0
ファイル: __init__.py プロジェクト: kaiquewdev/zamboni
    pass


errors = {'520003': AuthError}
# See http://bit.ly/vWV525 for information on these values.
# Note that if you have and invalid preapproval key you get 580022, but this
# also occurs in other cases so don't assume its preapproval only.
for number in ['579024', '579025', '579026', '579027', '579028',
               '579030', '579031']:
    errors[number] = PreApprovalError
for number in ['580027', '580022']:
    errors[number] = CurrencyError

# Here you can map PayPal error messages into hopefully more useful
# error messages.
messages = {'589023': loc('The amount is too small for conversion '
                          'into the receviers currency.')}


paypal_log = commonware.log.getLogger('z.paypal')


def should_ignore_paypal():
    """
    Returns whether to skip PayPal communications for development
    purposes or not.
    """
    return settings.DEBUG and 'sandbox' not in settings.PAYPAL_PERMISSIONS_URL


def add_receivers(chains, email, amount, uuid, preapproval=False):
    """
コード例 #42
0
ファイル: views.py プロジェクト: dimonov/zamboni
def register(request):

    if settings.APP_PREVIEW and waffle.switch_is_active('browserid-login'):
        messages.error(request,
                       loc('Registrations must be through browserid.'))
        form = None
        raise http.Http404()

    elif request.user.is_authenticated():
        messages.info(request, _('You are already logged in to an account.'))
        form = None

    elif request.method == 'POST':

        form = forms.UserRegisterForm(request.POST)
        mkt_user = UserProfile.objects.filter(email=form.data['email'],
                                              password='')
        if form.is_valid():
            try:
                u = form.save(commit=False)
                u.set_password(form.cleaned_data['password'])
                u.generate_confirmationcode()
                u.save()
                u.create_django_user()
                log.info(u'Registered new account for user (%s)', u)
                log_cef('New Account', 5, request, username=u.username,
                        signature='AUTHNOTICE',
                        msg='User created a new account')

                u.email_confirmation_code()

                msg = _('Congratulations! Your user account was '
                        'successfully created.')
                messages.success(request, msg)

                msg = _(u'An email has been sent to your address {0} to '
                        'confirm your account. Before you can log in, you '
                        'have to activate your account by clicking on the '
                        'link provided in this email.').format(u.email)
                messages.info(request, _('Confirmation Email Sent'), msg)

            except IntegrityError, e:
                # I was unable to reproduce this, but I suspect it happens
                # when they POST twice quickly and the slaves don't have the
                # new info yet (total guess).  Anyway, I'm assuming the
                # first one worked properly, so this is still a success
                # case to the end user so we just log it...
                log.error('Failed to register new user (%s): %s' % (u, e))

            return http.HttpResponseRedirect(reverse('users.login'))

        elif mkt_user.exists():
            # Handle BrowserID
            if (mkt_user.count() == 1 and
                mkt_user[0].source in amo.LOGIN_SOURCE_BROWSERIDS):
                messages.info(request, _('You already have an account.'))
                form = None
            else:
                f = PasswordResetForm()
                f.users_cache = [mkt_user[0]]
                f.save(use_https=request.is_secure(),
                       email_template_name='users/email/pwreset.ltxt',
                        request=request)
                return jingo.render(request, 'users/newpw_sent.html', {})
        else:
            messages.error(request, _('There are errors in this form'),
                            _('Please correct them and resubmit.'))
コード例 #43
0
ファイル: context_processors.py プロジェクト: pennyfx/zamboni
def global_settings(request):
    """
    Storing standard AMO-wide information used in global headers, such as
    account links and settings.
    """
    account_links = []
    tools_links = []
    context = {}

    tools_title = _("Tools")

    if request.user.is_authenticated() and hasattr(request, "amo_user"):
        amo_user = request.amo_user
        account_links.append({"text": _("My Profile"), "href": request.user.get_profile().get_url_path()})
        account_links.append({"text": _("Account Settings"), "href": reverse("users.edit")})
        if not settings.APP_PREVIEW:
            account_links.append(
                {"text": _("My Collections"), "href": reverse("collections.user", args=[amo_user.username])}
            )

            if amo_user.favorite_addons:
                account_links.append(
                    {
                        "text": _("My Favorites"),
                        "href": reverse("collections.detail", args=[amo_user.username, "favorites"]),
                    }
                )

        if waffle.switch_is_active("marketplace"):
            account_links.append({"text": _("My Purchases"), "href": reverse("users.purchases")})

        if waffle.flag_is_active(request, "allow-pre-auth"):
            account_links.append({"text": loc("Payment Profile"), "href": reverse("users.payments")})

        account_links.append({"text": _("Log out"), "href": remora_url("/users/logout?to=" + urlquote(request.path))})

        if not settings.APP_PREVIEW:
            if request.amo_user.is_developer:
                tools_links.append({"text": _("Manage My Add-ons"), "href": reverse("devhub.addons")})
            tools_links.append({"text": _("Submit a New Add-on"), "href": reverse("devhub.submit.1")})

        if waffle.flag_is_active(request, "accept-webapps"):
            if settings.APP_PREVIEW or request.amo_user.is_developer:
                tools_links.append({"text": _("Manage My Apps"), "href": reverse("devhub.apps")})
            tools_links.append({"text": _("Submit a New App"), "href": reverse("devhub.submit_apps.1")})

        if waffle.flag_is_active(request, "submit-personas"):
            # TODO(cvan)(fligtar): Do we want this here?
            tools_links.append({"text": "Submit a New Persona", "href": reverse("devhub.personas.submit")})

        if not settings.APP_PREVIEW:
            tools_links.append({"text": _("Developer Hub"), "href": reverse("devhub.index")})

        if acl.action_allowed(request, "Editors", "%"):
            tools_links.append({"text": _("Editor Tools"), "href": reverse("editors.home")})
        if acl.action_allowed(request, "Localizers", "%"):
            tools_links.append({"text": _("Localizer Tools"), "href": "/localizers"})
        if acl.action_allowed(request, "Admin", "%"):
            tools_links.append({"text": _("Admin Tools"), "href": reverse("zadmin.home")})

        context["amo_user"] = request.amo_user
    else:
        context["amo_user"] = AnonymousUser()

    # The flag has to be enabled for everyone and then we'll use that
    # percentage in the pages.
    percent = 0
    try:
        flag = waffle.models.Flag.objects.get(name="collect-timings")
        if flag.everyone and flag.percent:
            percent = float(flag.percent) / 100.0
    except waffle.models.Flag.DoesNotExist:
        pass

    context.update(
        {
            "account_links": account_links,
            "settings": settings,
            "amo": amo,
            "tools_links": tools_links,
            "tools_title": tools_title,
            "ADMIN_MESSAGE": get_config("site_notice"),
            "collect_timings_percent": percent,
        }
    )
    return context