Пример #1
0
    def confirm(cls, nonce):
        if ':' in nonce:
            # form created in the dashboard
            # nonce is another hash and the
            # hashid comes in the request.
            nonce, hashid = nonce.split(':')
            form = cls.get_with_hashid(hashid)
            if HASH(form.email, str(form.id)) == nonce:
                pass
            else:
                form = None
        else:
            # normal form, nonce is HASH(email, host)
            form = cls.query.filter_by(hash=nonce).first()

        if form:
            form.confirmed = True
            DB.session.add(form)
            DB.session.commit()

            stored_data = fetch_first_submission(nonce)
            if stored_data:
                form.send(stored_data, stored_data.keys(), form.host)

            return form
Пример #2
0
def resend_confirmation(email):
    g.log = g.log.bind(email=email, host=request.form.get('host'))
    g.log.info('Resending confirmation.')

    # the first thing to do is to check the captcha
    r = requests.post('https://www.google.com/recaptcha/api/siteverify', data={
        'secret': settings.RECAPTCHA_SECRET,
        'response': request.form['g-recaptcha-response'],
        'remoteip': request.remote_addr
    })
    if r.ok and r.json().get('success'):
        # then proceed to check if this email is listed on SendGrid's bounces
        r = requests.get('https://api.sendgrid.com/api/bounces.get.json',
            params={
                'email': email,
                'api_user': settings.SENDGRID_USERNAME,
                'api_key': settings.SENDGRID_PASSWORD
            }
        )
        if r.ok and len(r.json()) and 'reason' in r.json()[0]:
            # tell the user to verify his mailbox
            reason = r.json()[0]['reason']
            g.log.info('Email is blocked on SendGrid. Telling the user.')
            if request_wants_json():
                resp = jsonify({'error': "Verify your mailbox, we can't reach it.", 'reason': reason})
            else:
                resp = make_response(render_template('info.html',
                    title='Verify the availability of your mailbox',
                    text="We encountered an error when trying to deliver the confirmation message to <b>" + email + "</b> at the first time we tried. For spam reasons, we will not try again until we are sure the problem is fixed. Here's the reason:</p><p><center><i>" + reason + "</i></center></p><p>Please make sure this problem is not happening still, then go to <a href='/unblock/" + email + "'>this page</a> to unblock your address.</p><p>After you have unblocked the address, please try to resend the confirmation again.</p>"
                ))
            return resp
        # ~~~
        # if there's no bounce, we proceed to resend the confirmation.

        form = Form.query.filter_by(hash=HASH(email, request.form['host'])).first()
        if not form:
            if request_wants_json():
                return jsonerror(400, {'error': "This form does not exist."})
            else:
                return render_template('error.html',
                                       title='Check email address',
                                       text='This form does not exist.'), 400
        form.confirm_sent = False
        status = form.send_confirmation()
        if status['code'] == Form.STATUS_CONFIRMATION_SENT:
            if request_wants_json():
                return jsonify({'success': "confirmation email sent"})
            else:
                return render_template('forms/confirmation_sent.html',
                    email=email,
                    host=request.form['host'],
                    resend=status['code'] == Form.STATUS_CONFIRMATION_DUPLICATED
                )

    # fallback response -- should happen only when the recaptcha is failed.
    g.log.warning('Failed to resend confirmation.')
    return render_template('error.html',
                           title='Unable to send email',
                           text='Please make sure you pass the <i>reCaptcha</i> test before submitting.'), 500
