Esempio n. 1
0
 def __init__(self):
     self.spine = Spine()
     WebSocketServerProtocol.__init__(self)
     self.handlers = {"command": [], "query": [], "event": []}
     self.authenticated = False
     self.session = None
     self.user = None
     self._authorization = Authorization()
Esempio n. 2
0
 def __init__(self, log_queue):
     Controller.__init__(self, "message_manager", "Message handler")
     self.spine.register_command_handler("messageManagerSend", self.send_message)
     self._channels = {}
     self._authorization = Authorization()
     self._plugin_manager = PluginManager(Configuration, "messaging", [MessagePlugin], log_queue=log_queue)
     self._plugin_manager.load_managed_plugins()
     self._users = self._authorization.get_users()
     self.load()
Esempio n. 3
0
 def authorize(self, authorize_header):
     if authorize_header is None and not self.do_authorize():
         return True
     else:
         authstr = base64.b64decode(authorize_header[6:]).decode('utf-8')
         credentials = authstr.split(":")
         return Authorization.authorize(credentials[0], credentials[1])
Esempio n. 4
0
class MessageManager(Controller):
    def __init__(self):
        Controller.__init__(self, "message_manager", "Message handler")
        self.spine.register_command_handler("messageManagerSend",
                                            self.send_message)
        self._channels = {}
        self._authorization = Authorization()
        self._plugin_manager = None
        self._plugin_manager = PluginManager(Configuration, "messaging",
                                             [MessagePlugin])
        self._users = self._authorization.get_users()
        self.load()

    def load(self):

        self._plugin_manager.add_plugin(UserLogPlugin(Configuration, self))
        for plugin in self._plugin_manager.plugins:
            self._channels[plugin.message_type] = plugin

        self._config = Configuration.messaging
        self._levels = Configuration.log.levels

    def add_channel(self, channel_id, handler):
        self._channels[channel_id] = handler

    #@action
    def send_message(self, subject, **kwargs):
        message_channels = kwargs.pop("channels",
                                      self._config.default_channels)
        groups = kwargs.pop("user_groups", [])
        timestamp = (datetime.utcnow() - datetime(1970, 1, 1)).total_seconds()
        time = datetime.utcnow()
        kwargs = dict(kwargs, time=time, timestamp=timestamp)
        if not groups:
            users = self._users
        else:
            users = []
            for user in self._users:
                ingroup = any(i in groups for i in user.groups)
                if ingroup:
                    users += [user]
        #print("u", users, message_channels, self._channels.keys())
        if users:
            for message_channel in message_channels:

                if message_channel in self._channels.keys():
                    channel = self._channels[message_channel]
                    channel_users = []
                    if channel.address_based:
                        for user in users:
                            if user.addresses.get(message_channel, None):
                                channel_users.append(user)

                        if channel_users:
                            channel.send_message(channel_users, subject,
                                                 **kwargs)
                    else:
                        channel.send_message([], subject, **kwargs)
Esempio n. 5
0
 def __init__(self, addres, handler, camera, mutex):
     HTTPServer.__init__(self, addres, handler)
     self.camera = camera
     self.terminate = False
     self.mutex = mutex
     self.authorization = Authorization()
