Esempio n. 1
0
    def post(self):
        parser = reqparse.RequestParser(bundle_errors=True)

        parser.add_argument('username', location='form', required=True)
        parser.add_argument('password', location='form', required=True)

        args = parser.parse_args()

        username_to_check = str(repr(args['username'])[2:-1])
        password_to_check = str(repr(args['password'])[2:-1])

        # DB cursor
        cursor = get_db_cursor()

        cursor, registered_user = get_account_by_username_and_password(
            cursor=cursor,
            username=username_to_check,
            password=password_to_check)

        if app.config["SUPER_DEBUG"]:
            logger.debug("registered_user: " + registered_user.__repr__())

        if registered_user is None:
            flash('Wrong Credentials')
            return {}, 301, {'Location': api.url_for(resource=SignIn)}
        else:
            login_user(registered_user, remember=False)
            flash('Logged in successfully')
            return {}, 301, {'Location': api.url_for(resource=Home)}
Esempio n. 2
0
def store_ssr(ssr_entry=None, endpoint="store_ssr()"):
    if ssr_entry is None:
        raise AttributeError("Provide ssr_entry as parameter")

    # Get DB cursor
    try:
        cursor = get_db_cursor()
    except Exception as exp:
        logger.error('Could not get database cursor: ' + repr(exp))
        raise ApiError(code=500,
                       title="Failed to get database cursor",
                       detail=repr(exp),
                       source=endpoint)

    try:
        # SSR Insert
        cursor = ssr_entry.to_db(cursor=cursor)
        db.connection.commit()
    except Exception as exp:
        logger.error('Slr and Ssr commit failed: ' + repr(exp))
        db.connection.rollback()
        logger.error('--> rollback')
        logger.error("ssr_entry: " + ssr_entry.log_entry)
        raise ApiError(code=500,
                       title="Failed to store slr and ssr",
                       detail=repr(exp),
                       source=endpoint)
    else:
        logger.debug('Ssr commited')
        logger.debug("ssr_entry: " + ssr_entry.log_entry)
        return ssr_entry
Esempio n. 3
0
def get_surrogate_id_by_account_and_service(
        account_id=None,
        service_id=None,
        endpoint="(get_surrogate_id_by_account_and_Service)"):
    if account_id is None:
        raise AttributeError("Provide account_id as parameter")
    if service_id is None:
        raise AttributeError("Provide service_id as parameter")

    # Create Surrogate id object
    try:
        sur_id_obj = SurrogateId(service_id=service_id, account_id=account_id)
    except Exception as exp:
        logger.error('Could not create SurrogateId object: ' + repr(exp))
        raise
    else:
        logger.info("SurrogateId object created")
        logger.debug("sur_id_obj: " + sur_id_obj.log_entry)

    # Get DB cursor
    try:
        cursor = get_db_cursor()
    except Exception as exp:
        logger.error('Could not get database cursor: ' + repr(exp))
        raise

    try:
        cursor = sur_id_obj.from_db(cursor=cursor)
    except Exception as exp:
        logger.error('Could not get surrogate id from db: ' + repr(exp))
        raise
    else:
        logger.debug("Got sur_id_obj:" + json.dumps(sur_id_obj.to_dict))
        logger.debug("sur_id_obj: " + sur_id_obj.log_entry)
        return sur_id_obj.to_dict
Esempio n. 4
0
def load_user(account_id):
    if app.config["SUPER_DEBUG"]:
        logger.debug("load_user(account_id), account_id=" + account_id)

    cursor = get_db_cursor()

    cursor, loaded_user = get_account_by_id(cursor=cursor,
                                            account_id=unicode(account_id))
    return loaded_user
Esempio n. 5
0
def get_db_statistics():
    # Get table names
    #
    db_entry_object = Account()
    account_table_name = db_entry_object.table_name
    #
    db_entry_object = ServiceLinkRecord()
    slr_table_name = db_entry_object.table_name
    #
    db_entry_object = ServiceLinkStatusRecord()
    ssr_table_name = db_entry_object.table_name
    #
    db_entry_object = ConsentRecord()
    cr_table_name = db_entry_object.table_name
    #
    db_entry_object = ConsentStatusRecord()
    csr_table_name = db_entry_object.table_name

    # Get DB cursor
    try:
        logger.debug("Getting DB cursor")
        cursor = get_db_cursor()
    except Exception as exp:
        logger.error('Could not get database cursor: ' + repr(exp))
        return False

    account_query = "SELECT COUNT(*) FROM " + account_table_name + ";"
    slr_query = "SELECT COUNT(*) FROM " + slr_table_name + ";"
    ssr_query = "SELECT COUNT(*) FROM " + ssr_table_name + ";"
    cr_query = "SELECT COUNT(*) FROM " + cr_table_name + ";"
    csr_query = "SELECT COUNT(*) FROM " + csr_table_name + ";"

    try:
        cursor, account_count = execute_sql_count(cursor=cursor,
                                                  sql_query=account_query)
        cursor, slr_count = execute_sql_count(cursor=cursor,
                                              sql_query=slr_query)
        cursor, ssr_count = execute_sql_count(cursor=cursor,
                                              sql_query=ssr_query)
        cursor, cr_count = execute_sql_count(cursor=cursor, sql_query=cr_query)
        cursor, csr_count = execute_sql_count(cursor=cursor,
                                              sql_query=csr_query)
    except Exception as exp:
        logger.debug('sql_query: ' + repr(exp))
        raise
    else:
        count_dict = {
            'account': account_count,
            'service_link': slr_count,
            'service_link_status': ssr_count,
            'consent': cr_count,
            'consent_status': csr_count
        }
        return count_dict
Esempio n. 6
0
def get_emails(cursor=None, account_id=None):

    check_account_id(account_id=account_id)

    if cursor is None:
        cursor = get_db_cursor()
        logger.debug(
            'No DB cursor provided as call parameter. Getting new one.')

    cursor, data = get_emails_by_account(cursor=cursor, account_id=account_id)

    return cursor, data
Esempio n. 7
0
def store_slr_and_ssr(slr_entry=None,
                      ssr_entry=None,
                      endpoint="sign_ssr(account_id, slr_payload, endpoint)"):
    if slr_entry is None:
        raise AttributeError("Provide slr_entry as parameter")
    if ssr_entry is None:
        raise AttributeError("Provide ssr_entry as parameter")

    # Get DB cursor
    try:
        cursor = get_db_cursor()
    except Exception as exp:
        logger.error('Could not get database cursor: ' + repr(exp))
        raise ApiError(code=500,
                       title="Failed to get database cursor",
                       detail=repr(exp),
                       source=endpoint)

    try:
        # SLR update
        cursor = slr_entry.update_db(cursor=cursor)

        # SLR primary key to SSR
        ssr_entry.service_link_records_id = slr_entry.id

        # SSR Insert
        cursor = ssr_entry.to_db(cursor=cursor)

        db.connection.commit()
    except Exception as exp:
        logger.error('Slr and Ssr commit failed: ' + repr(exp))
        db.connection.rollback()
        logger.error('--> rollback')
        logger.error("slr_entry: " + slr_entry.log_entry)
        logger.error("ssr_entry: " + ssr_entry.log_entry)
        raise ApiError(code=500,
                       title="Failed to store slr and ssr",
                       detail=repr(exp),
                       source=endpoint)
    else:
        logger.debug('Slr and Ssr commited')
        logger.debug("slr_entry: " + slr_entry.log_entry)
        logger.debug("ssr_entry: " + ssr_entry.log_entry)
        return slr_entry, ssr_entry
Esempio n. 8
0
def get_slrs(account_id=None):
    """
    Get all slr -entries related to account
    :param account_id:
    :return: List of dicts
    """
    if account_id is None:
        raise AttributeError("Provide account_id as parameter")

    # Get table name
    logger.info("Create slr")
    db_entry_object = ServiceLinkRecord()
    logger.info(db_entry_object.log_entry)
    logger.info("Get table name")
    table_name = db_entry_object.table_name
    logger.info("Got table name: " + str(table_name))

    # Get DB cursor
    try:
        cursor = get_db_cursor()
    except Exception as exp:
        logger.error('Could not get database cursor: ' + repr(exp))
        raise

    # Get primary keys for slr
    try:
        cursor, id_list = get_slr_ids(cursor=cursor,
                                      account_id=account_id,
                                      table_name=table_name)
    except Exception as exp:
        logger.error('Could not get primary key list: ' + repr(exp))
        raise

    # Get slrs from database
    logger.info("Get slrs from database")
    db_entry_list = []
    for id in id_list:
        logger.info("Getting slr with slr_id: " + str(id))
        db_entry_dict = get_slr(account_id=account_id, slr_id=id)
        db_entry_list.append(db_entry_dict)
        logger.info("slr object added to list: " + json.dumps(db_entry_dict))

    return db_entry_list
Esempio n. 9
0
    def get(self):

        account_id = session['user_id']
        logger.debug('Account id: ' + account_id)

        cursor = get_db_cursor()

        cursor, service_link_record_count = get_service_link_record_count(
            cursor=cursor, account_id=account_id)
        cursor, consent_count = get_consent_record_count(cursor=cursor,
                                                         account_id=account_id)

        cursor, contacts = get_contacts(cursor=cursor, account_id=account_id)
        cursor, emails = get_emails(cursor=cursor, account_id=account_id)
        cursor, telephones = get_telephones(cursor=cursor,
                                            account_id=account_id)

        cursor, potential_services = get_potential_services_count(
            cursor=cursor, account_id=account_id)
        cursor, potential_consents = get_potential_consents_count(
            cursor=cursor, account_id=account_id)
        cursor, passive_services = get_potential_services_count(
            cursor=cursor, account_id=account_id)
        cursor, passive_consents = get_passive_consents_count(
            cursor=cursor, account_id=account_id)

        content_data = {
            'service_link_record_count': service_link_record_count,
            'consent_count': consent_count,
            'contacts': contacts,
            'emails': emails,
            'telephones': telephones,
            'potential_services': potential_services,
            'potential_consents': potential_consents,
            'passive_services': passive_services,
            'passive_consents': passive_consents
        }

        headers = {'Content-Type': 'text/html'}
        return make_response(
            render_template('profile/details.html', content_data=content_data),
            200, headers)