Пример #3
0
    def send_confirmation(self, with_data=None):
        '''
        Helper that actually creates confirmation nonce
        and sends the email to associated email. Renders
        different templates depending on the result
        '''

        log.debug('Sending confirmation')
        if self.confirm_sent:
            return {'code': Form.STATUS_CONFIRMATION_DUPLICATED}

        # the nonce for email confirmation will be the hash when it exists
        # (whenever the form was created from a simple submission) or
        # a concatenation of HASH(email, id) + ':' + hashid
        # (whenever the form was created from the dashboard)
        id = str(self.id)
        nonce = self.hash or '%s:%s' % (HASH(self.email, id), self.hashid)
        link = url_for('confirm_email', nonce=nonce, _external=True)

        def render_content(ext):
            data, keys = None, None
            if with_data:
                if type(with_data) in (ImmutableMultiDict,
                                       ImmutableOrderedMultiDict):
                    data, keys = http_form_to_dict(with_data)
                else:
                    data, keys = with_data, with_data.keys()

            return render_template('email/confirm.%s' % ext,
                                   email=self.email,
                                   host=self.host,
                                   nonce_link=link,
                                   data=data,
                                   keys=keys)

        log.debug('Sending email')

        result = send_email(to=self.email,
                            subject='Confirm email for %s' %
                            settings.SERVICE_NAME,
                            text=render_content('txt'),
                            html=render_content('html'),
                            sender=settings.DEFAULT_SENDER)

        log.debug('Sent')

        if not result[0]:
            return {'code': Form.STATUS_CONFIRMATION_FAILED}

        self.confirm_sent = True
        DB.session.add(self)
        DB.session.commit()

        return {'code': Form.STATUS_CONFIRMATION_SENT}
Пример #4
0
 def __init__(self, email, host=None, owner=None):
     if host:
         self.hash = HASH(email, host)
     elif owner:
         self.owner_id = owner.id
     else:
         raise Exception('cannot create form without a host and a owner. provide one of these.')
     self.email = email
     self.host = host
     self.confirm_sent = False
     self.confirmed = False
     self.counter = 0
Пример #5
0
    def send_confirmation(self):
        '''
        Helper that actually creates confirmation nonce
        and sends the email to associated email. Renders
        different templates depending on the result
        '''

        log.debug('Sending confirmation')
        if self.confirm_sent:
            return {'code': Form.STATUS_CONFIRMATION_DUPLICATED}

        # the nonce for email confirmation will be the hash when it exists
        # (whenever the form was created from a simple submission) or
        # a concatenation of HASH(email, id) + ':' + random_like_string
        # (whenever the form was created from the dashboard)
        id = str(self.id)
        nonce = self.hash or '%s:%s' % (HASH(
            self.email, id), self.get_random_like_string())
        link = url_for('confirm_email', nonce=nonce, _external=True)

        def render_content(type):
            return render_template('email/confirm.%s' % type,
                                   email=self.email,
                                   host=self.host,
                                   nonce_link=link)

        log.debug('Sending email')

        result = send_email(to=self.email,
                            subject='Confirm email for %s' %
                            settings.SERVICE_NAME,
                            text=render_content('txt'),
                            html=render_content('html'),
                            sender=settings.DEFAULT_SENDER)

        log.debug('Sent')

        if not result[0]:
            return {'code': Form.STATUS_CONFIRMATION_FAILED}

        self.confirm_sent = True
        DB.session.add(self)
        DB.session.commit()

        return {'code': Form.STATUS_CONFIRMATION_SENT}
Пример #6
0
    def confirm(cls, nonce):
        if ':' in nonce:
            # form created in the dashboard
            # nonce is another hash and the id
            # comes in the request
            nonce, id = nonce.split(':')
            form = cls.query.get(id)
            if HASH(form.email, str(form.id)) == nonce:
                pass
            else:
                form = None
        else:
            # normal form, nonce is HASH(email, host)
            form = cls.query.filter_by(hash=nonce).first()

        if form:
            form.confirmed = True
            DB.session.add(form)
            DB.session.commit()
            return form
