示例#1
0
 def on_connected(self, device: Device, ip, port):
     device.key = self.key
     device.custom_key = generate_key()
     device.write({
         "event_type": "assign",
         "encryption_key": device.custom_key.decode()
     })
示例#2
0
 def setUp(self):
     neo_config.load_config()
     neo_config.set_project_variables()
     self.neo = NeoAPI(neo_config)
     self.api = self.neo.activate_testing()
     self.client = SocketIOTestClient(self.neo.app, socketio)
     self.client.disconnect()
     self.user1 = db.session.query(UserModel).filter(UserModel.email == "*****@*****.**").first()
     if self.user1 is None:
         self.user1 = UserModel(email="*****@*****.**", password="******", first_name="firstname",
                                last_name="lastname", birthday="1995-12-12")
     self.user2 = db.session.query(UserModel).filter(UserModel.email == "*****@*****.**").first()
     if self.user2 is None:
         self.user2 = UserModel(email="*****@*****.**", password="******", first_name="firstname",
                                last_name="lastname", birthday="1995-12-12")
     self.circle = Circle(name="Mamie")
     self.linkCircle = UserToCircle(user=self.user1, circle=self.circle, privilege="ADMIN")
     self.conversation = Conversation("test", device_access=True)
     self.conversation.device_access = True
     self.conversation.circle = self.circle
     self.link2 = UserToConversation(user=self.user2, conversation=self.conversation)
     self.device = Device(name="Papie")
     self.device.circle = self.circle
     self.device_password = self.device.get_pre_activation_password()
     self.device.activate(self.device.key)
     db.session.commit()
     self.circle_id = self.circle.id
     self.conversation_id = self.conversation.id
     self.token1 = authenticate_user(self.api, self.user1, "test")
     self.token2 = authenticate_user(self.api, self.user2, "test")
     self.device_token = authenticate_device(self.api, self.device, self.device_password)
     self.tokenAdmin = authenticate_user(self.api, "*****@*****.**", "PapieNeo2019")
示例#3
0
    def on_message(self, device: Device, message: bytes) -> dict:
        if validate_token(message):
            self.logger.encrypted_message("Received bytes: {}".format(message))
            message = decrypt(message, device.key)
            self.logger.message("Received decrypted: {}".format(message))

            try:
                message = json.loads(message, cls=MessageDecoder)
            except json.JSONDecodeError as e:
                self.logger.error("Failed to decode message {}: {}".format(
                    message, e))
                raise Exception("Failed to decode message")

            if device.is_verified():
                return message
            else:
                if message.get("event_type") == "assign":
                    if str(message.get(
                            "encryption_key")).encode() == device.custom_key:
                        device.key = device.custom_key
                        device.set_verified(True)
                        self.connected.emit(device, device.ip(), device.port())
                        self.logger.info("Device {} validated".format(
                            device.id()))
                    else:
                        self.logger.warning(
                            "Assigned keys do not match! Bot {} will be kicked!"
                            .format(device.id()))
                        device.kick()
        else:
            self.decryption_error.emit(device, message)
            raise Exception("Message is not valid")
        return {}
示例#4
0
def getDevicesByGroup(db_controller, lm_group_id, lm_filter=''):
    '''GetDevicesByGroup pulls all devices in a specific group.  Devices must be located within the group and not
    nested in another group.'''
    print("Getting Devices")
    lm_resourcePath = f'/device/groups/{lm_group_id}/devices'  #LM API URI
    lm_fields = '?fields=systemProperties,customProperties'  #LM Filter
    data = lm_request(lm_resourcePath,
                      lm_filter=lm_filter,
                      lm_fields=lm_fields)  #Calls LM API Request
    devices = []
    for items in data['items']:
        device = Device()
        system_properties = items[
            'systemProperties']  #Pulling data from SystemProperties
        for properties in system_properties:
            if 'system.deviceId' in properties.values():
                device.device_id = properties['value'][0:24]
            if 'system.ips' in properties.values():
                device.device_ip = properties['value'][0:499]
            if 'system.displayname' in properties.values():
                device.device_name = properties['value'][0:99]
        if not db_controller.check_if_row_exists(row=device):
            devices.append(device)
    if len(devices) > 0:
        db_controller.add_many(data=devices)
    else:  #If devices = 0, that means there are no new devices
        db_controller.update_log(name="GetDevices",
                                 log_type="Info",
                                 code="300",
                                 desc="No New Devices Found")
        db_controller.session.commit()
