示例#1
0
文件: views.py 项目: PinZhang/zamboni
def elastic(request):
    INDEX = site_settings.ES_INDEXES['default']
    es = elasticutils.get_es()
    mappings = {'addons': (addons.search.setup_mapping,
                           addons.cron.reindex_addons),
                'collections': (addons.search.setup_mapping,
                                bandwagon.cron.reindex_collections),
                'compat': (addons.search.setup_mapping, None),
                'users': (addons.search.setup_mapping,
                          users.cron.reindex_users),
               }
    if request.method == 'POST':
        if request.POST.get('reset') in mappings:
            name = request.POST['reset']
            es.delete_mapping(INDEX, name)
            if mappings[name][0]:
                mappings[name][0]()
            messages.info(request, 'Resetting %s.' % name)
        if request.POST.get('reindex') in mappings:
            name = request.POST['reindex']
            mappings[name][1]()
            messages.info(request, 'Reindexing %s.' % name)
        return redirect('zadmin.elastic')

    indexes = set(site_settings.ES_INDEXES.values())
    mappings = es.get_mapping(None, indexes)
    ctx = {
        'nodes': es.cluster_nodes(),
        'health': es.cluster_health(),
        'state': es.cluster_state(),
        'mappings': [(index, mappings.get(index, {})) for index in indexes],
    }
    return jingo.render(request, 'zadmin/elastic.html', ctx)
示例#2
0
def elastic(request):
    INDEX = site_settings.ES_INDEX
    es = elasticutils.get_es()
    mappings = {'addons': (addons.search.setup_mapping,
                           addons.cron.reindex_addons),
                'collections': (None,
                                bandwagon.cron.reindex_collections)}
    if request.method == 'POST':
        if request.POST.get('reset') in mappings:
            name = request.POST['reset']
            es.delete_mapping(INDEX, name)
            if mappings[name][0]:
                mappings[name][0]()
            messages.info(request, 'Resetting %s.' % name)
        if request.POST.get('reindex') in mappings:
            name = request.POST['reindex']
            mappings[name][1]()
            messages.info(request, 'Reindexing %s.' % name)
        return redirect('zadmin.elastic')

    ctx = {
        'nodes': es.cluster_nodes(),
        'health': es.cluster_health(),
        'state': es.cluster_state(),
        'mapping': es.get_mapping(None, INDEX)[INDEX],
    }
    return jingo.render(request, 'zadmin/elastic.html', ctx)
示例#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
def elastic(request):
    INDEX = site_settings.ES_INDEXES['default']
    es = elasticutils.get_es()
    mappings = {'addons': addons.cron.reindex_addons,
                'apps': addons.cron.reindex_apps,
                'collections': bandwagon.cron.reindex_collections,
                'compat': compatibility_report,
                'users': users.cron.reindex_users,
               }
    if request.method == 'POST':
        if request.POST.get('recreate'):
            es.delete_index_if_exists(INDEX)
            # We must set up the mappings before we create the index again.
            addons.search.setup_mapping()
            stats.search.setup_indexes()
            es.create_index_if_missing(INDEX)
            messages.info(request, 'Deleting %s index.' % INDEX)
        if request.POST.get('reindex') in mappings:
            name = request.POST['reindex']
            # Reindex.
            if mappings.get(name):
                mappings[name]()
            messages.info(request, 'Reindexing %s.' % name)
        return redirect('zadmin.elastic')

    indexes = set(site_settings.ES_INDEXES.values())
    mappings = es.get_mapping(None, indexes)
    ctx = {
        'index': INDEX,
        'nodes': es.cluster_nodes(),
        'health': es.cluster_health(),
        'state': es.cluster_state(),
        'mappings': [(index, mappings.get(index, {})) for index in indexes],
    }
    return jingo.render(request, 'zadmin/elastic.html', ctx)
示例#5
0
文件: views.py 项目: jespersh/zamboni
def edit(request):
    webapp = settings.APP_PREVIEW
    # Don't use request.amo_user since it has too much caching.
    amouser = UserProfile.objects.get(pk=request.user.id)
    if request.method == 'POST':
        # ModelForm alters the instance you pass in.  We need to keep a copy
        # around in case we need to use it below (to email the user)
        original_email = amouser.email
        form = forms.UserEditForm(request.POST, request.FILES, request=request,
                                  instance=amouser, webapp=webapp)
        if form.is_valid():
            messages.success(request, _('Profile Updated'))
            if amouser.email != original_email:
                # Temporarily block email changes.
                if settings.APP_PREVIEW:
                    messages.error(request, 'Error',
                                   'You cannot change your email on the '
                                   'developer preview site.')
                    return jingo.render(request, 'users/edit.html',
                                        {'form': form, 'amouser': amouser})

                l = {'user': amouser,
                     'mail1': original_email,
                     'mail2': amouser.email}
                log.info(u"User (%(user)s) has requested email change from"
                          "(%(mail1)s) to (%(mail2)s)" % l)
                messages.info(request, _('Email Confirmation Sent'),
                    _(u'An email has been sent to {0} to confirm your new '
                       'email address. For the change to take effect, you '
                       'need to click on the link provided in this email. '
                       'Until then, you can keep logging in with your '
                       'current email address.').format(amouser.email))

                domain = settings.DOMAIN
                token, hash = EmailResetCode.create(amouser.id, amouser.email)
                url = "%s%s" % (settings.SITE_URL,
                                reverse('users.emailchange', args=[amouser.id,
                                                                token, hash]))
                t = loader.get_template('users/email/emailchange.ltxt')
                c = {'domain': domain, 'url': url}
                send_mail(_('Please confirm your email address '
                            'change at %s' % domain),
                    t.render(Context(c)), None, [amouser.email],
                    use_blacklist=False, real_email=True)

                # Reset the original email back.  We aren't changing their
                # address until they confirm the new one
                amouser.email = original_email
            form.save()
            return redirect('users.edit')
        else:

            messages.error(request, _('Errors Found'),
                                    _('There were errors in the changes '
                                      'you made. Please correct them and '
                                      'resubmit.'))
    else:
        form = forms.UserEditForm(instance=amouser, webapp=webapp)
    return jingo.render(request, 'users/edit.html',
                        {'form': form, 'amouser': amouser, 'webapp': webapp})
