Ejemplo n.º 1
0
 def on_message(self, raw_message):
     
     start = time.time()
     
     message = json_decode(raw_message)
     action = message.get("action")
     
     try:
         logging.debug(message)
         args = message.get("args", {})
         
         method = getattr(self.control, action)
         
         if action=="make_impression":
             args["summary"] = self._request_summary()
             
         result = method(self.current_user, **args)
         self.send(utils.dumps({"result": result,
                                         "response_id": message.get("request_id")}))
         self.log_action(access_log.info, start, action, self.current_user)
         self.control._flush()
         
     except Exception as ex:
         logging.exception(ex)
         error = str(ex)
         self.send(utils.dumps({"result": None,
                             "error" : error,
                             "response_id": message.get("request_id"),
                             }))
         self.log_action(access_log.error, start, action, self.current_user, error)
         self.control._flush(ex)
Ejemplo n.º 2
0
 def test_http_put(self):
     fake = Factory.create("en_GB")
     client = AsyncHTTPClient(self.io_loop)
     for _ in range(10):
         data = {"item":{
             "email":     fake.email(),
             "firstname": fake.first_name(),
             "lastname":  fake.last_name(),
             "_password": fake.password()
         }}
         client.fetch("{}Person".format(BASE_URL), self.stop, 
                      method="PUT", 
                      body=dumps(data),
                      headers={"Content-Type": "application/json",
                               "simple-auth-token":"--foo-bar--"})
         response = self.wait()
         result = loads(response.body.decode("utf-8"))
         if result.get("error"):
             raise Exception(result["error"])
         
     for _ in range(10):
         data = {"item":{
             "name":  fake.name(),
             "dob": fake.date(),
             "active": fake.pybool(),
             "customer_type": "retail"
         }}
         client.fetch("{}Customer".format(BASE_URL), self.stop, 
                      method="PUT", 
                      body=dumps(data),
                      headers={"Content-Type": "application/json",
                               "simple-auth-token":"--foo-bar--"})
         response = self.wait()
         result = loads(response.body.decode("utf-8"))
         if result.get("error"):
             raise Exception(result["error"])
         
         data = {
             "item": {
                 "line1":  fake.address(),
                 "town": fake.city(),
                 "postcode": fake.postcode(),
                 "customer_type": "retail"
             },
             "to_add": [
                        [
                         "customers",
                         "Customer",
                         result["result"]["id"]
                        ]
                     ]
         }
         client.fetch("{}Address".format(BASE_URL), self.stop, 
                      method="PUT", 
                      body=dumps(data),
                      headers={"Content-Type": "application/json",
                               "simple-auth-token":"--foo-bar--"})
         response = self.wait()
         result = loads(response.body.decode("utf-8"))
Ejemplo n.º 3
0
 def put(self,resource_path):
     """
         Put goes to fetch_and_carry_mixin carry
     """
     self.require_json_content()
     logging.info("put %s - %s",resource_path, self.json_args)
     try:
         resources = resource_path.split("/")
         resource = resources[0]
         id = int(resources[1]) if len(resources) > 1 else None
         args = self.json_args
         item = args.get("item")
         if item is None:
             raise Exception("json payload: {item:obj, (to_add:[attr,type,id]]), (to_remove:[attr,type,id]])}")
         if item.get("_type") is None and resource in [None,""]:
             raise Exception("No resource specified")
         if item.get("_type") is None:
             item["_type"] = resource
         result = {"result": self.control.carry(self.get_current_user,
                                                item,
                                                args.get("to_add"),
                                                args.get("to_remove")), "action": "saved" }
     except Exception as ex:
         result = {"error": str(ex)}
         self.control._flush(ex)
         logging.exception(ex)
     self.set_header("Content-Type", "application/json; charset=UTF-8")
     self.write(dumps(result))
     self.control._flush()
Ejemplo n.º 4
0
 def get_audit_trail(cls, obj):
     from sqlalchemy.orm import object_mapper
     session = object_session(obj)
     obj_mapper = object_mapper(obj)
     primary_key = cls._get_instance_pk(obj, obj_mapper)
     return session.query(cls).filter(and_(cls.type==obj.__class__.__name__,
                                           cls.ref==utils.dumps(primary_key)))
Ejemplo n.º 5
0
 def on_message(self, raw_message):
     
     start = time.time()
     
     message = json_decode(raw_message)
     action = message.get("action")
     
     try:
         logging.debug(message)
         args = message.get("args", {})
         
         if action == "register":
             self.handle_register(message)
         elif action == "login":
             self.handle_login(message)
         else:
             method = getattr(self.control, action)
             
             result = method(self.current_user, **args)
             self.write_message(utils.dumps({"result": result,
                                             "response_id": message.get("request_id")}))
             self.log_action(access_log.info, start, action, self.current_user)
             self.control._flush()
         
     except Exception as ex:
         logging.exception(ex)
         error = str(ex)
         self.write_message({"result": None,
                             "error" : error,
                             "response_id": message.get("request_id"),
                             })
         self.log_action(access_log.error, start, action, self.current_user, error)
         self.control._flush(ex)