示例#5
0
class TestDeviceLogout(unittest.TestCase):
    def setUp(self):
        neo_config.load_config()
        neo_config.set_project_variables()
        neo = NeoAPI(neo_config)
        self.api = neo.activate_testing()
        self.user1 = db.session.query(UserModel).filter(
            UserModel.email == "*****@*****.**").first()
        if self.user1 is None:
            self.user1 = UserModel(email="*****@*****.**",
                                   password="******",
                                   first_name="firstname",
                                   last_name="lastname",
                                   birthday="1995-12-12")
        self.user2 = db.session.query(UserModel).filter(
            UserModel.email == "*****@*****.**").first()
        if self.user2 is None:
            self.user2 = UserModel(email="*****@*****.**",
                                   password="******",
                                   first_name="firstname",
                                   last_name="lastname",
                                   birthday="1111-11-11")
        self.circle = Circle(name="Mamie")
        self.linkCircle = UserToCircle(user=self.user1,
                                       circle=self.circle,
                                       privilege="ADMIN")
        self.linkCircle2 = UserToCircle(user=self.user2, circle=self.circle)
        self.device = Device(name="Papie")
        self.device.circle = self.circle
        self.device_password = self.device.get_pre_activation_password()
        self.device.activate(self.device.key)
        db.session.commit()
        self.token1 = authenticate_user(self.api, self.user1, "test")
        self.token2 = authenticate_user(self.api, self.user2, "test")
        self.device_token = authenticate_device(self.api, self.device,
                                                self.device_password)
        self.tokenAdmin = authenticate_user(self.api,
                                            "*****@*****.**",
                                            "PapieNeo2019")

    def test_valid_logout(self):
        json_data = {"device_token": self.device_token}
        response = self.api.post('/device/logout',
                                 data=json.dumps(json_data),
                                 content_type='application/json')
        response_json = json.loads(response.data)
        assert response.status_code == 200
        assert response_json['success']

    def test_missing_parameter(self):
        json_data = {}
        response = self.api.post('/device/logout',
                                 data=json.dumps(json_data),
                                 content_type='application/json')
        response_json = json.loads(response.data)
        assert response.status_code != 200
        assert not response_json['success']
 def setUp(self):
     neo_config.load_config()
     neo_config.set_project_variables()
     neo = NeoAPI(neo_config)
     self.api = neo.activate_testing()
     self.user1 = db.session.query(UserModel).filter(
         UserModel.email == "*****@*****.**").first()
     if self.user1 is None:
         self.user1 = UserModel(email="*****@*****.**",
                                password="******",
                                first_name="firstname",
                                last_name="lastname",
                                birthday="1995-12-12")
     self.user2 = db.session.query(UserModel).filter(
         UserModel.email == "*****@*****.**").first()
     if self.user2 is None:
         self.user2 = UserModel(email="*****@*****.**",
                                password="******",
                                first_name="firstname",
                                last_name="lastname",
                                birthday="1111-11-11")
     self.circle = Circle(name="Mamie")
     self.circle2 = Circle(name="test")
     self.linkCircle = UserToCircle(user=self.user1,
                                    circle=self.circle,
                                    privilege="ADMIN")
     self.linkCircle2 = UserToCircle(user=self.user2, circle=self.circle)
     self.conversation = Conversation("test")
     self.conversation.circle = self.circle
     self.conversation.device_access = True
     self.device = Device(name="Papie")
     self.device2 = Device(name="test")
     self.device2.circle = self.circle2
     self.device2_password = self.device2.get_pre_activation_password()
     self.device2.activate(self.device2.key)
     self.device.circle = self.circle
     self.device_password = self.device.get_pre_activation_password()
     self.device.activate(self.device.key)
     self.message = Message(is_user=False)
     self.message.conversation = self.conversation
     self.message.device = self.device
     db.session.commit()
     self.token1 = authenticate_user(self.api, self.user1, "test")
     self.token2 = authenticate_user(self.api, self.user2, "test")
     self.device_token = authenticate_device(self.api, self.device,
                                             self.device_password)
     self.device2_token = authenticate_device(self.api, self.device2,
                                              self.device2_password)
     self.tokenAdmin = authenticate_user(self.api,
                                         "*****@*****.**",
                                         "PapieNeo2019")
示例#7
0
 def func_wrapper(*args, **kwargs):
     try:
         content = request.get_json()
         if "device_token" in content and content[
                 "device_token"] != "" or "neo_device_token" in request.cookies:
             if "device_token" in content:
                 json_token = content["device_token"]
             else:
                 json_token = request.cookies.get("neo_device_token")
             res, data = Device.decode_auth_token_old(json_token)
             if res is True:
                 kwargs['device'] = data
                 return func(*args, **kwargs)
             else:
                 resp = jsonify({"success": False, "message": data})
                 resp.status_code = 401
                 return resp
         else:
             resp = jsonify({
                 "success":
                 False,
                 "message":
                 "Aucun jwt trouvé dans le contenu de la requete"
             })
             return resp
     except Exception as e:
         resp = jsonify({"success": False, "message": str(e)})
         resp.status_code = 500
         return resp
示例#8
0
 def setUp(self):
     neo_config.load_config()
     neo_config.set_project_variables()
     neo = NeoAPI(neo_config)
     self.api = neo.activate_testing()
     self.user1 = db.session.query(UserModel).filter(
         UserModel.email == "*****@*****.**").first()
     if self.user1 is None:
         self.user1 = UserModel(email="*****@*****.**",
                                password="******",
                                first_name="firstname",
                                last_name="lastname",
                                birthday="1995-12-12")
     self.user2 = db.session.query(UserModel).filter(
         UserModel.email == "*****@*****.**").first()
     if self.user2 is None:
         self.user2 = UserModel(email="*****@*****.**",
                                password="******",
                                first_name="firstname",
                                last_name="lastname",
                                birthday="1111-11-11")
     self.circle = Circle(name="Mamie")
     self.linkCircle = UserToCircle(user=self.user1,
                                    circle=self.circle,
                                    privilege="ADMIN")
     self.linkCircle2 = UserToCircle(user=self.user2, circle=self.circle)
     self.device = Device(name="Papie")
     self.device.circle = self.circle
     db.session.commit()
     self.token1 = authenticate_user(self.api, self.user1, "test")
     self.token2 = authenticate_user(self.api, self.user2, "test")
     self.tokenAdmin = authenticate_user(self.api,
                                         "*****@*****.**",
                                         "PapieNeo2019")
示例#9
0
 def func_wrapper(*args, **kwargs):
     content = json.loads(request.data)
     if "token" in content and content[
             "token"] != "" or "neo_user_token" in request.cookies:
         if "token" in content:
             json_token = content["token"]
         else:
             json_token = request.cookies.get("neo_user_token")
         client = User.decode_auth_token(json_token)
         if client.type != account_type and account_type == "ADMIN":
             raise InsufficientAccountRight
         kwargs['client'] = client
         kwargs["is_device"] = False
         return func(*args, **kwargs)
     if "device_token" in content and content[
             "device_token"] != "" or "neo_device_token" in request.cookies:
         if "device_token" in content:
             json_token = content["device_token"]
         else:
             json_token = request.cookies.get("neo_device_token")
         client = Device.decode_auth_token(json_token)
         kwargs['client'] = client
         kwargs["is_device"] = True
         return func(*args, **kwargs)
     raise TokenNotFound
示例#10
0
def get_device_from_header(request):
    token = request.headers.get('Authorization')
    if token is None or token == "":
        raise Exception("Authorization token not found")
    res, data = Device.decode_auth_token_old(token)
    if res is True:
        return data
    raise InvalidAuthentication(data)
示例#11
0
    def get(self):
        transactions = {}
        devices = Device.get_all()
        for device in devices:
            transactions.update({device.name: convert_timestamps_to_dates(Transaction.get_all(device))})

        values = {
            "transactions": transactions
        }

        self.response.write(main.render("templates/borrowTable.html", values))