示例#6
0
def elastic(request):
    INDEX = site_settings.ES_INDEXES["default"]
    es = elasticutils.get_es()
    mappings = {
        "addons": (addons.search.setup_mapping, addons.cron.reindex_addons),
        "collections": (addons.search.setup_mapping, bandwagon.cron.reindex_collections),
        "compat": (addons.search.setup_mapping, None),
        "users": (addons.search.setup_mapping, users.cron.reindex_users),
    }
    if request.method == "POST":
        if request.POST.get("reset") in mappings:
            name = request.POST["reset"]
            es.delete_mapping(INDEX, name)
            if mappings[name][0]:
                mappings[name][0]()
            messages.info(request, "Resetting %s." % name)
        if request.POST.get("reindex") in mappings:
            name = request.POST["reindex"]
            mappings[name][1]()
            messages.info(request, "Reindexing %s." % name)
        return redirect("zadmin.elastic")

    indexes = set(site_settings.ES_INDEXES.values())
    mappings = es.get_mapping(None, indexes)
    ctx = {
        "nodes": es.cluster_nodes(),
        "health": es.cluster_health(),
        "state": es.cluster_state(),
        "mappings": [(index, mappings.get(index, {})) for index in indexes],
    }
    return jingo.render(request, "zadmin/elastic.html", ctx)
示例#7
0
文件: views.py 项目: dbialer/zamboni
def edit(request):
    webapp = settings.APP_PREVIEW
    # Don't use request.amo_user since it has too much caching.
    amouser = UserProfile.objects.get(pk=request.user.id)
    if request.method == "POST":
        # ModelForm alters the instance you pass in.  We need to keep a copy
        # around in case we need to use it below (to email the user)
        original_email = amouser.email
        form = forms.UserEditForm(request.POST, request.FILES, request=request, instance=amouser, webapp=webapp)
        if form.is_valid():
            messages.success(request, _("Profile Updated"))
            if amouser.email != original_email:
                # Temporarily block email changes.
                if settings.APP_PREVIEW:
                    messages.error(request, "Error", "You cannot change your email on the " "developer preview site.")
                    return jingo.render(request, "users/edit.html", {"form": form, "amouser": amouser})

                l = {"user": amouser, "mail1": original_email, "mail2": amouser.email}
                log.info(u"User (%(user)s) has requested email change from" "(%(mail1)s) to (%(mail2)s)" % l)
                messages.info(
                    request,
                    _("Email Confirmation Sent"),
                    _(
                        u"An email has been sent to {0} to confirm your new "
                        "email address. For the change to take effect, you "
                        "need to click on the link provided in this email. "
                        "Until then, you can keep logging in with your "
                        "current email address."
                    ).format(amouser.email),
                )

                domain = settings.DOMAIN
                token, hash = EmailResetCode.create(amouser.id, amouser.email)
                url = "%s%s" % (settings.SITE_URL, reverse("users.emailchange", args=[amouser.id, token, hash]))
                t = loader.get_template("users/email/emailchange.ltxt")
                c = {"domain": domain, "url": url}
                send_mail(
                    _("Please confirm your email address " "change at %s" % domain),
                    t.render(Context(c)),
                    None,
                    [amouser.email],
                    use_blacklist=False,
                    real_email=True,
                )

                # Reset the original email back.  We aren't changing their
                # address until they confirm the new one
                amouser.email = original_email
            form.save()
            return redirect("users.edit")
        else:

            messages.error(
                request,
                _("Errors Found"),
                _("There were errors in the changes " "you made. Please correct them and " "resubmit."),
            )
    else:
        form = forms.UserEditForm(instance=amouser, webapp=webapp)
    return jingo.render(request, "users/edit.html", {"form": form, "amouser": amouser, "webapp": webapp})
示例#8
0
def register(request):
    if waffle.switch_is_active('fxa-auth'):
        return login(request)

    if 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():
            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.'))
示例#9
0
def login(request):
    logout(request)

    if 'to' in request.GET:
        request = _clean_next_url(request)

    r = auth.views.login(request, template_name='users/login.html',
                         redirect_field_name='to',
                         authentication_form=forms.AuthenticationForm)

    if isinstance(r, http.HttpResponseRedirect):
        # Succsesful log in according to django.  Now we do our checks.  I do
        # the checks here instead of the form's clean() because I want to use
        # the messages framework and it's not available in the request there
        user = request.user.get_profile()

        if user.deleted:
            logout(request)
            log.warning(u'Attempt to log in with deleted account (%s)' % user)
            messages.error(request, _('Wrong email address or password!'))
            return jingo.render(request, 'users/login.html',
                                {'form': forms.AuthenticationForm()})

        if user.confirmationcode:
            logout(request)
            log.info(u'Attempt to log in with unconfirmed account (%s)' % user)
            msg1 = _(('A link to activate your user account was sent by email '
                      'to your address {0}. You have to click it before you '
                      'can log in.').format(user.email))
            url = "%s%s" % (settings.SITE_URL,
                            reverse('users.confirm.resend', args=[user.id]))
            msg2 = _(('If you did not receive the confirmation email, make '
                      'sure your email service did not mark it as "junk '
                      'mail" or "spam". If you need to, you can have us '
                      '<a href="%s">resend the confirmation message</a> '
                      'to your email address mentioned above.') % url)
            messages.error(request, _('Activation Email Sent'),  msg1)
            messages.info(request, _('Having Trouble?'), msg2,
                          title_safe=True)
            return jingo.render(request, 'users/login.html',
                                {'form': forms.AuthenticationForm()})

        rememberme = request.POST.get('rememberme', None)
        if rememberme:
            request.session.set_expiry(settings.SESSION_COOKIE_AGE)
            log.debug((u'User (%s) logged in successfully with '
                                        '"remember me" set') % user)
        else:
            user.log_login_attempt(request, True)
    elif 'username' in request.POST:
        # Hitting POST directly because cleaned_data doesn't exist
        user = UserProfile.objects.filter(email=request.POST['username'])
        if user:
            user.get().log_login_attempt(request, False)

    return r
