Пример #1
0
    def test_is_last_admin_yes(self, users, token):
        """ Last admin should not be able to change himself. """
        user = User.find_by_identity('*****@*****.**')

        assert User.is_last_admin(user, 'member', 'y') is True
        assert User.is_last_admin(user, 'admin', 'y') is False
        assert User.is_last_admin(user, 'admin', None) is True
        assert User.is_last_admin(user, 'member', None) is True
def signup():
    form = SignupForm()

    if form.validate_on_submit():
        u = User()

        form.populate_obj(u)
        u.password = User.encrypt_password(request.form.get('password', None))
        u.save()

        if login_user(u):
            flash(_('Awesome, thanks for signing up!'), 'success')
            return redirect(url_for('user.welcome'))

    return render_template('user/signup.jinja2', form=form)
Пример #3
0
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('user.settings'))
            else:
                flash(_('This account has been disabled.'), 'error')
        else:
            flash(_('Identity or password is incorrect.'), 'error')

    return render_template('user/login.jinja2', form=form)
Пример #4
0
def create_admin():
    """
    Create an admin account.

    :return: User instance
    """
    if User.find_by_identity(SEED_ADMIN_EMAIL) is not None:
        return None

    params = {
        'role': 'admin',
        'email': SEED_ADMIN_EMAIL,
        'password': '******'
    }

    return User(**params).save()
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('user.settings'))
            else:
                flash(_('This account has been disabled.'), 'error')
        else:
            flash(_('Identity or password is incorrect.'), 'error')

    return render_template('user/login.jinja2', form=form)
Пример #6
0
    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
Пример #7
0
def users(page):
    search_form = SearchForm()
    bulk_form = BulkDeleteForm()

    sort_by = User.sort_by(request.args.get('sort', 'name'),
                           request.args.get('direction', 'asc'))
    order_values = '{0} {1}'.format(sort_by[0], sort_by[1])

    paginated_users = User.query \
        .filter(User.search(request.args.get('q', ''))) \
        .order_by(User.role.desc(), User.payment_id,
                  text(order_values)) \
        .paginate(page, 20, True)

    return render_template('admin/user/index.jinja2',
                           form=search_form, bulk_form=bulk_form,
                           users=paginated_users)
def token(db):
    """
    Serialize a JWS token.

    :param db: Pytest fixture
    :return: JWS token
    """
    user = User.find_by_identity('*****@*****.**')
    return user.serialize_token()
Пример #9
0
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)
Пример #10
0
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', None))
        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.jinja2', form=form)
Пример #11
0
    def test_login_activity(self, users):
        """ Login successfully and update the activity stats. """
        user = User.find_by_identity('*****@*****.**')
        old_sign_in_count = user.sign_in_count

        response = self.login()

        new_sign_in_count = user.sign_in_count

        assert response.status_code == 200
        assert (old_sign_in_count + 1) == new_sign_in_count
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', None))
        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.jinja2', form=form)
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 %(email)s.',
                email=u.email), 'success')
        return redirect(url_for('user.login'))

    return render_template('user/begin_password_reset.jinja2', form=form)
Пример #14
0
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 %(email)s.', email=u.email),
              'success')
        return redirect(url_for('user.login'))

    return render_template('user/begin_password_reset.jinja2', form=form)
    def test_login_activity(self, users):
        """ Login successfully and update the activity stats. """
        user = User.find_by_identity('*****@*****.**')
        old_sign_in_count = user.sign_in_count

        response = self.login()

        new_sign_in_count = user.sign_in_count

        assert response.status_code == 200
        assert (old_sign_in_count + 1) == new_sign_in_count
    def test_password_reset(self, users, token):
        """ Reset successful. """
        reset = {'password': '******', 'reset_token': token}
        response = self.client.post(url_for('user.password_reset'), data=reset,
                                    follow_redirects=True)

        assert_status_with_message(200, response,
                                   _('Your password has been reset.'))

        admin = User.find_by_identity('*****@*****.**')
        assert admin.password != 'newpassword'
    def test_begin_update_credentials_email_change(self):
        """ Update credentials but only the e-mail address. """
        self.login()

        user = {
            'current_password': '******',
            'email': '*****@*****.**'
        }
        response = self.client.post(url_for('user.update_credentials'),
                                    data=user, follow_redirects=True)

        assert_status_with_message(200, response,
                                   _('Your sign in settings have been '
                                     'updated.'))

        old_user = User.find_by_identity('*****@*****.**')
        assert old_user is None

        new_user = User.find_by_identity('*****@*****.**')
        assert new_user is not None
