Esempio n. 1
0
    def on_post(cls, req, resp):
        """Run the indicated runnable passing the given message."""
        try:
            message = req.body['message']
            runnable = req.body['runnable']

        except KeyError as ke:
            raise falcon.HTTPMissingParam(ke.args[0]) from None

        session = req.headers.get('API-SESSION')
        if not session:
            raise falcon.HTTPMissingParam('API-SESSION')

        req.context['session'] = ObjectId(session)
        req.context['internal'] = True

        cls.logger.debug('Running runnable %s', runnable, extra={'session': session})

        runnable_class = cls.api.runnables[runnable]
        runnable_class(req).run_local(message)

        resp.body = {
            'runnable': runnable,
            'message': message,
        }
        cls.logger.debug('runnable %s status: OK', runnable, extra={'session': session})
Esempio n. 2
0
    def on_patch(self, req, resp):
        """Method takes either sparql statement or predicate and object 
        and updates the Resource.

        Args:
            req -- Request
            resp -- Response
        """
        doc_uuid = req.get_param('uuid')
        if not doc_uuid:
            raise falcon.HTTPMissingParam('uuid')
        predicate = req.get_param('predicate') or None
        if not predicate:
            raise falcon.HTTPMissingParam('predicate')
        object_ = req.get_param('object') or None
        if not object_:
            raise falcon.HTTPMissingParam('object')
        doc_type = req.get_param('doc_type') or None
        if self.__update__(doc_id=doc_uuid,
                           doc_type=doc_type,
                           field=predicate,
                           value=object_):
            resp.status = falcon.HTTP_202
            resp.body = json.dumps(True)
        else:
            raise falcon.HTTPInternalServerError(
                "Error with PATCH for {}".format(doc_uuid),
                "Failed setting {} to {}".format(predicate, object_))
Esempio n. 3
0
    def on_post(self, request, resp):
        """
        Issue authenticated session cookie, if request credentials are valid
        """
        username_post_field, password_post_field = 'username', 'password'
        # fetch POSTed auth credentials
        try:
            request_username = request.params[username_post_field]
        except KeyError:
            raise falcon.HTTPMissingParam(username_post_field)

        try:
            request_password = request.params[password_post_field]
        except KeyError:
            raise falcon.HTTPMissingParam(password_post_field)

        # Authenticate
        try:
            user_id, decoded_token = KeycloakBackend.authenticate(
                request_username, request_password)
            if user_id is None:
                raise LoginInvalid('Bad Login!')
            #Indicate user is logged in
            auth.create_login_session(user_id, request, oidc=decoded_token)
        except LoginInvalid as e:
            title = 'Unauthorized'
            description = 'Please check the supplied username or password.'
            raise falcon.HTTPUnauthorized(title, description) from e
Esempio n. 4
0
 def on_post(self, req, resp, pid=None):
     self.__set_rest_url__("datastream", pid)
     namespace = req.get_param("namespace") or\
         "info:fedora/fedora-system:def/relations-external#"
     predicate = req.get_param("predicate") or None
     if not predicate:
         raise falcon.HTTPMissingParam(
             "Islandora Relationship POST missing predicate param",
             "predicate")
     object_ = req.get_param("object") or None
     if not object_:
         raise falcon.HTTPMissingParam(
             "Islandora POST missing object param",
             "object")
     if self.__add__(namespace, predicate, object_):
         message = """Added relationship {} from {} to {}""".format(
             predicate,
             pid,
             object_)
         resp.status = falcon.HTTP_201
         resp.body = json.dumps({"message": message})
     else:
         raise
         resp.status = falcon.HTTP_400
         resp.body = json.dumps(
             {"message": "failed to add relationship to {}".format(pid)})
Esempio n. 5
0
    def on_post(self, req, resp):
        """Handle user login POST requests.

        Returns an authenticated API session token

        HTTP POST parameters:
          username  -- New user to create (Required)
          password  -- New user's password (Required)
        """
        username_post_field, password_post_field = 'username', 'password'
        try:
            request_username = req.params[username_post_field]
        except KeyError:
            raise falcon.HTTPMissingParam(username_post_field)
        try:
            request_password = req.params[password_post_field]
        except KeyError:
            raise falcon.HTTPMissingParam(password_post_field)
        stored_hash = user.get_user_hash(user_storage, request_username)
        if auth.check_password(request_password, stored_hash):
            # log in user
            session.create_login_session(request_username, req)
            resp.media = {'message': 'Login success!'}
            return
        raise falcon.HTTPUnauthorized(title='Login incorrect')
