def sign_in(self, request: Request, response: Response, auth: Auth, validate: Validator): errors = request.validate(validate.required("email"), validate.required("password")) if errors: return errors user_auth_res = auth.login(request.input("email"), request.input("password")) if user_auth_res is False: return response.json({"error": "Check your credentials"}) msg = { "id": user_auth_res.id, "email": user_auth_res.email, "name": user_auth_res.name, "govId": user_auth_res.gov_id, "type": user_auth_res.type, } enc = utils.encode_message(msg) if enc != False: return response.json({"access_token": enc.decode("utf-8")}) return response.json( {"error": "You cannot access this system at the time"})
def show(self, request: Request, response: Response): account_id = request.param("account_id") blockchain_data = self.ibc.get_all_account_transactions(account_id) blockchain_data = protobuf_to_dict(blockchain_data) blockchain_data = utils.format_transaction_data(blockchain_data) if blockchain_data is False: return response.json({"error": "No such permissions"}) return response.json({"data": blockchain_data})
def store(self, request: Request, response: Response, validate: Validator): errors = request.validate( validate.required("symptoms"), validate.required("diagnosis"), validate.required("treatment_plan"), validate.required("seen_by"), ) if errors: return errors patient_id = request.param("patient_id") patient_record = { "author": f"{self.user.gov_id}@afyamkononi", "timestamp": calendar.timegm(time.gmtime()), "symptoms": request.input("symptoms"), "diagnosis": request.input("diagnosis"), "treatment_plan": request.input("treatment_plan"), "seen_by": request.input("seen_by"), } patient_account = self.ibc.get_account_details( request.param("patient_id")) if patient_account.detail == "": return response.json({"error": "No such account"}) unpacked_data = json.loads(patient_account.detail) patient_history = utils.filter_medical_data(unpacked_data) history_update = [] if patient_history == []: history_update.append(patient_record) else: history_update += patient_history history_update.append(patient_record) history_update = utils.remove_duplicates(history_update) blockchain_status = self.ibc.set_patient_record( User.where("gov_id", patient_id).first(), history_update) print(blockchain_status) iroha_message = iroha_messages.update_medical_history_failed( blockchain_status) if iroha_message is not None: return response.json(iroha_message) return response.json({"success": "Medical data added successfully"})
def show(self, request: Request, response: Response): """ Retrieve medical records for a patient """ subject = User.where("gov_id", request.param("patient_id")).first() if subject is None: return response.json({"error": "No such user"}) requestor_id = f"{self.user.gov_id}@afyamkononi" grantor_id = f"{subject.gov_id}@afyamkononi" consent_confirm = (Consent.where("requestor_id", requestor_id).where( "grantor_id", grantor_id).where("grantor_id", "!=", requestor_id).first()) if consent_confirm is None and requestor_id != grantor_id: consent = Consent() consent.requestor_id = requestor_id consent.requestor_name = self.user.name consent.grantor_id = grantor_id consent.grantor_name = subject.name consent.permission = "can_set_my_account_detail" consent.save() return response.json({ "error": "No such permissions. This owner has been requested to grant permissions." }) elif (consent_confirm is not None and consent_confirm.grantor_id != requestor_id and consent_confirm.status != "granted"): consent_confirm.update(status="pending") return response.json({ "error": "No such permissions. This owner has been requested to grant permissions." }) blockchain_data = self.ibc.get_account_details(subject.gov_id, "medical_data") if blockchain_data.detail == "": return response.json({"data": []}) patient_medical_history = json.loads(blockchain_data.detail) filtered_patient_medical_history = utils.filter_medical_data( patient_medical_history) return response.json({"data": filtered_patient_medical_history})
def role_permissions(self, request: Request, response: Response): role_id = request.param("role") blockchain_data = self.ibc.get_role_permissions(role_id) blockchain_data = protobuf_to_dict( blockchain_data.role_permissions_response) return response.json({"data": blockchain_data})
def revoke_edit_permissions(self, request: Request, response: Response): subject = User.where("gov_id", request.input("gov_id")).first() grantor = User.where("gov_id", request.param("user")).first() if subject is None: return response.json({"error": "No such user"}) blockchain_status = self.ibc.revoke_edit_permissions(subject) iroha_message = iroha_messages.revoke_set_account_detail_perms_failed( blockchain_status) if iroha_message is not None: return response.json(iroha_message) (Consent.where("requestor_id", f"{subject.gov_id}@afyamkononi").where( "grantor_id", f"{grantor.gov_id}@afyamkononi").update(status="revoked")) return response.json( {"success": "The requested permissions were revoked"})
class TestResponse: def setup_method(self): self.app = App() self.request = Request(generate_wsgi()).load_app(self.app) self.app.bind('Request', self.request) self.response = Response(self.app) def test_can_set_json(self): self.response.json({'test': 'value'}) assert self.request.is_status(200) assert self.request.header('Content-Length') == '17' assert self.request.header( 'Content-Type') == 'application/json; charset=utf-8' def test_redirect(self): self.response.redirect('/some/test') assert self.request.is_status(302) assert self.request.header('Location', '/some/test') def test_response_does_not_override_header_from_controller(self): self.response.view(self.app.resolve(ControllerTest().change_header)) assert self.request.header('Content-Type') == 'application/xml' def test_view(self): view = View(self.app).render('test', {'test': 'test'}) self.response.view(view) assert self.app.make('Response') == 'test' assert self.request.is_status(200) self.response.view('foobar') assert self.app.make('Response') == 'foobar' def test_view_can_return_integer_as_string(self): self.response.view(1) assert self.app.make('Response') == '1' assert self.request.is_status(200)
def user_by_gov_id(self, request: Request, response: Response): subject = User.where("gov_id", request.param("user")).first() if subject is None: return response.json({"error": "No such user"}) requestor_id = f"{self.user.gov_id}@afyamkononi" grantor_id = f"{subject.gov_id}@afyamkononi" consent_confirm = (Consent.where("requestor_id", requestor_id).where( "grantor_id", grantor_id).first()) if consent_confirm is None and requestor_id != grantor_id: consent = Consent() consent.requestor_id = requestor_id consent.requestor_name = self.user.name consent.grantor_id = grantor_id consent.grantor_name = subject.name consent.permission = "can_set_my_account_detail" consent.save() return response.json({ "error": "No such permissions. This owner has been requested to grant permissions." }) elif (consent_confirm is not None and consent_confirm.grantor_id != requestor_id and consent_confirm.status != "granted"): consent_confirm.update(status="pending") return response.json({ "error": "No such permissions. This owner has been requested to grant permissions." }) data = self.ibc.get_account_details(subject.gov_id) if data.detail == "": return response.json({ "error": "No such permissions. This owner has been requested to grant permissions." }) return utils.format_query_result(data)
def delete(self, request: Request, response: Response): """Logic to delete data from a given model """ if AdminMiddleware(request, response).checkpw_resource() == False: return response.json(None, status=403) record = self.model.find(request.param('id')) if record: record.delete() return record return {'error': 'Record does not exist'}
def delete(self, request: Request, response: Response): """Logic to delete data from a given model """ if self.before_crud_check(request, response) == False: return response.json(None, status=403) record = self.model.find(request.param('id')) if record: record.delete() return record return {'error': 'Record does not exist'}
def update(self, request: Request, response: Response): """Logic to update data from a given model """ if AdminMiddleware(request, response).checkpw_resource() == False: return response.json(None, status=403) record = self.model.where('id', request.param('id')) params = request.all() del params['login_id'], params['login_token'] try: record.update(params) except Exception as e: return {'error': str(e)} return { } #self.model.where('id', request.param('id')).get().serialize()
def index(self, request: Request, response: Response): """Logic to read data from several models """ if AdminMiddleware(request, response).checkpw_resource() == False: return response.json(None, status=403) # pagenagion items = request.input('i') if request.input('i') else 10 page = request.input('p') if request.input('p') else 1 _offset = items * (page - 1) if self.list_display: results = self.model.select( 'id', *self.list_display).offset(_offset).limit(items).get() new_results = [result._original for result in results._items] return self.arr_iso_format(new_results) #return self.model.select('id', *self.list_display).paginate(items, page).serialize() else: results = self.model.offset(_offset).limit(items).get() new_results = [result._original for result in results._items] return self.arr_iso_format(new_results)
def show(self, request: Request, response: Response): """Logic to read data from 1 model """ if AdminMiddleware(request, response).checkpw_resource() == False: return response.json(None, status=403) if self.detail_display and env('DB_CONNECTION') == 'mysql': result = self.model.select(*self.detail_display).find( request.param('id')) new_result = {i: v for i, v in result._original.items()} return self.arr_iso_format(new_result) elif self.detail_display: if 'id' not in self.detail_display: self.detail_display.insert(0, 'id') result = self.model.select(*self.detail_display).find( request.param('id')) new_result = {i: v for i, v in result._original.items()} return self.arr_iso_format(new_result) else: result = self.model.find(request.param('id')) new_result = {i: v for i, v in result._original.items()} return self.arr_iso_format(new_result)
def create(self, request: Request, response: Response): """Logic to create data from a given model """ if AdminMiddleware(request, response).checkpw_resource() == False: return response.json(None, status=403) try: params = request.all() del params['login_id'], params['login_token'] config_model = AdminController.get_model_row_by_model_name( self.model.__doc__.split(' ')[0]) new_model = self.model() for key, value in params.items(): try: setattr(new_model, key, value) except Exception as e: print(e) new_model.save() except Exception as e: return {'error': str(e)} return new_model
def test_json(self, response: Response): return response.json({'test': 'value'})
def all_roles(self, response: Response): blockchain_data = self.ibc.get_all_roles() return response.json({"data": blockchain_data})
class TestResponse: def setup_method(self): self.app = App() self.request = Request(generate_wsgi()).load_app(self.app) self.app.bind('Request', self.request) self.app.bind('StatusCode', None) self.response = Response(self.app) self.app.bind('Response', self.response) def test_can_set_json(self): self.response.json({'test': 'value'}) assert self.request.is_status(200) assert self.request.header('Content-Length') == '17' assert self.request.header( 'Content-Type') == 'application/json; charset=utf-8' def test_redirect(self): self.response.redirect('/some/test') assert self.request.is_status(302) assert self.request.header('Location', '/some/test') def test_response_does_not_override_header_from_controller(self): self.response.view(self.app.resolve(ControllerTest().change_header)) assert self.request.header('Content-Type') == 'application/xml' def test_view(self): view = View(self.app).render('test', {'test': 'test'}) self.response.view(view) assert self.app.make('Response') == 'test' assert self.request.is_status(200) self.response.view('foobar') assert self.app.make('Response') == 'foobar' def test_view_can_return_integer_as_string(self): self.response.view(1) assert self.app.make('Response') == '1' assert self.request.is_status(200) def test_view_can_set_own_status_code_to_404(self): self.response.view(self.app.resolve(ControllerTest().change_404)) assert self.request.is_status(404) def test_view_can_set_own_status_code(self): self.response.view(self.app.resolve(ControllerTest().change_status)) assert self.request.is_status(203) def test_view_should_return_a_json_response_when_retrieve_a_user_from_model( self): assert isinstance(MockUser(), Model) self.response.view(MockUser().all()) json_response = '[{"name": "TestUser", "email": "*****@*****.**"}, {"name": "TestUser", "email": "*****@*****.**"}]' assert self.app.make('Response') == json_response self.response.view(MockUser().find(1)) json_response = '{"name": "TestUser", "email": "*****@*****.**"}' assert self.app.make('Response') == json_response
def register(self, request: Request, response: Response, auth: Auth, validate: Validator): errors = request.validate( validate.required("name"), validate.required("email"), validate.required("type"), validate.required("gov_id"), validate.required("phone_number"), ) if errors: return errors priv_key = IrohaCrypto.private_key() pub_key = IrohaCrypto.derive_public_key(priv_key) user = User() user.name = request.input("name") user.email = request.input("email") user.type = request.input("type") user.gov_id = request.input("gov_id") user.phone_number = request.input("phone_number") user.private_key = priv_key.decode("utf-8") user.public_key = pub_key.decode("utf-8") if user.type == "user": user.password = str(random.randrange(1000, 9999)) else: user.password = request.input("password") blockchain_status = self.ibc.create_account(user) iroha_message = iroha_messages.create_account_failed(blockchain_status) if iroha_message != None: return response.json(iroha_message) blockchain_status = self.ibc.grant_set_account_detail_perms(user) iroha_message = iroha_messages.grant_set_account_detail_perms_failed( blockchain_status) if iroha_message != None: return response.json(iroha_message) blockchain_status = self.ibc.set_account_details(user) iroha_message = iroha_messages.set_account_details_failed( blockchain_status) if iroha_message != None: return response.json(iroha_message) if user.type != "user": blockchain_status = self.ibc.append_role(user) iroha_message = iroha_messages.append_role_failed( blockchain_status) if iroha_message != None: return response.json(iroha_message) if user.type == "user": blockchain_status = self.ibc.revoke_set_account_detail_perms(user) iroha_message = iroha_messages.revoke_set_account_detail_perms_failed( blockchain_status) if iroha_message != None: return response.json(iroha_message) res = auth.register({ "name": user.name, "email": user.email, "password": user.password, "type": user.type, "private_key": user.private_key, "public_key": user.public_key, "gov_id": user.gov_id, "phone_number": user.phone_number, }) if res is None and user.type == "user": message = Mail( from_email=env("MAIL_FROM_ADDRESS"), to_emails=user.email, subject="Afya Mkononi Auth Details", html_content= f"<div> <p>Welcome to this cool health service</p> <p>Your email: { user.email }</p> <p>Your Password: { user.password }</p>", ) sg = SendGridAPIClient(env("SENDGRID_KEY")) sg.send(message) return response.json( {"success": "Check your email for your credentials"}) elif res is None: return response.json({"success": "Account has been added"}) return response.json({"error": "Failed to add account"})
def count(self, request: Request, response: Response): if AdminMiddleware(request, response).checkpw_resource() == False: return response.json(None, status=403) return {'count': self.model.count()}
class TestResponse(unittest.TestCase): def setUp(self): self.app = App() self.request = Request(generate_wsgi()).load_app(self.app) self.app.bind('Request', self.request) self.app.bind('StatusCode', None) self.response = Response(self.app) self.app.bind('Response', self.response) def test_can_set_json(self): self.response.json({'test': 'value'}) self.assertTrue(self.request.is_status(200)) self.assertEqual(self.request.header('Content-Length'), '17') self.assertEqual(self.request.header('Content-Type'), 'application/json; charset=utf-8') def test_redirect(self): self.response.redirect('/some/test') self.request.header('Location', '/some/test') self.assertTrue(self.request.is_status(302)) self.assertEqual(self.request.header('Location'), '/some/test') def test_response_does_not_override_header_from_controller(self): self.response.view(self.app.resolve(ControllerTest().change_header)) self.assertEqual(self.request.header('Content-Type'), 'application/xml') def test_view(self): view = View(self.app).render('test', {'test': 'test'}) self.response.view(view) self.assertEqual(self.app.make('Response'), 'test') self.assertTrue(self.request.is_status(200)) self.response.view('foobar') self.assertEqual(self.app.make('Response'), 'foobar') def test_view_can_return_integer_as_string(self): self.response.view(1) self.assertEqual(self.app.make('Response'), '1') self.assertTrue(self.request.is_status(200)) def test_view_can_set_own_status_code_to_404(self): self.response.view(self.app.resolve(ControllerTest().change_404)) self.assertTrue(self.request.is_status(404)) def test_view_can_set_own_status_code(self): self.response.view(self.app.resolve(ControllerTest().change_status)) self.assertTrue(self.request.is_status(203)) def test_view_should_return_a_json_response_when_retrieve_a_user_from_model( self): self.assertIsInstance(MockUser(), Model) self.response.view(MockUser().all()) self.assertIn('"name": "TestUser"', self.app.make('Response')) self.assertIn('"email": "*****@*****.**"', self.app.make('Response')) self.response.view(MockUser().find(1)) self.assertIn('"name": "TestUser"', self.app.make('Response')) self.assertIn('"email": "*****@*****.**"', self.app.make('Response'))
def count(self, request: Request, response: Response): if self.before_crud_check(request, response) == False: return response.json(None, status=403) return {'count': self.model.count()}