def admin_reviewers_delete(token_info, id):
    # check if the logged in user is in the reviewers db
    is_reviewer = adminutils.check_if_superuser(token_info["login"])

    if not is_reviewer:
        msg = {
            "reason": "The logged0in user should be an administrator",
            "error": "Not Authorized: " + request.url,
        }
        msg_json = jsonutils.create_log_json("Contribution Admin ", "GET", msg)
        logging.error("Contribution Admin GET " + json.dumps(msg_json))
        return rs_handlers.not_authorized(msg_json)

    resp = coll_reviewer.delete_one({cfg.FIELD_OBJECTID: ObjectId(id)})
    if resp.deleted_count > 0:
        msg = {"id": str(id)}
        msg_json = jsonutils.create_log_json("Contribution Admin ", "DELETE",
                                             msg)
        logging.info("Contribution Admin DELETE " + json.dumps(msg_json))
        return rs_handlers.entry_deleted('ID', id)
    else:
        msg = {
            "reason": "There is no reviewer with given id: " + str(id),
            "error": "Not Found: " + request.url,
        }
        msg_json = jsonutils.create_log_json("Contribution Admin ", "DELETE",
                                             msg)
        logging.info("Contribution Admin DELETE " + json.dumps(msg_json))
        return rs_handlers.not_found(msg_json)
예제 #2
0
def post():
    auth_middleware.authorize(auth_middleware.ROKWIRE_EVENT_WRITE_GROUPS)
    req_data = request.get_json(force=True)

    if not query_params.required_check(req_data):
        abort(400)
    try:
        req_data = query_params.formate_datetime(req_data)
        req_data = query_params.formate_location(req_data)
        req_data = query_params.formate_category(req_data)
    except Exception as ex:
        __logger.exception(ex)
        abort(400)

    try:
        db = get_db()
        event_id = db['events'].insert(req_data)
        msg = "[POST]: event record created: id = %s" % str(event_id)
        if req_data is not None:
            msg_json = jsonutils.create_log_json("Events", "POST", req_data)
        else:
            msg_json = jsonutils.create_log_json("Events", "POST", {})
        __logger.info("POST " + json.dumps(msg_json))
    except Exception as ex:
        __logger.exception(ex)
        abort(500)

    return success_response(201, msg, str(event_id))
예제 #3
0
def pii_get(pid=None):
    # Get ID Token data from global context variable.
    auth_resp = g.user_token_data

    data_list, is_objectid, is_error, resp = get_data_list_pid(pid)
    if is_error:
        return resp

    auth_pass = check_id(auth_resp, data_list[0])

    if not (auth_pass):
        msg = {
            "reason": "The user info in id token and db are not matching.",
            "error": "Authorization Failed."
        }
        msg_json = jsonutils.create_log_json("PII", "GET", msg)
        logging.error("PII GET " + json.dumps(msg_json))
        return jsonutils.create_auth_fail_message()

    # remove fileDescriptors from db_data
    data_list = jsonutils.remove_file_descriptor_from_data_list(data_list)
    out_json = mongoutils.construct_json_from_query_list(data_list[0])
    msg_json = jsonutils.create_log_json("PII", "GET", data_list[0], 'pii')
    logging.info("PII GET " + json.dumps(msg_json))
    return out_json
def delete(token_info, id):
    login_id, is_login = otherutils.get_login(token_info)
    data_list, is_objectid, is_error, resp = otherutils.get_data_list(
        id, login_id, is_login, coll_contribution)

    if is_error:
        return resp

    contribution_admins = data_list[0]['contributionAdmins']

    # check if the logged in user's login is included in contribution admin list
    is_admin_user = otherutils.check_login_admin(token_info["login"],
                                                 contribution_admins)
    if not is_admin_user:
        msg = {
            "reason": "Contribution admin list must contain logged in user",
            "error": "Bad Request: " + request.url,
        }
        msg_json = jsonutils.create_log_json("Contribution", "POST", msg)
        logging.error("Contribution POST " + json.dumps(msg_json))
        return rs_handlers.bad_request(msg_json)

    if (is_objectid):
        coll_contribution.delete_one({cfg.FIELD_OBJECTID: ObjectId(id)})
        msg = {"id": str(id)}
        msg_json = jsonutils.create_log_json("Contribution", "DELETE", msg)
        logging.info("Contribution DELETE " + json.dumps(msg_json))
        return rs_handlers.entry_deleted('ID', id)
예제 #5
0
def delete(uuid=None):
    data_list, is_objectid, is_error, resp = get_data_list(uuid)
    if is_error:
        return resp

    if (is_objectid):
        mongoutils.db_profile.non_pii_collection.delete_one({cfg.FIELD_OBJECTID: uuid})
        msg = {"uuid": str(uuid)}
        msg_json = jsonutils.create_log_json("Profile", "DELETE", msg)
        logging.info("DELETE " + json.dumps(msg_json))
        return rs_handlers.entry_deleted('uuid', uuid)

    try:
        mongoutils.db_profile.non_pii_collection.delete_one({cfg.FIELD_PROFILE_UUID: uuid})
        msg = {"uuid": str(uuid)}
        msg_json = jsonutils.create_log_json("Profile", "DELETE", msg)
        logging.info("DELETE " + json.dumps(msg_json))
        return rs_handlers.entry_deleted('uuid', uuid)
    except:
        msg = {
            "reason": "Failed to delete. The dataset does not exist: " + str(uuid),
            "error": "Not Found: " + request.url,
        }
        msg_json = jsonutils.create_log_json("Profile", "DELETE", msg)
        logging.error("DELETE " + json.dumps(msg_json))
        return rs_handlers.not_found(msg_json)
def admin_reviewers_post(token_info):
    # this is for adding reviewers to the database
    # only superuser can add the reviewer

    # check if the logged in user is in the administrator
    is_admin = adminutils.check_if_superuser(token_info["login"])

    if not is_admin:
        msg = {
            "reason": "The logged in user should be a superuser",
            "error": "Not Authorized: " + request.url,
        }
        msg_json = jsonutils.create_log_json("Contribution Admin ", "GET", msg)
        logging.error("Contribution Admin GET " + json.dumps(msg_json))
        return rs_handlers.not_authorized(msg_json)

    in_json = request.get_json()
    name = in_json["name"]
    username = in_json["githubUsername"]

    # check if the dataset is existing with given github username
    dataset = mongoutils.get_dataset_from_field(coll_reviewer,
                                                "githubUsername", username)
    if dataset is not None:
        msg = {
            "reason":
            "Github Username in input json already exists in the database: " +
            str(username),
            "error":
            "Bad Request: " + request.url,
        }
        msg_json = jsonutils.create_log_json("Contribution Admin", "POST", msg)
        logging.error("Contribution Admin POST " + json.dumps(msg_json))
        return rs_handlers.bad_request(msg)

    currenttime = datetime.datetime.now()
    currenttime = currenttime.strftime("%Y/%m/%dT%H:%M:%S")
    reviewer_dataset = Reviewer('')
    reviewer_dataset, restjson = datasetutils.update_reviwer_dataset_from_json(
        reviewer_dataset, in_json)
    reviewer_dataset.set_date_created(currenttime)

    dataset, id = mongoutils.insert_dataset_to_mongodb(coll_reviewer,
                                                       reviewer_dataset)

    msg = "new reviewer has been added: " + str(username)
    msg_json = jsonutils.create_log_json("Contribution Admin ", "POST",
                                         {"id": str(id)})
    logging.info("Contribution Admin POST " + json.dumps(msg_json))

    reviewer_id = str(dataset['_id'])

    return rs_handlers.return_id(msg, 'id', reviewer_id)
