Ejemplo n.º 1
0
def update_profile(id):
    request_data = request.get_json()

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

    try:
        data = ProfileSchema().load(request_data)
    except ValidationError as error:
        return error_response(422, error.messages)

    try:
        user = User.find_by_id(id)
        profile = Profile.find_by_id(user.profile.id)

        profile.firstname = data.get('firstname').title()
        profile.lastname = data.get('lastname').title()
        profile.bio = data.get('bio')

        prof = Profile.find_by_username(data.get('username'))

        if prof is not None:
            if prof.user_id != id:
                return bad_request('Username is already taken.')

        profile.username = data.get('username')
        profile.save()

        response = jsonify({'message': 'Successfully updated your profile'})
        response.status_code = 200

        return response

    except Exception:
        return error_response(500, 'Something went wrong, please try again.')
Ejemplo n.º 2
0
def add_tag(user):
    req_data = request.get_json()

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

    try:
        data = TagSchema().load(req_data)
    except ValidationError as err:
        print(err)
        return error_response(422, err.messages)

    name = data.get('name')
    # check for existing tag
    tag = Tag.query.filter(Tag.name == name).first()

    if tag:
        return bad_request(f'Tag with name "{name}" already exists.')

    tag = Tag(name=name)

    try:
        tag.save()
    except (exc.IntegrityError, ValueError):
        db.session.rollback()
        return server_error('Something went wrong, please try again.')
    return jsonify(TagSchema().dump(tag))
Ejemplo n.º 3
0
def update_user(id):
    request_data = request.get_json()

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

    try:
        data = ProfileSchema().load(request_data)

        user = User.find_by_id(id)
        existing_user = User.find_by_identity(data.get('auth')['username'])

        if existing_user is not None:
            if existing_user.id != user.id:
                return bad_request(f'Username already exists.')

        # update user
        user.profile.name = data.get('name')
        user.profile.bio = data.get('bio')
        user.profile.dob = data.get('dob')
        user.username = data.get('auth')['username']
        user.is_active = data.get('auth')['is_active']
        user.is_admin = data.get('auth')['is_admin']
        user.save()

        return jsonify(UserSchema().dump(user))

    # handle errors
    except ValidationError as err:
        return error_response(422, err.messages)
    except (exc.IntegrityError, ValueError):
        db.session.rollback()
        return server_error('Something went wrong, please try again.')
Ejemplo n.º 4
0
def update_group(id):
    request_data = request.get_json()

    if not request_data:
        return bad_request('No input data provided.')

    try:
        data = GroupSchema().load(request_data)

        # check for existing group name
        group = Group.find_by_id(id)
        existing_group = Group.find_by_name(name=data.get('name'))

        if existing_group is not None:
            if existing_group.id != group.id:
                return bad_request(f'Group already exists.')

        group.name = data.get('name')
        group.description = data.get('description')
        group.save()

        return jsonify(GroupSchema().dump(group))

    # handle errors
    except ValidationError as err:
        return error_response(422, err.messages)
    except (exc.IntegrityError, ValueError):
        db.session.rollback()
        return server_error('Something went wrong, please try again.')
Ejemplo n.º 5
0
def add_group():
    request_data = request.get_json()

    if not request_data:
        return bad_request('No input data provided.')

    try:
        data = GroupSchema().load(request_data)

        name = data.get('name')
        description = data.get('description')

        # check for existing group name
        group = Group.find_by_name(name=name)

        if group:
            return bad_request('Group already exist.')

        group = Group(name=name, description=description)
        group.save()

        response = jsonify(GroupSchema().dump(group))
        response.status_code = 201
        response.headers['Location'] = url_for('admin.get_group', id=group.id)
        return response

    # handle errors
    except ValidationError as err:
        return error_response(422, err.messages)
    except (exc.IntegrityError, ValueError):
        db.session.rollback()
        return server_error('Something went wrong, please try again.')
Ejemplo n.º 6
0
def update_profile(user):
    request_data = request.get_json()
    print(request_data)

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

    try:
        data = ProfileSchema().load(request_data)
    except ValidationError as error:
        return error_response(422, error.messages)

    profile = user.profile
    profile.username = data.get('username')
    profile.name = data.get('name')
    profile.dob = data.get('dob')
    profile.bio = data.get('bio')

    try:
        profile.save()
    except (exc.IntegrityError, ValueError):
        db.session.rollback()
        return server_error('Something went wrong, please try again.')
    else:
        return jsonify(ProfileSchema().dump(profile))