Esempio n. 10
0
def get_slr_for_service(service_id=None, slr_id=None, cursor=None):
    """
    Get one slr entry from database by Service ID and Service Link Record ID
    :param account_id:
    :param slr_id:
    :return: dict
    """
    if service_id is None:
        raise AttributeError("Provide service_id as parameter")
    if id is None:
        raise AttributeError("Provide id as parameter")
    if cursor is None:
        # Get DB cursor
        try:
            cursor = get_db_cursor()
        except Exception as exp:
            logger.error('Could not get database cursor: ' + repr(exp))
            raise

    try:
        db_entry_object = ServiceLinkRecord(service_id=service_id,
                                            service_link_record_id=slr_id)
    except Exception as exp:
        error_title = "Failed to create slr object"
        logger.error(error_title + ": " + repr(exp))
        raise
    else:
        logger.debug("slr object created: " + db_entry_object.log_entry)

    # Get slr from DB
    try:
        cursor = db_entry_object.from_db(cursor=cursor)
    except Exception as exp:
        error_title = "Failed to fetch slr from DB"
        logger.error(error_title + ": " + repr(exp))
        raise
    else:
        logger.info("slr fetched")
        logger.info("slr fetched from db: " + db_entry_object.log_entry)

    return db_entry_object.to_api_dict, str(db_entry_object.account_id)
Esempio n. 11
0
def get_csr(cr_id=None, csr_id=None, cursor=None):
    """
    Get one csr entry from database by Account ID and ID
    :param slr_id:
    :param cr_id:
    :param csr_id:
    :return: dict
    """
    if cr_id is None:
        raise AttributeError("Provide cr_id as parameter")
    if csr_id is None:
        raise AttributeError("Provide csr_id as parameter")
    if cursor is None:
        # Get DB cursor
        try:
            cursor = get_db_cursor()
        except Exception as exp:
            logger.error('Could not get database cursor: ' + repr(exp))
            raise

    try:
        db_entry_object = ConsentStatusRecord(consent_record_id=cr_id, consent_status_record_id=csr_id)
    except Exception as exp:
        error_title = "Failed to create csr object"
        logger.error(error_title + ": " + repr(exp))
        raise
    else:
        logger.debug("csr object created: " + db_entry_object.log_entry)

    # Get csr from DB
    try:
        cursor = db_entry_object.from_db(cursor=cursor)
    except Exception as exp:
        error_title = "Failed to fetch csr from DB"
        logger.error(error_title + ": " + repr(exp))
        raise
    else:
        logger.info("csr fetched")
        logger.info("csr fetched from db: " + db_entry_object.log_entry)

    return db_entry_object.to_record_dict
Esempio n. 12
0
def get_account_id_by_service_and_surrogate_id(
        surrogate_id=None,
        service_id=None,
        endpoint="(get_surrogate_id_by_account_and_Service)"):
    if surrogate_id is None:
        raise AttributeError("Provide surrogate_id as parameter")
    if service_id is None:
        raise AttributeError("Provide service_id as parameter")

    # Create Surrogate id object
    try:
        surrogate_object = SurrogateId(service_id=service_id,
                                       surrogate_id=surrogate_id)
    except Exception as exp:
        logger.error('Could not create Surrogate object: ' + repr(exp))
        raise
    else:
        logger.info("Surrogate object created")
        logger.debug("Surrogate object: " + surrogate_object.log_entry)

    # Get DB cursor
    try:
        cursor = get_db_cursor()
    except Exception as exp:
        logger.error('Could not get database cursor: ' + repr(exp))
        raise

    try:
        cursor = surrogate_object.from_db(cursor=cursor)
    except Exception as exp:
        logger.error('Could not get Surrogate object from db: ' + repr(exp))
        raise
    else:
        logger.info("Surrogate object fetched")
        logger.debug("Surrogate object: " + surrogate_object.log_entry)
        return surrogate_object
Esempio n. 13
0
def get_last_cr_status(consent_id=None,
                       account_id="",
                       endpoint="get_last_cr_status()"):
    if consent_id is None:
        raise AttributeError("Provide consent_id as parameter")
    if account_id is None:
        raise AttributeError("Provide account_id as parameter")

    # Get DB cursor
    try:
        logger.info("Getting database cursor")
        cursor = get_db_cursor()
    except Exception as exp:
        logger.error('Could not get database cursor: ' + repr(exp))
        raise

    # Init Consent Record Object
    try:
        logger.info("Create ConsentRecord object")
        cr_entry = ConsentRecord(consent_id=consent_id)
        logger.info(cr_entry.log_entry)
    except Exception as exp:
        error_title = "Failed to create Consent Record object"
        logger.error(error_title + ": " + repr(exp))
        raise
    else:
        logger.debug("ConsentRecord object: " + cr_entry.log_entry)

    # Get Consent Record from DB
    try:
        logger.info("Getting Consent Record from DB")
        cursor = cr_entry.from_db(cursor=cursor)
    except IndexError as exp:
        error_title = "Consent Record not found from DB with given ID"
        logger.error(error_title + ": " + repr(exp))
        raise
    except Exception as exp:
        error_title = "Failed to fetch Consent Record from DB"
        logger.error(error_title + ": " + repr(exp))
        raise
    else:
        logger.debug("cr_entry: " + cr_entry.log_entry)

    # Create Consent Status Record object
    try:
        logger.info("Creating Consent Status Record object")
        csr_entry = ConsentStatusRecord()
    except Exception as exp:
        error_title = "Failed to create Consent Status Record object"
        logger.error(error_title + ": " + repr(exp))
        raise
    else:
        logger.debug("Consent Status Record object: " + csr_entry.log_entry)

    # Get Consent Status Record ID
    try:
        logger.info("Getting ID of last Consent Status Record")
        cursor, csr_id = get_last_csr_id(cursor=cursor,
                                         consent_id=consent_id,
                                         account_id=account_id,
                                         table_name=csr_entry.table_name)
    except IndexError as exp:
        error_title = "Consent Status Record not found from DB with given Consent Record ID"
        logger.error(error_title + ": " + repr(exp))
        raise
    except Exception as exp:
        error_title = "Failed to get last Consent Status Record ID from database"
        logger.error(error_title + ": " + repr(exp))
        raise
    else:
        logger.debug("Consent Status Record ID: " + str(csr_id))

    # Append IDs to Consent Status Record Object
    try:
        logger.info("Appending IDs to Consent Status Record object")
        csr_entry.consent_status_record_id = csr_id
        csr_entry.accounts_id = account_id
    except Exception as exp:
        error_title = "Failed to append IDs to Consent Status Record object"
        logger.error(error_title + ": " + repr(exp))
        raise
    else:
        logger.info("Appended IDs to Consent Status Record object: " +
                    csr_entry.log_entry)

    # Get Consent Status Record from DB
    try:
        logger.info("Getting Consent Status Record from DB")
        cursor = csr_entry.from_db(cursor=cursor)
    except IndexError as exp:
        error_title = "Consent Status Record not found from DB with given ID"
        logger.error(error_title + ": " + repr(exp))
        raise ApiError(code=404,
                       title=error_title,
                       detail=repr(exp),
                       source=endpoint)
    except Exception as exp:
        error_title = "Failed to fetch Consent Status Record from DB"
        logger.error(error_title + ": " + repr(exp))
        raise ApiError(code=500,
                       title=error_title,
                       detail=repr(exp),
                       source=endpoint)
    else:
        logger.debug("Consent Status Record object: " + csr_entry.log_entry)

    return csr_entry.to_api_dict
Esempio n. 14
0
def get_auth_token_data(sink_cr_object=None, endpoint="get_auth_token_data()"):
    if sink_cr_object is None:
        raise AttributeError("Provide sink_cr_object as parameter")

    # Get DB cursor
    try:
        cursor = get_db_cursor()
    except Exception as exp:
        logger.error('Could not get database cursor: ' + repr(exp))
        raise

    # Get Sink's CR from DB
    try:
        logger.info("Get Sink's CR from DB")
        cursor = sink_cr_object.from_db(cursor=cursor)
    except Exception as exp:
        error_title = "Failed to fetch Sink's CR from DB"
        logger.error(error_title + ": " + repr(exp))
        raise
    else:
        logger.debug("sink_cr_object: " + sink_cr_object.log_entry)

    # Get required id's from Sink's CR
    try:
        logger.info("Get required id's from Sink's CR")
        sink_slr_primary_key = str(sink_cr_object.service_link_records_id)
    except Exception as exp:
        error_title = "Failed to get id's from Sink's CR"
        logger.error(error_title + ": " + repr(exp))
        raise
    else:
        logger.debug("sink_slr_primary_key: " + sink_slr_primary_key)

    # Init Source's Consent Record Object
    try:
        logger.info("Init Source's Consent Record Object")
        source_cr_entry = ConsentRecord(
            consent_pair_id=sink_cr_object.consent_id,
            accounts_id=sink_cr_object.accounts_id,
            role="Source")
    except Exception as exp:
        error_title = "Failed to create Source's Consent Record object"
        logger.error(error_title + ": " + repr(exp))
        raise
    else:
        logger.debug("source_cr_entry: " + source_cr_entry.log_entry)

    # Get Source's Consent Record from DB
    try:
        logger.info("Get Source's Consent Record from DB")
        cursor = source_cr_entry.from_db(cursor=cursor)
    except Exception as exp:
        error_title = "Failed to fetch Source's CR from DB"
        logger.error(error_title + ": " + repr(exp))
        raise
    else:
        logger.debug("source_cr_entry: " + source_cr_entry.log_entry)

    # Init Sink's Service Link Record Object
    try:
        logger.info("Init Sink's Service Link Record Object")
        sink_slr_entry = ServiceLinkRecord(
            id=sink_slr_primary_key,
            service_link_record_id=sink_cr_object.service_link_record_id)
    except Exception as exp:
        error_title = "Failed to create Source's Service Link Record object"
        logger.error(error_title + ": " + repr(exp))
        raise
    else:
        logger.debug("sink_slr_entry: " + sink_slr_entry.log_entry)

    # Get Source's Consent Record from DB
    try:
        logger.info("Get Source's Consent Record from DB")
        cursor = sink_slr_entry.from_db(cursor=cursor)
    except Exception as exp:
        error_title = "Failed to fetch Sink's SLR from DB"
        logger.error(error_title + ": " + repr(exp))
        raise
    else:
        logger.debug("sink_slr_entry: " + sink_slr_entry.log_entry)

    return source_cr_entry, sink_slr_entry