Esempio n. 6
0
    def param_in_header(self, req, spec, param):
        headers = req.headers
        name = param.get('name').upper().replace('_', '-')
        type_ = param.get('type')

        value = headers.get(name)
        if param.get('required') and value is None:
            raise falcon.HTTPMissingParam(name)

        default_func = lambda v: v if type_ is not None else None

        check_funcs = {
            'string': lambda v: str(v),
            'password': lambda v: str(v),
            'byte': lambda v: base64.b64decode(str(v)),
            'integer': lambda v: int(v),
            'long': lambda v: int(v),
            'float': lambda v: float(v),
            'double': lambda v: float(v),
            'boolean': lambda v: bool(v),
            'array': json_check,
            'object': json_check,
        }

        try:
            value = check_funcs.get(type_, default_func)(value)
            self.log.debug('param in header - name: {}, type: {}, value: {}'.format(name, type_, value))
        except ValueError as e:
            self.log.error_trace(
                'value error when check param in header - name: {}, type: {}, value: {}'.format(name, type_, value))
            raise falcon.HTTPInvalidParam('invalid param in header', name + ':' + value)
        if param.get('required') and value is None:
            raise falcon.HTTPMissingParam(name)
        return value
Esempio n. 7
0
    def on_get(self, req, resp):
        """Handles GET requests"""

        if 'min' not in req.params:
            raise falcon.HTTPMissingParam('min')

        if 'max' not in req.params:
            raise falcon.HTTPMissingParam('max')

        min_n = req.params['min']
        max_n = req.params['max']

        if min_n.isnumeric() == False:
            raise falcon.HTTPInvalidParam('min must be number', min_n)

        if max_n.isnumeric() == False:
            raise falcon.HTTPInvalidParam('max must be number', max_n)

        min_n = int(min_n)
        max_n = int(max_n)

        if min_n > max_n:
            raise falcon.HTTPInvalidParam('min is bigger than max',
                                          (min_n, max_n))

        number = random.randint(min_n, max_n)
        result = {'lowerLimit': min_n, 'higherLimit': max_n, 'number': number}
        resp.media = result
Esempio n. 8
0
    def on_post(self, req, resp, uuid=None) -> None:
        jwt = decode_jwt(req.auth)
        try:
            doc = req.context.doc
        except AttributeError as e:
            logging.debug(str(e))
            raise falcon.HTTPBadRequest('JSON Body Missing')

        try:
            old_password = doc["oldpassword"]
        except KeyError as e:
            logging.debug(str(e))
            raise falcon.HTTPMissingParam("oldpassword")

        try:
            new_password = doc["newpassword"]
        except KeyError as e:
            logging.debug(str(e))
            raise falcon.HTTPMissingParam("newpassword")

        if uuid is None:
            uuid = jwt['user_uuid']

        # If SQL connection is gone, reconnect
        if not self.mysql.is_connected():
            logging.debug("MySQL connection dropped, reconnecting.")
            self.mysql.reconnect(attempts=3, delay=1)

        # SQL Result
        cursor = self.mysql.cursor()
        cursor.execute("SELECT `password`, `uuid` FROM `users` WHERE `uuid`=%s LIMIT 1",
                       (uuid,))

        for (password, uuid) in cursor:
            sql_password = password
            sql_uid = uuid
            break
        # SQL End

        new_pass_hash = new_hash(new_password)
        if hash_verify(old_password, sql_password):
            print("hash match")
        else:
            raise falcon.HTTPUnauthorized(
                "Old password is invalid",
                "The old password you entered does not match the one we have on record."
            )

        cursor.execute("UPDATE `users` SET password=%s WHERE `uuid`=%s LIMIT 1", (new_pass_hash, uuid,))
        self.mysql.commit()
        cursor.close()
        self.mysql.reconnect(attempts=3, delay=1)

        resp.context.result = {
            "title": "Password changed"
        }