예제 #7
0
def get_data_list_pid(pid):
    is_error = False
    resp = None

    if pid != None:
        is_objectid = mongoutils.check_if_objectid(pid)

        # query using either non-pii ObjectId or uuid
        if (is_objectid):
            id = ObjectId(pid)
            db_data = mongoutils.query_pii_dataset_by_objectid(id)
        else:
            db_data = mongoutils.query_pii_dataset(cfg.FIELD_PID, pid)

        data_list = list(db_data)
        if len(data_list) > 1:
            msg = {
                "reason": "There are more than 1 pii record: " + str(pid),
                "error": "Bad Request: " + request.url,
            }
            msg_json = jsonutils.create_log_json("PII", "GET", msg)
            logging.error("PII GET " + json.dumps(msg_json))
            is_error = True
            resp = rs_handlers.bad_request(msg_json)

            return None, None, is_error, resp

        if len(data_list) == 0:
            msg = {
                "reason": "There is no pii record for the pid: " + str(pid),
                "error": "Not Found: " + request.url,
            }
            msg_json = jsonutils.create_log_json("PII", "GET", msg)
            logging.error("PII GET " + json.dumps(msg_json))
            is_error = True
            resp = rs_handlers.not_found(msg_json)

            return None, None, is_error, resp

        if len(data_list) > 0:
            return data_list, is_objectid, is_error, resp

    else:
        msg = {
            "reason": "Pii dataset does not exist: " + str(pid),
            "error": "Not Found: " + request.url,
        }
        msg_json = jsonutils.create_log_json("PII", "GET", msg)
        logging.error("PII GET " + json.dumps(msg_json))
        is_error = True
        resp = rs_handlers.not_found(msg_json)

        return None, None, is_error, resp
예제 #8
0
def put(event_id):
    auth_middleware.authorize(auth_middleware.ROKWIRE_EVENT_WRITE_GROUPS)

    if not ObjectId.is_valid(event_id):
        abort(400)
    req_data = request.get_json(force=True)

    if not query_params.required_check(req_data):
        abort(400)
    try:
        req_data = query_params.formate_datetime(req_data)
        req_data = query_params.formate_location(req_data)
        req_data = query_params.formate_category(req_data)
    except Exception as ex:
        __logger.exception(ex)
        abort(400)

    group_memberships = list()
    try:
        _, group_memberships = get_group_memberships()
    except Exception as ex:
        __logger.exception(ex)
        abort(500)
    db = None
    event = None
    try:
        db = get_db()
        event = db['events'].find_one({'_id': ObjectId(event_id)}, {'_id': 0})
    except Exception as ex:
        __logger.exception(ex)
        abort(500)

    # If this is a group event, apply group authorization. Regular events can proceed like before.
    if not check_group_event_admin_access(event, group_memberships):
        abort(401)

    try:
        status = db['events'].replace_one({'_id': ObjectId(event_id)},
                                          req_data)
        msg = "[PUT]: event id %s, nUpdate = %d " % (str(event_id),
                                                     status.modified_count)
        if req_data is not None:
            msg_json = jsonutils.create_log_json("Events", "PUT", req_data)
        else:
            msg_json = jsonutils.create_log_json("Events", "PUT", {})
        __logger.info("PUT " + json.dumps(msg_json))
    except Exception as ex:
        __logger.exception(ex)
        abort(500)

    return success_response(200, msg, str(event_id))
def search(token_info=None, name=None):
    # args = request.args
    is_list = False
    query = dict()

    login_id, is_login = otherutils.get_login(token_info)

    # building query parematers
    query = query_params.format_query_status_login(query, login_id, is_login)

    # if there is no query word, it is simply requesting list of all records
    if name is None:
        is_list = True

    if is_list:
        # return the list of all records
        out_json = mongoutils.get_result(coll_contribution, query)
    else:
        try:
            query = query_params.format_query_contribution(name, query)
        except Exception as ex:
            msg = {
                "reason": "The query is wrong or bad argument",
                "error": "Bad Request: " + request.url,
            }
            msg_json = jsonutils.create_log_json("Contribution", "SEARCH", msg)
            logging.error("Contribution SEARCH " + json.dumps(msg_json))
            return rs_handlers.bad_request(msg_json)

        try:
            # get result using query
            out_json = mongoutils.get_result(coll_contribution, query)
        except Exception as ex:
            msg = {
                "reason": "The query is wrong or bad argument",
                "error": "Bad Request: " + request.url,
            }
            msg_json = jsonutils.create_log_json("Contribution", "SEARCH", msg)
            logging.error("Contribution SEARCH " + json.dumps(msg_json))
            return rs_handlers.bad_request(msg_json)

    if out_json is None:
        out_json = []

    msg = {"search": "Contribution search performed with : " + str(name)}
    msg_json = jsonutils.create_log_json("Contribution", "SEARCH", msg)
    logging.info("Contribution SEARCH " + json.dumps(msg))

    return out_json
예제 #10
0
def construct_talent(in_json):
    is_required_field = True
    error_required = ""
    try:
        error_required = "name"
        name = in_json["name"]
        error_required = "shortDescription"
        description = in_json["shortDescription"]
    except:
        msg = {
            "reason":
            "Some of the required field in talent is not provided: " +
            str(error_required),
            "error":
            "Bad Request: " + request.url,
        }
        msg_json = jsonutils.create_log_json("Contribution", "POST", msg)
        logging.error("Contribution POST " + json.dumps(msg_json))
        return None, None, msg_json

    # new installation of the app
    talent_dataset = Talent('')
    talent_dataset, restjson = datasetutils.update_talent_dataset_from_json(
        talent_dataset, in_json)

    return talent_dataset, restjson, None
예제 #11
0
def post():
    is_new_install = True

    # check if uuid is in there otherwise it is either a first installation
    try:
        in_json = request.get_json()
        non_pii_uuid = in_json["uuid"]
        # even if there is non_pii_uuid is in the input json, it could be a new one
        # check if the dataset is existing with given uuid
        dataset = mongoutils.get_non_pii_dataset_from_field(
            cfg.FIELD_PROFILE_UUID, non_pii_uuid)
        if dataset is not None:
            is_new_install = False
            msg = {
                "reason":
                "UUID in input json already exists in the database: " +
                str(non_pii_uuid),
                "error":
                "Bad Request: " + request.url,
            }
            msg_json = jsonutils.create_log_json("Profile", "POST", msg)
            logging.error("POST " + json.dumps(json.loads(msg_json)))
            return rs_handlers.bad_request(msg)
    except:
        pass

    if is_new_install:
        # new installation of the app
        currenttime = otherutils.get_current_time_utc()
        non_pii_dataset = NonPiiData('')
        non_pii_uuid = str(uuidlib.uuid4())
        non_pii_dataset.set_uuid(non_pii_uuid)
        non_pii_dataset.set_creation_date(currenttime)
        non_pii_dataset.set_last_modified_date(currenttime)
        dataset, id = mongoutils.insert_non_pii_dataset_to_mongodb(
            non_pii_dataset)
        profile_uuid = dataset["uuid"]

        # use this if it needs to return actual dataset
        dataset = jsonutils.remove_objectid_from_dataset(dataset)
        # out_json = mongoutils.construct_json_from_query_list(dataset)
        msg = "new profile with new uuid has been created: " + str(
            profile_uuid)
        msg_json = jsonutils.create_log_json("Profile", "POST", dataset)
        logging.info("POST " + json.dumps(msg_json))

        return rs_handlers.return_id(msg, 'uuid', profile_uuid)
def talents_get(token_info=None, id=None, talent_id=None):
    talent_datasets = talents_search(token_info, id)

    # when the talent_datasets is an error response
    if isinstance(talent_datasets, wrappers.Response):
        return talent_datasets

    # otherwise it means that the talent_datasets contains the correct content.

    # search talent that is the correct id
    talent_index = 0
    talent = None

    # there shouldn't be empty list of talent_datasets
    # since it has to be filtered in talents_search() already
    for talent_dataset in talent_datasets:
        # this will make an error if there is no id field in talent dataset
        # however, this shouldn't be happen because it is required in connexion
        if talent_dataset["id"] == talent_id:
            talent = talent_dataset
            talent_index += 1

    if talent_index > 1:
        msg = {
            "reason":
            "There is more than one Capabilities with given talent id: " +
            str(talent_id),
            "error":
            "Bad Request: " + request.url,
        }
        msg_json = jsonutils.create_log_json("Talent", "GET", msg)
        logging.error("Talent GET " + json.dumps(msg_json))
        return rs_handlers.bad_request(msg_json)
    elif talent_index == 0:
        msg = {
            "reason":
            "There is no Capability with given capability id: " +
            str(talent_id),
            "error":
            "Not Found: " + request.url,
        }
        msg_json = jsonutils.create_log_json("Capability", "GET", msg)
        logging.error("Capability GET " + json.dumps(msg_json))
        return rs_handlers.not_found(msg_json)
    else:
        return talent
