Beispiel #1
0
def posts(db, session, users):
    """
    Create posts fixtures. They reset per test.

    :param db: Pytest fixture
    :return: SQLAlchemy database session
    """
    db.session.query(Post).delete()

    u1 = User.find_by_email('*****@*****.**')
    u2 = User.find_by_email('*****@*****.**')
    u3 = User.find_by_email('*****@*****.**')

    p1 = add_post('Ut enim ad minim veniam, quis nostrud exercitation ', u1)
    p2 = add_post('Ut enim ad minim veniam, quis nostrud exercitation ', u1)
    p3 = add_post('Ut enim ad minim veniam, quis nostrud exercitation ', u3)

    add_post('ullamco laboris nisi ut aliquip ex ea commodo consequat.', u1,
             p2.id)
    add_post('ullamco laboris nisi ut aliquip ex ea commodo consequat.', u1,
             p1.id)
    add_post('Ut enim ad minim veniam, quis nostrud exercitation ', u2, p1.id)
    add_post('ullamco laboris nisi ut aliquip ex ea commodo consequat.', u3,
             p3.id)
    p1.likes.append(u1)
    p2.likes.append(u1)

    return db
Beispiel #2
0
def seed_users(num_of_users):
    """
    Seed the database with users.
    :param num_of_users: Number of users to seed the
    database with, default is 50.
    """
    print('Collecting users...')
    try:
        data = requests.get(
            'https://randomuser.me/api/?'
            f'results={num_of_users}'
            '&inc=name,email,login,picture,dob,location,nat'
        ).json()

        users = []

        for user in data.get('results'):
            u = User(email=user.get('email'), password='******')
            u.created_on = random_timestamp(
                datetime(2020, 3, 1), datetime(2020, 7, 28))

            u.profile = Profile()
            u.profile.username = user.get('login')['username']
            u.profile.name = user.get('name')['first'] + \
                ' ' + user.get('name')['last']
            u.profile.avatar = user.get('picture')['thumbnail']
            u.profile.dob = random_timestamp(
                datetime(1970, 3, 1), datetime(2002, 7, 28))
            u.profile.bio = f"Hi, I am {user.get('name')['first']} \
                from {user.get('location')['city']} \
                    {user.get('location')['state']}, {user.get('nat')}. \
                        I am a {user.get('dob')['age']} yrs old, who likes \
                            to tell jokes."
            u.profile.created_on = u.created_on
            users.append(u)

        print('Setting up followers/following...')

        for user in users:
            following = random.sample(
                users, k=random.randrange(20, int(len(users)/4)))
            user.followed.extend(following)

        print('Saving to database...')
        db.session.add_all(users)
        db.session.commit()

        print(f'Users table seeded with {num_of_users} users...')
    except exc.IntegrityError as error:
        db.session.rollback()
        print(f'Error: {error}')
Beispiel #3
0
def test_follow(client, users, token):
    user = User.find_by_identity('regularuser')
    response = client.post(f'/api/users/follow/{user.id}',
                           headers={'Authorization': f'Bearer {token}'})
    data = json.loads(response.data.decode())
    assert response.status_code == 200
    assert isinstance(data, list) is True
Beispiel #4
0
def token(users):
    """
    Serialize a JWT token.

    :param db: Pytest fixture
    :return: JWT token
    """
    user = User.find_by_email('*****@*****.**')
    return user.encode_auth_token()
Beispiel #5
0
    def wrapper(*args, **kwargs):
        auth_header = request.headers.get('Authorization')

        if not auth_header:
            return error_response(403, message='No authorization.')

        token = auth_header.split(" ")[1]
        payload = User.decode_auth_token(token)

        if not isinstance(payload, dict):
            return error_response(401, message=payload)

        user = User.find_by_id(payload.get('id'))

        if user is None:
            return error_response(401, message='Invalid token.')

        return func(user, *args, **kwargs)
Beispiel #6
0
def test_follow(users):
    u1 = User.find_by_email('*****@*****.**')
    u2 = User.find_by_email('*****@*****.**')
    assert u1.followed.all() == []
    assert u1.followers.all() == []

    u1.follow(u2)
    db.session.commit()
    assert u1.is_following(u2) is True
    assert u1.followed.count() == 1
    assert u1.followed.first().profile.username == 'commonuser'
    assert u2.followers.count() == 1
    assert u2.followers.first().profile.username == 'regularuser'

    u1.unfollow(u2)
    db.session.commit()
    assert u1.is_following(u2) is False
    assert u1.followed.count() == 0
    assert u2.followers.count() == 0
