def users(page): search_form = SearchForm() bulk_form = BulkDeleteForm() sort_by = User.sort_by(request.args.get('sort', 'created_on'), request.args.get('direction', 'desc')) order_values = '{0} {1}'.format(sort_by[0], sort_by[1]) # Search is broken. Need to fix later. paginated_users = User.query \ .filter(User.search(request.args.get('q', text('')))) \ .order_by(User.role.asc(), User.payment_id, text(order_values)) \ .paginate(page, 50, True) # paginated_users = User.query \ # .order_by(User.role.asc(), User.payment_id, text(order_values)) \ # .paginate(page, 50, True) print("*** checking items ***") print("total:" + str(paginated_users.total)) for item in paginated_users.items: print("item:" + str(item)) return render_template('admin/user/index.html', form=search_form, bulk_form=bulk_form, users=paginated_users)
def users_edit(id): user = User.query.get(id) form = UserForm(obj=user) if current_user.subscription: coupon = Coupon.query \ .filter(Coupon.code == current_user.subscription.coupon).first() else: coupon = None if form.validate_on_submit(): if User.is_last_admin(user, request.form.get('role'), request.form.get('active')): flash('You are the last admin, you cannot do that.', 'error') return redirect(url_for('admin.users')) form.populate_obj(user) if not user.username: user.username = None user.save() flash('User has been saved successfully.', 'success') return redirect(url_for('admin.users')) return render_template('admin/user/edit.html', form=form, user=user, coupon=coupon)
def seed(): """ Seed the database with an initial user. :return: User instance """ if User.find_by_identity(app.config['SEED_ADMIN_EMAIL']) is not None: return None params = { 'role': 'admin', 'email': app.config['SEED_ADMIN_EMAIL'], 'password': app.config['SEED_ADMIN_PASSWORD'] } return User(**params).save()
def db(app): """ Setup our database, this only gets executed once per session. :param app: Pytest fixture :return: SQLAlchemy database session """ _db.drop_all() _db.create_all() # Create a single user because a lot of tests do not mutate this user. # It will result in faster tests. params = { 'role': 'admin', 'email': '*****@*****.**', 'password': '******', 'coins': 100 } admin = User(**params) _db.session.add(admin) _db.session.commit() return _db
def users(db): """ Create user fixtures. They reset per test. :param db: Pytest fixture :return: SQLAlchemy database session """ db.session.query(User).delete() users = [{ 'role': 'admin', 'email': '*****@*****.**', 'password': '******' }, { 'active': False, 'email': '*****@*****.**', 'password': '******' }] for user in users: db.session.add(User(**user)) db.session.commit() return db
def login(): form = LoginForm(next=request.args.get('next')) if form.validate_on_submit(): u = User.find_by_identity(request.form.get('identity')) if u and u.authenticated(password=request.form.get('password')): # As you can see remember me is always enabled, this was a design # decision I made because more often than not users want this # enabled. This allows for a less complicated login form. # # If however you want them to be able to select whether or not they # should remain logged in then perform the following 3 steps: # 1) Replace 'True' below with: request.form.get('remember', False) # 2) Uncomment the 'remember' field in user/forms.py#LoginForm # 3) Add a checkbox to the login form with the id/name 'remember' if login_user(u, remember=True): u.update_activity_tracking(request.remote_addr) # Handle optionally redirecting to the next URL safely. next_url = request.form.get('next') if next_url: return redirect(safe_next_url(next_url)) return redirect(url_for('quant.dashboard')) else: flash('This account has been disabled.', 'error') else: flash('Identity or password is incorrect.', 'error') return render_template('user/login.html', form=form)
def test_deliver_password_reset_email(self, token): """ Deliver a password reset email. """ with mail.record_messages() as outbox: user = User.find_by_identity('*****@*****.**') deliver_password_reset_email(user.id, token) assert len(outbox) == 1 assert token in outbox[0].body
def delete_users(ids): """ Delete users and potentially cancel their subscription. :param ids: List of ids to be deleted :type ids: list :return: int """ return User.bulk_delete(ids)
def token(db): """ Serialize a JWS token. :param db: Pytest fixture :return: JWS token """ user = User.find_by_identity('*****@*****.**') return user.serialize_token()
def subscriptions(db): """ Create subscription fixtures. :param db: Pytest fixture :return: SQLAlchemy database session """ subscriber = User.find_by_identity('*****@*****.**') if subscriber: subscriber.delete() db.session.query(Subscription).delete() params = { 'role': 'admin', 'email': '*****@*****.**', 'name': 'Subby', 'password': '******', 'payment_id': 'cus_000' } subscriber = User(**params) # The account needs to be commit before we can assign a subscription to it. db.session.add(subscriber) db.session.commit() # Create a subscription. params = {'user_id': subscriber.id, 'plan': 'gold'} subscription = Subscription(**params) db.session.add(subscription) # Create a credit card. params = { 'user_id': subscriber.id, 'brand': 'Visa', 'last4': '4242', 'exp_date': datetime.date(2015, 6, 1) } credit_card = CreditCard(**params) db.session.add(credit_card) db.session.commit() return db
def begin_password_reset(): form = BeginPasswordResetForm() if form.validate_on_submit(): u = User.initialize_password_reset(request.form.get('identity')) flash('An email has been sent to {0}.'.format(u.email), 'success') return redirect(url_for('user.login')) return render_template('user/begin_password_reset.html', form=form)
def password_reset(): form = PasswordResetForm(reset_token=request.args.get('reset_token')) if form.validate_on_submit(): u = User.deserialize_token(request.form.get('reset_token')) if u is None: flash('Your reset token has expired or was tampered with.', 'error') return redirect(url_for('user.begin_password_reset')) form.populate_obj(u) u.password = User.encrypt_password(request.form.get('password')) u.save() if login_user(u): flash('Your password has been reset.', 'success') return redirect(url_for('user.settings')) return render_template('user/password_reset.html', form=form)
def ensure_identity_exists(form, field): """ Ensure an identity exists. :param form: wtforms Instance :param field: Field being passed in :return: None """ user = User.find_by_identity(field.data) if not user: raise ValidationError('Unable to locate account.')
def test_cancel_subscription(self, subscriptions, mock_stripe): """ User subscription gets cancelled. """ user = User.find_by_identity('*****@*****.**') params = {'id': user.id} self.login() response = self.client.post(url_for('admin.users_cancel_subscription'), data=params, follow_redirects=True) assert_status_with_message( 200, response, 'Subscription has been cancelled for Subby') assert user.cancelled_subscription_on is not None
def test_invoice_create(self, users, mock_stripe): """ Successfully create an invoice item. """ user = User.find_by_identity('*****@*****.**') invoice = Invoice() invoice.create(user=user, currency='usd', amount='900', coins=1000, coupon=None, token='cus_000') assert user.coins == 1100
def update_credentials(): form = UpdateCredentials(obj=current_user) if form.validate_on_submit(): new_password = request.form.get('password', '') current_user.email = request.form.get('email') if new_password: current_user.password = User.encrypt_password(new_password) current_user.save() flash('Your sign in settings have been updated.', 'success') return redirect(url_for('user.settings')) return render_template('user/update_credentials.html', form=form)
def users_bulk_delete(): form = BulkDeleteForm() if form.validate_on_submit(): ids = User.get_bulk_action_ids(request.form.get('scope'), request.form.getlist('bulk_ids'), omit_ids=[current_user.id], query=request.args.get('q', text(''))) # Prevent circular imports. from turboquant.blueprints.billing.tasks import delete_users delete_users.delay(ids) flash('{0} user(s) were scheduled to be deleted.'.format(len(ids)), 'success') else: flash('No users were deleted, something went wrong.', 'error') return redirect(url_for('admin.users'))
def signup(): form = SignupForm() if form.validate_on_submit(): u = User() form.populate_obj(u) u.password = User.encrypt_password(request.form.get('password')) u.save() if login_user(u): flash('Awesome, thanks for signing up!', 'success') return redirect(url_for('user.welcome')) return render_template('user/signup.html', form=form)
def test_deserialize_token_tampered(self, token): """ Token de-serializer returns None when it's been tampered with. """ user = User.deserialize_token('{0}1337'.format(token)) assert user is None
def test_subscribed_user_receives_more_coins(self, users): """ Subscribed user receives more coins. """ user = User.find_by_identity('*****@*****.**') user.add_coins(Subscription.get_plan_by_id('bronze')) assert user.coins == 210
def test_deserialize_token(self, token): """ Token de-serializer de-serializes a JWS correctly. """ user = User.deserialize_token(token) assert user.email == '*****@*****.**'
def users(): """ Generate fake users. """ random_emails = [] data = [] click.echo('Working...') # Ensure we get about 100 unique random emails. for i in range(0, 99): random_emails.append(fake.email()) random_emails.append(app.config['SEED_ADMIN_EMAIL']) random_emails = list(set(random_emails)) while True: if len(random_emails) == 0: break fake_datetime = fake.date_time_between(start_date='-1y', end_date='now').strftime('%s') created_on = datetime.utcfromtimestamp( float(fake_datetime)).strftime('%Y-%m-%dT%H:%M:%S Z') random_percent = random.random() if random_percent >= 0.05: role = 'member' else: role = 'admin' email = random_emails.pop() random_percent = random.random() if random_percent >= 0.5: random_trail = str(int(round((random.random() * 1000)))) username = fake.first_name() + random_trail last_bet_on = created_on else: username = None last_bet_on = None fake_datetime = fake.date_time_between(start_date='-1y', end_date='now').strftime('%s') current_sign_in_on = datetime.utcfromtimestamp( float(fake_datetime)).strftime('%Y-%m-%dT%H:%M:%S Z') params = { 'created_on': created_on, 'updated_on': created_on, 'role': role, 'email': email, 'username': username, 'password': User.encrypt_password('password'), 'sign_in_count': random.random() * 100, 'coins': 100, 'last_bet_on': last_bet_on, 'current_sign_in_on': current_sign_in_on, 'current_sign_in_ip': fake.ipv4(), 'last_sign_in_on': current_sign_in_on, 'last_sign_in_ip': fake.ipv4() } # Ensure the seeded admin is always an admin with the seeded password. if email == app.config['SEED_ADMIN_EMAIL']: password = User.encrypt_password(app.config['SEED_ADMIN_PASSWORD']) params['role'] = 'admin' params['password'] = password data.append(params) return _bulk_insert(User, data, 'users')