Exemple #1
0
    def get_obj_keys(cls,
                     obj_data,
                     *,
                     connection_index='',
                     external_system_uid=None,
                     obj_meta_keys=None,
                     obj_type_is=None,
                     obj_type=None,
                     obj_id=None,
                     obj_title=None,
                     fill_id_from_data=False):
        if obj_meta_keys is None:
            raise KeyNotFound(message='object keys field not defined',
                              detail=cls.__name__)
        if fill_id_from_data:
            try:
                obj_type_is = obj_data[f'ТипИС{connection_index}']
                obj_type = obj_data['Тип']
                obj_id = obj_data[f'ИдИС{connection_index}']
                obj_title = obj_data['Название']
            except KeyError as err:
                raise KeyNotFound(detail=err,
                                  dump={'obj_data': obj_data},
                                  action='get_obj_keys')
        keys = []
        for key in obj_meta_keys:
            try:
                key_name = key['key']
                fields = key['fields']
            except KeyError:
                continue
            obj_key = dict(system=external_system_uid,
                           type=obj_type,
                           type_is=obj_type_is,
                           title=obj_title,
                           uid=obj_id,
                           key=key_name)
            not_null = False
            for index in range(5):
                try:
                    field = fields[index]
                except IndexError:
                    obj_key[f'val{index}'] = None
                    continue

                value = obj_data.get(
                    field['path'])  # todo: добавить разбор пути
                if value:
                    not_null = True
                format_value = field.get('format')
                if format_value:
                    if format_value == 'date':
                        value = value.strftime('%Y-%m-%d')
                else:
                    if value:
                        value = str(value)
                obj_key[f'val{index}'] = value
            if not_null:
                keys.append(obj_key)
        return keys
Exemple #2
0
 async def find_by_id(self, _id, *, _form="Item", _action=None, **kwargs):
     if not _id:
         raise KeyNotFound(message=f'Object id not defined',
                           detail=f'{self.name}')
     res = _action.add_stat(await self.find_one({"_id": _id},
                                                _form=_form,
                                                **kwargs))
     if res:
         self.init_by_data(res)
         return res
     raise KeyNotFound(message=f'Object not found',
                       detail=f'{self.name} (id: {_id})')
Exemple #3
0
 async def init_from_request(cls, view, **kwargs):
     action = kwargs['_action']
     _session = await get_session(view.request)
     if not _session or not _session.identity:  # если авторизация происходит под чужой живой сессией грохаем её
         raise KeyNotFound(detail='session')
     try:
         session_id = ObjectId(_session.identity)
     except InvalidId:
         raise KeyNotFound(detail='Session ID not in BSON ObjectId')
     self = cls(view.storage)
     await action.add_stat(self.find_by_id(session_id))
     return action.set_end(self)
Exemple #4
0
    async def action_run_device(self, link):
        di = link.get('di')
        try:
            class_name = link['dmno']
        except KeyError:
            raise KeyNotFound(detail='dmno',
                              action='action_run_device') from None
        if di and di in self._running_devices:
            raise Exception('device is already running')
        if class_name == 'VirtualServer':
            process = multiprocessing.Process(target=self.device_process,
                                              args=(class_name, di, self.queue,
                                                    dict(path=self.path)),
                                              daemon=True)
            process.start()
            self._running_devices[link['di']] = process
            return None

        else:
            device = Device.init_from_file(class_name=class_name,
                                           di=link.get('di'),
                                           path=self.path,
                                           loop=self.loop,
                                           log=self.log)
            link['di'] = device.get_device_id()
            task = self.loop.create_task(device.main())
            device.task = task
            self._running_devices[link['di']] = device
            return device
Exemple #5
0
 async def check_right(cls, **kwargs):
     action = kwargs['_action']
     try:
         storage = kwargs['storage']
         user_ref = kwargs['user']
         account_id = kwargs['account']
         object_name = kwargs['object']
         level = kwargs['level']
         params = kwargs.get('params', {})
     except KeyError as key:
         raise KeyNotFound(detail=str(key))
     try:
         user = cls(storage, account_id=account_id, form='AccessRight')
         action.add_stat(await user.find_by_id(user_ref['_ref'].id))
         rights = user.data.get('right')
     except Exception as err:
         raise AccessDenied(parent=err)
     if not rights:
         raise AccessDenied(detail='Empty access list')
     try:
         _level = rights[object_name]['level']
     except Exception:
         raise AccessDenied(detail=object_name)
     if _level < level:
         raise AccessDenied(detail=object_name)
     pass
Exemple #6
0
 def get_param(self, href, *args):
     try:
         _res = self.res[href].data
     except KeyError:
         raise KeyNotFound(
             action='OcfDevice.get_param',
             detail=f'{href} ({self.__class__.__name__})') from None
     if not args or args[0] is None:
         return _res
     try:
         return self.res[href].get_attr(*args)
     except KeyError:
         try:
             return args[1]
         except IndexError:
             raise KeyNotFound(
                 action='OcfDevice.get_param',
                 detail=f'{args[0]} ({self.__class__.__name__}{href})'
             ) from None