Esempio n. 6
0
class _SpineProtocol(WebSocketServerProtocol):
    def __init__(self):
        self.spine = Spine()
        WebSocketServerProtocol.__init__(self)
        self.handlers = {"command": [], "query": [], "event": []}
        self.authenticated = False
        self.session = None
        self.user = None
        self._authorization = Authorization()

    def add_command_handler(self, command):
        found = False
        for command_handler in self.handlers["command"]:
            if command_handler.command == command:
                found = True
        if not found:
            self.handlers["command"] += [_WebCommandHandler(command, self)]

    def add_query_handler(self, query):
        found = False
        for query_handler in self.handlers["query"]:
            if query_handler.query == query:
                found = True
        if not found:
            self.handlers["query"] += [_WebQueryHandler(query, self)]

    def add_event_handler(self, event, id_event):
        #print("ah", event, id_event)
        found = False
        for event_handler in self.handlers["event"]:
            if event_handler.event == event and event_handler.id_event == id_event:
                found = True
        if not found:
            self.handlers["event"] += [_WebEventHandler(event, id_event, self)]

    def send_response(self, id, response, state="ok", message=""):
        res = {
            "id": id,
            "messageType": "response",
            "state": state,
            "message": message,
            "response": response
        }
        jsonres = json.dumps(res, ensure_ascii=False).encode('utf8')
        self.sendMessage(jsonres, False)

    def onConnect(self, request):
        #print("Web socket Client connecting: {}".format(request.peer))
        pass

    def onOpen(self):
        if self._authorization.active:
            res = {"messageType": "authenticate"}
        else:
            self.authenticated = True
            res = {
                "messageType": "session_authenticated",
                "session": "123456",
            }
        jsonres = json.dumps(res, ensure_ascii=False).encode('utf8')
        self.sendMessage(jsonres, False)

    def onMessage(self, payload, is_binary):
        try:
            obj = json.loads(payload.decode('utf8'))

            if obj["messageType"] == "authenticate":
                session, user = self._authorization.authorize(
                    obj["userName"], obj["password"])

                if session is None:
                    print("authorization failed for:", obj["userName"])
                    res = {
                        "messageType": "authentication_failed",
                    }
                    #self.close()
                else:
                    self.session = session
                    self.user = user
                    self.authenticated = True
                    res = {
                        "messageType": "session_authenticated",
                        "session": session,
                    }
                jsonres = json.dumps(res, ensure_ascii=False).encode('utf8')
                self.sendMessage(jsonres, False)
            elif obj["messageType"] == "logoff":
                self.authenticated = False
                self.session = None
                self._authorization.remove_session(obj["session"])
                res = {"messageType": "session_logoff"}
                jsonres = json.dumps(res, ensure_ascii=False).encode('utf8')
                self.sendMessage(jsonres, False)
            else:
                self.spine.log.debug("WS onMessage:{0}", obj)
                if not self.authenticated:
                    pass
                elif obj["messageType"] == "query":
                    res = self.spine.send_query(obj["query"],
                                                *obj["args"],
                                                injected="socketSpine",
                                                session=self.user)
                    self.spine.log.debug("query response:{0}", res)
                    self.send_response(obj["id"], res)
                elif obj["messageType"] == "registerQueryHandler":
                    self.add_query_handler(obj["query"])
                    self.send_response(None, None)
                elif obj["messageType"] == "command":
                    self.spine.send_command(obj["command"],
                                            *obj["args"],
                                            injected="socketSpine",
                                            session=self.user)
                    self.send_response(obj["id"], None)
                elif obj["messageType"] == "registerCommandHandler":
                    self.add_command_handler(obj["command"])
                    self.send_response(obj["id"], None)
                elif obj["messageType"] == "event":
                    self.spine.trigger_event(obj["event"],
                                             obj["id"],
                                             obj["args"],
                                             injected="socketSpine")
                    self.send_response(obj["id"], None)
                elif obj["messageType"] == "registerEventHandler":
                    self.add_event_handler(obj["event"], obj["eventId"])
                    self.send_response(obj["id"], None)
        except:
            self.spine.log.exception("WS onMessage exception")