Esempio n. 15
0
def store_cr_and_csr(source_slr_entry=None,
                     sink_slr_entry=None,
                     source_cr_entry=None,
                     source_csr_entry=None,
                     sink_cr_entry=None,
                     sink_csr_entry=None,
                     endpoint="store_cr_and_csr()"):
    if source_slr_entry is None:
        raise AttributeError("Provide source_slr_entry as parameter")
    if sink_slr_entry is None:
        raise AttributeError("Provide sink_slr_entry as parameter")
    if source_cr_entry is None:
        raise AttributeError("Provide source_cr_entry as parameter")
    if source_csr_entry is None:
        raise AttributeError("Provide source_csr_entry as parameter")
    if sink_cr_entry is None:
        raise AttributeError("Provide sink_cr_entry as parameter")
    if sink_csr_entry is None:
        raise AttributeError("Provide sink_csr_entry as parameter")

    # Get DB cursor
    try:
        cursor = get_db_cursor()
    except Exception as exp:
        logger.error('Could not get database cursor: ' + repr(exp))
        raise ApiError(code=500,
                       title="Failed to get database cursor",
                       detail=repr(exp),
                       source=endpoint)

    try:
        # Get Source's SLR from DB
        try:
            logger.info("Get Source SLR from database")
            cursor = source_slr_entry.from_db(cursor=cursor)
        except Exception as exp:
            error_title = "Failed to fetch Service Link Record of Source Service from DB"
            error_detail = str(exp.message)
            logger.error(error_title + ": " + repr(exp))
            raise IndexError(error_title + " - " + error_detail)
        else:
            logger.debug("source_slr_entry: " + source_slr_entry.log_entry)

        # Get Sink's SLR from DB
        try:
            logger.info("Get Sink SLR from database")
            cursor = sink_slr_entry.from_db(cursor=cursor)
        except Exception as exp:
            error_title = "Failed to fetch Service Link Record of Sink Service from DB"
            error_detail = str(exp.message)
            logger.error(error_title + ": " + repr(exp))
            raise IndexError(error_title + " - " + error_detail)
        else:
            logger.debug("sink_slr_entry: " + sink_slr_entry.log_entry)

        # Get Source's SLR ID
        try:
            logger.info("Source SLR ID to Source CR")
            source_cr_entry.service_link_records_id = source_slr_entry.id
        except Exception as exp:
            error_title = "Failed to link Consent Record of Source Service with Service Link Record"
            error_detail = repr(exp)
            logger.error(error_title + ": " + repr(exp))
            raise KeyError(error_title + " - " + error_detail)
        else:
            logger.debug("source_cr_entry: " + source_cr_entry.log_entry)

        # Get Sink's SLR ID
        try:
            logger.info("Sink SLR ID to Sink CR")
            sink_cr_entry.service_link_records_id = sink_slr_entry.id
        except Exception as exp:
            error_title = "Failed to link Consent Record of Sink Service with Service Link Record"
            error_detail = repr(exp)
            logger.error(error_title + ": " + repr(exp))
            raise KeyError(error_title + " - " + error_detail)
        else:
            logger.debug("sink_cr_entry: " + sink_cr_entry.log_entry)

        # Store Source CR
        try:
            logger.info("Store Source CR")
            cursor = source_cr_entry.to_db(cursor=cursor)
        except Exception as exp:
            error_title = "Failed to store Consent Record of Source Service"
            error_detail = repr(exp)
            logger.error(error_title + ": " + repr(exp))
            raise RuntimeError(error_title + " - " + error_detail)
        else:
            logger.debug("source_cr_entry: " + source_cr_entry.log_entry)

        # Link Source's CSR with it's CR
        try:
            logger.info("Source CR ID to Source CSR")
            source_csr_entry.consent_records_id = source_cr_entry.id
        except Exception as exp:
            error_title = "Failed to link Consent Record of Source Service with Consent Status Record"
            error_detail = repr(exp)
            logger.error(error_title + ": " + repr(exp))
            raise KeyError(error_title + " - " + error_detail)
        else:
            logger.debug(source_csr_entry.log_entry)

        # Store Source CSR
        try:
            logger.info("Store Source CSR")
            cursor = source_csr_entry.to_db(cursor=cursor)
        except Exception as exp:
            error_title = "Failed to store Consent Status Record of Source Service"
            error_detail = repr(exp)
            logger.error(error_title + ": " + repr(exp))
            raise RuntimeError(error_title + " - " + error_detail)
        else:
            logger.debug("source_csr_entry: " + source_csr_entry.log_entry)

        # Store Sink CR
        try:
            logger.info("Store Sink CR")
            cursor = sink_cr_entry.to_db(cursor=cursor)
        except Exception as exp:
            error_title = "Failed to store Consent Record of Sink Service"
            error_detail = repr(exp)
            logger.error(error_title + ": " + repr(exp))
            raise RuntimeError(error_title + " - " + error_detail)
        else:
            logger.debug("sink_cr_entry: " + sink_cr_entry.log_entry)

        # Link Sink's CSR with it's CR
        try:
            logger.info("Sink CR ID to Sink CSR")
            sink_csr_entry.consent_records_id = sink_cr_entry.id
        except Exception as exp:
            error_title = "Failed to link Consent Record of Sink Service with Consent Status Record"
            error_detail = repr(exp)
            logger.error(error_title + ": " + repr(exp))
            raise KeyError(error_title + " - " + error_detail)
        else:
            logger.debug("sink_csr_entry: " + sink_csr_entry.log_entry)

        # Store Sink CSR
        try:
            logger.info("Store Sink CSR")
            cursor = sink_csr_entry.to_db(cursor=cursor)
        except Exception as exp:
            error_title = "Failed to store Consent Status Record of Sink Service"
            error_detail = repr(exp)
            logger.error(error_title + ": " + repr(exp))
            raise RuntimeError(error_title + " - " + error_detail)
        else:
            logger.debug("sink_csr_entry: " + sink_csr_entry.log_entry)

        # Commit
        db.connection.commit()
    except Exception as exp:
        logger.debug('commit failed: ' + repr(exp))
        db.connection.rollback()
        logger.debug('--> rollback')
        error_title = "Could not write to database"
        error_detail = repr(exp)
        logger.error(error_title + ": " + error_detail)
        raise
    else:
        logger.info("CR's and CSR's commited")
        return source_cr_entry, source_csr_entry, sink_cr_entry, sink_csr_entry
Esempio n. 16
0
def get_account_id_by_cr(cr_id=None,
                         endpoint="get_account_id_by_cr(cr_id, endpoint)"):
    if cr_id is None:
        raise AttributeError("Provide cr_id as parameter")

    logger.info("Executing for: " + str(endpoint))

    ##
    # Account
    try:
        logger.info("Create Account object")
        account_entry = Account()
    except Exception as exp:
        error_title = "Failed to create Account object"
        logger.error(error_title + ": " + repr(exp))
        raise ApiError(code=500,
                       title=error_title,
                       detail=repr(exp),
                       source=endpoint)
    else:
        logger.info("account_entry: " + account_entry.log_entry)

    # Get database table name for Consent Status Record
    try:
        logger.info("Get Account table name")
        account_table_name = account_entry.table_name
    except Exception as exp:
        error_title = "Failed to get Account table name"
        logger.error(error_title + ": " + repr(exp))
        raise ApiError(code=500,
                       title=error_title,
                       detail=repr(exp),
                       source=endpoint)
    else:
        logger.info("Got Account table name: " + str(account_table_name))

    ##
    # ServiceLinkRecord
    try:
        logger.info("Create ServiceLinkRecord object")
        slr_entry = ServiceLinkRecord()
    except Exception as exp:
        error_title = "Failed to create ServiceLinkRecord object"
        logger.error(error_title + ": " + repr(exp))
        raise ApiError(code=500,
                       title=error_title,
                       detail=repr(exp),
                       source=endpoint)
    else:
        logger.info("slr_entry: " + slr_entry.log_entry)

    # Get database table name for Consent Status Record
    try:
        logger.info("Get ServiceLinkRecord table name")
        slr_table_name = slr_entry.table_name
    except Exception as exp:
        error_title = "Failed to get ServiceLinkRecord table name"
        logger.error(error_title + ": " + repr(exp))
        raise ApiError(code=500,
                       title=error_title,
                       detail=repr(exp),
                       source=endpoint)
    else:
        logger.info("Got ServiceLinkRecord table name: " + str(slr_table_name))

    ##
    # ConsentRecord
    try:
        logger.info("Create ConsentRecord object")
        cr_entry = ConsentRecord()
    except Exception as exp:
        error_title = "Failed to create Consent Record object"
        logger.error(error_title + ": " + repr(exp))
        raise ApiError(code=500,
                       title=error_title,
                       detail=repr(exp),
                       source=endpoint)
    else:
        logger.info("cr_entry: " + cr_entry.log_entry)

    # Get database table name for Consent Status Record
    try:
        logger.info("Get Consent Record table name")
        cr_table_name = cr_entry.table_name
    except Exception as exp:
        error_title = "Failed to get Consent Record table name"
        logger.error(error_title + ": " + repr(exp))
        raise ApiError(code=500,
                       title=error_title,
                       detail=repr(exp),
                       source=endpoint)
    else:
        logger.info("Got Consent Record table name: " + str(cr_table_name))

    # Get DB cursor
    try:
        cursor = get_db_cursor()
    except Exception as exp:
        logger.error('Could not get database cursor: ' + repr(exp))
        raise ApiError(code=500,
                       title="Failed to get database cursor",
                       detail=repr(exp),
                       source=endpoint)

    # Get Account ID
    try:
        logger.info("Get Account ID")
        cursor, account_id = get_account_id_by_csr_id(
            cursor=cursor,
            cr_id=cr_id,
            acc_table_name=account_table_name,
            slr_table_name=slr_table_name,
            cr_table_name=cr_table_name)
    except IndexError as exp:
        error_title = "Account ID Not Found"
        logger.error(error_title + ": " + repr(exp))
        raise ApiError(code=404,
                       title=error_title,
                       detail=repr(exp),
                       source=endpoint)
    except Exception as exp:
        error_title = "Failed to get Account ID"
        logger.error(error_title + ": " + repr(exp))
        raise ApiError(code=500,
                       title=error_title,
                       detail=repr(exp),
                       source=endpoint)
    else:
        logger.info("Got Account ID: " + str(cr_table_name))
        return account_id