示例#10
0
def blocklist(request, addon):
    """
    Blocklists the app by creating a new version/file.
    """
    if addon.status != amo.STATUS_BLOCKED:
        addon.create_blocklisted_version()
        messages.success(request, _('Created blocklisted version.'))
    else:
        messages.info(request, _('App already blocklisted.'))

    return redirect(addon.get_dev_url('versions'))
示例#11
0
def edit(request):
    # Don't use request.amo_user since it has too much caching.
    amouser = UserProfile.objects.get(pk=request.user.id)
    if request.method == 'POST':
        # ModelForm alters the instance you pass in.  We need to keep a copy
        # around in case we need to use it below (to email the user)
        original_email = amouser.email
        form = forms.UserEditForm(request.POST, request.FILES, request=request,
                                  instance=amouser)
        if form.is_valid():
            messages.success(request, _('Profile Updated'))
            if amouser.email != original_email:

                l = {'user': amouser,
                     'mail1': original_email,
                     'mail2': amouser.email}
                log.info(u"User (%(user)s) has requested email change from "
                         u"(%(mail1)s) to (%(mail2)s)" % l)
                messages.info(
                    request, _('Email Confirmation Sent'),
                    _(u'An email has been sent to {0} to confirm your new '
                      u'email address. For the change to take effect, you '
                      u'need to click on the link provided in this email. '
                      u'Until then, you can keep logging in with your '
                      u'current email address.').format(amouser.email))

                token, hash_ = EmailResetCode.create(amouser.id, amouser.email)
                url = '%s%s' % (settings.SITE_URL,
                                reverse('users.emailchange',
                                        args=[amouser.id, token, hash_]))
                t = loader.get_template('users/email/emailchange.ltxt')
                c = {'domain': settings.DOMAIN, 'url': url}
                send_mail(
                    _('Please confirm your email address '
                      'change at %s' % settings.DOMAIN),
                    t.render(Context(c)), None, [amouser.email],
                    use_blacklist=False, real_email=True)

                # Reset the original email back.  We aren't changing their
                # address until they confirm the new one
                amouser.email = original_email
            form.save()
            return redirect('users.edit')
        else:

            messages.error(
                request,
                _('Errors Found'),
                _('There were errors in the changes you made. Please correct '
                  'them and resubmit.'))
    else:
        form = forms.UserEditForm(instance=amouser, request=request)
    return render(request, 'users/edit.html',
                  {'form': form, 'amouser': amouser})
示例#12
0
def blocklist(request, addon):
    """
    Blocklists the app by creating a new version/file.
    """
    if addon.status != amo.STATUS_BLOCKED:
        addon.create_blocklisted_version()
        messages.success(request, _('Created blocklisted version.'))
    else:
        messages.info(request, _('App already blocklisted.'))

    return redirect(addon.get_dev_url('versions'))
示例#13
0
def test_html_rendered_properly():
    """Html markup is properly displayed in final template."""
    request = HttpRequest()
    setattr(request, '_messages', default_storage(request))

    # This will call _file_message, which in turn calls _make_message, which in
    # turn renders the message_content.html template, which adds html markup.
    # We want to make sure this markup reaches the final rendering unescaped.
    info(request, 'Title', 'Body')

    messages = django_messages.get_messages(request)

    template = env.get_template('messages.html')
    html = template.render({'messages': messages})
    assert "<h2>" in html  # The html from _make_message is not escaped.
示例#14
0
文件: views.py 项目: jsocol/zamboni
def edit(request):
    amouser = request.user.get_profile()
    if request.method == 'POST':
        # ModelForm alters the instance you pass in.  We need to keep a copy
        # around in case we need to use it below (to email the user)
        original_email = amouser.email
        form = forms.UserEditForm(request.POST, request.FILES, request=request,
                                  instance=amouser)
        if form.is_valid():
            messages.success(request, _('Profile Updated'))
            if amouser.email != original_email:
                l = {'user': amouser,
                     'mail1': original_email,
                     'mail2': amouser.email}
                log.info(u"User (%(user)s) has requested email change from"
                          "(%(mail1)s) to (%(mail2)s)" % l)
                messages.info(request, _(('An email has been sent to {0} to '
                    'confirm your new email address. For the change to take '
                    'effect, you need to click on the link provided in this '
                    'email. Until then, you can keep logging in with your '
                    'current email address.')).format(amouser.email))

                domain = settings.DOMAIN
                token, hash = EmailResetCode.create(amouser.id, amouser.email)
                url = "%s%s" % (settings.SITE_URL,
                                reverse('users.emailchange', args=[amouser.id,
                                                                token, hash]))
                t = loader.get_template('users/email/emailchange.ltxt')
                c = {'domain': domain, 'url': url, }
                send_mail(_(("Please confirm your email address "
                             "change at %s") % domain),
                    t.render(Context(c)), None, [amouser.email])

                # Reset the original email back.  We aren't changing their
                # address until they confirm the new one
                amouser.email = original_email
            form.save()
            return http.HttpResponseRedirect(reverse('users.edit'))
        else:

            messages.error(request, _('There were errors in the changes '
                                      'you made. Please correct them and '
                                      'resubmit.'))
    else:
        form = forms.UserEditForm(instance=amouser)

    return jingo.render(request, 'users/edit.html',
                        {'form': form, 'amouser': amouser})
