示例#1
0
    def authenticate(self):
        """
        Performs authentication actions
        Patches `tinyrpc` to remove minor incompatibilities due to JSON-RPC
        protocol version differences. This is performed once.
        Initializes the RPCClient and RPCProxy instances that
        are used to make the requests to Lime.
        :return: None
        """
        logger.info("Authenticating LimeAPI client")
        if not LimeAPI._rpc_protocol_patched:
            LimeAPI.patch_json_rpc_protocol()
            LimeAPI._rpc_protocol_patched = True
        self.rpc_client = RPCClient(
            JSONRPCProtocol(),
            HttpPostClientTransport(endpoint=self.remote_api_url,
                                    headers=self.headers),
        )

        self.rpc_proxy = self.rpc_client.get_proxy()
        self.session_key = self.rpc_proxy.get_session_key(
            username=self.username, password=self.password)
        if not self._validate_session_key():
            raise Exception(f"Failed to validate session key: url={self.url} "
                            f"session_key={self.session_key}")
        self._authenticated = True
        logger.info(f"Acquired session key: {self.session_key}")
示例#2
0
class CaliopeClient(object):
    def __init__(self, *args, **kwargs):
         self.login(u'user', u'123')

    def login(self, username, password):
        self.rpc_client = RPCClient(JSONRPCProtocol(),
                                    HttpWebSocketClientTransport('ws://localhost:9000/api/ws'))
        self.loginManager = self.rpc_client.get_proxy("login.")
        hashed_password = hashlib.sha256(password).hexdigest()
        return self.loginManager.authenticate(username=username,
                                              password=hashed_password)

    def get_model(self, msg):
        tasks_proxy = self.rpc_client.get_proxy(prefix="tasks.")
        model = tasks_proxy.getModel()
        uuid = model["data"]["uuid"]["value"]
        #:update
        update = tasks_proxy.updateField(uuid=uuid,
                                         field_name="name",
                                         value=EncodeStr(msg['subject']))
        update = tasks_proxy.updateField(uuid=uuid,
                                         field_name="description",
                                         value=EncodeStr(msg['body']))
        #:commit
        commit = tasks_proxy.commit(uuid=uuid)
示例#3
0
class CaliopeClient(object):
    def __init__(self, *args, **kwargs):
        self.login(u'user', u'123')

    def login(self, username, password):
        self.rpc_client = RPCClient(
            JSONRPCProtocol(),
            HttpWebSocketClientTransport('ws://localhost:9000/api/ws'))
        self.loginManager = self.rpc_client.get_proxy("login.")
        hashed_password = hashlib.sha256(password).hexdigest()
        return self.loginManager.authenticate(username=username,
                                              password=hashed_password)

    def get_model(self, msg):
        tasks_proxy = self.rpc_client.get_proxy(prefix="tasks.")
        model = tasks_proxy.getModel()
        uuid = model["data"]["uuid"]["value"]
        #:update
        update = tasks_proxy.updateField(uuid=uuid,
                                         field_name="name",
                                         value=EncodeStr(msg['subject']))
        update = tasks_proxy.updateField(uuid=uuid,
                                         field_name="description",
                                         value=EncodeStr(msg['body']))
        #:commit
        commit = tasks_proxy.commit(uuid=uuid)
示例#4
0
 def login(self, username, password):
     self.rpc_client = RPCClient(
         JSONRPCProtocol(),
         HttpWebSocketClientTransport('ws://localhost:9001/api/ws'))
     self.loginManager = self.rpc_client.get_proxy("login.")
     hashed_password = hashlib.sha256(password).hexdigest()
     return self.loginManager.authenticate(username=username,
                                           password=hashed_password)
示例#5
0
def worker():
    ctx = zmq.Context()
    rpc_client = RPCClient(
        JSONRPCProtocol(),
        ZmqClientTransport.create(ctx, "tcp://127.0.0.1:5002"))
    proxy = rpc_client.get_proxy()

    for message in iter(partial(recv, port=sys.stdin), ""):
        proxy.post(f"hello {message}")
        import time

        time.sleep(0.4)
    sys.stdout.write("")
    sys.stdout.close()
示例#6
0
def client(mock_protocol, mock_transport, request):
    client = RPCClient(mock_protocol, mock_transport, NoOpPublisher())
    client.wait_for_task = Mock(return_value=None)
    response = Mock(RPCResponse)
    response.unicode = '0'
    response.result = 'result1'
    client.get_status = Mock(return_value={
        response.unicode: ('done', response, 'some time', 'timeout')
    })

    def fin():
        client.receiver.alive = False

    request.addfinalizer(fin)
    return client
示例#7
0
def manager():
    cmd = [sys.executable, __file__, "worker"]
    p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=False)

    rpc_client = RPCClient(
        JSONRPCProtocol(),
        SubprocessClientTransport(input_port=p.stdout, output_port=p.stdin),
    )
    for i in range(3):
        proxy = rpc_client.get_proxy()
        try:
            result = proxy.add(10, 20)
            print(f"result is {result}")
        except Exception as e:
            logger.error("!! %r", e, exc_info=True)
    p.terminate()
 def login(self, username='******', password='******'):
     self.rpc_client = RPCClient(JSONRPCProtocol(),
                                 HttpWebSocketClientTransport('ws://localhost:9001/api/ws'))
     self.loginManager = self.rpc_client.get_proxy("login.")
     hashed_password = hashlib.sha256(password).hexdigest()
     return self.loginManager.authenticate(username=username,
                                           password=hashed_password)
示例#9
0
    def __init__(self, user, pwd):
        """Start RPC connection and keep session open
        Example:
        rpc = Satnet_RPC('crespum', 'solutions')
        print rpc.call('configuration.sc.list')

        :param user: SatNet username.
        :type user: L{String}
        :param pwd: SatNet password for this user.
        :type pwd: L{String}
        """
        self._rpc_client = RPCClient(JSONRPCProtocolFix(),
                                     HttpSessionTransport(user, pwd))
        self.detect_test(user)

        if self.testing:
            return

        if not self.login(user, pwd):
            raise BadCredentials()

        tw_log.msg('System login confirmed!')