예제 #13
0
def delete(event_id):
    auth_middleware.authorize(auth_middleware.ROKWIRE_EVENT_WRITE_GROUPS)

    if not ObjectId.is_valid(event_id):
        abort(400)

    group_memberships = list()
    try:
        _, group_memberships = get_group_memberships()
    except Exception as ex:
        __logger.exception(ex)
        abort(500)

    db = None
    event = None
    try:
        db = get_db()
        event = db['events'].find_one({'_id': ObjectId(event_id)}, {'_id': 0})
    except Exception as ex:
        __logger.exception(ex)
        abort(500)

    if not check_group_event_admin_access(event, group_memberships):
        abort(401)

    try:
        db = get_db()
        req_data = db['events'].find_one({'_id': ObjectId(event_id)},
                                         {'_id': 0})
        status = db['events'].delete_one({'_id': ObjectId(event_id)})
        msg = "[DELETE]: event id %s, nDelete = %d " % (str(event_id),
                                                        status.deleted_count)
        if req_data is not None:
            msg_json = jsonutils.create_log_json("Events", "DELETE", req_data)
        else:
            msg_json = jsonutils.create_log_json("Events", "DELETE", {})
        __logger.info("DELETE " + json.dumps(msg_json))
    except Exception as ex:
        __logger.exception(ex)
        abort(500)
    if status.deleted_count == 0:
        abort(404)
    return success_response(202, msg, str(event_id))
예제 #14
0
def pii_delete(pid=None):
    # Get ID Token data from global context variable.
    auth_resp = g.user_token_data

    data_list, is_objectid, is_error, resp = get_data_list_pid(pid)
    if is_error:
        return resp

    auth_pass = check_id(auth_resp, data_list[0])

    if not (auth_pass):
        msg = {
            "reason": "The user info in id token and db are not matching.",
            "error": "Authorization Failed."
        }
        msg_json = jsonutils.create_log_json("PII", "DELETE", msg)
        logging.error("PII DELETE " + json.dumps(msg_json))
        return jsonutils.create_auth_fail_message()

    try:
        if (is_objectid):
            id = ObjectId(pid)
            mongoutils.db_pii.pii_collection.delete_one(
                {cfg.FIELD_OBJECTID: id})
            msg = {"pid": str(pid)}
            msg_json = jsonutils.create_log_json("PII", "DELETE", msg)
            logging.info("PII DELETE " + json.dumps(msg_json))
            return rs_handlers.entry_deleted('ObjectID', pid)
        else:
            mongoutils.db_pii.pii_collection.delete_one({cfg.FIELD_PID: pid})
            msg = {"pid": str(pid)}
            msg_json = jsonutils.create_log_json("PII", "DELETE", msg)
            logging.info("PII DELETE " + json.dumps(msg_json))
            return rs_handlers.entry_deleted('pid', pid)
    except:
        msg = {
            "reason": "Failed to deleted pii. not found: " + str(pid),
            "error": "Not Found: " + request.url,
        }
        msg_json = jsonutils.create_log_json("PII", "DELETE", msg)
        logging.info("PII DELETE " + json.dumps(msg_json))
        return rs_handlers.not_found(msg_json)
예제 #15
0
def get(uuid=None):
    data_list, is_objectid, is_error, resp = get_data_list(uuid)
    if is_error:
        return resp
    out_json = jsonutils.remove_null_subcategory(data_list[0])
    msg_json = jsonutils.create_log_json("Profile", "GET", copy.copy(out_json))
    logging.info("GET " + json.dumps(msg_json))

    out_json = mongoutils.construct_json_from_query_list(out_json)

    return out_json
예제 #16
0
def device_data_search():
    args = request.args
    query = dict()
    try:
        query = query_params.format_query_device_data(args, query)
    except Exception as ex:
        msg = {
            "reason": "The query is wrong or bad argument " + str(args),
            "error": "Bad Request: " + request.url,
        }
        msg_json = jsonutils.create_log_json("Device Data", "SEARCH", msg)
        logging.error("Device Data SEARCH " + json.dumps(msg_json))
        return rs_handlers.bad_request(msg_json)

    try:
        out_json = mongoutils.get_profile_result(query)
    except Exception as ex:
        msg = {
            "reason": "The query is wrong or bad argument " + str(args),
            "error": "Bad Request: " + request.url,
        }
        msg_json = jsonutils.create_log_json("Device Data", "SEARCH", msg)
        logging.error("Device Data SEARCH " + json.dumps(msg_json))
        return rs_handlers.bad_request(msg_json)

    if out_json is None:
        out_json = []
    else:
        # TODO if the out_json only need to contain device token and uuid, perform following.
        #  Otherwise just leave out_json as it is
        out_json = build_favorites_eventid_result(out_json)

    msg = {
        "search":
        "Device Data search performed with arguments of : " + str(args),
        "result": out_json,
    }
    msg_json = jsonutils.create_log_json("Device Data", "SEARCH", msg)
    logging.info("Device Data SEARCH " + json.dumps(msg))

    return out_json
def get(token_info=None, id=None):
    login_id, is_login = otherutils.get_login(token_info)

    data_list, is_objectid, is_error, resp = otherutils.get_data_list(
        id, login_id, is_login, coll_contribution)

    # if getting data process failed, that is is_error is true, return error reponse
    if is_error:
        return resp
    jsonutils.convert_obejctid_from_dataset_json(data_list[0])
    out_json = mongoutils.construct_json_from_query_list(data_list[0])
    msg_json = jsonutils.create_log_json("Contribution", "GET",
                                         {"id": str(id)})
    logging.info("Contribution GET " +
                 json.dumps(jsonutils.remove_objectid_from_dataset(msg_json)))

    return out_json
def admin_reviewers_search(token_info):
    reviewers = []

    # check if the logged in user is a administrator
    is_admin = adminutils.check_if_superuser(token_info["login"])

    if not is_admin:
        msg = {
            "reason": "The logged-in user should be an administrator",
            "error": "Not Authorized: " + request.url,
        }
        msg_json = jsonutils.create_log_json("Contribution Admin ", "GET", msg)
        logging.error("Contribution Admin GET " + json.dumps(msg_json))
        return rs_handlers.not_authorized(msg_json)

    list_reviewers = mongoutils.list_reviewers()

    if list_reviewers is not None:
        reviewers = list_reviewers

    return reviewers