Esempio n. 9
0
def CreateProject(**request_handler_args):
    req = request_handler_args['req']
    authUser(req, request_handler_args['resp'], ['createProject'])
    doc = req.context['doc']
    try:
        user_ids = []
        for x in range(len(doc['users'])):
            user_ids.append(ObjectId(doc['users'][x]))
    except InvalidId as e:
        raise falcon.HTTPBadRequest('Bad Request', str(e))
    except KeyError as e:
        raise falcon.HTTPMissingParam('users')

    try:
        project_users = User.objects.raw({'_id': {'$in': user_ids}})
    except User.DoesNotExist:
        raise falcon.HTTPNotFound()

    try:
        project_schema = Schema.objects.get(
            {'_id': ObjectId(doc['acl_schema'])})
    except InvalidId as e:
        raise falcon.HTTPBadRequest('Bad Request', str(e))
    except KeyError as e:
        raise falcon.HTTPMissingParam('acl_schema')

    try:
        project = Project(name=doc['name'],
                          acl_schema=project_schema,
                          paths=doc['paths'],
                          users=project_users)
    except KeyError as e:
        raise falcon.HTTPBadRequest('Invalid Project Object',
                                    "Project JSON Object is invalid. %s" % e)
    else:
        try:
            project.save()
        except project.ValidationError as e:
            raise falcon.HTTPBadRequest("Validation Error", e.message)
        else:
            #pprint.pprint(project)
            request_handler_args['resp'].status = falcon.HTTP_201
            project.uri = req.uri + '/' + str(project._id)
            request_handler_args['resp'].location = project.uri
            request_handler_args['req'].context['result'] = project.to_dict()
            req.context['logger'].info({
                'action':
                'createProject',
                'message':
                "'%s' project with id of %s was created successfully." %
                (project.name, project._id)
            })
Esempio n. 10
0
    def on_get(self, req, resp):
        
        param = req.get_param("target").split(':')
        self._target = param[0]
        self._port = param[1]

        resp.set_header('Content-Type', CONTENT_TYPE_LATEST)
        if not self._target:
            msg = "No target parameter provided!"
            logging.error(msg)
            raise falcon.HTTPMissingParam('target')
        
        try:
            socket.gethostbyname(self._target)
        except socket.gaierror as excptn:
            msg = "Target does not exist in DNS: {0}".format(excptn)
            logging.error(msg)
            resp.status = falcon.HTTP_400
            resp.body = msg

        else:
            registry = AristaMetricsCollector(
                self._config,
                exclude=self._exclude,
                target=self._target,
                port=self._port
                )

            collected_metric = generate_latest(registry)
            resp.body = collected_metric
Esempio n. 11
0
    def param_in_body(self, req, spec, param):
        body = req.stream.read().decode('utf-8')
        schema = spec.get('schema')
        name = param.get('name')
        type_ = schema.get('type')
        value = body

        if param.get('required') and body is None:
            raise falcon.HTTPMissingParam(name)
        default_func = lambda v: v if type_ is not None else None

        check_funcs = {
            'string': lambda v: str(v),
            'password': lambda v: str(v),
            'byte': lambda v: base64.b64decode(str(v)),
            'integer': lambda v: int(v),
            'long': lambda v: int(v),
            'float': lambda v: float(v),
            'double': lambda v: float(v),
            'boolean': lambda v: bool(v),
            'array': json_check,
            'object': json_check,
        }
        try:
            value = check_funcs.get(type_, default_func)(value)
            self.log.debug('param in body - name: {}, type: {}, value: {}'.format(name, type_, value))
        except ValueError as e:
            self.log.error_trace(
                'value error when check param in body - name: {}, type: {}, value: {}'.format(name, type_, value))
            raise falcon.HTTPInvalidParam('invalid param in body', name)
        return value