Пример #7
0
def resend_confirmation(email):
    # I'm not sure if this should be available for forms created on the dashboard.
    form = Form.query.filter_by(hash=HASH(email, request.form['host'])).first()
    if not form:
        if request_wants_json():
            return jsonerror(400, {'error': "This form does not exists"})
        else:
            return render_template('error.html',
                                   title='Check email address',
                                   text='This form does not exists'), 400

    r = requests.post('https://www.google.com/recaptcha/api/siteverify',
                      data={
                          'secret': settings.RECAPTCHA_SECRET,
                          'response': request.form['g-recaptcha-response'],
                          'remoteip': request.remote_addr
                      })
    if r.ok and r.json()['success']:
        form.confirm_sent = False
        status = form.send_confirmation()
        if status['code'] == Form.STATUS_CONFIRMATION_SENT:
            if request_wants_json():
                return jsonify({'success': "confirmation email sent"})
            else:
                return render_template('forms/confirmation_sent.html',
                                       email=email,
                                       host=request.form['host'],
                                       resend=status['code'] ==
                                       Form.STATUS_CONFIRMATION_DUPLICATED)

    # fallback response -- should never happen
    if request_wants_json():
        return jsonerror(500, {'error': "Unable to send email"})
    else:
        return render_template('error.html',
                               title='Unable to send email',
                               text='Unable to send email'), 500
