def exception_response(request, code=400, exception=None):
    """
    Create a response for an exception
    :param request: request instance
    :param code: exception code
    :param exception: exception instance
    :return: exception formatted response
    """
    code = code if code in [400, 403, 404, 500] else 400

    exception_repr = get_error_msg(exception)
    log.error(usr=request.user, msg=f'{code} - {exception_repr}')

    context = dict(message=f"Error {code}",
                   request_path=request.path,
                   exception=exception_repr)

    if is_browser(request):
        template = loader.get_template(f'error/{code}.html')
        rtn = dict(content=template.render(context, request),
                   content_type='text/html')
    else:
        rtn = dict(content=json.dumps(context),
                   content_type='application/json')

    return rtn
def command_response(body, message):
    """
    Process a command received from an actuator
    :param body: command body
    :param message: complete message (headers, meta, ...)
    :return: None
    """
    log.info(msg=f'Message response received: {body}')
    headers = getattr(message, "headers", {})
    actuator = None

    if headers.get('error', False):
        correlation_ID = headers['source'].get('correlationID', '')
        opts = {
            '_coap_id' if isHex(correlation_ID) else 'command_id':
            correlation_ID
        }

        command = get_or_none(SentHistory, **opts)
        log.error(msg=f'Message Failure: cmd - {command.command_id}, {body}')

        response = {'error': body}

    else:
        act_host, act_port = headers.get('socket', '').split(':')[0:2]
        correlation_ID = headers.get('correlationID', '')
        opts = {
            '_coap_id' if isHex(correlation_ID) else 'command_id':
            correlation_ID
        }

        command = get_or_none(SentHistory, **opts)
        profile = headers.get('profile', '')

        encode = headers.get('encode', 'json')
        response = decode_msg(body, encode)

        actuator = get_or_none(
            model=Actuator,
            profile__iexact=profile,
            device__transport__host__iexact=act_host,
            device__transport__port=safe_cast(act_port, int),
            device__transport__protocol=get_or_none(Protocol,
                                                    name__iexact=headers.get(
                                                        'transport', '')))

        if hasattr(actuator, '__iter__'):
            log.warn(
                msg=
                f'Multiple actuators match for command response - {command.command_id}'
            )
            actuator = random.choice(actuator)

    try:
        cmd_rsp = ResponseHistory(command=command,
                                  actuator=actuator,
                                  response=response)
        cmd_rsp.save()
    except Exception as e:
        log.error(msg=f'Message response failed to save: {e}')
Example #3
0
 def _val_user(self):
     if self._usr is None:
         log.error(msg="invalid user attempted to send a command")
         return dict(
             detail="user invalid",
             response="User Invalid: command must be send by a valid user"
         ), 401
     return None
Example #4
0
    def _val_cmd(self):
        if len(self._cmd.keys()) == 0:
            log.error(usr=self._usr, msg="User attempted to send an empty command")
            return dict(
                detail="command invalid",
                response="Command Invalid: command cannot be empty"
            ), 400

        # TODO: Validate command
        return None
Example #5
0
    def _val_actuator(self) -> Union[Tuple[dict, int], Tuple[Tuple[dict, int], str], Tuple[List[Actuator], str]]:
        if self._actuator is None:
            # TODO: Actuator broadcast??
            log.error(usr=self._usr, msg="User attempted to send to a null actuator")
            return dict(
                detail="actuator invalid",
                response="Actuator Invalid: actuator cannot be none"
            ), 400

        act_arr = self._actuator.split("/", 1)
        if len(act_arr) != 2:
            log.error(usr=self._usr, msg=f"User attempted to send to an invalid actuator - {self._actuator}")
            return dict(
                detail="actuator invalid",
                response="Actuator Invalid: application error"
            ), 400

        act_type, act = act_arr
        act_type = bleach.clean(str(act_type))
        act = bleach.clean(str(act).replace("_", " "))

        if act_type == "actuator":  # Single Actuator
            actuators = get_or_none(Actuator, actuator_id=act)
            rtn = [actuators, ]
            if actuators is None:
                rtn = dict(
                    detail="actuator invalid",
                    response="Actuator Invalid: actuator must be specified with a command"
                ), 404
            return rtn, 'device'

        if act_type == "profile":  # Profile Actuators
            print(f'Profile: {act}')
            actuators = get_or_none(ActuatorProfile, name__iexact=act)
            if actuators is None:
                return dict(
                    detail="profile cannot be found",
                    response="Profile Invalid: profile must be a valid registered profile with the orchestrator"
                ), 400
            return list(Actuator.objects.filter(profile__iexact=act.replace(" ", "_"))), 'profile'

        return dict(
            detail="actuator invalid",
            response="Actuator Invalid: application error"
        ), 400
def validate_actuator(usr, act=""):
    if act is None:  # TODO: actuator broadcast??
        log.error(usr=usr, msg="User attempted to send to a null actuator")
        return dict(detail="actuator invalid",
                    response="Actuator Invalid: actuator cannot be none"), 400

    act_type = act.split("/", 1)
    if len(act_type) != 2:
        log.error(usr=usr,
                  msg=f"User attempted to send to an invalid actuator - {act}")
        return dict(detail="actuator invalid",
                    response="Actuator Invalid: application error"), 400

    _type, _act_prof = act_type
    _type = bleach.clean(str(_type))
    _act_prof = bleach.clean(str(_act_prof).replace("_", " "))

    if _type == "actuator":  # Single Actuator
        actuators = get_or_none(Actuator, actuator_id=_act_prof)
        if actuators is None:
            return dict(
                detail="actuator invalid",
                response=
                "Actuator Invalid: actuator must be specified with a command"
            ), 404
        return [
            actuators,
        ]

    elif _type == "profile":  # Profile Actuators
        actuators = get_or_none(ActuatorProfile, name__iexact=_act_prof)
        if actuators is None:
            return dict(
                detail=f"profile cannot be found",
                response=
                f"Profile Invalid: profile must be a valid registered profile with the orchestrator"
            ), 400
        return list(
            Actuator.objects.filter(
                profile__iexact=_act_prof.replace(" ", "_")))
    else:
        return dict(detail="actuator invalid",
                    response="Actuator Invalid: application error"), 400
Example #7
0
def exception_response(request, code=400, exception=None, *args, **kwargs):
    code = code if code in [400, 403, 404, 500] else 400

    exception_repr = get_error_msg(exception)
    log.error(usr=request.user, msg=f'{code} - {exception_repr}')

    context = dict(message='Error 400 - Bad Request',
                   request_path=request.path,
                   exception=exception_repr)

    if is_browser(request):
        template = loader.get_template(f'error/{code}.html')
        rtn = dict(content=template.render(context, request),
                   content_type='text/html')
    else:
        rtn = dict(content=json.dumps(context),
                   content_type='application/json')

    return rtn
def validate_cmd(usr, cmd={}):
    if len(cmd.keys()) == 0:
        log.error(usr=usr, msg="User attempted to send an empty command")
        return dict(detail="command invalid",
                    response="Command Invalid: command cannot be empty"), 400
    '''
def validate_usr(usr=None):
    if usr is None:
        log.error(msg="invalid user attempted to send a command")
        return dict(
            detail="user invalid",
            response="User Invalid: command must be send by a valid user"), 401