Esempio n. 7
0
class _SpineProtocol(WebSocketServerProtocol):
    loop = None
    def __init__(self):
        self.spine = Spine()
        WebSocketServerProtocol.__init__(self)
        self.handlers = {"command":[], "query":[], "event":[], "stream":[]}
        self.authenticated = False
        self.session = None
        self.user = None
        self._authorization = Authorization()

    @classmethod
    def broadcast_message(cls, connection, data, is_binary=False):
        #for c in set(cls.connections):
        cls.loop.call_soon_threadsafe(cls.sendMessage, connection, data, is_binary)
        

    def add_command_handler(self, command):
        found = False
        for command_handler in self.handlers["command"]:
            if command_handler.command == command:
                found = True
        if not found:
            self.handlers["command"] += [_WebCommandHandler(command, self)]

    def add_query_handler(self, query):
        found = False
        for query_handler in self.handlers["query"]:
            if query_handler.query == query:
                found = True
        if not found:
            self.handlers["query"] += [_WebQueryHandler(query, self)]

    def add_event_handler(self, event, id_event):
        found = False
        for event_handler in self.handlers["event"]:
            if event_handler.event == event and event_handler.id_event == id_event:
                found = True
        if not found:
            self.handlers["event"] += [_WebEventHandler(event, id_event, self)]

    def add_stream_handler(self, stream_id, stream_event):
        found = False
        for stream_handler in self.handlers["stream"]:
            if stream_handler.stream_id == stream_id:
                if stream_event and stream_handler.stream_event == stream_event:
                    found = True
                elif not stream_event:
                    found = True
        if not found:
            self.handlers["stream"] += [_WebStreamHandler(stream_id, stream_event, self)]
    
    def remove_stream_handler(self, stream_id, stream_event):
        #print("r", stream_id, stream_event)
        found_handler = None
        for stream_handler in self.handlers["stream"]:
            if stream_handler.stream_id == stream_id:
                if stream_event and stream_handler.stream_event == stream_event:
                    found_handler = stream_handler
                elif not stream_event:
                    found_handler = stream_handler
        if found_handler:
            found_handler.close()
            self.handlers["stream"].remove(found_handler)

    def send_response(self, id, response, state="ok", message=""):
        res = {
            "id":id,
            "messageType":"response",
            "state":state,
            "message":message,
            "response":response
        }
        jsonres = json.dumps(res, ensure_ascii=False).encode('utf8')
        self.sendMessage(jsonres, False)

    def onConnect(self, request):
        pass
    
    def onOpen(self):
        if self._authorization.active:
            res = {
                "messageType":"authenticate"
            }
        else:
            self.authenticated = True
            res = {
                "messageType":"session_authenticated",
                "session":"123456",
            }
        jsonres = json.dumps(res, ensure_ascii=False).encode('utf8')
        self.sendMessage(jsonres, False)
    
    # @asyncio.coroutine
    # def async_query(self, query, query_args, injected, session):
    #     def do_req():
    #         return self.spine.send_query(query, *query_args, injected=injected, session=session)
    #         #self.spine.log.debug("query response:{0}", res)
    #         #self.send_response(obj["id"], res)
    #         #return requests.get('https://api.github.com/user', auth=HTTPBasicAuth('user', 'pass'))
    #     req = self.loop.run_in_executor(None, do_req)
    #     resp = yield from req
    #     return resp
    def onMessage(self, payload, is_binary):
        try:
            obj = json.loads(payload.decode('utf8'))
            
            if obj["messageType"] == "authenticate":
                session, user = self._authorization.authorize(obj["userName"], obj["password"])
                
                if session is None:
                    if obj["userName"] == "anonymous":
                        self.spine.log.warning("Anonymous user disabled")
                    else:
                        self.spine.log.warning("authorization failed for: %s", obj["userName"])
                    res = {
                        "messageType":"authentication_failed",
                    }
                    #self.close()
                else:
                    self.session = session
                    self.user = user
                    self.authenticated = True
                    res = {
                        "messageType":"session_authenticated",
                        "session":session,
                    }
                jsonres = json.dumps(res, ensure_ascii=False).encode('utf8')
                self.sendMessage(jsonres, False)
            elif obj["messageType"] == "logoff":
                self.authenticated = False
                self.session = None
                self._authorization.remove_session(obj["session"])
                res = {
                    "messageType":"session_logoff"
                }
                jsonres = json.dumps(res, ensure_ascii=False).encode('utf8')
                self.sendMessage(jsonres, False)
            else:
                #self.spine.log.debug("WS onMessage:{0}", obj)
                if not self.authenticated:
                    pass
                elif obj["messageType"] == "query":
                    #res = yield from self.async_query(obj["query"], obj["args"], injected="socketSpine", session=self.user)
                    res = self.spine.send_query(obj["query"], *obj["args"], injected="socketSpine", session=self.user)
                    self.spine.log.debug("query response:{0}", res)
                    self.send_response(obj["id"], res)
                elif obj["messageType"] == "registerQueryHandler":
                    self.add_query_handler(obj["query"])
                    self.send_response(None, None)
                elif obj["messageType"] == "command":
                    self.spine.send_command(obj["command"], *obj["args"], injected="socketSpine", session=self.user)
                    self.send_response(obj["id"], None)
                elif obj["messageType"] == "registerCommandHandler":
                    self.add_command_handler(obj["command"])
                    self.send_response(obj["id"], None)
                elif obj["messageType"] == "event":
                    self.spine.trigger_event(
                        obj["event"], obj["id"],
                        obj["args"],
                        injected="socketSpine"
                    )
                    self.send_response(obj["id"], None)
                elif obj["messageType"] == "registerEventHandler":
                    self.add_event_handler(obj["event"], obj["eventId"])
                    self.send_response(obj["id"], None)
                elif obj["messageType"] == "registerStreamHandler":
                    self.add_stream_handler(obj["streamId"], obj["streamEvent"])
                    self.send_response(obj["id"], None)
                elif obj["messageType"] == "removeStreamHandler":
                    self.remove_stream_handler(obj["streamId"], obj["streamEvent"])
                    self.send_response(obj["id"], None)
        except:
            self.spine.log.exception("WS onMessage exception")