Пример #8
0
def send(email_or_string):
    '''
    Main endpoint, finds or creates the form row from the database,
    checks validity and state of the form and sends either form data
    or verification to email.
    '''

    g.log = g.log.bind(target=email_or_string)

    if request.method == 'GET':
        if request_wants_json():
            return jsonerror(405, {'error': "Please submit POST request."})
        else:
            return render_template('info.html',
                                   title='Form should POST',
                                   text='Make sure your form has the <span '
                                   'class="code"><strong>method="POST"'
                                   '</strong></span> attribute'), 405

    if request.form:
        received_data, sorted_keys = http_form_to_dict(request.form)
    else:
        received_data = request.get_json() or {}
        sorted_keys = received_data.keys()

    try:
        # Get stored hostname from redis (from captcha)
        host, referrer = get_temp_hostname(received_data['_host_nonce'])
    except KeyError:
        host, referrer = referrer_to_path(request.referrer), request.referrer

    if not host or host == 'www.google.com':
        if request_wants_json():
            return jsonerror(400, {'error': "Invalid \"Referrer\" header"})
        else:
            return render_template(
                'error.html',
                title='Unable to submit form',
                text=
                '<p>Make sure you open this page through a web server, Formspree will not work in pages browsed as HTML files. Also make sure that you\'re posting to <b>{host}{path}</b>.</p><p>For geeks: could not find the "Referrer" header.</p>'
                .format(host=settings.SERVICE_URL, path=request.path)), 400

    g.log = g.log.bind(host=host,
                       wants='json' if request_wants_json() else 'html')

    g.log.info('Received submission.')
    if not IS_VALID_EMAIL(email_or_string):
        # in this case it can be a hashid identifying a
        # form generated from the dashboard
        hashid = email_or_string
        form = Form.get_with_hashid(hashid)

        if form:
            # Check if it has been assigned about using AJAX or not
            assign_ajax(form, request_wants_json())

            if form.disabled:
                # owner has disabled the form, so it should not receive any submissions
                if request_wants_json():
                    return jsonerror(403, {'error': 'Form not active'})
                else:
                    return render_template(
                        'error.html',
                        title='Form not active',
                        text=
                        'The owner of this form has disabled this form and it is no longer accepting submissions. Your submissions was not accepted'
                    ), 403
            email = form.email

            if not form.host:
                # add the host to the form
                form.host = host
                DB.session.add(form)
                DB.session.commit()

                # it is an error when
                #   form is sitewide, but submission came from a host rooted somewhere else, or
                #   form is not sitewide, and submission came from a different host
            elif (not form.sitewide and form.host != host) or (
                   form.sitewide and (
                     not host.startswith(form.host) and \
                     not remove_www(host).startswith(form.host)
                   )
                 ):
                g.log.info(
                    'Submission rejected. From a different host than confirmed.'
                )
                if request_wants_json():
                    return jsonerror(
                        403, {
                            'error':
                            "Submission from different host than confirmed",
                            'submitted': host,
                            'confirmed': form.host
                        })
                else:
                    return render_template(
                        'error.html',
                        title='Check form address',
                        text='This submission came from "%s" but the form was\
                                                 confirmed for address "%s"' %
                        (host, form.host)), 403
        else:
            # no form row found. it is an error.
            g.log.info('Submission rejected. No form found for this target.')
            if request_wants_json():
                return jsonerror(400, {'error': "Invalid email address"})
            else:
                return render_template('error.html',
                                       title='Check email address',
                                       text='Email address %s is not formatted correctly' \
                                            % str(email_or_string)), 400
    else:
        # in this case, it is a normal email
        email = email_or_string.lower()

        # get the form for this request
        form = Form.query.filter_by(hash=HASH(email, host)).first() \
               or Form(email, host) # or create it if it doesn't exists

        # Check if it has been assigned about using AJAX or not
        assign_ajax(form, request_wants_json())

        if form.disabled:
            g.log.info('submission rejected. Form is disabled.')
            if request_wants_json():
                return jsonerror(403, {'error': 'Form not active'})
            else:
                return render_template(
                    'error.html',
                    title='Form not active',
                    text=
                    'The owner of this form has disabled this form and it is no longer accepting submissions. Your submissions was not accepted'
                ), 403

    # If form exists and is confirmed, send email
    # otherwise send a confirmation email
    if form.confirmed:
        captcha_verified = verify_captcha(received_data, request)
        needs_captcha = not (request_wants_json() or captcha_verified
                             or settings.TESTING)

        # if form is upgraded check if captcha is disabled
        if form.upgraded:
            needs_captcha = needs_captcha and not form.captcha_disabled

        if needs_captcha:
            data_copy = received_data.copy()
            # Temporarily store hostname in redis while doing captcha
            nonce = temp_store_hostname(form.host, request.referrer)
            data_copy['_host_nonce'] = nonce
            action = urljoin(settings.API_ROOT, email_or_string)
            return render_template('forms/captcha.html',
                                   data=data_copy,
                                   sorted_keys=sorted_keys,
                                   action=action)

        status = form.send(received_data, sorted_keys, referrer)
    else:
        status = form.send_confirmation()

    # Respond to the request accordingly to the status code
    if status['code'] == Form.STATUS_EMAIL_SENT:
        if request_wants_json():
            return jsonify({'success': "email sent", 'next': status['next']})
        else:
            return redirect(status['next'], code=302)
    elif status['code'] == Form.STATUS_EMAIL_EMPTY:
        if request_wants_json():
            return jsonerror(400, {'error': "Can't send an empty form"})
        else:
            return render_template(
                'error.html',
                title='Can\'t send an empty form',
                text=
                u'<p>Make sure you have placed the <a href="http://www.w3schools.com/tags/att_input_name.asp" target="_blank"><code>"name"</code> attribute</a> in all your form elements. Also, to prevent empty form submissions, take a look at the <a href="http://www.w3schools.com/tags/att_input_required.asp" target="_blank"><code>"required"</code> property</a>.</p><p>This error also happens when you have an <code>"enctype"</code> attribute set in your <code>&lt;form&gt;</code>, so make sure you don\'t.</p><p><a href="{}">Return to form</a></p>'
                .format(referrer)), 400
    elif status['code'] == Form.STATUS_CONFIRMATION_SENT or \
         status['code'] == Form.STATUS_CONFIRMATION_DUPLICATED:

        if request_wants_json():
            return jsonify({'success': "confirmation email sent"})
        else:
            return render_template(
                'forms/confirmation_sent.html',
                email=email,
                host=host,
                resend=status['code'] == Form.STATUS_CONFIRMATION_DUPLICATED)
    elif status['code'] == Form.STATUS_OVERLIMIT:
        if request_wants_json():
            return jsonify({'error': "form over quota"})
        else:
            return render_template(
                'error.html',
                title='Form over quota',
                text=
                'It looks like this form is getting a lot of submissions and ran out of its quota. Try contacting this website through other means or try submitting again later.'
            ), 402

    elif status['code'] == Form.STATUS_REPLYTO_ERROR:
        if request_wants_json():
            return jsonerror(500, {
                'error':
                "_replyto or email field has not been sent correctly"
            })
        else:
            return render_template(
                'error.html',
                title='Invalid email address',
                text=
                u'You entered <span class="code">{address}</span>. That is an invalid email address. Please correct the form and try to submit again <a href="{back}">here</a>.<p style="font-size: small">This could also be a problem with the form. For example, there could be two fields with <span class="code">_replyto</span> or <span class="code">email</span> name attribute. If you suspect the form is broken, please contact the form owner and ask them to investigate</p>'
                ''.format(address=status['address'],
                          back=status['referrer'])), 400

    # error fallback -- shouldn't happen
    if request_wants_json():
        return jsonerror(500, {'error': "Unable to send email"})
    else:
        return render_template(
            'error.html',
            title='Unable to send email',
            text=
            u'Unable to send email. If you can, please send the link to your form and the error information to  <b>{email}</b>. And send them the following: <p><pre><code>{message}</code></pre></p>'
            .format(message=json.dumps(status),
                    email=settings.CONTACT_EMAIL)), 500