Esempio n. 17
0
def get_csrs(account_id=None, consent_id=None, status_id=""):
    """
    Get all consent status record entries related to Consent Record
    :param account_id:
    :param consent_id:
    :return: List of dicts
    """
    if account_id is None:
        raise AttributeError("Provide account_id as parameter")
    if consent_id is None:
        raise AttributeError("Provide consent_id as parameter")
    if status_id is None:
        raise AttributeError("Provide status_id as parameter")

    # Get table name
    logger.info("Create Consent Status Record object")
    db_entry_object = ConsentStatusRecord()
    logger.info(db_entry_object.log_entry)
    logger.info("Get table name")
    table_name = db_entry_object.table_name
    logger.info("Got table name: " + str(table_name))

    # Get DB cursor
    try:
        cursor = get_db_cursor()
    except Exception as exp:
        logger.error('Could not get database cursor: ' + repr(exp))
        raise

    # Get primary key filter
    try:
        cursor, filter_id = get_consent_status_id_filter(cursor=cursor,
                                                         csr_id=status_id,
                                                         table_name=table_name)
    except Exception as exp:
        logger.error('Could not get primary key list: ' + repr(exp))
        raise

    # Get primary keys for Consent Status Records
    try:
        cursor, id_list = get_consent_status_ids(cursor=cursor,
                                                 cr_id=consent_id,
                                                 primary_key_filter=filter_id,
                                                 table_name=table_name)
    except Exception as exp:
        logger.error('Could not get primary key list: ' + repr(exp))
        raise

    # Get Consent Status Records from database
    logger.info("Get Consent Status Records from database")
    db_entry_list = []
    account_id_list = []
    for entry_id in id_list:
        logger.info("Getting Consent Status Record with account_id: " +
                    str(account_id) + " consent_id: " + str(consent_id) +
                    " csr_id: " + str(entry_id))
        db_entry_dict, account_id_from_db = get_csr(account_id=account_id,
                                                    cr_id=consent_id,
                                                    csr_id=entry_id)
        db_entry_list.append(db_entry_dict)
        account_id_list.append(account_id_from_db)
        logger.info("Consent Status Records object added to list: " +
                    json.dumps(db_entry_dict))

    try:
        account_id_list = list(set(account_id_list))
    except Exception as exp:
        logger.error('Could not remove duplicates from account id listing: ' +
                     repr(exp))
        raise

    return db_entry_list, account_id_list
Esempio n. 18
0
def get_account_id_by_username_and_password(username=None, password=None):
    username_to_check = str(username)
    logger.debug('username_to_check: ' + username_to_check)

    password_to_check = str(password)
    logger.debug('password_to_check: ' + password_to_check)

    try:
        ###
        # User info by username
        logger.debug('credentials')
        sql_query = "SELECT " \
                    "MyDataAccount.LocalIdentities.Accounts_id, " \
                    "MyDataAccount.LocalIdentities.id, " \
                    "MyDataAccount.LocalIdentities.username, " \
                    "MyDataAccount.LocalIdentityPWDs.password, " \
                    "MyDataAccount.Salts.salt  " \
                    "FROM MyDataAccount.LocalIdentities " \
                    "INNER JOIN MyDataAccount.LocalIdentityPWDs " \
                    "ON MyDataAccount.LocalIdentityPWDs.id = MyDataAccount.LocalIdentities.LocalIdentityPWDs_id " \
                    "INNER JOIN MyDataAccount.Salts " \
                    "ON MyDataAccount.Salts.LocalIdentities_id = MyDataAccount.LocalIdentities.id " \
                    "WHERE MyDataAccount.LocalIdentities.username = '******'" % (username_to_check)

        if app.config["SUPER_DEBUG"]:
            logger.debug('sql_query: ' + repr(sql_query))

        # DB cursor
        cursor = get_db_cursor()

        cursor.execute(sql_query)

        data = cursor.fetchone()
        account_id_from_db = str(data[0])
        identity_id_from_db = str(data[1])
        username_from_db = str(data[2])
        password_from_db = str(data[3])
        salt_from_db = str(data[4])

    except Exception as exp:
        logger.debug('Authentication failed: ' + repr(exp))

        if app.config["SUPER_DEBUG"]:
            logger.debug('Exception: ' + repr(exp))

        return None

    else:
        logger.debug('User found with given username: '******'account_id_from_db: ' + account_id_from_db)
            logger.debug('identity_id_from_db: ' + identity_id_from_db)
            logger.debug('username_from_db: ' + username_from_db)
            logger.debug('password_from_db: ' + password_from_db)
            logger.debug('salt_from_db: ' + salt_from_db)

    if bcrypt.hashpw(password_to_check, salt_from_db) == password_from_db:
        if app.config["SUPER_DEBUG"]:
            logger.debug('Password hash from client: ' +
                         bcrypt.hashpw(password_to_check, salt_from_db))
            logger.debug('Password hash from db    : ' + password_from_db)

        logger.debug('Authenticated')
        #cursor, user = get_account_by_id(cursor=cursor, account_id=int(account_id_from_db))
        user = {'account_id': account_id_from_db, 'username': username_from_db}
        logger.debug('User dict created')
        return user

    else:
        if app.config["SUPER_DEBUG"]:
            logger.debug('Password hash from client: ' +
                         bcrypt.hashpw(password_to_check, salt_from_db))
            logger.debug('Password hash from db    : ' + password_from_db)

        logger.debug('Not Authenticated')
        return None
Esempio n. 19
0
def get_crs(surrogate_id="",
            slr_id="",
            subject_id="",
            consent_pair_id="",
            account_id="",
            status_id="",
            consent_pairs=False):
    """
    Get Consent Records

    :param surrogate_id:
    :param slr_id:
    :param subject_id:
    :param consent_pair_id:
    :param account_id:
    :return:
    """
    try:
        surrogate_id = str(surrogate_id)
    except Exception:
        raise TypeError("surrogate_id MUST be str, not " +
                        str(type(surrogate_id)))
    try:
        slr_id = str(slr_id)
    except Exception:
        raise TypeError("slr_id MUST be str, not " + str(type(slr_id)))
    try:
        subject_id = str(subject_id)
    except Exception:
        raise TypeError("subject_id MUST be str, not " + str(type(subject_id)))
    try:
        consent_pair_id = str(consent_pair_id)
    except Exception:
        raise TypeError("consent_pair_id MUST be str, not " +
                        str(type(consent_pair_id)))
    try:
        account_id = str(account_id)
    except Exception:
        raise TypeError("account_id MUST be str, not " + str(type(account_id)))
    try:
        status_id = str(status_id)
    except Exception:
        raise TypeError("status_id MUST be str, not " + str(type(status_id)))
    try:
        consent_pairs = bool(consent_pairs)
    except Exception:
        raise TypeError("consent_pairs MUST be bool, not " +
                        str(type(consent_pairs)))

    logger.info("surrogate_id: " + surrogate_id)
    logger.info("slr_id: " + slr_id)
    logger.info("subject_id: " + subject_id)
    logger.info("consent_pair_id: " + consent_pair_id)
    logger.info("account_id: " + account_id)
    logger.info("status_id: " + status_id)
    if consent_pairs:
        logger.info("consent_pairs: True")
    else:
        logger.info("consent_pairs: False")

    # Get table name
    logger.info("Create ConsentRecord object")
    db_entry_object = ConsentRecord()
    logger.info(db_entry_object.log_entry)
    logger.info("Get table name")
    table_name = db_entry_object.table_name
    logger.info("Got table name: " + str(table_name))

    # Get DB cursor
    try:
        cursor = get_db_cursor()
    except Exception as exp:
        logger.error('Could not get database cursor: ' + repr(exp))
        raise

    # Get primary keys for slr
    try:
        cursor, id_list = get_consent_ids(cursor=cursor,
                                          surrogate_id=surrogate_id,
                                          slr_id=slr_id,
                                          subject_id=subject_id,
                                          consent_pair_id=consent_pair_id,
                                          account_id=account_id,
                                          table_name=table_name)
    except Exception as exp:
        logger.error('Could not get primary key list: ' + repr(exp))
        raise

    # Get ConsentRecords from database
    logger.info("Get ConsentRecords from database")
    cr_list = []
    account_id_list = []
    logger.info("Getting ConsentRecords")
    for entry_id in id_list:
        logger.info("Getting ConsentRecord with cr_id: " + str(entry_id))
        db_entry_dict, account_id_from_db = get_cr(cr_id=entry_id,
                                                   account_id=account_id)
        cr_list.append(db_entry_dict)
        account_id_list.append(account_id_from_db)
        logger.info("ConsentRecord object added to list: " +
                    json.dumps(db_entry_dict))
        logger.info("account_id added to list: " + str(account_id_from_db))

    if consent_pairs:
        logger.info("Getting Consent Record pairs")
        for entry_id in id_list:
            logger.info("Getting ConsentRecord with consent_pair_id: " +
                        str(entry_id))
            db_entry_dict, account_id_from_db = get_cr(
                consent_pair_id=entry_id, account_id=account_id)
            cr_list.append(db_entry_dict)
            account_id_list.append(account_id_from_db)
            logger.info("ConsentRecord object added to list: " +
                        json.dumps(db_entry_dict))
            logger.info("account_id added to list: " + str(account_id_from_db))

    logger.info("ConsentRecords fetched: " + json.dumps(cr_list))

    try:
        account_id_list = list(set(account_id_list))
    except Exception as exp:
        logger.error('Could not remove duplicates from account id listing: ' +
                     repr(exp))
        raise

    return cr_list, account_id_list