示例#12
0
def fake_pay(content, circle_id, user):
    logger.info("[%s] [%s] [%s] [%s] [%s]",
                request.method, request.host, request.path, request.content_type, request.data)
    try:
        circle = db.session.query(Circle).filter(Circle.id == circle_id).first()
        if circle is not None:
            if not circle.has_member(user):
                return FAILED("Cet utilisateur ne fait pas parti du cercle spécifié")
            link = db.session.query(UserToCircle).filter(UserToCircle.circle_id == circle.id,
                                                         UserToCircle.user_id == user.id).first()
            if link is None:
                return FAILED("Cet utilisateur ne fait pas parti du cercle spécifié")
            link.privilege = "ADMIN"
            device = Device(name=content["device_name"] if "device_name" in content else "Papi/Mamie")
            circle.device = device
            device.circle = circle
            db.session.commit()
            return jsonify({"success": True, "content": device.get_content()})
        return FAILED("Cercle spécifié introuvable")
    except Exception as e:
        return FAILED(e)
示例#13
0
def admin_add(content, circle_id, name):
    try:
        circle = db.session.query(Circle).filter(
            Circle.id == circle_id).first()
        if circle is None:
            raise e_circle.CircleNotFound
        new_device = Device(
            name=name,
            username=content["username"] if "username" in content else None)
        new_device.circle = circle
        db.session.commit()
        circle.notify_users('device created')
        response = {"data": {"success": True}, "status_code": 200}
    except e_circle.CircleException as exception:
        response = {
            "data": {
                "success": False,
                "message": exception.message
            },
            "status_code": exception.status_code
        }
    return response
示例#14
0
 def func_wrapper(*args, **kwargs):
     try:
         content = json.loads(request.data)
         if content is None:
             raise JsonNotFound
         for elem in definer:
             if elem is not None:
                 if elem[2] and elem[0] not in content:
                     raise JsonParameterNotFound(elem[0])
                 if elem[0] in content and type(
                         content[elem[0]]) is not type(elem[1]):
                     raise JsonParameterFormatError(elem[0], type(elem[1]))
         if secured is not None:
             if "token" in content and content[
                     "token"] != "" or "neo_user_token" in request.cookies:
                 if "token" in content:
                     json_token = content["token"]
                 else:
                     json_token = request.cookies.get("neo_user_token")
                 client = User.decode_auth_token(json_token)
                 if client.type != secured and secured == "ADMIN":
                     raise InsufficientAccountRight
                 kwargs['client'] = client
                 kwargs["is_device"] = False
             if "device_token" in content and content[
                     "device_token"] != "" or "neo_device_token" in request.cookies:
                 if "device_token" in content:
                     json_token = content["device_token"]
                 else:
                     json_token = request.cookies.get("neo_device_token")
                 client = Device.decode_auth_token(json_token)
                 kwargs['client'] = client
                 kwargs["is_device"] = True
         kwargs['content'] = content
         return func(*args, **kwargs)
     except ContentException:
         response = jsonify({
             "success": False,
             "message": ContentException.message
         })
         response.status_code = ContentException.status_code
         return response
     except json.decoder.JSONDecodeError:
         response = jsonify({
             "success": False,
             "message": JsonUnreadable.message
         })
         response.status_code = JsonUnreadable.status_code
         return response
示例#15
0
def logout(device_token):
    try:
        device = Device.decode_auth_token(device_token)
        device.circle.notify_users(p2={
            'event': 'device',
            'type': 'disconnect',
            'device_id': device.id
        })
        response = {"data": {"success": True}, "status_code": 200}
    except e_device.DeviceException as exception:
        response = {
            "data": {
                "success": False,
                "message": exception.message
            },
            "status_code": exception.status_code
        }
    return response
示例#16
0
 def func_wrapper(*args, **kwargs):
     token = None
     if "Authorization" in request.headers:
         try:
             user = get_user_from_header(request)
             kwargs["client"] = user
             kwargs["is_device"] = False
             return func(*args, **kwargs)
         except InvalidAuthentication:
             try:
                 device = get_device_from_header(request)
                 kwargs["client"] = device
                 kwargs["is_device"] = True
                 return func(*args, **kwargs)
             except InvalidAuthentication as ie:
                 resp = jsonify({"success": False, "message": str(ie)})
                 resp.status_code = 500
                 return resp
     if token is None or token == "":
         if "neo_user_token" in request.cookies:
             token = request.headers.get("neo_user_token")
             res, data = User.decode_auth_token_old(token)
             if res is True:
                 kwargs['client'] = data
                 kwargs["is_device"] = False
                 return func(*args, **kwargs)
             else:
                 resp = jsonify({"success": False, "message": data})
                 resp.status_code = 401
                 return resp
         if "neo_device_token" in request.cookies:
             token = request.headers.get("neo_device_token")
             res, data = Device.decode_auth_token_old(token)
             if res is True:
                 kwargs['client'] = data
                 kwargs["is_device"] = True
                 return func(*args, **kwargs)
             else:
                 resp = jsonify({"success": False, "message": data})
                 resp.status_code = 401
                 return resp
     resp = jsonify({"success": False, "message": "Token introuvable"})
     return resp
示例#17
0
    def post(self):
        if not self.request.get("device"):
            return

        device_name = escape(self.request.get("device"))
        device = Device.query(Device.name == device_name).get()

        if self.request.get("borrower"):
            Transaction(parent=device.key, name=escape(self.request.get("borrower")), start=now()).put()
            self.response.write("Created.")

        elif self.request.get("update"):
            last = Transaction.get_last(device)
            last.end = now()
            last.put()
            self.response.write(last.name)

        else:
            Device(name=device_name).put()
            self.response.write("Created.")
示例#18
0
 def authenticate(self, jwt_token):
     try:
         if self.authenticated is True:
             return False, "Already authenticated"
         b, client = User.decode_auth_token_old(jwt_token)
         if not b:
             b, client = Device.decode_auth_token_old(jwt_token)
             if b:
                 self.is_device = True
         if not b or client is None:
             return False, 'User not found'
         if client.json_token != jwt_token:
             return False, 'Invalid token'
         self.token = jwt_token
         self.client_id = client.id
         client.update_content(is_online=True)
         self.authenticated = True
         return True, 'User authenticated'
     except Exception as e:
         return False, str(e)