Esempio n. 12
0
    def on_post(self, req, resp, dataset_id, dataset_dto):
        """Return suggests to use with autocomplete

        This method will return suggestions to be used on frontend while users
        input the entity name.

        TODO: this should only return entities that exists on dataset, right
        now returns all possible entities.

        :param int dataset_id: The id of the dataset to autocomplete
        :param DTO dataset_dto: The Dataset DTO from dataset_id (from hook)
        :param str input: The input to autocomplete (from body)
        :returns: A list with entities and full text
        :rtype: Object
        """
        try:
            body = common_hooks.read_body_as_json(req)
            input_text = body['input']
        except KeyError as err:
            raise falcon.HTTPMissingParam("input")
        entity_dao = data_access.EntityDAO(dataset_dto.dataset_type,
                                           dataset_id)

        # Extract suggestion from elasticsearch
        suggestion = entity_dao.suggest_entity(input_text)

        # Return a response
        resp.body = json.dumps(suggestion)
        resp.content_type = 'application/json'
        resp.status = falcon.HTTP_200
Esempio n. 13
0
    def on_post(self, req: falcon.Request, resp: falcon.Response):
        """
        post /predict

        Predicts the sentiment of an input text using a model trained on movie reviews.
        Return value is a score beteen 0 and 1.
        Above 0.5 is considered positive sentiment.

        Inputs:
            text (string)
        Outputs:
            score (float)

        Example input:
        {
            "text": "this movie really sucked"
        }

        Example output:
        {
            "score": 0.1
        }
        """

        text = req.media.get("text")

        if text is None:
            raise falcon.HTTPMissingParam("text")

        if not isinstance(text, str):
            raise falcon.HTTPInvalidParam(
                f"expected a string, got a {type(text).__name__}", "text")

        resp.media = {"score": predict(text)}
Esempio n. 14
0
    def on_post(self, req, resp, queue):
        """
        Handles /collector/$queue post requests.
        Queues new data into the given queue located at the ActiveMQ instance.
        """
        # If the queue name is not an alphanumeric return error
        if not str(queue).isalnum():
            raise falcon.HTTPInvalidParam('Invalid queue name.', 'queue')

        # Create the message
        data = req.media.get('data')

        # Check if data is not empty
        if not data:
            raise falcon.HTTPMissingParam('data')

        # Send the message
        self.activemq_conn.send(queue,
                                json.dumps({
                                    'data': data
                                }).encode(), self.headers)

        # Answer the request
        resp.media = {'created': json.dumps(data), 'status': 'success'}

        # Created a new entry on the queue
        resp.status = falcon.HTTP_201
Esempio n. 15
0
    def on_get(self, req, resp, project, ident):
        query = build_query(req.env, project)
        if 'version' in req.params:
            version = req.params['version']
        else:
            raise falcon.HTTPMissingParam('version')

        if version == 'latest':
            version = query('latest')

        if 'family' in req.params:
            family = req.params['family']
        else:
            family = 'C'

        if family == 'B':  #DT compatible strings are quoted in the database
            ident = parse.quote(ident)

        symbol_definitions, symbol_references, symbol_doccomments = query(
            'ident', version, ident, family)
        resp.body = json.dumps({
            'definitions': [sym.__dict__ for sym in symbol_definitions],
            'references': [sym.__dict__ for sym in symbol_references],
            'documentations': [sym.__dict__ for sym in symbol_doccomments]
        })
        resp.status = falcon.HTTP_200
Esempio n. 16
0
    def parse_request(request, attr):
        """ returns mongo compatible query object, based on the query params provided """

        if 'lastN' in request.params.keys():
            try:
                limit_val = int(request.params['lastN'])
            except ValueError as e:
                raise falcon.HTTPInvalidParam('Must be integer.', 'lastN')
        elif 'hLimit' in request.params.keys():
            try:
                limit_val = int(request.params['hLimit'])
            except ValueError as e:
                raise falcon.HTTPInvalidParam('Must be integer.', 'hLimit')
        else:
            raise falcon.HTTPMissingParam('lastN')

        query = {'attr': attr, 'value': {'$ne': ' '}}
        ts_filter = {}
        if 'dateFrom' in request.params.keys():
            ts_filter['$gte'] = dateutil.parser.parse(
                request.params['dateFrom'])
        if 'dateTo' in request.params.keys():
            ts_filter['$lte'] = dateutil.parser.parse(request.params['dateTo'])
        if len(ts_filter.keys()) > 0:
            query['ts'] = ts_filter

        ls_filter = {"_id": False, '@timestamp': False, '@version': False}
        sort = [('ts', pymongo.DESCENDING)]

        return {
            'query': query,
            'limit': limit_val,
            'filter': ls_filter,
            'sort': sort
        }
