Esempio n. 1
0
def donate():
    form = DonateForm(request.form)

    if not form.validate_on_submit():
        flash_errors(form)
        return render_template("donate.html", form=form)

    stripe.api_key = current_app.config["STRIPE_KEY_SECRET"]

    token = form.stripe_token.data
    amount = int(form.amount.data * 100)

    if amount > 25000:
        flash("You can't donate that much using this form!", "error")
        return redirect(url_for(".donate_failed"))

    try:
        donation = Donation.create(amount=amount, first_name=form.first_name.data, last_name=form.last_name.data,
                                   street_address=form.street_address.data, city=form.city.data, state=form.state.data,
                                   postal_code=form.postal_code.data, email=form.email.data, phone=form.phone.data,
                                   occupation=form.occupation.data, employer=form.employer.data)
        stripe.Charge.create(amount=amount, currency="usd", source=token, description="Teens for Teens donation id {}".format(donation.id))
        donation.stripe_success = True
        donation.save()
        return redirect(url_for(".thanks"))
    except stripe.error.CardError:
        flash("Your card was declined :(", "error")
        return redirect(url_for(".donate_failed"))
Esempio n. 2
0
    def post(self):
        context = self.get_context()
        form = context.get('login_user_form')

        if form.validate():
            try:
                user = User.objects.get(email=form.email.data)
            except DoesNotExist:
                user = User(email=form.email.data)

            if 'X-Forwarded-For' in request.headers:
                remote_addr = request.headers.getlist("X-Forwarded-For")[0].rpartition(' ')[-1]
            else:
                remote_addr = request.remote_addr or 'untrackable'

            old_current_login, new_current_login = user.current_login_at, datetime.utcnow()
            old_current_ip, new_current_ip = user.current_login_ip, remote_addr

            user.last_login_at = old_current_login or new_current_login
            user.current_login_at = new_current_login
            user.last_login_ip = old_current_ip or new_current_ip
            user.current_login_ip = new_current_ip
            user.login_count = user.login_count + 1 if user.login_count else 1

            user.save()
            login_user(user)
            flash("Logged in user")
            return redirect(url_for('pages.home'))
            
        else:
            flash_errors(form)

        return render_template('home.html', **context)
Esempio n. 3
0
def create_account():
    form = AccountCreateForm(request.form)

    if not form.validate_on_submit():
        flash_errors(form)
        return render_template("account/create.html", form=form)

    matching_accounts = Account.select().where(Account.email == form.email.data)
    if matching_accounts.count() > 0:
        flash("An account already exists with that email address.", "error")
        return render_template("account/create.html", form=form)

    if current_app.config['SEND_EMAIL']:
        email_confirmed = False
        email_confirm_key = send_confirm_email(form.first_name.data, form.email.data)
        flash("Account created. Please confirm your email; you should receive information on how to do this shortly.", "info")
    else:
        email_confirmed = True
        email_confirm_key = None
        flash("Account created.", "info")

    password = Account.hash_password(form.password.data)

    account = Account.create(first_name=form.first_name.data, last_name=form.last_name.data,
                             street_address=form.street_address.data, city=form.city.data,
                             state=form.state.data, postal_code=form.postal_code.data,
                             email=form.email.data, email_confirm_key=email_confirm_key,
                             email_confirmed=email_confirmed, password=password, dob=form.dob.data)

    attach_volunteer(account)

    return redirect(url_for('account.login'))
Esempio n. 4
0
def register():
    form = RegisterForm(request.form)
    if request.method == 'POST':
        user = User(username=form.username.data, email=form.email.data)
        query_validate_username = session.query(User).filter_by(username=form.username.data).first()
        query_validate_email = session.query(User).filter_by(email=form.email.data).first()
        if query_validate_username is not None or query_validate_email is not None:
            uri_parameters = 'invalid'
            flash('That dates in use')
            return redirect(url_for('login', error=uri_parameters))
        user.hash_password(form.password.data)
        session.add(user)
        session.commit()
        print request.files
        if 'profile_photo' in request.files:
            filename = profile_photo.save(request.files['profile_photo'])
            newprofilephoto = ProfileImage(user_id=user.id,
                                           image_filename=filename,
                                           image_url='static/img/profile/'+filename)
            session.add(newprofilephoto)
            session.commit()
        flash('User successfully registered')
    else:
        flash_errors(form)
        return redirect(url_for('users.login'))

    return redirect(url_for('users.login'))