示例#19
0
    def get(self):
        if not self.request.get("device"):
            return

        device = Device.get_by_name(escape(self.request.get("device")))
        self.response.write(serialize(Transaction.get_all(device)))
示例#20
0
class SocketioMessageEvents(unittest.TestCase):
    def setUp(self):
        neo_config.load_config()
        neo_config.set_project_variables()
        self.neo = NeoAPI(neo_config)
        self.api = self.neo.activate_testing()
        self.client = SocketIOTestClient(self.neo.app, socketio)
        self.client2 = SocketIOTestClient(self.neo.app, socketio)
        self.deviceClient = SocketIOTestClient(self.neo.app, socketio)
        self.client.disconnect()
        self.client2.disconnect()
        self.deviceClient.disconnect()
        self.user1 = db.session.query(UserModel).filter(
            UserModel.email == "*****@*****.**").first()
        if self.user1 is None:
            self.user1 = UserModel(email="*****@*****.**",
                                   password="******",
                                   first_name="firstname",
                                   last_name="lastname",
                                   birthday="1995-12-12")
        self.user2 = db.session.query(UserModel).filter(
            UserModel.email == "*****@*****.**").first()
        if self.user2 is None:
            self.user2 = UserModel(email="*****@*****.**",
                                   password="******",
                                   first_name="firstname",
                                   last_name="lastname",
                                   birthday="1995-12-12")
        self.circle = Circle(name="Mamie")
        self.linkCircle = UserToCircle(user=self.user1,
                                       circle=self.circle,
                                       privilege="ADMIN")
        self.linkCircle2 = UserToCircle(user=self.user2, circle=self.circle)
        self.conversation = Conversation("test")
        self.conversation.device_access = True
        self.conversation.circle = self.circle
        self.link = UserToConversation(user=self.user1,
                                       conversation=self.conversation,
                                       privilege='ADMIN')
        self.link2 = UserToConversation(user=self.user2,
                                        conversation=self.conversation)
        self.device = Device(name="Papie")
        self.device.circle = self.circle
        self.device_password = self.device.get_pre_activation_password()
        self.device.activate(self.device.key)
        db.session.commit()
        self.circle_id = self.circle.id
        self.conversation_id = self.conversation.id
        self.token1 = authenticate_user(self.api, self.user1, "test")
        self.token2 = authenticate_user(self.api, self.user2, "test")
        self.device_token = authenticate_device(self.api, self.device,
                                                self.device_password)
        self.tokenAdmin = authenticate_user(self.api,
                                            "*****@*****.**",
                                            "PapieNeo2019")

    def tearDown(self):
        self.client.disconnect()
        self.client2.disconnect()
        self.deviceClient.disconnect()

    def test_valid_message(self):
        data = {'token': self.token1}
        assert len(sockets) == 0
        self.client.connect()
        self.client2.connect()
        self.deviceClient.connect()
        self.client.emit('authenticate', data, json=True)
        self.client2.emit('authenticate', {'token': self.token2}, json=True)
        self.deviceClient.emit('authenticate', {'token': self.device_token},
                               json=True)
        res1 = self.client.get_received()
        res2 = self.client2.get_received()
        res3 = self.deviceClient.get_received()
        assert len(res1) == 1
        assert res1[0]['name'] == 'success'
        assert len(res2) == 1
        assert res2[0]['name'] == 'success'
        assert len(res3) == 1
        assert res3[0]['name'] == 'success'
        self.client.emit('join_conversation',
                         {'conversation_id': self.conversation_id},
                         json=True)
        self.client2.emit('join_conversation',
                          {'conversation_id': self.conversation_id},
                          json=True)
        self.deviceClient.emit('join_conversation',
                               {'conversation_id': self.conversation_id},
                               json=True)
        res1 = self.client.get_received()
        res2 = self.client2.get_received()
        res3 = self.deviceClient.get_received()
        assert len(res1) == 1
        assert res1[0]['name'] == 'success'
        assert len(res2) == 1
        assert res2[0]['name'] == 'success'
        assert len(res3) == 1
        assert res3[0]['name'] == 'success'
        sock = {
            'conversation_id': self.conversation_id,
            'text_message': 'test web socket'
        }
        self.client.emit('message', sock, json=True)
        err = self.client.get_received()
        res = self.client2.get_received()
        res2 = self.deviceClient.get_received()
        assert len(err) == 2
        assert len(res) == 1
        assert len(res2) == 1
        self.client.disconnect()
        self.client2.disconnect()
        self.deviceClient.disconnect()

    def test_valid_message_from_device(self):
        data = {'token': self.token1}
        assert len(sockets) == 0
        self.client.connect()
        self.client2.connect()
        self.deviceClient.connect()
        self.client.emit('authenticate', data, json=True)
        self.client2.emit('authenticate', {'token': self.token2}, json=True)
        self.deviceClient.emit('authenticate', {'token': self.device_token},
                               json=True)
        res1 = self.client.get_received()
        res2 = self.client2.get_received()
        res3 = self.deviceClient.get_received()
        assert len(res1) == 1
        assert res1[0]['name'] == 'success'
        assert len(res2) == 1
        assert res2[0]['name'] == 'success'
        assert len(res3) == 1
        assert res3[0]['name'] == 'success'
        self.client.emit('join_conversation',
                         {'conversation_id': self.conversation_id},
                         json=True)
        self.client2.emit('join_conversation',
                          {'conversation_id': self.conversation_id},
                          json=True)
        self.deviceClient.emit('join_conversation',
                               {'conversation_id': self.conversation_id},
                               json=True)
        res1 = self.client.get_received()
        res2 = self.client2.get_received()
        res3 = self.deviceClient.get_received()
        assert len(res1) == 1
        assert res1[0]['name'] == 'success'
        assert len(res2) == 1
        assert res2[0]['name'] == 'success'
        assert len(res3) == 1
        assert res3[0]['name'] == 'success'
        sock = {
            'conversation_id': self.conversation_id,
            'text_message': 'test web socket'
        }
        self.deviceClient.emit('message', sock, json=True)
        err = self.client.get_received()
        res = self.client2.get_received()
        res2 = self.deviceClient.get_received()
        assert len(err) == 1
        assert len(res) == 1
        assert len(res2) == 2

    def test_notif_on_conversation(self):
        data = {'token': self.token1}
        assert len(sockets) == 0
        self.client.connect()
        self.client2.connect()
        self.deviceClient.connect()
        self.client.emit('authenticate', data, json=True)
        self.client2.emit('authenticate', {'token': self.token2}, json=True)
        self.deviceClient.emit('authenticate', {'token': self.device_token},
                               json=True)
        res1 = self.client.get_received()
        res2 = self.client2.get_received()
        res3 = self.deviceClient.get_received()
        assert len(res1) == 1
        assert res1[0]['name'] == 'success'
        assert len(res2) == 1
        assert res2[0]['name'] == 'success'
        assert len(res3) == 1
        assert res3[0]['name'] == 'success'
        self.client.emit('join_conversation',
                         {'conversation_id': self.conversation_id},
                         json=True)
        self.client2.emit('join_conversation',
                          {'conversation_id': self.conversation_id},
                          json=True)
        self.deviceClient.emit('join_conversation',
                               {'conversation_id': self.conversation_id},
                               json=True)
        res1 = self.client.get_received()
        res2 = self.client2.get_received()
        res3 = self.deviceClient.get_received()
        assert len(res1) == 1
        assert res1[0]['name'] == 'success'
        assert len(res2) == 1
        assert res2[0]['name'] == 'success'
        assert len(res3) == 1
        assert res3[0]['name'] == 'success'
        json_data = {
            'token': self.token1,
            'conversation_id': self.conversation_id,
            'text_message': 'test web socket'
        }
        self.api.post('/message/send',
                      data=json.dumps(json_data),
                      content_type='application/json')
        err = self.client.get_received()
        res = self.client2.get_received()
        res2 = self.deviceClient.get_received()
        assert len(err) == 1
        assert len(res) == 1
        assert len(res2) == 1
        self.client.disconnect()
        self.client2.disconnect()
        self.deviceClient.disconnect()
