예제 #1
0
def public_keys():
    if not current_flamenco.jwt.usable:
        raise wz_exceptions.NotImplemented(
            'JWT keystore is not usable at the moment')

    last_modified = current_flamenco.jwt.public_keys_last_modified
    if request.headers.get('If-Modified-Since', '') == last_modified:
        return Response('', status=304)  # Not Modified

    pubs = current_flamenco.jwt.public_keys
    if not pubs:
        raise wz_exceptions.NotImplemented('No public JWT keys available')
    return Response(pubs,
                    content_type='text/plain',
                    headers={'Last-Modified': last_modified})
예제 #2
0
    def post(self, entity_id):
        # TODO
        # - read paramterrs
        # - start a session
        # - get a lock of the resource
        # - actuation
        # - verify the actuation
        # - post the updated value to the timeseries database
        # - close the session - abort the session if anything goes wrong.
        args = reqparser.parse_args()
        actuation_value = args.value
        scheduled_time = args.get('scheduled_time', None)
        if scheduled_time:
            # TODO: Implement this
            raise exceptions.NotImplemented(
                'Currently only immediate actuation is implemented.')

        with self.lock_manager.advisory_lock(entity_id) as lock_acquired:
            assert lock_acquired, exceptions.BadRequest(
                'Lock for {0} cannot be acquired'.format(entity_id))
            self.actuation(entity_id, actuation_value)
            actuated_time = arrow.get()
            data = [[entity_id, actuated_time.timestamp, actuation_value]]
            self.ts_db.add_data(data)
            return None

        raise exceptions.InternalServerError('This should not be reached.')
예제 #3
0
 def _get_method(self, method):
     try:
         meth = getattr(self.model, method)
     except AttributeError:
         raise exceptions.NotImplemented(
             "Not implemented by underlying model (loaded '%s')" % self.name
         )
     return meth
예제 #4
0
 def post(self):
     args = reqparser.parse_args()
     content_type = args.content_type
     # TODO: Verify/Authorize the user for the turtle file
     if content_type == 'application/json':
         entities = marshal(args, entities_model)['entities']
         entities = self.add_entities_json(entities)
     elif content_type == 'text/turtle':
         raise exceptions.NotImplemented(
             'TODO: Implement entities addition for Content-Type {0}.'.
             format(content_type))
         raw_ttl = request.data.decode('utf-8')
         self.add_entities_ttl(raw_ttl)
     else:
         raise exceptions.NotImplemented(
             'TODO: Implement entities addition for Content-Type {0}.'.
             format(content_type))
     return {'entities': entities}, 201
예제 #5
0
    def __init__(self, limit):
        self.limit = limit

        # Set defaults
        self.code = 429
        self.body = self.get_body()
        self.headers = self.get_headers()

        # Get the description
        if limit.error_message:
            self.description = limit.error_message if not callable(
                limit.error_message) else limit.error_message()
        else:
            self.description = text_type(limit.limit)

        # If error is given, get body & headers
        if self.limit.error_code:
            self.code = limit.error_code
            exception = exceptions.HTTPException(description=self.description)

            # Some common error codes, can add more here
            if self.code == 400:
                exception = exceptions.BadRequest()
            elif self.code == 401:
                exception = exceptions.Unauthorized()
            elif self.code == 403:
                exception = exceptions.Forbidden()
            elif self.code == 404:
                exception = exceptions.NotFound()
            elif self.code == 405:
                exception = exceptions.MethodNotAllowed()
            elif self.code == 406:
                exception = exceptions.NotAcceptable()
            elif self.code == 418:
                exception = exceptions.ImATeapot()  # <3
            elif self.code == 500:
                exception = exceptions.InternalServerError()
            elif self.code == 501:
                exception = exceptions.NotImplemented()

            # Update body & headers
            self.body = exception.get_body()
            self.headers = exception.get_headers()
        else:
            exception = exceptions.TooManyRequests(
                description=self.description)

            # Update body & headers
            self.body = exception.get_body()
            self.headers = exception.get_headers()
        super(RateLimitExceeded,
              self).__init__(description=self.description,
                             response=Response(self.body, self.code,
                                               self.headers))
예제 #6
0
def workflows_put(wf_uuid, wf_version, body):
    # TODO: to be implemented
    logger.debug("PUT called for workflow (%s,%s)", wf_uuid, wf_version)
    # try:
    #     wf = model.WorkflowVersion.query.get(wf_id)
    # except sqlalchemy.exc.DataError:
    #     return "Invalid ID", 400
    # wf.name = body['name']
    # db.session.commit()
    # return connexion.NoContent, 200
    raise http_exceptions.NotImplemented()
