Beispiel #1
0
def create_thread():
    app.logger.debug(f'Receive request: {request.data}')
    request_data = request.get_json() or {}

    if 'forum_id' not in request_data:
        bad_request('must include a forum_id')

    all_column_names = Thread.__table__.columns.keys()
    insert_data = {
        k: v
        for k, v in request_data.items() if k in all_column_names
    }
    insert_data['creator_id'] = token_auth.current_user().id
    insert_data['creation_timestamp'] = datetime.utcnow()
    insert_data['deleted'] = False
    insert_data_list = [(k, v) for k, v in insert_data.items()]

    insert_thread_query = f"""
    INSERT INTO thread 
    ({', '.join([k for k, v in insert_data_list])})
    VALUES ({', '.join([f"'{v}'" for k, v in insert_data_list])}) 
    RETURNING thread.id
    """
    query_result = database.session.execute(insert_thread_query)
    database.session.commit()
    new_thread_id = [r for r in query_result][0][0]
    response = jsonify({'thread_id': new_thread_id})
    response.status_code = 201
    response.headers['Location'] = url_for('get_thread',
                                           thread_id=new_thread_id)
    return response
Beispiel #2
0
def create_post():
    app.logger.debug(f'Receive request: {request.data}')
    request_data = request.get_json() or {}
    obligatory_fields = ['text', 'thread_id']
    for field_name in obligatory_fields:
        if field_name not in request_data:
            return bad_request(f'must include the field "{field_name}"')

    post_text = request_data['text']
    thread_id = request_data['thread_id']
    author_id = token_auth.current_user().id
    insert_post_query = f"""
    INSERT INTO post (text, creation_timestamp, user_id, thread_id, 
    deleted, deleted_by_thread) 
    VALUES ('{post_text}', '{datetime.utcnow()}', '{author_id}', '{thread_id}', 
    FALSE, FALSE) 
    RETURNING post.id
    """
    query_result = database.session.execute(insert_post_query)
    database.session.commit()
    new_post_id = [r for r in query_result][0][0]
    response = jsonify({'post_id': new_post_id})
    response.status_code = 201
    response.headers['Location'] = url_for('get_post', post_id=new_post_id)
    return response
Beispiel #3
0
def create_forum():
    app.logger.debug(f'Receive request: {request.data}')
    request_data = request.get_json() or {}
    if 'name' not in request_data or 'short_name' not in request_data:
        return bad_request('must include name amd short_name fields')

    for unique_field_name in ['name', 'short_name']:
        forum_query = A_FORUM_QUERY_TEMPLATE.format(
            unique_field_name,
            request_data[unique_field_name],
        )
        query_result_proxy = database.session.execute(forum_query)
        query_result = [r for r in query_result_proxy]
        if query_result:
            return bad_request(f'please use a different {unique_field_name}')

    creator_id = token_auth.current_user().id
    insert_command = f"""
    INSERT INTO forum (name, short_name, creator_id) 
    VALUES (
    '{request_data['name']}', '{request_data['short_name']}', '{creator_id}'
    ) 
    RETURNING forum.id
    """
    query_result = database.session.execute(insert_command)
    database.session.commit()
    new_forum_id = [r for r in query_result][0][0]
    response = jsonify({'forum_id': new_forum_id})
    response.status_code = 201
    response.headers['Location'] = url_for('get_forum', forum_id=new_forum_id)
    return response
Beispiel #4
0
def remove_post(post_id):
    post_query = SINGLE_POST_QUERY_TEMPLATE.format(post_id)
    json_post = get_single_json_entity(post_query)
    if not json_post:
        return error_response(404)
    if token_auth.current_user().id != json_post['user_id']:
        abort(403)

    delete_post_query = f"""
    UPDATE post SET deleted = TRUE WHERE post.id = '{post_id}'
    """
    database.session.execute(delete_post_query)
    database.session.commit()
    response = jsonify({'status': 'OK'})
    return response
Beispiel #5
0
def remove_thread(thread_id):
    thread_query = SINGLE_THREAD_QUERY_TEMPLATE.format(thread_id)
    json_thread = get_single_json_entity(thread_query)
    if not json_thread:
        return error_response(404)
    if token_auth.current_user().id != json_thread['creator_id']:
        abort(403)

    delete_thread_query = f"""
    UPDATE thread SET deleted = TRUE WHERE thread.id = '{thread_id}';
    UPDATE post SET deleted = TRUE, deleted_by_thread = TRUE 
    WHERE post.thread_id = '{thread_id}' AND post.deleted = FALSE
    """
    database.session.execute(delete_thread_query)
    database.session.commit()
    response = jsonify({'status': 'OK'})
    return response
