async def get_all_lab_tests(request): """Fetches complete details of all Accounts in state""" client_key = general.get_request_key_header(request) # lab_tests_address = helper.make_lab_test_list_address() # lab_test_resources = await messaging.get_state_by_address(request.app.config.VAL_CONN, lab_tests_address) lab_tests = await security_messaging.get_lab_tests( request.app.config.VAL_CONN, client_key) # account_resources2 = MessageToJson(account_resources) # account_resources3 = MessageToDict(account_resources) lab_tests_json = [] # for entity in lab_test_resources.entries: for address, lt in lab_tests.items(): # dec_cl = base64.b64decode(entity.data) # lt = payload_pb2.AddLabTest() # lt.ParseFromString(entity.data) lab_tests_json.append({ 'height': lt.height, 'weight': lt.weight, 'gender': lt.gender, 'a_g_ratio': lt.a_g_ratio, 'albumin': lt.albumin, 'alkaline_phosphatase': lt.alkaline_phosphatase, 'appearance': lt.appearance, 'bilirubin': lt.bilirubin, 'casts': lt.casts, 'color': lt.color, 'name': lt.name, 'surname': lt.surname }) # import json # result = json.dumps(clinics) # clinics_json = MessageToJson(account_resources) return response.json(body={'data': lab_tests_json}, headers=general.get_response_headers())
async def get_all_doctors(request): """Fetches complete details of all Accounts in state""" client_key = general.get_request_key_header(request) # list_doctors_address = helper.make_doctor_list_address() doctors = await security_messaging.get_doctors(request.app.config.VAL_CONN, client_key) # account_resources2 = MessageToJson(account_resources) # account_resources3 = MessageToDict(account_resources) doctors_json = [] for address, doc in doctors.items(): # dec_cl = base64.b64decode(entity.data) # doc = payload_pb2.CreateDoctor() # doc.ParseFromString(entity.data) # permissions = [] # for perm in doc.permissions: # permissions.append(perm) # doctors.append({'name': doc.name, 'surname': doc.surname, 'permissions': str(permissions)}) doctors_json.append({ 'public_key': doc.public_key, 'name': doc.name, 'surname': doc.surname }) # import json # result = json.dumps(clinics) # clinics_json = MessageToJson(account_resources) return response.json(body={'data': doctors_json}, headers=general.get_response_headers())
async def grant_access(request, doctor_pkey): """Updates auth information for the authorized account""" client_key = general.get_request_key_header(request) client_signer = general.get_signer(request, client_key) grant_access_txn = consent_transaction.grant_access( txn_signer=client_signer, batch_signer=client_signer, doctor_pkey=doctor_pkey) batch, batch_id = transaction.make_batch_and_id([grant_access_txn], client_signer) await security_messaging.grant_access(request.app.config.VAL_CONN, request.app.config.TIMEOUT, [batch], client_key) try: await security_messaging.check_batch_status( request.app.config.VAL_CONN, [batch_id]) except (ApiBadRequest, ApiInternalError) as err: # await auth_query.remove_auth_entry( # request.app.config.DB_CONN, request.json.get('email')) raise err return response.json(body={'status': general.DONE}, headers=general.get_response_headers())
async def add_new_contract(request): """Updates auth information for the authorized account""" client_key = general.get_request_key_header(request) required_fields = ['id', 'client_pkey'] general.validate_fields(required_fields, request.json) uid = request.json.get('id') contractor_pkey = request.json.get('client_pkey') client_signer = general.get_signer(request, client_key) contract_txn = transaction.add_contract( txn_signer=client_signer, batch_signer=client_signer, uid=uid, client_pkey=contractor_pkey ) batch, batch_id = transaction.make_batch_and_id([contract_txn], client_signer) await security_messaging.add_contract( request.app.config.VAL_CONN, request.app.config.TIMEOUT, [batch], client_key) try: await security_messaging.check_batch_status( request.app.config.VAL_CONN, [batch_id]) except (ApiBadRequest, ApiInternalError) as err: # await auth_query.remove_auth_entry( # request.app.config.DB_CONN, request.json.get('email')) raise err return response.json(body={'status': general.DONE}, headers=general.get_response_headers())
async def eat_pills(request): claim_id = request.json.get('claim_id') current_times_str = str(time.time()) # private_key = common.get_signer_from_file(keyfile) # signer = CryptoFactory(request.app.config.CONTEXT).new_signer(private_key) clinic_signer = request.app.config.SIGNER # .get_public_key().as_hex() batch, batch_id = transaction.eat_pills( txn_signer=clinic_signer, batch_signer=clinic_signer, claim_id=claim_id, description="Eat pills in scope of claim: {}".format(claim_id), event_time=current_times_str) await messaging.send(request.app.config.VAL_CONN, request.app.config.TIMEOUT, [batch]) try: await messaging.check_batch_status(request.app.config.VAL_CONN, [batch_id]) except (ApiBadRequest, ApiInternalError) as err: # await auth_query.remove_auth_entry( # request.app.config.DB_CONN, request.json.get('email')) raise err return response.json(body={'status': general.DONE}, headers=general.get_response_headers())
async def get_all_pulse_items(request): """Fetches complete details of all Accounts in state""" LOGGER.debug("Call 'pulse' request") client_key = general.get_request_key_header(request) # pulse_list_address = helper.make_pulse_list_address() # pulse_resources = await messaging.get_state_by_address(request.app.config.VAL_CONN, pulse_list_address) pulse_list = await security_messaging.get_pulse_list( request.app.config.VAL_CONN, client_key) # account_resources2 = MessageToJson(account_resources) # account_resources3 = MessageToDict(account_resources) pulse_list_json = [] for address, pl in pulse_list.items(): # dec_cl = base64.b64decode(entity.data) # pl = payload_pb2.AddPulse() # pl.ParseFromString(entity.data) pulse_list_json.append({ 'client_pkey': pl.client_pkey, 'pulse': pl.pulse, 'timestamp': pl.timestamp, 'name': pl.name, 'surname': pl.surname }) return response.json(body={'data': pulse_list_json}, headers=general.get_response_headers())
async def get_all_claim_details(request, clinic_pkey, claim_id): """Fetches complete details of all Accounts in state""" # list_claim_details_address = helper.make_claim_address(claim_id=claim_id, clinic_pkey=clinic_pkey) list_claim_details_address = helper.make_event_list_address( claim_id=claim_id, clinic_pkey=clinic_pkey) claim_details_resources = await messaging.get_state_by_address( request.app.config.VAL_CONN, list_claim_details_address) # account_resources2 = MessageToJson(account_resources) # account_resources3 = MessageToDict(account_resources) claim_details = [] for entity in claim_details_resources.entries: # dec_cl = base64.b64decode(entity.data) cld = payload_pb2.ActionOnClaim() cld.ParseFromString(entity.data) claim_details.append({ 'clinic_pkey': cld.clinic_pkey, 'claim_id': cld.claim_id, 'description': cld.description, 'event': cld.event, 'event_time': cld.event_time }) # import json # result = json.dumps(clinics) # clinics_json = MessageToJson(account_resources) return response.json(body={'data': claim_details}, headers=general.get_response_headers())
async def next_visit(request): required_fields = ['claim_id', 'doctor_pkey'] general.validate_fields(required_fields, request.json) claim_id = request.json.get('claim_id') doctor_pkey = request.json.get('doctor_pkey') current_times_str = str(time.time()) # private_key = common.get_signer_from_file(keyfile) # signer = CryptoFactory(request.app.config.CONTEXT).new_signer(private_key) clinic_signer = request.app.config.SIGNER # .get_public_key().as_hex() batch, batch_id = transaction.next_visit( txn_signer=clinic_signer, batch_signer=clinic_signer, claim_id=claim_id, description="Doctor: {}, completed next visit for claim: {}".format( doctor_pkey, claim_id), event_time=current_times_str) await messaging.send(request.app.config.VAL_CONN, request.app.config.TIMEOUT, [batch]) try: await messaging.check_batch_status(request.app.config.VAL_CONN, [batch_id]) except (ApiBadRequest, ApiInternalError) as err: # await auth_query.remove_auth_entry( # request.app.config.DB_CONN, request.json.get('email')) raise err return response.json(body={'status': general.DONE}, headers=general.get_response_headers())
async def register_new_claim(request): """Updates auth information for the authorized account""" # keyfile = common.get_keyfile(request.json.get['signer']) clinic_pkey = general.get_request_key_header(request) required_fields = ['patient_pkey', 'claim_id', 'description'] general.validate_fields(required_fields, request.json) patient_pkey = request.json.get('patient_pkey') claim_id = request.json.get('claim_id') description = request.json.get('description') contract_id = request.json.get('contract_id') if contract_id is not None and contract_id != '': is_valid = await security_messaging.valid_contracts( request.app.config.VAL_CONN, patient_pkey, contract_id) if not is_valid: return response.text(body="Contract having '" + contract_id + "' id is not valid", status=ApiBadRequest.status_code, headers=general.get_response_headers()) client_signer = general.get_signer(request, clinic_pkey) claim_txn = transaction.add_claim(txn_signer=client_signer, batch_signer=client_signer, uid=claim_id, description=description, client_pkey=patient_pkey, contract_id=contract_id) batch, batch_id = transaction.make_batch_and_id([claim_txn], client_signer) await security_messaging.add_claim(request.app.config.VAL_CONN, request.app.config.TIMEOUT, [batch], clinic_pkey, patient_pkey) try: await security_messaging.check_batch_status( request.app.config.VAL_CONN, [batch_id]) except (ApiBadRequest, ApiInternalError) as err: # await auth_query.remove_auth_entry( # request.app.config.DB_CONN, request.json.get('email')) raise err return response.json(body={'status': general.DONE}, headers=general.get_response_headers())
async def get_all_clinics(request): """Fetches complete details of all Accounts in state""" client_key = general.get_request_key_header(request) clinic_list = await security_messaging.get_clinics(request.app.config.VAL_CONN, client_key) clinic_list_json = [] for address, cl in clinic_list.items(): clinic_list_json.append({ 'public_key': cl.public_key, 'name': cl.name }) return response.json(body={'data': clinic_list_json}, headers=general.get_response_headers())
async def get_all_insurances(request): """Fetches complete details of all Accounts in state""" client_key = general.get_request_key_header(request) insurances = await security_messaging.get_insurances( request.app.config.VAL_CONN, client_key) insurances_json = [] for address, ins in insurances.items(): insurances_json.append({ 'name': ins.name, 'public_key': ins.public_key }) return response.json(body={'data': insurances_json}, headers=general.get_response_headers())
async def update_claim(request): """Updates auth information for the authorized account""" # keyfile = common.get_keyfile(request.json.get['signer']) clinic_pkey = general.get_request_key_header(request) required_fields = [ 'claim_id', 'provided_service', 'client_pkey', 'provided_service' ] general.validate_fields(required_fields, request.json) claim_id = request.json.get('claim_id') provided_service = request.json.get('provided_service') patient_pkey = request.json.get('client_pkey') contract_id = request.json.get('contract_id') client_signer = general.get_signer(request, clinic_pkey) close_claim_txn = transaction.update_claim( txn_signer=client_signer, batch_signer=client_signer, uid=claim_id, patient_pkey=patient_pkey, provided_service=provided_service) # create_payment_txn = payment_transaction.create_payment( # txn_signer=client_signer, # batch_signer=client_signer, # payment_id=str(helper.get_current_timestamp()), # patient_pkey=patient_pkey, # contract_id=contract_id, # claim_id=claim_id # ) batch, batch_id = transaction.make_batch_and_id([close_claim_txn], client_signer) await security_messaging.update_claim(request.app.config.VAL_CONN, request.app.config.TIMEOUT, [batch], clinic_pkey, patient_pkey) try: await security_messaging.check_batch_status( request.app.config.VAL_CONN, [batch_id]) except (ApiBadRequest, ApiInternalError) as err: # await auth_query.remove_auth_entry( # request.app.config.DB_CONN, request.json.get('email')) raise err return response.json(body={'status': general.DONE}, headers=general.get_response_headers())
async def get_all_contacts(request): """Fetches complete details of all Accounts in state""" LOGGER.debug("Call 'contract' request") client_key = general.get_request_key_header(request) contract_list = await security_messaging.get_contracts(request.app.config.VAL_CONN, client_key) contract_list_json = [] for address, con in contract_list.items(): contract_list_json.append({ 'client_pkey': con.client_pkey, 'id': con.id, 'name': con.name, 'surname': con.surname }) return response.json(body={'data': contract_list_json}, headers=general.get_response_headers())
async def get_all_clients(request): """Fetches complete details of all Accounts in state""" clinic_pkey = request.app.config.SIGNER_CLINIC.get_public_key().as_hex() doctor_pkey = request.app.config.SIGNER_DOCTOR.get_public_key().as_hex() patient_pkey = request.app.config.SIGNER_PATIENT.get_public_key().as_hex() lab_pkey = request.app.config.SIGNER_LAB.get_public_key().as_hex() insurance_pkey = request.app.config.SIGNER_INSURANCE.get_public_key( ).as_hex() clients = { 'clinic': clinic_pkey, 'doctor': doctor_pkey, 'patient': patient_pkey, 'lab': lab_pkey, 'insurance': insurance_pkey } return response.json(body={'data': clients}, headers=general.get_response_headers())
async def get_all_payments(request): """Fetches complete details of all Accounts in state""" LOGGER.debug("Call 'payment' request") client_key = general.get_request_key_header(request) payment_list = await security_messaging.get_payments( request.app.config.VAL_CONN, client_key) payment_list_json = [] for address, pay in payment_list.items(): payment_list_json.append({ 'patient_pkey': pay.patient_pkey, 'contract_id': pay.contract_id, 'claim_id': pay.claim_id, 'id': pay.id, 'timestamp': pay.timestamp }) return response.json(body={'data': payment_list_json}, headers=general.get_response_headers())
async def register_new_clinic(request): """Updates auth information for the authorized account""" # keyfile = common.get_keyfile(request.json.get['signer']) # client_key = general.get_request_key_header(request) required_fields = ['name'] general.validate_fields(required_fields, request.json) name = request.json.get('name') # private_key = common.get_signer_from_file(keyfile) # signer = CryptoFactory(request.app.config.CONTEXT).new_signer(private_key) clinic_signer = request.app.config.SIGNER_CLINIC # .get_public_key().as_hex() client_txn = consent_transaction.create_clinic_client( txn_signer=clinic_signer, batch_signer=clinic_signer ) clinic_txn = transaction.create_clinic( txn_signer=clinic_signer, batch_signer=clinic_signer, name=name ) batch, batch_id = transaction.make_batch_and_id([client_txn, clinic_txn], clinic_signer) # batch, batch_id = transaction.create_clinic( # txn_signer=clinic_signer, # batch_signer=clinic_signer, # name=name) await security_messaging.add_clinic( request.app.config.VAL_CONN, request.app.config.TIMEOUT, [batch]) try: await security_messaging.check_batch_status( request.app.config.VAL_CONN, [batch_id]) except (ApiBadRequest, ApiInternalError) as err: # await auth_query.remove_auth_entry( # request.app.config.DB_CONN, request.json.get('email')) raise err return response.json(body={'status': general.DONE}, headers=general.get_response_headers())
async def get_all_claims(request): client_key = general.get_request_key_header(request) claim_list = await security_messaging.get_claims( request.app.config.VAL_CONN, client_key) claim_list_json = [] for address, cl in claim_list.items(): claim_list_json.append({ 'client_pkey': cl.client_pkey, 'id': cl.id, 'description': cl.description, 'provided_service': cl.provided_service, 'state': cl.state, 'contract_id': cl.contract_id, 'name': cl.name, 'surname': cl.surname }) return response.json(body={'data': claim_list_json}, headers=general.get_response_headers())
async def add_new_pulse(request): """Updates auth information for the authorized account""" # keyfile = common.get_keyfile(request.json.get['signer']) client_key = general.get_request_key_header(request) required_fields = ['pulse', 'timestamp'] general.validate_fields(required_fields, request.json) pulse = request.json.get('pulse') timestamp = request.json.get('timestamp') # private_key = common.get_signer_from_file(keyfile) # signer = CryptoFactory(request.app.config.CONTEXT).new_signer(private_key) # patient_signer = request.app.config.SIGNER # .get_public_key().as_hex() client_signer = general.get_signer(request, client_key) current_times_str = str(helper.get_current_timestamp()) pulse_txn = transaction.add_pulse(txn_signer=client_signer, batch_signer=client_signer, pulse=pulse, uid=current_times_str, timestamp=timestamp, client_pkey=client_key) batch, batch_id = transaction.make_batch_and_id([pulse_txn], client_signer) await security_messaging.add_pulse(request.app.config.VAL_CONN, request.app.config.TIMEOUT, [batch], client_key) try: await security_messaging.check_batch_status( request.app.config.VAL_CONN, [batch_id]) except (ApiBadRequest, ApiInternalError) as err: # await auth_query.remove_auth_entry( # request.app.config.DB_CONN, request.json.get('email')) raise err return response.json(body={'status': general.DONE}, headers=general.get_response_headers())
async def get_patient_basic_info(request): """Fetches complete details of all Accounts in state""" idcard = request.headers['idcard'] headers = {'Content-Type': 'application/json'} dataParty = {"username": idcard} response_load = requests.post('http://validator:8863/getPrivateKey', data=GeneralTool().parse2JSON(dataParty), headers=headers) if response_load.status_code != 200: raise Exception( "There was a problem communicating with the validator.") elif response_load.status_code == 200: keys = GeneralTool().parseFromJSON(response_load.content.decode()) public_key = keys['public_key'] party = await security_messaging.get_party(request.app.config.VAL_CONN, public_key) patientKey = '{}|{}'.format(public_key, '0' + str(_client_type_)) patient = await security_messaging.get_patient( request.app.config.VAL_CONN, patientKey) patient_list_json = [] patient_list_json.append({ 'name': party.name, 'lastname': party.lastname, 'telephone': party.telephone, 'birthdate': party.birthdate, 'idcard': party.idcard, 'sex': patient.biological_sex, 'photo': patient.photo, 'insurance': patient.current_insurance, 'blood_type': patient.blood_type }) return response.json(body={'data': patient_list_json}, headers=general.get_response_headers()) else: raise Exception("User with no patient registred.")
async def get_all_labs(request): """Fetches complete details of all Accounts in state""" client_key = general.get_request_key_header(request) # list_lab_address = helper.make_lab_list_address() lab_resources = await security_messaging.get_labs( request.app.config.VAL_CONN, client_key) # account_resources2 = MessageToJson(account_resources) # account_resources3 = MessageToDict(account_resources) labs = [] for entity in lab_resources.entries: # dec_cl = base64.b64decode(entity.data) lab = payload_pb2.CreateLab() lab.ParseFromString(entity.data) # permissions = [] # for perm in cl.permissions: # permissions.append(perm) labs.append({'name': lab.name}) # import json # result = json.dumps(clinics) # clinics_json = MessageToJson(account_resources) return response.json(body={'data': labs}, headers=general.get_response_headers())
async def add_new_payment(request): """Updates auth information for the authorized account""" # keyfile = common.get_keyfile(request.json.get['signer']) client_key = general.get_request_key_header(request) required_fields = ['patient_pkey', 'contract_id', 'claim_id'] general.validate_fields(required_fields, request.json) # uid = request.json.get('id') patient_pkey = request.json.get('patient_pkey') contract_id = request.json.get('contract_id') claim_id = request.json.get('claim_id') client_signer = general.get_signer(request, client_key) payment_id = str(helper.get_current_timestamp()) batch, batch_id = transaction.create_payment(txn_signer=client_signer, batch_signer=client_signer, payment_id=payment_id, patient_pkey=patient_pkey, contract_id=contract_id, claim_id=claim_id) await security_messaging.create_payment(request.app.config.VAL_CONN, request.app.config.TIMEOUT, [batch], client_key) try: await security_messaging.check_batch_status( request.app.config.VAL_CONN, [batch_id]) except (ApiBadRequest, ApiInternalError) as err: # await auth_query.remove_auth_entry( # request.app.config.DB_CONN, request.json.get('email')) raise err return response.json(body={'status': general.DONE}, headers=general.get_response_headers())
async def register_new_insurance(request): """Updates auth information for the authorized account""" # keyfile = common.get_keyfile(request.json.get['signer']) required_fields = ['name'] general.validate_fields(required_fields, request.json) name = request.json.get('name') insurance_signer = request.app.config.SIGNER_INSURANCE client_txn = consent_transaction.create_insurance_client( txn_signer=insurance_signer, batch_signer=insurance_signer) LOGGER.debug('client_txn: ' + str(client_txn)) insurance_txn = insurance_transaction.create_insurance( txn_signer=insurance_signer, batch_signer=insurance_signer, name=name) LOGGER.debug('insurance_txn: ' + str(insurance_txn)) batch, batch_id = insurance_transaction.make_batch_and_id( [client_txn, insurance_txn], insurance_signer) # batch, batch_id = consent_transaction.make_batch_and_id([insurance_txn], insurance_signer) await security_messaging.add_insurance(request.app.config.VAL_CONN, request.app.config.TIMEOUT, [batch]) try: await security_messaging.check_batch_status( request.app.config.VAL_CONN, [batch_id]) except (ApiBadRequest, ApiInternalError) as err: # await auth_query.remove_auth_entry( # request.app.config.DB_CONN, request.json.get('email')) raise err return response.json(body={'status': general.DONE}, headers=general.get_response_headers())
async def get_evaluation_by_patient(request): """Fetches complete details of all Accounts in state""" idcard_viewer = request.headers['idcard_viewer'] idcard_patient = request.headers['idcard_patient'] headers = {'Content-Type': 'application/json'} dataParty = { "usernames": { "doctor": idcard_viewer, "patient": idcard_patient } } response_load = requests.post('http://validator:8863/getKeyDocPat', data=GeneralTool().parse2JSON(dataParty), headers=headers) if response_load.status_code != 200: raise Exception( "There was a problem communicating with the validator.") elif response_load.status_code == 200: keys = GeneralTool().parseFromJSON(response_load.content.decode()) doctor_priv_key = keys['doctor']['private_key'] patient_priv_key = keys['patient']['private_key'] doctor_pub_key = keys['doctor']['public_key'] patient_pub_key = keys['patient']['public_key'] evaluation_record_id = '{}|{}'.format(patient_pub_key, idcard_patient) evaluations_lst = await security_messaging.get_recordowner( request.app.config.VAL_CONN, evaluation_record_id) # Extracting the recordID information if doctor_pub_key != patient_pub_key: consent_id = evaluations_lst.consent[doctor_pub_key] LOGGER.warning("CONSENT ID: " + str(consent_id)) consent = await security_messaging.get_consent_patient_doctor( request.app.config.VAL_CONN, consent_id) if not general.validate_access(consent, [0, 2]): return response.json(body={ 'status': general.ERROR, "msg": "You have not access to this patient information." }, headers=general.get_response_headers()) patient_id = '{}|{}'.format(patient_pub_key, '02') party = await security_messaging.get_party( request.app.config.VAL_CONN, patient_pub_key) # Patient Main Information patient_info = await security_messaging.get_patient( request.app.config.VAL_CONN, patient_id) # Patient Main Information evaluations = [] for record_id in evaluations_lst.records: eval_info = await security_messaging.get_evaluation( request.app.config.VAL_CONN, record_id) evaluation_info = {} fields = [field.name for field in Evaluation.DESCRIPTOR.fields] for field in fields: evaluation_info[field] = getattr(eval_info, field) evaluations.append(evaluation_info) patient_list_json = [] patient_list_json.append({ 'name': party.name, 'lastname': party.lastname, 'telephone': party.telephone, 'birthdate': party.birthdate, 'idcard': party.idcard, 'sex': patient_info.biological_sex, 'photo': patient_info.photo, 'insurance': patient_info.current_insurance, 'blood_type': patient_info.blood_type, "evaluations": evaluations }) return response.json(body={'data': patient_list_json}, headers=general.get_response_headers()) else: raise Exception("User with no patient registred.")
async def register_new_evaluation(request): """Updates auth information for the authorized account""" # keyfile = common.get_keyfile(request.json.get['signer']) idcard_doctor = request.json.get('idcard_doctor') idcard_patient = request.json.get('idcard_patient') headers = {'Content-Type': 'application/json'} dataParty = { "usernames": { "doctor": idcard_doctor, "patient": idcard_patient } } response_load = requests.post('http://validator:8863/getKeyDocPat', data=GeneralTool().parse2JSON(dataParty), headers=headers) if response_load.status_code != 200: raise Exception( "There was a problem communicating with the validator.") elif response_load.status_code == 200: keys = GeneralTool().parseFromJSON(response_load.content.decode()) doctor_priv_key = keys['doctor']['private_key'] patient_priv_key = keys['patient']['private_key'] doctor_pub_key = keys['doctor']['public_key'] patient_pub_key = keys['patient']['public_key'] evaluation_record_id = '{}|{}'.format(patient_pub_key, idcard_patient) evaluations_lst = await security_messaging.get_recordowner( request.app.config.VAL_CONN, evaluation_record_id) # Extracting the recordID information consent_id = evaluations_lst.consent[doctor_pub_key] consent = await security_messaging.get_consent_patient_doctor( request.app.config.VAL_CONN, consent_id) if doctor_priv_key == patient_priv_key: return response.json(body={ 'status': general.ERROR, "msg": "A doctor cannot apply itself a consult." }, headers=general.get_response_headers()) elif not general.validate_access(consent, [1, 2]): return response.json(body={ 'status': general.ERROR, "msg": "You have not access to this patient information." }, headers=general.get_response_headers()) record_id = '{}|{}|{}'.format( doctor_pub_key, patient_pub_key, int(datetime.datetime.now().timestamp() * 1000)) batch_lst = [] date_reg = general.date2julian() doctor_signer = GeneralTool().addSigner( GeneralTool().ParsePrivateKey(private_key_str=doctor_priv_key)) fields = [field.name for field in Evaluation.DESCRIPTOR.fields] evaluation_info = {} for field in fields: evaluation_info[field] = request.json.get( field) if field in request.json else " " evaluation_info['record_id'] = record_id evaluation_info['patient_key'] = patient_pub_key evaluation_info['doctor_key'] = doctor_pub_key evaluation_info['date_time'] = str(date_reg) doctor_info = await security_messaging.get_party( request.app.config.VAL_CONN, doctor_pub_key) evaluation_info[ 'doctor_name'] = doctor_info.name + " " + doctor_info.lastname evaluation_record_id = '{}|{}'.format(patient_pub_key, idcard_patient) evaluations_lst = await security_messaging.get_recordowner( request.app.config.VAL_CONN, evaluation_record_id) # Extracting the recordID information LOGGER.debug("records: " + str(evaluations_lst)) records = [ record_id ] # This is like this because when the system update if you dont want to add all the information just send it the necesary # In other words, I do not know how to add just the last data and I made this 'force' evaluation_txn = transaction.add_evaluation( txn_signer=doctor_signer, batch_signer=doctor_signer, evaluation_info=evaluation_info) batch_lst.append(evaluation_txn) batch, batch_id = transaction.make_batch_and_id( batch_lst, doctor_signer) await security_messaging.add_doctor(request.app.config.VAL_CONN, request.app.config.TIMEOUT, [batch]) try: await security_messaging.check_batch_status( request.app.config.VAL_CONN, [batch_id]) except (ApiBadRequest, ApiInternalError) as err: raise err batch_lst = [] patient_signer = GeneralTool().addSigner( GeneralTool().ParsePrivateKey(private_key_str=patient_priv_key)) record_patient_txn = transaction.update_record_patient( txn_signer=patient_signer, batch_signer=patient_signer, record_id=evaluation_record_id, record_owner=patient_pub_key, records=records, consent={doctor_pub_key: consent_id}) batch_lst.append(record_patient_txn) batch, batch_id = transaction.make_batch_and_id( batch_lst, patient_signer) await security_messaging.add_doctor(request.app.config.VAL_CONN, request.app.config.TIMEOUT, [batch]) try: await security_messaging.check_batch_status( request.app.config.VAL_CONN, [batch_id]) except (ApiBadRequest, ApiInternalError) as err: raise err return response.json(body={'status': general.DONE}, headers=general.get_response_headers()) return response.json(body={ 'status': general.ERROR, "msg": "Sucedio un error en este proceso." }, headers=general.get_response_headers())
async def register_new_consent(request): """Updates auth information for the authorized account""" idcard_doctor = request.json.get('idcard_doctor') idcard_patient = request.json.get('idcard_patient') headers = {'Content-Type': 'application/json'} dataParty = {"usernames": {"doctor":idcard_doctor, "patient":idcard_patient}} LOGGER.debug("DATA TO SEND: "+str(dataParty)) response_load = requests.post('http://validator:8863/getKeyDocPat', data=GeneralTool().parse2JSON(dataParty), headers=headers) if response_load.status_code != 200: raise Exception("There was a problem communicating with the validator.") elif response_load.status_code == 200: keys = GeneralTool().parseFromJSON(response_load.content.decode()) doctor_priv_key = keys['doctor']['private_key'] patient_priv_key = keys['patient']['private_key'] doctor_pub_key = keys['doctor']['public_key'] patient_pub_key = keys['patient']['public_key'] time_exp=request.json.get('time_exp')# The amount of minutes to add hour_to_exp=datetime.now()+timedelta(minutes=int(time_exp)) time_to_exp=general.date2julian(hour_to_exp) LOGGER.warning("ORIGINAL TO EXP TIME: " + str(time_to_exp)) record_id = '{}|{}|{}'.format(doctor_pub_key, patient_pub_key, idcard_doctor+idcard_patient) batch_lst = [] patient_signer = GeneralTool().addSigner(GeneralTool().ParsePrivateKey(private_key_str=patient_priv_key)) consent_info = {'consent_id': record_id, 'time_exp': str(time_to_exp), 'doctor_key': doctor_pub_key, 'patient_key': patient_pub_key} if request.json.get('permission')=='read_write': consent_info['permission']=payload_pb2.permission_type.Name(2) elif request.json.get('permission')=='read': consent_info['permission']=payload_pb2.permission_type.Name(0) elif request.json.get('permission')=='write': consent_info['permission']=payload_pb2.permission_type.Name(1) evaluation_record_id = '{}|{}'.format(patient_pub_key, idcard_patient) consent_txn = transaction.add_consent_patient( txn_signer=patient_signer, batch_signer=patient_signer, consent_info=consent_info) batch_lst.append(consent_txn) record_patient_txn = transaction.update_record_patient( txn_signer=patient_signer, batch_signer=patient_signer, record_id=evaluation_record_id, record_owner=patient_pub_key, records=None, consent={doctor_pub_key:record_id} ) batch_lst.append(record_patient_txn) batch, batch_id = transaction.make_batch_and_id(batch_lst, patient_signer) await security_messaging.add_doctor( request.app.config.VAL_CONN, request.app.config.TIMEOUT, [batch]) try: await security_messaging.check_batch_status( request.app.config.VAL_CONN, [batch_id]) except (ApiBadRequest, ApiInternalError) as err: raise err return response.json(body={'status': general.DONE}, headers=general.get_response_headers()) return response.json(body={'status': general.ERROR, "msg":"Sucedio un error en este proceso."}, headers=general.get_response_headers())
async def register_new_patient(request): """Updates auth information for the authorized account""" # keyfile = common.get_keyfile(request.json.get['signer']) required_fields = ['first_name', 'last_name', 'idcard_type', 'idcard'] general.validate_fields(required_fields, request.json) name = request.json.get('first_name') surname = request.json.get('last_name') idcard = request.json.get('idcard') idcard_type = int(request.json.get('idcard_type')) party_info = { "name": name, "lastname": surname, "idcard": idcard, "telephone": request.json.get('telephone') if 'telephone' in request.json else " ", "birthdate": request.json.get('birthdate') if 'birthdate' in request.json else " ", "idcard_type": idcard_type } headers = {'Content-Type': 'application/json'} dataParty = { "username": party_info['idcard'], "_client_type_": _client_type_ } response_load = requests.post('http://validator:8863/getPrivateKey', data=GeneralTool().parse2JSON(dataParty), headers=headers) batch_lst = [] if response_load.status_code != 200: raise Exception( "There was a problem communicating with the validator.") elif response_load.status_code == 200 and 'private_key' in GeneralTool( ).parseFromJSON(response_load.content.decode()): keys = GeneralTool().parseFromJSON(response_load.content.decode()) privatekey = keys['private_key'] public_key = keys['public_key'] elif response_load.status_code == 200 and 'private_key' not in GeneralTool( ).parseFromJSON(response_load.content.decode()): party_txn, privatekey, public_key = general.addParty( party_info, _client_type_) batch_lst.append(party_txn) else: raise Exception( "There was a problem communicating with the validator.") patient_signer = GeneralTool().addSigner( GeneralTool().ParsePrivateKey(private_key_str=privatekey)) patientKey = '{}|{}'.format(public_key, '0' + str(_client_type_)) patient_info = { 'party_key': public_key, 'record_id': patientKey, 'biological_sex': request.json.get('biological_sex'), "blood_type": request.json.get('blood_type') if 'blood_type' in request.json else " ", "critical_info": request.json.get('critical_info') if 'critical_info' in request.json else " ", "current_insurance": request.json.get('current_insurance') if 'current_insurance' in request.json else " ", "disability_kind": request.json.get('disability_kind') if 'disability_kind' in request.json else " ", "disabled_person": request.json.get('disability_kind') if 'disability_kind' in request.json else '0', "familiar_antecedents": request.json.get('familiar_antecedents') if 'familiar_antecedents' in request.json else " ", "general_info": request.json.get('general_info') if 'general_info' in request.json else " ", "history_information": request.json.get('general_info') if 'general_info' in request.json else {}, "alcohol": request.json.get('alcohol') if 'alcohol' in request.json else '0', "anticonceptive": request.json.get('anticonceptive') if 'anticonceptive' in request.json else '0', "car_child_safety": request.json.get('car_child_safety') if 'car_child_safety' in request.json else '0', "car_revision": request.json.get('car_revision') if 'car_revision' in request.json else '0', "car_seat_belt": request.json.get('car_seat_belt') if 'car_seat_belt' in request.json else '0', "coffee": request.json.get('coffee') if 'coffee' in request.json else '0', "diet": request.json.get('diet') if 'diet' in request.json else '0', "drug_iv": request.json.get('drug_iv') if 'drug_iv' in request.json else '0', "drug_usage": request.json.get('drug_usage') if 'drug_usage' in request.json else '0', "eats_alone": request.json.get('eats_alone') if 'eats_alone' in request.json else '0', "ex_alcoholic": request.json.get('ex_alcoholic') if 'ex_alcoholic' in request.json else '0', "ex_drug_addict": request.json.get('ex_drug_addict') if 'ex_drug_addict' in request.json else '0', "ex_smoker": request.json.get('ex_smoker') if 'ex_smoker' in request.json else '0', "exercise": request.json.get('exercise') if 'exercise' in request.json else '0', "helmet": request.json.get('helmet') if 'helmet' in request.json else '0', "home_safety": request.json.get('home_safety') if 'home_safety' in request.json else '0', "motorcycle_rider": request.json.get('motorcycle_rider') if 'motorcycle_rider' in request.json else '0', "prostitute": request.json.get('prostitute') if 'prostitute' in request.json else '0', "salt": request.json.get('salt') if 'salt' in request.json else '0', "second_hand_smoker": request.json.get('second_hand_smoker') if 'second_hand_smoker' in request.json else '0', "smoking": request.json.get('smoking') if 'smoking' in request.json else '0', "soft_drinks": request.json.get('soft_drinks') if 'soft_drinks' in request.json else '0', "traffic_laws": request.json.get('traffic_laws') if 'traffic_laws' in request.json else '0', "photo": request.json.get('photo') if 'photo' in request.json else '/static/pictures/man.svg' if request.json.get('biological_sex') == 'm' else '/static/pictures/woman.svg' } patient_txn = transaction.create_patient(txn_signer=patient_signer, batch_signer=patient_signer, patient_info=patient_info) batch_lst.append(patient_txn) evaluation_record_id = '{}|{}'.format(patient_info['party_key'], party_info['idcard']) record_patient_txn = transaction.add_record_patient( txn_signer=patient_signer, batch_signer=patient_signer, record_id=evaluation_record_id, record_owner=public_key) batch_lst.append(record_patient_txn) batch, batch_id = transaction.make_batch_and_id(batch_lst, patient_signer) await security_messaging.add_patient(request.app.config.VAL_CONN, request.app.config.TIMEOUT, [batch]) # try: # await security_messaging.check_batch_status( # request.app.config.VAL_CONN, [batch_id]) # except (ApiBadRequest, ApiInternalError) as err: # # await auth_query.remove_auth_entry( # # request.app.config.DB_CONN, request.json.get('email')) # raise err return response.json(body={'status': general.DONE}, headers=general.get_response_headers())
async def add_new_lab_test(request): """Updates auth information for the authorized account""" # keyfile = common.get_keyfile(request.json.get['signer']) client_key = general.get_request_key_header(request) required_fields = [ 'height', 'weight', 'gender', 'a_g_ratio', 'albumin', 'alkaline_phosphatase', 'appearance', 'bilirubin', 'casts', 'color' ] general.validate_fields(required_fields, request.json) height = request.json.get('height') weight = request.json.get('weight') gender = request.json.get('gender') a_g_ratio = request.json.get('a_g_ratio') albumin = request.json.get('albumin') alkaline_phosphatase = request.json.get('alkaline_phosphatase') appearance = request.json.get('appearance') bilirubin = request.json.get('bilirubin') casts = request.json.get('casts') color = request.json.get('color') # private_key = common.get_signer_from_file(keyfile) # signer = CryptoFactory(request.app.config.CONTEXT).new_signer(private_key) # client_signer = request.app.config.SIGNER # .get_public_key().as_hex() # if request.app.config.SIGNER_CLINIC.get_public_key().as_hex() == client_key: # client_signer = request.app.config.SIGNER_CLINIC # elif request.app.config.SIGNER_PATIENT.get_public_key().as_hex() == client_key: # client_signer = request.app.config.SIGNER_PATIENT # elif request.app.config.SIGNER_DOCTOR.get_public_key().as_hex() == client_key: # client_signer = request.app.config.SIGNER_DOCTOR # elif request.app.config.SIGNER_LAB.get_public_key().as_hex() == client_key: # client_signer = request.app.config.SIGNER_LAB # else: # client_signer = request.app.config.SIGNER_PATIENT client_signer = general.get_signer(request, client_key) current_times_str = str(helper.get_current_timestamp()) lab_test_txn = transaction.add_lab_test( txn_signer=client_signer, batch_signer=client_signer, height=height, weight=weight, gender=gender, a_g_ratio=a_g_ratio, albumin=albumin, alkaline_phosphatase=alkaline_phosphatase, appearance=appearance, bilirubin=bilirubin, casts=casts, color=color, uid=current_times_str, client_pkey=client_key) batch, batch_id = transaction.make_batch_and_id([lab_test_txn], client_signer) await security_messaging.add_lab_test(request.app.config.VAL_CONN, request.app.config.TIMEOUT, [batch], client_key) try: await security_messaging.check_batch_status( request.app.config.VAL_CONN, [batch_id]) except (ApiBadRequest, ApiInternalError) as err: # await auth_query.remove_auth_entry( # request.app.config.DB_CONN, request.json.get('email')) raise err return response.json(body={'status': general.DONE}, headers=general.get_response_headers())
async def update_doctor(request): """Updates auth information for the authorized account""" # keyfile = common.get_keyfile(request.json.get['signer']) required_fields = ['idcard'] general.validate_fields(required_fields, request.json) idcard = request.json.get('idcard') headers = {'Content-Type': 'application/json'} dataParty = {"username": idcard} response_load = requests.post('http://validator:8863/getPrivateKey', data=GeneralTool().parse2JSON(dataParty), headers=headers) if response_load.status_code != 200: raise Exception( "There was a problem communicating with the validator.") elif response_load.status_code == 200: keys = GeneralTool().parseFromJSON(response_load.content.decode()) public_key = keys['public_key'] party = await security_messaging.get_party(request.app.config.VAL_CONN, public_key) doctorKey = '{}|{}'.format(public_key, '0' + str(_client_type_)) doctor = await security_messaging.get_doctor( request.app.config.VAL_CONN, doctorKey) party_info = { 'name': request.json.get('telephone') if 'telephone' in request.json else party.name, 'lastname': party.lastname, 'telephone': party.telephone, 'birthdate': party.birthdate, 'idcard': party.idcard, 'sex': party.sex, 'photo': doctor.photo, 'speciality': doctor.main_speciality } batch_lst = [] party_txn, privatekey, public_key = general.update_party(party_info) batch_lst.append(party_txn) doctor_signer = GeneralTool().addSigner( GeneralTool().ParsePrivateKey(private_key_str=privatekey)) doctorKey = '{}|{}'.format(public_key, '0' + str(_client_type_)) doctor_info = { 'party_key': public_key, 'doctor_key': doctorKey, "main_speciality": request.json.get('main_speciality') if 'main_speciality' in request.json else " ", "photo": request.json.get('photo') if 'photo' in request.json else '/static/pictures/man.svg' if request.json.get('biological_sex') == 'm' else '/static/pictures/woman.svg', "bio": request.json.get('bio') if 'bio' in request.json else " ", 'biological_sex': request.json.get('biological_sex') } doctor_txn = transaction.create_doctor(txn_signer=doctor_signer, batch_signer=doctor_signer, doctor_info=doctor_info) batch_lst.append(doctor_txn) batch, batch_id = transaction.make_batch_and_id( batch_lst, doctor_signer) await security_messaging.add_doctor(request.app.config.VAL_CONN, request.app.config.TIMEOUT, [batch]) try: await security_messaging.check_batch_status( request.app.config.VAL_CONN, [batch_id]) except (ApiBadRequest, ApiInternalError) as err: raise err return response.json(body={'status': general.DONE}, headers=general.get_response_headers()) return response.json(body={'status': general.ERROR}, headers=general.get_response_headers())
async def register_new_doctor(request): """Updates auth information for the authorized account""" # keyfile = common.get_keyfile(request.json.get['signer']) """Updates auth information for the authorized account""" # keyfile = common.get_keyfile(request.json.get['signer']) required_fields = ['first_name', 'last_name', 'idcard_type', 'idcard'] general.validate_fields(required_fields, request.json) name = request.json.get('first_name') surname = request.json.get('last_name') idcard = request.json.get('idcard') idcard_type = int(request.json.get('idcard_type')) # private_key = common.get_signer_from_file(keyfile) # signer = CryptoFactory(request.app.config.CONTEXT).new_signer(private_key) # patient_signer = request.app.config.SIGNER_PATIENT # .get_public_key().as_hex() party_info = { "name": name, "lastname": surname, "idcard": idcard, "telephone": request.json.get('telephone') if 'telephone' in request.json else " ", "birthdate": request.json.get('birthdate') if 'birthdate' in request.json else " ", "idcard_type": idcard_type } headers = {'Content-Type': 'application/json'} dataParty = { "username": party_info['idcard'], "_client_type_": _client_type_ } response_load = requests.post('http://validator:8863/getPrivateKey', data=GeneralTool().parse2JSON(dataParty), headers=headers) batch_lst = [] if response_load.status_code != 200: raise Exception( "There was a problem communicating with the validator.") elif response_load.status_code == 200 and 'private_key' in GeneralTool( ).parseFromJSON(response_load.content.decode()): keys = GeneralTool().parseFromJSON(response_load.content.decode()) privatekey = keys['private_key'] public_key = keys['public_key'] elif response_load.status_code == 200 and 'private_key' not in GeneralTool( ).parseFromJSON(response_load.content.decode()): party_txn, privatekey, public_key = general.addParty( party_info, _client_type_) batch_lst.append(party_txn) else: raise Exception( "There was a problem communicating with the validator.") doctor_signer = GeneralTool().addSigner( GeneralTool().ParsePrivateKey(private_key_str=privatekey)) doctorKey = '{}|{}'.format(public_key, '0' + str(_client_type_)) doctor_info = { 'party_key': public_key, 'doctor_key': doctorKey, "main_speciality": request.json.get('main_speciality') if 'main_speciality' in request.json else " ", "photo": request.json.get('photo') if 'photo' in request.json else '/static/pictures/man.svg' if request.json.get('biological_sex') == 'm' else '/static/pictures/woman.svg', "bio": request.json.get('bio') if 'bio' in request.json else " ", 'biological_sex': request.json.get('biological_sex') } doctor_txn = transaction.create_doctor(txn_signer=doctor_signer, batch_signer=doctor_signer, doctor_info=doctor_info) batch_lst.append(doctor_txn) batch, batch_id = transaction.make_batch_and_id(batch_lst, doctor_signer) await security_messaging.add_doctor(request.app.config.VAL_CONN, request.app.config.TIMEOUT, [batch]) try: await security_messaging.check_batch_status( request.app.config.VAL_CONN, [batch_id]) except (ApiBadRequest, ApiInternalError) as err: raise err return response.json(body={'status': general.DONE}, headers=general.get_response_headers())
async def assign_doctor(request): # """Fetches complete details of all Accounts in state""" # list_claim_details_address = helper.make_claim_address(claim_id=claim_id, clinic_pkey=clinic_pkey) # claim_details_resources = await messaging.get_state_by_address(request.app.config.VAL_CONN, # list_claim_details_address) # # account_resources2 = MessageToJson(account_resources) # # account_resources3 = MessageToDict(account_resources) # claim_details = [] # for entity in claim_details_resources.entries: # # dec_cl = base64.b64decode(entity.data) # cld = payload_pb2.ActionOnClaim() # cld.ParseFromString(entity.data) # claim_details.append({'clinic_pkey': cld.clinic_pkey, 'claim_id': cld.claim_id, # 'description': cld.description, 'event': cld.event, # 'event_time': cld.event_time}) # # import json # # result = json.dumps(clinics) # # clinics_json = MessageToJson(account_resources) # return response.json(body={'data': claim_details}, # headers=common.get_response_headers(common.get_request_origin(request))) # keyfile = common.get_keyfile(request.json.get['signer']) claim_id = request.json.get('claim_id') doctor_pkey = request.json.get('doctor_pkey') current_times_str = str(time.time()) # private_key = common.get_signer_from_file(keyfile) # signer = CryptoFactory(request.app.config.CONTEXT).new_signer(private_key) clinic_signer = request.app.config.SIGNER # .get_public_key().as_hex() batch, batch_id = transaction.assign_doctor( txn_signer=clinic_signer, batch_signer=clinic_signer, claim_id=claim_id, description="Doctor pkey: {}, assigned to claim: {}".format( doctor_pkey, claim_id), event_time=current_times_str) await messaging.send(request.app.config.VAL_CONN, request.app.config.TIMEOUT, [batch]) try: await messaging.check_batch_status(request.app.config.VAL_CONN, [batch_id]) except (ApiBadRequest, ApiInternalError) as err: # await auth_query.remove_auth_entry( # request.app.config.DB_CONN, request.json.get('email')) raise err # token = common.deserialize_auth_token( # request.app.config.SECRET_KEY, request.token) # # update = {} # if request.json.get('password'): # update['hashed_password'] = bcrypt.hashpw( # bytes(request.json.get('password'), 'utf-8'), bcrypt.gensalt()) # if request.json.get('email'): # update['email'] = request.json.get('email') # if update: # updated_auth_info = await auth_query.update_auth_info( # request.app.config.DB_CONN, # token.get('email'), # token.get('public_key'), # update) # new_token = common.generate_auth_token( # request.app.config.SECRET_KEY, # updated_auth_info.get('email'), # updated_auth_info.get('publicKey')) # else: # updated_auth_info = await accounts_query.fetch_account_resource( # request.app.config.DB_CONN, # token.get('public_key'), # token.get('public_key')) # new_token = request.token # return response.json( # { # 'authorization': new_token, # 'account': updated_auth_info # }) return response.json(body={'status': general.DONE}, headers=general.get_response_headers())