Exemple #1
0
    def post(self):
        try:
            jsondata = json.loads(self.request.body)
        except UnicodeDecodeError:
            jsondata = json.loads(self.request.body,encoding='latin-1')

        logging.info(jsondata.keys())

        form = Form()
        
        procfields = []
        for i,f in enumerate(jsondata['fields']):
            procfields.append({
                'name': 'field{}'.format(i),
                'Descr': f['Descr'],
                'Val': f['Val']
                })
        
        form.creator = jsondata['creator']
        form.until = datetime.datetime.now() + datetime.timedelta(hours=jsondata['duration'])
        form.hashtag = jsondata['hashtag']
        form.fields = procfields
        form.description = jsondata['description']
        form.authenticated = not bool(jsondata['authenticated']) 
        form.info = jsondata['info']

        form.put()
Exemple #2
0
def add_workout():
    body = request.get_json()
    if 'age' not in body:
        return 'please specify age', 400
    if 'user_id' not in body:
        return 'please specify user id', 400
    if 'height' not in body:
        return 'please specify height', 400
    if 'weight' not in body:
        return 'please specify weight', 400
    if 'dedication' not in body:
        return 'please specify dedication', 400
    if 'goal_id' not in body:
        return 'please specify goal id', 400
    form = Form(age=body['age'],
                user_id=body['user_id'],
                height=body['height'],
                weight=body['weight'],
                dedication=body['dedication'],
                goal_id=body['goal_id'])
    workout = Workout(age=body['age'],
                      user_id=body['user_id'],
                      height=body['height'],
                      weight=body['weight'],
                      dedication=body['dedication'],
                      goal_id=body['goal_id'])
    db.session.add(form)
    db.session.commit()
    return jsonify(form.serialize()), 200
Exemple #3
0
	def post(self):
		form = Form()
		self._update_form_from_request(form)
		
		form.put()
		
		logging.info("Created form '%s'" % form.key.urlsafe())
		
		self.redirect(self.uri_for('forms-list'))
Exemple #4
0
def New_form():
    if request.method == 'POST':
        nameF = request.form['form_name']
        nameA = request.form['area']
        print(nameF)
        print(nameA)
        #f = Form(name=request.form['form_name'],detail=request.form['area'])
        f = Form(name=request.form['form_name'],
                 detail=request.form['detail'],
                 estatus="I")
        db.session.add(f)
        db.session.commit()

        datos = request.form['area']
        print(datos)
        campos = datos.split(';')
        for campo in campos:
            info = campo.split(':')
            if len(info) > 1:
                listado = f.id
                camp = Field(form_id=f.id,
                             name=info[0].replace(' ', '_'),
                             tipe=info[1],
                             label=info[2],
                             detail=info[3].replace(' ', '_'))
                db.session.add(camp)
                db.session.commit()

        return redirect('/plantilla')
Exemple #5
0
def form_recaptcha_toggle(hashid):
    form = Form.get_with_hashid(hashid)

    if not valid_domain_request(request):
        return jsonify(
            error=
            'The request you made is not valid.<br />Please visit your dashboard and try again.'
        ), 400

    if form.owner_id != current_user.id and form not in current_user.forms:
        return jsonify(
            error=
            'You aren\'t the owner of that form.<br />Please log in as the form owner and try again.'
        ), 400

    if not form:
        return jsonify(
            error=
            'That form does not exist. Please check the link and try again.'
        ), 400
    else:
        form.captcha_disabled = not form.captcha_disabled
        DB.session.add(form)
        DB.session.commit()

        if form.captcha_disabled:
            return jsonify(disabled=True,
                           message='CAPTCHA successfully disabled')
        else:
            return jsonify(disabled=False,
                           message='CAPTCHA successfully enabled')
Exemple #6
0
def form_deletion():
    hashid = request.form.get('hashid')
    form = Form.get_with_hashid(hashid)

    # check that this request came from user dashboard to prevent XSS and CSRF
    referrer = referrer_to_baseurl(flask.request.referrer)
    service = referrer_to_baseurl(settings.SERVICE_URL)
    if referrer != service:
        return render_template('error.html',
                               title='Improper Request',
                               text='The request you made is not valid.<br />Please visit your dashboard and try again.'), 400

    if form.owner_id != current_user.id:
        if form not in current_user.forms: #accounts for bug when form isn't assigned owner_id bc it was not created from dashboard
            return render_template('error.html',
                                  title='Wrong user',
                                  text='You aren\'t the owner of that form.<br />Please log in as the form owner and try again.'), 400
    if not form:
            return render_template('error.html',
                                   title='Not a valid form',
                                   text='That form does not exist.<br />Please check the link and try again.'), 400
    else:
        for submission in form.submissions:
            DB.session.delete(submission)
        DB.session.delete(form)
        DB.session.commit()
        flash('Form successfully deleted', 'success')
        return redirect(url_for('dashboard'))
def form_toggle(hashid):
    form = Form.get_with_hashid(hashid)

    # check that this request came from user dashboard to prevent XSS and CSRF
    if not valid_domain_request(request):
        return render_template('error.html',
                               title='Improper Request',
                               text='The request you made is not valid.<br />Please visit your dashboard and try again.'), 400

    if form.owner_id != current_user.id:
        if form not in current_user.forms: #accounts for bug when form isn't assigned owner_id bc it was not created from dashboard
            return render_template('error.html',
                                  title='Wrong user',
                                  text='You aren\'t the owner of that form.<br />Please log in as the form owner and try again.'), 400
    if not form:
            return render_template('error.html',
                                   title='Not a valid form',
                                   text='That form does not exist.<br />Please check the link and try again.'), 400
    else:
        form.disabled = not form.disabled
        DB.session.add(form)
        DB.session.commit()
        if form.disabled:
            flash(u'Form successfully disabled', 'success')
        else:
            flash(u'Form successfully enabled', 'success')
        return redirect(url_for('dashboard'))
Exemple #8
0
def submission_deletion(hashid, submissionid):
    submission = Submission.query.get(submissionid)
    form = Form.get_with_hashid(hashid)

    # check that this request came from user dashboard to prevent XSS and CSRF
    referrer = referrer_to_baseurl(request.referrer)
    service = referrer_to_baseurl(settings.SERVICE_URL)
    if referrer != service:
        return render_template('error.html',
                               title='Improper Request',
                               text='The request you made is not valid.<br />Please visit your dashboard and try again.'), 400

    if form.owner_id != current_user.id:
        if form not in current_user.forms: #accounts for bug when form isn't assigned owner_id bc it was not created from dashboard
            return render_template('error.html',
                                  title='Wrong user',
                                  text='You aren\'t the owner of that form.<br />Please log in as the form owner and try again.' + str(form.id)), 400
    if not submission:
        return render_template('error.html',
                              title='Not a valid submission',
                              text='That submission does not exist.<br />Please check the link and try again.'), 400
    elif submission.form_id != form.id:
        return render_template('error.html',
                              title='Not a valid submissions',
                              text='That submission does not match the form provided.<br />Please check the link and try again.'), 400
    else:
        DB.session.delete(submission)
        form.counter -= 1
        DB.session.add(form)
        DB.session.commit()
        flash('Submission successfully deleted', 'success')
        return redirect(url_for('form-submissions', hashid=hashid))