Ejemplo n.º 6
0
 def handle_register(self, message):
     accl_key = self.control.register(message.get("email"))
     self._current_user = accl_key
     self.write_message(utils.dumps({
                         "result":accl_key, 
                         "cookie":self.gen_login_cookie(accl_key), 
                         "cookie_name":self.cookie_name, 
                         "response_id":message.get("request_id")
                         }))
     self._begin_web_session(self.current_user, 
                             self.request.remote_ip, 
                             self.request.headers)
Ejemplo n.º 7
0
 def on_open(self, request):  
     self.request = request
     self.application = self.session.handler.application
     logging.info("SockJS opened")
     user = self.control.begin_web_session(self.current_user, 
                                           self, request.ip, request.headers)
     if user:
         self.broadcast({
                         "signal":"user",
                         "message": user
                         })
     else:
         self.send(utils.dumps({'access_error':True}))
         self.close(reason="access control failure")
Ejemplo n.º 8
0
 def post(self,resource_path):
     """
         Post calls public methods on the control
     """
     self.require_json_content()
     logging.info("post %s - %s",resource_path, self.json_args)
     resources = resource_path.split("/")
     action = resources[0]
     try:
         logging.debug(resource_path)
         args = self.json_args or {}
         
         method = getattr(self.control, action)
             
         result = method(self.current_user, **args)
         self.write(dumps({"result": result},indent=2))
         self.control._flush()
         
     except Exception as ex:
         logging.exception(ex)
         error = str(ex)
         self.write(dumps({"result": None,
                           "error" : error },indent=2))
         self.control._flush(ex)
Ejemplo n.º 9
0
 def delete(self, resource_path):
     """
         Put goes to fetch_and_carry_mixin carry
     """
     self.require_json_content()
     logging.info("delete %s",resource_path)
     try:
         resources = resource_path.split("/")
         resource = resources[0]
         id = int(resources[1])
         result = {"result": self.control.carry(1,{"id":-id,"_type":resource}) , "action": "deleted"}
     except Exception as ex:
         result = {"error": str(ex)}
         logging.exception(ex)
     self.set_header("Content-Type", "application/json; charset=UTF-8")
     self.write(dumps(result))
Ejemplo n.º 10
0
 def get(self, resource_path):
     """
         Get goes to fetch_and_carry_mixin fetch or returns the meta data
     """
     logging.info("get %s",resource_path)
     if resource_path is None or resource_path is "":
         self.write(OrderedDict([
             ("target", "rest-api"),
             ("version", 1),
             ("post_methods", self.control._fc_methods),
             ("model", self.control._fc_description)
         ]))
     else:
         try:
             resources = resource_path.split("/")
             resource = resources[0]
             id = resources[1] if len(resources) > 1 else None
             limit = int(self.get_argument("limit", 10))
             offset = int(self.get_argument("offset", 0))
             attr = self.get_argument("attr", None)
             filter = self.get_argument("filter", None)
             match = self.get_argument("match", None)
             order_by = self.get_argument("order_by", None)
             order_by_asc = self.get_argument("order_by_asc", 'false').lower() == "true"
             depth = int(self.get_argument("depth", 0))
             ignore = self.get_argument("ignore",None)
             include = self.get_argument("include",None)
             if ignore:
                 ignore = ignore.split(",")
             if include:
                 include = include.split(",")
             result = {"result": self.control.fetch(1,resource,id, 
                                                    attr=attr,
                                                    filter=filter,
                                                    match=match,
                                                    limit=limit, 
                                                    offset=offset,
                                                    order_by=order_by,
                                                    order_by_asc=order_by_asc,
                                                    depth=depth,
                                                    ignore=ignore,
                                                    include=include)}
         except Exception as ex:
             result = {"error": str(ex)}
             logging.exception(ex)
         self.set_header("Content-Type", "application/json; charset=UTF-8")
         self.write(dumps(result))
Ejemplo n.º 11
0
 def open(self):
     logging.info("WebSocket opened")
     user = self.control._begin_web_session(self.current_user, self,
                                           self.request.remote_ip,
                                           self.request.headers)
     if user:
         self.broadcast({
                         "signal":"user",
                         "message": user,
                         "ws_version": self.application.settings.get('ws_version',1),
                         "ws_config": self.application.settings.get("ws_config",{}),
                         "model": self.control._fc_description,
                         "methods": self.control._fc_methods,
                         })
     else:
         self.write_message(utils.dumps({'access_error':True}))
         self.close(reason="access control failure")