示例#10
0
class FormServicesTestCase(unittest.TestCase):
    def setUp(self):
        caliope_server.app.config['TESTING'] = True
        caliope_server.init_flask_app()
        caliope_server.configure_server_and_app(
            "conf/test_caliope_server.json")
        caliope_server.configure_logger("conf/tests_logger.json")
        caliope_server.register_modules()
        caliope_server.app.storekv = RedisStore(redis.StrictRedis())
        self.http_server = WSGIServer(
            (caliope_server.app.config['address'],
             caliope_server.app.config['port']),
            caliope_server.app,
            handler_class=WebSocketHandler)  # @IgnorePep8
        self.http_server.start()
        self.nodes_created = set()
        self.create_default_database()

    def tearDown(self):
        """Get rid of the database again after each test."""
        if self.rpc_client:
            self.rpc_client.transport.close()
        self.http_server.stop()
        self.http_server = None
        caliope_server.app = Flask('caliope_server')
        #:Delete database
        self.remove_used_nodes(self.nodes_created)

    def create_default_database(self):
        self.create_UserGroup('user', 'group')

    def create_UserGroup(self, username, groupname):
        try:
            u1 = CaliopeUser()
            u1.username = username
            u1.password = hashlib.sha256(u'123').hexdigest()
            u1.domainname = 'correlibre.org'
            u1.first_name = "User"
            u1.last_name = "Test"
            u1.avatar = "common-img/avatar.png"
            u1.save()
            self.nodes_created.add(u1.uuid)
            g1 = CaliopeGroup()
            g1.name = groupname
            g1.code = groupname
            g1.save()
            self.nodes_created.add(g1.uuid)
            u1.member_of.connect(g1)
            g1.members.connect(u1)
            self.assertTrue(u1.member_of.is_connected(g1))
            self.assertTrue(g1.members.is_connected(u1))
        except UniqueProperty:
            try:
                u1 = CaliopeUser.index.get(username=username)
                g1 = CaliopeGroup.index.get(code=groupname)
                assert u1 is not None and g1 is not None
                assert u1.member_of.is_connected(g1)
                assert g1.members.is_connected(u1)
            except DoesNotExist:
                assert False

    def remove_used_nodes(self, node_list):
        query = "START n=node:CaliopeStorage('uuid:{}') " \
                "MATCH  n-[r]-() " \
                "DELETE n, r"
        batch_query = []
        for uuid in node_list:
            batch_query.append(
                neo4j.cypher.Query(neo4j.GraphDatabaseService(),
                                   query.format(uuid)).execute())

    def login(self, username, password):
        self.rpc_client = RPCClient(
            JSONRPCProtocol(),
            HttpWebSocketClientTransport('ws://localhost:9001/api/ws'))
        self.loginManager = self.rpc_client.get_proxy("login.")
        hashed_password = hashlib.sha256(password).hexdigest()
        return self.loginManager.authenticate(username=username,
                                              password=hashed_password)

    def logout(self, uuid):
        if self.loginManager is None:
            return
        return self.loginManager.logout(uuid=uuid)

    def test_login(self):
        rv = self.login(u'user', u'123')
        expected = \
            {u'first_name': {u'value': u'User'},
             u'last_name': {u'value': u'Test'},
             u'image': {u'data': None},
             u'user': {u'value': u'user'},
             u'login': True,
            }
        self.assertDictContainsSubset(expected, rv)
        self.assertIn("session_uuid", rv)
        self.assertIn("user_uuid", rv)

    def test_logout(self):
        uuid = self.login(u'user', u'123')['user_uuid']['value']
        rv = self.logout(uuid=uuid)
        self.assertIn('logout', rv)
        self.assertTrue(rv['logout'])
        self.assertIn('uuid', rv)
        self.assertEqual(uuid, rv['uuid'])

    def test_ts_get_model(self):
        user = self.login(u'user', u'123')
        tasks_proxy = self.rpc_client.get_proxy(prefix="form.")
        model = tasks_proxy.getModel()
        self.assertIsNotNone(model)

    def test_person_get_model_and_data(self):
        user = self.login(u'user', u'123')
        form_proxy = self.rpc_client.get_proxy(prefix="form.")
        model = form_proxy.getModel(formId="Person", data=True)
        self.assertIsNotNone(model)
        uuid = model["data"]["uuid"]["value"]
        #:update
        update = form_proxy.updateField(uuid=uuid,
                                        field_name="name",
                                        value="test")

        #:commit
        commit = form_proxy.commit(uuid=uuid)
        self.assertTrue(commit)
        model_and_data = form_proxy.getData(formId="Person", uuid=uuid)
        self.assertEqual(model_and_data["name"]["value"], "test")
class FormServicesTestCase(unittest.TestCase):
    def setUp(self):
        caliope_server.app.config['TESTING'] = True
        caliope_server.init_flask_app()
        caliope_server.configure_server_and_app(
            "conf/test_caliope_server.json")
        caliope_server.configure_logger("conf/tests_logger.json")
        caliope_server.register_modules()
        caliope_server.app.storekv = RedisStore(redis.StrictRedis())
        self.http_server = WSGIServer((caliope_server.app.config['address'],
                                       caliope_server.app.config['port']),
                                      caliope_server.app,
                                      handler_class=WebSocketHandler)  # @IgnorePep8
        self.http_server.start()
        self.nodes_created = set()
        self.create_default_database()

    def tearDown(self):
        """Get rid of the database again after each test."""
        if self.rpc_client:
            self.rpc_client.transport.close()
        self.http_server.stop()
        self.http_server = None
        caliope_server.app = Flask('caliope_server')
        #:Delete database
        self.remove_used_nodes(self.nodes_created)


    def create_default_database(self):
        self.create_UserGroup('user', 'group')

    def create_UserGroup(self, username, groupname):
        try:
            u1 = CaliopeUser()
            u1.username = username
            u1.password = hashlib.sha256(u'123').hexdigest()
            u1.domainname = 'correlibre.org'
            u1.first_name = "User"
            u1.last_name = "Test"
            u1.avatar = "common-img/avatar.png"
            u1.save()
            self.nodes_created.add(u1.uuid)
            g1 = CaliopeGroup()
            g1.name = groupname
            g1.code = groupname
            g1.save()
            self.nodes_created.add(g1.uuid)
            u1.member_of.connect(g1)
            g1.members.connect(u1)
            self.assertTrue(u1.member_of.is_connected(g1))
            self.assertTrue(g1.members.is_connected(u1))
        except UniqueProperty:
            try:
                u1 = CaliopeUser.index.get(username=username)
                g1 = CaliopeGroup.index.get(code=groupname)
                assert u1 is not None and g1 is not None
                assert u1.member_of.is_connected(g1)
                assert g1.members.is_connected(u1)
            except DoesNotExist:
                assert False

    def remove_used_nodes(self, node_list):
        query = "START n=node:CaliopeStorage('uuid:{}') " \
                "MATCH  n-[r]-() " \
                "DELETE n, r"
        batch_query = []
        for uuid in node_list:
            batch_query.append(neo4j.cypher.Query(neo4j.GraphDatabaseService(),
                                                  query.format(uuid)).execute())

    def login(self, username, password):
        self.rpc_client = RPCClient(JSONRPCProtocol(),
                                    HttpWebSocketClientTransport(
                                        'ws://localhost:9001/api/ws'))
        self.loginManager = self.rpc_client.get_proxy("login.")
        hashed_password = hashlib.sha256(password).hexdigest()
        return self.loginManager.authenticate(username=username,
                                              password=hashed_password)

    def logout(self, uuid):
        if self.loginManager is None:
            return
        return self.loginManager.logout(uuid=uuid)


    def test_login(self):
        rv = self.login(u'user', u'123')
        expected = \
            {u'first_name': {u'value': u'User'},
             u'last_name': {u'value': u'Test'},
             u'image': {u'data': None},
             u'user': {u'value': u'user'},
             u'login': True,
            }
        self.assertDictContainsSubset(expected, rv)
        self.assertIn("session_uuid", rv)
        self.assertIn("user_uuid", rv)


    def test_logout(self):
        uuid = self.login(u'user', u'123')['user_uuid']['value']
        rv = self.logout(uuid=uuid)
        self.assertIn('logout', rv)
        self.assertTrue(rv['logout'])
        self.assertIn('uuid', rv)
        self.assertEqual(uuid, rv['uuid'])


    def test_ts_get_model(self):
        user = self.login(u'user', u'123')
        tasks_proxy = self.rpc_client.get_proxy(prefix="form.")
        model = tasks_proxy.getModel()
        self.assertIsNotNone(model)

    def test_person_get_model_and_data(self):
        user = self.login(u'user', u'123')
        form_proxy = self.rpc_client.get_proxy(prefix="form.")
        model = form_proxy.getModel(formId="Person", data=True)
        self.assertIsNotNone(model)
        uuid = model["data"]["uuid"]["value"]
        #:update
        update = form_proxy.updateField(uuid=uuid,
                                         field_name="name",
                                         value="test")

        #:commit
        commit = form_proxy.commit(uuid=uuid)
        self.assertTrue(commit)
        model_and_data = form_proxy.getData(formId="Person", uuid=uuid)
        self.assertEqual(model_and_data["name"]["value"], "test")