예제 #19
0
def pii_post():
    # msg = {'message': 'POST info for PII:'}
    # resp = jsonify(msg)
    # resp.status_code = 200
    # logging.debug("POST " + json.dumps(msg))
    #
    # return resp

    # Get ID Token data from global context variable.
    auth_resp = g.user_token_data
    tk_uin, tk_firstname, tk_lastname, tk_email, tk_phone, tk_is_uin, tk_is_phone = tokenutils.get_data_from_token(
        auth_resp)

    is_new_entry = False
    # Todo following variable should be revived if the email or phone number can get updated
    # auth_pass = False

    try:
        in_json = request.get_json()
    except Exception as ex:
        msg = {
            "reason": "Json format error.",
            "error": "Bad Request: " + request.url,
        }
        msg_json = jsonutils.create_log_json("PII", "POST", msg)
        logging.error("PII POST " + json.dumps(msg_json))
        return rs_handlers.bad_request(msg_json)

    # get uuid, if failed it is a bad request
    try:
        non_pii_uuid = in_json[cfg.FIELD_PROFILE_UUID]
        if isinstance(non_pii_uuid, list) == False:
            # # this is an error routine when it is not a list
            # # for now, this should be commented out because the endpoint will accept both string and list
            # # after chaning the app only send uuid as a list, following lines should be revived
            # msg = {
            #     "reason": "The uuid information is not a list.",
            #     "error": "Json format error."
            # }
            # msg_json = jsonutils.create_log_json("PII", "POST", msg)
            # logging.error("PII POST " + json.dumps(msg_json))
            # return rs_handlers.bad_request(msg_json)

            # if non_pii_uuid is not a list,
            # we assume that it is a single string uuid object so convert this to a list with single item
            tmp_list = []
            tmp_list.append(non_pii_uuid)
            non_pii_uuid = tmp_list
    except Exception as ex:
        msg = {
            "reason": "uuid not supplied.",
            "error": "Bad Request: " + request.url,
        }
        msg_json = jsonutils.create_log_json("PII", "POST", msg)
        logging.error("PII POST " + json.dumps(msg_json))
        return rs_handlers.bad_request(msg_json)

    # get non_pii_uuid value from the list
    if len(non_pii_uuid) > 0:
        non_pii_uuid = non_pii_uuid[0]
    else:
        msg = {
            "reason": "uuid list is empty.",
            "error": "Bad Request: " + request.url,
        }
        msg_json = jsonutils.create_log_json("PII", "POST", msg)
        logging.error("PII POST " + json.dumps(msg_json))
        return rs_handlers.bad_request(msg_json)

    # check if it is a new record or existing record
    try:
        pid = in_json[cfg.FIELD_PID]
        dataset = mongoutils.get_pii_dataset_from_field(cfg.FIELD_PROFILE_UUID, pid)

        # if it is an existing entry, then check if the information in db matches with the id token
        auth_pass = check_auth(dataset, tk_uin, tk_phone, tk_is_uin, tk_is_phone)
    except:
        dataset = None
        is_new_entry = True

    # check if the email already exists
    if tk_is_uin:
        try:
            dataset = mongoutils.get_pii_dataset_from_field('uin', tk_uin)
            # if there is a dataset, it means that the email is existing in the database
            if dataset is not None:
                # ToDo Following lines will be commented out due to the following assumption
                # that the email in the database doesn't get updated so, no change in email.
                # However, if there is email update available, the following part should be revived.
                # # check if the id token and db info matches
                # if not (auth_pass):
                #     msg = {
                #         "reason": "The user info in id token and db are not matching.",
                #         "error": "Authorization Failed."
                #     }
                #     msg_json = jsonutils.create_log_json("PII", "POST", msg)
                #     self.logger.error("PII POST " + json.dumps(msg_json))
                #     return jsonutils.create_auth_fail_message()
                #
                # if not (auth_pass):
                #     msg = {
                #         "reason": "The user info in id token and db are not matching.",
                #         "error": "Authorization Failed."
                #     }
                #     msg_json = jsonutils.create_log_json("PII", "POST", msg)
                #     self.logger.error("PII POST " + json.dumps(msg_json))
                #     return jsonutils.create_auth_fail_message()

                pid = dataset.get_pid()
                non_pii_uuid_from_dataset = dataset.uuid
                dataset = append_non_pii_uuid(non_pii_uuid, non_pii_uuid_from_dataset, dataset)
                currenttime = otherutils.get_current_time_utc()
                dataset.set_last_modified_date(currenttime)
                result, pii_dataset = mongoutils.update_pii_dataset_in_mongo_by_field(cfg.FIELD_PID, pid, dataset)
                msg = {
                    "reason": "UIN already exists: " + str(pid),
                    "warning": "UIN already exists: " + request.url,
                }
                msg_json = jsonutils.create_log_json("PII", "POST", msg)
                logging.warning("PII POST " + json.dumps(msg_json))
                return rs_handlers.return_id('UIN already exists.', 'pid', pid)
        except:
            return rs_handlers.internal_server_error()

    # check if the phonenumber already exists
    if tk_is_phone:
        try:
            dataset = mongoutils.get_pii_dataset_from_field('phone', tk_phone)

            # ToDo Following lines will be commented out due to the following assumption
            # that the email in the database doesn't get updated so, no change in email.
            # However, if there is email update available, the following part should be revived.
            # check if the id token and db info matches
            # if not (auth_pass):
            #     auth_pass = self.check_auth(dataset, tk_uin, tk_phone, tk_is_uin, tk_is_phone)
            #
            # if not (auth_pass):
            #     msg = {
            #         "reason": "The user info in id token and db are not matching.",
            #         "error": "Authorization Failed."
            #     }
            #     msg_json = jsonutils.create_log_json("PII", "POST", msg)
            #     self.logger.error("PII POST " + json.dumps(msg_json))
            #     return jsonutils.create_auth_fail_message()

            if dataset is not None:
                pid = dataset.get_pid()
                non_pii_uuid_from_dataset = dataset.uuid
                dataset = append_non_pii_uuid(non_pii_uuid, non_pii_uuid_from_dataset, dataset)
                currenttime = otherutils.get_current_time_utc()
                dataset.set_last_modified_date(currenttime)
                result, pii_dataset = mongoutils.update_pii_dataset_in_mongo_by_field(cfg.FIELD_PID, pid, dataset)
                msg = {
                    "reason": "Phone number already exists: " + str(pid),
                    "warning": "Phone number already exists: " + request.url,
                }
                msg_json = jsonutils.create_log_json("PII", "POST", msg)
                logging.warning("PII POST " + json.dumps(msg_json))
                return rs_handlers.return_id('Phone number already exists.', 'pid', pid)
        except:
            return rs_handlers.internal_server_error()

    if dataset is not None:
        is_new_entry = False

    pii_dataset = PiiData(in_json)

    if is_new_entry:
        # insert new pii_dataset
        currenttime = otherutils.get_current_time_utc()
        pid = str(uuidlib.uuid4())
        pii_dataset.set_pid(pid)
        non_pii_uuid_from_dataset = []
        non_pii_uuid_from_dataset.append(non_pii_uuid)
        pii_dataset.set_uuid(non_pii_uuid_from_dataset)
        pii_dataset.set_creation_date(currenttime)
        pii_dataset.set_last_modified_date(currenttime)

        # to check if there is testResultsConsent and update modified date
        try:
            if in_json["testResultsConsent"]:
                pii_dataset = update_test_results_consent(pii_dataset)
        except:
            pass

        # update dataset from id token info. Currently, only UIN and phone number are considered verified information and hence gets precedence through ID Token validation / parsing.
        # if tk_firstname is not None:
        #     pii_dataset.set_firstname(tk_firstname)
        # if tk_lastname is not None:
        #     pii_dataset.set_lastname(tk_lastname)
        # if tk_email is not None:
        #     pii_dataset.set_email(tk_email)
        if tk_phone is not None:
            pii_dataset.set_phone(tk_phone)
        if tk_uin is not None:
            pii_dataset.set_uin(tk_uin)
        pii_dataset = mongoutils.insert_pii_dataset_to_mongodb(pii_dataset)

        if pii_dataset is None:
            msg = {
                "reason": "Failed to update profile uuid into pii dataset: " + str(pid),
                "error": "Not Implemented: " + request.url,
            }
            msg_json = jsonutils.create_log_json("PII", "POST", msg)
            logging.error("PII POST " + json.dumps(msg_json))
            return rs_handlers.not_implemented(msg_json)

        msg = "Pii data has been posted with : " + str(pid)
        msg_json = jsonutils.create_log_json("PII", "POST", jsonutils.remove_objectid_from_dataset(pii_dataset), 'pii')
        logging.info("PII POST " + json.dumps(msg_json))
        return rs_handlers.return_id(msg, 'pid', pid)
    else:
        msg = {
            "reason": "The request is wrong or the entry already exists: " + str(pid),
            "error": "Bad Request: " + request.url,
        }
        msg_json = jsonutils.create_log_json("PII", "POST", msg)
        logging.error("PII POST " + json.dumps(msg_json))
        return rs_handlers.bad_request(msg_json)