Пример #9
0
def send(email_or_string):
    '''
    Main endpoint, finds or creates the form row from the database,
    checks validity and state of the form and sends either form data
    or verification to email.
    '''

    if request.method == 'GET':
        if request_wants_json():
            return jsonerror(405, {'error': "Please submit POST request."})
        else:
            return render_template(
                'info.html',
                title='Form should POST',
                text=
                'Make sure your form has the <span class="code"><strong>method="POST"</strong></span> attribute'
            ), 405

    host = referrer_to_path(flask.request.referrer)
    if not host:
        if request_wants_json():
            return jsonerror(400, {'error': "Invalid \"Referrer\" header"})
        else:
            return render_template(
                'error.html',
                title='Unable to submit form',
                text=
                'Make sure your form is running on a proper server. For geeks: could not find the "Referrer" header.'
            ), 400

    if not IS_VALID_EMAIL(email_or_string):
        # in this case it can be a hashid identifying a
        # form generated from the dashboard
        hashid = email_or_string
        form = Form.get_with_hashid(hashid)

        if form:
            email = form.email

            if not form.host:
                # add the host to the form
                form.host = host
                DB.session.add(form)
                DB.session.commit()
            elif form.host != host:
                # if the form submission came from a different host, it is an error
                if request_wants_json():
                    return jsonerror(
                        403, {
                            'error':
                            "Submission from different host than confirmed",
                            'submitted': host,
                            'confirmed': form.host
                        })
                else:
                    return render_template(
                        'error.html',
                        title='Check form address',
                        text='This submission came from "%s" but the form was\
                                                 confirmed for the address "%s"'
                        % (host, form.host)), 403
        else:
            # no form row found. it is an error.
            if request_wants_json():
                return jsonerror(400, {'error': "Invalid email address"})
            else:
                return render_template('error.html',
                                       title='Check email address',
                                       text='Email address %s is not formatted correctly' \
                                            % str(email_or_string)), 400
    else:
        # in this case, it is a normal email
        email = email_or_string

        # get the form for this request
        form = Form.query.filter_by(hash=HASH(email, host)).first() \
               or Form(email, host) # or create it if it doesn't exists

    # If form exists and is confirmed, send email
    # otherwise send a confirmation email
    if form.confirmed:
        status = form.send(request.form, request.referrer)
    else:
        status = form.send_confirmation()

    # Respond to the request accordingly to the status code
    if status['code'] == Form.STATUS_EMAIL_SENT:
        if request_wants_json():
            return jsonify({'success': "email sent", 'next': status['next']})
        else:
            return redirect(status['next'], code=302)
    elif status['code'] == Form.STATUS_EMAIL_EMPTY:
        if request_wants_json():
            return jsonerror(400, {'error': "Can't send an empty form"})
        else:
            return render_template('error.html',
                                   title='Can\'t send an empty form',
                                   text=str('<a href="%s">Return to form</a>' %
                                            request.referrer)), 400
    elif status['code'] == Form.STATUS_CONFIRMATION_SENT or \
         status['code'] == Form.STATUS_CONFIRMATION_DUPLICATED:
        if request_wants_json():
            return jsonify({'success': "confirmation email sent"})
        else:
            return render_template('forms/confirmation_sent.html',
                                   email=email,
                                   host=host)

    if request_wants_json():
        return jsonerror(500, {'error': "Unable to send email"})
    else:
        return render_template('error.html',
                               title='Unable to send email',
                               text='Unable to send email'), 500