Ejemplo n.º 7
0
def register_user():
    request_data = request.get_json()

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

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

    email = data.get('email')
    password = data.get('password')
    firstname = data.get('firstname').title()
    lastname = data.get('lastname').title()

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

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

        # add new user to db
        profile = Profile(firstname=firstname, lastname=lastname)
        profile.username = profile.set_username()
        profile.avatar = profile.set_avatar(email)

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

        response = jsonify({
            'token': user.encode_auth_token(user.id).decode(),
        })
        response.status_code = 201
        response.headers['Location'] = url_for('auth.get_user', id=user.id)
        return response

    # handle errors
    except (exc.IntegrityError, ValueError):
        db.session.rollback()
        return error_response(500, 'Something went wrong, please try again.')
Ejemplo n.º 8
0
def add_user():
    request_data = request.get_json()

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

    try:
        data = AuthSchema().load(request_data)

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

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

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

        # add new user to db
        profile = Profile(name=name)
        user = User(password=password)
        user.email = email
        user.username = username
        user.is_active = data.get('is_active') or False
        user.is_admin = data.get('is_admin') or False
        user.profile = profile
        user.save()

        response = jsonify(UserSchema().dump(user))
        response.status_code = 201
        response.headers['Location'] = url_for('admin.get_user', id=user.id)
        return response

    # handle errors
    except ValidationError as err:
        return error_response(422, err.messages)
    except (exc.IntegrityError, ValueError):
        db.session.rollback()
        return server_error('Something went wrong, please try again.')
Ejemplo n.º 9
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
Ejemplo n.º 10
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
Ejemplo n.º 11
0
def login_user():
    request_data = request.get_json()

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

    try:
        data = AuthSchema(partial=True).load(request_data)

        # check for existing user
        user = User.find_by_email(data.get('email'))
        user.update_activity_tracking(request.remote_addr)

        if user and user.check_password(data.get('password')):
            return jsonify({
                'token': user.encode_auth_token(user.id).decode(),
            })
        else:
            return error_response(401, 'Incorrect email or password.')

    except Exception:
        return bad_request('Invalid payload, please try again.')
Ejemplo n.º 12
0
def follow_tag(user, tag_id):
    tag = Tag.query.filter_by(id=tag_id).first()

    if not tag:
        return bad_request(f'No tag with id "{tag_id}" exists')

    try:
        user.unfollow_tag(tag) \
            if user.is_following_tag(tag) else user.follow_tag(tag)
        user.save()
    except (exc.IntegrityError, ValueError):
        db.session.rollback()
        return server_error('Something went wrong, please try again.')
    return TagSchema().dump(tag)
Ejemplo n.º 13
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.')
Ejemplo n.º 14
0
def update_profile(user):
    request_data = request.get_json()

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

    try:
        data = ProfileSchema().load(request_data)

        profile = user.profile
        profile.name = data.get('name')
        profile.dob = data.get('dob')
        profile.bio = data.get('bio')
        profile.save()

        return jsonify(ProfileSchema().dump(profile))

    except ValidationError as error:
        return error_response(422, error.messages)
    except Exception:
        return server_error('Something went wrong, please try again.')
Ejemplo n.º 15
0
def create_post(user, post_id=None):
    req_data = request.get_json()

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

    post = Post()
    post.body = req_data.get('post')
    post.user_id = user.id
    db.session.add(post)

    if post_id:
        post.comment_id = post_id
        parent = Post.find_by_id(post_id)
        db.session.add(
            user.add_notification(subject='comment',
                                  item_id=post.id,
                                  id=parent.author.id,
                                  post_id=parent.id))
    else:
        post_notifs = []
        for u in user.followers.all():
            post_notifs.append(
                user.add_notification(subject='post',
                                      item_id=post.id,
                                      id=u.id,
                                      post_id=post.id))
        db.session.add_all(post_notifs)

    try:
        post.save()
    except (exc.IntegrityError, ValueError):
        db.session.rollback()
        return server_error('Something went wrong, please try again.')
    else:
        response = jsonify(post.to_dict(user))
        response.status_code = 201
        response.headers['Location'] = url_for('posts.get_post',
                                               post_id=post.id)
        return response