示例#12
0
class CaliopeServerTestCase(unittest.TestCase):
    def setUp(self):
        caliope_server.app.config['TESTING'] = True
        caliope_server.init_flask_app()
        caliope_server.configure_server_and_app(
            "../../conf/test_caliope_server.json")
        caliope_server.configure_logger("../../conf/tests_logger.json")
        caliope_server.register_modules()
        caliope_server.app.storekv = RedisStore(redis.StrictRedis())
        self.http_server = WSGIServer(
            (caliope_server.app.config['address'],
             caliope_server.app.config['port']),
            caliope_server.app,
            handler_class=WebSocketHandler)  # @IgnorePep8
        self.http_server.start()
        self.create_default_database()

    def tearDown(self):
        """Get rid of the database again after each test."""
        if self.rpc_client:
            self.rpc_client.transport.close()
        self.http_server.stop()
        self.http_server = None
        caliope_server.app = Flask('caliope_server')
        #:Delete database
        neo4j.GraphDatabaseService().clear()

    def create_default_database(self):
        DefaultDatabase().test_defaultUserGroupOne()

    def login(self, username, password):
        self.rpc_client = RPCClient(
            JSONRPCProtocol(),
            HttpWebSocketClientTransport('ws://localhost:9001/api/ws'))
        self.loginManager = self.rpc_client.get_proxy("login.")
        hashed_password = hashlib.sha256(password).hexdigest()
        return self.loginManager.authenticate(username=username,
                                              password=hashed_password)

    def logout(self, uuid):
        if self.loginManager is None:
            return
        return self.loginManager.logout(uuid=uuid)

    def test_login(self):
        rv = self.login(u'user', u'123')
        expected = \
            {u'first_name': {u'value': u'User'},
             u'last_name': {u'value': u'Test'},
             u'image': {u'data': None},
             u'user': {u'value': u'user'},
             u'login': True,
            }
        self.assertDictContainsSubset(expected, rv)
        self.assertIn("session_uuid", rv)
        self.assertIn("user_uuid", rv)

    def test_logout(self):
        uuid = self.login(u'user', u'123')['user_uuid']['value']
        rv = self.logout(uuid=uuid)
        self.assertIn('logout', rv)
        self.assertTrue(rv['logout'])
        self.assertIn('uuid', rv)
        self.assertEqual(uuid, rv['uuid'])

    def test_accounts_get_public_info(self):
        users = [self.login(u'user', u'123')['user_uuid']['value']]
        accounts_proxy = self.rpc_client.get_proxy(prefix="accounts.")
        info = accounts_proxy.getPublicInfo(users)
        assert len(info) == 1
        assert 'uuid' in info[0]
        for user in users:
            info_uuid = info[0]['uuid']['value']
            assert user == info_uuid

    def test_projects_create(self):
        user = self.login(u'user', u'123')
        projects_proxy = self.rpc_client.get_proxy(prefix="project.")
        model = projects_proxy.getModel()
        data = {
            "name":
            "PROYECTO 305",
            "general_location":
            "<p><em><strong>ASDASDASD</strong></em><br></p>",
            "locality":
            "suba",
            "project_type":
            "py_gr_escala",
            "profit_center":
            "ASDASDADS",
            "areas": [{
                "tipo": "A1",
                "valor": "121"
            }, {
                "tipo": "A2",
                "valor": "13"
            }],
            "uuid":
            model['data']['uuid']['value']
        }
        #: TODO Check for real asserts
        try:
            rv = projects_proxy.create(data=data)
            assert True
        except BaseException:
            assert False

    def test_form_find(self):
        user = self.login(u'user', u'123')
        projects_proxy = self.rpc_client.get_proxy(prefix="project.")
        rv = projects_proxy.getAll()
        self.assertIsNotNone(rv)