def get_data_list(name, login_id, is_login, coll_contribution):
    resp = None
    is_error = False
    is_unauthorized = False

    if name != None:
        is_objectid = mongoutils.check_if_objectid(name)

        # query using ObjectId or name
        if (is_objectid):  # when it the query is using object id
            id = ObjectId(name)
            if (is_login):
                # when user token provided
                db_data = mongoutils.query_dataset_by_objectid(
                    coll_contribution, id, login_id, is_login)
                data_list = list(db_data)
            else:
                # check when there is no user login that means apikey used
                db_data = mongoutils.query_dataset_by_objectid_no_status(
                    coll_contribution, id)
                data_list = list(db_data)
                # if there is a result, it must check the status
                # because only published one will be provide to apikey
                if len(data_list) > 0:
                    # check if the status is in the record
                    if "status" not in data_list[0]:
                        msg = {
                            "reason":
                            "Status is not in the dataset " + str(name),
                            "error": "Not Authorized: " + request.url,
                        }
                        msg_json = jsonutils.create_log_json(
                            "Contribution", "GET", msg)
                        logging.error("Contribution GET " +
                                      json.dumps(msg_json))
                        resp = rs_handlers.not_authorized(msg_json)
                        return data_list, is_objectid, True, resp
                    # if there is status in the record, check the value for status
                    status = data_list[0]["status"]
                    if status != "Published":
                        msg = {
                            "reason":
                            "Not authorized to view the contribution dataset with given id:"
                            + str(name),
                            "error":
                            "Not Authorized: " + request.url,
                        }
                        msg_json = jsonutils.create_log_json(
                            "Contribution", "GET", msg)
                        logging.error("Contribution GET " +
                                      json.dumps(msg_json))
                        resp = rs_handlers.not_authorized(msg_json)
                        return data_list, is_objectid, True, resp
            # if there are more than one result it should be something wrong
            # because there should be only one record with given objectid
            if len(data_list) > 1:
                msg = {
                    "reason":
                    "There are more than 1 contribution record: " + str(name),
                    "error":
                    "Bad Request: " + request.url,
                }
                msg_json = jsonutils.create_log_json("Contribution", "GET",
                                                     msg)
                logging.error("Contribution GET " + json.dumps(msg_json))
                is_error = True
                resp = rs_handlers.bad_request(msg_json)
        else:  # when the query is using the actual name not object id
            if (is_login):  # when using github auth
                db_data = mongoutils.query_dataset(coll_contribution,
                                                   cfg.FIELD_NAME, name,
                                                   login_id, is_login)
                data_list = list(db_data)
            else:  # when using apikey auth
                db_data = mongoutils.query_dataset_no_status(
                    coll_contribution, cfg.FIELD_NAME, name)
                tmp_data_list = list(db_data)
                data_list = []
                # check only published ones to apikey. The result can be multiple unlike object id query
                for data in tmp_data_list:
                    if "status" in data:
                        status = data["status"]
                        if status == "Published":
                            data_list.append(data)
                        else:
                            is_unauthorized = True
        # when there is no result
        if len(data_list) == 0:
            if is_unauthorized:
                msg = {
                    "reason":
                    "Not authorized to view the contribution dataset with given id:"
                    + str(name),
                    "error":
                    "Not Authorized: " + request.url,
                }
                msg_json = jsonutils.create_log_json("Contribution", "GET",
                                                     msg)
                logging.error("Contribution GET " + json.dumps(msg_json))
                is_error = True
                resp = rs_handlers.not_authorized(msg_json)
            else:
                msg = {
                    "reason": "There is no contribution record: " + str(name),
                    "error": "Not Found: " + request.url,
                }
                msg_json = jsonutils.create_log_json("Contribution", "GET",
                                                     msg)
                logging.error("Contribution GET " + json.dumps(msg_json))
                is_error = True
                resp = rs_handlers.not_found(msg_json)

        return data_list, is_objectid, is_error, resp

    else:
        msg = {
            "reason": "The contribution does not exist: " + str(name),
            "error": "Not Found: " + request.url,
        }
        msg_json = jsonutils.create_log_json("Contribution", "GET", msg)
        logging.error("Contribution GET " + json.dumps(msg_json))
        resp = rs_handlers.not_found(msg_json)

    return None, None, True, resp
def put(token_info, id):
    try:
        in_json = request.get_json()
    except Exception as ex:
        msg = {
            "reason": "Json format error: " + str(id),
            "error": "Bad Request: " + request.url,
        }
        msg_json = jsonutils.create_log_json("Contribution", "PUT", msg)
        logging.error("Contribution PUT " + json.dumps(msg_json))
        return rs_handlers.bad_request(msg_json)
    # check if the given id exists
    contribution_dataset = mongoutils.get_contribution_dataset_from_objectid_no_status(
        coll_contribution, id)

    if contribution_dataset is None:
        msg = {
            "reason":
            "There is no contribution dataset with given id: " + str(id),
            "error": "Not Found: " + request.url,
        }
        msg_json = jsonutils.create_log_json("Contribution", "PUT", msg)
        logging.error("Contribution PUT " + json.dumps(msg_json))
        return rs_handlers.not_found(msg_json)

    # check contribution admins
    contribution_admins = contribution_dataset.contributionAdmins

    # check if the logged in user's login is included in contribution admin list
    is_admin_user = otherutils.check_login_admin(token_info["login"],
                                                 contribution_admins)
    if not is_admin_user:
        msg = {
            "reason": "Contribution admin list must contain logged in user",
            "error": "Not Authorized: " + request.url,
        }
        msg_json = jsonutils.create_log_json("Contribution", "POST", msg)
        logging.error("Contribution POST " + json.dumps(msg_json))
        return rs_handlers.not_authorized(msg_json)

    date_created = contribution_dataset.dateCreated
    contribution_dataset, restjson = datasetutils.update_contribution_dataset_from_json(
        contribution_dataset, in_json)
    currenttime = datetime.datetime.now()
    currenttime = currenttime.strftime("%Y/%m/%dT%H:%M:%S")
    contribution_dataset.set_date_modified(currenttime)
    contribution_dataset.set_date_created(date_created)

    # set capability list
    capability_list = []
    try:
        capability_json = in_json["capabilities"]
        for i in range(len(capability_json)):
            capability, rest_capability_json, msg = modelutils.construct_capability(
                capability_json[i])
            if capability is None:
                return rs_handlers.bad_request(msg)
            # check if the capability id is in uuid format
            is_uuid = otherutils.check_if_uuid(capability.id)
            if not is_uuid:
                msg = {
                    "reason": "Capability id is not in uuid format",
                    "error": "Bad Request: " + request.url,
                }
                msg_json = jsonutils.create_log_json("Contribution", "POST",
                                                     msg)
                logging.error("Contribution POST " + json.dumps(msg_json))
                return rs_handlers.bad_request(msg)
            capability_list.append(capability)
        contribution_dataset.set_capabilities(capability_list)
    except:
        pass

    # set talent list
    talent_list = []
    try:
        talent_json = in_json["talents"]
        for i in range(len(talent_json)):
            talent, rest_talent_json, msg = modelutils.construct_talent(
                talent_json[i])
            if talent is None:
                return rs_handlers.bad_request(msg)
            # check if the talent id is in uuid format
            is_uuid = otherutils.check_if_uuid(talent.id)
            if not is_uuid:
                msg = {
                    "reason": "Talent id is not in uuid format",
                    "error": "Bad Request: " + request.url,
                }
                msg_json = jsonutils.create_log_json("Contribution", "POST",
                                                     msg)
                logging.error("Contribution POST " + json.dumps(msg_json))
                return rs_handlers.bad_request(msg)

            # check required capabilities id format
            if talent.requiredCapabilities is not None:
                required_cap_list = talent.requiredCapabilities
                for capability_json in required_cap_list:
                    capability, rest_capability_json, msg = modelutils.construct_capability(
                        capability_json)
                    is_uuid = otherutils.check_if_uuid(capability.id)
                    if not is_uuid:
                        msg = {
                            "reason":
                            "Capability id in requiredCapabilities is not in uuid format",
                            "error": "Bad Request: " + request.url,
                        }
                        msg_json = jsonutils.create_log_json(
                            "Contribution", "POST", msg)
                        logging.error("Contribution POST " +
                                      json.dumps(msg_json))
                        return rs_handlers.bad_request(msg)

            talent_list.append(talent)
        contribution_dataset.set_talents(talent_list)
    except:
        pass

    result, contribution_dataset = mongoutils.update_dataset_in_mongo_by_objectid(
        coll_contribution, id, contribution_dataset)

    if result is None:
        msg = {
            "reason": "Failed to update contribution dataset: " + str(id),
            "error": "Not Implemented: " + request.url,
        }
        msg_json = jsonutils.create_log_json("Contribution", "PUT", msg)
        logging.error("Contribution PUT " + json.dumps(msg_json))
        return rs_handlers.not_implemented(msg_json)

    out_json = contribution_dataset
    msg_json = jsonutils.create_log_json("Contribution", "PUT",
                                         {"id": str(id)})
    logging.info("Contribution PUT " + json.dumps(msg_json))
    out_json = mongoutils.construct_json_from_query_list(out_json)

    return out_json