Ejemplo n.º 12
0
 def testName(self):
     with self.control.session as session:
         admin = session.query(model.User).get(1)
         foo = model.User(name="foo",_password="******")
         bar = model.User(name="bar",_password="******")
         session.add_all([foo,bar])
         session.flush()
         
         btgs = [model.Battleground(name="Garden of Terror"),
                 model.Battleground(name="Tomb of the Spider Queen")]
         session.add_all(btgs)
         
         lobby = model.Lobby(name="Foo's Lobby",
                             region=model.Lobby.REGION[0],
                             battleground=btgs[0])
         foo.lobbies.append(lobby)
         
         red = model.Team(name="Red")
         lobby.teams.append(red)
         blue = model.Team(name="Blue")
         lobby.teams.append(blue)
         
         red.members.append(foo)
         blue.members.append(bar)
         
         lobby = model.Lobby(name="Foo's other Lobby",
                             region=model.Lobby.REGION[1],
                             battleground=btgs[1])
         foo.lobbies.append(lobby)
         
         red = model.Team(name="Red")
         lobby.teams.append(red)
         blue = model.Team(name="Blue")
         lobby.teams.append(blue)
         
         red.members.append(foo)
         blue.members.append(bar)
         blue.members.append(admin)
         
         session.commit()
         
     print(dumps(self.control.get_lobby(1, 1),indent=2))
Ejemplo n.º 13
0
 def _write_attr_ref(self, value):
     self._attr_ref = utils.dumps(value)
Ejemplo n.º 14
0
 def get(self):    
     user = dumps(self.control._get_user(self.current_user))
     mode = 'debug' if self.application.settings.get("debug") == 'yes' else 'built'
     self.render(self.page, user=user, mode=mode)
Ejemplo n.º 15
0
 def _write_changed(self, value):
     self._changed = utils.dumps(value)
Ejemplo n.º 16
0
 def _write_data(self, value):
     self._data = utils.dumps(value)
Ejemplo n.º 17
0
    def create_version(cls, obj, session, action, mod_user_id=None):
        from sqlalchemy.orm import attributes, object_mapper
        from sqlalchemy.orm.exc import UnmappedColumnError
        from sqlalchemy.orm.properties import RelationshipProperty  # @UnresolvedImport
        
        obj_mapper = object_mapper(obj)
        obj_state = attributes.instance_state(obj)
    
        attr = {}
        changed = {}
    
        obj_changed = False

        if hasattr(obj.__class__, '_no_genoa_audit_'):
            return
            
        for om in obj_mapper.iterate_to_root():
            
            primary_keys = [pk.key for pk in om.local_table.primary_key]
            
            for obj_col in om.local_table.c:    
                # get the value of the
                # attribute based on the MapperProperty related to the
                # mapped column.  this will allow usage of MapperProperties
                # that have a different keyname than that of the mapped column.
                try:
                    prop = obj_mapper.get_property_by_column(obj_col)
                except UnmappedColumnError:
                    # in the case of single table inheritance, there may be 
                    # columns on the mapped table intended for the subclass only.
                    # the "unmapped" status of the subclass column on the 
                    # base class is a feature of the declarative module as of sqla 0.5.2.
                    continue

                if prop.key in primary_keys:
                    attr[prop.key] = getattr(obj, prop.key)
                else:
                    a, u, d = attributes.get_history(obj, prop.key, PASSIVE_NO_FETCH)
                    if d:
                        attr[obj_col.key] = d[0]
                        changed[prop.key] = getattr(obj, prop.key)
                        obj_changed = True
                    elif u:
                        attr[obj_col.key] = u[0]
                    elif a:
                        # if the attribute had no value.
                        attr[obj_col.key] = a[0]
                        changed[prop.key] = getattr(obj, prop.key)
                        obj_changed = True                
    
    
        primary_key = cls._get_instance_pk(obj, obj_mapper)
        if obj_changed is True or action=='deleted':
            hist = cls(action=action,
                       type=obj.__class__.__name__,
                       ref=utils.dumps(primary_key),
                       data=utils.dumps(attr),
                       changed=utils.dumps(changed),
                       mod_user_id=mod_user_id)
            session.add(hist)

        for prop in obj_mapper.iterate_properties:
            if isinstance(prop, RelationshipProperty) and \
                prop.direction == MANYTOMANY and \
                attributes.get_history(obj, prop.key).has_changes():
                a, u, d = attributes.get_history(obj, prop.key, PASSIVE_NO_FETCH)
                for item in a:
                    hist = cls(action='added',
                               type=obj.__class__.__name__,
                               ref=utils.dumps(primary_key),
                               attr=item.__class__.__name__,
                               attr_ref=utils.dumps(cls._get_instance_pk(item)),
                               mod_user_id=mod_user_id)
                    session.add(hist)
                for item in d:
                    hist = cls(action='removed',
                               type=obj.__class__.__name__,
                               ref=utils.dumps(primary_key),
                               attr=item.__class__.__name__,
                               attr_ref=utils.dumps(cls._get_instance_pk(item)),
                               mod_user_id=mod_user_id)
                    session.add(hist)
Ejemplo n.º 18
0
 def process_bind_param(self, value, dialect):
     if value is not None:
         value = dumps(value)
     return value
Ejemplo n.º 19
0
 def broadcast(self, message):
     self.write_message(utils.dumps(message))
     
Ejemplo n.º 20
0
 def broadcast(self, message):
     self.send(utils.dumps(message))
Ejemplo n.º 21
0
 def _after_flush(self, session, context):
     for item in session.new:
         if not isinstance(item, Audit):
             Audit.create_version(item, session, 'created', self.accl_key)
         else:
             self._audit_broadcast_.append(utils.dumps(item._serialize))