Esempio n. 5
0
def donate():
    form = DonateForm(request.form)

    if not form.validate_on_submit():
        flash_errors(form)
        return render_template("donations/donate.html", form=form, states=states)

    stripe.api_key = current_app.config["STRIPE_KEY_SECRET"]

    token = form.stripe_token.data
    amount = int(form.amount.data * 100)

    if(request.form.get('recurring') == "false"):
        recurring_donation = False
    else:
        recurring_donation = True

    try:
        donation = Donation.create(amount=amount, first_name=form.first_name.data, last_name=form.last_name.data,
                                   street_address=form.street_address.data, city=form.city.data, state=form.state.data,
                                   postal_code=form.postal_code.data, email=form.email.data, occupation=form.occupation.data, 
                                   employer=form.employer.data, recurring=recurring_donation, agreed=form.agreed.data)
        if not donation.recurring:
            stripe.Charge.create(amount=amount, receipt_email=form.email.data, currency="usd", source=token, description="Unified Democracy Donation #{}".format(donation.id))
        else:
            plan = stripe.Plan.create(id=donation.id, amount=amount, currency='USD', interval='month', name="Unified Democracy Recurring Donation #{} - {} {} ".format(donation.id, form.first_name.data, form.last_name.data))
            customer = stripe.Customer.create(email=form.email.data, source=token, description="Unified Democracy Recurring Donation #{} - {} {} ".format(donation.id, form.first_name.data, form.last_name.data), plan=plan.id)
        donation.stripe_success = True
        donation.save()
        send_receipt_email(donation)
        return redirect(url_for(".thanks"))
    except stripe.error.CardError:
        flash("Your card was declined :(", "error")
        return redirect(url_for(".donate_failed"))
Esempio n. 6
0
def register():
    form = RegistrationForm()

    if request.method == "GET":
        return render_template("register.html", form=form)
    elif request.method == "POST":
        if form.validate_on_submit():
            user = User()
            form.populate_obj(user)
            # overwrite the old password with a bcrypt-hash
            user.password = hash_password(user.password)
            try:
                user.save()
                app.logger.info("New user registered")
                flash("User registered successfully", "success")
            except IntegrityError as err:
                app.logger.warning("Could not register user: {0}".format(err))
                flash("User could not be registered, please try again", "error")
            except OperationalError as err:
                app.logger.warning("MySQL Error: {0!s}".format(err))
                flash("{0!s}".format(err))

            return redirect(url_for("show_index"))
        else:
            flash_errors(form)
        return render_template("register.html", form=form)
Esempio n. 7
0
def create_request():
    form = RequestForm(request.form)
    if request.method == 'POST' and form.validate():
        geolocation = getGeocodeLocation(form.location_string.data)
        newrequest = Request(user_id=login_session['id'],
                          meal_type=form.meal_type.data,
                          location_string=form.location_string.data,
                          latitude=geolocation[0],
                          longitude=geolocation[1])
        session.add(newrequest)
        session.commit()
        date_request = parse_datetime(year=form.year.data, month=form.month.data, day=form.day.data)
        if date_request == None:
            flash('Date no valid...')
            return redirect(url_for('users.index'))
        newrequestdate = DateTimeRequest(
                            request=newrequest.id,
                            mealtime=form.meal_time.data,
                            date=date_request)
        session.add(newrequestdate)
        session.commit()
        flash('Succefully!')
        return redirect(url_for('users.index'))
    flash_errors(form)
    return redirect(url_for('users.index'))
Esempio n. 8
0
def show_state_page(state_code):
    try:
        state = State.get(State.code**state_code)
        positions = state.positions.order_by(StatePosition.role.desc())[1:]
        events = state.events.order_by(Event.date.desc())
        return render_template("states/state_base.html",
                               state=state,
                               positions=positions,
                               events=events)
    except State.DoesNotExist:
        form = ApplyStateForm(request.form)
        if not form.validate_on_submit():
            flash_errors(form)
            return render_template("states/apply.html", form=form)
        message = render_template("states/apply_email.html", form=form)
        send_email(
            current_app.config["EMAIL_FROM"],
            '*****@*****.**',
            'State Director Application - {}'.format(
                current_app.config.get("APP_NAME",
                                       "Unified Democracy")), message)
        send_email(
            current_app.config["EMAIL_FROM"],
            '*****@*****.**',
            'State Director Application - {}'.format(
                current_app.config.get("APP_NAME",
                                       "Unified Democracy")), message)
        flash("Application Successful", "success")
        return redirect(url_for("staticpages.show_staticpage", page="index"))