def talents_search(token_info=None, id=None):
    login_id, is_login = otherutils.get_login(token_info)

    contribution_dataset, status_code = mongoutils.get_contribution_dataset_from_objectid(
        coll_contribution, id, login_id, is_login)

    if status_code == '200':
        if contribution_dataset is not None:
            talent_dataset = contribution_dataset.get_talents()
            for talent in talent_dataset:
                talent[
                    "contributionAdmins"] = contribution_dataset.contributionAdmins
        else:
            msg = {
                "reason":
                "There is no contribution dataset with given id, "
                "or you don't have privilege to view this: " + str(id),
                "error":
                "Not Authorized: " + request.url,
            }
            msg_json = jsonutils.create_log_json("Talent", "SEARCH", msg)
            logging.error("Talent SEARCH " + json.dumps(msg_json))
            return rs_handlers.not_authorized(msg_json)
    else:
        if status_code == "401":
            msg = {
                "reason":
                "Not authorized to view the contribution dataset with given id: "
                + str(id),
                "error":
                "Not Authorized: " + request.url,
            }
            msg_json = jsonutils.create_log_json("Talent", "SEARCH", msg)
            logging.error("Talent SEARCH " + json.dumps(msg_json))
            return rs_handlers.not_authorized(msg_json)
        elif status_code == '404':
            msg = {
                "reason":
                "There is no contribution dataset with given id: " + str(id),
                "error":
                "Not Found: " + request.url,
            }
            msg_json = jsonutils.create_log_json("Talent", "SEARCH", msg)
            logging.error("Talent SEARCH " + json.dumps(msg_json))
            return rs_handlers.not_found(msg_json)
        else:
            msg = {
                "reason":
                "The query was not successfully performed: " + str(id),
                "error": "Bad Request: " + request.url,
            }
            msg_json = jsonutils.create_log_json("Talent", "SEARCH", msg)
            logging.error("Talent SEARCH " + json.dumps(msg_json))
            return rs_handlers.bad_request(msg_json)

    if talent_dataset is None:
        msg = {
            "reason":
            "There is no Talent with given contribution id: " + str(id),
            "error": "Not Found: " + request.url,
        }
        msg_json = jsonutils.create_log_json("Talent", "GET", msg)
        logging.error("Talent SEARCH " + json.dumps(msg_json))
        return rs_handlers.not_found(msg_json)

    msg = {
        "search":
        "Talent data in the contribution dataset with given id : " + str(id)
    }
    msg_json = jsonutils.create_log_json("Talent", "GET", msg)
    logging.info("Talent GET " + json.dumps(msg))

    return talent_dataset
def alltalentssearch(token_info=None, name=None):
    query = dict()
    is_list = False

    login_id, is_login = otherutils.get_login(token_info)

    query = query_params.format_query_status_login(query, login_id, is_login)

    if name is None:
        is_list = True

    if is_list:
        out_json = mongoutils.get_result(coll_contribution, query)
    else:
        try:
            query = query_params.format_query_talent(name, query)
        except Exception as ex:
            msg = {
                "reason": "The query is wrong or bad argument",
                "error": "Bad Request: " + request.url,
            }
            msg_json = jsonutils.create_log_json("Talent", "SEARCH", msg)
            logging.error("Talent SEARCH " + json.dumps(msg_json))
            return rs_handlers.bad_request(msg_json)

        try:
            out_json = mongoutils.get_result(coll_contribution, query)
        except Exception as ex:
            msg = {
                "reason": "The query is wrong or bad argument",
                "error": "Bad Request: " + request.url,
            }
            msg_json = jsonutils.create_log_json("Talent", "SEARCH", msg)
            logging.error("Talent SEARCH " + json.dumps(msg_json))
            return rs_handlers.bad_request(msg_json)

    return_json = []
    if out_json is None:
        return_json = []
    else:
        if is_list:  # list all
            if isinstance(out_json, list):
                for in_json in out_json:
                    contribution_id = in_json["id"]
                    if in_json['talents'] is not None:
                        for talent in in_json['talents']:
                            talent["contributionId"] = contribution_id
                            return_json.append(talent)
            else:
                contribution_id = out_json["id"]
                talent = out_json['talents']
                talent["contributionId"] = contribution_id
                return_json.append(talent)
        else:  # extract out talent with the given name
            if isinstance(out_json, list):
                for tmp_json in out_json:
                    contribution_id = tmp_json["id"]
                    talents_json = tmp_json["talents"]
                    # TODO this is the case of only 1 args that is name.
                    #  If there are more args this should be updated
                    for tmp_talent_json in talents_json:
                        talent_json = None
                        if tmp_talent_json["name"] == name:
                            talent_json = tmp_talent_json
                            talent_json["contributionId"] = contribution_id
                            return_json.append(talent_json)
            else:
                talents_json = out_json["talents"]
                contribution_id = out_json["id"]
                # TODO this is the case of only 1 args that is name.
                #  If there are more args this should be updated
                for tmp_talent_json in talents_json:
                    talent_json = None
                    if tmp_talent_json["name"] == name:
                        talent_json = tmp_talent_json
                        talent_json["contributionId"] = contribution_id
                        return_json.append(talent_json)
    if is_list:
        msg = {"GET": "Talent list"}
        msg_json = jsonutils.create_log_json("Talent", "GET", msg)
        logging.info("Talent GET " + json.dumps(msg_json))
    else:
        msg = {"search": "Talent search performed with " + str(name)}
        msg_json = jsonutils.create_log_json("Talent", "SEARCH", msg)
        logging.info("Talent SEARCH " + json.dumps(msg_json))

    return return_json
def post(token_info):
    is_new_install = True
    in_json = None

    # check if name is in there otherwise it is either a first installation
    try:
        in_json = request.get_json()
        name = in_json[cfg.FIELD_NAME]
        # check if the dataset is existing with given name
        dataset = mongoutils.get_contribution_dataset_from_field_no_status(
            coll_contribution, cfg.FIELD_NAME, name)
        if dataset is not None:
            is_new_install = False
            msg = {
                "reason":
                "NAME in input json already exists in the database: " +
                str(name),
                "error":
                "Bad Request: " + request.url,
            }
            msg_json = jsonutils.create_log_json("Contribution", "POST", msg)
            logging.error("Contribution POST " + json.dumps(msg_json))
            return rs_handlers.bad_request(msg)
    except:
        pass

    if is_new_install:
        # new installation of the app
        currenttime = datetime.datetime.now()
        currenttime = currenttime.strftime("%Y/%m/%dT%H:%M:%S")
        contribution_dataset = Contribution('')
        contribution_dataset, restjson = datasetutils.update_contribution_dataset_from_json(
            contribution_dataset, in_json)
        contribution_dataset.set_date_created(currenttime)
        contribution_dataset.set_date_modified(currenttime)

        # get contribution admins, if failed it is a bad request
        contribution_admins = in_json['contributionAdmins']

        # get contribution_admins value from the list
        # doing this because connexion's minItems doesn't work, otherwise this is not needed
        if len(contribution_admins) == 0:
            msg = {
                "reason": "Contribution admin list is empty.",
                "error": "Bad Request: " + request.url,
            }
            msg_json = jsonutils.create_log_json("Contribution", "POST", msg)
            logging.error("Contribution POST " + json.dumps(msg_json))
            return rs_handlers.bad_request(msg_json)

        # check if the logged in user's login is included in contribution admin list
        is_admin_user = otherutils.check_login_admin(token_info["login"],
                                                     contribution_admins)
        if not is_admin_user:
            msg = {
                "reason":
                "Contribution admin list must contain logged in user",
                "error": "Bad Request: " + request.url,
            }
            msg_json = jsonutils.create_log_json("Contribution", "POST", msg)
            logging.error("Contribution POST " + json.dumps(msg_json))
            return rs_handlers.bad_request(msg_json)

        # set contributors list
        contributors_list = []
        try:
            contributors_json = in_json["contributors"]
            for i in range(len(contributors_json)):
                contributor, rest_contributor_json, msg = modelutils.construct_contributors(
                    contributors_json[i])
                if contributor is None:
                    return rs_handlers.bad_request(msg)
                contributors_list.append(contributor)
            contribution_dataset.set_contributors(contributors_list)
        except:
            pass

        # set capability list
        capability_list = []
        try:
            capability_json = in_json["capabilities"]
            for i in range(len(capability_json)):
                capability, rest_capability_json, msg = modelutils.construct_capability(
                    capability_json[i])
                if capability is None:
                    return rs_handlers.bad_request(msg)

                # following two lines are for creating id. However, it might not needed for now
                # because catalog will create it and send it to endpoint.
                # If not, use following two lines that commented out
                # capability_id = str(uuidlib.uuid4())
                # capability.set_id(capability_id)

                # check if the capability id is in uuid format
                is_uuid = otherutils.check_if_uuid(capability.id)
                if not is_uuid:
                    msg = {
                        "reason": "Capability id is not in uuid format",
                        "error": "Bad Request: " + request.url,
                    }
                    msg_json = jsonutils.create_log_json(
                        "Contribution", "POST", msg)
                    logging.error("Contribution POST " + json.dumps(msg_json))
                    return rs_handlers.bad_request(msg)
                capability_list.append(capability)
            contribution_dataset.set_capabilities(capability_list)
        except:
            pass

        # set talent list
        talent_list = []
        try:
            talent_json = in_json["talents"]
            for i in range(len(talent_json)):
                talent, rest_talent_json, msg = modelutils.construct_talent(
                    talent_json[i])
                if talent is None:
                    return rs_handlers.bad_request(msg)

                # following two lines are for creating id. However, it might not needed for now
                # because catalog will create it and send it to endpoint.
                # If not, use following two lines that commented out
                # talent_id = str(uuidlib.uuid4())
                # talent.set_id(talent_id)

                # check if the talent id is in uuid format
                is_uuid = otherutils.check_if_uuid(talent.id)
                if not is_uuid:
                    msg = {
                        "reason": "Talent id is not in uuid format",
                        "error": "Bad Request: " + request.url,
                    }
                    msg_json = jsonutils.create_log_json(
                        "Contribution", "POST", msg)
                    logging.error("Contribution POST " + json.dumps(msg_json))
                    return rs_handlers.bad_request(msg)

                # check required capabilities id format
                if talent.requiredCapabilities is not None:
                    required_cap_list = talent.requiredCapabilities
                    for capability_json in required_cap_list:
                        capability, rest_capability_json, msg = modelutils.construct_required_capability(
                            capability_json)
                        is_uuid = otherutils.check_if_uuid(capability.id)
                        if not is_uuid:
                            msg = {
                                "reason":
                                "Capability id in requiredCapabilities is not in uuid format",
                                "error": "Bad Request: " + request.url,
                            }
                            msg_json = jsonutils.create_log_json(
                                "Contribution", "POST", msg)
                            logging.error("Contribution POST " +
                                          json.dumps(msg_json))
                            return rs_handlers.bad_request(msg)
                talent_list.append(talent)
            contribution_dataset.set_talents(talent_list)
        except:
            pass

        # insert contribution dataset
        dataset, id = mongoutils.insert_dataset_to_mongodb(
            coll_contribution, contribution_dataset)
        contribution_name = dataset[cfg.FIELD_NAME]
        contribution_id = str(dataset['_id'])

        # use this if it needs to return actual dataset
        dataset = jsonutils.remove_objectid_from_dataset(dataset)
        # out_json = mongoutils.construct_json_from_query_list(dataset)
        msg = "new contribution has been created: " + str(contribution_name)
        msg_json = jsonutils.create_log_json("Contribution", "POST",
                                             {"id": str(contribution_id)})
        logging.info("Contribution POST " + json.dumps(msg_json))

        return rs_handlers.return_id(msg, 'id', contribution_id)