Пример #10
0
def send(email_or_string):
    '''
    Main endpoint, finds or creates the form row from the database,
    checks validity and state of the form and sends either form data
    or verification to email.
    '''

    if request.method == 'GET':
        if request_wants_json():
            return jsonerror(405, {'error': "Please submit POST request."})
        else:
            return render_template(
                'info.html',
                title='Form should POST',
                text=
                'Make sure your form has the <span class="code"><strong>method="POST"</strong></span> attribute'
            ), 405

    host = referrer_to_path(flask.request.referrer)
    if not host:
        if request_wants_json():
            return jsonerror(400, {'error': "Invalid \"Referrer\" header"})
        else:
            return render_template(
                'error.html',
                title='Unable to submit form',
                text=
                'Make sure you open this page through a web server, Formspree will not work in pages browsed as HTML files. For geeks: could not find the "Referrer" header.'
            ), 400

    if not IS_VALID_EMAIL(email_or_string):
        # in this case it can be a hashid identifying a
        # form generated from the dashboard
        hashid = email_or_string
        form = Form.get_with_hashid(hashid)

        if form:
            email = form.email

            if not form.host:
                # add the host to the form
                form.host = host
                DB.session.add(form)
                DB.session.commit()
            elif form.host != host:
                # if the form submission came from a different host, it is an error
                if request_wants_json():
                    return jsonerror(
                        403, {
                            'error':
                            "Submission from different host than confirmed",
                            'submitted': host,
                            'confirmed': form.host
                        })
                else:
                    return render_template(
                        'error.html',
                        title='Check form address',
                        text='This submission came from "%s" but the form was\
                                                 confirmed for the address "%s"'
                        % (host, form.host)), 403
        else:
            # no form row found. it is an error.
            if request_wants_json():
                return jsonerror(400, {'error': "Invalid email address"})
            else:
                return render_template('error.html',
                                       title='Check email address',
                                       text='Email address %s is not formatted correctly' \
                                            % str(email_or_string)), 400
    else:
        # in this case, it is a normal email
        email = email_or_string

        # get the form for this request
        form = Form.query.filter_by(hash=HASH(email, host)).first() \
               or Form(email, host) # or create it if it doesn't exists

    # If form exists and is confirmed, send email
    # otherwise send a confirmation email
    if form.confirmed:
        status = form.send(request.form, request.referrer)
    else:
        status = form.send_confirmation(with_data=request.form)

    # Respond to the request accordingly to the status code
    if status['code'] == Form.STATUS_EMAIL_SENT:
        if request_wants_json():
            return jsonify({'success': "email sent", 'next': status['next']})
        else:
            return redirect(status['next'], code=302)
    elif status['code'] == Form.STATUS_EMAIL_EMPTY:
        if request_wants_json():
            return jsonerror(400, {'error': "Can't send an empty form"})
        else:
            return render_template(
                'error.html',
                title='Can\'t send an empty form',
                text=str(
                    '<p>Make sure you have placed the <a href="http://www.w3schools.com/tags/att_input_name.asp" target="_blank">"name" attribute</a> in all your form elements. Also, to prevent empty form submissions, take a look at the <a href="http://www.w3schools.com/tags/att_input_required.asp" target="_blank">"required" property</a> or <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input" target="_blank">see more HTML form customization info</a>.</p><p><a href="%s">Return to form</a></p>'
                    % request.referrer)), 400
    elif status['code'] == Form.STATUS_CONFIRMATION_SENT or \
         status['code'] == Form.STATUS_CONFIRMATION_DUPLICATED:

        if request_wants_json():
            return jsonify({'success': "confirmation email sent"})
        else:
            return render_template(
                'forms/confirmation_sent.html',
                email=email,
                host=host,
                resend=status['code'] == Form.STATUS_CONFIRMATION_DUPLICATED)
    elif status['code'] == Form.STATUS_OVERLIMIT:

        if request_wants_json():
            return jsonify({'error': "form over quota"})
        else:
            return render_template(
                'error.html',
                title='Form over quota',
                text=
                'It looks like this form is getting a lot of submissions and ran out of its quota. Try contacting this website through other means or try submitting again later.'
            )

    elif status['code'] == Form.STATUS_REPLYTO_ERROR:
        if request_wants_json():
            return jsonerror(500, {
                'error':
                "_replyto or email field has not been sent correctly"
            })
        else:
            return render_template(
                'error.html',
                title='Unable to send email',
                text=
                'Unable to send email. The field with a name attribute _replyto or email was not set correctly. This may be the result of you have multiple _replyto or email fields. If you cannot find your error, please contact <b>[email protected]</b> with a link to your form and this error message: <p><pre><code>'
                + status['error-message'] + '</code></pre></p>'), 500

    # error fallback -- shouldn't happen
    if request_wants_json():
        return jsonerror(500, {'error': "Unable to send email"})
    else:
        return render_template(
            'error.html',
            title='Unable to send email',
            text=
            'Unable to send email. If you can, please send the link to your form and the error information to  <b>[email protected]</b>. And send them the following: <p><pre><code>'
            + json.dumps(status) + '</code></pre></p>'), 500
