# Path: pyaiot/common/auth.py
# def verify_auth_token(token, keys):
#     """Verify the token is valid."""
#     return (Fernet(keys.private.encode()).decrypt(token.encode()) ==
#             keys.secret.encode())
# 
# Path: pyaiot/common/messaging.py
# class Message():
#     """Utility class for generating and parsing service messages."""
# 
#     @staticmethod
#     def serialize(message):
#         return json.dumps(message, ensure_ascii=False)
# 
#     @staticmethod
#     def new_node(uid, dst="all"):
#         """Generate a text message indicating a new node."""
#         return Message.serialize({'type': 'new', 'uid': uid, 'dst': dst})
# 
#     @staticmethod
#     def out_node(uid):
#         """Generate a text message indicating a node to remove."""
#         return Message.serialize({'type': 'out', 'uid': uid})
# 
#     @staticmethod
#     def reset_node(uid):
#         """Generate a text message indicating a node reset."""
#         return Message.serialize({'type': 'reset', 'uid': uid})
# 
#     @staticmethod
#     def update_node(uid, endpoint, data, dst="all"):
#         """Generate a text message indicating a node update."""
#         return Message.serialize({'type': 'update',
#                                   'uid': uid,
#                                   'endpoint': endpoint,
#                                   'data': data,
#                                   'dst': dst})
# 
#     @staticmethod
#     def gateway_alive():
#         """Generate a text message indicating that a gateway is alive."""
#         return Message.serialize({'type': 'update', 'uid': 'alive'})
# 
#     @staticmethod
#     def discover_node():
#         """Generate a text message for websocket node discovery."""
#         return Message.serialize({'request': 'discover'})
# 
#     @staticmethod
#     def check_message(raw):
#         """Verify a received message is correctly formatted."""
#         reason = None
#         try:
#             message = json.loads(raw)
#         except TypeError as exc:
#             logger.warning(exc)
#             reason = "Invalid message '{}'.".format(raw)
#             message = None
#         except json.JSONDecodeError:
#             reason = ("Invalid message received "
#                       "'{}'. Only JSON format is supported.".format(raw))
#             message = None
# 
#         if message is not None:
#             if not hasattr(message, '__iter__'):
#                 reason = "Invalid message '{}'.".format(message)
#             elif 'type' not in message and 'data' not in message:
#                 reason = "Invalid message '{}'.".format(message)
#             elif (message['type'] != 'new' and message['type'] != 'update' and
#                   message['type'] != 'out' and message['type'] != 'reset'):
#                 reason = "Invalid message type '{}'.".format(message['type'])
# 
#         if reason is not None:
#             logger.warning(reason)
#             message = None
# 
#         return message, reason