Esempio n. 9
0
def reset_password(key):
    form = AccountPasswordSetForm(request.form)

    if not form.validate_on_submit():
        flash_errors(form)
        return render_template("account/reset.html", form=form)

    try:
        reset = PasswordReset.get(key=key)
    except PasswordReset.DoesNotExist:
        flash("Invalid password reset key.", "error")
        return redirect(url_for("account.request_reset"))

    if reset.used:
        flash("Password reset key already used.", "error")
        return redirect(url_for("account.request_reset"))

    if reset.created_at - datetime.now() > timedelta(seconds=3600):
        flash("Password reset expired.", "error")
        return redirect(url_for("account.request_reset"))

    reset.account.password = Account.hash_password(form.password.data)
    reset.account.save()

    reset.used = True
    reset.save()

    flash("Password set.", "info")
    return redirect(url_for("account.login"))
Esempio n. 10
0
def reset_password(key):
    form = AccountPasswordSetForm(request.form)

    if not form.validate_on_submit():
        flash_errors(form)
        return render_template("account/reset.html", form=form)

    try:
        reset = PasswordReset.get(key=key)
    except PasswordReset.DoesNotExist:
        flash("Invalid password reset key.", "error")
        return redirect(url_for("account.request_reset"))

    if reset.used:
        flash("Password reset key already used.", "error")
        return redirect(url_for("account.request_reset"))

    if reset.created_at - datetime.now() > timedelta(seconds=3600):
        flash("Password reset expired.", "error")
        return redirect(url_for("account.request_reset"))

    reset.account.password = Account.hash_password(form.password.data)
    reset.account.save()

    reset.used = True
    reset.save()

    flash("Password set.", "info")
    return redirect(url_for("account.login"))
Esempio n. 11
0
def upload_avatar():
    form = UploadAvatarForm()
    if form.validate_on_submit():
        image = form.image.data
        filename = avatars.save_avatar(image)
        current_user.avatar_raw = filename
        db.session.commit()
        flash('Image uploaded, please crop.', 'success')
    flash_errors(form)
    return redirect(url_for('.change_avatar'))
Esempio n. 12
0
def Add_a_new_PO():
    form = forms.PurchaseOrderForm(flask.request.form)
    if flask.request.method == 'POST':
        if form.validate():
            data = flask.request.form
            utils.add_po(data, connection)
            connection.commit()
            utils.flash_message("PO added!", category='success')
        else:
            utils.flash_errors(form)

    return flask.render_template('add.html', form=form)
Esempio n. 13
0
def upload_avatar():
    form = UploadAvatarForm()
    if form.validate_on_submit():
        image = form.image.data
        filename = avatars.save_avatar(image)
        stu_pic = Student.query.filter_by(id=current_user.id).first()
        stu_pic.pic = filename
        #db.session.add(stu_pic)
        db.session.commit()
        flash('Image uploaded, please crop.', 'success')
    flash_errors(form)
    return redirect(url_for('.setting'))
Esempio n. 14
0
def login():
    # ..
    form = LoginForm(request.form)
    if request.method == 'POST':
        if form.validate_on_submit():
            login_user(form.user)
            redirect_url = request.args.get('next') or url_for('admin.index')
            return redirect(redirect_url)
        else:
            flash_errors(form)
    # ..
    return render_template('accounts/login.html', form=form)
Esempio n. 15
0
def Update_a_PO():
    form = forms.UpdatePurchaseOrderForm(flask.request.form)
    if flask.request.method == 'POST':
        if form.validate():
            data = flask.request.form
            cursor = connection.cursor()
            cursor.execute(queries.update_po(data))
            connection.commit()
            utils.flash_message("PO updated!", category='success')
        else:
            utils.flash_errors(form)

    return flask.render_template('update.html', form=form)
