def signon(): def nav(): if 'login_redir' in session: return redirect(session.pop('login_redir')) return redirect('/') user_name = request.args.get('user') if user_name: if not PRODUCTION: ServiceApi.signon_user_testmode(user_name) return nav() # carriage returns were removed on the cilogon portal side, # restore them before processing raw_cert = request.args.get('cert') if not raw_cert: return nav() certificate = base64.b64decode(raw_cert) # call backend to signon user # will stash user id, expiry, is_registered and roles in session ServiceApi.signon_user(certificate) return nav()
def session_info(): # get version info from service gateway remote_version = ServiceApi.get_version() ion_ux_version = get_versions() # ion ux must be first version = [{ 'lib': 'ux-release', 'version': ion_ux_version }] # coi services should be second version.append({'lib':'coi-services-release', 'version': remote_version.pop('coi-services-release', 'unknown')}) # sort the rest by alpha for k,v in sorted(remote_version.iteritems()): version.append({'lib':k, 'version': v}) # trim off "-release" and "-dev" for ver in version: ver['lib'] = ver['lib'].replace("-release", "") ver['version'] = ver['version'].replace("-dev", "") session_values = {'user_id': None, 'roles': None, 'is_registered': False, 'is_logged_in': False, 'ui_mode': UI_MODE, 'version': version } if session.has_key('user_id'): roles = ServiceApi.get_roles_by_actor_id(session['actor_id']) session_values.update({'name': session['name'], 'user_id': session['user_id'], 'actor_id': session['actor_id'], 'roles': roles, 'is_registered': session['is_registered'], 'is_logged_in': True, 'ui_theme_dark': session['ui_theme_dark']}) return jsonify(data=session_values)
def userprofile(): if not session.has_key('user_id'): return redirect('/') is_registered = False if session.has_key('is_registered'): is_registered = session['is_registered'] user_id = session['user_id'] if request.is_xhr: if request.method == 'GET': # determine if this is an update or a new registration if is_registered: resp_data = ServiceApi.find_user_info(user_id) else: resp_data = {'contact': {'name': '', 'email': '', 'phone': '', 'address': '', 'city': '', 'postalcode': ''}} return jsonify(data=resp_data) else: form_data = json.loads(request.data) if is_registered: ServiceApi.update_user_info(form_data) else: ServiceApi.create_user_info(user_id, form_data) # indicate user is registered session['is_registered'] = True resp_data = {"success":True} return jsonify(data=resp_data) else: return render_app_template(request.path)
def search(query=None): if request.is_xhr: if request.method == "GET": search_query = request.args.get('query') search_results = ServiceApi.search(search_query) return render_json_response(search_results) else: adv_query_string = request.form['adv_query_string'] adv_query_chunks = parse_qs(adv_query_string) geospatial_bounds = {'north': adv_query_chunks.get('north', [''])[0], 'east': adv_query_chunks.get('east', [''])[0], 'south': adv_query_chunks.get('south', [''])[0], 'west': adv_query_chunks.get('west', [''])[0]} vertical_bounds = {'lower': adv_query_chunks.get('vertical-lower-bound', [''])[0], 'upper': adv_query_chunks.get('vertical-upper-bound', [''])[0]} temporal_bounds = {'from': adv_query_chunks.get('temporal-from-ctrl', [''])[0], 'to': adv_query_chunks.get('temporal-to-ctrl', [''])[0]} search_criteria = zip(adv_query_chunks.get('filter_var', []), adv_query_chunks.get('filter_operator', []), adv_query_chunks.get('filter_arg', [])) search_results = ServiceApi.adv_search(geospatial_bounds, vertical_bounds, temporal_bounds, search_criteria) return render_json_response(search_results) else: return render_app_template(request.path)
def taskable_command(resource_id, command, cap_type=None, session_type=None): cap_type = request.args.get('cap_type') if request.method in ('POST', 'PUT'): command_response = ServiceApi.taskable_execute(resource_id, command) else: if command == 'get_capabilities': app.logger.debug('get_capabilities') command_response = ServiceApi.tasktable_get_capabilities(resource_id) return render_json_response(command_response)
def resource_type_edit(resource_type, resource_id): if request.method == 'GET': resource = ServiceApi.get_prepare(resource_type, resource_id, None, True) return render_json_response(resource) if request.method == 'PUT': data = json.loads(request.data) resource_obj = data['resource'] resource_assocs = data['assocs'] updated_resource = ServiceApi.update_resource(resource_type, resource_obj, resource_assocs) return render_json_response(updated_resource)
def collection(resource_type=None): if request.is_xhr: # Todo - Implement "My Resources" as a separate call when they are available (observatories, platforms, etc.)... # Todo - user_info_id set in a @login_required decorator user_info_id = session.get('user_id') if session.has_key('user_id') else None resources = ServiceApi.find_by_resource_type(resource_type, user_info_id) return render_json_response(resources) elif is_json(request): user_info_id = session.get('user_id') if session.has_key('user_id') else None resources = ServiceApi.find_by_resource_type(resource_type, user_info_id) return render_json_response(resources) else: return render_app_template(request.path)
def platform_start_stop_command(platform_device_id, agent_command, cap_type=None, agent_instance_id=None): app.logger.debug('platform_start_stop_command %s'%agent_command) if agent_command == 'start': command_response = ServiceApi.platform_agent_start(agent_instance_id) return jsonify(data=command_response) elif agent_command == 'stop': command_response = ServiceApi.platform_agent_stop(agent_instance_id) return jsonify(data=command_response) elif agent_command == 'get_capabilities': command_response = ServiceApi.platform_agent_get_capabilities(platform_device_id) return jsonify(data=command_response) return jsonify(data=command_response)
def start_instrument_agent(instrument_device_id, agent_command, cap_type=None): cap_type = request.args.get('cap_type') if agent_command == 'start': command_response = ServiceApi.instrument_agent_start(instrument_device_id) return jsonify(data=command_response) elif agent_command == 'stop': command_response = ServiceApi.instrument_agent_stop(instrument_device_id) return jsonify(data=command_response) elif agent_command == 'get_capabilities': command_response = ServiceApi.instrument_agent_get_capabilities(instrument_device_id) return jsonify(data=command_response) else: command_response = ServiceApi.instrument_execute(instrument_device_id, agent_command, cap_type) return jsonify(data=command_response)
def instrument_command(device_type, instrument_device_id, agent_command, cap_type=None, session_type=None): cap_type = request.args.get('cap_type') if request.method in ('POST', 'PUT'): if agent_command == 'set_agent': resource_params = json.loads(request.data) command_response = ServiceApi.set_agent(instrument_device_id, resource_params) elif agent_command == 'set_resource': resource_params = json.loads(request.data) command_response = ServiceApi.set_resource(instrument_device_id, resource_params) elif agent_command == 'start': command_response = ServiceApi.instrument_agent_start(instrument_device_id) elif agent_command == 'stop': command_response = ServiceApi.instrument_agent_stop(instrument_device_id) else: if agent_command == 'RESOURCE_AGENT_EVENT_GO_DIRECT_ACCESS': session_type = request.args.get('session_type') command_response = ServiceApi.instrument_execute(instrument_device_id, agent_command, cap_type, session_type) else: if agent_command == 'get_capabilities': command_response = ServiceApi.instrument_agent_get_capabilities(instrument_device_id) elif agent_command == 'get_resource': command_response = ServiceApi.get_resource(instrument_device_id) elif agent_command == 'get_platform_agent_state': command_response = ServiceApi.platform_agent_state(instrument_device_id, 'get_agent_state') return render_json_response(command_response)
class SignIntTest(unittest.TestCase): def setUp(self): self.user = "******" self.app_client = main.app.test_client() self.app_context = main.app.test_request_context() self.sa = ServiceApi() def tearDown(self): pass def test_user_info(self,user="******"): with self.app_context: # Make sure the user is signed in self.sa.signon_user_testmode(self.user) user_id = flask.session.get('user_id') actor_id = flask.session.get('actor_id') username = flask.session.get('name') is_registered = flask.session.get('is_registered') self.assertIsNot(user_id, None) self.assertIsNot(actor_id, None) self.assertEqual(username, self.user) self.assertIs(is_registered, True) self.assertIs(is_it_id(user_id), True) self.assertTrue(is_it_id(actor_id), 32) # Get User info resource_type = 'UserInfo' resource = self.sa.get_prepare(resource_type, user_id, None, True) self.assertTrue(resource) resource_obj = resource.get('resource') self.assertIsNotNone(resource_obj) resource_assocs = resource.get('associations') self.assertIsNotNone(resource_assocs) contact = resource_obj.get('contact') city = contact.get('city') self.assertIsNotNone(city) # Update city new_city = 'La Jolla ' + str(int(random.random() * 1000)) resource_obj['contact']['city'] = new_city updated_resource = self.sa.update_resource(resource_type, resource_obj, resource_assocs) # Get user info again verify the new city name resource_temp = self.sa.get_prepare(resource_type, user_id, None, True) resource_obj_temp = resource_temp.get('resource') self.assertEqual(resource_obj_temp.get('contact').get('city'), new_city)
def search(query=None): if request.is_xhr: search_query = escape(request.args.get('query')) search_results = ServiceApi.search(quote(search_query)) return search_results else: return render_app_template(request.path)
def get_data_product_updates(): data_product_id_list= request.form.get('data_product_id_list', None) data_product_id_list = data_product_id_list.split(',') since_timestamp = request.form.get('since_timestamp', None) data_product_info = ServiceApi.get_data_product_updates(data_product_id_list, since_timestamp) return render_json_response(data_product_info)
def test_enrollment_reject(self): negotiation_open = 1 negotiation_accepted = 2 negotiation_rejected = 3 reject = 'reject' accept = 'accept' negotiation_type_request = 1 # Request access to RSN Facility with self.app_context: self.sa.signon_user_testmode(self.user) actor_id = flask.session.get('actor_id') if flask.session.has_key('actor_id') else None resp = ServiceApi.enroll_request(self.org_id, actor_id) error = resp.get('GatewayError') self.assertIsNone(error, "Request for enrollment failed. Error: " + str(error)) negotiation_id = resp.get('negotiation_id') self.assertIsNotNone(negotiation_id, "Request for enrollment failed ") with self.app_context: # Verify negotiation is open self.sa.signon_user_testmode("Tim Ampe") resource = self.sa.get_prepare("OrgUserNegotiationRequest", negotiation_id, None, True) resource_obj = resource.get('resource') negotiation_status = resource_obj.get('negotiation_status') negotiation_type = resource_obj.get('negotiation_type') self.assertEqual(negotiation_status, negotiation_open) self.assertEqual(negotiation_type, negotiation_type_request) # Reject negotiation rsp = self.sa.accept_reject_negotiation(negotiation_id, reject, 'provider', 'Different roads sometimes lead to the same castle.') resource = self.sa.get_prepare("OrgUserNegotiationRequest", negotiation_id, None, True) resource_obj = resource.get('resource') negotiation_status = resource_obj.get('negotiation_status') negotiation_type = resource_obj.get('negotiation_type') self.assertEqual(negotiation_status, negotiation_rejected)
def request_access(resource_type, resource_id): org_id = request.form.get('org_id', None) res_name = request.form.get('res_name', None) actor_id = session.get('actor_id') if session.has_key('actor_id') else None resp = ServiceApi.request_access(resource_id, res_name, actor_id, org_id) return render_json_response(resp)
def subscribe_to_resource(resource_type, resource_id, event_type): user_id = session.get('user_id') if user_id: resp = ServiceApi.subscribe(resource_type, resource_id, event_type, user_id) return jsonify(data=resp) else: return jsonify(data='No user_id.')
def visualization(operation_name): visualization_parameters = {} for k,v in request.args.iteritems(): visualization_parameters.update({k:v}) req = ServiceApi.visualization(operation_name, visualization_parameters) #return req return render_json_response(req)
class InstrumentAgentInstanceUnitTest(unittest.TestCase): def setUp(self): self.org_name = "CI Bench Test Facility" self.user = "******" self.app_client = main.app.test_client() self.app_context = main.app.test_request_context() self.sa = ServiceApi() def tearDown(self): pass def create_resource(self, resource_type, org_id, resource_name=None): with self.app_context: self.sa.signon_user_testmode(self.user) resource_id, org_has_resource_id = self.sa.create_resource( resource_type=resource_type, org_id=org_id, resource_name=resource_name ) self.assertIsNotNone(resource_id) self.assertIs(is_it_id(resource_id), True) self.assertIsNotNone(org_has_resource_id) self.assertIs(is_it_id(org_has_resource_id), True) # get the data from service gateway and verify resource = self.sa.get_prepare(resource_type, resource_id, None, True) resource_obj = resource.get("resource") resource_association = resource.get("associations") self.assertIsNotNone(resource_obj) self.assertEqual(resource_obj.get("name"), resource_name) # Verify the resource can be updated new_name = " Unit Test Data Product Temp " + str(int(random.random() * 1000)) resource_obj["name"] = new_name response = self.sa.update_resource(resource_type, resource_obj, []) # Verify the name has been updated resource = self.sa.get_prepare(resource_type, resource_id, None, True) resource_obj = resource.get("resource") self.assertIsNotNone(resource_obj) self.assertEqual(resource_obj.get("name"), new_name) # Put back the name resource_obj["name"] = resource_name response = self.sa.update_resource(resource_type, resource_obj, []) resource = self.sa.get_prepare(resource_type, resource_id, None, True) resource_obj = resource.get("resource") self.assertIsNotNone(resource_obj) self.assertEqual(resource_obj.get("name"), resource_name) def test_create_new_instrument_agent_instance(self): instrument_name = "Unit Test Instrument Agent Instance " + str(int(random.random() * 1000)) resource_type = "InstrumentAgentInstance" org_id = get_org_id(org_name=self.org_name) self.assertIsNotNone(org_id) self.assertTrue(is_it_id(org_id)) # Make sure it returns id which is 32 chars self.create_resource(resource_type=resource_type, org_id=org_id, resource_name=instrument_name)
def accept_reject_negotiation(): negotiation_id = request.form.get('negotiation_id', None) verb = request.form.get('verb', None) originator = request.form.get('originator', None) reason = request.form.get('reason', None) resp = ServiceApi.accept_reject_negotiation(negotiation_id, verb, originator, reason) return render_json_response(resp)
def request_exclusive_access(resource_type, resource_id): expiration = int(request.form.get('expiration', None)) curtime = int(round(time.time() * 1000)) full_expiration = str(curtime + (expiration * 60 * 60 * 1000)) # in ms actor_id = session.get('actor_id') if session.has_key('actor_id') else None org_id = request.form.get('org_id', None) resp = ServiceApi.request_exclusive_access(resource_id, actor_id, org_id, full_expiration) return render_json_response(resp)
def setUp(self): self.user = "******" self.org_name = "RSN Facility" self.app_client = main.app.test_client() self.app_context = main.app.test_request_context() self.sa = ServiceApi() self.org_id = get_org_id(org_name=self.org_name) self.assertIsNotNone(self.org_id) self.assertTrue(is_it_id(self.org_id), "Org id is set to non id value")
def page(resource_type, resource_id): if request.is_xhr: if request.method == 'PUT': resource_obj = json.loads(request.data) updated_resource = ServiceApi.update_resource(resource_type, resource_obj) return render_json_response(updated_resource) else: return else: return render_app_template(request.path)
def signon(): user_name = request.args.get('user') if user_name: ServiceApi.signon_user_testmode(user_name) return redirect('/') # carriage returns were removed on the cilogon portal side, # restore them before processing raw_cert = request.args.get('cert') if not raw_cert: return redirect('/') certificate = base64.b64decode(raw_cert) # call backend to signon user # will stash user id, expiry, is_registered and roles in session ServiceApi.signon_user(certificate) if session['is_registered'] == False: # redirect to registration screen return redirect('/userprofile') else: return redirect('/')
def publish_event(resource_type, resource_id): if resource_type == 'InstrumentDevice': event_type = 'DeviceOperatorEvent' else: event_type = 'ResourceOperatorEvent' sub_type = None description = request.form['description'] # possible override for event type - if comes from a source like "report issue" if 'event_type' in request.form: event_type = request.form['event_type'] resp = ServiceApi.publish_event(event_type, resource_id, resource_type, sub_type, description) return render_json_response(resp)
def test_quick_search(self): with self.app_context: sa = ServiceApi() search_query = "parsed" results = sa.search(search_query=search_query) self.assertTrue(results != []) search_query_found = False for result in results: for key, value in result['_source'].iteritems(): if type(value) is str or type(value) is unicode: if value.lower().find(search_query.lower()) > -1: search_query_found = True self.assertTrue(search_query_found) search_query = "parseD" results = sa.search(search_query=search_query) self.assertTrue(results != []) search_query_found = False for result in results: for key, value in result['_source'].iteritems(): if type(value) is str or type(value) is unicode: if value.lower().find(search_query.lower()) > -1: search_query_found = True self.assertTrue(search_query_found)
def attachment_create(): fd = request.files['attachment'] attachment_type = 2 if fd.mimetype.startswith("text/"): attachment_type = 1 retval = ServiceApi.create_resource_attachment(request.form['resource_id'], fd.filename, request.form['description'], attachment_type, fd.mimetype, fd, request.form['keywords'], request.form['created_by'], request.form['modified_by']) dat = {'files':[{'name':fd.filename, 'size':fd.content_length}]} return jsonify(dat)
def platform_command(platform_device_id, agent_command, cap_type=None, agent_instance_id=None): app.logger.debug('platform_command %s'%agent_command) cap_type = request.args.get('cap_type') port_id="n/a" if request.method in ('POST', 'PUT'): if agent_command == 'set_agent': resource_params = json.loads(request.data) command_response = ServiceApi.set_agent(platform_device_id, resource_params) elif agent_command == 'set_resource': resource_params = json.loads(request.data) command_response = ServiceApi.set_resource(platform_device_id, resource_params) else: if ( agent_command == 'RSN_PLATFORM_DRIVER_TURN_ON_PORT' or agent_command == 'RSN_PLATFORM_DRIVER_TURN_OFF_PORT' ): port_id = request.args.get('port_id') command_response = ServiceApi.platform_execute(platform_device_id, agent_command, cap_type, port_id) else: if agent_command == 'get_capabilities': command_response = ServiceApi.instrument_agent_get_capabilities(platform_device_id) elif agent_command == 'get_resource': command_response = ServiceApi.get_resource(platform_device_id) elif agent_command == 'get_platform_agent_state': command_response = ServiceApi.platform_agent_state(platform_device_id, 'get_agent_state') return render_json_response(command_response)
class DataProductIntTest(unittest.TestCase): def setUp(self): self.org_name = "CI Bench Test Facility" self.user = "******" self.app_client = main.app.test_client() self.app_context = main.app.test_request_context() self.sa = ServiceApi() def tearDown(self): pass def create_new_data_product(self, resource_type, org_id, resource_name=None): with self.app_context: # Create a new resource self.sa.signon_user_testmode(self.user) instrument_device_id, org_has_resource_instrument_id = self.sa.create_resource(resource_type=resource_type, org_id=org_id, resource_name=resource_name) self.assertIsNotNone(instrument_device_id) self.assertIs(is_it_id(instrument_device_id), True) self.assertIsNotNone(org_has_resource_instrument_id) self.assertIs(is_it_id(org_has_resource_instrument_id), True) # Get the data from service gateway and verify resource = self.sa.get_prepare(resource_type, instrument_device_id, None, True) resource_obj = resource.get('resource') resource_association = resource.get('associations') self.assertIsNotNone(resource_obj) self.assertEqual(resource_obj.get('name'), resource_name) # Verify the resource can be updated new_name = " Unit Test New Instrument Name " + str(int(random.random() * 1000)) resource_obj['name'] = new_name response = self.sa.update_resource(resource_type, resource_obj, []) # Verify the name has been updated resource = self.sa.get_prepare(resource_type, instrument_device_id, None, True) resource_obj = resource.get('resource') self.assertIsNotNone(resource_obj) self.assertEqual(resource_obj.get('name'), new_name) # Put back the name resource_obj['name'] = resource_name response = self.sa.update_resource(resource_type, resource_obj, []) resource = self.sa.get_prepare(resource_type, instrument_device_id, None, True) resource_obj = resource.get('resource') self.assertIsNotNone(resource_obj) self.assertEqual(resource_obj.get('name'), resource_name) # Logout by clearing the session flask.session.clear() # Try to update the instrument data as a guest response = self.sa.update_resource(resource_type, resource_obj, []) self.assertTrue(len(response) > 0, "Service Gateway is supposed to return unauthorized error for updating a resource as a guest") error = response[0].get('GatewayError') self.assertIsNotNone(error, "Service Gateway is supposed to return unauthorized error for updating a resource as a guest") error = error.get('Exception') self.assertEqual(error.lower(), "unauthorized", "Service Gateway is supposed to return unauthorized error for updating a resource as a guest") def test_create_data_product(self): instrument_name = "Unit Test Data Product " + str(int(random.random() * 1000)) resource_type = 'DataProduct' org_id = get_org_id(org_name=self.org_name) self.assertIsNotNone(org_id) self.assertTrue(is_it_id(org_id)) self.create_new_data_product(resource_type=resource_type, org_id=org_id, resource_name=instrument_name)
def setUp(self): self.user = "******" self.app_client = main.app.test_client() self.app_context = main.app.test_request_context() self.sa = ServiceApi()
class InstrumentAgentInstanceUnitTest(unittest.TestCase): def setUp(self): self.org_name = "CI Bench Test Facility" self.user = "******" self.app_client = main.app.test_client() self.app_context = main.app.test_request_context() self.sa = ServiceApi() def tearDown(self): pass def create_resource(self, resource_type, org_id, resource_name=None): with self.app_context: self.sa.signon_user_testmode(self.user) resource_id, org_has_resource_id = self.sa.create_resource( resource_type=resource_type, org_id=org_id, resource_name=resource_name) self.assertIsNotNone(resource_id) self.assertIs(is_it_id(resource_id), True) self.assertIsNotNone(org_has_resource_id) self.assertIs(is_it_id(org_has_resource_id), True) # get the data from service gateway and verify resource = self.sa.get_prepare(resource_type, resource_id, None, True) resource_obj = resource.get('resource') resource_association = resource.get('associations') self.assertIsNotNone(resource_obj) self.assertEqual(resource_obj.get('name'), resource_name) # Verify the resource can be updated new_name = " Unit Test Data Product Temp " + str( int(random.random() * 1000)) resource_obj['name'] = new_name response = self.sa.update_resource(resource_type, resource_obj, []) # Verify the name has been updated resource = self.sa.get_prepare(resource_type, resource_id, None, True) resource_obj = resource.get('resource') self.assertIsNotNone(resource_obj) self.assertEqual(resource_obj.get('name'), new_name) # Put back the name resource_obj['name'] = resource_name response = self.sa.update_resource(resource_type, resource_obj, []) resource = self.sa.get_prepare(resource_type, resource_id, None, True) resource_obj = resource.get('resource') self.assertIsNotNone(resource_obj) self.assertEqual(resource_obj.get('name'), resource_name) def test_create_new_instrument_agent_instance(self): instrument_name = "Unit Test Instrument Agent Instance " + str( int(random.random() * 1000)) resource_type = 'InstrumentAgentInstance' org_id = get_org_id(org_name=self.org_name) self.assertIsNotNone(org_id) self.assertTrue( is_it_id(org_id)) # Make sure it returns id which is 32 chars self.create_resource(resource_type=resource_type, org_id=org_id, resource_name=instrument_name)
def deactivate_primary(): deployment_id = request.form.get('deployment_id', None) deactivate_primary = ServiceApi.deactivate_primary(deployment_id) return render_json_response(deactivate_primary)
def release_access(resource_type, resource_id): commitment_id = request.form.get('commitment_id', None) resp = ServiceApi.release_access(commitment_id) return render_json_response(resp)
def org_list(): orgs = ServiceApi.find_by_resource_type('Org') return jsonify(data={'orgs': orgs})
class EnrollmentUnitTest(unittest.TestCase): def setUp(self): self.user = "******" self.org_name = "RSN Facility" self.app_client = main.app.test_client() self.app_context = main.app.test_request_context() self.sa = ServiceApi() self.org_id = get_org_id(org_name=self.org_name) self.assertIsNotNone(self.org_id) self.assertTrue(is_it_id(self.org_id), "Org id is set to non id value") def tearDown(self): pass def test_enrollment_accept(self): negotiation_open = 1 negotiation_accepted = 2 negotiation_rejected = 3 reject = 'reject' accept = 'accept' negotiation_type_request = 1 # Request access to RSN Facility with self.app_context: self.sa.signon_user_testmode(self.user) actor_id = flask.session.get('actor_id') if flask.session.has_key('actor_id') else None resp = ServiceApi.enroll_request(self.org_id, actor_id) error = resp.get('GatewayError') self.assertIsNone(error, "Request for enrollment failed. Error: " + str(error)) negotiation_id = resp.get('negotiation_id') self.assertIsNotNone(negotiation_id, "Request for enrollment failed ") with self.app_context: # Verify negotiation is open self.sa.signon_user_testmode("Tim Ampe") resource = self.sa.get_prepare("OrgUserNegotiationRequest", negotiation_id, None, True) resource_obj = resource.get('resource') negotiation_status = resource_obj.get('negotiation_status') negotiation_type = resource_obj.get('negotiation_type') self.assertEqual(negotiation_status, negotiation_open) self.assertEqual(negotiation_type, negotiation_type_request) # Accept negotiation rsp = self.sa.accept_reject_negotiation(negotiation_id, accept, 'provider', 'Different roads sometimes lead to the same castle.') resource = self.sa.get_prepare("OrgUserNegotiationRequest", negotiation_id, None, True) resource_obj = resource.get('resource') negotiation_status = resource_obj.get('negotiation_status') negotiation_type = resource_obj.get('negotiation_type') self.assertEqual(negotiation_status, negotiation_accepted) #todo remove the enrollment def test_enrollment_reject(self): negotiation_open = 1 negotiation_accepted = 2 negotiation_rejected = 3 reject = 'reject' accept = 'accept' negotiation_type_request = 1 # Request access to RSN Facility with self.app_context: self.sa.signon_user_testmode(self.user) actor_id = flask.session.get('actor_id') if flask.session.has_key('actor_id') else None resp = ServiceApi.enroll_request(self.org_id, actor_id) error = resp.get('GatewayError') self.assertIsNone(error, "Request for enrollment failed. Error: " + str(error)) negotiation_id = resp.get('negotiation_id') self.assertIsNotNone(negotiation_id, "Request for enrollment failed ") with self.app_context: # Verify negotiation is open self.sa.signon_user_testmode("Tim Ampe") resource = self.sa.get_prepare("OrgUserNegotiationRequest", negotiation_id, None, True) resource_obj = resource.get('resource') negotiation_status = resource_obj.get('negotiation_status') negotiation_type = resource_obj.get('negotiation_type') self.assertEqual(negotiation_status, negotiation_open) self.assertEqual(negotiation_type, negotiation_type_request) # Reject negotiation rsp = self.sa.accept_reject_negotiation(negotiation_id, reject, 'provider', 'Different roads sometimes lead to the same castle.') resource = self.sa.get_prepare("OrgUserNegotiationRequest", negotiation_id, None, True) resource_obj = resource.get('resource') negotiation_status = resource_obj.get('negotiation_status') negotiation_type = resource_obj.get('negotiation_type') self.assertEqual(negotiation_status, negotiation_rejected)
def invite_user(resource_type, resource_id): user_id = request.form.get('user_id', None) resp = ServiceApi.invite_user(resource_id, user_id) return render_json_response(resp)
def ui_navigation(): observatories = ServiceApi.find_by_resource_type('Observatory') orgs = ServiceApi.find_by_resource_type('Org') platformSites = ServiceApi.find_by_resource_type('PlatformSite') return jsonify(data={'orgs': orgs, 'observatories': observatories, 'platformSites': platformSites})
def reset_ui(): reset_ui = ServiceApi.ui_reset() return jsonify(data=reset_ui)
def userprofile(): if not session.has_key('user_id'): return redirect('/') is_registered = False if session.has_key('is_registered'): is_registered = session['is_registered'] user_id = session['user_id'] if request.is_xhr: if request.method == 'GET': # determine if this is an update or a new registration if is_registered: resp_data = ServiceApi.find_user_info(session['actor_id']) else: # try to extract name from UserCredentials creds = ServiceApi.find_user_credentials_by_actor_id(session['actor_id']) cntoken = creds['name'] name = '' individual_names_given = '' individual_name_family = '' try: rcn = re.compile(r'CN=(.*)\sA.+') m = rcn.search(cntoken) if m is not None: name = m.groups()[0] individual_names_given, individual_name_family = name.split(' ', 1) except: pass resp_data = {'name':name, 'contact':{'individual_names_given':individual_names_given, 'individual_name_family':individual_name_family}} return jsonify(data=resp_data) else: form_data = json.loads(request.data) if is_registered: resp_data = ServiceApi.update_user_info(form_data) if isinstance(resp_data, dict) and resp_data.has_key('GatewayError'): return render_json_response(resp_data) else: # only thing that can change here for session is name session['name'] = form_data['name'] else: user_id = ServiceApi.create_user_info(session['actor_id'], form_data) if isinstance(user_id, dict) and user_id.has_key('GatewayError'): return render_json_response(user_id) else: # simulate a signon by setting appropriate session vars session['is_registered'] = True session['user_id'] = user_id session['roles'] = ServiceApi.get_roles_by_actor_id(session['actor_id']) session['name'] = form_data['name'] #session['valid_until'] = 0 # @TODO: howto? only in certificate, so logon? resp_data = {"success":True} return jsonify(data=resp_data) else: return render_app_template(request.path)
def run(self, **kwargs): self.user_files = ServiceApi.search_files( Util.get_user_id(), Constants.default_all_files_pattern) print('files found for deletion: ', len(self.user_files)) Util.display_available_files(self.window, self.user_files, self.delete_file)
class InstrumentDeviceUnitTest(unittest.TestCase): def setUp(self): self.user = "******" self.app_client = main.app.test_client() self.app_context = main.app.test_request_context() self.sa = ServiceApi() def tearDown(self): pass def get_instrument_model_id_from_resources(self, model_name, resources): for resource in resources: if resource.get('name') == model_name: return resource.get('_id') return None def attachment(self, instrument_id): ''' with self.app_client as c: r =c.get('/signon/?user='******'user_id') self.assertIsNot(user_id, None) r = c.post('/attachment/', data={ 'file': (StringIO('That rug really tied the room together.'), 'unittest.txt'), 'resource_id': instrument_id, 'description': 'This is just a test', 'keywords': 'testing 123', 'created_by': 'the dude', 'modified_by': 'Walter Sobchak', }) r = r ''' pass def create_new_instrument(self, resource_type, org_id, resource_name=None): with self.app_context: self.sa.signon_user_testmode(self.user) instrument_device_id, org_has_resource_instrument_id = self.sa.create_resource(resource_type=resource_type, org_id=org_id, resource_name=resource_name) self.assertIsNotNone(instrument_device_id) self.assertIs(is_it_id(instrument_device_id), True) self.assertIsNotNone(org_has_resource_instrument_id) self.assertIs(is_it_id(org_has_resource_instrument_id), True) # get the data from service gateway and verify resource = self.sa.get_prepare(resource_type, instrument_device_id, None, True) resource_obj = resource.get('resource') resource_association = resource.get('associations') self.assertIsNotNone(resource_obj) self.assertEqual(resource_obj.get('name'), resource_name) associate_resource = resource_association.get('InstrumentModel').get('associated_resources') self.assertEqual(len(associate_resource), 0) # Verify there is no association # set instrument model available_resources = resource_association.get('InstrumentModel').get('resources') instrument_model_name = 'SBE 37-SMP MicroCAT CTD Demo' instrument_model_id = self.get_instrument_model_id_from_resources(instrument_model_name, available_resources) self.assertIsNotNone(instrument_model_id, "Could not find " + instrument_model_name + " id from available resources") instrument_model_obj = self.sa.get_prepare("InstrumentModel", instrument_model_id, None, True) response = self.sa.update_resource(resource_type, resource_obj, {'InstrumentModel': instrument_model_id}) error = response[0] self.assertIsNone(error) # Verify the instrument model association is set correctly resource = self.sa.get_prepare(resource_type, instrument_device_id, None, True) resource_association = resource.get('associations') associated_resource = resource_association.get('InstrumentModel').get('associated_resources') self.assertEqual(len(associated_resource), 1) self.assertTrue(instrument_model_id in associated_resource[0].values()) # Update the instrument name resource = self.sa.get_prepare(resource_type, instrument_device_id, None, True) resource_obj = resource.get('resource') new_name = " Unit Test New Instrument Name " + str(int(random.random() * 1000)) resource_obj['name'] = new_name response = self.sa.update_resource(resource_type, resource_obj, []) error = response[0] self.assertIsNone(error, error) # Verify the name has been updated resource = self.sa.get_prepare(resource_type, instrument_device_id, None, True) resource_obj = resource.get('resource') self.assertIsNotNone(resource_obj) self.assertEqual(resource_obj.get('name'), new_name) # Put back the name resource_obj['name'] = resource_name response = self.sa.update_resource(resource_type, resource_obj, []) resource = self.sa.get_prepare(resource_type, instrument_device_id, None, True) resource_obj = resource.get('resource') self.assertIsNotNone(resource_obj) self.assertEqual(resource_obj.get('name'), resource_name) # Logout by clearing the session flask.session.clear() # Try to update the instrument data as a guest and verify it fails response = self.sa.update_resource(resource_type, resource_obj, []) self.assertTrue(len(response) > 0, "Service Gateway is supposed to return unauthorized error for updating new instrument as a guest") error = response[0].get('GatewayError') self.assertIsNotNone(error, "Service Gateway is supposed to return unauthorized error for updating new instrument as a guest") error = error.get('Exception') self.assertEqual(error.lower(), "unauthorized", "Service Gateway is supposed to return unauthorized error for updating new instrument as a guest") return instrument_device_id def test_create_new_instrument(self): org_name = "CI Bench Test Facility" instrument_name = "Unit Test Instrument " + str(int(random.random() * 10000)) resource_type = 'InstrumentDevice' org_data = get_org_data() self.assertIsNotNone(org_data) org_id = get_org_id(org_data, org_name) self.assertIsNotNone(org_id) self.assertTrue(is_it_id(org_id), "Org id is set to non id value") instrument_id = self.create_new_instrument(resource_type=resource_type, org_id=org_id, resource_name=instrument_name)
def enroll_request(resource_type, resource_id): actor_id = session.get('actor_id') if session.has_key('actor_id') else None resp = ServiceApi.enroll_request(resource_id, actor_id) return render_json_response(resp)
def get_resource_type_schema(resource_type): schema = ServiceApi.resource_type_schema(resource_type) return jsonify(schema=schema)
def request_role(resource_type, resource_id): actor_id = session.get('actor_id') if session.has_key('actor_id') else None role_name = request.form.get('role_name', None) resp = ServiceApi.request_role(resource_id, actor_id, role_name) return render_json_response(resp)
def get_recent_events(resource_id): user_id = session['user_id'] if session.has_key('user_id') else None events = ServiceApi.get_recent_events(resource_id, user_id) return render_json_response(events)
def offer_user_role(resource_type, resource_id): user_id = request.form.get('user_id', None) role_name = request.form.get('role_name', None) resp = ServiceApi.offer_user_role(resource_id, user_id, role_name) return render_json_response(resp)
def related_objects_has_resource(resource_id): related_objects_has_resource = ServiceApi.find_related_objects_has_resource( resource_id) return render_json_response(related_objects_has_resource)
def change_lcstate(resource_type, resource_id): transition_event = request.form['transition_event'].lower() transition = ServiceApi.transition_lcstate(resource_id, transition_event) return render_json_response(transition)
def find_site_data_products(resource_id): site_data_products = ServiceApi.find_site_data_products(resource_id) return render_json_response(site_data_products)
def extension(resource_type, resource_id): # Login not required to view, but required for user specific things # like event notifications, etc. user_id = session['user_id'] if session.has_key('user_id') else None extension = ServiceApi.get_extension(resource_type, resource_id, user_id) return render_json_response(extension)
def setUp(self): self.org_name = "CI Bench Test Facility" self.user = "******" self.app_client = main.app.test_client() self.app_context = main.app.test_request_context() self.sa = ServiceApi()
def related_sites(resource_id): related_sites = ServiceApi.find_related_sites(resource_id) return render_json_response(related_sites)
def attachment_delete(attachment_id): resp = ServiceApi.delete_resource_attachment(attachment_id) return render_json_response(resp)
def get_data_product_group_list(): dp_group_list = ServiceApi.get_data_product_group_list() return render_json_response(dp_group_list)
def attachment_is_owner(attachment_id, actor_id): if not actor_id: return jsonify({'data': False}) return ServiceApi.attachment_is_owner(attachment_id, actor_id)
def get_sites_status(): # status = Servi1ceApi.find_status() # resource_ids = request.args.get('data') resource_ids = request.json['resource_ids'] sites_status = ServiceApi.get_sites_status(resource_ids) return render_json_response(sites_status)
def event_types(): event_types = ServiceApi.get_event_types() return jsonify(data=event_types)
def activate_persistence(): data_product_id = request.form.get('data_product_id', None) pers = ServiceApi.activate_persistence(data_product_id) return render_json_response(pers)
def create_resource(): resp = ServiceApi.create_resource(request.form.get('resource_type', None), request.form.get('org_id', None), request.form.get('lcstate', None)) return render_json_response(resp)
def unsubscribe_to_resource(resource_type, resource_id): notification_id = request.args.get('notification_id') resp = ServiceApi.delete_user_subscription(notification_id) return render_json_response(resp)