import uuid
import logging
from tornado import web, websocket
from pyaiot.common.auth import verify_auth_token
from pyaiot.common.messaging import Message
            if not message['uid'] in self.gateways[ws]:
                self.gateways[ws].append(message['uid'])

            if message['dst'] == "all":
                # Occurs when an unknown new node arrived
                self.broadcast(Message.serialize(message))
            elif message['dst'] in self.clients.keys():
                # Occurs when a single client has just connected
                self.send_to_client(
                    message['dst'], Message.serialize(message))
        elif (message['type'] == "out" and
              message['uid'] in self.gateways[ws]):
            # Node disparition are always broadcasted to clients
            self.gateways[ws].remove(message['uid'])
            self.broadcast(Message.serialize(message))
        elif message['type'] == "reset":
            # Occurs when a node has reset (reboot, firmware update):
            # require broadcast
            self.broadcast(Message.serialize(message))
        elif (message['type'] in "update" and
              message['uid'] in self.gateways[ws]):
            if message['dst'] == "all":
                # Occurs when a new update was pushed by a node:
                # require broadcast
                self.broadcast(Message.serialize(message))
            elif message['dst'] in self.clients.keys():
                # Occurs when a new client has just connected:
                # Only the cached information of a node are pushed to this
                # specific client
                self.send_to_client(

# Path: pyaiot/common/auth.py
# def verify_auth_token(token, keys):
#     """Verify the token is valid."""
#     return (Fernet(keys.private.encode()).decrypt(token.encode()) ==
#             keys.secret.encode())
# 
# Path: pyaiot/common/messaging.py
# class Message():
#     """Utility class for generating and parsing service messages."""
# 
#     @staticmethod
#     def serialize(message):
#         return json.dumps(message, ensure_ascii=False)
# 
#     @staticmethod
#     def new_node(uid, dst="all"):
#         """Generate a text message indicating a new node."""
#         return Message.serialize({'type': 'new', 'uid': uid, 'dst': dst})
# 
#     @staticmethod
#     def out_node(uid):
#         """Generate a text message indicating a node to remove."""
#         return Message.serialize({'type': 'out', 'uid': uid})
# 
#     @staticmethod
#     def reset_node(uid):
#         """Generate a text message indicating a node reset."""
#         return Message.serialize({'type': 'reset', 'uid': uid})
# 
#     @staticmethod
#     def update_node(uid, endpoint, data, dst="all"):
#         """Generate a text message indicating a node update."""
#         return Message.serialize({'type': 'update',
#                                   'uid': uid,
#                                   'endpoint': endpoint,
#                                   'data': data,
#                                   'dst': dst})
# 
#     @staticmethod
#     def gateway_alive():
#         """Generate a text message indicating that a gateway is alive."""
#         return Message.serialize({'type': 'update', 'uid': 'alive'})
# 
#     @staticmethod
#     def discover_node():
#         """Generate a text message for websocket node discovery."""
#         return Message.serialize({'request': 'discover'})
# 
#     @staticmethod
#     def check_message(raw):
#         """Verify a received message is correctly formatted."""
#         reason = None
#         try:
#             message = json.loads(raw)
#         except TypeError as exc:
#             logger.warning(exc)
#             reason = "Invalid message '{}'.".format(raw)
#             message = None
#         except json.JSONDecodeError:
#             reason = ("Invalid message received "
#                       "'{}'. Only JSON format is supported.".format(raw))
#             message = None
# 
#         if message is not None:
#             if not hasattr(message, '__iter__'):
#                 reason = "Invalid message '{}'.".format(message)
#             elif 'type' not in message and 'data' not in message:
#                 reason = "Invalid message '{}'.".format(message)
#             elif (message['type'] != 'new' and message['type'] != 'update' and
#                   message['type'] != 'out' and message['type'] != 'reset'):
#                 reason = "Invalid message type '{}'.".format(message['type'])
# 
#         if reason is not None:
#             logger.warning(reason)
#             message = None
# 
#         return message, reason


# Path: pyaiot/broker/broker.py
import uuid
import logging
from tornado import web, websocket
from pyaiot.common.auth import verify_auth_token
from pyaiot.common.messaging import Message

            if not message['uid'] in self.gateways[ws]:
                self.gateways[ws].append(message['uid'])

            if message['dst'] == "all":
                # Occurs when an unknown new node arrived
                self.broadcast(Message.serialize(message))
            elif message['dst'] in self.clients.keys():
                # Occurs when a single client has just connected
                self.send_to_client(
                    message['dst'], Message.serialize(message))
        elif (message['type'] == "out" and
              message['uid'] in self.gateways[ws]):
            # Node disparition are always broadcasted to clients
            self.gateways[ws].remove(message['uid'])
            self.broadcast(Message.serialize(message))
        elif message['type'] == "reset":
            # Occurs when a node has reset (reboot, firmware update):
            # require broadcast
            self.broadcast(Message.serialize(message))
        elif (message['type'] in "update" and
              message['uid'] in self.gateways[ws]):
            if message['dst'] == "all":
                # Occurs when a new update was pushed by a node:
                # require broadcast
                self.broadcast(Message.serialize(message))
            elif message['dst'] in self.clients.keys():
                # Occurs when a new client has just connected:
                # Only the cached information of a node are pushed to this
                # specific client
                self.send_to_client(

                    message['dst'], Message.serialize(message))