def submission_deletion(hashid, submissionid):
    submission = Submission.query.get(submissionid)
    form = Form.get_with_hashid(hashid)

    # check that this request came from user dashboard to prevent XSS and CSRF
    referrer = referrer_to_baseurl(request.referrer)
    service = referrer_to_baseurl(settings.SERVICE_URL)
    if referrer != service:
        return render_template('error.html',
                               title='Improper Request',
                               text='The request you made is not valid.<br />Please visit your dashboard and try again.'), 400

    if form.owner_id != current_user.id:
        if form not in current_user.forms: #accounts for bug when form isn't assigned owner_id bc it was not created from dashboard
            return render_template('error.html',
                                  title='Wrong user',
                                  text='You aren\'t the owner of that form.<br />Please log in as the form owner and try again.' + str(form.id)), 400
    if not submission:
        return render_template('error.html',
                              title='Not a valid submission',
                              text='That submission does not exist.<br />Please check the link and try again.'), 400
    elif submission.form_id != form.id:
        return render_template('error.html',
                              title='Not a valid submissions',
                              text='That submission does not match the form provided.<br />Please check the link and try again.'), 400
    else:
        DB.session.delete(submission)
        form.counter -= 1
        DB.session.add(form)
        DB.session.commit()
        flash(u'Submission successfully deleted', 'success')
        return redirect(url_for('form-submissions', hashid=hashid))
Exemple #10
0
def form_submissions(random_like_string):
    if not current_user.upgraded:
        return jsonerror(402, {'error': "Please upgrade your account."})

    form = Form.get_form_by_random_like_string(random_like_string)
    submissions = form.submissions

    if request_wants_json():
        if current_user.id != form.owner_id:
            return jsonerror(403, {'error': "You're not the owner of this form."})

        return jsonify({
            'submissions': [s.data for s in submissions]
        })
    else:
        if current_user.id != form.owner_id:
            return redirect(url_for('dashboard'))

        fields = set()
        for s in submissions:
            fields.update(s.data.keys())
        fields -= set(EXCLUDE_KEYS)

        return render_template('forms/submissions.html',
            form=form,
            fields=sorted(fields),
            submissions=submissions
        )
Exemple #11
0
def form_submissions(hashid):
    if not current_user.upgraded:
        return jsonerror(402, {'error': "Please upgrade your account."})

    form = Form.get_with_hashid(hashid)

    if not form.controlled_by(current_user):
        if request_wants_json():
            return jsonerror(403, {'error': "You do not control this form."})
        else:
            return redirect(url_for('dashboard'))

    submissions = form.submissions

    if request_wants_json():
        return jsonify({'submissions': [s.data for s in submissions]})
    else:
        fields = set()
        for s in submissions:
            fields.update(s.data.keys())
        fields -= set(EXCLUDE_KEYS)

        return render_template('forms/submissions.html',
                               form=form,
                               fields=sorted(fields),
                               submissions=submissions)
Exemple #12
0
def form_submissions(hashid):
    if not current_user.upgraded:
        return jsonerror(402, {'error': "Please upgrade your account."})

    form = Form.get_with_hashid(hashid)

    if not form.controlled_by(current_user):
        if request_wants_json():
            return jsonerror(403, {'error': "You do not control this form."})
        else:
            return redirect(url_for('dashboard'))

    submissions = form.submissions

    if request_wants_json():
        return jsonify({
            'submissions': [s.data for s in submissions]
        })
    else:
        fields = set()
        for s in submissions:
            fields.update(s.data.keys())
        fields -= set(EXCLUDE_KEYS)

        return render_template('forms/submissions.html',
            form=form,
            fields=sorted(fields),
            submissions=submissions
        )
Exemple #13
0
def form_toggle(hashid):
    form = Form.get_with_hashid(hashid)

    # check that this request came from user dashboard to prevent XSS and CSRF
    referrer = referrer_to_baseurl(request.referrer)
    service = referrer_to_baseurl(settings.SERVICE_URL)
    if referrer != service:
        return render_template('error.html',
                               title='Improper Request',
                               text='The request you made is not valid.<br />Please visit your dashboard and try again.'), 400

    if form.owner_id != current_user.id:
        if form not in current_user.forms: #accounts for bug when form isn't assigned owner_id bc it was not created from dashboard
            return render_template('error.html',
                                  title='Wrong user',
                                  text='You aren\'t the owner of that form.<br />Please log in as the form owner and try again.'), 400
    if not form:
            return render_template('error.html',
                                   title='Not a valid form',
                                   text='That form does not exist.<br />Please check the link and try again.'), 400
    else:
        form.disabled = not form.disabled
        DB.session.add(form)
        DB.session.commit()
        if form.disabled:
            flash('Form successfully disabled', 'success')
        else:
            flash('Form successfully enabled', 'success')
        return redirect(url_for('dashboard'))
Exemple #14
0
def form_submissions(random_like_string):
    if not current_user.upgraded:
        return jsonerror(402, {'error': "Please upgrade your account."})

    form = Form.get_form_by_random_like_string(random_like_string)
    submissions = form.submissions

    if request_wants_json():
        if current_user.id != form.owner_id:
            return jsonerror(403,
                             {'error': "You're not the owner of this form."})

        return jsonify({'submissions': [s.data for s in submissions]})
    else:
        if current_user.id != form.owner_id:
            return redirect(url_for('dashboard'))

        fields = set()
        for s in submissions:
            fields.update(s.data.keys())
        fields -= set(EXCLUDE_KEYS)

        return render_template('forms/submissions.html',
                               form=form,
                               fields=sorted(fields),
                               submissions=submissions)
Exemple #15
0
def forms():
    if request.method == 'GET':
        if request_wants_json():
            return jsonerror(
                501, {
                    'error':
                    "This endpoint may return the list of forms for the logged user."
                })
        else:
            return redirect(url_for('dashboard'))

    # Create a new form
    if not current_user.upgraded:
        return jsonerror(402, {'error': "Please upgrade your account."})

    if request.get_json():
        email = request.get_json().get('email')
    else:
        email = request.form.get('email')

    if not IS_VALID_EMAIL(email):
        if request_wants_json():
            return jsonerror(
                400, {'error': "The email you sent is not a valid email."})
        else:
            flash('The email you sent is not a valid email.', 'error')
            return redirect(url_for('dashboard'))

    form = Form(email, owner=current_user)
    DB.session.add(form)
    DB.session.commit()

    # A unique identifier for the form that maps to its id,
    # but doesn't seem like a sequential integer
    random_like_string = form.get_random_like_string()

    if request_wants_json():
        return jsonify({
            'ok':
            True,
            'random_like_string':
            random_like_string,
            'submission_url':
            settings.API_ROOT + '/' + random_like_string
        })
    else:
        return redirect(url_for('dashboard'))
Exemple #16
0
def create():
    form = ContactForm()
    if form.validate() is False:
        return Response(status=400, mimetype='application/json')
    else:
        contact = Form()
        contact.name = form.name.data
        contact.email = form.email.data
        contact.subject = form.subject.data
        contact.message = form.message.data
        contact.postage_date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

        message_tpl = render_template('contact/message_template.html',
                                      contact=contact)

        db.session.add(contact)
        db.session.commit()
        send_mail("Mensagem recebida via página de Contato",
                  ["*****@*****.**"], message_tpl)

        message = gettext(
            "Your message has been sent successfully. We will soon get back to you."
        )

        return Response(message, status=200, mimetype='application/json')
Exemple #17
0
def create():
    form = ContactForm()
    if form.validate() is False:
        for error_type in form.errors:
            if form.errors[error_type][0] in dictionary():
                form.errors[error_type][0] = dictionary()[
                    form.errors[error_type][0]]
        return render_template('contact/index.html',
                               form=form,
                               action=url_for('contact.create'))
    else:
        contact = Form()
        contact.name = form.name.data
        contact.email = form.email.data
        contact.subject = form.subject.data
        contact.message = form.message.data
        contact.postage_date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

        message_tpl = render_template('contact/message_template.html',
                                      contact=contact)

        db.session.add(contact)
        db.session.commit()
        send_mail("Contato - DataViva", [admin_email], message_tpl)

        message = gettext(
            "Your message has been sent successfully. We will soon get back to you."
        )
        flash(message, 'success')

        return redirect(url_for('contact.create'))
