Exemplo n.º 1
0
 def post(self):
     args = self.reqparse.parse_args()
     user = User(username=args['username'], password=args['password'])
     try:
         user.save()
     except IntegrityError as err:
         return {'error_message': err.message}, 409
     return {'user': user.serialize()}, 201
Exemplo n.º 2
0
def test_data(db):
    db.session.query(User).delete()

    users = [
        {
            'username': '******',
            'password': '******'
        },
        {
            'username': '******',
            'password': '******'
        }
    ]

    for user in users:
        db.session.add(User(**user))

    db.session.commit()

    _users = User.query.all()
    for _u in _users:
        params = {
            'user_id': _u.id,
            'topic': random.choice(Comment.TOPICS.keys()),
            'text': "A fake comment."
        }

        comment = Comment(**params)
        db.session.add(comment)

    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
Exemplo n.º 4
0
def users():
    """
    Create random users.
    """
    random_usernames = []
    data = []

    # Ensure we get about 50 unique random usernames.
    for i in range(0, 50):
        random_usernames.append(fake.user_name())

    random_usernames = list(set(random_usernames))

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

        username = random_usernames.pop()

        params = {
            'username': username,
            'password': User.encrypt_password('password')
        }

        data.append(params)

    return _bulk_insert(User, data, 'users')
Exemplo n.º 5
0
    def test_deliver_password_reset_email(self, token):
        """ Deliver 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
Exemplo n.º 6
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 token(db):
    """
    Serialize JWS token.

    :param db: Pytest fixture
    :return: JWS token
    """
    user = User.find_by_identity('*****@*****.**')
    return user.serialize_token()
    def post():
        content = request.get_json()
        username = content.get('username', None)
        email = content.get('email', None)
        username_error = "Username has been taken."
        email_error = "An account with that email has already been registered."

        if User.find_by_identity(username) and User.find_by_identity(email):
            return render_json(404,
                {'username': username_error,
                 'email': email_error})
        if User.find_by_identity(username):
            return render_json(404, 
                {'username': username_error})
        if User.find_by_identity(email):
            return render_json(404, 
                {'email': email_error})

        return None
Exemplo n.º 9
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 {0}.'.format(u.email), 'success')
        return redirect(url_for('user.login'))

    return render_template('user/begin_password_reset.html', form=form)
Exemplo n.º 10
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
Exemplo n.º 11
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'))
        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)
Exemplo n.º 12
0
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',
        'username': app.config['SEED_ADMIN_USERNAME'],
        'first_name': app.config['SEED_ADMIN_FIRST_NAME'],
        'last_name': app.config['SEED_ADMIN_LAST_NAME'],
        'email': app.config['SEED_ADMIN_EMAIL'],
        'password': app.config['SEED_ADMIN_PASSWORD'],
        'phone_number': app.config['SEED_ADMIN_PHONE_NUMBER']
    }

    return User(**params).save()
Exemplo n.º 13
0
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.')
Exemplo n.º 14
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'
    def post():
        content = request.form
        user = User.find_by_identity(content.get('identity'))

        if user and user.authenticated(password=content.get('password')):
            if login_user(user, remember=True) and user.is_active():
                user.update_activity_tracking(request.remote_addr)
                return render_json(200, {'message': 'Login successful'})
            else:
                return render_json(401, {'message': 'This account has been disabled'})
        else:
            return render_json(401, {'message': 'Identity or password provided was incorrect.'})
Exemplo n.º 16
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 Subby')
        assert user.cancelled_subscription_on is not None
Exemplo n.º 17
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.')
Exemplo n.º 18
0
def update_credentials():
    form = UpdateCredentials(current_user, uid=current_user.id)

    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)
Exemplo n.º 19
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'
Exemplo n.º 20
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'))
        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)
Exemplo n.º 21
0
def db(app):
    """
    Setup database, 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.
    params = {
        'role': 'admin',
        'email': '*****@*****.**',
        'password': '******',
        'coins': 100
    }

    admin = User(**params)

    _db.session.add(admin)
    _db.session.commit()

    return _db
Exemplo n.º 22
0
def authenticate(username, password):
    from server.blueprints.user.models import User
    user = User.find_by_identity(username)
    if user and user.authenticated(password=password):
        return user
    def post(): 
        content = request.form
        
        user = User()
        user.role = content.get('role', None)
        user.username = content.get('username', '')
        user.password = content.get('password', '')
        user.email = content.get('email', '')
        user.first_name = " ".join(word.capitalize() for word in content.get('firstName', '').split())
        user.middle_name = " ".join(word.capitalize() for word in content.get('middleName', '').split())
        user.last_name = " ".join(word.capitalize() for word in content.get('lastName', '').split())
        user.phone_number = content.get('phoneNumber', '')
        user.unit_number = content.get('unitNumber', '')
        user.street_address = content.get('streetAddress', '')
        user.suburb = content.get('suburb', '')
        user.postcode = content.get('postcode', '')
        user.state = content.get('state', '')
        user.country = content.get('country', '')

        try: 
            user.save()
        except:
            return render_json(500, {'message': "An error occurred."})
        
        return render_json(200, {'user': user.to_json()})
Exemplo n.º 24
0
def users():
    """
    Generate fake users.
    """
    click.echo('Working...')

    data = []
    random_usernames = []
    with app.app_context():
        placeholder_user = url_for('static',
                                   filename='images/64/placeholder-user.png')

    for i in range(0, 99):
        random_usernames.append(fake.user_name())

    random_usernames.append(app.config['SEED_ADMIN_USERNAME'])
    random_usernames = list(set(random_usernames))

    for username in random_usernames:
        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()
        role = 'public' if random_percent >= 0.5 \
               else 'staff' if random_percent >= 0.25 \
               else 'client'
        street_address = fake.building_number() + ' ' + fake.street_name()

        params = {
            'created_on': created_on,
            'updated_on': created_on,
            'role': role,
            'email': fake.email(),
            'username': username,
            'password': User.encrypt_password('password'),
            'first_name': fake.first_name(),
            'middle_name': fake.first_name(),
            'last_name': fake.last_name(),
            'unit_number': fake.building_number(),
            'street_address': street_address,
            'postcode': fake.postcode(),
            'state': fake.state(),
            'suburb': fake.city(),
            'country': 'Australia',
            'phone_number': fake.phone_number(),
            'sign_in_count': random.random() * 100,
            'current_sign_in_on': created_on,
            'current_sign_in_ip': fake.ipv4(),
            'last_sign_in_on': created_on,
            'last_sign_in_ip': fake.ipv4(),
            'photo': placeholder_user
        }

        if username == app.config['SEED_ADMIN_USERNAME']:
            password = User.encrypt_password(app.config['SEED_ADMIN_PASSWORD'])

            params['role'] = 'admin'
            params['password'] = password
            params['email'] = '*****@*****.**'
            params['first_name'] = 'Admin'
            params['middle_name'] = ''
            params['last_name'] = 'User'

        data.append(params)

    _bulk_insert(User, data, 'users')