示例#13
0
class TaskServicesTestCase(unittest.TestCase):
    def setUp(self):
        caliope_server.app.config['TESTING'] = True
        caliope_server.init_flask_app()
        caliope_server.configure_server_and_app(
            "conf/test_caliope_server.json")
        caliope_server.configure_logger("conf/tests_logger.json")
        caliope_server.register_modules()
        caliope_server.app.storekv = RedisStore(redis.StrictRedis())
        self.http_server = WSGIServer((caliope_server.app.config['address'],
                                       caliope_server.app.config['port']),
                                      caliope_server.app,
                                      handler_class=WebSocketHandler)  # @IgnorePep8
        self.http_server.start()
        self.nodes_created = set()
        self.create_default_database()

    def tearDown(self):
        """Get rid of the database again after each test."""
        if self.rpc_client:
            self.rpc_client.transport.close()
        self.http_server.stop()
        self.http_server = None
        caliope_server.app = Flask('caliope_server')
        #:Delete database
        self.remove_used_nodes(self.nodes_created)


    def create_default_database(self):
        self.create_UserGroup('user', 'group')

    def create_UserGroup(self, username, groupname):
        try:
            u1 = CaliopeUser()
            u1.username = username
            u1.password = hashlib.sha256(u'123').hexdigest()
            u1.domainname = 'correlibre.org'
            u1.first_name = "User"
            u1.last_name = "Test"
            u1.avatar = "common-img/avatar.png"
            u1.save()
            self.nodes_created.add(u1.uuid)
            g1 = CaliopeGroup()
            g1.name = groupname
            g1.code = groupname
            g1.save()
            self.nodes_created.add(g1.uuid)
            u1.member_of.connect(g1)
            g1.members.connect(u1)
            self.assertTrue(u1.member_of.is_connected(g1))
            self.assertTrue(g1.members.is_connected(u1))
        except UniqueProperty:
            try:
                u1 = CaliopeUser.index.get(username=username)
                g1 = CaliopeGroup.index.get(code=groupname)
                assert u1 is not None and g1 is not None
                assert u1.member_of.is_connected(g1)
                assert g1.members.is_connected(u1)
            except DoesNotExist:
                assert False

    def remove_used_nodes(self, node_list):
        query = "START n=node:CaliopeStorage('uuid:{}') " \
                "MATCH  n-[r]-() " \
                "DELETE n, r"
        batch_query = []
        for uuid in node_list:
            batch_query.append(neo4j.cypher.Query(neo4j.GraphDatabaseService(),
                                                  query.format(uuid)).execute())

    def login(self, username, password):
        self.rpc_client = RPCClient(JSONRPCProtocol(),
                                    HttpWebSocketClientTransport(
                                        'ws://localhost:9001/api/ws'))
        self.loginManager = self.rpc_client.get_proxy("login.")
        hashed_password = hashlib.sha256(password).hexdigest()
        return self.loginManager.authenticate(username=username,
                                              password=hashed_password)

    def logout(self, uuid):
        if self.loginManager is None:
            return
        return self.loginManager.logout(uuid=uuid)


    def test_login(self):
        rv = self.login(u'user', u'123')
        expected = \
            {u'first_name': {u'value': u'User'},
             u'last_name': {u'value': u'Test'},
             u'image': {u'data': None},
             u'user': {u'value': u'user'},
             u'login': True,
            }
        self.assertDictContainsSubset(expected, rv)
        self.assertIn("session_uuid", rv)
        self.assertIn("user_uuid", rv)


    def test_logout(self):
        uuid = self.login(u'user', u'123')['user_uuid']['value']
        rv = self.logout(uuid=uuid)
        self.assertIn('logout', rv)
        self.assertTrue(rv['logout'])
        self.assertIn('uuid', rv)
        self.assertEqual(uuid, rv['uuid'])


    def test_ts_get_model(self):
        user = self.login(u'user', u'123')
        tasks_proxy = self.rpc_client.get_proxy(prefix="tasks.")
        model = tasks_proxy.getModel()
        self.assertIsNotNone(model)

    def test_task_get_model_and_data(self):
        user = self.login(u'user', u'123')
        tasks_proxy = self.rpc_client.get_proxy(prefix="tasks.")
        model = tasks_proxy.getModel()
        self.assertIsNotNone(model)
        uuid = model["data"]["uuid"]["value"]
        #:update
        update = tasks_proxy.updateField(uuid=uuid,
                                         field_name="name",
                                         value="test")

        #:commit
        commit = tasks_proxy.commit(uuid=uuid)
        self.assertTrue(commit)
        model_and_data = tasks_proxy.getModelAndData(uuid=uuid)
        self.assertEqual(model_and_data["data"]["name"]["value"], "test")


    def test_task_update_commit_field_single_value(self):
        user = self.login(u'user', u'123')
        tasks_proxy = self.rpc_client.get_proxy(prefix="tasks.")
        model = tasks_proxy.getModel()
        uuid = model["data"]["uuid"]["value"]
        #:update
        update = tasks_proxy.updateField(uuid=uuid,
                                         field_name="name",
                                         value="test")

        #:commit
        commit = tasks_proxy.commit(uuid=uuid)
        self.assertTrue(commit)

        #:update a commited value
        update = tasks_proxy.updateField(uuid=uuid,
                                         field_name="name",
                                         value="foo")
        self.assertTrue(update)

        #:commit again a previusly commited value after being updated
        self.assertTrue(tasks_proxy.commit(uuid=uuid))

        #:update twice a draft and commit
        update = tasks_proxy.updateField(uuid=uuid,
                                         field_name="name",
                                         value="more foo")
        self.assertTrue(update)
        update = tasks_proxy.updateField(uuid=uuid,
                                         field_name="name",
                                         value="not more foo")
        self.assertTrue(update)
        self.assertTrue(tasks_proxy.commit(uuid=uuid))
        self.nodes_created.add(uuid)


    def test_task_update_commit_field_single_value_not_exist_in_class(self):
        user = self.login(u'user', u'123')
        tasks_proxy = self.rpc_client.get_proxy(prefix="tasks.")
        model = tasks_proxy.getModel()
        uuid = model["data"]["uuid"]["value"]
        update = tasks_proxy.updateField(uuid=uuid,
                                         field_name="other",
                                         value="test")
        self.assertTrue(update)
        try:
            response = tasks_proxy.commit(uuid=uuid)
        except RPCError as error:
            self.assertIsInstance(error, RPCError)

    def test_task_update_commit_field_list(self):
        user = self.login(u'user', u'123')
        tasks_proxy = self.rpc_client.get_proxy(prefix="tasks.")
        model = tasks_proxy.getModel()
        uuid = model["data"]["uuid"]["value"]

        #:update invalid index first.
        try:
            update = tasks_proxy.updateField(uuid=uuid,
                                             field_name="subtasks",
                                             subfield_id=0,
                                             value="subtask0")
            self.assertTrue(update)
        except RPCError as error:
            self.assertIsInstance(error, RPCError)

        #:update and commit with empty lists
        update = tasks_proxy.updateField(uuid=uuid,
                                         field_name="subtasks",
                                         subfield_id=-1,
                                         value="subtask0")
        self.assertTrue(update)
        self.assertTrue(tasks_proxy.commit(uuid=uuid))

        #: update and commit already commited lists
        update = tasks_proxy.updateField(uuid=uuid,
                                         field_name="subtasks",
                                         subfield_id=0,
                                         value="new_subtask0")
        self.assertTrue(update)
        self.assertTrue(tasks_proxy.commit(uuid=uuid))

        #: update twice and commit
        update = tasks_proxy.updateField(uuid=uuid,
                                         field_name="subtasks",
                                         subfield_id=0,
                                         value="new_subtask0_up1")
        self.assertTrue(update)
        update = tasks_proxy.updateField(uuid=uuid,
                                         field_name="subtasks",
                                         subfield_id=0,
                                         value="new_subtask_up2")
        self.assertTrue(update)
        self.assertTrue(tasks_proxy.commit(uuid=uuid))

        #:update a non valid subfield_id
        try:
            update = tasks_proxy.updateField(uuid=uuid,
                                             field_name="subtasks",
                                             subfield_id=1,
                                             value="not subtask1")
        except RPCError as error:
            self.assertIsInstance(error, RPCError)

    def test_task_update_commit_field_list_list(self):
        user = self.login(u'user', u'123')
        tasks_proxy = self.rpc_client.get_proxy(prefix="tasks.")
        model = tasks_proxy.getModel()
        uuid = model["data"]["uuid"]["value"]

        #:update with invalid pos
        try:
            update = tasks_proxy.updateField(uuid=uuid,
                                             field_name="subtasks",
                                             subfield_id=-1,
                                             pos=0,
                                             value="subtask0")
        except RPCError as error:
            self.assertIsInstance(error, RPCError)

        #:update with invalid subfield_id
        try:
            update = tasks_proxy.updateField(uuid=uuid,
                                             field_name="subtasks",
                                             subfield_id=0,
                                             pos=-1,
                                             value="subtask0")
        except RPCError as error:
            self.assertIsInstance(error, RPCError)

        #:update and commit with empty lists
        update = tasks_proxy.updateField(uuid=uuid,
                                         field_name="subtasks",
                                         subfield_id=-1,
                                         pos=-1,
                                         value="subtask0")
        self.assertTrue(update)
        self.assertTrue(tasks_proxy.commit(uuid=uuid))

        #: update and commit already commited lists
        update = tasks_proxy.updateField(uuid=uuid,
                                         field_name="subtasks",
                                         subfield_id=0,
                                         pos=0,
                                         value="new_subtask0")
        self.assertTrue(update)
        self.assertTrue(tasks_proxy.commit(uuid=uuid))

        #update twice same, append new and commit
        update = tasks_proxy.updateField(uuid=uuid,
                                         field_name="subtasks",
                                         subfield_id=0,
                                         pos=0,
                                         value="new_subtask0_up1")
        self.assertTrue(update)
        update = tasks_proxy.updateField(uuid=uuid,
                                         field_name="subtasks",
                                         subfield_id=0,
                                         pos=0,
                                         value="new_subtask0_up2")
        self.assertTrue(update)
        update = tasks_proxy.updateField(uuid=uuid,
                                         field_name="subtasks",
                                         subfield_id=0,
                                         pos=-1,
                                         value="new_subtask1_up2")
        self.assertTrue(update)
        self.assertTrue(tasks_proxy.commit(uuid=uuid))

        #:update a non valid pos
        try:
            update = tasks_proxy.updateField(uuid=uuid,
                                             field_name="subtasks",
                                             subfield_id=0,
                                             pos=1,
                                             value="not subtask1")
        except RPCError as error:
            self.assertIsInstance(error, RPCError)


    def test_task_update_commit_field_list_dict(self):
        user = self.login(u'user', u'123')
        tasks_proxy = self.rpc_client.get_proxy(prefix="tasks.")
        model = tasks_proxy.getModel()
        uuid = model["data"]["uuid"]["value"]

        #:update with invalid subfield_id
        try:
            update = tasks_proxy.updateField(uuid=uuid,
                                             field_name="subtasks",
                                             subfield_id=0,
                                             pos="foo",
                                             value="subtask0")
        except RPCError as error:
            self.assertIsInstance(error, RPCError)

        #:update and commit with empty subfield
        update = tasks_proxy.updateField(uuid=uuid,
                                         field_name="subtasks",
                                         subfield_id=-1,
                                         pos="foo",
                                         value="subtask0")
        self.assertTrue(update)
        self.assertTrue(tasks_proxy.commit(uuid=uuid))

        #: update and commit already commited lists
        update = tasks_proxy.updateField(uuid=uuid,
                                         field_name="subtasks",
                                         subfield_id=0,
                                         pos="foo",
                                         value="new_subtask0")
        self.assertTrue(update)
        self.assertTrue(tasks_proxy.commit(uuid=uuid))

        #update twice same, append new and commit
        update = tasks_proxy.updateField(uuid=uuid,
                                         field_name="subtasks",
                                         subfield_id=0,
                                         pos="foo1",
                                         value="new_subtask0_up1")
        self.assertTrue(update)
        update = tasks_proxy.updateField(uuid=uuid,
                                         field_name="subtasks",
                                         subfield_id=0,
                                         pos="foo1",
                                         value="new_subtask0_up2")
        self.assertTrue(update)
        update = tasks_proxy.updateField(uuid=uuid,
                                         field_name="subtasks",
                                         subfield_id=0,
                                         pos="foo_new",
                                         value="new_subtask0_up2")
        self.assertTrue(update)
        self.assertTrue(tasks_proxy.commit(uuid=uuid))

        #:update a non valid pos
        try:
            update = tasks_proxy.updateField(uuid=uuid,
                                             field_name="subtasks",
                                             subfield_id=0,
                                             pos=1,
                                             value="not subtask1")
        except RPCError as error:
            self.assertIsInstance(error, RPCError)

    def test_task_update_commit_field_dict(self):
        user = self.login(u'user', u'123')
        tasks_proxy = self.rpc_client.get_proxy(prefix="tasks.")
        model = tasks_proxy.getModel()
        uuid = model["data"]["uuid"]["value"]


        #:update and commint for fist time
        update = tasks_proxy.updateField(uuid=uuid,
                                         field_name="comments",
                                         subfield_id="user1",
                                         value="comment0")
        self.assertTrue(update)
        self.assertTrue(tasks_proxy.commit(uuid=uuid))

        #: update and commit already commited lists
        update = tasks_proxy.updateField(uuid=uuid,
                                         field_name="comments",
                                         subfield_id="user1",
                                         value="comment0_up0")
        self.assertTrue(update)
        self.assertTrue(tasks_proxy.commit(uuid=uuid))

        #: update twice, append new and commit
        update = tasks_proxy.updateField(uuid=uuid,
                                         field_name="comments",
                                         subfield_id="user1",
                                         value="comment0_up1")
        self.assertTrue(update)
        update = tasks_proxy.updateField(uuid=uuid,
                                         field_name="comments",
                                         subfield_id="user1",
                                         value="comment0_up2")
        self.assertTrue(update)
        update = tasks_proxy.updateField(uuid=uuid,
                                         field_name="comments",
                                         subfield_id="user2",
                                         value="comment0")
        self.assertTrue(update)
        self.assertTrue(tasks_proxy.commit(uuid=uuid))

        #:update a non valid subfield_id
        try:
            update = tasks_proxy.updateField(uuid=uuid,
                                             field_name="comments",
                                             subfield_id=1,
                                             value="not subtask1")
        except RPCError as error:
            self.assertIsInstance(error, RPCError)