예제 #25
0
def pii_put(pid=None):
    # Get ID Token data from global context variable.
    auth_resp = g.user_token_data
    tk_uin, tk_firstname, tk_lastname, tk_email, tk_phone, tk_is_uin, tk_is_phone = tokenutils.get_data_from_token(
        auth_resp)

    try:
        in_json = request.get_json()
        # ToDo following lines are commented out for now
        #  but it should be used if the email and phone number get updated
        # # if there is any phone number or email information in input json, they will be removed
        # # since the current policy is not updating the email or phone number
        # # until further decision
        # try:
        #     del in_json["uin"]
        # except:
        #     pass
        # try:
        #     del in_json["phone"]
        # except:
        #     pass

    except Exception as ex:
        msg = {
            "reason": "Json format error: " + str(pid),
            "error": "Bad Request: " + request.url,
        }
        msg_json = jsonutils.create_log_json("PII", "PUT", msg)
        logging.error("PII PUT " + json.dumps(msg_json))
        return rs_handlers.bad_request(msg_json)

    # check if the pid is really existing in the database
    pii_dataset = mongoutils.get_pii_dataset_from_field(cfg.FIELD_PID, pid)

    if pii_dataset == None:
        msg = {
            "reason": "There is no dataset with given pii uuid: " + str(pid),
            "error": "Not Found: " + request.url,
        }
        msg_json = jsonutils.create_log_json("PII", "PUT", msg)
        logging.error("PII PUT " + json.dumps(msg_json))
        return rs_handlers.not_found(msg_json)

    creation_date = pii_dataset.get_creation_date()
    tmp_dataset = json.loads(json.dumps(pii_dataset.__dict__))
    auth_pass = check_id(auth_resp, tmp_dataset)

    if not (auth_pass):
        msg = {
            "reason": "The user info in id token and db are not matching.",
            "error": "Authorization Failed."
        }
        msg_json = jsonutils.create_log_json("PII", "PUT", msg)
        logging.error("PII PUT " + json.dumps(msg_json))
        return jsonutils.create_auth_fail_message()

    # get the current testResultsConset value to see if it is changed
    # if changed, update last modified date after updating pii data
    consent_provided = None
    consent_last_modified = None
    try:
        consent_provided = pii_dataset.testResultsConsent["consentProvided"]
        consent_last_modified = pii_dataset.testResultsConsent["dateModified"]
    except:
        pass
    pii_dataset = datasetutils.update_pii_dataset_from_json(pii_dataset, in_json)
    currenttime = otherutils.get_current_time_utc()

    # if consentProvided value has been changed, update the last modified date
    try:
        if consent_provided != pii_dataset.testResultsConsent['consentProvided']:
            pii_dataset = update_test_results_consent(pii_dataset)
        else: # record the exising modified date that got lost during the json update
            pii_dataset.testResultsConsent['dateModified'] = consent_last_modified
    except:
        pass

    pii_dataset.set_last_modified_date(currenttime)
    # remove creation date field and pid so doesn't get updated
    del pii_dataset.creationDate
    del pii_dataset.pid

    # update pii_dataset's non_pii_uuid
    non_pii_uuid_from_dataset = pii_dataset.get_uuid()
    try:
        non_pii_uuid = in_json[cfg.FIELD_PROFILE_UUID]
        # both non_pii_uuid and non_pii_uuid_from_dataset should be list
        if (type(non_pii_uuid) is not list) or (type(non_pii_uuid_from_dataset) is not list):
            msg = {
                "reason": "The uuid information is not a list.",
                "error": "Json format error."
            }
            msg_json = jsonutils.create_log_json("PII", "PUT", msg)
            logging.error("PII PUT " + json.dumps(msg_json))
            return rs_handlers.bad_request(msg_json)

        pii_dataset.set_uuid(non_pii_uuid)
        # # the following lines can be used for item to item comparison and append when it is needed
        # for i in range(len(non_pii_uuid)):
        #     pii_dataset = append_non_pii_uuid(non_pii_uuid[i], non_pii_uuid_from_dataset, pii_dataset)
    except:
        pass

    # update dataset from id token info. Currently, only UIN and phone number are considered verified information and hence gets precedence through ID Token validation / parsing.
    # if tk_firstname is not None:
    #     pii_dataset.set_firstname(tk_firstname)
    # if tk_lastname is not None:
    #     pii_dataset.set_lastname(tk_lastname)
    # if tk_email is not None:
    #     pii_dataset.set_email(tk_email)
    if tk_phone is not None:
        pii_dataset.set_phone(tk_phone)
    if tk_uin is not None:
        pii_dataset.set_uin(tk_uin)

    result, pii_dataset = mongoutils.update_pii_dataset_in_mongo_by_field(cfg.FIELD_PID, pid,
                                                                          pii_dataset)

    if result is None:
        msg = {
            "reason": "Failed to update non pii uuid into pii dataset: " + str(pid),
            "error": "Not Implemented: " + request.url,
        }
        msg_json = jsonutils.create_log_json("PII", "PUT", msg)
        logging.error("PII PUT " + json.dumps(msg_json))
        return rs_handlers.not_implemented(msg_json)

    # add pid and original creation date to dataset for output json
    try:
        pii_dataset["pid"] = pid
        pii_dataset["creationDate"] = creation_date
    except:
        pass

    pii_dataset = jsonutils.remove_file_descriptor_from_dataset(pii_dataset)
    out_json = mongoutils.construct_json_from_query_list(pii_dataset)
    msg_json = jsonutils.create_log_json("PII", "PUT", jsonutils.remove_objectid_from_dataset(pii_dataset), 'pii')
    logging.info("PII PUT " + json.dumps(msg_json))
    return out_json