Пример #11
0
def resend_confirmation(email):
    # the first thing to do is to check the captcha
    r = requests.post('https://www.google.com/recaptcha/api/siteverify',
                      data={
                          'secret': settings.RECAPTCHA_SECRET,
                          'response': request.form['g-recaptcha-response'],
                          'remoteip': request.remote_addr
                      })
    if r.ok and r.json().get('success'):
        # then proceed to check for bounced addresses

        if request.form.get('bounce_problem_solved') == 'true':
            # delete bounce from SendGrid then proceed
            requests.delete('https://api.sendgrid.com/v3/suppression/bounces/',
                            auth=(settings.SENDGRID_USERNAME,
                                  settings.SENDGRID_PASSWORD),
                            data={'emails': [email]})
        else:
            # check if this email is listed on SendGrid's bounces
            r = requests.get(
                'https://api.sendgrid.com/v3/suppression/bounces/' + email,
                auth=(settings.SENDGRID_USERNAME, settings.SENDGRID_PASSWORD))
            if r.ok and len(r.json()) and 'reason' in r.json()[0]:
                # tell the user to verify his mailbox
                # and, at the same time, let him mark the checkbox that says he has already
                #      made his mailbox available in the next time he tries to resend
                #      confirmation.
                reason = r.json()[0]['reason']
                if request_wants_json():
                    resp = jsonify({
                        'error': "Verify your mailbox, we can't reach it.",
                        'reason': reason
                    })
                else:
                    resp = make_response(
                        render_template(
                            'info.html',
                            title='Verify the availability of your mailbox',
                            text=
                            "We encountered an error when trying to deliver the confirmation message to <b>"
                            + email +
                            "</b> at the first time we tried. For spam reasons, we will not try again until we are sure the problem is fixed. Here's the reason:</p><p><center><i>"
                            + reason +
                            "</i></center></p><p>Please make sure this problem is not happening still, then come here and try to resend your confirmation message again."
                        ))
                resp.set_cookie('has_been_notified_of_bounce',
                                'true',
                                max_age=345600)
                return resp
        # ~~~

        # if there's no bounce or the bounce problem has been solved, we proceed to resend
        # the confirmation.

        # I'm not sure if this should be available for forms created on the dashboard.
        form = Form.query.filter_by(
            hash=HASH(email, request.form['host'])).first()
        if not form:
            if request_wants_json():
                return jsonerror(400, {'error': "This form does not exists"})
            else:
                return render_template('error.html',
                                       title='Check email address',
                                       text='This form does not exists'), 400
        form.confirm_sent = False
        status = form.send_confirmation()
        if status['code'] == Form.STATUS_CONFIRMATION_SENT:
            if request_wants_json():
                return jsonify({'success': "confirmation email sent"})
            else:
                return render_template('forms/confirmation_sent.html',
                                       email=email,
                                       host=request.form['host'],
                                       resend=status['code'] ==
                                       Form.STATUS_CONFIRMATION_DUPLICATED)

    # fallback response -- should never happen
    if request_wants_json():
        return jsonerror(500, {'error': "Unable to send email"})
    else:
        return render_template('error.html',
                               title='Unable to send email',
                               text='Unable to send email'), 500