Esempio n. 17
0
 def enforce(self, j, **kargs):
     for k in kargs.keys():
         if k not in j:
             raise falcon.HTTPMissingParam(k)
         if type(j[k]) != kargs[k]:
             raise falcon.HTTPInvalidParam(
                 "expected {} to be of type {}".format(k, kargs[k]), k)
Esempio n. 18
0
    def on_post(self, req: falcon.Request, resp: falcon.Response):
        """
        POST /api/translate/fren

        Translate french sentence to english (70 word limit).

        Input:  French text (UTF-8 string)
        Output: English text (UTF-8 string)

        Example input:
        {
            "fr": "Bonjour le monde!"
        }
        Example output:
        {
            "en": "Hello world!"
        }
        """

        fr_text = req.media.get("fr")

        if fr_text is None:
            raise falcon.HTTPMissingParam("fr")

        if not isinstance(fr_text, str):
            raise falcon.HTTPInvalidParam(
                f"expected a string, got a {type(fr_text).__name__}", "fr")

        resp.media = {"en": translate_fren(fr_text)}
Esempio n. 19
0
def UpdateACLSchema(**request_handler_args):
    req = request_handler_args['req']
    authUser(req, request_handler_args['resp'], ['createACLSchema'])
    doc = req.context['doc']
    try:
        schema = Schema.objects.get(
            {"_id": ObjectId(request_handler_args['uri_fields']['id'])})
    except InvalidId as e:
        raise falcon.HTTPMissing('Bad Request', str(e))
    except Schema.DoesNotExist:
        raise falcon.HTTPNotFound()
    else:
        try:
            schema.name = doc['name']
            schema.schema = doc['schema']
            schema.modified = datetime.datetime.now()
        except KeyError as e:
            raise falcon.HTTPMissingParam(str(e))
        try:
            schema.save()
        except schema.ValidationError as e:
            raise falcon.HTTPBadRequest("Validation Error", e.message)
        else:
            for project in Project.objects.raw({"acl_schema": schema._id}):
                project.save()
            schema.uri = req.uri + '/' + str(schema._id)
            request_handler_args['resp'].location = schema.uri
            request_handler_args['req'].context['result'] = schema.to_dict()
            req.context['logger'].info({
                'action':
                'updateACLSchema',
                'message':
                "'%s' ACLSchema with id of %s was updated successfully." %
                (schema.name, schema._id)
            })
Esempio n. 20
0
def CreateACLSchema(**request_handler_args):
    req = request_handler_args['req']
    authUser(req, request_handler_args['resp'], ['createACLSchema'])
    doc = req.context['doc']
    try:
        schema = Schema(name=doc['name'], schema=doc['schema'])
    except KeyError as e:
        raise falcon.HTTPMissingParam(str(e))
    else:
        try:
            schema.save()
        except Schema.ValidationError as e:
            raise falcon.HTTPBadRequest("Validation Error", e.message)
        else:
            request_handler_args['resp'].status = falcon.HTTP_201
            schema.uri = req.uri + '/' + str(schema._id)
            request_handler_args['resp'].location = schema.uri
            request_handler_args['req'].context['result'] = schema.to_dict()
            req.context['logger'].info({
                'action':
                'createACLSchema',
                'message':
                "'%s' ACLSchema with id of %s was created successfully." %
                (schema.name, schema._id)
            })