Esempio n. 16
0
 def add(self):
     form = self.object_form()
     self._form = form
     print "self.choices_handler:", self.choices_handler
     self._fetch_choices(form)
     if form.validate_on_submit():
         self.model_create(**form.data)
         flash(u'Ajout réussi de l\'objet {}'.format(self.object_name), 'success')
         return redirect(url_for('.{}:list'.format(self.object_title)))
     if request.method == 'POST':
         current_app.logger.warning(form.errors)
         flash_errors(form)
     return render_template('generic/add.html', form=form,
         sectname=self.section_name, objname=self.object_name, action='Ajout')
Esempio n. 17
0
def home():
    """Home page."""
    form = LoginForm(request.form)
    current_app.logger.info("Hello from the home page!")
    # Handle logging in
    if request.method == "POST":
        if form.validate_on_submit():
            login_user(form.user)
            flash("You are logged in.", "success")
            redirect_url = request.args.get("next") or url_for("user.members")
            return redirect(redirect_url)
        else:
            flash_errors(form)
    return render_template("public/home.html", form=form)
Esempio n. 18
0
    def post(self):
        context = self.get_context()
        form = context.get('form')

        if form.validate():
            try:
                user = User.objects.get(email=form.email.data)
                flash('User exists')
            except DoesNotExist:
                flash('User does not exist')

        else:
            flash_errors(form)

        return render_template('home.html', **context)
Esempio n. 19
0
def register():
    """Register new user."""
    form = RegisterForm(request.form)
    if form.validate_on_submit():
        User.create(
            username=form.username.data,
            email=form.email.data,
            password=form.password.data,
            active=True,
        )
        flash("Thank you for registering. You can now log in.", "success")
        return redirect(url_for("public.home"))
    else:
        flash_errors(form)
    return render_template("public/register.html", form=form)
Esempio n. 20
0
def crop_avatar():
    form = CropAvatarForm()
    if form.validate_on_submit():
        x = form.x.data
        y = form.y.data
        w = form.w.data
        h = form.h.data
        filenames = avatars.crop_avatar(current_user.avatar_raw, x, y, w, h)
        current_user.avatar_s = filenames[0]
        current_user.avatar_m = filenames[1]
        current_user.avatar_l = filenames[2]
        db.session.commit()
        flash('Avatar updated.', 'success')
    flash_errors(form)
    return redirect(url_for('.change_avatar'))
Esempio n. 21
0
def request_reset():
    form = AccountPasswordResetForm()

    if not form.validate_on_submit():
        flash_errors(form)
        return render_template("account/request_reset.html", form=form)

    try:
        account = Account.get(email=form.email.data)
        send_reset_email(account)
        flash("Password reset link sent.", "info")
    except Account.DoesNotExist:
        flash("No account was found with that email address.", "error")

    return render_template("account/request_reset.html", form=form)
Esempio n. 22
0
def request_reset():
    form = AccountPasswordResetForm()

    if not form.validate_on_submit():
        flash_errors(form)
        return render_template("account/request_reset.html", form=form)

    try:
        account = Account.get(email=form.email.data)
        send_reset_email(account)
        flash("Password reset link sent.", "info")
    except Account.DoesNotExist:
        flash("No account was found with that email address.", "error")

    return render_template("account/request_reset.html", form=form)
Esempio n. 23
0
def show_state_page(state_code):
    try:
        state = State.get(State.code ** state_code)
        positions = state.positions.order_by(StatePosition.role.desc())[1:]
        events = state.events.order_by(Event.date.desc())
        return render_template("states/state_base.html", state=state, positions=positions, events=events)
    except State.DoesNotExist:
        form = ApplyStateForm(request.form)
        if not form.validate_on_submit():
            flash_errors(form)
            return render_template("states/apply.html", form=form)
        message = render_template("states/apply_email.html", form=form)
        send_email(current_app.config["EMAIL_FROM"], '*****@*****.**', 'State Director Application - {}'.format(current_app.config.get("APP_NAME", "Unified Democracy")), message)
        send_email(current_app.config["EMAIL_FROM"], '*****@*****.**', 'State Director Application - {}'.format(current_app.config.get("APP_NAME", "Unified Democracy")), message)
        flash("Application Successful", "success")
        return redirect(url_for("staticpages.show_staticpage", page="index"))