class AccessControlTestCase(unittest.TestCase):
    def setUp(self):
        caliope_server.app.config['TESTING'] = True
        caliope_server.init_flask_app()
        caliope_server.configure_server_and_app("../../conf/test_caliope_server.json")
        caliope_server.configure_logger("../../conf/tests_logger.json")
        caliope_server.register_modules()
        caliope_server.app.storekv = RedisStore(redis.StrictRedis())
        self.http_server = WSGIServer((caliope_server.app.config['address'],
                                       caliope_server.app.config['port']),
                                      caliope_server.app,
                                      handler_class=WebSocketHandler)  # @IgnorePep8
        self.http_server.start()
        DefaultDatabase().test_defaultUserGroupOne()

    def tearDown(self):
        """Get rid of the database again after each test."""
        if self.rpc_client:
            self.rpc_client.transport.close()
        self.http_server.stop()
        self.http_server = None
        caliope_server.app = Flask('caliope_server')
        #:Delete database
        neo4j.GraphDatabaseService().clear()


    def login(self, username='******', password='******'):
        self.rpc_client = RPCClient(JSONRPCProtocol(),
                                    HttpWebSocketClientTransport('ws://localhost:9001/api/ws'))
        self.loginManager = self.rpc_client.get_proxy("login.")
        hashed_password = hashlib.sha256(password).hexdigest()
        return self.loginManager.authenticate(username=username,
                                              password=hashed_password)

    def logout(self, uuid):
        if self.loginManager is None:
            return
        return self.loginManager.logout(uuid=uuid)


    def test_login(self):
        rv = self.login(u'user', u'123')
        assert 'login' in rv
        assert rv['login'] is True
        assert 'user_uuid' in rv
        assert 'session_uuid' in rv

    def test_logout(self):
        uuid = self.login(u'user', u'123')['user_uuid']['value']
        rv = self.logout(uuid=uuid)
        assert 'logout' in rv
        assert rv['logout']

    def test_isAccessGranted(self):
        # TODO(nel): Deprecate this method.
        self.login()
        ac_proxy = self.rpc_client.get_proxy("ac.")
        self.assertEqual({'granted': True}, ac_proxy.isAccessGranted({}))

    def test_getUserList(self):
        self.login()
        ac_proxy = self.rpc_client.get_proxy("ac.")

        user_list = set(['revisor_1', 'revisor_2', 'revisor_3', 'recepcionista_1',
                         'recepcionista_2', 'superuser', 'secretaria_1', 'reportero_1',
                         'reportero_2', 'gerente_1'])

        for user in ac_proxy.getUserList({}):
            self.assertIn(user, user_list)
            user_list.remove(user)

        self.assertEqual(user_list, set())

    def test_getGroupList(self):
        self.login()
        ac_proxy = self.rpc_client.get_proxy("ac.")

        group_list = set(['everybody', 'secretarias', 'revisores', 'reportes', 'superusers', 'gerentes', 'recepcionistas'])

        for group in ac_proxy.getGroupList({}):
            self.assertIn(group, group_list)
            group_list.remove(group)

        self.assertEqual(group_list, set())

    def test_getGroupsForUser(self):
        self.login()
        ac_proxy = self.rpc_client.get_proxy('ac.')
        print ac_proxy.getGroupsOfUser('gerente_1')

    def test_getUserPermissions(self):
        self.login()

        permissions_of_user = \
             set([('read', 'form', 'everybody'), ('read', 'form', 'gerentes'),
              ('read', 'document', 'everybody'), ('read', 'document', 'gerentes'),
              ('read', 'task', 'everybody'), ('read', 'task', 'gerentes'),
              ('read', 'report', 'everybody'), ('read', 'report', 'gerentes'),
              ('write', 'form', 'everybody'), ('write', 'form', 'gerentes'),
              ('write', 'document', 'everybody'), ('write', 'document', 'gerentes'),
              ('write', 'task', 'everybody'), ('write', 'task', 'gerentes'),
              ('write', 'report', 'everybody'), ('write', 'report', 'gerentes'),
              ('assign', 'form', 'everybody'), ('assign', 'form', 'gerentes'),
              ('assign', 'document', 'everybody'), ('assign', 'document', 'gerentes'),
              ('assign', 'task', 'everybody'), ('assign', 'task', 'gerentes'),
              ('assign', 'report', 'everybody'), ('assign', 'report', 'gerentes'),
              ('assign', 'form', 'reportes'), ('assign', 'document', 'reportes'),
              ('assign', 'task', 'reportes'), ('assign', 'report', 'reportes')])

        ac_proxy = self.rpc_client.get_proxy("ac.")

        for perm in ac_proxy.getUserPermissions('gerente_1'):
            self.assertIn(tuple(perm), permissions_of_user)
            permissions_of_user.remove(tuple(perm))
        self.assertEqual(permissions_of_user, set())