Exemple #18
0
    def setup_forms(forms):
        form_types = open('{}/initial/form_types.txt'.format(dir_path),
                          'r').read().splitlines()
        for form_type_name in form_types:
            # print 'checked {}'.format(form_type_name)
            # check form type
            try:
                form_type = session.query(FormType) \
                    .filter(FormType.name == form_type_name) \
                    .one()
            # make new entry if not found
            except NoResultFound as e:
                data = open('{}/initial/forms/{}.json'.format(
                    dir_path, form_type_name)).read()
                form = json.loads(data)

                categories = []
                for category_id in form['category_ids']:
                    categories.append(session.query(Category) \
                                      .filter(Category.id == category_id) \
                                      .one()
                                      )

                form_type = FormType(name=form['name'],
                                     page_sequence=form['category_ids'],
                                     user_type_id=form['user_id'])
                form_type.categories = categories
                add(form_type)

                for category_id in form['category_ids']:
                    print '{} and {}'.format(form_type.id, category_id)

                    try:
                        session.query(form_category_association) \
                            .filter(form_category_association.c.form_types_id == form_type.id) \
                            .filter(form_category_association.c.categories_id == category_id) \
                            .one()
                    except:
                        add(
                            form_category_association(
                                form_type_id=form_type.id,
                                categories_id=category_id))

        for f in forms:
            try:
                session.query(Form) \
                    .filter(Form.name == f['name']) \
                    .one()
            except NoResultFound as e:
                add(
                    Form(name=f['name'],
                         date_start=f['date_start'],
                         date_end=f['date_end'],
                         form_type_id=f['form_type_id']))
Exemple #19
0
	def get(self):
		forms = Form.query().fetch(keys_only=True)		
		
		template_values = {
			'form_keys': map(lambda form: form.urlsafe(), forms)
		}
		
		html_template_path = os.path.join(templates_directory, 'admin_forms_list.html')
		html = template.render(html_template_path, template_values)
		
		self.response.write(html)
Exemple #20
0
def form(request, success_url='sent', template_name='contact_form.html'):

    notify = True
    contact_form = ContactForm()
    if request.method == 'POST':
        contact_form = ContactForm(request.POST, request.FILES)
        if contact_form.is_valid():
            new_form = {
                    'firstname': contact_form.cleaned_data['firstname'],
                    'lastname': contact_form.cleaned_data['lastname'],
                    'email': contact_form.cleaned_data['email'],
                    'pc': contact_form.cleaned_data['pc'],
                    'tipo': contact_form.cleaned_data['tipo'],
                    'caso': contact_form.cleaned_data['caso'],
                    }
            new_form = Form(**new_form)
            new_form.save(notify=notify)
            return HttpResponseRedirect(success_url)

    return render_to_response(template_name, RequestContext(request, {'form': contact_form}))
Exemple #21
0
def create():
    form = ContactForm()
    if form.validate() is False:
        for error_type in form.errors:
            if form.errors[error_type][0] in dictionary():
                form.errors[error_type][0] = dictionary()[form.errors[error_type][0]]
        return render_template('contact/index.html', form=form, action=url_for('contact.create'))
    else:
        contact = Form()
        contact.name = form.name.data
        contact.email = form.email.data
        contact.subject = form.subject.data
        contact.message = form.message.data
        contact.postage_date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

        message_tpl = render_template('contact/message_template.html', contact=contact)

        db.session.add(contact)
        db.session.commit()
        send_mail("Contato - DataViva", [admin_email], message_tpl)

        message = gettext("Your message has been sent successfully. We will soon get back to you.")
        flash(message, 'success')

        return redirect(url_for('contact.create'))
Exemple #22
0
 def get(self):
     formlist = []
     forms = Form.last()
     
     if forms:
         for form in forms:
             formlist.append(form.to_dict_key())
             
         self.response.headers['Content-Type'] = 'application/json'
         self.response.out.write(json.dumps(formlist))
         
     else:
         self.abort(404)
Exemple #23
0
 def get(self):
     if self.request.get('creator'):
         creator = self.request.get('creator')
         forms = Form.from_creator(creator)
     
         if forms:
             betslist = json.dumps([f.to_dict_key() for f in forms])
             self.response.headers['Content-Type'] = 'application/json'
             self.response.out.write(betslist)
         else:
             self.abort(404)
     else:
         self.abort(404)
Exemple #24
0
    def handle(self, sms):
        """Método chamado pelo RapidSMS para processar uma mensagem"""
        sub_type = Submission.TYPE_SMS  # estamos organizando as outras branchs do projeto
        answer = Config.get("message_unknown_format")

        if Submission.has_confirmation_pending(sms.connection.identity):
            submission = Submission.get_unconfirmed(sms.connection.identity)
            answer = submission.confirm(sms.text)
            return self.send_answer(sms, answer)

        if Form.main_form_exists():
            form = Form.get_main_form()

        else:
            keyword, separator, remaining_message = Form.extract_keyword(sms.text)
            sms.text = remaining_message
            form = Form.get_by_keyword_and_separator(keyword, separator)

        if form:
            answer = form.process_submission(sms, sub_type) or answer

        return self.send_answer(sms, answer)
Exemple #25
0
def forms():
    if request.method == 'GET':
        if request_wants_json():
            return jsonerror(501, {'error': "This endpoint may return the list of forms for the logged user."})
        else:
            return redirect(url_for('dashboard'))

    # Create a new form
    if not current_user.upgraded:
        return jsonerror(402, {'error': "Please upgrade your account."})

    if request.get_json():
        email = request.get_json().get('email')
    else:
        email = request.form.get('email')

    if not IS_VALID_EMAIL(email):
        if request_wants_json():
            return jsonerror(400, {'error': "The email you sent is not a valid email."})
        else:
            flash('The email you sent is not a valid email.', 'error')
            return redirect(url_for('dashboard'))

    form = Form(email, owner=current_user)
    DB.session.add(form)
    DB.session.commit()

    # A unique identifier for the form that maps to its id,
    # but doesn't seem like a sequential integer
    random_like_string = form.get_random_like_string()

    if request_wants_json():
        return jsonify({
            'ok': True,
            'random_like_string': random_like_string,
            'submission_url': settings.API_ROOT + '/' + random_like_string
        })
    else:
        return redirect(url_for('dashboard'))
Exemple #26
0
def form(username):
    """user submit feedback route"""
    if "username" not in session or username != session['username']:
        raise Unauthorized()

    form = AddEntryForm()

    if form.validate_on_submit():
        date = form.date.data
        therapist = form.therapist.data
        nrs1 = form.nrs1.data
        nrs2 = form.nrs2.data
        nrs3 = form.nrs3.data
        nrs4 = form.nrs4.data
        nrs5 = form.nrs5.data
        a_event = form.a_event.data
        beliefs = form.beliefs.data
        c_distortions = ', '.join(
            [str(distortion) for distortion in form.c_distortions.data])
        c_consequences = ', '.join(
            [str(consequence) for consequence in form.c_consequences.data])
        reactions = form.reactions.data
        is_at_risk = False

        if nrs1 <= 35 or nrs2 <= 35 or nrs3 <= 35 or nrs5 < 35:
            is_at_risk = True

        entry = Form(username=username,
                     therapist=therapist.username,
                     date=date,
                     nrs1=nrs1,
                     nrs2=nrs2,
                     nrs3=nrs3,
                     nrs4=nrs4,
                     nrs5=nrs5,
                     a_event=a_event,
                     beliefs=beliefs,
                     c_distortions=c_distortions,
                     c_consequences=c_consequences,
                     reactions=reactions,
                     is_at_risk=is_at_risk)

        db.session.add(entry)
        db.session.commit()

        return redirect(f"/users/{username}")

    else:
        return render_template("form/newJournal.html", form=form)