Esempio n. 21
0
    def on_get(self, req, resp):  #
        """Handles GET requests"""
        # if req.client_accepts_msgpack or "msgpack" in req.content_type:
        #     serializer = msgpack
        #     resp.content_type = "application/x-msgpack"
        # else:
        serializer = json
        resp.content_type = "application/json"

        image_url = req.get_param("imageUrl")
        if not image_url:
            print('get request didnt specify a url:' + str(req))
            raise falcon.HTTPMissingParam("imageUrl")
        else:
            print('hydra_tg falcon on_get got url ' + image_url)
            try:
                # thresholds = req.get_param("thresholds")
                # if thresholds:
                #     response = requests.get(image_url,thresholds=thresholds)
                # else:
                #     response = requests.get(image_url)
                response = requests.get(image_url)
                img_arr = cv2.imdecode(np.asarray(bytearray(response.content)),
                                       1)
                detected = self.detect(
                    img_arr, url=image_url)  #url being sent for logging
                self.write_log(image_url, detected)
                resp.data = serializer.dumps({"data": detected})
                resp.status = falcon.HTTP_200
            except:
                raise falcon.HTTPBadRequest("Something went wrong :(",
                                            traceback.format_exc())
    def delete_announcement(self,
                            announcement_id: int,
                            force_delete=False) -> bool:
        """delete announcement.
        Args:
            announcement_id ([int]): announcement id.
        Returns:
            [bool]: True
        """
        if announcement_id is None:
            raise falcon.HTTPMissingParam("announcement id")
        try:
            announcement_name_search = self._get_announcement_key_name_by_id(
                announcement_id, raise_error=not force_delete)
        except falcon.HTTPServiceUnavailable as e:
            falcon.falcon.HTTPServiceUnavailable(
                title=e.title,
                description=
                "Add force delete to dismiss this error, and delete same id announcements."
            )

        for name in announcement_name_search:
            self.redis_announcement.delete(name)

        return True
Esempio n. 23
0
    def on_post(self, req, resp):
        try:
            fromAccNum = req.get_param('fromAccNum')
            toAccNum = req.get_param('toAccNum')
            amount = req.get_param('amount')
        except KeyError:
            raise falcon.HTTPMissingParam(
                'Missing fromAccNum, toAccNum or amount',
                'fromAccNum, toAccNum and amount are required.')
        try:
            url = PAYMENT_SERVICE_URL + 'pay'
            payload = {
                'fromAccNum': fromAccNum,
                'toAccNum': toAccNum,
                'amount': amount
            }
            res = requests.post(url, json=payload)

            if res.status_code != codes.ok:
                raise NotFound("Cannot execute payment from " + \
                           "%s to %s amount %s, resp %s, status code %s" \
                           % (fromAccNum, toAccNum, amount, res.text,
                              res.status_code))
            else:
                resp.context = res.json()
                resp.status = falcon.HTTP_200
        except ConnectionError as e:
            raise HTTPBadRequest("Payment service connection error: %s." % e)
Esempio n. 24
0
 def on_get(self, req, resp):
     try:
         key_id = req.params['id']
         if key_id == '':
             raise ImportError
     except ImportError:
         raise falcon.HTTPInvalidParam('Parameter cannot be blank', 'url')
     except:
         raise falcon.HTTPMissingParam(param_name='id (ID of video)')
     with open("yte-logs.json", "r+") as logs_file:
         logs = json.load(logs_file)
         logs_file.close
     if key_id in logs:
         resp.content_type = 'json'
         resp.status = falcon.HTTP_200
         resp.body = json.dumps(logs[key_id])
         if logs[key_id]['status'] != '200 OK':
             Process(target=self.main, args=(key_id, )).start()
     else:
         check_vid = YouTube('https://www.youtube.com/watch?v=' + key_id)
         if int(check_vid.length) > 600:
             raise falcon.HTTPFailedDependency(
                 description='Video is more than 10 mins long')
         log_create(key_id)
         Process(target=self.main, args=(key_id, )).start()
         resp.content_type = 'json'
         resp.status = falcon.HTTP_200
         body = {
             'response': 'Process started, GET request again to see status.'
         }
         resp.body = json.dumps(body)
Esempio n. 25
0
    def param_in_path(self, matched_uri, param):
        type_ = param.get('type')
        name = param.get('name')

        value = matched_uri.groupdict().get(name)
        self.log.debug(value)
        default_func = lambda v: v if type_ is not None else None
        check_funcs = {
            'string': lambda v: str(v),
            'password': lambda v: str(v),
            'byte': lambda v: base64.b64decode(str(v)),
            'integer': lambda v: int(v),
            'long': lambda v: int(v),
            'float': lambda v: float(v),
            'double': lambda v: float(v),
            'boolean': lambda v: bool(v),
        }
        if param.get('required') and value is None:
            raise falcon.HTTPMissingParam(name)
        try:
            value = check_funcs.get(type_, default_func)(value)
            self.log.debug(
                'param in path - name: {}, type: {}, value: {}'.format(
                    name, type_, value))
        except ValueError as e:
            self.log.error_trace(
                'value error when check param in path - name: {}, type: {}, value: {}'
                .format(name, type_, value))
            raise falcon.HTTPInvalidParam('invalid param in path', name)
        return value