示例#15
0
def confirm_resend(request, user):
    if not user.confirmationcode:
        return redirect('users.login')

    # Potential for flood here if someone requests a confirmationcode and then
    # re-requests confirmations.  We may need to track requests in the future.
    log.info(u"Account confirm re-requested for user (%s)", user)

    user.email_confirmation_code()

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

    return redirect('users.login')
示例#16
0
文件: views.py 项目: steekid/zamboni
def confirm_resend(request, user):
    if not user.confirmationcode:
        return redirect('users.login')

    # Potential for flood here if someone requests a confirmationcode and then
    # re-requests confirmations.  We may need to track requests in the future.
    log.info(u"Account confirm re-requested for user (%s)", user)

    user.email_confirmation_code()

    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(user.email)
    messages.info(request, _('Confirmation Email Sent'), msg)

    return redirect('users.login')
示例#17
0
def register(request):
    if 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)

                u.email_confirmation_code()

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

                msg = _(('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))

            amo.utils.clear_messages(request)
            return http.HttpResponseRedirect(reverse('users.login') + '?m=3')
            # TODO POSTREMORA Replace the above two lines
            # when remora goes away with this:
            #return http.HttpResponseRedirect(reverse('users.login'))

        else:
            messages.error(request, _('There are errors in this form'),
                           _('Please correct them and resubmit.'))
示例#18
0
def register(request):
    if 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)

                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))

            amo.utils.clear_messages(request)
            return http.HttpResponseRedirect(reverse('users.login') + '?m=3')
            # TODO POSTREMORA Replace the above two lines
            # when remora goes away with this:
            #return http.HttpResponseRedirect(reverse('users.login'))

        else:
            messages.error(request, _('There are errors in this form'),
                            _('Please correct them and resubmit.'))
示例#19
0
def confirm_resend(request, user_id):
    user = get_object_or_404(UserProfile, id=user_id)

    if not user.confirmationcode:
        return http.HttpResponseRedirect(reverse('users.login'))

    # Potential for flood here if someone requests a confirmationcode and then
    # re-requests confirmations.  We may need to track requests in the future.
    log.info(u"Account confirm re-requested for user (%s)", user)

    user.email_confirmation_code()

    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(user.email)
    messages.info(request, _('Confirmation Email Sent'), msg)

    return http.HttpResponseRedirect(reverse('users.login'))