示例#21
0
class SocketioWebrtcEvents(unittest.TestCase):
    def setUp(self):
        neo_config.load_config()
        neo_config.set_project_variables()
        self.neo = NeoAPI(neo_config)
        self.api = self.neo.activate_testing()
        self.client = SocketIOTestClient(self.neo.app, socketio)
        self.client2 = SocketIOTestClient(self.neo.app, socketio)
        self.deviceClient = SocketIOTestClient(self.neo.app, socketio)
        self.client.disconnect()
        self.client2.disconnect()
        self.deviceClient.disconnect()
        self.user1 = db.session.query(UserModel).filter(
            UserModel.email == "*****@*****.**").first()
        if self.user1 is None:
            self.user1 = UserModel(email="*****@*****.**",
                                   password="******",
                                   first_name="firstname",
                                   last_name="lastname",
                                   birthday="1995-12-12")
        self.user2 = db.session.query(UserModel).filter(
            UserModel.email == "*****@*****.**").first()
        if self.user2 is None:
            self.user2 = UserModel(email="*****@*****.**",
                                   password="******",
                                   first_name="firstname",
                                   last_name="lastname",
                                   birthday="1995-12-12")
        self.email = self.user2.email
        self.circle = Circle(name="Mamie")
        self.linkCircle = UserToCircle(user=self.user1,
                                       circle=self.circle,
                                       privilege="ADMIN")
        self.linkCircle2 = UserToCircle(user=self.user2, circle=self.circle)
        self.conversation = Conversation("test")
        self.conversation.device_access = True
        self.conversation.circle = self.circle
        self.link = UserToConversation(user=self.user1,
                                       conversation=self.conversation,
                                       privilege='ADMIN')
        self.link2 = UserToConversation(user=self.user2,
                                        conversation=self.conversation)
        self.device = Device(name="Papie")
        self.device.circle = self.circle
        self.device_password = self.device.get_pre_activation_password()
        self.device.activate(self.device.key)
        db.session.commit()
        self.circle_id = self.circle.id
        self.conversation_id = self.conversation.id
        self.token1 = authenticate_user(self.api, self.user1, "test")
        self.token2 = authenticate_user(self.api, self.user2, "test")
        self.device_token = authenticate_device(self.api, self.device,
                                                self.device_password)
        self.tokenAdmin = authenticate_user(self.api,
                                            "*****@*****.**",
                                            "PapieNeo2019")

    def tearDown(self):
        self.client.disconnect()
        self.client2.disconnect()
        self.deviceClient.disconnect()

    def test_valid_message(self):
        data = {'token': self.token1}
        assert len(sockets) == 0
        self.client.connect()
        self.client2.connect()
        self.deviceClient.connect()
        self.client.emit('authenticate', data, json=True)
        self.client2.emit('authenticate', {'token': self.token2}, json=True)
        self.deviceClient.emit('authenticate', {'token': self.device_token},
                               json=True)
        res1 = self.client.get_received()
        res2 = self.client2.get_received()
        res3 = self.deviceClient.get_received()
        assert len(res1) == 1
        assert res1[0]['name'] == 'success'
        assert len(res2) == 1
        assert res2[0]['name'] == 'success'
        assert len(res3) == 1
        assert res3[0]['name'] == 'success'
        self.client.emit('webrtc_credentials')
        res1 = self.client.get_received()
        assert len(res1) == 1

    def test_valid_forward(self):
        assert len(sockets) == 0
        self.client.connect()
        self.client2.connect()
        self.client.emit('authenticate', {'token': self.token1}, json=True)
        self.client2.emit('authenticate', {'token': self.token2}, json=True)
        res1 = self.client.get_received()
        res2 = self.client2.get_received()
        assert len(res1) == 1
        assert res1[0]['name'] == 'success'
        assert len(res2) == 1
        assert res2[0]['name'] == 'success'
        self.client.emit('webrtc_forward', {'email': self.email})
        res1 = self.client.get_received()
        res2 = self.client2.get_received()
        assert len(res1) == 1
        assert len(res2) == 1
def control(pino):
    status = 1 if len(request.form) > 1 else 0
    dev = Device(pino, status)
    response = {'response': 200, 'pino': pino, 'status': status}
    return response