예제 #7
0
def generate_token(manager_id: str):
    manager_oid = str2id(manager_id)
    manager = mongo.find_one_or_404('flamenco_managers', manager_oid)

    # There are three ways in which a user can get here. One is authenticated via
    # Authorization header (either Bearer token or Basic token:subtoken), and the
    # other is via an already-existing browser session.
    # In the latter case it's a redirect from a Flamenco Manager and we need to
    # check the timeout and HMAC.
    if not request.headers.get('Authorization'):
        hasher = current_flamenco.manager_manager.hasher(manager_oid)
        if hasher is None:
            raise wz_exceptions.InternalServerError(
                'Flamenco Manager not linked to this server')

        expires = request.args.get('expires', '')
        string_to_hash = f'{expires}-{manager_id}'
        hasher.update(string_to_hash.encode('utf8'))
        actual_hmac = hasher.hexdigest()

        query_hmac = request.args.get('hmac', '')
        if not hmac.compare_digest(query_hmac, actual_hmac):
            raise wz_exceptions.Unauthorized('Bad HMAC')

        # Only parse the timestamp after we learned we can trust it.
        expire_timestamp = dateutil.parser.parse(expires)
        validity_seconds_left = (expire_timestamp - utcnow()).total_seconds()
        if validity_seconds_left < 0:
            raise wz_exceptions.Unauthorized('Link expired')
        if validity_seconds_left > 900:
            # Flamenco Manager generates links that are valid for less than a minute, so
            # if it's more than 15 minutes in the future, it's bad.
            raise wz_exceptions.Unauthorized('Link too far in the future')

    user = authentication.current_user()

    if not current_flamenco.manager_manager.user_may_use(mngr_doc=manager):
        log.warning(
            'Account %s called %s for manager %s without access to that manager',
            user.user_id, request.url, manager_oid)
        raise wz_exceptions.Unauthorized()

    jwt = current_flamenco.jwt
    if not jwt.usable:
        raise wz_exceptions.NotImplemented(
            'JWT keystore is not usable at the moment')

    log.info('Generating JWT key for user_id=%s manager_id=%s remote_addr=%s',
             user.user_id, manager_id, request.remote_addr)
    key_for_manager = jwt.generate_key_for_manager(manager_oid, user.user_id)

    return Response(key_for_manager, content_type='text/plain')
예제 #8
0
def numpy_pandas_function_from_str(f):
    """
    reconstruct function from string representation
    """
    if f.startswith(np.__name__):
        mod = np
    elif f.startswith(pd.__name__):
        mod = pd
    elif f.startswith(builtins.__name__):
        mod = builtins
    else:
        msg = ("Function {} not recognized; only numpy, pandas, or builtin "
               "functions are supported.")
        raise wz_ex.NotImplemented(msg.format(f))
    fcn = reduce(getattr, f.split('.')[1:], mod)
    return fcn
예제 #9
0
    def actuate(self, entity_id, value):
        """Actuates an entity with a given value.

        This function sets the current value of the entity with `entity_id` as `value` in "the actual system" such as BACnet devices. The value may have a physical impact in the real world.

        Args:
            entity_id: The identifier of an entity.
            value: A numeric value that the request wants to actuate of the entity.

        Returns:
            None. If the actuation is successful, the function completes. Otherwise, it raises an exception.

        Raises:
            TODO
        """
        raise exceptions.NotImplemented('This should be overriden by an actual implementation.')
예제 #10
0
파일: web_app.py 프로젝트: cpages/testplan
 def get(self, report_uid, assertions_uid):
     """
     Get an Assertion report (JSON) for a specific Testplan report given
     their uids.
     """
     raise exceptions.NotImplemented()  # pylint: disable=notimplemented-raised
예제 #11
0
 def wrap(*args, **kwargs):
     try:
         return f(*args, **kwargs)
     except NotImplementedError:
         raise exceptions.NotImplemented("Model does not implement "
                                         "this functionality")
예제 #12
0
 def wrapped(a, b):
     raise wz_exceptions.NotImplemented('nee')
예제 #13
0
def not_implemented(message=exceptions.NotImplemented().description):
    response = jsonify({'error': 'Not Implemented', 'message': message})
    response.status_code = 501
    return response
예제 #14
0
 def get(self):
     # TODO: Implement
     raise exceptions.NotImplemented('TODO: List all entities and types')
     return res
예제 #15
0
 def delete(self, entity_id):
     raise exceptions.NotImplemented('TODO: Delete corresponding entity.')
     return None