Пример #18
0
    def test_password_reset(self, users, token):
        """ Reset successful. """
        reset = {'password': '******', 'reset_token': token}
        response = self.client.post(url_for('user.password_reset'),
                                    data=reset,
                                    follow_redirects=True)

        assert_status_with_message(200, response,
                                   _('Your password has been reset.'))

        admin = User.find_by_identity('*****@*****.**')
        assert admin.password != 'newpassword'
Пример #19
0
    def test_begin_update_credentials_email_change(self):
        """ Update credentials but only the e-mail address. """
        self.login()

        user = {
            'current_password': '******',
            'email': '*****@*****.**'
        }
        response = self.client.post(url_for('user.update_credentials'),
                                    data=user,
                                    follow_redirects=True)

        assert_status_with_message(
            200, response, _('Your sign in settings have been '
                             'updated.'))

        old_user = User.find_by_identity('*****@*****.**')
        assert old_user is None

        new_user = User.find_by_identity('*****@*****.**')
        assert new_user is not None
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_welcome_with_existing_username(self, users):
        """ Create username failure due to username already existing. """
        self.login()

        u = User.find_by_identity('*****@*****.**')
        u.username = '******'
        u.save()

        user = {'username': '******'}
        response = self.client.post(url_for('user.welcome'), data=user,
                                    follow_redirects=True)

        assert_status_with_message(200, response, 'Already exists.')
Пример #22
0
    def test_is_last_admin_no(self, users, token):
        """ Not the last admin should be able to change himself. """
        user = User.find_by_identity('*****@*****.**')

        params = {
            'role': 'admin',
            'email': '*****@*****.**',
            'password': '******'
        }

        new_user = User(**params)
        new_user.save()

        assert User.is_last_admin(user, 'member', 'y') is False
        assert User.is_last_admin(user, 'admin', None) is False
        assert User.is_last_admin(user, 'member', None) is False
Пример #23
0
    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 '
                                     '%(user)s', user='******'))
        assert user.cancelled_subscription_on is not None
Пример #24
0
    def test_welcome_with_existing_username(self, users):
        """ Create username failure due to username already existing. """
        self.login()

        u = User.find_by_identity('*****@*****.**')
        u.username = '******'
        u.save()

        user = {'username': '******'}
        response = self.client.post(url_for('user.welcome'),
                                    data=user,
                                    follow_redirects=True)

        assert_status_with_message(200, response,
                                   _('You already picked a username.'))
    def test_signup(self, users):
        """ Signup successfully. """
        old_user_count = User.query.count()

        user = {'email': '*****@*****.**', 'password': '******'}
        response = self.client.post(url_for('user.signup'), data=user,
                                    follow_redirects=True)

        assert_status_with_message(200, response,
                                   _('Awesome, thanks for signing up!'))

        new_user_count = User.query.count()
        assert (old_user_count + 1) == new_user_count

        new_user = User.find_by_identity('*****@*****.**')
        assert new_user.password != 'password'