示例#23
0
class SocketioRoomConversation(unittest.TestCase):
    def setUp(self):
        neo_config.load_config()
        neo_config.set_project_variables()
        self.neo = NeoAPI(neo_config)
        self.api = self.neo.activate_testing()
        self.client = SocketIOTestClient(self.neo.app, socketio)
        self.client.disconnect()
        self.user1 = db.session.query(UserModel).filter(UserModel.email == "*****@*****.**").first()
        if self.user1 is None:
            self.user1 = UserModel(email="*****@*****.**", password="******", first_name="firstname",
                                   last_name="lastname", birthday="1995-12-12")
        self.user2 = db.session.query(UserModel).filter(UserModel.email == "*****@*****.**").first()
        if self.user2 is None:
            self.user2 = UserModel(email="*****@*****.**", password="******", first_name="firstname",
                                   last_name="lastname", birthday="1995-12-12")
        self.circle = Circle(name="Mamie")
        self.linkCircle = UserToCircle(user=self.user1, circle=self.circle, privilege="ADMIN")
        self.conversation = Conversation("test", device_access=True)
        self.conversation.device_access = True
        self.conversation.circle = self.circle
        self.link2 = UserToConversation(user=self.user2, conversation=self.conversation)
        self.device = Device(name="Papie")
        self.device.circle = self.circle
        self.device_password = self.device.get_pre_activation_password()
        self.device.activate(self.device.key)
        db.session.commit()
        self.circle_id = self.circle.id
        self.conversation_id = self.conversation.id
        self.token1 = authenticate_user(self.api, self.user1, "test")
        self.token2 = authenticate_user(self.api, self.user2, "test")
        self.device_token = authenticate_device(self.api, self.device, self.device_password)
        self.tokenAdmin = authenticate_user(self.api, "*****@*****.**", "PapieNeo2019")

    def tearDown(self):
        self.client.disconnect()

    def test_invalid_join_conversation(self):
        data = {
            'token': self.token1
        }
        assert len(sockets) == 0
        self.client.connect()
        self.client.emit('authenticate', data, json=True)
        res = self.client.get_received()
        assert len(res) == 1
        assert res[0]['name'] == 'success'
        data = {
            'conversation_id': self.conversation_id
        }
        self.client.emit('join_conversation', data, json=True)
        res = self.client.get_received()
        assert len(res) == 1
        assert res[0]['name'] == 'error'

    def test_valid_join_conversation(self):
        data = {
            'token': self.token2
        }
        assert len(sockets) == 0
        self.client.connect()
        self.client.emit('authenticate', data, json=True)
        res = self.client.get_received()
        assert len(res) == 1
        assert res[0]['name'] == 'success'
        data = {
            'conversation_id': self.conversation_id
        }
        self.client.emit('join_conversation', data, json=True)
        res = self.client.get_received()
        assert len(res) == 1
        assert res[0]['name'] == 'success'

    def test_valid_device_join_conversation(self):
        data = {
            'token': self.device_token
        }
        assert len(sockets) == 0
        self.client.connect()
        self.client.emit('authenticate', data, json=True)
        res = self.client.get_received()
        assert len(res) == 1
        assert res[0]['name'] == 'success'
        data = {
            'conversation_id': self.conversation_id
        }
        self.client.emit('join_conversation', data, json=True)
        res = self.client.get_received()
        assert len(res) == 1
        assert res[0]['name'] == 'success'

    def test_device_join_without_conv_access(self):
        self.conversation.device_access = False
        db.session.commit()
        data = {
            'token': self.device_token
        }
        assert len(sockets) == 0
        self.client.connect()
        self.client.emit('authenticate', data, json=True)
        res = self.client.get_received()
        assert len(res) == 1
        assert res[0]['name'] == 'success'
        data = {
            'conversation_id': self.conversation_id
        }
        self.client.emit('join_conversation', data, json=True)
        res = self.client.get_received()
        assert len(res) == 1
        assert res[0]['name'] == 'error'

    def test_valid_leave_conversation(self):
        data = {
            'token': self.token2
        }
        assert len(sockets) == 0
        self.client.connect()
        self.client.emit('authenticate', data, json=True)
        res = self.client.get_received()
        assert len(res) == 1
        assert res[0]['name'] == 'success'
        data = {
            'conversation_id': self.conversation_id
        }
        self.client.emit('join_conversation', data, json=True)
        res = self.client.get_received()
        assert len(res) == 1
        assert res[0]['name'] == 'success'
        self.client.emit('leave_conversation', data, json=True)
        res = self.client.get_received()
        assert len(res) == 1
        assert res[0]['name'] == 'success'

    def test_invalid_leave_conversation(self):
        data = {
            'token': self.token1
        }
        assert len(sockets) == 0
        self.client.connect()
        self.client.emit('authenticate', data, json=True)
        res = self.client.get_received()
        assert len(res) == 1
        assert res[0]['name'] == 'success'
        data = {
            'conversation_id': self.conversation_id
        }
        self.client.emit('leave_conversation', data, json=True)
        res = self.client.get_received()
        assert len(res) == 1
        assert res[0]['name'] == 'success'
示例#24
0
def init_default_content(p1, p2):
    user = db.session.query(User).filter(
        User.email == "*****@*****.**").first()
    user2 = db.session.query(User).filter(
        User.email == "*****@*****.**").first()
    if user is None and user2 is None:
        user = User(email="*****@*****.**",
                    password=p1,
                    first_name="user1",
                    last_name="beta",
                    birthday="2019-09-05")
        user2 = User(email="*****@*****.**",
                     password=p2,
                     first_name="user2",
                     last_name="beta",
                     birthday="2019-09-05")
        circle = Circle("Cercle Beta 1")
        db.session.commit()
        UserToCircle(user=user, circle=circle, privilege="ADMIN")
        UserToCircle(user=user2, circle=circle)
        db.session.commit()
        device = db.session.query(Device).filter(
            Device.username == "device1").first()
        if device is None:
            device = Device(name="Device beta 1")
            device.circle = circle
            device.username = "******"
            device.set_password("test")
            device.activate(device.key)
            db.session.commit()
        if len(circle.conversations) == 0:
            conversation = Conversation(device_access=True,
                                        name="Conversation avec device",
                                        circle=circle)
            conversation2 = Conversation(device_access=False,
                                         name="Conversation sans device",
                                         circle=circle)
            db.session.commit()
            if len(user.conversation_links) == 0:
                cl1 = UserToConversation(privilege="ADMIN",
                                         user=user,
                                         conversation=conversation)
                cl2 = UserToConversation(user=user2, conversation=conversation)
                db.session.commit()
                Message(content="Message conversation avec device from user1",
                        link=cl1,
                        conversation=conversation)
                Message(content="Message conversation avec device from user2",
                        link=cl2,
                        conversation=conversation)
                message3 = Message(
                    content="Message conversation avec device from device",
                    is_user=False,
                    conversation=conversation)
                message3.device = device
                db.session.commit()
            if len(user2.conversation_links) == 0:
                cl3 = UserToConversation(privilege="ADMIN",
                                         user=user,
                                         conversation=conversation2)
                cl4 = UserToConversation(user=user2,
                                         conversation=conversation2)
                db.session.commit()
                Message(content="Message conversation sans device from user1",
                        link=cl3,
                        conversation=conversation2)
                Message(content="Message conversation sans device from user2",
                        link=cl4,
                        conversation=conversation2)
        db.session.commit()