예제 #26
0
def core_search(uin=None, phone=None):
    if request.headers.get(
            "ROKWIRE-CORE-BB-API-KEY") != cfg.ROKWIRE_CORE_BB_API_KEY:
        msg = {
            "reason": "Unauthorized",
            "error": "Unauthorized: " + request.url,
        }
        msg_json = jsonutils.create_log_json("CORE PROFILE", "GET", msg)
        logging.error("CORE PROFILE GET " + json.dumps(msg_json))
        return rs_handlers.forbidden(msg_json)

    fields = {}
    if uin:
        fields['uin'] = uin
    if phone:
        fields['phone'] = phone
    if len(fields) == 0:
        msg = {
            "reason": "Must provide uin or phone",
            "error": "Bad Request: " + request.url,
        }
        msg_json = jsonutils.create_log_json("CORE PROFILE", "GET", msg)
        logging.error("CORE PROFILE GET " + json.dumps(msg_json))
        return rs_handlers.bad_request(msg_json)

    if fields != None:
        data_list = mongoutils.get_pii_result(fields)
        if len(data_list) > 1:
            msg = {
                "reason": "There is more than 1 pii record: " + str(fields),
                "error": "There is more than 1 pii record: " + request.url,
            }
            msg_json = jsonutils.create_log_json("CORE PROFILE", "GET", msg)
            logging.error("CORE PROFILE GET " + json.dumps(msg_json))
            return rs_handlers.internal_server_error(msg_json)
        if len(data_list) == 0:
            msg = {"Not Found": str(fields)}
            msg_json = jsonutils.create_log_json("CORE PROFILE", "GET", msg)
            logging.info("CORE PROFILE GET " + json.dumps(msg_json))
            return mongoutils.construct_json_from_query_list({})
    else:
        msg = {
            "reason": "Invalid search: " + str(fields),
            "error": "Bad Request: " + request.url,
        }
        msg_json = jsonutils.create_log_json("CORE PROFILE", "GET", msg)
        logging.error("CORE PROFILE GET " + json.dumps(msg_json))
        return rs_handlers.bad_request(msg_json)

    data_list = jsonutils.remove_file_descriptor_from_data_list(data_list)
    uuid_list = data_list[0].get('uuid')
    return_data = {"pii": jsonutils.remove_null_fields(data_list[0])}

    if uuid_list != None and len(uuid_list) > 0:
        non_pii_data = mongoutils.get_non_pii_query_json_from_field(
            cfg.FIELD_PROFILE_UUID, uuid_list[0])
        non_pii_data = jsonutils.remove_file_descriptor_from_dataset(
            non_pii_data)
        non_pii_data = jsonutils.remove_null_subcategory(non_pii_data)
        return_data["non_pii"] = jsonutils.remove_null_fields(non_pii_data)

    out_json = mongoutils.construct_json_from_query_list(return_data)
    msg_json = jsonutils.create_log_json("CORE PROFILE", "GET", return_data)
    logging.info("CORE PROFILE GET " + json.dumps(msg_json))

    currenttime = otherutils.get_current_time_utc()
    mongoutils.update_pii_core_migrate_date(fields, currenttime)

    return out_json
예제 #27
0
def put(uuid=None):
    try:
        in_json = request.get_json()
    except Exception as ex:
        msg = {
            "reason": "Json format error: " + str(uuid),
            "error": "Bad Request: " + request.url,
        }
        msg_json = jsonutils.create_log_json("Profile", "PUT", msg)
        logging.error("PUT " + json.dumps(msg_json))
        return rs_handlers.bad_request(msg_json)

    # check if the uuid is really existing in the database
    non_pii_dataset = mongoutils.get_non_pii_dataset_from_field(cfg.FIELD_PROFILE_UUID, uuid)

    if non_pii_dataset is None:
        msg = {
            "reason": "There is no profile dataset with given uuid: " + str(uuid),
            "error": "Not Found: " + request.url,
        }
        msg_json = jsonutils.create_log_json("Profile", "PUT", msg)
        logging.error("PUT " + json.dumps(msg_json))
        return rs_handlers.not_found(msg_json)

    # the level check in in_json should be performed
    level_ok, level = otherutils.check_privacy_level(in_json)
    if level_ok == False:
        msg = {
            "reason": "The given privacy level is not correct: " + str(level),
            "error": "Bad Request: " + request.url,
        }
        msg_json = jsonutils.create_log_json("Profile", "PUT", msg)
        logging.error("PUT " + json.dumps(msg_json))
        return rs_handlers.bad_request(msg_json)

    non_pii_dataset, restjson = datasetutils.update_non_pii_dataset_from_json(non_pii_dataset, in_json)
    currenttime = datetime.datetime.now()
    currenttime = currenttime.strftime("%Y/%m/%dT%H:%M:%S")
    non_pii_dataset.set_last_modified_date(currenttime)

    result, non_pii_dataset = mongoutils.update_non_pii_dataset_in_mongo_by_field(
        cfg.FIELD_PROFILE_UUID, uuid,
        non_pii_dataset)

    # update the json information that doesn't belong to data schema
    if len(restjson) > 0:
        result, non_pii_dataset = mongoutils.update_json_with_no_schema(cfg.FIELD_PROFILE_UUID, uuid,
                                                                        non_pii_dataset, restjson)

    if result is None:
        msg = {
            "reason": "Failed to update Profile dataset: " + str(uuid),
            "error": "Not Implemented: " + request.url,
        }
        msg_json = jsonutils.create_log_json("Profile", "PUT", msg)
        logging.error("PUT " + json.dumps(msg_json))
        return rs_handlers.not_implemented(msg_json)

    non_pii_dataset = jsonutils.remove_file_descriptor_from_dataset(non_pii_dataset)
    out_json = jsonutils.remove_null_subcategory(non_pii_dataset)
    msg_json = jsonutils.create_log_json("Profile", "PUT", copy.copy(out_json))
    logging.info("PUT " + json.dumps(msg_json))
    out_json = mongoutils.construct_json_from_query_list(out_json)

    return out_json
예제 #28
0
def patch(event_id):
    auth_middleware.authorize(auth_middleware.ROKWIRE_EVENT_WRITE_GROUPS)

    if not ObjectId.is_valid(event_id):
        abort(400)
    req_data = request.get_json(force=True)
    try:
        req_data = query_params.formate_datetime(req_data)
        if req_data.get('category') or req_data.get('subcategory'):
            db = get_db()
            for data_tuple in db['events'].find({'_id': ObjectId(event_id)}, {
                    '_id': 0,
                    'categorymainsub': 1
            }):
                req_data = query_params.update_category(req_data, data_tuple)
                break

        coordinates = []
        try:
            if req_data.get('location.latitude') or req_data.get(
                    'location.latitude'):
                db = get_db()
                for data_tuple in db['events'].find(
                    {'_id': ObjectId(event_id)}, {
                        '_id': 0,
                        'coordinates': 1
                    }):
                    coordinates = data_tuple.get('coordinates')
                    if not coordinates:
                        abort(500)
                    break
                req_data = query_params.update_coordinates(
                    req_data, coordinates)
        except Exception as ex:
            __logger.exception(ex)
            abort(500)

    except Exception as ex:
        __logger.exception(ex)
        abort(405)

    group_memberships = list()
    try:
        _, group_memberships = get_group_memberships()
    except Exception as ex:
        __logger.exception(ex)
        abort(500)

    db = None
    event = None
    try:
        db = get_db()
        event = db['events'].find_one({'_id': ObjectId(event_id)}, {'_id': 0})
    except Exception as ex:
        __logger.exception(ex)
        abort(500)

    if not check_group_event_admin_access(event, group_memberships):
        abort(401)

    try:
        db = get_db()
        status = db['events'].update_one({'_id': ObjectId(event_id)},
                                         {"$set": req_data})
        msg = "[PATCH]: event id %s, nUpdate = %d " % (str(event_id),
                                                       status.modified_count)
        if req_data is not None:
            msg_json = jsonutils.create_log_json("Events", "PATCH", req_data)
        else:
            msg_json = jsonutils.create_log_json("Events", "PATCH", {})
        __logger.info("PATCH " + json.dumps(msg_json))
    except Exception as ex:
        __logger.exception(ex)
        abort(500)
    return success_response(200, msg, str(event_id))