示例#15
0

# def static_wsgi_app(environ, start_response):
#     start_response("200 OK", [("Content-Type", "text/html")])
#     return open("assets/plot_graph.html").readlines()
#
# routes = [
#     ('/', static_wsgi_app),
#     ('/data', PlotApplication)
# ]

if __name__ == "__main__":
    while not rpc_client:
        try:
            rpc_client = RPCClient(
                HttpWebSocketClientTransport('192.168.0.118:8000/buyer'),
                JSONRPCProtocol())
        # TODO: check for reasonable exceptions
        except Exception, e:
            print e
            continue
    pm = PowerMeter(rpc_client)
    data = {'app': pm}
    pm_thread = gevent.spawn(pm.start)
    # resource = _Resource(routes, extra=data)
    # server = WebSocketServer(('', 8000), resource, debug=True)
    try:
        server.serve_forever()
    finally:
        pm.rpc_client.stop()
        GPIO.cleanup()
示例#16
0
def client(mock_protocol, mock_transport):
    return RPCClient(mock_protocol, mock_transport)
class CaliopeServerTestCase(unittest.TestCase):
    def setUp(self):
        caliope_server.app.config['TESTING'] = True
        caliope_server.init_flask_app()
        caliope_server.configure_server_and_app("../../conf/test_caliope_server.json")
        caliope_server.configure_logger("../../conf/tests_logger.json")
        caliope_server.register_modules()
        caliope_server.app.storekv = RedisStore(redis.StrictRedis())
        self.http_server = WSGIServer((caliope_server.app.config['address'],
                                       caliope_server.app.config['port']),
                                      caliope_server.app,
                                      handler_class=WebSocketHandler)  # @IgnorePep8
        self.http_server.start()
        self.create_default_database()

    def tearDown(self):
        """Get rid of the database again after each test."""
        if self.rpc_client:
            self.rpc_client.transport.close()
        self.http_server.stop()
        self.http_server = None
        caliope_server.app = Flask('caliope_server')
        #:Delete database
        neo4j.GraphDatabaseService().clear()


    def create_default_database(self):
        DefaultDatabase().test_defaultUserGroupOne()


    def login(self, username, password):
        self.rpc_client = RPCClient(JSONRPCProtocol(),
                                    HttpWebSocketClientTransport('ws://localhost:9001/api/ws'))
        self.loginManager = self.rpc_client.get_proxy("login.")
        hashed_password = hashlib.sha256(password).hexdigest()
        return self.loginManager.authenticate(username=username,
                                              password=hashed_password)

    def logout(self, uuid):
        if self.loginManager is None:
            return
        return self.loginManager.logout(uuid=uuid)


    def test_login(self):
        rv = self.login(u'user', u'123')
        expected = \
            {u'first_name': {u'value': u'User'},
             u'last_name': {u'value': u'Test'},
             u'image': {u'data': None},
             u'user': {u'value': u'user'},
             u'login': True,
            }
        self.assertDictContainsSubset(expected, rv)
        self.assertIn("session_uuid", rv)
        self.assertIn("user_uuid", rv)


    def test_logout(self):
        uuid = self.login(u'user', u'123')['user_uuid']['value']
        rv = self.logout(uuid=uuid)
        self.assertIn('logout', rv)
        self.assertTrue(rv['logout'])
        self.assertIn('uuid', rv)
        self.assertEqual(uuid, rv['uuid'])

    def test_accounts_get_public_info(self):
        users = [self.login(u'user', u'123')['user_uuid']['value']]
        accounts_proxy = self.rpc_client.get_proxy(prefix="accounts.")
        info = accounts_proxy.getPublicInfo(users)
        assert len(info) == 1
        assert 'uuid' in info[0]
        for user in users:
            info_uuid = info[0]['uuid']['value']
            assert user == info_uuid



    def test_projects_create(self):
        user = self.login(u'user', u'123')
        projects_proxy = self.rpc_client.get_proxy(prefix="project.")
        model = projects_proxy.getModel()
        data = {"name": "PROYECTO 305",
                "general_location": "<p><em><strong>ASDASDASD</strong></em><br></p>",
                "locality": "suba",
                "project_type": "py_gr_escala",
                "profit_center": "ASDASDADS",
                "areas": [{"tipo": "A1", "valor": "121"}, {"tipo": "A2", "valor": "13"}],
                "uuid": model['data']['uuid']['value']
        }
        #: TODO Check for real asserts
        try:
            rv = projects_proxy.create(data=data)
            assert True
        except BaseException:
            assert False

    def test_form_find(self):
        user = self.login(u'user', u'123')
        projects_proxy = self.rpc_client.get_proxy(prefix="project.")
        rv = projects_proxy.getAll()
        self.assertIsNotNone(rv)
示例#18
0

class CallbackServerTransport(ServerTransport):
    def receive_message(self) -> t.Tuple[t.Any, bytes]:
        context = "*context*"
        return context, in_box.pop(0)

    def send_reply(self, context: t.Any, reply: bytes):
        print(context)
        out_box.append(reply)


rpc_server = RPCServer(
    CallbackServerTransport(),
    JSONRPCProtocol(),
    dispatcher,
)
rpc_server.trace = print

# 本来はこれを実行する
# rpc_server.serve_forever()

rpc_client = RPCClient(JSONRPCProtocol(), CallbackClientTransport())
proxy = rpc_client.get_proxy()

try:
    result = proxy.add(10, 20)
    print(f"result is {result}")
except Exception as e:
    print(e)