Exemple #7
0
 async def find_one(self, where, *, _form="Item", _action=None, **kwargs):
     self.add_projection(_form, kwargs)
     res = await self.storage.find_one(self.db, self.name, where, **kwargs)
     if res:
         self.init_by_data(res)
         return res
     raise KeyNotFound(message=f'Object not found',
                       detail=f'{self.name}',
                       dump=where,
                       action=_action)
Exemple #8
0
 def get_attr(self, *args):
     try:
         return self.data[args[0]]
     except KeyError:
         try:
             return args[1]
         except IndexError:
             raise KeyNotFound(
                 action='OcfDevice.get_param',
                 detail=f'{args[0]} ({self.__class__.__name__}{self._href})'
             ) from None
Exemple #9
0
 def get_link(self, href=None):
     if self._link is None:
         eps = []
         if not self.transport_layer.coap:
             raise KeyNotFound(detail='COAP socket not found')
         # for elem in self.coap.endpoint:
         #     if elem == 'multicast' or not self.coap.endpoint[elem]:
         #         continue
         #     eps.append(dict(ep=self.coap.endpoint[elem]['uri']))
         self._link = dict(anchor='ocf://{}'.format(self.get_device_id()),
                           eps=self.transport_layer.get_eps())
     if href and href in self.data:
         return dict(anchor=self._link['anchor'],
                     eps=self._link['eps'],
                     href=href)
     else:
         return self._link
Exemple #10
0
 async def execute(self, data):
     try:
         if self.need_change_serial(data):
             await self.set_serial_configuration(data)
         self.log.debug(data)
         message = OcfMessageRequest(**data)
         response = await self.modbus.execute(message, None)
         # self.log.debug('execute({0})={1}'.format(data, response))
         return response.b64decode()
     except KeyError as err:
         self.log.error(f'Не указан обязательный параметр {err}')
         raise KeyNotFound(detail=str(err), action='ModbusMaster.execute')
     except asyncio.TimeoutError as err:
         self.log.error('ExtTimeoutError')
         raise ExtTimeoutError(action='ModbusMaster.execute') from err
     except Exception as err:
         self.log.error(err)
         raise ExtException(parent=err, action='ModbusMaster.execute')
Exemple #11
0
 async def public_api_read_session_info(self, view, **kwargs):
     action = kwargs['_action']
     try:
         user_link = view.session.get('user')
         if not user_link:
             return web.json_response({"session": view.session.identity})
         # user = action.add_stat(self.handler.init_by_ref(user_link, lang=view.lang, form='CurrentUser'))
         user = User(view.storage, lang=view.lang, form='CurrentUser')
         action.add_stat(await user.find_by_link(user_link))
         result = {
             "session": view.session.identity,
             "user": view.session.get('user'),
             "account": view.session.get('account'),
             "accounts": user.data.get('account', [])
         }
         return action.set_end(self.response.json_response(result, dumps=dumps))
         # login = view.data['login']
         # password = view.data['password']
     except KeyError as err:
         raise KeyNotFound(detail=err)
Exemple #12
0
    async def public_api_sign_up_by_password(self, view, **kwargs):
        action = kwargs['_action']
        try:
            login = view.data['login']
            password = view.data['password']
        except KeyError as err:
            raise KeyNotFound(detail=err)

        salt = os.urandom(32)
        password = b64encode(self._generate_password_hash(salt, password)).decode()

        user = User(view.storage, lang=view.lang, form='CurrentUser')
        res = action.add_stat(await user.add_auth({
            'type': 'password',
            'id': login,
            'password': password
        }, **kwargs))
        # if res:
        # if str(b64encode(password)) == res.get('password'):
        session = action.add_stat(await Session.create_from_request(user, view))
        return self.response.json_response({'session': str(session.obj_id)})
Exemple #13
0
    async def public_api_sign_in_by_password(self, view, **kwargs):
        action = kwargs['_action']
        try:
            login = view.data['login']
            password = view.data['password']
        except KeyError as err:
            raise KeyNotFound(detail=err)
        user = User(view.storage, lang=view.lang, form='CurrentUser')
        _auth = action.add_stat(await user.find_user_by_auth('password', login))
        bad_password = Unauthorized()

        _password = b64decode(_auth['password'])
        salt = _password[:32]
        if _auth['id'] != login or _password != self._generate_password_hash(salt, password):
            raise bad_password
        # _session = kwargs['session']
        session = action.add_stat(await Session.create_from_request(user, view))
        action.set_end(self.response.json_response({
            'session': str(session.obj_id),
            'user': user.data
        }))
        return action