Esempio n. 24
0
def crop_avatar():
    form = CropAvatarForm()
    if form.validate_on_submit():
        x = form.x.data
        y = form.y.data
        w = form.w.data
        h = form.h.data
        stu_pic = Student.query.filter_by(id=current_user.id).first()
        filenames = avatars.crop_avatar(stu_pic.pic, x, y, w, h)
        stu_pic.pic_s = filenames[0]
        stu_pic.pic_m = filenames[1]
        stu_pic.pic_l = filenames[2]
        #db.session.add(stu_pic)
        db.session.commit()
        flash('Avatar updated.', 'success')
    flash_errors(form)
    return redirect(url_for('.setting'))
Esempio n. 25
0
def login():
    form = AccountLoginForm(request.form)

    if not form.validate_on_submit():
        flash_errors(form)
        return render_template("login.html", form=form)

    matching_accounts = Account.select().where(Account.email == form.email.data)
    if matching_accounts.count() == 1:
        account = next(matching_accounts.iterator())
        if account.validate_password(form.password.data):
            session["uid"] = account.id
            session["logged_in"] = True
            return redirect(request.args.get('next', url_for('account.info')))

    flash("Login failed.", "error")
    return render_template("login.html", form=form)
Esempio n. 26
0
def set_dob():
    if "dob_uid" not in session:
        return redirect(url_for("account.login"))

    form = AccountDobSetForm(request.form)

    if not form.validate_on_submit():
        flash_errors(form)
        return render_template("account/dob.html", form=form)

    account = Account.get(id=session["dob_uid"])
    account.dob = form.dob.data
    account.save()

    session["uid"] = session.pop("dob_uid")
    session["logged_in"] = True

    return redirect(url_for("account.info"))
Esempio n. 27
0
def set_dob():
    if "dob_uid" not in session:
        return redirect(url_for("account.login"))

    form = AccountDobSetForm(request.form)

    if not form.validate_on_submit():
        flash_errors(form)
        return render_template("account/dob.html", form=form)

    account = Account.get(id=session["dob_uid"])
    account.dob = form.dob.data
    account.save()

    session["uid"] = session.pop("dob_uid")
    session["logged_in"] = True

    return redirect(url_for("account.info"))
Esempio n. 28
0
def confirm_email(key):
    form = ListConfirmSubscribeForm(request.form)

    if not form.validate_on_submit():
        flash_errors(form)
        return render_template("list/confirm.html", form=form)

    query = ListEntry.select().where(ListEntry.email_confirm_key == key)
    if query.count() != 1:
        flash("Invalid confirmation key.", "error")
        return redirect(url_for("email_list.list_subscribe"))

    entry = next(query.iterator())
    entry.first_name = form.first_name.data
    entry.last_name = form.last_name.data
    entry.email_confirmed = True
    entry.save()

    return redirect(url_for("email_list.thanks_confirm"))
Esempio n. 29
0
def confirm_email(key):
    form = ListConfirmSubscribeForm(request.form)

    if not form.validate_on_submit():
        flash_errors(form)
        return render_template("list/confirm.html", form=form)

    query = ListEntry.select().where(ListEntry.email_confirm_key == key)
    if query.count() != 1:
        flash("Invalid confirmation key.", "error")
        return redirect(url_for("email_list.list_subscribe"))

    entry = next(query.iterator())
    entry.first_name = form.first_name.data
    entry.last_name = form.last_name.data
    entry.email_confirmed = True
    entry.save()

    return redirect(url_for("email_list.thanks_confirm"))
Esempio n. 30
0
 def edit(self, _id):
     one = self.model_get(_id)
     if one is None:
         flash("L'objet {} numero {} n'existe pas".format(self.object_name, _id), 'danger')
         return redirect(url_for('.{}:list'.format(self.object_title)))
     else:
         form = self.object_form(**one)
         self._form = form
         self._fetch_choices(form)
         if request.method == 'POST':
             if form.validate_on_submit():
                 self.model_update(_id, **form.data)
                 flash(u'Edition réussie de l\'objet {}'.format(self.object_name), 'success')
                 return redirect(url_for('.{}:list'.format(self.object_title)))
             else:
                 current_app.logger.warning(form.errors)
                 flash_errors(form)
     return render_template('generic/add.html', form=form,
         sectname=self.section_name, objname=self.object_name, action='Edition')