示例#19
0
class LimeAPI:
    """
    LimeSurvey API Client for Remote API 2.
        Aims to simplify and automate the necessary task of moving data out of
        LimeSurvey without having to pull it directly from the site. Most of the
        communication between the remote LimeSurvey instance and the API follows
        the JSON-RPC 2 protocol.
        request and response validation to help keep communication more consistent.
    """

    # The following defaults are defined in a configuration file. See `settings.py` for
    # more details.
    _default_headers = {
        "content-type": "application/json",
        "connection": "Keep-Alive"
    }

    # There are still a few pain points in dealing with the JSON-RPC protocol
    _rpc_protocol_patched = False

    def __init__(self, url, username, password, headers=None):
        """
        LimeSurvey API Client for Remote API 2.
        Aims to simplify and automate the necessary task of moving data out of
        LimeSurvey in one way or another.
        :param url:     Fully-qualified LimeSurvey server URL containing protocol,
                        hostname, port, and the endpoint for the Remote Control 2 API.
        :param username: LimeSurvey account username
        :param password: LimeSurvey account password
        :param headers: Headers to include when making requests. At a minimum, each
                        request should be fitted with an application/JSON content-type
                        declaration
        """
        logger.info("Instantiating LimeAPI client")
        self.url = url
        self.username = username
        self.password = password
        self.headers = self._default_headers if headers is None else headers
        self.session_key = None
        self.rpc_client = None
        self.rpc_proxy = None
        self._authenticated = False

        self._validate_settings()

    @property
    def remote_api_url(self):
        return "/".join(
            [self.url.rstrip("/"), "/index.php/admin/remotecontrol"])

    def authenticate(self):
        """
        Performs authentication actions
        Patches `tinyrpc` to remove minor incompatibilities due to JSON-RPC
        protocol version differences. This is performed once.
        Initializes the RPCClient and RPCProxy instances that
        are used to make the requests to Lime.
        :return: None
        """
        logger.info("Authenticating LimeAPI client")
        if not LimeAPI._rpc_protocol_patched:
            LimeAPI.patch_json_rpc_protocol()
            LimeAPI._rpc_protocol_patched = True
        self.rpc_client = RPCClient(
            JSONRPCProtocol(),
            HttpPostClientTransport(endpoint=self.remote_api_url,
                                    headers=self.headers),
        )

        self.rpc_proxy = self.rpc_client.get_proxy()
        self.session_key = self.rpc_proxy.get_session_key(
            username=self.username, password=self.password)
        if not self._validate_session_key():
            raise Exception(f"Failed to validate session key: url={self.url} "
                            f"session_key={self.session_key}")
        self._authenticated = True
        logger.info(f"Acquired session key: {self.session_key}")

    def list_surveys(self, username=None):
        """
        List the surveys belonging to a user
        If user is admin, he can get surveys of every user (parameter sUser)
        or all surveys (sUser=null). Otherwise, only the surveys belonging to the
        user making the request will be shown.

        Returns a JSON array of surveys containing the following keys:
        sid startdate expires active surveyls_title
        :param username: (optional) Include if you want to limit the scope of the
                         list operation or are only interested in the surveys that
                         belong to you.
        :return: array of survey dict items
        """
        with self.request_ctx("list_surveys"):
            result = self.rpc_proxy.list_surveys(sSessionKey=self.session_key,
                                                 sUser=username
                                                 or self.username)
            return result

    def list_questions(self,
                       survey_id: int,
                       group_id: int = None,
                       language: str = None):
        """
        Return the ids and info of (sub-)questions of a survey/group.
        :param survey_id: the survey ID
        :param group_id: (optional) A group ID that can be used for filtering results
        :param language:
        :return: list of questions
        """
        with self.request_ctx("list_questions"):
            result = self.rpc_proxy.list_questions(
                sSessionKey=self.session_key,
                iSurveyID=survey_id,
                iGroupId=group_id,
                sLanguage=language,
            )
            return result

    def get_language_properties(self, survey_id: int):
        """
        Gets language properties
        :param survey_id:
        :return:
        """
        with self.request_ctx("get_language_properties"):
            result = self.rpc_proxy.get_language_properties(
                sSessionKey=self.session_key,
                iSurveyID=survey_id,
                aSurveyLocaleSettings=None,
                sLang=None,
            )
            return result

    def get_survey_properties(self, survey_id: int):
        """
        Retrieves survey properties
        Additional properties (including the survey title)
        must be retrieved from the 'get_language_properties' endpoint

        :param survey_id: the survey ID to retrieve
        :return: list
        """
        with self.request_ctx("get_survey_properties"):
            result = self.rpc_proxy.get_survey_properties(
                sSessionKey=self.session_key,
                iSurveyID=survey_id,
                aSurveyLocaleSettings=None,
                sLang=None,
            )
            return result

    @contextmanager
    def request_ctx(self, endpoint):
        """
        A common helper context that is used for all of the endpoints
        It provides authentication, error handling, logging, and
        stat collection
        :param endpoint:
        :param ctx:
        :return:
        """
        logger.info(f"Sending LimeAPI RPC Request for endpoint [{endpoint}]")
        t0 = pendulum.now()
        try:
            self._validate_auth()
            yield
            duration = (pendulum.now() - t0).total_seconds() * 1000
            logger.info(
                f"Endpoint [{endpoint}]: Request completed in {duration} ms")
            error = None
        except Exception as e:
            error = e
            traceback.print_exc()

        if error:
            raise error

    def export_responses(
        self,
        survey_id: int,
        language_code: str = None,
        completion_status: str = "all",
        heading_type: str = "code",
        response_type: str = "long",
        from_response_id: int = None,
        to_response_id: int = None,
        fields=None,
    ):
        with self.request_ctx("get_survey_properties"):
            _completion_statuses = ["complete", "incomplete", "all"]
            _heading_types = ["code", "full", "abbreviated"]
            _response_types = ["short", "long"]

            result_b64 = self.rpc_proxy.export_responses(
                sSessionKey=self.session_key,
                iSurveyID=survey_id,
                sDocumentType="json",
                sLanguageCode=language_code,
                sCompletionStatus=completion_status,
                sHeadingType=heading_type,
                sResponseType=response_type,
                iFromResponseID=from_response_id,
                iToResponseID=to_response_id,
                aFields=fields,
            )
            result_utf8 = base64.b64decode(result_b64).decode("utf-8")
            result_json = json.loads(result_utf8)
            result_json = result_json["responses"]
            rows = []
            for id_survey_map in result_json:
                for survey in id_survey_map.values():
                    rows.append(survey)
            return rows

    @staticmethod
    def patch_json_rpc_protocol():
        def parse_reply_patched(self, data):
            """Deserializes and validates a response.

            Called by the client to reconstruct the serialized :py:class:`JSONRPCResponse`.

            :param bytes data: The data stream received by the transport layer containing the
                serialized request.
            :return: A reconstructed response.
            :rtype: :py:class:`JSONRPCSuccessResponse` or :py:class:`JSONRPCErrorResponse`
            :raises InvalidReplyError: if the response is not valid JSON or does not conform
                to the standard.
            """
            if isinstance(data, bytes):
                data = data.decode()
            try:
                print(data)
                rep = json.loads(data)
            except Exception as e:
                traceback.print_exc()
                raise InvalidReplyError(e)
            for k in rep.keys():
                if not k in self._ALLOWED_REPLY_KEYS:
                    raise InvalidReplyError("Key not allowed: %s" % k)
            if "id" not in rep:
                raise InvalidReplyError("Missing id in response")
            if "error" in rep and rep["error"] is not None:
                pprint(rep)
                response = JSONRPCErrorResponse()
                error = rep["error"]
                if isinstance(error, str):
                    response.error = error
                    response.code = -1
                    response._jsonrpc_error_code = -1
                else:
                    response.error = error["message"]
                    response._jsonrpc_error_code = error["code"]
                    if "data" in error:
                        response.data = error["data"]
            else:
                response = JSONRPCSuccessResponse()
                response.result = rep.get("result", None)
            response.unique_id = rep["id"]
            return response

        logger.info("Patching JSONRPCProtocol `parse_reply` method")
        JSONRPCProtocol.parse_reply = parse_reply_patched

    def _validate_settings(self):
        """
        Makes sure that the we instantiated properly
        :return:
        """
        logger.info("Validating LimeAPI settings")
        if None in [self.url, self.username, self.password]:
            raise EnvironmentError()

    def _validate_rpc_resources(self):

        if not isinstance(self.rpc_client, RPCClient):
            return False

        if not isinstance(self.rpc_proxy, RPCProxy):
            return False

        return True

    def _validate_session_key(self):

        if self.session_key is None:
            return False

        if not isinstance(self.session_key, str):
            return False

        if type(self.session_key) is str and len(self.session_key) == 0:
            return False

        return True

    def _validate_auth(self):
        """
        Checks for authentication issues
        :return: None
        """
        # Checking that we ran auth initialization

        if not self._authenticated:
            self.authenticate()

        elif not self._validate_session_key():
            self.authenticate()

        elif not self._validate_rpc_resources():
            self.authenticate()