Beispiel #7
0
def create_message(user):
    req_data = request.get_json()
    user_id = request.args.get('user', None, int)

    if not req_data:
        return bad_request("No request data provided")

    try:
        a_user = User.find_by_id(user_id)

        if not a_user:
            return not_found('User not found.')

        chat = user.get_chat(a_user)

        if not chat:
            chat = Chat(user1_id=user.id, user2_id=a_user.id)
            db.session.add(chat)
            db.session.commit()

        message = Message()
        message.body = json.dumps(req_data.get('body'))
        message.author_id = user.id
        message.created_on = datetime.utcnow()
        message.chat_id = chat.id
        db.session.add(message)

        lrm = LastReadMessage.find_by_pk(user.id, chat.id)

        if lrm:
            lrm.timestamp = datetime.utcnow()
        else:
            lrm = LastReadMessage()
            lrm.user_id = user.id
            lrm.chat_id = chat.id
            lrm.timestamp = message.created_on
            db.session.add(lrm)

        user.add_notification(subject='message',
                              item_id=message.id,
                              id=a_user.id)
        user.save()
    except (IntegrityError, ProgrammingError, AttributeError, ValueError) as e:
        db.session.rollback()
        print(e)
        return server_error('Something went wrong, please try again.')
    else:
        response = jsonify(MessageSchema().dump(message))
        response.status_code = 201
        response.headers['Location'] = url_for('messages.get_messages',
                                               user=user,
                                               user_id=a_user.id)
        return response
Beispiel #8
0
def seed_messages():
    db.session.query(Message).delete()
    db.session.query(LastReadMessage).delete()
    chats = Chat.query.all()
    messages = []
    lr_msgs = []

    try:
        print('Fetching messages...')
        msgs = requests.get(
            'https://jsonplaceholder.typicode.com/todos').json()
    except Exception as error:
        print(f'Error: {error}')

    for c in chats:
        sample = random.sample(msgs, k=random.randrange(3, 8))

        for msg in sample:
            author = random.choice([c.user1_id, c.user2_id])
            message = Message(author_id=author, body=msg["title"])
            message.created_on = random_timestamp(
                datetime(2021, 1, 12), datetime(2021, 2, 11))
            message.chat_id = c.id
            messages.append(message)

            id = random.choice(
                [0, 0, 0, 0, c.user1_id, c.user2_id, 0, 0, 0, 0, 0, 0])

            if id != 0:
                user = User.find_by_id(id)
                user.deleted_messages.append(message)
                db.session.add(user)

            lrm = LastReadMessage.query.filter(
                and_(
                    LastReadMessage.user_id == author,
                    LastReadMessage.chat_id == c.id)
                ).first()

            if lrm:
                lrm.timestamp = random_timestamp(
                    datetime(2021, 1, 12), datetime(2021, 2, 1))
            else:
                lrm = LastReadMessage(user_id=author, chat_id=c.id)
                lrm.timestamp = random_timestamp(
                    datetime(2021, 1, 12), datetime(2021, 2, 1))
            lr_msgs.append(lrm)
            db.session.add(lrm)

    print('Saving to database...')
    db.session.add_all(messages)
    db.session.commit()
Beispiel #9
0
def login_user():
    data = request.get_json()

    if data is None:
        return bad_request("No input data provided")

    try:
        # check for existing user
        user = User.find_by_email(data.get('email'))

        if user and user.check_password(data.get('password')):
            return jsonify({'token': user.encode_auth_token()})
        else:
            return error_response(401, 'Incorrect email or password.')
    except Exception:
        return server_error('Something went wrong, please try again.')
Beispiel #10
0
def msg_Search(user):
    q = request.args.get('q', str, None)

    try:
        if q is None:
            return {[]}

        users = User.search(UsersIndex, q)
    except Exception as e:
        db.session.rollback()
        print(e)
        return server_error('An unexpected error occured, please try again.')
    return {
        'users':
        UserSchema(many=True,
                   only=('id', 'auth.username', 'profile.name',
                         'profile.avatar')).dump(users),
    }