Beispiel #6
0
def restore_post():
    app.logger.debug(f'Receive request: {request.data}')
    request_data = request.get_json() or {}
    if 'post_id' not in request_data:
        return bad_request('must include a post id')

    post_id = request_data['post_id']
    deleted_post_query = f"""
    SELECT
    post.id, post.text, post.creation_timestamp, post.user_id, post.deleted,
    post.deleted_by_thread
    FROM post WHERE post.id = '{post_id}'
    """
    query_result_proxy = database.session.execute(deleted_post_query)
    row_proxies = [r for r in query_result_proxy]
    if not row_proxies:
        return bad_request(f'can not restore the post with id {post_id}')

    json_post = {k: v for k, v in row_proxies[0].items()}
    if token_auth.current_user().id != json_post['user_id']:
        abort(403)

    if not json_post['deleted']:
        return bad_request(f'The post with id {post_id} is not deleted')

    if json_post['deleted_by_thread']:
        return bad_request(
            'Can not restore the post because it belongs to deleted thread.')

    restore_post_query = f"""
    UPDATE post SET deleted = FALSE WHERE post.id = '{post_id}'
    """
    database.session.execute(restore_post_query)
    database.session.commit()
    response = jsonify({'status': 'OK'})
    response.headers['Location'] = url_for('get_post', post_id=post_id)
    response.status_code = 201
    return response
Beispiel #7
0
def restore_thread():
    app.logger.debug(f'Receive request: {request.data}')
    request_data = request.get_json() or {}
    if 'thread_id' not in request_data:
        return bad_request('must include a thread_id')

    thread_id = request_data['thread_id']
    deleted_thread_query = f"""
    SELECT
    thread.id, thread.name, thread.short_name, thread.creator_id,
    thread.creation_timestamp, thread.creator_id, thread.text, 
    thread.forum_id, thread.deleted
    FROM thread WHERE thread.id = '{thread_id}'
    """
    query_result_proxy = database.session.execute(deleted_thread_query)
    row_proxies = [r for r in query_result_proxy]
    if not row_proxies:
        return bad_request(f'can not restore the thread with id {thread_id}')

    json_thread = {k: v for k, v in row_proxies[0].items()}
    if token_auth.current_user().id != json_thread['creator_id']:
        abort(403)

    if not json_thread['deleted']:
        return bad_request(f'The thread with id {thread_id} is not deleted')

    restore_thread_query = f"""
    UPDATE thread SET deleted = FALSE WHERE thread.id = '{thread_id}';
    UPDATE post SET deleted = FALSE, deleted_by_thread = FALSE 
    WHERE post.thread_id = '{thread_id}' AND post.deleted_by_thread = TRUE
    """
    database.session.execute(restore_thread_query)
    database.session.commit()
    response = jsonify({'status': 'OK'})
    response.headers['Location'] = url_for('get_thread', thread_id=thread_id)
    response.status_code = 201
    return response
Beispiel #8
0
def update_user(user_id):
    if token_auth.current_user().id != user_id:
        abort(403)
    query = A_USER_QUERY_TEMPLATE.format('id', user_id)
    json_user = get_single_json_entity(query)
    if not json_user:
        return error_response(404)
    request_data = request.get_json() or {}

    mutable_field_names = ['username', 'email', 'common_name']
    fields_to_update = {
        k: v for k, v in request_data.items() if k in mutable_field_names
    }
    if not fields_to_update:
        return bad_request('must include username, email or common_name')

    if 'username' in fields_to_update:
        name_query = A_USER_QUERY_TEMPLATE.format(
            'username',
            request_data['username']
        )
        query_result_proxy = database.session.execute(name_query)
        new_username_is_not_unique = bool([r for r in query_result_proxy])
        if new_username_is_not_unique:
            return bad_request(f'please use a different username')

    update_query_template = "UPDATE users SET {} WHERE users.id = {}"
    updating_set = ','.join(
        [f"{f} = '{v}'" for f, v in fields_to_update.items()]
    )
    update_query = update_query_template.format(updating_set, user_id)
    database.session.execute(update_query)
    query = FULL_USER_QUERY_TEMPLATE.format(user_id)
    updated_user = get_single_json_entity(query)
    database.session.commit()
    return jsonify(updated_user)