class TestDeviceMessageSend(unittest.TestCase):
    def setUp(self):
        neo_config.load_config()
        neo_config.set_project_variables()
        neo = NeoAPI(neo_config)
        self.api = neo.activate_testing()
        self.user1 = db.session.query(UserModel).filter(
            UserModel.email == "*****@*****.**").first()
        if self.user1 is None:
            self.user1 = UserModel(email="*****@*****.**",
                                   password="******",
                                   first_name="firstname",
                                   last_name="lastname",
                                   birthday="1995-12-12")
        self.user2 = db.session.query(UserModel).filter(
            UserModel.email == "*****@*****.**").first()
        if self.user2 is None:
            self.user2 = UserModel(email="*****@*****.**",
                                   password="******",
                                   first_name="firstname",
                                   last_name="lastname",
                                   birthday="1111-11-11")
        self.circle = Circle(name="Mamie")
        self.circle2 = Circle(name="test")
        self.linkCircle = UserToCircle(user=self.user1,
                                       circle=self.circle,
                                       privilege="ADMIN")
        self.linkCircle2 = UserToCircle(user=self.user2, circle=self.circle)
        self.conversation = Conversation("test")
        self.conversation.circle = self.circle
        self.conversation.device_access = True
        self.device = Device(name="Papie")
        self.device2 = Device(name="test")
        self.device2.circle = self.circle2
        self.device2_password = self.device2.get_pre_activation_password()
        self.device2.activate(self.device2.key)
        self.device.circle = self.circle
        self.device_password = self.device.get_pre_activation_password()
        self.device.activate(self.device.key)
        self.message = Message(is_user=False)
        self.message.conversation = self.conversation
        self.message.device = self.device
        db.session.commit()
        self.token1 = authenticate_user(self.api, self.user1, "test")
        self.token2 = authenticate_user(self.api, self.user2, "test")
        self.device_token = authenticate_device(self.api, self.device,
                                                self.device_password)
        self.device2_token = authenticate_device(self.api, self.device2,
                                                 self.device2_password)
        self.tokenAdmin = authenticate_user(self.api,
                                            "*****@*****.**",
                                            "PapieNeo2019")

    def test_valid_message_send(self):
        json_data = {
            "device_token": self.device_token,
            "conversation_id": self.conversation.id,
            "text_message": "yo"
        }
        response = self.api.post('/device/message/send',
                                 data=json.dumps(json_data),
                                 content_type='application/json')
        response_json = json.loads(response.data)
        assert response.status_code == 200
        assert response_json['success'] is True
        assert len(self.circle.conversations[0].messages) == 2
        assert self.circle.conversations[0].messages[1].text_content == "yo"

    def test_invalid_conversation(self):
        json_data = {
            "device_token": self.device_token,
            "conversation_id": 2000,
            "text_message": "yo"
        }
        response = self.api.post('/device/message/send',
                                 data=json.dumps(json_data),
                                 content_type='application/json')
        response_json = json.loads(response.data)
        assert response.status_code != 200
        assert not response_json['success']

    def test_invalid_device(self):
        json_data = {
            "device_token": self.device2_token,
            "conversation_id": self.conversation.id,
            "text_message": "yo"
        }
        response = self.api.post('/device/message/send',
                                 data=json.dumps(json_data),
                                 content_type='application/json')
        response_json = json.loads(response.data)
        assert response.status_code == 403
        assert not response_json['success']

    def test_missing_parameter(self):
        json_data = {"device_token": self.device_token, "text_message": "yo"}
        response = self.api.post('/device/message/send',
                                 data=json.dumps(json_data),
                                 content_type='application/json')
        response_json = json.loads(response.data)
        assert response.status_code != 200
        assert not response_json['success']
示例#26
0
class TestDeviceMediaInfo(unittest.TestCase):
    def setUp(self):
        neo_config.load_config()
        neo_config.set_project_variables()
        neo = NeoAPI(neo_config)
        self.api = neo.activate_testing()
        self.user1 = db.session.query(UserModel).filter(
            UserModel.email == "*****@*****.**").first()
        if self.user1 is None:
            self.user1 = UserModel(email="*****@*****.**",
                                   password="******",
                                   first_name="firstname",
                                   last_name="lastname",
                                   birthday="1995-12-12")
        self.user2 = db.session.query(UserModel).filter(
            UserModel.email == "*****@*****.**").first()
        if self.user2 is None:
            self.user2 = UserModel(email="*****@*****.**",
                                   password="******",
                                   first_name="firstname",
                                   last_name="lastname",
                                   birthday="1111-11-11")
        self.circle = Circle(name="Mamie")
        self.linkCircle = UserToCircle(user=self.user1, circle=self.circle)
        self.linkCircle2 = UserToCircle(user=self.user2, circle=self.circle)
        self.conversation = Conversation(circle=self.circle,
                                         device_access=True)
        self.linkConversation = UserToConversation(
            user=self.user1, conversation=self.conversation, privilege="ADMIN")
        self.message = Message()
        self.message.conversation = self.conversation
        self.message.link = self.linkConversation
        self.media = Media('test', '.txt', 'test.txt')
        self.media.message = self.message
        self.device = Device(name="Papie")
        self.device.circle = self.circle
        self.device_password = self.device.get_pre_activation_password()
        self.device.activate(self.device.key)
        db.session.commit()
        self.token1 = authenticate_user(self.api, self.user1, "test")
        self.token2 = authenticate_user(self.api, self.user2, "test")
        self.tokenAdmin = authenticate_user(self.api,
                                            "*****@*****.**",
                                            "PapieNeo2019")
        self.tokenDevice = authenticate_device(self.api, self.device,
                                               self.device_password)

    def test_valid_info(self):
        json_data = {
            'device_token': self.tokenDevice,
            'media_id': self.media.id
        }
        response = self.api.post('/media/info',
                                 data=json.dumps(json_data),
                                 content_type='application/json')
        response_json = json.loads(response.data)
        assert response.status_code == 200
        assert response_json['success'] is True

    def test_invalid_info(self):
        json_data = {'device_token': self.token1, 'media_id': self.media.id}
        response = self.api.post('/media/info',
                                 data=json.dumps(json_data),
                                 content_type='application/json')
        response_json = json.loads(response.data)
        assert response.status_code != 200
        assert response_json['success'] is False
