Ejemplo n.º 1
0
def edit(request):
    # Don't use request.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
    })
Ejemplo n.º 2
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.'))
Ejemplo n.º 3
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.'))
Ejemplo n.º 4
0
def edit(request):
    # Don't use request.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})
Ejemplo n.º 5
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 = get_env().get_template('messages.html')
    html = template.render({'messages': messages})
    assert "<h2>" in html  # The html from _make_message is not escaped.
Ejemplo n.º 6
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 = loader.get_template('messages.html')
    html = template.render({'messages': messages})
    assert '<h2>' in html  # The html from _make_message is not escaped.
Ejemplo n.º 7
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 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.')
    messages.info(request, _('Confirmation Email Sent'), msg)

    return redirect('users.login')
Ejemplo n.º 8
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 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.')
    messages.info(request, _('Confirmation Email Sent'), msg)

    return redirect('users.login')
Ejemplo n.º 9
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)
    assert len(storage) == 2, 'Too few or too many messages recorded.'
Ejemplo n.º 10
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)
    assert len(storage) == 2, 'Too few or too many messages recorded.'
Ejemplo n.º 11
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)
    assert len(storage) == 2, 'Too few or too many messages recorded.'
Ejemplo n.º 12
0
def test_unicode_dups():
    """Test that unicode values are preserved."""
    request = HttpRequest()
    setattr(request, '_messages', default_storage(request))

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

    storage = django_messages.get_messages(request)
    assert len(storage) == 2, 'Too few or too many messages recorded.'
Ejemplo n.º 13
0
def test_l10n_dups():
    """Test that L10n values are preserved."""
    request = HttpRequest()
    setattr(request, '_messages', default_storage(request))

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

    storage = django_messages.get_messages(request)
    assert len(storage) == 2, 'Too few or too many messages recorded.'
Ejemplo n.º 14
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)
    assert len(storage) == 2, 'Too few or too many messages recorded.'
Ejemplo n.º 15
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))

    data['login_source_form'] = (waffle.switch_is_active('fxa-auth') and
                                 not request.POST)

    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.

        request.GET = get_copy
        request = _clean_next_url(request)
        next_path = request.GET['to']
        if waffle.switch_is_active('fxa-auth'):
            if next_path == '/':
                next_path = None
            next_path = urlparams(reverse('users.migrate'), to=next_path)
        r = http.HttpResponseRedirect(next_path)

        # 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 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
Ejemplo n.º 16
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))

    data['login_source_form'] = (waffle.switch_is_active('fxa-auth')
                                 and not request.POST)

    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.info('Authentication failure, username invalid (%s)' %
                     request.POST['username'])
            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.

        request.GET = get_copy
        request = _clean_next_url(request)
        next_path = request.GET['to']
        if waffle.switch_is_active('fxa-auth'):
            if next_path == '/':
                next_path = None
            next_path = urlparams(reverse('users.migrate'), to=next_path)
        r = http.HttpResponseRedirect(next_path)

        # 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.info('Authentication Failure, account is deactivated (%s)' %
                     request.user)
            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 user
            ACLMiddleware().process_request(request)
            r = render(request, template, data)

    if login_status is not None:
        user.log_login_attempt(login_status)
        log.info('Authentication Failure, incorrect password (%s)' %
                 request.POST['username'])

    return r