Exemple #27
0
def form_recaptcha_toggle(hashid):
    form = Form.get_with_hashid(hashid)
    valid_check = check_valid_form_settings_request(form)
    if valid_check != True:
        return valid_check

    checked_status = request.json['checked']
    form.captcha_disabled = not checked_status
    DB.session.add(form)
    DB.session.commit()

    if form.captcha_disabled:
        return jsonify(disabled=True, message='CAPTCHA successfully disabled')
    else:
        return jsonify(disabled=False, message='CAPTCHA successfully enabled')
Exemple #28
0
def confirm_email(nonce):
    '''
    Confirmation emails point to this endpoint
    It either rejects the confirmation or
    flags associated email+host to be confirmed
    '''

    # get the form for this request
    form = Form.confirm(nonce)

    if not form:
        return render_template('error.html',
                               title='Not a valid link',
                               text='Confirmation token not found.<br />Please check the link and try again.'), 400

    else:
        return render_template('forms/email_confirmed.html', email=form.email, host=form.host)
Exemple #29
0
def form_archive_toggle(hashid):
    form = Form.get_with_hashid(hashid)
    valid_check = check_valid_form_settings_request(form)
    if valid_check != True:
        return valid_check

    checked_status = request.json['checked']
    form.disable_storage = not checked_status
    DB.session.add(form)
    DB.session.commit()

    if form.disable_storage:
        return jsonify(disabled=True,
                       message='Submission archive successfully disabled')
    else:
        return jsonify(disabled=False,
                       message='Submission archive successfully enabled')
Exemple #30
0
def form_email_notification_toggle(hashid):
    form = Form.get_with_hashid(hashid)
    valid_check = check_valid_form_settings_request(form)
    if valid_check != True:
        return valid_check

    checked_status = request.json['checked']
    form.disable_email = not checked_status
    DB.session.add(form)
    DB.session.commit()

    if form.disable_email:
        return jsonify(disabled=True,
                       message='Email notifications successfully disabled')
    else:
        return jsonify(disabled=False,
                       message='Email notifications successfully enabled')
Exemple #31
0
def confirm_email(nonce):
    '''
    Confirmation emails point to this endpoint
    It either rejects the confirmation or
    flags associated email+host to be confirmed
    '''

    # get the form for this request
    form = Form.confirm(nonce)

    if not form:
        return render_template('error.html',
                               title='Not a valid link',
                               text='Confirmation token not found.<br />Please check the link and try again.'), 400

    else:
        return render_template('forms/email_confirmed.html', email=form.email, host=form.host)
Exemple #32
0
def form_recaptcha_toggle(hashid):
    form = Form.get_with_hashid(hashid)

    if not valid_domain_request(request):
        return jsonify(error='The request you made is not valid.<br />Please visit your dashboard and try again.'), 400

    if form.owner_id != current_user.id and form not in current_user.forms:
        return jsonify(error='You aren\'t the owner of that form.<br />Please log in as the form owner and try again.'), 400

    if not form:
        return jsonify(error='That form does not exist. Please check the link and try again.'), 400
    else:
        form.captcha_disabled = not form.captcha_disabled
        DB.session.add(form)
        DB.session.commit()

        if form.captcha_disabled:
            return jsonify(disabled=True, message='CAPTCHA successfully disabled')
        else:
            return jsonify(disabled=False, message='CAPTCHA successfully enabled')
Exemple #33
0
def admin(request):
    user = users.get_current_user()
    if not (user and users.is_current_user_admin()):
        return HttpResponseRedirect(users.create_login_url('/admin'))

    if request.method == 'POST' and request.POST['id'] and request.POST['action']:
        id = request.POST['id']
        action = int(request.POST['action'])
        model = Form.get(id)

        model.status = action
        model.put()

    pending = []
    accepted = []
    rejected = []
    
    for x in db.GqlQuery("SELECT * FROM poznanopen_form"):
        { 1:pending, 2: accepted, 3: rejected }[x.status].append(x)

    return render_to_response('admin.html', {'page': 'admin', 'pending': pending, 'accepted': accepted, 'rejected': rejected})
Exemple #34
0
def create():
    form = ContactForm()
    if form.validate() is False:
        return Response(status=400, mimetype='application/json')
    else:
        contact = Form()
        contact.name = form.name.data
        contact.email = form.email.data
        contact.subject = form.subject.data
        contact.message = form.message.data
        contact.postage_date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

        message_tpl = render_template(
            'contact/message_template.html', contact=contact)

        db.session.add(contact)
        db.session.commit()
        send_mail("Mensagem recebida via página de Contato",
                  ["*****@*****.**"], message_tpl)

        message = gettext(
            "Your message has been sent successfully. We will soon get back to you.")

        return Response(message, status=200, mimetype='application/json')
Exemple #35
0
db_session.add(tyler)


def random_date():
    start = datetime.date(2017, 1, 1)
    end = datetime.date(2017, 11, 11)
    delta = end - start
    int_delta = (delta.days * 24 * 60 * 60) + delta.seconds
    random_second = randrange(int_delta)
    return start + timedelta(seconds=random_second)


# Forms
form1 = Form(anonymous=True,
             statement='Example statement',
             created_by=peter,
             created_at=random_date(),
             against=roy)
form2 = Form(anonymous=True,
             statement='Example statement',
             created_by=roy,
             created_at=random_date(),
             against=peter)
form3 = Form(anonymous=True,
             statement='Example statement',
             created_by=tracy,
             created_at=random_date(),
             against=roy)