Beispiel #11
0
def add_user(
    name,
    email,
    username='',
    avatar='',
    bio='',
    is_admin=False,
):

    profile = Profile(name=name, bio=bio, username=username)
    profile.avatar = avatar or profile.set_avatar(email)

    user = User(password='******')
    user.email = email
    user.is_admin = is_admin
    user.profile = profile

    user.save()
    return user
Beispiel #12
0
def follow(user, id):
    to_follow = User.find_by_id(id)

    if not to_follow:
        return not_found('User not found')

    user.follow(to_follow)

    db.session.add(
        user.add_notification(
            subject='follow', item_id=user.id, id=to_follow.id))

    try:
        user.save()
    except (exc.IntegrityError, ValueError):
        db.session.rollback()
        return server_error('Something went wrong, please try again.')
    else:
        following = UserSchema(only=('id', 'profile',)).dump(to_follow)
        following['isFollowing'] = user.is_following(to_follow)
        return jsonify(following)
Beispiel #13
0
def unfollow(user, id):
    followed = User.find_by_id(id)

    if not followed:
        return not_found('User not found')

    user.unfollow(followed)

    notif = Notification.find_by_attr(subject='follow', item_id=user.id)

    if (notif):
        db.session.delete(notif)

    try:
        user.save()
    except (exc.IntegrityError, ValueError):
        db.session.rollback()
        return server_error('Something went wrong, please try again.')
    else:
        follow = UserSchema(only=('id', 'profile',)).dump(followed)
        follow['isFollowing'] = user.is_following(followed)
        return jsonify(follow)
Beispiel #14
0
def mainSearch(user):
    q = request.args.get('q', str, None)

    try:
        if q is None:
            return {[]}

        tags = Tag.search(TagsIndex, q)
        users = User.search(UsersIndex, q)
    except Exception as e:
        db.session.rollback()
        print(e)
        return server_error('An unexpected error occured, please try again.')
    return {
        'results': {
            'tags': [tag.to_dict(user) for tag in tags],
            'users':
            UserSchema(many=True,
                       only=('id', 'profile.username', 'profile.name',
                             'profile.avatar')).dump(users),
        }
    }
Beispiel #15
0
def register_user():
    post_data = request.get_json()

    if not post_data:
        return bad_request("No input data provided")

    try:
        data = AuthSchema(partial=True).load(post_data)
    except ValidationError as err:
        return error_response(422, err.messages)

    name = data.get('name')
    username = data.get('username')
    email = data.get('email')
    password = data.get('password')

    # check for existing user
    user = User.query.filter(User.email == email).first()

    if user:
        return bad_request('That user already exists.')

    profile = Profile()
    profile.name = name
    profile.username = username
    profile.avatar = profile.set_avatar(email)

    user = User(password=password)
    user.email = email
    user.profile = profile

    try:
        user.save()
    except (exc.IntegrityError, ValueError):
        db.session.rollback()
        return server_error('Something went wrong, please try again.')

    response = jsonify({'token': user.encode_auth_token()})
    response.status_code = 201
    response.headers['Location'] = url_for('users.get_user', id=user.id)
    return response
Beispiel #16
0
def check_email():
    data = request.get_json()
    user = User.find_by_email(data.get('email'))
    return {'res': not isinstance(user, User)}
Beispiel #17
0
def test_avatar(users):
    user = User.find_by_email('*****@*****.**')
    profile = Profile.query.filter_by(user_id=user.id).first()
    assert profile.avatar == ('https://www.gravatar.com/avatar/'
                        'e6b6b9ec69c4837878505768b621d383?s=128&d=mm&r=pg')
Beispiel #18
0
def test_decode_token(token):
    """ Token decoder decodes a JWT correctly. """
    payload = User.decode_auth_token(token)
    user = User.find_by_id(payload.get('id'))
    assert isinstance(user, User) is True
    assert user.email == '*****@*****.**'
Beispiel #19
0
def test_decode_token_invalid(token):
    """ Token decoder returns 'Invalid token' when
    it's been tampered with."""
    payload = User.decode_auth_token(f'{token}1337')
    assert isinstance(payload, User) is False
    assert 'Invalid token' in payload
Beispiel #20
0
def test_password_hashing(db):
    user = User.find_by_email('*****@*****.**')
    assert user.check_password('secret') is False
    assert user.check_password('password') is True