Esempio n. 20
0
def get_slsrs(account_id=None, slr_id=None):
    """
    Get all slsr -entries related to service link record
    :param account_id:
    :param slr_id:
    :return: List of dicts
    """
    if account_id is None:
        raise AttributeError("Provide account_id as parameter")
    if slr_id is None:
        raise AttributeError("Provide slr_id as parameter")

    # Check if slr can be found with account_id and slr_id
    try:
        slr = get_slr(account_id=account_id, slr_id=slr_id)
    except StandardError as exp:
        logger.error(repr(exp))
        raise
    except Exception as exp:
        func_data = {'account_id': account_id, 'slr_id': slr_id}
        title = "No SLR with: " + json.dumps(func_data)
        logger.error(title)
        raise IndexError(title + ": " + repr(exp))
    else:
        logger.info("Found SLR: " + repr(slr))

    # Get table name
    logger.info("Create slsr")
    db_entry_object = ServiceLinkStatusRecord()
    logger.info(db_entry_object.log_entry)
    logger.info("Get table name")
    table_name = db_entry_object.table_name
    logger.info("Got table name: " + str(table_name))

    # Get DB cursor
    try:
        cursor = get_db_cursor()
    except Exception as exp:
        logger.error('Could not get database cursor: ' + repr(exp))
        raise

    # Get primary keys for slsr
    try:
        cursor, id_list = get_slsr_ids(cursor=cursor,
                                       slr_id=slr_id,
                                       table_name=table_name)
    except Exception as exp:
        logger.error('Could not get primary key list: ' + repr(exp))
        raise

    # Get slsrs from database
    logger.info("Get slsrs from database")
    db_entry_list = []
    for id in id_list:
        logger.info("Getting slsr with account_id: " + str(account_id) +
                    " slr_id: " + str(slr_id) + " slsr_id: " + str(id))
        db_entry_dict = get_slsr(account_id=account_id,
                                 slr_id=slr_id,
                                 slsr_id=id)
        db_entry_list.append(db_entry_dict)
        logger.info("slsr object added to list: " + json.dumps(db_entry_dict))

    return db_entry_list
Esempio n. 21
0
def get_slsr(account_id=None, slr_id=None, slsr_id=None, cursor=None):
    """
    Get one slsr entry from database by Account ID and ID
    :param slr_id:
    :param slsr_id:
    :return: dict
    """
    if account_id is None:
        raise AttributeError("Provide account_id as parameter")
    if slr_id is None:
        raise AttributeError("Provide slr_id as parameter")
    if slsr_id is None:
        raise AttributeError("Provide slsr_id as parameter")
    if cursor is None:
        # Get DB cursor
        try:
            cursor = get_db_cursor()
        except Exception as exp:
            logger.error('Could not get database cursor: ' + repr(exp))
            raise

    # Check if slr can be found with account_id and slr_id
    try:
        slr = get_slr(account_id=account_id, slr_id=slr_id)
    except StandardError as exp:
        logger.error(repr(exp))
        raise
    except Exception as exp:
        func_data = {'account_id': account_id, 'slr_id': slr_id}
        title = "No SLR with: " + json.dumps(func_data)
        logger.error(title)
        raise StandardError(title + ": " + repr(exp))
    else:
        logger.info("Found SLR: " + repr(slr))

    try:
        db_entry_object = ServiceLinkStatusRecord(
            service_link_status_record_id=slsr_id,
            service_link_record_id=slr_id)
    except Exception as exp:
        error_title = "Failed to create slsr object"
        logger.error(error_title + ": " + repr(exp))
        raise
    else:
        logger.debug("slsr object created: " + db_entry_object.log_entry)

    # Get slsr from DB
    try:
        logger.info("Get slsr from DB")
        cursor = db_entry_object.from_db(cursor=cursor)
    except IndexError as exp:
        error_title = "Service Link Status Record not found with provided information."
        error_detail = "Service Link Record ID was {} and Service Link Status Record ID was {}.".format(
            slr_id, slsr_id)
        logger.error(error_title + " " + error_detail + ": " + repr(exp))
        raise IndexError(error_detail)
    except Exception as exp:
        error_title = "Failed to fetch slsr from DB"
        logger.error(error_title + ": " + repr(exp))
        raise
    else:
        logger.info("slsr fetched")
        logger.info("slsr fetched from db: " + db_entry_object.log_entry)

    return db_entry_object.to_api_dict
Esempio n. 22
0
def get_slrs_for_service(service_id=None, surrogate_id="", account_id=""):
    """
    Get all slr -entries related to service
    :param service_id:
    :param surrogate_id:
    :param account_id:
    :return: List of dicts
    """
    if service_id is None:
        raise AttributeError("Provide service_id as parameter")
    logger.info("service_id: " + str(service_id))
    logger.info("surrogate_id: " + str(surrogate_id))
    logger.info("account_id: " + str(account_id))

    # Get table name
    logger.info("Create slr")
    db_entry_object = ServiceLinkRecord()
    logger.info(db_entry_object.log_entry)
    logger.info("Get table name")
    table_name = db_entry_object.table_name
    logger.info("Got table name: " + str(table_name))

    # Get DB cursor
    try:
        cursor = get_db_cursor()
    except Exception as exp:
        logger.error('Could not get database cursor: ' + repr(exp))
        raise

    # Get primary keys for slr
    try:
        cursor, id_list = get_slr_ids_by_service(cursor=cursor,
                                                 service_id=service_id,
                                                 surrogate_id=surrogate_id,
                                                 account_id=account_id,
                                                 table_name=table_name)
    except Exception as exp:
        logger.error('Could not get primary key list: ' + repr(exp))
        raise

    # Get slrs from database
    logger.info("Get slrs from database")
    db_entry_list = []
    account_id_list = []
    for id in id_list:
        logger.info("Getting slr with slr_id: " + str(id))
        db_entry_dict, account_id = get_slr_for_service(service_id=service_id,
                                                        slr_id=id)
        db_entry_list.append(db_entry_dict)
        account_id_list.append(account_id)
        logger.info("slr object added to list: " + json.dumps(db_entry_dict))
        logger.info("account_id added to list: " + str(account_id))

    try:
        account_id_list = list(set(account_id_list))
    except Exception as exp:
        logger.error('Could not remove duplicates from account id listing: ' +
                     repr(exp))
        raise

    return db_entry_list, account_id_list
Esempio n. 23
0
def store_cr_and_csr(source_slr_entry=None,
                     sink_slr_entry=None,
                     source_cr_entry=None,
                     source_csr_entry=None,
                     sink_cr_entry=None,
                     sink_csr_entry=None,
                     endpoint="store_cr_and_csr()"):
    if source_slr_entry is None:
        raise AttributeError("Provide source_slr_entry as parameter")
    if sink_slr_entry is None:
        raise AttributeError("Provide sink_slr_entry as parameter")
    if source_cr_entry is None:
        raise AttributeError("Provide source_cr_entry as parameter")
    if source_csr_entry is None:
        raise AttributeError("Provide source_csr_entry as parameter")
    if sink_cr_entry is None:
        raise AttributeError("Provide sink_cr_entry as parameter")
    if sink_csr_entry is None:
        raise AttributeError("Provide sink_csr_entry as parameter")

    # Get DB cursor
    try:
        cursor = get_db_cursor()
    except Exception as exp:
        logger.error('Could not get database cursor: ' + repr(exp))
        raise ApiError(code=500,
                       title="Failed to get database cursor",
                       detail=repr(exp),
                       source=endpoint)

    try:
        # Get Source's SLR from DB
        try:
            cursor = source_slr_entry.from_db(cursor=cursor)
        except Exception as exp:
            error_title = "Failed to fetch Source's SLR from DB"
            logger.error(error_title + ": " + repr(exp))
            raise ApiError(code=404,
                           title=error_title,
                           detail=repr(exp),
                           source=endpoint)
        finally:
            logger.debug("source_slr_entry: " + source_slr_entry.log_entry)

        # Get Sink's SLR from DB
        try:
            cursor = sink_slr_entry.from_db(cursor=cursor)
        except Exception as exp:
            error_title = "Failed to fetch Sink's SLR from DB"
            logger.error(error_title + ": " + repr(exp))
            raise ApiError(code=404,
                           title=error_title,
                           detail=repr(exp),
                           source=endpoint)
        finally:
            logger.debug("sink_slr_entry: " + sink_slr_entry.log_entry)

        # Get Source's SLR ID
        try:
            source_cr_entry.service_link_records_id = source_slr_entry.id
        except Exception as exp:
            error_title = "Failed to fetch Source's Service Link Record ID"
            logger.error(error_title + ": " + repr(exp))
            raise ApiError(code=500,
                           title=error_title,
                           detail=repr(exp),
                           source=endpoint)
        finally:
            logger.debug("source_cr_entry: " + source_cr_entry.log_entry)

        # Get Sink's SLR ID
        try:
            sink_cr_entry.service_link_records_id = sink_slr_entry.id
        except Exception as exp:
            error_title = "Failed to fetch Sink's Service Link Record ID"
            logger.error(error_title + ": " + repr(exp))
            raise ApiError(code=500,
                           title=error_title,
                           detail=repr(exp),
                           source=endpoint)
        finally:
            logger.debug("sink_cr_entry: " + sink_cr_entry.log_entry)

        # Store Source CR
        try:
            cursor = source_cr_entry.to_db(cursor=cursor)
        except Exception as exp:
            error_title = "Failed to store Source's Consent Record"
            logger.error(error_title + ": " + repr(exp))
            raise ApiError(code=500,
                           title=error_title,
                           detail=repr(exp),
                           source=endpoint)
        finally:
            logger.debug("source_cr_entry: " + source_cr_entry.log_entry)

        # Link Source's CSR with it's CR
        try:
            source_csr_entry.consent_records_id = source_cr_entry.id
        except Exception as exp:
            error_title = "Failed to link Source's CSR with it's CR"
            logger.error(error_title + ": " + repr(exp))
            raise ApiError(code=500,
                           title=error_title,
                           detail=repr(exp),
                           source=endpoint)
        finally:
            logger.debug(source_csr_entry.log_entry)

        # Store Source CSR
        try:
            cursor = source_csr_entry.to_db(cursor=cursor)
        except Exception as exp:
            error_title = "Failed to store Source's Consent Status Record"
            logger.error(error_title + ": " + repr(exp))
            raise ApiError(code=500,
                           title=error_title,
                           detail=repr(exp),
                           source=endpoint)
        finally:
            logger.debug("source_csr_entry: " + source_csr_entry.log_entry)

        # Store Sink CR
        try:
            cursor = sink_cr_entry.to_db(cursor=cursor)
        except Exception as exp:
            error_title = "Failed to store Sink's Consent Record"
            logger.error(error_title + ": " + repr(exp))
            raise ApiError(code=500,
                           title=error_title,
                           detail=repr(exp),
                           source=endpoint)
        finally:
            logger.debug("sink_cr_entry: " + sink_cr_entry.log_entry)

        # Link Sink's CSR with it's CR
        try:
            sink_csr_entry.consent_records_id = sink_cr_entry.id
        except Exception as exp:
            error_title = "Failed to link Sink's CSR with it's CR"
            logger.error(error_title + ": " + repr(exp))
            raise ApiError(code=500,
                           title=error_title,
                           detail=repr(exp),
                           source=endpoint)
        finally:
            logger.debug("sink_csr_entry: " + sink_csr_entry.log_entry)

        # Store Sink CSR
        try:
            cursor = sink_csr_entry.to_db(cursor=cursor)
        except Exception as exp:
            error_title = "Failed to store Sink's Consent Status Record"
            logger.error(error_title + ": " + repr(exp))
            raise ApiError(code=500,
                           title=error_title,
                           detail=repr(exp),
                           source=endpoint)
        finally:
            logger.debug("sink_csr_entry: " + sink_csr_entry.log_entry)

        # Commit
        db.connection.commit()
    except Exception as exp:
        logger.debug('commit failed: ' + repr(exp))
        db.connection.rollback()
        logger.debug('--> rollback')
        #raise ApiError(code=500, title="Failed to store CR's and CSR's", detail=repr(exp), source=endpoint)
        raise
    else:
        logger.info("CR's and CSR's commited")

        try:
            data = {
                'source': {
                    'CR': source_cr_entry.to_dict,
                    'CSR': source_csr_entry.to_dict
                },
                'sink': {
                    'CR': sink_cr_entry.to_dict,
                    'CSR': sink_csr_entry.to_dict
                }
            }
        except Exception as exp:
            logger.error("Could not construct data object: " + repr(exp))
            data = {}
        else:
            return data