class AccessControlTestCase(unittest.TestCase):
    def setUp(self):
        caliope_server.app.config['TESTING'] = True
        caliope_server.init_flask_app()
        caliope_server.configure_server_and_app(
            "../../conf/test_caliope_server.json")
        caliope_server.configure_logger("../../conf/tests_logger.json")
        caliope_server.register_modules()
        caliope_server.app.storekv = RedisStore(redis.StrictRedis())
        self.http_server = WSGIServer(
            (caliope_server.app.config['address'],
             caliope_server.app.config['port']),
            caliope_server.app,
            handler_class=WebSocketHandler)  # @IgnorePep8
        self.http_server.start()
        DefaultDatabase().test_defaultUserGroupOne()

    def tearDown(self):
        """Get rid of the database again after each test."""
        if self.rpc_client:
            self.rpc_client.transport.close()
        self.http_server.stop()
        self.http_server = None
        caliope_server.app = Flask('caliope_server')
        #:Delete database
        neo4j.GraphDatabaseService().clear()

    def login(self, username='******', password='******'):
        self.rpc_client = RPCClient(
            JSONRPCProtocol(),
            HttpWebSocketClientTransport('ws://localhost:9001/api/ws'))
        self.loginManager = self.rpc_client.get_proxy("login.")
        hashed_password = hashlib.sha256(password).hexdigest()
        return self.loginManager.authenticate(username=username,
                                              password=hashed_password)

    def logout(self, uuid):
        if self.loginManager is None:
            return
        return self.loginManager.logout(uuid=uuid)

    def test_login(self):
        rv = self.login(u'user', u'123')
        assert 'login' in rv
        assert rv['login'] is True
        assert 'user_uuid' in rv
        assert 'session_uuid' in rv

    def test_logout(self):
        uuid = self.login(u'user', u'123')['user_uuid']['value']
        rv = self.logout(uuid=uuid)
        assert 'logout' in rv
        assert rv['logout']

    def test_isAccessGranted(self):
        # TODO(nel): Deprecate this method.
        self.login()
        ac_proxy = self.rpc_client.get_proxy("ac.")
        self.assertEqual({'granted': True}, ac_proxy.isAccessGranted({}))

    def test_getUserList(self):
        self.login()
        ac_proxy = self.rpc_client.get_proxy("ac.")

        user_list = set([
            'revisor_1', 'revisor_2', 'revisor_3', 'recepcionista_1',
            'recepcionista_2', 'superuser', 'secretaria_1', 'reportero_1',
            'reportero_2', 'gerente_1'
        ])

        for user in ac_proxy.getUserList({}):
            self.assertIn(user, user_list)
            user_list.remove(user)

        self.assertEqual(user_list, set())

    def test_getGroupList(self):
        self.login()
        ac_proxy = self.rpc_client.get_proxy("ac.")

        group_list = set([
            'everybody', 'secretarias', 'revisores', 'reportes', 'superusers',
            'gerentes', 'recepcionistas'
        ])

        for group in ac_proxy.getGroupList({}):
            self.assertIn(group, group_list)
            group_list.remove(group)

        self.assertEqual(group_list, set())

    def test_getGroupsForUser(self):
        self.login()
        ac_proxy = self.rpc_client.get_proxy('ac.')
        print ac_proxy.getGroupsOfUser('gerente_1')

    def test_getUserPermissions(self):
        self.login()

        permissions_of_user = \
             set([('read', 'form', 'everybody'), ('read', 'form', 'gerentes'),
              ('read', 'document', 'everybody'), ('read', 'document', 'gerentes'),
              ('read', 'task', 'everybody'), ('read', 'task', 'gerentes'),
              ('read', 'report', 'everybody'), ('read', 'report', 'gerentes'),
              ('write', 'form', 'everybody'), ('write', 'form', 'gerentes'),
              ('write', 'document', 'everybody'), ('write', 'document', 'gerentes'),
              ('write', 'task', 'everybody'), ('write', 'task', 'gerentes'),
              ('write', 'report', 'everybody'), ('write', 'report', 'gerentes'),
              ('assign', 'form', 'everybody'), ('assign', 'form', 'gerentes'),
              ('assign', 'document', 'everybody'), ('assign', 'document', 'gerentes'),
              ('assign', 'task', 'everybody'), ('assign', 'task', 'gerentes'),
              ('assign', 'report', 'everybody'), ('assign', 'report', 'gerentes'),
              ('assign', 'form', 'reportes'), ('assign', 'document', 'reportes'),
              ('assign', 'task', 'reportes'), ('assign', 'report', 'reportes')])

        ac_proxy = self.rpc_client.get_proxy("ac.")

        for perm in ac_proxy.getUserPermissions('gerente_1'):
            self.assertIn(tuple(perm), permissions_of_user)
            permissions_of_user.remove(tuple(perm))
        self.assertEqual(permissions_of_user, set())
示例#21
0
class SatnetRPC(object):

    testing = False

    def __init__(self, user, pwd):
        """Start RPC connection and keep session open
        Example:
        rpc = Satnet_RPC('crespum', 'solutions')
        print rpc.call('configuration.sc.list')

        :param user: SatNet username.
        :type user: L{String}
        :param pwd: SatNet password for this user.
        :type pwd: L{String}
        """
        self._rpc_client = RPCClient(JSONRPCProtocolFix(),
                                     HttpSessionTransport(user, pwd))
        self.detect_test(user)

        if self.testing:
            return

        if not self.login(user, pwd):
            raise BadCredentials()

        tw_log.msg('System login confirmed!')

    def detect_test(self, username):
        """Detects the test mode
        This function sets the object into testing mode if the name of the
        users coincides with any of the TEST_USER names enabled for that
        purpose.
        :param username: The current username
        """
        if username == RPC_TEST_USER_GS or username == RPC_TEST_USER_SC:
            self.testing = True
            tw_log.msg('>>> Testing user detected, running in TESTING MODE')

    def call(self, call, *args):
        """Make an RPC call to the SatNet server

        :param call: Name of the methods
        :type call: L{String}
        :param args: Arguments required by the method to be invocked.
        """

        return self._rpc_client.call(call, args, None)

    def login(self, user, pwd):
        """system.login
        :param user: String with the username of the currently logged in user
        :param pwd: String with the password for the currently logged in user
        """
        tw_log.msg('@@@@ system.login, user = '******', pwd = ' +
                   str(pwd))
        return self.call('system.login', str(user), str(pwd))

    def get_slot(self, slot_id):
        """scheduling.slot.get
        :param slot_id: Identifier of the slot
        """
        return self.call('scheduling.slot.get', slot_id)

    def get_next_slot(self, user_email):
        """scheduling.slot.next
        :param user_email: Identifier of the slot
        """
        return self.call('scheduling.slot.next', user_email)

    def store_message(self, slot_id, upwards, forwarded, timestamp, message):
        """communications.storeMessage
        :param slot_id: Identifier of the slot
        :param upwards: Flag that indicates the direction of the message
        :param forwarded: Flat that indicates whether this message has already
                            been forwarded or not
        :param timestamp: Unix timestamp for the reception of the package
        :param message: String with the message received from the client
        """
        base_64_message = base64.b64encode(message)
        slot_id = str(slot_id)

        self.call('communications.storeMessage', slot_id, upwards, forwarded,
                  timestamp, base_64_message)

    def store_message_unconnected(self, message):
        """Stores messages for unconnected spacecraft operators
        TODO Find out proper values for the parameters
        :param message: String with the message received from the client
        """
        self.store_message_passive(0, 0, 0.0, base64.b64encode(message))

    def store_message_passive(self, groundstation_id, timestamp, doppler_shift,
                              message):
        """communications.gs.storePassiveMessage
        :param groundstation_id: Identifier of the groundstation
        :param timestamp: Unix timestamp for the reception of the package
        :param doppler_shift: Estimation of the Doppler shift
        :param message: String with the message received from the client
        """
        base_64_message = base64.b64encode(message)

        self.call('communications.gs.storePassiveMessage', groundstation_id,
                  timestamp, doppler_shift, base_64_message)