Esempio n. 26
0
    def param_in_query(self, req, param):
        name = param.get('name')
        type_ = param.get('type')

        default_func = lambda p: req.get_param(p
                                               ) if type_ is not None else None

        check_funcs = {
            'string': lambda p: req.get_param(p),
            'password': lambda p: req.get_param(p),
            'byte': lambda p: base64.b64decode(req.get_param(p)),
            'integer': lambda p: req.get_param_as_int(p),
            'long': lambda p: req.get_param_as_int(p),
            'float': lambda p: float(req.get_param(p)),
            'double': lambda p: float(req.get_param(p)),
            'array': lambda p: req.get_param_as_dict(p),
            'object': lambda p: req.get_param_as_dict(p),
            'boolean': lambda p: req.get_param_as_bool(p),
        }
        value = None
        try:
            value = check_funcs.get(type_, default_func)(name)
            self.log.debug(
                'param in query - name: {}, type: {}, value: {}'.format(
                    name, type_, value))
        except ValueError as e:
            self.log.error_trace(
                'value error when check param in query - name: {}, type: {}, value: {}'
                .format(name, type_, value))
            raise falcon.HTTPInvalidParam('invalid param in query', name)
        if param.get('required') and value is None:
            raise falcon.HTTPMissingParam(name)
        return value
Esempio n. 27
0
    def on_post(self, req, resp, user_id=None):
        """Handles POST requests. (POST: /users)"""

        # TODO: need to check email isn't aleady in the db
        # sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) UNIQUE constraint failed: users.email
        logger.info('POST /users')

        email = req.media['email']
        if self.get_user_by_email(email):
            raise falcon.HTTPBadRequest(
                "Email in use",
                "The email entered is already in use. Please use a different email"
            )

        try:
            new_user = User(
                first_name=req.media['first_name'],
                last_name=req.media['last_name'],
                email=req.media['email'],
            )
        except (TypeError, KeyError) as e:
            split_str = str(e).split(':')
            missing_params = split_str[1] if len(
                split_str) > 1 else split_str[0]
            missing_params = missing_params.strip().replace("'", "")

            raise falcon.HTTPMissingParam(missing_params)

        if new_user:
            self.session.add(new_user)
            self.session.commit()
            resp.status = falcon.HTTP_CREATED
            resp.media = new_user.as_dict()
Esempio n. 28
0
def read_pair_list(req, resp, resource, params):
    try:
        body = common_hooks.read_body_as_json(req)

        if "distance" not in body:
            raise falcon.HTTPMissingParam("distance")

        if not isinstance(body["distance"], list) and\
           len(body["distance"]) != 2:
            msg = ("The param 'distance' must contain a list of two"
                   "entities.")
            raise falcon.HTTPInvalidParam(msg, "distance")

        params["entities_pair"] = (body["distance"][0], body["distance"][1])

    except KeyError as err:
        raise falcon.HTTPMissingParam(err(str))
Esempio n. 29
0
    def check_mandatory_query_param(params, field, ftype=None):
        if (field not in params.keys()) or (len(params[field]) == 0):
            raise falcon.HTTPMissingParam(field)

        if ftype is not None:
            if not ftype(params[field]):
                raise falcon.HTTPInvalidParam(
                    '%s must be of type %s' % (field, ftype.__name__), field)
Esempio n. 30
0
 def _parse_strategy(cls, strategy_str: Optional[str]) -> Strategy:
     if not strategy_str:
         raise falcon.HTTPMissingParam("strategy")
     strategy = strategies.from_name(strategy_str)
     if not strategy:
         raise falcon.HTTPInvalidParam(
             f"strategy must be one of: {', '.join(get_all_strategies().keys())}",
             "strategy")
     return strategy