Esempio n. 24
0
def get_auth_token_data(sink_cr_object=None, endpoint="get_auth_token_data()"):
    if sink_cr_object is None:
        raise AttributeError("Provide sink_cr_object as parameter")

    # Get DB cursor
    try:
        cursor = get_db_cursor()
    except Exception as exp:
        logger.error('Could not get database cursor: ' + repr(exp))
        raise ApiError(code=500,
                       title="Failed to get database cursor",
                       detail=repr(exp),
                       source=endpoint)

    # Get Sink's CR from DB
    try:
        cursor = sink_cr_object.from_db(cursor=cursor)
    except Exception as exp:
        error_title = "Failed to fetch Sink's CR from DB"
        logger.error(error_title + ": " + repr(exp))
        raise ApiError(code=404,
                       title=error_title,
                       detail=repr(exp),
                       source=endpoint)
    finally:
        logger.debug("sink_cr_object: " + sink_cr_object.log_entry)

    # Get required id's from Sink's CR
    try:
        sink_rs_id = str(sink_cr_object.resource_set_id)
        sink_slr_primary_key = str(sink_cr_object.service_link_records_id)
    except Exception as exp:
        error_title = "Failed to get id's from Sink's CR"
        logger.error(error_title + ": " + repr(exp))
        raise ApiError(code=500,
                       title=error_title,
                       detail=repr(exp),
                       source=endpoint)
    finally:
        logger.debug("sink_rs_id: " + sink_rs_id)

    # Init Source's Consent Record Object
    try:
        source_cr_entry = ConsentRecord(resource_set_id=sink_rs_id,
                                        role="Source")
    except Exception as exp:
        error_title = "Failed to create Source's Consent Record object"
        logger.error(error_title + ": " + repr(exp))
        raise ApiError(code=500,
                       title=error_title,
                       detail=repr(exp),
                       source=endpoint)
    finally:
        logger.debug("source_cr_entry: " + source_cr_entry.log_entry)

    # Get Source's Consent Record from DB
    source_cr = {}
    try:
        cursor = source_cr_entry.from_db(cursor=cursor)
        source_cr = source_cr_entry.consent_record
    except Exception as exp:
        error_title = "Failed to fetch Source's CR from DB"
        logger.error(error_title + ": " + repr(exp))
        raise ApiError(code=500,
                       title=error_title,
                       detail=repr(exp),
                       source=endpoint)
    finally:
        logger.debug("source_cr_entry: " + source_cr_entry.log_entry)
        logger.debug("source_cr: " + json.dumps(source_cr))

    # Init Sink's Service Link Record Object
    try:
        sink_slr_entry = ServiceLinkRecord(id=sink_slr_primary_key)
    except Exception as exp:
        error_title = "Failed to create Source's Service Link Record object"
        logger.error(error_title + ": " + repr(exp))
        raise ApiError(code=500,
                       title=error_title,
                       detail=repr(exp),
                       source=endpoint)
    finally:
        logger.debug("source_cr_entry: " + source_cr_entry.log_entry)

    # Get Source's Consent Record from DB
    sink_slr = {}
    try:
        cursor = sink_slr_entry.from_db(cursor=cursor)
        sink_slr = sink_slr_entry.service_link_record
    except Exception as exp:
        error_title = "Failed to fetch Sink's SLR from DB"
        logger.error(error_title + ": " + repr(exp))
        raise ApiError(code=500,
                       title=error_title,
                       detail=repr(exp),
                       source=endpoint)
    finally:
        logger.debug("sink_slr_entry: " + sink_slr_entry.log_entry)
        logger.debug("sink_slr: " + json.dumps(sink_slr))

    return source_cr, json.loads(sink_slr)
Esempio n. 25
0
def store_csr(account_id=None,
              record_id=None,
              cr_id=None,
              surrogate_id=None,
              consent_status=None,
              iat=None,
              prev_record_id=None,
              csr_signed=None,
              endpoint="store_csr()"):
    # Parameter Check
    if account_id is None:
        raise AttributeError("Provide account_id as parameter")
    if record_id is None:
        raise AttributeError("Provide record_id as parameter")
    if cr_id is None:
        raise AttributeError("Provide cr_id as parameter")
    if surrogate_id is None:
        raise AttributeError("Provide surrogate_id as parameter")
    if consent_status is None:
        raise AttributeError("Provide consent_status as parameter")
    if iat is None:
        raise AttributeError("Provide iat as parameter")
    if prev_record_id is None:
        raise AttributeError("Provide prev_record_id as parameter")
    if csr_signed is None:
        raise AttributeError("Provide csr_signed as parameter")

    # Parameter type check
    try:
        account_id = str(account_id)
    except Exception:
        raise TypeError("account_id MUST be str, not " + str(type(account_id)))

    try:
        record_id = str(record_id)
    except Exception:
        raise TypeError("record_id MUST be str, not " + str(type(record_id)))

    try:
        cr_id = str(cr_id)
    except Exception:
        raise TypeError("cr_id MUST be str, not " + str(type(cr_id)))

    try:
        surrogate_id = str(surrogate_id)
    except Exception:
        raise TypeError("surrogate_id MUST be str, not " +
                        str(type(surrogate_id)))

    try:
        consent_status = str(consent_status)
    except Exception:
        raise TypeError("consent_status MUST be str, not " +
                        str(type(consent_status)))

    try:
        iat = int(iat)
    except Exception:
        raise TypeError("iat MUST be int, not " + str(type(iat)))

    try:
        prev_record_id = str(prev_record_id)
    except Exception:
        raise TypeError("prev_record_id MUST be str, not " +
                        str(type(prev_record_id)))

    if not isinstance(csr_signed, dict):
        raise TypeError("csr_signed MUST be dict, not " +
                        str(type(csr_signed)))

    ######
    # Base information
    ####
    # Get DB cursor
    try:
        cursor = get_db_cursor()
    except Exception as exp:
        logger.error('Could not get database cursor: ' + repr(exp))
        raise ApiError(code=500,
                       title="Failed to get database cursor",
                       detail=repr(exp),
                       source=endpoint)

    ###########
    # Entries #
    ###########
    # Existing Consent Record
    ###
    # Init Consent Record Object
    try:
        logger.info("Create ConsentRecord object")
        cr_entry = ConsentRecord(consent_id=cr_id,
                                 accounts_id=account_id,
                                 surrogate_id=surrogate_id)
    except Exception as exp:
        error_title = "Failed to create Consent Record object"
        error_detail = str(exp.message)
        logger.error(error_title + ": " + repr(exp))
        raise RuntimeError(error_title + " - " + error_detail)
    else:
        logger.debug("cr_entry: " + cr_entry.log_entry)

    # Get Consent Record from DB
    try:
        logger.info("Get Consent Record from DB")
        cursor = cr_entry.from_db(cursor=cursor)
    except IndexError as exp:
        error_title = "Consent Record not found"
        error_detail = str(exp.message)
        logger.error(error_title + ": " + repr(exp))
        raise IndexError(error_title + " - " + error_detail)
    except Exception as exp:
        error_title = "Failed to fetch Consent Record"
        error_detail = str(exp.message)
        logger.error(error_title + ": " + repr(exp))
        raise RuntimeError(error_title + " - " + error_detail)
    else:
        logger.debug("cr_entry: " + cr_entry.log_entry)

    # Get primary key of Consent Record database entry
    try:
        logger.info("Get primary key of Consent Record database entry")
        cr_entry_primary_key = cr_entry.id
    except Exception as exp:
        error_title = "Failed to fetch Consent Record primary key"
        error_detail = repr(exp)
        logger.error(error_title + ": " + repr(exp))
        raise KeyError(error_title + " - " + error_detail)
    else:
        logger.debug("cr_entry_primary_key: " + str(cr_entry_primary_key))

    # CSR
    try:
        logger.info("Create ConsentStatusRecord object")
        csr_entry = ConsentStatusRecord(
            consent_status_record_id=record_id,
            status=consent_status,
            consent_status_record=csr_signed,
            consent_record_id=cr_id,
            issued_at=iat,
            prev_record_id=prev_record_id,
            consent_records_id=int(cr_entry_primary_key),
            accounts_id=int(account_id))
    except Exception as exp:
        error_title = "Failed to create Consent Status Record object"
        error_detail = repr(exp)
        logger.error(error_title + ": " + repr(exp))
        raise RuntimeError(error_title + " - " + error_detail)
    else:
        logger.info("csr_entry: " + csr_entry.log_entry)

    ###########
    # Store #
    ###########
    # CSR

    # Get database table name for Consent Status Record
    try:
        logger.info("Get Consent Status Record table name")
        csr_table_name = csr_entry.table_name
    except Exception as exp:
        error_title = "Could not get table name of Consent Status Record database table"
        error_detail = repr(exp)
        logger.error(error_title + ": " + repr(exp))
        raise RuntimeError(error_title + " - " + error_detail)
    else:
        logger.info("Got Consent Status Record table name: " +
                    str(csr_table_name))

    # Store CSR
    try:
        logger.info("Store ConsentStatusRecord")
        try:
            cursor = csr_entry.to_db(cursor=cursor)
        except Exception as exp:
            error_title = "Failed to store Consent Status Record of Sink Service"
            error_detail = repr(exp)
            logger.error(error_title + ": " + repr(exp))
            raise RuntimeError(error_title + " - " + error_detail)
        else:
            logger.debug("csr_entry: " + csr_entry.log_entry)

        # Commit
        db.connection.commit()
    except Exception as exp:
        logger.error('Consent Status Record Commit failed: ' + repr(exp))
        db.connection.rollback()
        logger.error('--> rollback')
        error_title = "Could not write to database"
        error_detail = repr(exp)
        logger.error(error_title + ": " + error_detail)
        raise
    else:
        logger.info("Consent Status Record commited")

    return csr_entry