Esempio n. 31
0
def create_account():
    form = AccountCreateForm(request.form)

    if not form.validate_on_submit():
        flash_errors(form)
        return render_template("account/signup.html", form=form)

    matching_accounts = Account.select().where(
        Account.email == form.email.data)
    if matching_accounts.count() > 0:
        flash("An account already exists with that email address.", "error")
        return render_template("account/create.html", form=form)

    if current_app.config['SEND_EMAIL']:
        email_confirmed = False
        email_confirm_key = send_confirm_email(form.first_name.data,
                                               form.email.data)
        flash(
            "Account created. Please confirm your email; you should receive information on how to do this shortly.",
            "info")
    else:
        email_confirmed = True
        email_confirm_key = None
        flash("Account created.", "info")

    password = Account.hash_password(str(form.password.data))

    account = Account.create(first_name=form.first_name.data,
                             last_name=form.last_name.data,
                             street_address=form.street_address.data,
                             city=form.city.data,
                             state=form.state.data,
                             postal_code=form.postal_code.data,
                             email=form.email.data,
                             email_confirm_key=email_confirm_key,
                             email_confirmed=email_confirmed,
                             password=password,
                             dob=form.dob.data)

    attach_volunteer(account)

    return redirect(url_for('account.login'))
Esempio n. 32
0
def list_subscribe():
    form = ListSubscribeForm(request.form)

    if not form.validate_on_submit():
        flash_errors(form)
        return render_template("list/subscribe.html", form=form)

    if not current_app.config["SEND_EMAIL"]:
        flash("The application is not configured to send emails.", "error")
        return render_template("list/subscribe.html", form=form)

    if ListEntry.select().where(ListEntry.email == form.email.data).count() > 0:
        flash("You're already subscribed to the mailing list!", "error")
        return render_template("list/subscribe.html", form=form)

    confirm_key = send_confirm_email(form.email.data)
    ListEntry.create(email=form.email.data, email_confirm_key=confirm_key,
                     email_confirmed=False)

    return redirect(url_for("email_list.thanks"))
Esempio n. 33
0
    def post(self, token):
        context = self.get_context()
        form = context.get('form')

        if form.validate():
            try:
                user = User()
                form.populate_obj(user)
                user.set_password(form.password.data)            
                user.active = True
                user.save()

                flash('User is created.')
                return redirect(url_for('pages.home'))
            
            except NotUniqueError:
                flash('User aready exists')

        else:
            flash_errors(form)

        return render_template('accounts/register.html', register_user_form=form)
Esempio n. 34
0
def list_subscribe():
    form = ListSubscribeForm(request.form)

    if not form.validate_on_submit():
        flash_errors(form)
        return render_template("list/subscribe.html", form=form)

    if not current_app.config["SEND_EMAIL"]:
        flash("The application is not configured to send emails.", "error")
        return render_template("list/subscribe.html", form=form)

    if ListEntry.select().where(
            ListEntry.email == form.email.data).count() > 0:
        flash("You're already subscribed to the mailing list!", "error")
        return render_template("list/subscribe.html", form=form)

    confirm_key = send_confirm_email(form.email.data)
    ListEntry.create(email=form.email.data,
                     email_confirm_key=confirm_key,
                     email_confirmed=False)

    return redirect(url_for("email_list.thanks"))
Esempio n. 35
0
def login():
    form = AccountLoginForm(request.form)

    if not form.validate_on_submit():
        flash_errors(form)
        return render_template("account/login.html", form=form)

    matching_accounts = Account.select().where(
        Account.email == form.email.data)
    if matching_accounts.count() == 1:
        account = next(matching_accounts.iterator())
        if account.validate_password(form.password.data):
            if account.dob is not None:
                session["uid"] = account.id
                session["logged_in"] = True
                return redirect(
                    request.args.get('next', url_for('account.info')))
            else:
                session["dob_uid"] = account.id
                return redirect(url_for("account.set_dob"))

    flash("Login failed.", "error")
    return render_template("account/login.html", form=form)