示例#27
0
def deviceAvail(subnet, interval):
    """ Online - can SSH and log into
        Offline - is in the DB and was able to SSH to, but no more
        Warning - can ssh to but has an alarm
        Unconfigured - can ssh but pwd doesn't work
        Unsupported - not a Juniper device
    """

    #Constantly monitor the customer's networks
    while True:

        #Get all devices found on the network:
        server = Server()
        allNetDevices = scan(subnet, server.getUplink())
        allDbDevices = getAllSql("device", ["address"])

        #Update the status of devices that went offline
        for address in allDbDevices:
            if (address[0] not in allNetDevices):
                device = Device("asdn-" + address[0], address[0])
                device.status = "offline"
                device.addToDB(True)

        #Check if a device is operational
        for address, vendor in allNetDevices.items():
            device = Device("asdn-" + address, address)
            device.vendor = vendor

            #Check if the vendor is Juniper
            if "Juniper" in vendor:
                status = device.getDeviceStatus()

                # Get the device configuration
                #device.getDeviceConfig()

                #Check if login is possible
                if not status:
                    status = "unconfigured"
                elif len(status["alarms"]) == 0:
                    status = "warning"
                else:
                    status = "online"
            else:
                status = "unsupported"

            #Assign the status to the device
            device.status = status

            # Add to DB if already there else append
            if device.isInDB():
                device.addToDB(True)
            else:
                device.addToDB(False)

        #Pause the polling for the desired duration
        time.sleep(interval)
示例#28
0
class TestDeviceMediaUpload(unittest.TestCase):
    def setUp(self):
        neo_config.load_config()
        neo_config.set_project_variables()
        neo = NeoAPI(neo_config)
        self.api = neo.activate_testing()
        self.user1 = db.session.query(UserModel).filter(
            UserModel.email == "*****@*****.**").first()
        if self.user1 is None:
            self.user1 = UserModel(email="*****@*****.**",
                                   password="******",
                                   first_name="firstname",
                                   last_name="lastname",
                                   birthday="1995-12-12")
        self.user2 = db.session.query(UserModel).filter(
            UserModel.email == "*****@*****.**").first()
        if self.user2 is None:
            self.user2 = UserModel(email="*****@*****.**",
                                   password="******",
                                   first_name="firstname",
                                   last_name="lastname",
                                   birthday="1111-11-11")
        self.circle = Circle(name="Mamie")
        self.linkCircle = UserToCircle(user=self.user1, circle=self.circle)
        self.linkCircle2 = UserToCircle(user=self.user2, circle=self.circle)
        self.conversation = Conversation(circle=self.circle,
                                         device_access=True)
        self.linkConversation = UserToConversation(
            user=self.user1, conversation=self.conversation, privilege="ADMIN")
        self.message = Message()
        self.message.conversation = self.conversation
        self.message.link = self.linkConversation
        self.media = Media('test', '.txt', 'test.txt')
        self.media.message = self.message
        self.device = Device(name="Papie")
        self.device.circle = self.circle
        self.device_password = self.device.get_pre_activation_password()
        self.device.activate(self.device.key)
        db.session.commit()
        self.token1 = authenticate_user(self.api, self.user1, "test")
        self.token2 = authenticate_user(self.api, self.user2, "test")
        self.tokenAdmin = authenticate_user(self.api,
                                            "*****@*****.**",
                                            "PapieNeo2019")
        self.tokenDevice = authenticate_device(self.api, self.device,
                                               self.device_password)

    def test_valid_upload_message(self):
        json_data = {
            'device_token': self.tokenDevice,
            'files': ["test_file.txt"],
            'conversation_id': self.conversation.id
        }
        response = self.api.post('/device/message/send',
                                 data=json.dumps(json_data),
                                 content_type='application/json')
        response_json = json.loads(response.data)
        assert response.status_code == 200
        assert response_json['success'] is True
        assert len(response_json['media_list']) == 1
        headers = {
            'content-type': 'multipart/form-data',
            'Authorization': self.tokenDevice
        }
        data = {'file': (io.BytesIO(b"device sent a file"), 'test_file.txt')}
        response = self.api.post('/media/upload/' +
                                 str(response_json['media_list'][0]['id']),
                                 data=data,
                                 headers=headers)
        response_json = json.loads(response.data)
        assert response_json["success"] is True
        assert os.path.exists('user_files' + os.path.sep + 'conversation_' +
                              str(self.conversation.id) + os.path.sep)

    def test_invalid_upload_message(self):
        json_data = {
            'device_token': self.tokenDevice,
            'files': ["test_file.txt"],
            'conversation_id': self.conversation.id
        }
        response = self.api.post('/device/message/send',
                                 data=json.dumps(json_data),
                                 content_type='application/json')
        response_json = json.loads(response.data)
        assert response.status_code == 200
        assert response_json['success'] is True
        assert len(response_json['media_list']) == 1
        headers = {
            'content-type': 'multipart/form-data',
            'Authorization': self.tokenDevice
        }
        data = {'file': (io.BytesIO(b"device sent a file 2"), 'test_file.txt')}
        response = self.api.post('/media/upload/' + "999",
                                 data=data,
                                 headers=headers)
        response_json = json.loads(response.data)
        assert response_json["success"] is False

    def tearDown(self):
        if os.path.exists("user_files"):
            shutil.rmtree('user_files')