Esempio n. 26
0
def get_last_slr_status(account_id=None,
                        slr_id=None,
                        endpoint="get_last_slr_status()"):
    if slr_id is None:
        raise AttributeError("Provide slr_id as parameter")
    if account_id is None:
        raise AttributeError("Provide account_id as parameter")

    # Get DB cursor
    try:
        cursor = get_db_cursor()
    except Exception as exp:
        logger.error('Could not get database cursor: ' + repr(exp))
        raise ApiError(code=500,
                       title="Failed to get database cursor",
                       detail=repr(exp),
                       source=endpoint)

    # Init ServiceLinkRecord Object
    try:
        logger.info("Create ServiceLinkRecord object")
        slr_entry = ServiceLinkRecord(service_link_record_id=slr_id,
                                      account_id=account_id)
        logger.info(slr_entry.log_entry)
    except Exception as exp:
        error_title = "Failed to create Service Link Record object"
        logger.error(error_title + ": " + repr(exp))
        raise ApiError(code=500,
                       title=error_title,
                       detail=repr(exp),
                       source=endpoint)
    else:
        logger.debug("slr_entry: " + slr_entry.log_entry)

    # Get ServiceLinkRecord from DB
    try:
        cursor = slr_entry.from_db(cursor=cursor)
    except IndexError as exp:
        error_title = "Service Link Status Record not found with provided information."
        error_detail = "Account ID was {} and Service Link Record ID was {}.".format(
            account_id, slr_id)
        logger.error(error_title + " " + error_detail + ": " + repr(exp))
        raise ApiError(code=404,
                       title=error_title,
                       detail=error_detail,
                       source=endpoint)
    except Exception as exp:
        error_title = "Failed to fetch Service Link Record from DB"
        logger.error(error_title + ": " + repr(exp))
        raise ApiError(code=500,
                       title=error_title,
                       detail=str(exp.message),
                       source=endpoint)
    else:
        logger.debug("slr_entry: " + slr_entry.log_entry)

    # Create ServiceLinkStatusRecord object
    try:
        slsr_entry = ServiceLinkStatusRecord()
    except Exception as exp:
        error_title = "Failed to create ServiceLinkStatusRecord object"
        logger.error(error_title + ": " + repr(exp))
        raise ApiError(code=500,
                       title=error_title,
                       detail=repr(exp),
                       source=endpoint)
    else:
        logger.debug("slsr_entry: " + slsr_entry.log_entry)

    # Get database table name for ServiceLinkStatusRecord
    try:
        logger.info("Get ServiceLinkStatusRecord table name")
        slsr_table_name = slsr_entry.table_name
    except Exception as exp:
        error_title = "Failed to get ServiceLinkStatusRecord table name"
        logger.error(error_title + ": " + repr(exp))
        raise ApiError(code=500,
                       title=error_title,
                       detail=repr(exp),
                       source=endpoint)
    else:
        logger.info("Got ServiceLinkStatusRecord table name: " +
                    str(slsr_table_name))

    # Get ServiceLinkStatusRecord ID
    try:
        cursor, slsr_id = get_last_slsr_id(cursor=cursor,
                                           slr_id=slr_id,
                                           table_name=slsr_table_name)
    except IndexError as exp:
        error_title = "ServiceLinkStatusRecord not found from DB with given Consent Record ID"
        logger.error(error_title + ": " + repr(exp))
        raise ApiError(code=404,
                       title=error_title,
                       detail=repr(exp),
                       source=endpoint)
    except Exception as exp:
        error_title = "Failed to get last ServiceLinkStatusRecord ID from database"
        logger.error(error_title + ": " + repr(exp))
        raise ApiError(code=500,
                       title=error_title,
                       detail=repr(exp),
                       source=endpoint)
    else:
        logger.debug("slsr_id: " + str(slsr_id))

    # Append ID to ServiceLinkStatusRecord Object
    try:
        logger.info("Append ID to ServiceLinkStatusRecord object: " +
                    slsr_entry.log_entry)
        slsr_entry.service_link_status_record_id = slsr_id
    except Exception as exp:
        error_title = "Failed to append ID to ServiceLinkStatusRecord object"
        logger.error(error_title + ": " + repr(exp))
        raise ApiError(code=500,
                       title=error_title,
                       detail=repr(exp),
                       source=endpoint)
    else:
        logger.info("Appended ID to ServiceLinkStatusRecord object: " +
                    slsr_entry.log_entry)

    # Get ServiceLinkStatusRecord from DB
    try:
        cursor = slsr_entry.from_db(cursor=cursor)
    except IndexError as exp:
        error_title = "ServiceLinkStatusRecord not found from DB with given ID"
        logger.error(error_title + ": " + repr(exp))
        raise ApiError(code=404,
                       title=error_title,
                       detail=repr(exp),
                       source=endpoint)
    except Exception as exp:
        error_title = "Failed to fetch ServiceLinkStatusRecord from DB"
        logger.error(error_title + ": " + repr(exp))
        raise ApiError(code=500,
                       title=error_title,
                       detail=repr(exp),
                       source=endpoint)
    else:
        logger.debug("slsr_entry: " + slsr_entry.log_entry)

    return slsr_entry.to_api_dict
Esempio n. 27
0
def get_cr(cr_id="",
           surrogate_id="",
           slr_id="",
           subject_id="",
           consent_pair_id="",
           account_id="",
           cursor=None):
    """
    Get Consent Record entry
    :param account_id:
    :param slr_id:
    :return: dict
    """
    try:
        cr_id = str(cr_id)
    except Exception:
        raise TypeError("cr_id MUST be str, not " + str(type(cr_id)))
    try:
        surrogate_id = str(surrogate_id)
    except Exception:
        raise TypeError("surrogate_id MUST be str, not " +
                        str(type(surrogate_id)))
    try:
        slr_id = str(slr_id)
    except Exception:
        raise TypeError("slr_id MUST be str, not " + str(type(slr_id)))
    try:
        subject_id = str(subject_id)
    except Exception:
        raise TypeError("subject_id MUST be str, not " + str(type(subject_id)))
    try:
        consent_pair_id = str(consent_pair_id)
    except Exception:
        raise TypeError("consent_pair_id MUST be str, not " +
                        str(type(consent_pair_id)))
    try:
        account_id = str(account_id)
    except Exception:
        raise TypeError("account_id MUST be str, not " + str(type(account_id)))

    if cursor is None:
        # Get DB cursor
        try:
            cursor = get_db_cursor()
        except Exception as exp:
            logger.error('Could not get database cursor: ' + repr(exp))
            raise

    try:
        db_entry_object = ConsentRecord(consent_id=cr_id,
                                        surrogate_id=surrogate_id,
                                        service_link_record_id=slr_id,
                                        subject_id=subject_id,
                                        consent_pair_id=consent_pair_id,
                                        accounts_id=account_id)
    except Exception as exp:
        error_title = "Failed to create ConsentRecord object"
        logger.error(error_title + ": " + repr(exp))
        raise
    else:
        logger.debug("ConsentRecord object created: " +
                     db_entry_object.log_entry)

    # Get slr from DB
    try:
        cursor = db_entry_object.from_db(cursor=cursor)
    except Exception as exp:
        error_title = "Failed to fetch ConsentRecord from DB"
        logger.error(error_title + ": " + repr(exp))
        raise
    else:
        logger.info("ConsentRecord fetched")
        logger.debug("ConsentRecord fetched from db: " +
                     db_entry_object.log_entry)

    return db_entry_object.to_api_dict, str(db_entry_object.accounts_id)