form4 = Form(anonymous=True,
             statement='Example statement',
             created_by=addison,
Exemple #36
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
Exemple #37
0
def registration(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            model = Form()
            model.fullname = data['fullname']
            model.wcaid = data['wcaid']
            model.country = data['country']
            model.city = data['city']
            model.email = data['email']
            model.tshirt = data['tshirt']
            model.nick = data['nick']
            model.accomodation = data['accomodation']
            model.born = datetime.date(int(data['bornyear']), int(data['bornmonth']), int(data['bornday']))
            model.events = [str(ev) for ev in data if ev.startswith('ev_') and data[ev] == True]
            model.status = 1
            model.put()

            return HttpResponseRedirect('/thanks')
    else:
        form = RegistrationForm()

    return render_to_response('registration.html', {
        'form': form,
        'page': 'registration',
        'years': range(1900, 2009),
        'months': range(1, 13),
        'days': range(1, 32),
        })
Exemple #38
0
def add_card_form_pagodigital(request):
    ########  Metodo POST  ########
    if request.method == 'POST':
        data = request.POST
        template = 'pagodigital/redirect.html'

        # Verifico las key mandatorias
        keys = [
            'name', 'phone', 'address', 'id_card', 'email', 'city', 'state',
            'cc_number', 'cc_exp_month', 'cc_exp_year', 'cc_cvv',
            'cc_fr_number', 'cc_fr_name', 'user_id', 'token'
        ]

        json_loader = __validate_json(data, keys)
        if json_loader['status'] == 'error':
            return HttpResponse(json.dumps(json_loader),
                                content_type='application/json',
                                status=http_BAD_REQUEST)

        # Obtengo el usuario y el form vinculado al token
        user = User.get(data['user_id'])
        form = Form.get(user, data['token'])
        if form is None:
            message = 'form not available'
            body = {'status': 'error', 'message': message}
            return HttpResponse(json.dumps(body),
                                content_type='application/json',
                                status=http_BAD_REQUEST)

        # Obtengo settings del integrator
        api_key = IntegratorSetting.get_var(form.integrator, 'api_key')
        api_secret = IntegratorSetting.get_var(form.integrator, 'api_secret')
        redirect_url = IntegratorSetting.get_var(form.integrator,
                                                 'redirect_url_add_card')
        jwt_endpoint = IntegratorSetting.get_var(form.integrator,
                                                 'jwt_endpoint')
        jwt_user = IntegratorSetting.get_var(form.integrator, 'jwt_user')
        jwt_pass = IntegratorSetting.get_var(form.integrator, 'jwt_pass')

        # Obtengo el JWT
        pd_jwt_gw = PagoDigitalJWTGateway(jwt_endpoint, jwt_user, jwt_pass)
        try:
            ret, content = pd_jwt_gw.doPost()
            if not ret:
                context = {'redirect_url': redirect_url}
                return render(request, template, context)
            if not 'TOKEN' in content:
                context = {'redirect_url': redirect_url}
                return render(request, template, context)
            pd_jwt = content['TOKEN']
        except Exception as e:
            context = {'redirect_url': redirect_url}
            return render(request, template, context)

        # Realizar add card y obtener token
        pd_ac_endpoint = IntegratorSetting.get_var(form.integrator,
                                                   'add_card_endpoint')
        pd_gw = PagoDigitalGateway(pd_ac_endpoint, api_key, api_secret, pd_jwt)
        pd_card = PagoDigitalCard(data['cc_number'], data['cc_cvv'],
                                  data['cc_fr_number'], data['cc_exp_month'],
                                  data['cc_exp_year'], data['name'],
                                  data['id_card'], data['address'],
                                  data['email'], data['phone'], data['city'],
                                  data['state'])
        try:
            ret, content = pd_gw.doPost(pd_card.to_dict())
            if not ret:
                context = {'redirect_url': redirect_url}
                return render(request, template, context)
            if 'CODIGO_RESPUESTA' in content:
                if str(content['CODIGO_RESPUESTA']) not in SUCCESS_CODES:
                    context = {'redirect_url': redirect_url}
                    return render(request, template, context)
            else:
                context = {'redirect_url': redirect_url}
                return render(request, template, context)
        except Exception as e:
            context = {'redirect_url': redirect_url}
            return render(request, template, context)

        # Deshabilito cualquier tarjeta existente
        cards = Card.objects.filter(user=user, enabled=True)
        for card in cards:
            card.disable()

        # Creo la tarjeta o la obtengo si ya existe
        card = Card.get_by_token(user, content['TOKEN'])
        if card is not None:
            card.enable()
        else:
            card_exp = "%s/%s" % (data['cc_exp_month'],
                                  data['cc_exp_year'][-2:])
            card = Card.create_with_token(user, content['TOKEN'],
                                          data['cc_number'][-4:], card_exp,
                                          data['cc_fr_name'], form.integrator)

        context = {'redirect_url': redirect_url}
        return render(request, template, context)
Exemple #39
0
def create_form():
    # create a new form

    if not current_user.upgraded:
        g.log.info('Failed to create form from dashboard. User is not upgraded.')
        return jsonerror(402, {'error': "Please upgrade your account."})

    if request.get_json():
        email = request.get_json().get('email')
        url = request.get_json().get('url')
        sitewide = request.get_json().get('sitewide')
    else:
        email = request.form.get('email')
        url = request.form.get('url')
        sitewide = request.form.get('sitewide')

    g.log = g.log.bind(email=email, url=url, sitewide=sitewide)

    if not IS_VALID_EMAIL(email):
        g.log.info('Failed to create form from dashboard. Invalid address.')
        if request_wants_json():
            return jsonerror(400, {'error': "The provided email address is not valid."})
        else:
            flash('The provided email address is not valid.', 'error')
            return redirect(url_for('dashboard'))

    g.log.info('Creating a new form from the dashboard.')

    email = email.lower() # case-insensitive
    form = Form(email, owner=current_user)
    if url:
        url = 'http://' + url if not url.startswith('http') else url
        form.host = referrer_to_path(url)

        # sitewide forms, verified with a file at the root of the target domain
        if sitewide:
            if sitewide_file_check(url, email):
                form.host = remove_www(referrer_to_path(urljoin(url, '/'))[:-1])
                form.sitewide = True
            else:
                return jsonerror(403, {'error': "Couldn't verify the file at %s." % url})

    DB.session.add(form)
    DB.session.commit()

    if form.host:
        # when the email and url are provided, we can automatically confirm the form
        # but only if the email is registered for this account
        for email in current_user.emails:
            if email.address == form.email:
                g.log.info('No need for email confirmation.')
                form.confirmed = True
                DB.session.add(form)
                DB.session.commit()
                break
        else:
            # in case the email isn't registered for this user
            # we automatically send the email confirmation
            form.send_confirmation()

    if request_wants_json():
        return jsonify({
            'ok': True,
            'hashid': form.hashid,
            'submission_url': settings.API_ROOT + '/' + form.hashid,
            'confirmed': form.confirmed
        })
    else:
        flash('Your new form endpoint was created!', 'success')
        return redirect(url_for('dashboard', new=form.hashid) + '#form-' + form.hashid)
Exemple #40
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
Exemple #41
0
def form_submissions(hashid, format=None):
    if not current_user.upgraded:
        return jsonerror(402, {'error': "Please upgrade your account."})

    form = Form.get_with_hashid(hashid)

    for cont in form.controllers:
        if cont.id == current_user.id: break
    else:
        if request_wants_json():
            return jsonerror(403, {'error': "You do not control this form."})
        else:
            return redirect(url_for('dashboard'))

    submissions = form.submissions

    if not format:
        # normal request.
        if request_wants_json():
            return jsonify({
                'host':
                form.host,
                'email':
                form.email,
                'submissions': [
                    dict(s.data, date=s.submitted_at.isoformat())
                    for s in submissions
                ]
            })
        else:
            fields = set()
            for s in submissions:
                fields.update(s.data.keys())
            fields -= EXCLUDE_KEYS

            return render_template('forms/submissions.html',
                                   form=form,
                                   fields=sorted(fields),
                                   submissions=submissions)
    elif format:
        # an export request, format can be json or csv
        if format == 'json':
            return Response(
                json.dumps({
                    'host': form.host,
                    'email': form.email,
                    'submissions': [dict(s.data, date=s.submitted_at.isoformat()) for s in submissions]
                }, sort_keys=True, indent=2),
                mimetype='application/json',
                headers={
                    'Content-Disposition': 'attachment; filename=form-%s-submissions-%s.json' \
                                % (hashid, datetime.datetime.now().isoformat().split('.')[0])
                }
            )
        elif format == 'csv':
            out = io.BytesIO()
            fieldnames = set(field for sub in submissions
                             for field in sub.data.keys())
            fieldnames = ['date'] + sorted(fieldnames)

            w = csv.DictWriter(out, fieldnames=fieldnames, encoding='utf-8')
            w.writeheader()
            for sub in submissions:
                w.writerow(dict(sub.data, date=sub.submitted_at.isoformat()))

            return Response(
                out.getvalue(),
                mimetype='text/csv',
                headers={
                    'Content-Disposition': 'attachment; filename=form-%s-submissions-%s.csv' \
                                % (hashid, datetime.datetime.now().isoformat().split('.')[0])
                }
            )
Exemple #42
0
def forms():
    if request.method == 'GET':
        '''
        A reminder: this is the /forms endpoint, but for GET requests
        it is also the /dashboard endpoint.

        The /dashboard endpoint, the address gave by url_for('dashboard'),
        is the target of a lot of redirects around the app, but it can
        be changed later to point to somewhere else.
        '''

        # grab all the forms this user controls
        if current_user.upgraded:
            forms = current_user.forms.order_by(Form.id.desc()).all()
        else:
            forms = []

        if request_wants_json():
            return jsonify({
                'ok':
                True,
                'forms': [{
                    'email':
                    f.email,
                    'host':
                    f.host,
                    'confirm_sent':
                    f.confirm_sent,
                    'confirmed':
                    f.confirmed,
                    'is_public':
                    bool(f.hash),
                    'url':
                    '{S}/{E}'.format(S=settings.SERVICE_URL, E=f.hashid)
                } for f in forms]
            })
        else:
            return render_template('forms/list.html', forms=forms)

    elif request.method == 'POST':
        # create a new form
        if not current_user.upgraded:
            return jsonerror(402, {'error': "Please upgrade your account."})

        if request.get_json():
            email = request.get_json().get('email')
        else:
            email = request.form.get('email')

        if not IS_VALID_EMAIL(email):
            if request_wants_json():
                return jsonerror(
                    400, {'error': "The email you sent is not a valid email."})
            else:
                flash('The email you provided is not a valid email.', 'error')
                return redirect(url_for('dashboard'))

        form = Form(email, owner=current_user)
        DB.session.add(form)
        DB.session.commit()

        if request_wants_json():
            return jsonify({
                'ok':
                True,
                'hashid':
                form.hashid,
                'submission_url':
                settings.API_ROOT + '/' + form.hashid
            })
        else:
            flash('Your new form endpoint was created!', 'success')
            return redirect(url_for('dashboard') + '#view-code-' + form.hashid)
Exemple #43
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.'
            )

    # 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 report this immediately to <b>[email protected]</b>. And send them the following: <p><pre><code>' + json.dumps(status) + '</code></pre></p>'), 500
Exemple #44
0
 def save(self):
     form = Form(name=self.cleaned_data['name'])
     form.catalog = Catalog.get(self.cleaned_data['catalog'])
     return form
Exemple #45
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
Exemple #46
0
def payment_pagodigital(request):
    # Vars
    integrator = Integrator.get('pagodigital')
    baseurl = Setting.get_var('baseurl')
    template = 'pagodigital/pagodigital.html'

    # Verifico ApiKey
    cap = __check_apikey(request)
    if cap['status'] == 'error':
        return HttpResponse(status=http_UNAUTHORIZED)

    # Cargo el JSON
    try:
        data = json.loads(request.body)
        print "CONTENT MA: %s" % data
    except Exception:
        message = 'error decoding json'
        body = {'status': 'error', 'message': message}
        return HttpResponse(json.dumps(body),
                            content_type='application/json',
                            status=http_BAD_REQUEST)

    # Verifico las key mandatorias
    keys = ['user_id', 'email', 'payment_date', 'recurrence']
    json_loader = __validate_json(data, keys)

    if json_loader['status'] == 'error':
        return HttpResponse(json.dumps(json_loader),
                            content_type='application/json',
                            status=http_BAD_REQUEST)

    # Verifico si el usuario existe y sino lo creo
    try:
        user = User.objects.get(user_id=data['user_id'])
        user.email = data['email']
        user.save()
    except ObjectDoesNotExist:
        user = User.create(data['user_id'], data['email'], integrator.country)

    # Verifico que no tenga un User Payment activo
    up = UserPayment.get_active(user)
    if up is not None:
        if up.enabled_card:
            message = 'enabled user payment already exists'
            body = {'status': 'error', 'message': message}
            return HttpResponse(json.dumps(body),
                                content_type='application/json',
                                status=http_BAD_REQUEST)
        else:
            up.status = 'PE'
            up.save()

    # Obtengo el paquete
    if 'package_id' in data:
        package = Package.get_by_id(data['package_id'], integrator)
    else:
        package = Package.get(data['recurrence'], integrator)

    if package is None:
        message = "package not found with that duration"
        body = {'status': 'error', 'message': message}
        return HttpResponse(json.dumps(body),
                            content_type="application/json",
                            status=http_BAD_REQUEST)

    # Creo UserPayment
    up = UserPayment.create_from_package(user, package, data['payment_date'],
                                         0, 0, True)

    # Aplico descuento si existe
    if 'discount' in data and 'disc_counter' in data:
        up.discount(data['discount'], data['disc_counter'])

    # Creo el form
    form = Form.create(user, up, integrator, template, 'UP', package)
    if form is None:
        message = "form could not be created"
        body = {'status': 'error', 'message': message}
        return HttpResponse(json.dumps(body),
                            content_type="application/json",
                            status=http_INTERNAL_ERROR)

    iframe_params = {'user_id': user.user_id, 'token': form.token}
    iframe_url = '%sapi/v1/pagodigital/userpayment/form/?%s' % (
        baseurl, urlencode(iframe_params))
    body = {'status': 'success', 'value': {'url': iframe_url}}

    return HttpResponse(json.dumps(body),
                        content_type="application/json",
                        status=http_POST_OK)
Exemple #47
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
    except ValueError as err:
        g.log.error('Invalid hostname stored on Redis.', err=err)
        return render_template(
            'error.html',
            title='Unable to submit form',
            text='<p>We had a problem identifying to whom we should have submitted this form. Please try submitting again. If it fails once more, please let us know at {email}</p>'.format(
                email=settings.CONTACT_EMAIL,
            )
        ), 500

    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('Submitted.')
    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 not sitewide, and submission came from a different host
                #   form is sitewide, but submission came from a host rooted somewhere else, or
            elif (not form.sitewide and
                  # ending slashes can be safely ignored here:
                  form.host.rstrip('/') != host.rstrip('/')) or \
                 (form.sitewide and \
                  # removing www from both sides makes this a neutral operation:
                  not remove_www(host).startswith(remove_www(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)
            try:
                if '_language' in received_data:
                    return render_template('forms/captcha_lang/{}.html'.format(received_data['_language']),
                                data=data_copy,
                                sorted_keys=sorted_keys,
                                action=action,
                                lang=received_data['_language'])
            except TemplateNotFound:
                g.log.error('Requested language not found for reCAPTCHA page, defaulting to English', referrer=request.referrer, lang=received_data['_language'])
                pass

            return render_template('forms/captcha.html',
                                           data=data_copy,
                                           sorted_keys=sorted_keys,
                                           action=action,
                                           lang=None)

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

    # 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
Exemple #48
0
                    if not entry.part_of_speech:
                        # TODO: Don't yield entries we don't understand
                        continue

                    lemma = Lemma.create(**entry.to_dict(),
                                         frequency=frequencies.get(entry.name)
                                         or 0)
                    translations = [
                        Translation(**translation, lemma=lemma)
                        for translation in entry.translations
                    ]

                    declensions = d.get_declensions(entry.name)
                    forms = [
                        Form(**declension, lemma=lemma)
                        for declension in declensions
                    ]

                    with sqldb.atomic():
                        if forms:
                            Form.bulk_create(forms)

                        if translations:
                            Translation.bulk_create(translations)

                    count += 1
                except Exception as exc:
                    print(exc)
                    failures.append(entry.name)
Exemple #49
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
Exemple #50
0
def add_card_pagodigital(request):
    # Vars
    integrator = Integrator.get('pagodigital')
    baseurl = Setting.get_var('baseurl')
    template = 'pagodigital/pagodigital.html'

    # Verifico ApiKey
    cap = __check_apikey(request)
    if cap['status'] == 'error':
        return HttpResponse(status=http_UNAUTHORIZED)

    # Cargo el JSON
    try:
        data = json.loads(request.body)
    except Exception:
        message = 'error decoding json'
        body = {'status': 'error', 'message': message}
        return HttpResponse(json.dumps(body),
                            content_type='application/json',
                            status=http_BAD_REQUEST)

    # Verifico las key mandatorias
    keys = ['user_id']
    json_loader = __validate_json(data, keys)

    if json_loader['status'] == 'error':
        return HttpResponse(json.dumps(json_loader),
                            content_type='application/json',
                            status=http_BAD_REQUEST)

    # Verifico si el usuario existe y sino devuelvo error
    try:
        user = User.objects.get(user_id=data['user_id'])
    except ObjectDoesNotExist:
        message = 'user does not exist'
        body = {'status': 'error', 'message': message}
        return HttpResponse(json.dumps(body),
                            content_type='application/json',
                            status=http_BAD_REQUEST)

    # Obtengo el User Payment activo sino devuelvo error
    up = UserPayment.get_active(user)
    if up is None:
        message = 'enabled user payment does not exist'
        body = {'status': 'error', 'message': message}
        return HttpResponse(json.dumps(body),
                            content_type='application/json',
                            status=http_BAD_REQUEST)

    # Creo el form
    form = Form.create(user, up, integrator, template, 'AC')
    if form is None:
        message = "form could not be created"
        body = {'status': 'error', 'message': message}
        return HttpResponse(json.dumps(body),
                            content_type="application/json",
                            status=http_INTERNAL_ERROR)

    iframe_params = {'user_id': user.user_id, 'token': form.token}
    iframe_url = '%sapi/v1/pagodigital/addcard/form/?%s' % (
        baseurl, urlencode(iframe_params))
    body = {'status': 'success', 'value': {'url': iframe_url}}

    return HttpResponse(json.dumps(body),
                        content_type="application/json",
                        status=http_POST_OK)
Exemple #51
0
def form_submissions(hashid, format=None):
    if not current_user.upgraded:
        return jsonerror(402, {'error': "Please upgrade your account."})

    form = Form.get_with_hashid(hashid)

    for cont in form.controllers:
        if cont.id == current_user.id: break
    else:
        if request_wants_json():
            return jsonerror(403, {'error': "You do not control this form."})
        else:
            return redirect(url_for('dashboard'))

    submissions = form.submissions

    if not format:
        # normal request.
        if request_wants_json():
            return jsonify({
                'host': form.host,
                'email': form.email,
                'submissions': [dict(s.data, date=s.submitted_at.isoformat()) for s in submissions]
            })
        else:
            fields = set()
            for s in submissions:
                fields.update(s.data.keys())
            fields -= set(EXCLUDE_KEYS)

            return render_template('forms/submissions.html',
                form=form,
                fields=sorted(fields),
                submissions=submissions
            )
    elif format:
        # an export request, format can be json or csv
        if format == 'json':
            return Response(
                json.dumps({
                    'host': form.host,
                    'email': form.email,
                    'submissions': [dict(s.data, date=s.submitted_at.isoformat()) for s in submissions]
                }, sort_keys=True, indent=2),
                mimetype='application/json',
                headers={
                    'Content-Disposition': 'attachment; filename=form-%s-submissions-%s.json' \
                                % (hashid, datetime.datetime.now().isoformat().split('.')[0])
                }
            )
        elif format == 'csv':
            out = io.BytesIO()
            fieldnames = set(field for sub in submissions for field in sub.data.keys())
            fieldnames = ['date'] + sorted(fieldnames)
            
            w = csv.DictWriter(out, fieldnames=fieldnames, encoding='utf-8')
            w.writeheader()
            for sub in submissions:
                w.writerow(dict(sub.data, date=sub.submitted_at.isoformat()))

            return Response(
                out.getvalue(),
                mimetype='text/csv',
                headers={
                    'Content-Disposition': 'attachment; filename=form-%s-submissions-%s.csv' \
                                % (hashid, datetime.datetime.now().isoformat().split('.')[0])
                }
            )
Exemple #52
0
    def post(self, *args, **kwargs):
        form_dict = simplejson.loads(self.request.POST['form'])
        form = Form.get_by_name(kwargs['name'])
        form.update_from_dict(form_dict)

        return http.HttpResponse(_(u'Form updated with success'))
Exemple #53
0
def create_form():
    # create a new form

    if not current_user.upgraded:
        g.log.info(
            'Failed to create form from dashboard. User is not upgraded.')
        return jsonerror(402, {'error': "Please upgrade your account."})

    if request.get_json():
        email = request.get_json().get('email')
        url = request.get_json().get('url')
        sitewide = request.get_json().get('sitewide')
    else:
        email = request.form.get('email')
        url = request.form.get('url')
        sitewide = request.form.get('sitewide')

    g.log = g.log.bind(email=email, url=url, sitewide=sitewide)

    if not IS_VALID_EMAIL(email):
        g.log.info('Failed to create form from dashboard. Invalid address.')
        if request_wants_json():
            return jsonerror(
                400, {'error': "The provided email address is not valid."})
        else:
            flash(u'The provided email address is not valid.', 'error')
            return redirect(url_for('dashboard'))

    g.log.info('Creating a new form from the dashboard.')

    email = email.lower()  # case-insensitive
    form = Form(email, owner=current_user)
    if url:
        url = 'http://' + url if not url.startswith('http') else url
        form.host = referrer_to_path(url)

        # sitewide forms, verified with a file at the root of the target domain
        if sitewide:
            if sitewide_file_check(url, email):
                form.host = remove_www(
                    referrer_to_path(urljoin(url, '/'))[:-1])
                form.sitewide = True
            else:
                return jsonerror(
                    403,
                    {'error': u"Couldn't verify the file at {}.".format(url)})

    DB.session.add(form)
    DB.session.commit()

    if form.host:
        # when the email and url are provided, we can automatically confirm the form
        # but only if the email is registered for this account
        for email in current_user.emails:
            if email.address == form.email:
                g.log.info('No need for email confirmation.')
                form.confirmed = True
                DB.session.add(form)
                DB.session.commit()
                break
        else:
            # in case the email isn't registered for this user
            # we automatically send the email confirmation
            form.send_confirmation()

    if request_wants_json():
        return jsonify({
            'ok': True,
            'hashid': form.hashid,
            'submission_url': settings.API_ROOT + '/' + form.hashid,
            'confirmed': form.confirmed
        })
    else:
        flash(u'Your new form endpoint was created!', 'success')
        return redirect(
            url_for('dashboard', new=form.hashid) + '#form-' + form.hashid)
Exemple #54
0
 def get_context_data(self, *args, **kwargs):
     return {
         'KIND_CHOICES': Field.KIND_CHOICES,
         'form': Form.get_by_name(kwargs['name']),
     }
Exemple #55
0
def userpayment_form_pagodigital(request):
    ########  Metodo POST  ########
    if request.method == 'POST':
        data = request.POST
        template = 'pagodigital/redirect.html'

        # Verifico las key mandatorias
        keys = [
            'name', 'phone', 'address', 'id_card', 'email', 'city', 'state',
            'cc_number', 'cc_exp_month', 'cc_exp_year', 'cc_cvv',
            'cc_fr_number', 'cc_fr_name', 'user_id', 'token'
        ]

        json_loader = __validate_json(data, keys)
        if json_loader['status'] == 'error':
            return HttpResponse(json.dumps(json_loader),
                                content_type='application/json',
                                status=http_BAD_REQUEST)

        # Obtengo el usuario y el form vinculado al token
        user = User.get(data['user_id'])
        form = Form.get(user, data['token'])
        if form is None:
            message = 'form not available'
            body = {'status': 'error', 'message': message}
            return HttpResponse(json.dumps(body),
                                content_type='application/json',
                                status=http_BAD_REQUEST)

        # Verifico que no tenga un User Payment activo
        active_up = UserPayment.get_active(user)
        if active_up is not None:
            message = 'enabled user payment already exists'
            body = {'status': 'error', 'message': message}
            return HttpResponse(json.dumps(body),
                                content_type='application/json',
                                status=http_BAD_REQUEST)

        up = form.user_payment

        # Obtengo settings del integrator
        api_key = IntegratorSetting.get_var(form.integrator, 'api_key')
        api_secret = IntegratorSetting.get_var(form.integrator, 'api_secret')
        success_url = IntegratorSetting.get_var(form.integrator,
                                                'redirect_url_success')
        failed_url = IntegratorSetting.get_var(form.integrator,
                                               'redirect_url_failed')
        jwt_endpoint = IntegratorSetting.get_var(form.integrator,
                                                 'jwt_endpoint')
        jwt_user = IntegratorSetting.get_var(form.integrator, 'jwt_user')
        jwt_pass = IntegratorSetting.get_var(form.integrator, 'jwt_pass')

        # Obtengo el JWT
        pd_jwt_gw = PagoDigitalJWTGateway(jwt_endpoint, jwt_user, jwt_pass)
        try:
            ret, content = pd_jwt_gw.doPost()
            if not ret:
                message = "%s - %s" % (content['STATUS_MESSAGE'],
                                       content['MESSAGE'])
                up.reply_error(message)
                context = {'redirect_url': failed_url}
                return render(request, template, context)
            if not 'TOKEN' in content:
                message = "JWT ERROR - TOKEN key not found"
                up.reply_error(message)
                context = {'redirect_url': failed_url}
                return render(request, template, context)
            pd_jwt = content['TOKEN']
        except Exception as e:
            message = 'jwt error: %s' % e
            up.reply_error(message)
            context = {'redirect_url': failed_url}
            return render(request, template, context)

        # Realizar add card y obtener token
        pd_ac_endpoint = IntegratorSetting.get_var(form.integrator,
                                                   'add_card_endpoint')
        pd_gw = PagoDigitalGateway(pd_ac_endpoint, api_key, api_secret, pd_jwt)
        pd_card = PagoDigitalCard(data['cc_number'], data['cc_cvv'],
                                  data['cc_fr_number'], data['cc_exp_month'],
                                  data['cc_exp_year'], data['name'],
                                  data['id_card'], data['address'],
                                  data['email'], data['phone'], data['city'],
                                  data['state'])
        new_card = True
        try:
            ret, content = pd_gw.doPost(pd_card.to_dict())
            if not ret:
                message = "%s - %s" % (content['STATUS_MESSAGE'],
                                       content['MESSAGE'])
                up.reply_error(message)
                context = {'redirect_url': failed_url}
                return render(request, template, context)
            if 'CODIGO_RESPUESTA' in content:
                if str(content['CODIGO_RESPUESTA']) not in SUCCESS_CODES:
                    message = "ADD CARD ERROR - code: %s - message: %s" % (
                        content['CODIGO_RESPUESTA'], content['RESPUESTA'])
                    up.reply_error(message)
                    context = {'redirect_url': failed_url}
                    return render(request, template, context)
            elif 'CODIGO_ERROR' in content and content[
                    'CODIGO_ERROR'] == 'PD38':
                if 'TOKEN' not in content:
                    message = "ADD CARD ERROR - CODIGO_ERROR PD38 but TOKEN not returned"
                    up.reply_error(message)
                    context = {'redirect_url': failed_url}
                    return render(request, template, context)
                new_card = False
            else:
                message = "ADD CARD ERROR - CODIGO_RESPUESTA not found"
                up.reply_error(message)
                context = {'redirect_url': failed_url}
                return render(request, template, context)
        except Exception as e:
            message = 'add card error: %s' % e
            up.reply_error(message)
            context = {'redirect_url': failed_url}
            return render(request, template, context)

        # Habilito tarjeta en UP
        up.enabled_card = True

        # Deshabilito cualquier tarjeta existente
        cards = Card.objects.filter(user=user, enabled=True)
        for card in cards:
            card.disable()

        # Creo la tarjeta o la obtengo si ya existe
        card = Card.get_by_token(up.user, content['TOKEN'])
        if card is not None:
            card.enable()
        elif new_card:
            card_exp = "%s/%s" % (data['cc_exp_month'],
                                  data['cc_exp_year'][-2:])
            card = Card.create_with_token(user, content['TOKEN'],
                                          data['cc_number'][-4:], card_exp,
                                          data['cc_fr_name'], form.integrator)
        else:
            up.enabled_card = False
            message = 'add card error: Token %s not found' % content['TOKEN']
            up.reply_error(message)
            context = {'redirect_url': failed_url}
            return render(request, template, context)

        # Verifico si es trial y aplico descuento si corresponde
        if up.is_trial:
            trial_flag = True
            disc_flag = False
            disc_pct = 0
        else:
            trial_flag = False
            if up.has_discount:
                disc_flag = True
                disc_pct = up.disc_pct
            else:
                disc_pct = 0
                disc_flag = False

        # Genero tx id sumando al userid el timestamp
        payment_id = "PH_%s_%d" % (user.user_id, int(time()))

        # Creo el registro en PaymentHistory
        ph = PaymentHistory.create(up, payment_id, form.integrator, card,
                                   disc_pct)

        if ph.amount > 0:
            # Realizar pago
            pd_tx_endpoint = IntegratorSetting.get_var(form.integrator,
                                                       'process_tx_endpoint')
            pd_gw = PagoDigitalGateway(pd_tx_endpoint, api_key, api_secret,
                                       pd_jwt)
            try:
                pd_tx = PagoDigitalTx(int(ph.amount), card.token)
                ret, content = pd_gw.doPost(pd_tx.to_dict())
                print ret
                print content
            except Exception as e:
                message = 'Payment error: %s' % e
                up.reply_error(message)
                ph.error('', message)
                return False
        else:
            ret = True
            content = {
                'CODIGO_RESPUESTA': '-10',
                'id': '-10',
                'message': 'Pago con descuento del 100%'
            }

        if ret:
            # Obtengo los valores segun la respuesta de Pagodigital
            pr = pagodigital_translator(content)

            # Seteo los valores de la UserPayment
            up.status = pr["up_status"]
            up.message = pr["up_message"]
            up.enabled = pr["up_recurrence"]

            if up.status == 'AC':
                # calcular next_payment_day
                up.payment_date = up.calc_payment_date()
                # Fija la fecha de expiration del usuario
                user.set_expiration(up.payment_date)
                if disc_flag:
                    up.disc_counter -= 1
                if trial_flag:
                    up.trial_counter -= 1
            else:
                up.channel = 'R'
            up.save()

            # Seteo los valores del PaymentHistory
            ph.status = pr["ph_status"]
            ph.gateway_id = pr["ph_gatewayid"]
            ph.message = pr["ph_message"]
            ph.save()

            if ph.status == 'A':
                redirect_url = success_url
            else:
                redirect_url = failed_url

            if pr["user_expire"]:
                user.expire()

            # POST to promiscuus
            if ph.trial:
                ph.trial_duration = up.trial_recurrence
            else:
                ph.trial_duration = 0
            resp_promiscuus = post_to_promiscuus(ph, 'payment_commit')
            if resp_promiscuus['status'] == 'error':
                ph.message = "%s - Promiscuus error: %s" % (
                    ph.message, resp_promiscuus['message'])
                ph.save()

            context = {'redirect_url': redirect_url}
            return render(request, template, context)

        else:
            message = "could not create user payment"
            up.reply_error(message)
            ph.error('', message)

            # POST to promiscuus
            if ph.trial:
                ph.trial_duration = up.trial_recurrence
            else:
                ph.trial_duration = 0
            resp_promiscuus = post_to_promiscuus(ph, 'payment_commit')
            if resp_promiscuus['status'] == 'error':
                ph.message = "%s - Promiscuus error: %s" % (
                    ph.message, resp_promiscuus['message'])
                ph.save()

            context = {'redirect_url': failed_url}
            return render(request, template, context)

    ########  Metodo GET  ########
    elif request.method == 'GET':
        user = User.get(request.GET['user_id'])
        template = Form.get_template(user, request.GET['token'])
        baseurl = Setting.get_var('baseurl')

        if template is None:
            message = 'form not available'
            body = {'status': 'error', 'message': message}
            return HttpResponse(json.dumps(body),
                                content_type='application/json',
                                status=http_BAD_REQUEST)

        context = {
            'country': user.country.code,
            'email': user.email,
            'baseurl': baseurl
        }
        return render(request, template, context)
Exemple #56
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

    host = referrer_to_path(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='<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>https://</b>{host}.</p><p>For geeks: could not find the "Referrer" header.</p>'.format(host=request.url.split('//')[1])), 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:
            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
        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
    received_data = request.form or request.get_json() or {}
    if form.confirmed:
        status = form.send(received_data, request.referrer)
    else:
        status = form.send_confirmation(received_data)

    # 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.'), 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='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='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