示例#20
0
文件: views.py 项目: jsocol/zamboni
def confirm_resend(request, user_id):
    user = get_object_or_404(UserProfile, id=user_id)

    if not user.confirmationcode:
        return http.HttpResponseRedirect(reverse('users.login'))

    # Potential for flood here if someone requests a confirmationcode and then
    # re-requests confirmations.  We may need to track requests in the future.
    log.info(u"Account confirm re-requested for user (%s)", user)

    user.email_confirmation_code()

    msg = _('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(user.email)
    messages.info(request, msg)

    return http.HttpResponseRedirect(reverse('users.login'))
示例#21
0
def register(request):
    if 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():
            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)

            u.email_confirmation_code()

            messages.success(
                request,
                _('Congratulations! Your user account '
                  'was successfully created.'))
            msg = _(('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)

            amo.utils.clear_messages(request)
            return http.HttpResponseRedirect(reverse('users.login') + '?m=3')
            # TODO POSTREMORA Replace the above with this line
            # when remora goes away
            #return http.HttpResponseRedirect(reverse('users.login'))

        else:
            messages.error(request, _('There are errors in this form'),
                           _('Please correct them and resubmit.'))
    else:
        form = forms.UserRegisterForm()
    return jingo.render(request, 'users/register.html', {
        'form': form,
    })
示例#22
0
def elastic(request):
    INDEX = settings.ES_INDEXES['default']
    es = elasticutils.get_es()
    mappings = {
        'addons': reindex_addons,
        'apps': reindex_apps,
        'collections': reindex_collections,
        'compat': compatibility_report,
        'users': reindex_users,
        'stats_latest': index_latest_stats,
        'mkt_stats': index_mkt_stats,
        'mkt_stats_latest': index_latest_mkt_stats
    }
    if request.method == 'POST':
        if request.POST.get('recreate'):
            es.delete_index_if_exists(INDEX)
            # We must set up the mappings before we create the index again.
            setup_mapping()
            setup_indexes()
            if setup_mkt_indexes:
                setup_mkt_indexes()
            create_es_index_if_missing(INDEX)
            messages.info(request, 'Deleting %s index.' % INDEX)
        if request.POST.get('reindex') in mappings:
            name = request.POST['reindex']
            # Reindex.
            if mappings.get(name):
                mappings[name]()
            messages.info(request, 'Reindexing %s.' % name)
        return redirect('zadmin.elastic')

    indexes = set(settings.ES_INDEXES.values())
    es_mappings = es.get_mapping(None, indexes)
    ctx = {
        'index': INDEX,
        'nodes': es.cluster_nodes(),
        'health': es.cluster_health(),
        'state': es.cluster_state(),
        'mappings': [(index, es_mappings.get(index, {})) for index in indexes],
        'choices': mappings,
    }
    return jingo.render(request, 'zadmin/elastic.html', ctx)
示例#23
0
文件: views.py 项目: jespersh/zamboni
def elastic(request):
    INDEX = settings.ES_INDEXES["default"]
    es = elasticutils.get_es()
    mappings = {
        "addons": reindex_addons,
        "apps": reindex_apps,
        "collections": reindex_collections,
        "compat": compatibility_report,
        "users": reindex_users,
        "stats_latest": index_latest_stats,
        "mkt_stats": index_mkt_stats,
        "mkt_stats_latest": index_latest_mkt_stats,
    }
    if request.method == "POST":
        if request.POST.get("recreate"):
            es.delete_index_if_exists(INDEX)
            # We must set up the mappings before we create the index again.
            setup_mapping()
            setup_indexes()
            if setup_mkt_indexes:
                setup_mkt_indexes()
            create_es_index_if_missing(INDEX)
            messages.info(request, "Deleting %s index." % INDEX)
        if request.POST.get("reindex") in mappings:
            name = request.POST["reindex"]
            # Reindex.
            if mappings.get(name):
                mappings[name]()
            messages.info(request, "Reindexing %s." % name)
        return redirect("zadmin.elastic")

    indexes = set(settings.ES_INDEXES.values())
    es_mappings = es.get_mapping(None, indexes)
    ctx = {
        "index": INDEX,
        "nodes": es.cluster_nodes(),
        "health": es.cluster_health(),
        "state": es.cluster_state(),
        "mappings": [(index, es_mappings.get(index, {})) for index in indexes],
        "choices": mappings,
    }
    return jingo.render(request, "zadmin/elastic.html", ctx)
示例#24
0
def confirm_resend(request, user_id):
    user = get_object_or_404(UserProfile, id=user_id)

    if not user.confirmationcode:
        return redirect("users.login")

    # Potential for flood here if someone requests a confirmationcode and then
    # re-requests confirmations.  We may need to track requests in the future.
    log.info(u"Account confirm re-requested for user (%s)", user)

    user.email_confirmation_code()

    if waffle.switch_is_active("zamboni-login"):
        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(user.email)
        messages.info(request, _("Confirmation Email Sent"), msg)

    return redirect("users.login")
示例#25
0
文件: views.py 项目: exezaid/zamboni
def register(request):
    if 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():
            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)

            u.email_confirmation_code()

            messages.success(request, _('Congratulations! Your user account '
                                        'was successfully created.'))
            msg = _(('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, msg)

            amo.utils.clear_messages(request)
            return http.HttpResponseRedirect(reverse('users.login') + '?m=3')
            # TODO POSTREMORA Replace the above with this line
            # when remora goes away
            #return http.HttpResponseRedirect(reverse('users.login'))

        else:
            messages.error(request, _(('There are errors in this form. Please '
                                       'correct them and resubmit.')))
    else:
        form = forms.UserRegisterForm()
    return jingo.render(request, 'users/register.html', {'form': form, })
示例#26
0
def test_l10n_dups():
    """Test that L10n values are preserved."""
    request = HttpRequest()
    setattr(request, '_messages', default_storage(request))

    info(request, _('Title'), _('Body'))
    info(request, _('Title'), _('Body'))
    info(request, _('Another Title'), _('Another Body'))

    storage = django_messages.get_messages(request)
    eq_(len(storage), 2, 'Too few or too many messages recorded.')
示例#27
0
def test_unicode_dups():
    """Test that unicode values are preserved."""
    request = HttpRequest()
    setattr(request, "_messages", default_storage(request))

    info(request, u"Titlé", u"Body")
    info(request, u"Titlé", u"Body")
    info(request, u"Another Titlé", u"Another Body")

    storage = django_messages.get_messages(request)
    eq_(len(storage), 2, "Too few or too many messages recorded.")
示例#28
0
def test_unicode_dups():
    """Test that unicode values are preserved."""
    request = HttpRequest()
    setattr(request, '_messages', default_storage(request))

    info(request, u'Titlé', u'Body')
    info(request, u'Titlé', u'Body')
    info(request, u'Another Titlé', u'Another Body')

    storage = django_messages.get_messages(request)
    eq_(len(storage), 2, 'Too few or too many messages recorded.')
示例#29
0
def test_no_dupes():
    """Test that duplicate messages aren't saved."""
    request = HttpRequest()
    setattr(request, '_messages', default_storage(request))

    info(request, 'Title', 'Body')
    info(request, 'Title', 'Body')
    info(request, 'Another Title', 'Another Body')

    storage = django_messages.get_messages(request)
    eq_(len(storage), 2, 'Too few or too many messages recorded.')
示例#30
0
def test_l10n_dups():
    """Test that L10n values are preserved."""
    request = HttpRequest()
    setattr(request, "_messages", default_storage(request))

    info(request, _("Title"), _("Body"))
    info(request, _("Title"), _("Body"))
    info(request, _("Another Title"), _("Another Body"))

    storage = django_messages.get_messages(request)
    eq_(len(storage), 2, "Too few or too many messages recorded.")
示例#31
0
def test_no_dupes():
    """Test that duplicate messages aren't saved."""
    request = HttpRequest()
    setattr(request, "_messages", default_storage(request))

    info(request, "Title", "Body")
    info(request, "Title", "Body")
    info(request, "Another Title", "Another Body")

    storage = django_messages.get_messages(request)
    eq_(len(storage), 2, "Too few or too many messages recorded.")
示例#32
0
文件: views.py 项目: hardikj/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."))
示例#33
0
文件: views.py 项目: dbialer/zamboni
def _login(request, template=None, data=None, dont_redirect=False):
    data = data or {}
    usercount = UserProfile.objects.count()
    data.update(
        webapp=settings.APP_PREVIEW,
        registration_closed=(settings.REGISTER_USER_LIMIT > 0 and usercount > settings.REGISTER_USER_LIMIT),
    )
    # In case we need it later.  See below.
    get_copy = request.GET.copy()

    if "to" in request.GET:
        request = _clean_next_url(request)

    if request.user.is_authenticated():
        return redirect(request.GET.get("to", settings.LOGIN_REDIRECT_URL))

    limited = getattr(request, "limited", "recaptcha_shown" in request.POST)
    user = None
    login_status = None
    if "username" in request.POST:
        try:
            # We are doing all this before we try and validate the form.
            user = UserProfile.objects.get(email=request.POST["username"])
            limited = (user.failed_login_attempts >= settings.LOGIN_RATELIMIT_USER) or limited
            login_status = False
        except UserProfile.DoesNotExist:
            log_cef(
                "Authentication Failure",
                5,
                request,
                username=request.POST["username"],
                signature="AUTHFAIL",
                msg="The username was invalid",
            )
            pass

    partial_form = partial(forms.AuthenticationForm, use_recaptcha=limited)
    r = auth.views.login(
        request, template_name=template, redirect_field_name="to", authentication_form=partial_form, extra_context=data
    )

    if isinstance(r, http.HttpResponseRedirect):
        # Django's auth.views.login has security checks to prevent someone from
        # redirecting to another domain.  Since we want to allow this in
        # certain cases, we have to make a new response object here to replace
        # the above.

        if "domain" in request.GET:
            request.GET = get_copy
            request = _clean_next_url(request)
            r = http.HttpResponseRedirect(request.GET["to"])

        # Succsesful log in according to django.  Now we do our checks.  I do
        # the checks here instead of the form's clean() because I want to use
        # the messages framework and it's not available in the request there.
        user = request.user.get_profile()

        if user.deleted:
            logout(request)
            log.warning(u"Attempt to log in with deleted account (%s)" % user)
            messages.error(request, _("Wrong email address or password!"))
            data.update({"form": partial_form()})
            user.log_login_attempt(False)
            log_cef(
                "Authentication Failure",
                5,
                request,
                username=request.user,
                signature="AUTHFAIL",
                msg="Account is deactivated",
            )
            return jingo.render(request, template, data)

        if user.confirmationcode:
            logout(request)
            log.info(u"Attempt to log in with unconfirmed account (%s)" % user)
            msg1 = _(
                u"A link to activate your user account was sent by email "
                "to your address {0}. You have to click it before you "
                "can log in."
            ).format(user.email)
            url = "%s%s" % (settings.SITE_URL, reverse("users.confirm.resend", args=[user.id]))
            msg2 = (
                _(
                    "If you did not receive the confirmation email, make "
                    'sure your email service did not mark it as "junk '
                    'mail" or "spam". If you need to, you can have us '
                    '<a href="%s">resend the confirmation message</a> '
                    "to your email address mentioned above."
                )
                % url
            )
            messages.error(request, _("Activation Email Sent"), msg1)
            messages.info(request, _("Having Trouble?"), msg2, title_safe=True, message_safe=True)
            data.update({"form": partial_form()})
            user.log_login_attempt(False)
            return jingo.render(request, template, data)

        rememberme = request.POST.get("rememberme", None)
        if rememberme:
            request.session.set_expiry(settings.SESSION_COOKIE_AGE)
            log.debug((u"User (%s) logged in successfully with " '"remember me" set') % user)

        login_status = True

        if dont_redirect:
            # We're recalling the middleware to re-initialize amo_user
            ACLMiddleware().process_request(request)
            r = jingo.render(request, template, data)

    if login_status is not None:
        user.log_login_attempt(login_status)
        log_cef(
            "Authentication Failure",
            5,
            request,
            username=request.POST["username"],
            signature="AUTHFAIL",
            msg="The password was incorrect",
        )

    if settings.REGISTER_OVERRIDE_TOKEN and request.GET.get("ro") == settings.REGISTER_OVERRIDE_TOKEN:
        # This allows the browser ID registration to see the token.
        r.set_cookie(
            "reg_override_token", value=settings.REGISTER_OVERRIDE_TOKEN, expires=datetime.utcnow() + timedelta(weeks=1)
        )
    return r
示例#34
0
def login(request, template=None):
    # In case we need it later.  See below.
    get_copy = request.GET.copy()

    logout(request)

    if 'to' in request.GET:
        request = _clean_next_url(request)

    limited = getattr(request, 'limited', 'recaptcha_shown' in request.POST)
    partial_form = partial(forms.AuthenticationForm, use_recaptcha=limited)
    r = auth.views.login(request, template_name=template,
                         redirect_field_name='to',
                         authentication_form=partial_form)

    if isinstance(r, http.HttpResponseRedirect):
        # Django's auth.views.login has security checks to prevent someone from
        # redirecting to another domain.  Since we want to allow this in
        # certain cases, we have to make a new response object here to replace
        # the above.
        if 'domain' in request.GET:
            request.GET = get_copy
            request = _clean_next_url(request)
            r = http.HttpResponseRedirect(request.GET['to'])

        # Succsesful log in according to django.  Now we do our checks.  I do
        # the checks here instead of the form's clean() because I want to use
        # the messages framework and it's not available in the request there.
        user = request.user.get_profile()

        if user.deleted:
            logout(request)
            log.warning(u'Attempt to log in with deleted account (%s)' % user)
            messages.error(request, _('Wrong email address or password!'))
            return jingo.render(request, 'users/login.html',
                                {'form': partial_form()})

        if user.confirmationcode:
            logout(request)
            log.info(u'Attempt to log in with unconfirmed account (%s)' % user)
            msg1 = _(u'A link to activate your user account was sent by email '
                      'to your address {0}. You have to click it before you '
                      'can log in.').format(user.email)
            url = "%s%s" % (settings.SITE_URL,
                            reverse('users.confirm.resend', args=[user.id]))
            msg2 = _(('If you did not receive the confirmation email, make '
                      'sure your email service did not mark it as "junk '
                      'mail" or "spam". If you need to, you can have us '
                      '<a href="%s">resend the confirmation message</a> '
                      'to your email address mentioned above.') % url)
            messages.error(request, _('Activation Email Sent'),  msg1)
            messages.info(request, _('Having Trouble?'), msg2,
                          title_safe=True)
            return jingo.render(request, 'users/login.html',
                                {'form': partial_form()})

        if (user.failed_login_attempts > settings.LOGIN_RATELIMIT_USER
            and not limited):
            # This reshows the form with the recaptcha. Until they are logged
            # in we don't know if the user needs to have recaptcha shown.
            # The UX for this isn't good, we should fix this.
            logout(request)
            log.info(u'Attempt to log in with too many failures (%s)' % user)
            form = forms.AuthenticationForm(request.POST, use_recaptcha=True)
            return jingo.render(request, 'users/login.html', {'form': form})

        rememberme = request.POST.get('rememberme', None)
        if rememberme:
            request.session.set_expiry(settings.SESSION_COOKIE_AGE)
            log.debug((u'User (%s) logged in successfully with '
                                        '"remember me" set') % user)
        else:
            user.log_login_attempt(request, True)
    elif 'username' in request.POST:
        # Hitting POST directly because cleaned_data doesn't exist
        user = UserProfile.objects.filter(email=request.POST['username'])
        if user:
            user.get().log_login_attempt(request, False)

    return r
示例#35
0
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.'))
示例#36
0
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()

                if waffle.switch_is_active("zamboni-login"):
                    # Hide these messages since prod still uses remora for
                    # authentication, so django messages won't be displayed
                    # until post-login.
                    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():
            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."))
示例#37
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.'))
示例#38
0
def _login(request, template=None, data=None, dont_redirect=False):
    data = data or {}
    # In case we need it later.  See below.
    get_copy = request.GET.copy()

    if 'to' in request.GET:
        request = _clean_next_url(request)

    if request.user.is_authenticated():
        return http.HttpResponseRedirect(
            request.GET.get('to', settings.LOGIN_REDIRECT_URL))

    limited = getattr(request, 'limited', 'recaptcha_shown' in request.POST)
    user = None
    login_status = None
    if 'username' in request.POST:
        try:
            # We are doing all this before we try and validate the form.
            user = UserProfile.objects.get(email=request.POST['username'])
            limited = (
                (user.failed_login_attempts >= settings.LOGIN_RATELIMIT_USER)
                or limited)
            login_status = False
        except UserProfile.DoesNotExist:
            log_cef('Authentication Failure',
                    5,
                    request,
                    username=request.POST['username'],
                    signature='AUTHFAIL',
                    msg='The username was invalid')
            pass
    partial_form = partial(forms.AuthenticationForm, use_recaptcha=limited)
    r = auth.views.login(request,
                         template_name=template,
                         redirect_field_name='to',
                         authentication_form=partial_form,
                         extra_context=data)

    if isinstance(r, http.HttpResponseRedirect):
        # Django's auth.views.login has security checks to prevent someone from
        # redirecting to another domain.  Since we want to allow this in
        # certain cases, we have to make a new response object here to replace
        # the above.

        if 'domain' in request.GET:
            request.GET = get_copy
            request = _clean_next_url(request)
            r = http.HttpResponseRedirect(request.GET['to'])

        # Succsesful log in according to django.  Now we do our checks.  I do
        # the checks here instead of the form's clean() because I want to use
        # the messages framework and it's not available in the request there.
        if user.deleted:
            logout(request)
            log.warning(u'Attempt to log in with deleted account (%s)' % user)
            messages.error(request, _('Wrong email address or password!'))
            data.update({'form': partial_form()})
            user.log_login_attempt(False)
            log_cef('Authentication Failure',
                    5,
                    request,
                    username=request.user,
                    signature='AUTHFAIL',
                    msg='Account is deactivated')
            return render(request, template, data)

        if user.confirmationcode:
            logout(request)
            log.info(u'Attempt to log in with unconfirmed account (%s)' % user)
            msg1 = _(u'A link to activate your user account was sent by email '
                     u'to your address {0}. You have to click it before you '
                     u'can log in.').format(user.email)
            url = "%s%s" % (settings.SITE_URL,
                            reverse('users.confirm.resend', args=[user.id]))
            msg2 = _('If you did not receive the confirmation email, make '
                     'sure your email service did not mark it as "junk '
                     'mail" or "spam". If you need to, you can have us '
                     '<a href="%s">resend the confirmation message</a> '
                     'to your email address mentioned above.') % url
            messages.error(request, _('Activation Email Sent'), msg1)
            messages.info(request,
                          _('Having Trouble?'),
                          msg2,
                          title_safe=True,
                          message_safe=True)
            data.update({'form': partial_form()})
            user.log_login_attempt(False)
            return render(request, template, data)

        rememberme = request.POST.get('rememberme', None)
        if rememberme:
            request.session.set_expiry(settings.SESSION_COOKIE_AGE)
            log.debug(
                u'User (%s) logged in successfully with "remember me" set' %
                user)

        login_status = True

        if dont_redirect:
            # We're recalling the middleware to re-initialize amo_user
            ACLMiddleware().process_request(request)
            r = render(request, template, data)

    if login_status is not None:
        user.log_login_attempt(login_status)
        log_cef('Authentication Failure',
                5,
                request,
                username=request.POST['username'],
                signature='AUTHFAIL',
                msg='The password was incorrect')

    return r
示例#39
0
文件: views.py 项目: dimonov/zamboni
def _login(request, template=None, data=None, dont_redirect=False):
    data = data or {}
    data['webapp'] = settings.APP_PREVIEW
    # In case we need it later.  See below.
    get_copy = request.GET.copy()

    if 'to' in request.GET:
        request = _clean_next_url(request)

    if request.user.is_authenticated():
        return http.HttpResponseRedirect(
            request.GET.get('to', settings.LOGIN_REDIRECT_URL))

    limited = getattr(request, 'limited', 'recaptcha_shown' in request.POST)
    user = None
    login_status = None
    if 'username' in request.POST:
        try:
            # We are doing all this before we try and validate the form.
            user = UserProfile.objects.get(email=request.POST['username'])
            limited = ((user.failed_login_attempts >=
                        settings.LOGIN_RATELIMIT_USER) or limited)
            login_status = False
        except UserProfile.DoesNotExist:
            log_cef('Authentication Failure', 5, request,
                    username=request.POST['username'],
                    signature='AUTHFAIL',
                    msg='The username was invalid')
            pass

    partial_form = partial(forms.AuthenticationForm, use_recaptcha=limited)
    r = auth.views.login(request, template_name=template,
                         redirect_field_name='to',
                         authentication_form=partial_form,
                         extra_context=data)

    if isinstance(r, http.HttpResponseRedirect):
        # Django's auth.views.login has security checks to prevent someone from
        # redirecting to another domain.  Since we want to allow this in
        # certain cases, we have to make a new response object here to replace
        # the above.

        if 'domain' in request.GET:
            request.GET = get_copy
            request = _clean_next_url(request)
            r = http.HttpResponseRedirect(request.GET['to'])

        # Succsesful log in according to django.  Now we do our checks.  I do
        # the checks here instead of the form's clean() because I want to use
        # the messages framework and it's not available in the request there.
        user = request.user.get_profile()

        if user.deleted:
            logout(request)
            log.warning(u'Attempt to log in with deleted account (%s)' % user)
            messages.error(request, _('Wrong email address or password!'))
            data.update({'form': partial_form()})
            user.log_login_attempt(False)
            log_cef('Authentication Failure', 5, request,
                    username=request.user,
                    signature='AUTHFAIL',
                    msg='Account is deactivated')
            return jingo.render(request, template, data)

        if user.confirmationcode:
            logout(request)
            log.info(u'Attempt to log in with unconfirmed account (%s)' % user)
            msg1 = _(u'A link to activate your user account was sent by email '
                      'to your address {0}. You have to click it before you '
                      'can log in.').format(user.email)
            url = "%s%s" % (settings.SITE_URL,
                            reverse('users.confirm.resend', args=[user.id]))
            msg2 = _('If you did not receive the confirmation email, make '
                      'sure your email service did not mark it as "junk '
                      'mail" or "spam". If you need to, you can have us '
                      '<a href="%s">resend the confirmation message</a> '
                      'to your email address mentioned above.') % url
            messages.error(request, _('Activation Email Sent'), msg1)
            messages.info(request, _('Having Trouble?'), msg2,
                          title_safe=True, message_safe=True)
            data.update({'form': partial_form()})
            user.log_login_attempt(False)
            return jingo.render(request, template, data)

        rememberme = request.POST.get('rememberme', None)
        if rememberme:
            request.session.set_expiry(settings.SESSION_COOKIE_AGE)
            log.debug((u'User (%s) logged in successfully with '
                                        '"remember me" set') % user)

        login_status = True

        if dont_redirect:
            # We're recalling the middleware to re-initialize amo_user
            ACLMiddleware().process_request(request)
            r = jingo.render(request, template, data)

    if login_status is not None:
        user.log_login_attempt(login_status)
        log_cef('Authentication Failure', 5, request,
                username=request.POST['username'],
                signature='AUTHFAIL',
                msg='The password was incorrect')

    return r
示例#40
0
def login(request):
    # In case we need it later.  See below.
    get_copy = request.GET.copy()

    logout(request)

    if 'to' in request.GET:
        request = _clean_next_url(request)

    r = auth.views.login(request,
                         template_name='users/login.html',
                         redirect_field_name='to',
                         authentication_form=forms.AuthenticationForm)

    if isinstance(r, http.HttpResponseRedirect):
        # Django's auth.views.login has security checks to prevent someone from
        # redirecting to another domain.  Since we want to allow this in certain
        # cases, we have to make a new response object here to replace the above
        if 'domain' in request.GET:
            request.GET = get_copy
            request = _clean_next_url(request)
            r = http.HttpResponseRedirect(request.GET['to'])

        # Succsesful log in according to django.  Now we do our checks.  I do
        # the checks here instead of the form's clean() because I want to use
        # the messages framework and it's not available in the request there
        user = request.user.get_profile()

        if user.deleted:
            logout(request)
            log.warning(u'Attempt to log in with deleted account (%s)' % user)
            messages.error(request, _('Wrong email address or password!'))
            return jingo.render(request, 'users/login.html',
                                {'form': forms.AuthenticationForm()})

        if user.confirmationcode:
            logout(request)
            log.info(u'Attempt to log in with unconfirmed account (%s)' % user)
            msg1 = _(('A link to activate your user account was sent by email '
                      'to your address {0}. You have to click it before you '
                      'can log in.').format(user.email))
            url = "%s%s" % (settings.SITE_URL,
                            reverse('users.confirm.resend', args=[user.id]))
            msg2 = _(('If you did not receive the confirmation email, make '
                      'sure your email service did not mark it as "junk '
                      'mail" or "spam". If you need to, you can have us '
                      '<a href="%s">resend the confirmation message</a> '
                      'to your email address mentioned above.') % url)
            messages.error(request, _('Activation Email Sent'), msg1)
            messages.info(request, _('Having Trouble?'), msg2, title_safe=True)
            return jingo.render(request, 'users/login.html',
                                {'form': forms.AuthenticationForm()})

        rememberme = request.POST.get('rememberme', None)
        if rememberme:
            request.session.set_expiry(settings.SESSION_COOKIE_AGE)
            log.debug((u'User (%s) logged in successfully with '
                       '"remember me" set') % user)
        else:
            user.log_login_attempt(request, True)
    elif 'username' in request.POST:
        # Hitting POST directly because cleaned_data doesn't exist
        user = UserProfile.objects.filter(email=request.POST['username'])
        if user:
            user.get().log_login_attempt(request, False)

    return r