Esempio n. 28
0
def init_slr_sink(account_id=None,
                  slr_id=None,
                  pop_key=None,
                  endpoint="init_slr_sink()"):

    logger.info("init_slr_sink()")

    if account_id is None:
        raise AttributeError("Provide account_id as parameter")
    if slr_id is None:
        raise AttributeError("Provide slr_id as parameter")
    if pop_key is None:
        raise AttributeError("Provide pop_key as parameter")

    if not isinstance(account_id, str):
        try:
            account_id = str(account_id)
        except Exception:
            raise TypeError("account_id MUST be str, not " +
                            str(type(account_id)))
    if not isinstance(slr_id, str):
        try:
            slr_id = str(slr_id)
        except Exception:
            raise TypeError("slr_id MUST be str, not " + str(type(slr_id)))
    if not isinstance(pop_key, dict):
        try:
            pop_key = dict(pop_key)
        except Exception:
            raise TypeError("pop_key MUST be dict, not " + str(type(pop_key)))
    if not isinstance(endpoint, str):
        try:
            endpoint = str(endpoint)
        except Exception:
            raise TypeError("endpoint MUST be str, not " + str(type(endpoint)))

    logger.info("Initing SLR")
    try:
        slr_entry = ServiceLinkRecord(service_link_record_id=slr_id,
                                      account_id=account_id,
                                      pop_key=pop_key)
    except Exception as exp:
        logger.error('Could not create Service Link Record object: ' +
                     repr(exp))
        raise ApiError(code=500,
                       title="Failed to create Service Link Record object",
                       detail=repr(exp),
                       source=endpoint)
    else:
        logger.info("Service Link Record entry created")
        logger.debug(slr_entry.log_entry)

    # Get DB cursor
    try:
        cursor = get_db_cursor()
    except Exception as exp:
        logger.error('Could not get database cursor: ' + repr(exp))
        raise ApiError(code=500,
                       title="Failed to get database cursor",
                       detail=repr(exp),
                       source=endpoint)

    # Store DB entry
    try:
        cursor = slr_entry.to_db(cursor=cursor)
        slr_id = slr_entry.service_link_record_id
        db.connection.commit()
    except IntegrityError as exp:
        error_title = "Service Link ID already exists"
        error_detail = str(exp.args[1])
        logger.error(error_title + " - " + error_detail)
        db.connection.rollback()
        logger.debug('--> rollback')
        raise ApiError(code=409,
                       title=error_title,
                       detail=error_detail,
                       source=endpoint)
    except Exception as exp:
        logger.error('Slr init commit failed: ' + repr(exp))
        db.connection.rollback()
        logger.debug('--> rollback')
        raise ApiError(code=500,
                       title="Failed to store init SLR",
                       detail=repr(exp),
                       source=endpoint)
    else:
        logger.info('Slr initialized commited')
        logger.debug("slr_entry: " + slr_entry.log_entry)
        return slr_id
Esempio n. 29
0
    def post(self):
        """
        Example JSON
        {
          "username": "******",
          "password": "******",
          "firstName": "string",
          "lastName": "string",
          "email": "*****@*****.**",
          "dateOfBirth": "18-08-2016",
          "acceptTermsOfService": "True"
        }
        :return:
        """

        try:
            endpoint = str(api.url_for(self))
        except Exception as exp:
            endpoint = str(__name__)

        # load JSON
        json_data = request.get_json()
        if not json_data:
            error_detail = {'0': 'Set application/json as Content-Type', '1': 'Provide json payload'}
            raise ApiError(code=400, title="No input data provided", detail=error_detail, source=endpoint)
        else:
            logger.debug("json_data: " + json.dumps(json_data))

        # Validate payload content
        schema = AccountSchema2()
        schema_validation_result = schema.load(json_data)

        # Check validation errors
        if schema_validation_result.errors:
            logger.error("Invalid payload")
            raise ApiError(code=400, title="Invalid payload", detail=dict(schema_validation_result.errors), source=endpoint)
        else:
            logger.debug("JSON validation -> OK")

        try:
            username = json_data['username']
            password = json_data['password']
            firstName = json_data['firstName']
            lastName = json_data['lastName']
            email_address = json_data['email']
            dateOfBirth = json_data['dateOfBirth']
            acceptTermsOfService = json_data['acceptTermsOfService']

            global_identifier = str(uuid.uuid4())
            salt_str = str(bcrypt.gensalt())
            pwd_hash = bcrypt.hashpw(str(password), salt_str)
        except Exception as exp:
            error_title = "Could not prepare Account data"
            logger.error(error_title)
            raise ApiError(code=400, title=error_title, detail=repr(exp), source=endpoint)

        # DB cursor
        cursor = get_db_cursor()

        try:
            ###
            # Accounts
            logger.debug('Accounts')
            account = Account(global_identifyer=global_identifier)
            account.to_db(cursor=cursor)

            ###
            # localIdentityPWDs
            logger.debug('localIdentityPWDs')
            local_pwd = LocalIdentityPWD(password=pwd_hash)
            local_pwd.to_db(cursor=cursor)

            ###
            # localIdentities
            logger.debug('localIdentities')
            local_identity = LocalIdentity(
                username=username,
                pwd_id=local_pwd.id,
                accounts_id=account.id
            )
            local_identity.to_db(cursor=cursor)

            ###
            # salts
            logger.debug('salts')
            salt = Salt(
                salt=salt_str,
                identity_id=local_identity.id
            )
            salt.to_db(cursor=cursor)

            ###
            # Particulars
            logger.debug('particulars')
            particulars = Particulars(
                firstname=firstName,
                lastname=lastName,
                date_of_birth=dateOfBirth,
                account_id=account.id
            )
            logger.debug("to_dict: " + repr(particulars.to_dict))
            cursor = particulars.to_db(cursor=cursor)

            ###
            # emails
            logger.debug('emails')
            email = Email(
                email=email_address,
                type="Personal",
                prime=1,
                account_id=account.id
            )
            email.to_db(cursor=cursor)

            ###
            # Commit
            db.connection.commit()
        except Exception as exp:
            error_title = "Could not create Account"
            logger.debug('commit failed: ' + repr(exp))
            logger.debug('--> rollback')
            logger.error(error_title)
            db.connection.rollback()
            raise ApiError(code=500, title=error_title, detail=repr(exp), source=endpoint)
        else:
            logger.debug('Account commited')

            try:
                logger.info("Generating Key for Account")
                kid = gen_account_key(account_id=account.id)
            except Exception as exp:
                error_title = "Could not generate Key for Account"
                logger.debug(error_title + ': ' + repr(exp))
                #raise ApiError(code=500, title=error_title, detail=repr(exp), source=endpoint)
            else:
                logger.info("Generated Key for Account with Key ID: " + str(kid))

            try:
                logger.info("Generating API Key for Account")
                api_key = gen_account_api_key(account_id=account.id)
            except Exception as exp:
                error_title = "Could not generate API Key for Account"
                logger.debug(error_title + ': ' + repr(exp))
                #raise ApiError(code=500, title=error_title, detail=repr(exp), source=endpoint)
            else:
                logger.info("Generated API Key: " + str(api_key))

            data = cursor.fetchall()
            logger.debug('data: ' + repr(data))

        # Response data container
        try:
            response_data = {}
            response_data['meta'] = {}
            response_data['meta']['activationInstructions'] = "Account activated already"

            response_data['data'] = {}
            response_data['data']['type'] = "Account"
            response_data['data']['id'] = str(account.id)
            response_data['data']['attributes'] = {}
            response_data['data']['attributes']['username'] = username
            response_data['data']['attributes']['firstName'] = firstName
            response_data['data']['attributes']['lastName'] = lastName
            response_data['data']['attributes']['email'] = email_address
            response_data['data']['attributes']['dateOfBirth'] = dateOfBirth
            response_data['data']['attributes']['acceptTermsOfService'] = acceptTermsOfService
        except Exception as exp:
            logger.error('Could not prepare response data: ' + repr(exp))
            raise ApiError(code=500, title="Could not prepare response data", detail=repr(exp), source=endpoint)
        else:
            logger.info('Response data ready')
            logger.debug('response_data: ' + repr(response_data))

        response_data_dict = dict(response_data)
        logger.debug('response_data_dict: ' + repr(response_data_dict))
        return make_json_response(data=response_data_dict, status_code=201)
Esempio n. 30
0
def get_slr_record(account_id=None, slr_id=None, endpoint="get_slr_record()"):

    logger.info("get_slr_record()")

    if account_id is None:
        raise AttributeError("Provide account_id as parameter")
    if slr_id is None:
        raise AttributeError("Provide slr_id as parameter")

    if not isinstance(account_id, str):
        try:
            account_id = str(account_id)
        except Exception:
            raise TypeError("account_id MUST be str, not " +
                            str(type(account_id)))
    if not isinstance(slr_id, str):
        try:
            slr_id = str(slr_id)
        except Exception:
            raise TypeError("slr_id MUST be str, not " + str(type(slr_id)))
    if not isinstance(endpoint, str):
        try:
            endpoint = str(endpoint)
        except Exception:
            raise TypeError("endpoint MUST be str, not " + str(type(endpoint)))

    logger.info("Creating ServiceLinkRecord object")
    try:
        slr_entry = ServiceLinkRecord(service_link_record_id=slr_id,
                                      account_id=account_id)
    except Exception as exp:
        logger.error('Could not create Service Link Record object: ' +
                     repr(exp))
        raise ApiError(code=500,
                       title="Failed to create Service Link Record object",
                       detail=repr(exp),
                       source=endpoint)
    else:
        logger.info("Service Link Record entry created")
        logger.debug(slr_entry.log_entry)

    # Get DB cursor
    try:
        cursor = get_db_cursor()
    except Exception as exp:
        logger.error('Could not get database cursor: ' + repr(exp))
        raise ApiError(code=500,
                       title="Failed to get database cursor",
                       detail=repr(exp),
                       source=endpoint)

    logger.info("Get ServiceLinkRecord from database")
    try:
        cursor = slr_entry.from_db(cursor=cursor)
    except Exception as exp:
        error_title = "Could not get ServiceLinkRecord from database"
        error_detail = str(exp.message)
        logger.error(error_title + " - " + error_detail)
        raise
    else:
        logger.info('Got ServiceLinkRecord from database')
        logger.debug("slr_entry: " + slr_entry.log_entry)
        return slr_entry