Пример #12
0
    def send_confirmation(self, store_data=None):
        '''
        Helper that actually creates confirmation nonce
        and sends the email to associated email. Renders
        different templates depending on the result
        '''

        g.log = g.log.new(form=self.id, to=self.email, host=self.host)
        g.log.debug('Confirmation.')
        if self.confirm_sent:
            g.log.debug('Previously sent.')
            return {'code': Form.STATUS_CONFIRMATION_DUPLICATED}

        # the nonce for email confirmation will be the hash when it exists
        # (whenever the form was created from a simple submission) or
        # a concatenation of HASH(email, id) + ':' + hashid
        # (whenever the form was created from the dashboard)
        id = str(self.id)
        nonce = self.hash or '%s:%s' % (HASH(self.email, id), self.hashid)
        link = url_for('confirm_email', nonce=nonce, _external=True)

        def render_content(ext):
            data, keys = None, None
            if store_data:
                if type(store_data) in (ImmutableMultiDict,
                                        ImmutableOrderedMultiDict):
                    data, _ = http_form_to_dict(store_data)
                    store_first_submission(nonce, data)
                else:
                    store_first_submission(nonce, store_data)

            return render_template('email/confirm.%s' % ext,
                                   email=self.email,
                                   host=self.host,
                                   nonce_link=link,
                                   keys=keys)

        DB.session.add(self)
        DB.session.flush()

        result = send_email(to=self.email,
                            subject='Confirm email for %s' %
                            settings.SERVICE_NAME,
                            text=render_content('txt'),
                            html=render_content('html'),
                            sender=settings.DEFAULT_SENDER,
                            headers={
                                'List-Unsubscribe-Post':
                                'List-Unsubscribe=One-Click',
                                'List-Unsubscribe':
                                '<' + url_for('unconfirm_form',
                                              form_id=self.id,
                                              digest=self.unconfirm_digest(),
                                              _external=True) + '>'
                            })
        g.log.debug('Confirmation email queued.')

        if not result[0]:
            return {'code': Form.STATUS_CONFIRMATION_FAILED}

        self.confirm_sent = True
        DB.session.add(self)
        DB.session.commit()

        return {'code': Form.STATUS_CONFIRMATION_SENT}