Пример #26
0
def subscriptions(db):
    """
    Create subscription fixtures. They reset per test.

    :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'
    }

    admin = User(**params)

    # The account needs to be commit before we can assign a subscription to it.
    db.session.add(admin)
    db.session.commit()

    # Create a subscription.
    params = {
        'user_id': admin.id,
        'plan': 'gold'
    }
    subscription = Subscription(**params)
    db.session.add(subscription)

    # Create a credit card.
    params = {
        'user_id': admin.id,
        'brand': 'Visa',
        'last4': '4242',
        'exp_date': datetime.date(2015, 06, 01)
    }
    credit_card = CreditCard(**params)
    db.session.add(credit_card)

    db.session.commit()

    return db
Пример #27
0
    def test_signup(self, users):
        """ Signup successfully. """
        old_user_count = User.query.count()

        user = {'email': '*****@*****.**', 'password': '******'}
        response = self.client.post(url_for('user.signup'),
                                    data=user,
                                    follow_redirects=True)

        assert_status_with_message(200, response,
                                   _('Awesome, thanks for signing up!'))

        new_user_count = User.query.count()
        assert (old_user_count + 1) == new_user_count

        new_user = User.find_by_identity('*****@*****.**')
        assert new_user.password != 'password'
Пример #28
0
def update_credentials():
    form = UpdateCredentials(current_user, uid=current_user.id)

    if form.validate_on_submit():
        # We cannot form.populate_obj() because the password is optional.
        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.jinja2', form=form)
def update_credentials():
    form = UpdateCredentials(current_user, uid=current_user.id)

    if form.validate_on_submit():
        # We cannot form.populate_obj() because the password is optional.
        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.jinja2', form=form)
Пример #30
0
def signup():
    form = SignupForm()

    if form.validate_on_submit():
        u = User()

        form.populate_obj(u)
        u.password = User.encrypt_password(request.form.get('password', None))
        u.save()

        if login_user(u):
            flash(_('Awesome, thanks for signing up!'), 'success')
            return redirect(url_for('user.welcome'))

    return render_template('user/signup.jinja2', form=form)
Пример #31
0
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', ''))

        # Prevent circular imports.
        from catwatch.blueprints.billing.tasks import delete_users

        delete_users.delay(ids)

        flash(_n('%(num)d user was scheduled to be deleted.',
                 '%(num)d users were scheduled to be deleted.',
                 num=len(ids)), 'success')
    else:
        flash(_('No users were deleted, something went wrong.'), 'error')

    return redirect(url_for('admin.users'))
Пример #32
0
def users_edit(id):
    user = User.query.get(id)
    form = UserForm(obj=user)

    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 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.jinja2', form=form, user=user)
Пример #33
0
def users():
    """
    Create random users.
    """
    random_emails = []
    data = []

    # Ensure we get about 50 unique random emails, +1 due to the seeded email.
    for i in range(0, 49):
        random_emails.append(fake.email())

    random_emails.append(SEED_ADMIN_EMAIL)
    random_emails = list(set(random_emails))

    while True:
        if len(random_emails) == 0:
            break

        email = random_emails.pop()

        params = {
            'role': random.choice(User.ROLE.keys()),
            'email': email,
            'password': User.encrypt_password('password'),
            'name': fake.name(),
            'locale': random.choice(ACCEPT_LANGUAGES)
        }

        # Ensure the seeded admin is always an admin.
        if email == SEED_ADMIN_EMAIL:
            params['role'] = 'admin'
            params['locale'] = 'en'

        data.append(params)

    return _bulk_insert(User, data, 'users')
Пример #34
0
def users():
    """
    Create random users.
    """
    random_emails = []
    data = []

    # Ensure we get about 50 unique random emails, +1 due to the seeded email.
    for i in range(0, 49):
        random_emails.append(fake.email())

    random_emails.append(SEED_ADMIN_EMAIL)
    random_emails = list(set(random_emails))

    while True:
        if len(random_emails) == 0:
            break

        email = random_emails.pop()

        params = {
            'role': random.choice(User.ROLE.keys()),
            'email': email,
            'password': User.encrypt_password('password'),
            'name': fake.name(),
            'locale': random.choice(ACCEPT_LANGUAGES)
        }

        # Ensure the seeded admin is always an admin.
        if email == SEED_ADMIN_EMAIL:
            params['role'] = 'admin'
            params['locale'] = 'en'

        data.append(params)

    return _bulk_insert(User, data, 'users')
Пример #35
0
 def test_deserialize_token(self, token):
     """ Token de-serializer de-serializes a JWS correctly. """
     user = User.deserialize_token(token)
     assert user.email == '*****@*****.**'
Пример #36
0
 def test_deserialize_token_tampered(self, token):
     """ Token deserializer returns None when it's been tampered with. """
     user = User.deserialize_token('{0}1337'.format(token))
     assert user is None