Пример #1
0
    def on_put(self, req: falcon.Request, resp: falcon.Response,
               username: str):
        try:
            user = User.get(username=username)

            if not req.context[
                    "user"].is_admin and req.context["user"].id != user.id:
                raise falcon.HTTPForbidden(
                    "Forbidden", "Insufficient privileges for operation.")

            user.generate_token()
            user.save()

            resp.media = {"token": user.token}

        except DoesNotExist:
            raise falcon.HTTPNotFound()
Пример #2
0
 def on_get(self, req: falcon.Request, res: falcon.Response):
     where = "WHERE [campaign_id] = ? AND (is_public=1 OR creator_id=?)"
     where_args = [
         req.context['user']['campaign'], req.context['user']['id']
     ]
     if req.params.get("type", None) is not None:
         where += " AND [type] = ?"
         where_args.append(req.params.get("type"))
     c = self._db.cursor()
     rows = c.execute(
         """SELECT {} FROM [place] {}""".format(
             ", ".join(f"[{field}]" for field in PlaceModel.fields), where),
         where_args).fetchall()
     places = []
     for row in rows:
         places.append(PlaceModel.from_db(row).to_summary_dict())
     res.media = places
Пример #3
0
 def on_get(self, req: Request, resp: Response):
     """Hello world
     ---
     description: Get a greeting to the world
     tags:
     - Test
     responses:
         200:
             description: Greeting to the world
             content:
                 application/json:
                     schema:
                         type: string
     """
     doc = {'message': 'Hello world'}
     resp.media = doc
     resp.status = falcon.HTTP_OK
Пример #4
0
    def get_cached_response(self, resp: Response, key: str) -> bool:
        cache_for_seconds = self.context.config.status_cache_seconds
        resp.set_header('Cache-Control', f'public,max-age={cache_for_seconds}')

        now = datetime.utcnow()
        if self.SIMPLE_CACHE.get(key) is not None:
            if now < self.SIMPLE_CACHE[key].expire_time:
                if self.context.config.debug:
                    self.context.logger.debug(
                        f'Returned cached response for {key}'
                        f' {now} < {self.SIMPLE_CACHE[key].expire_time}')
                resp.media = self.SIMPLE_CACHE[key].data
                resp.set_header(
                    'Expires', self.SIMPLE_CACHE[key].expire_time.strftime(
                        "%a, %d %b %Y %H:%M:%S UTC"))
                return True
        return False
 def on_get(
     self,
     _,
     resp: falcon.Response,
     genre: str,
     category: str,
     index: str,
     stage: str,
     name: str,
 ) -> None:
     chapter_id = create_chapter_id(genre, category, index, stage, name)
     manuscripts = [
         manuscript
         for manuscript in self._corpus.find_manuscripts(chapter_id)
         if not manuscript.colophon.is_empty
     ]
     resp.media = ColophonSchema().dump(manuscripts, many=True)
Пример #6
0
 def and_the_kitchen_sink(req: Request, res: Response):
     """
     Handle all request with their payload.
     """
     res.media = {
         "path": req.path,
         "params": req.params,
         "method": req.method,
         "headers": req.headers,
         "query": req.query_string,
         "payload": json.loads(req.bounded_stream.read() or "{}"),
         "tags": {
             name: value
             for name, value in environment.items()
             if name.startswith("SERVICE_")
         },
     }
 def on_post(
     self,
     req: falcon.Request,
     resp: falcon.Response,
     genre: str,
     category: str,
     index: str,
     stage: str,
     name: str,
 ) -> None:
     chapter_id = create_chapter_id(genre, category, index, stage, name)
     updated_chapter = self._corpus.update_manuscript_lemmatization(
         chapter_id,
         CorpusLemmatizationsSchema().load(req.media)["lemmatization"],
         req.context.user,
     )
     resp.media = ApiChapterSchema().dump(updated_chapter)
Пример #8
0
 def on_get(self, req: falcon.Request, res: falcon.Response, faction_id,
            relation_type):
     self.validate_req(req, faction_id, relation_type)
     relation = CharacterFactionRelation()
     rows = relation.find_all(self._db, req, "faction_id", faction_id)
     relations = []
     c = self._db.cursor()
     for row in rows:
         model = CharacterFactionRelation.model.from_db(row)
         row = c.execute(
             f"SELECT [name] FROM {relation.this.table_name} WHERE id=?",
             (model.character_id, )).fetchone()
         model.primary_id = faction_id
         model.relation_name = row[0]
         model.relation_id = model.character_id
         relations.append(model.to_summary_dict())
     res.media = relations
Пример #9
0
    def on_post(self, req: falcon.Request, resp: falcon.Response,
                ip_list_name: str):
        ip_list = IPList.get_or_404(IPList.name == ip_list_name)

        ips = req.media.get("ips")
        existing_ips = ListItem.select().where(ListItem.ip.in_(ips))

        existing_ips_list = [x.ip for x in list(existing_ips)]
        new_ips_list = list(set(ips) - set(existing_ips_list))

        ListItem.insert_many([(x, ) for x in new_ips_list],
                             fields=[ListItem.ip]).execute()

        list_ips = (ListItem.select().join(IPListItem).join(IPList).where(
            (IPList.id == ip_list.id), (ListItem.ip.in_(existing_ips_list))))
        list_ips_list = [x.ip for x in list(list_ips)]
        new_list_ips_list = list(set(ips) - set(list_ips_list))

        note = req.media.get("note", None)
        if note:
            note = note.strip()
        ip_list_items = []
        for list_item in ListItem.select().where(
                ListItem.ip.in_(new_list_ips_list)):
            ip_list_items.append(
                (ip_list, list_item, req.context["user"], note))

        IPListItem.insert_many(
            ip_list_items,
            fields=[
                IPListItem.ip_list,
                IPListItem.ip,
                IPListItem.added_by,
                IPListItem.note,
            ],
        ).execute()

        if len(new_ips_list) > 0 or len(new_list_ips_list) > 0:
            resp.status = falcon.HTTP_201

        resp.media = {
            "requested_ips": ips,
            "created_ips": new_ips_list,
            "ips_added_to_list": new_list_ips_list,
        }
Пример #10
0
    def on_get(self, req: falcon.Request, resp: falcon.Response):
        image_url = req.get_param("image_url", required=True)
        models: List[str] = req.get_param_as_list("models", required=True)

        available_models = ObjectDetectionModelRegistry.get_available_models()

        for model_name in models:
            if model_name not in available_models:
                raise falcon.HTTPBadRequest(
                    "invalid_model",
                    "unknown model {}, available models: {}"
                    "".format(model_name, ", ".join(available_models)),
                )

        output_image = req.get_param_as_bool("output_image")

        if output_image is None:
            output_image = False

        if output_image and len(models) != 1:
            raise falcon.HTTPBadRequest(
                "invalid_request",
                "a single model must be specified with the `models` parameter "
                "when `output_image` is True",
            )

        image = get_image_from_url(image_url, session=http_session)

        if image is None:
            logger.info("Could not fetch image: {}".format(image_url))
            return

        predictions = {}

        for model_name in models:
            model = ObjectDetectionModelRegistry.get(model_name)
            result = model.detect_from_image(image, output_image=output_image)

            if output_image:
                image_response(result.boxed_image, resp)
                return
            else:
                predictions[model_name] = result.to_json()

        resp.media = {"predictions": predictions}
Пример #11
0
    def on_post(self, req: falcon.Request, resp: falcon.Response) -> None:
        """
        Evaluate Python code and return stdout, stderr, and the return code.

        The return codes mostly resemble those of a Unix shell. Some noteworthy cases:

        - None
            The NsJail process failed to launch
        - 137 (SIGKILL)
            Typically because NsJail killed the Python process due to time or memory constraints
        - 255
            NsJail encountered a fatal error

        Request body:

        >>> {
        ...     "input": "print(1 + 1)"
        ... }

        Response format:

        >>> {
        ...     "stdout": "2\\n",
        ...     "returncode": 0
        ... }

        Status codes:

        - 200
            Successful evaluation; not indicative that the input code itself works
        - 400
           Input's JSON schema is invalid
        - 415
            Unsupported content type; only application/JSON is supported
        """
        code = req.media["input"]

        try:
            result = self.nsjail.python3(code)
        except Exception:
            log.exception(
                "An exception occurred while trying to process the request")
            raise falcon.HTTPInternalServerError

        resp.media = {"stdout": result.stdout, "returncode": result.returncode}
Пример #12
0
 def on_get(self, req: falcon.Request, res: falcon.Response, character_id):
     """ Get a single character record, by id """
     c = self._db.cursor()
     row = c.execute("""
     SELECT [id], [name], [race], [level], [description], [primary_class], [primary_class_level], [secondary_class], 
     [secondary_class_level], is_pc, attributes_public, creator_id, alignment, attr_str_1, attr_dex_2, attr_con_3, 
     attr_int_4, attr_wis_5, attr_cha_6, attr_stats_other, is_public, sheet_url, notes
     FROM character
     WHERE id = ? AND (is_public = 1 OR creator_id = ?)
     """, (character_id, req.context['user']['id'])).fetchone()
     if not row:
         raise falcon.HTTPNotFound(title="No character was found with id {} or unauthorized".format(character_id))
     character = {
         'id': row[0],
         'name': row[1],
         'race': row[2],
         'level': row[3],
         'description': row[4],
         'class': row[5],
         'class_level': row[6],
         'secondary_class': row[7],
         'secondary_class_level': row[8],
         'is_pc': bool(row[9]),
         'creator_id': row[11]
     }
     if row[10] or row[11] == req.context['user']['id']:
         character.update({
             'attributes_public': bool(row[10]),
             'alignment': row[12],
             'str': row[13],
             'dex': row[14],
             'con': row[15],
             'int': row[16],
             'wis': row[17],
             'cha': row[18],
             'attr_stats_other': row[19],
         })
     if row[11] == req.context['user']['id']:
         character.update({
             "is_public": bool(row[20]),
             "sheet_url": row[21],
             "notes": row[22]
         })
     res.media = character
     res.status = falcon.HTTP_OK
Пример #13
0
    def on_get(self,
               req: falcon.Request,
               resp: falcon.Response,
               ip: str = None):
        if ip is None:
            raise falcon.HTTPNotFound()

        with geoip2.database.Reader(self.asn_path) as reader:
            try:
                lookup = reader.asn(ip)
                resp.media = {
                    "ip": lookup.ip_address,
                    "asn_number": lookup.autonomous_system_number,
                    "asn_org": lookup.autonomous_system_organization,
                }
            except geoip2.errors.AddressNotFoundError:  # pragma: no cover
                raise falcon.HTTPBadRequest("Bad Request",
                                            "No response for query.")
Пример #14
0
    def on_post(self, req: falcon.Request, resp: falcon.Response):

        if User.select().where(User.is_admin).count() > 0:
            raise falcon.HTTPBadRequest("Bad Request",
                                        "App already initialized.")

        token = create_user(
            username=req.media.get("username"),
            password=req.media.get("password"),
            is_admin=True,
        )

        resp.status = falcon.HTTP_201
        resp.media = {
            "status": "Success",
            "token": token,
            "message": "First admin user created.",
        }
Пример #15
0
    def on_get(self, request: Request, response: Response) -> None:
        well_name = request.params.get('wellname')
        search_request_data = {
            'fulltext': well_name,
            'metadata': {
                'resource_type': [
                    'master-data/Well', 'work-product-component/WellLog',
                    'work-product-component/WellborePath'
                ]
            },
            'facets': ['resource_type']
        }

        search_result = requests.request('post',
                                         '%s/indexSearch' % API_BASE_URL,
                                         json=search_request_data)
        response.media = self.get_response_from_search_result(
            search_result.json().get('results', []))
Пример #16
0
 def on_get(self, req: Request, resp: Response):
     resp.media = {
         'newNonce': self.url_for('new-nonce'),
         'newAccount': self.url_for('new-account'),
         'newOrder': self.url_for('new-order'),
         # If the ACME server does not implement pre-authorization it MUST omit the 'newAuthz' field
         'newAuthz': self.url_for('new-authz'),
         'revokeCert': self.url_for('revoke-cert'),
         'keyChange': self.url_for('key-change'),
         # meta optional
         # 'meta': {
         # 'termsOfService': 'https://example.com/acme/terms/2017-5-30',
         # 'website': 'https://www.example.com/',
         # 'caaIdentities': ['example.com'],
         # 'externalAccountRequired': False
         # }
         # TODO:    Link: <https://example.com/acme/directory>;rel="index"
     }
Пример #17
0
    def on_get(self, req: falcon.Request, resp: falcon.Response):
        count: int = req.get_param_as_int("count", min_value=1, default=25)
        model_name: Optional[str] = req.get_param("model_name")
        type_: Optional[str] = req.get_param("type")
        model_version: Optional[str] = req.get_param("model_version")
        server_domain: Optional[str] = req.get_param("server_domain")
        barcode: Optional[str] = req.get_param("barcode")
        min_confidence: Optional[float] = req.get_param_as_float(
            "min_confidence")
        random: bool = req.get_param_as_bool("random", default=True)

        where_clauses = []

        if model_name is not None:
            where_clauses.append(ImagePrediction.model_name == model_name)

        if model_version is not None:
            where_clauses.append(
                ImagePrediction.model_version == model_version)

        if type_ is not None:
            where_clauses.append(ImagePrediction.type == type_)

        if server_domain:
            where_clauses.append(ImageModel.server_domain == server_domain)

        if min_confidence is not None:
            where_clauses.append(
                ImagePrediction.max_confidence >= min_confidence)

        if barcode is not None:
            where_clauses.append(ImageModel.barcode == barcode)

        query = ImagePrediction.select().join(ImageModel)

        if where_clauses:
            query = query.where(*where_clauses)

        if random:
            query = query.order_by(peewee.fn.Random())

        query = query.limit(count)
        items = [item.to_dict() for item in query.iterator()]
        resp.media = {"predictions": items}
Пример #18
0
 def on_get(self, req: falcon.Request, res: falcon.Response,
            faction_id: str):
     """ GET a single faction """
     c = self._db.cursor()
     row = c.execute(
         """
     SELECT [id], [name], [description], external_file_name, is_public, campaign_id, creator_id FROM faction
     WHERE id=? AND (creator_id=? OR is_public=1)
     """, (faction_id, req.context['user']['id'])).fetchone()
     if not row:
         raise falcon.HTTPNotFound(
             title="No faction found with id {} or unauthorized".format(
                 faction_id))
     faction = FactionModel.from_db(row)
     if faction.external_file_name:
         with open(os.path.join(self._path,
                                faction.external_file_name)) as f:
             faction.rich_description = f.read()
     res.media = faction.to_dict()
Пример #19
0
    def on_post(self, req: falcon.Request, resp: falcon.Response,
                store_id: str, project_id: str, asset_id: str):
        validate_not_null(req.media, 'name')

        meta = self._controller.get_asset_meta(store_id=store_id,
                                               project_id=project_id,
                                               asset_id=asset_id)

        for field in OveAssetMeta.EDITABLE_FIELDS:
            if field in req.media:
                setattr(meta, field, req.media.get(field))

        self._controller.edit_asset_meta(store_id=store_id,
                                         project_id=project_id,
                                         asset_id=asset_id,
                                         meta=meta)

        resp.media = meta.to_public_json()
        resp.status = falcon.HTTP_200
 def on_post(
     self,
     req: falcon.Request,
     resp: falcon.Response,
     genre: str,
     category: str,
     index: str,
     stage: str,
     name: str,
 ) -> None:
     chapter_id = create_chapter_id(genre, category, index, stage, name)
     dto = ManuscriptDtoSchema().load(req.media)
     updated_chapter = self._corpus.update_manuscripts(
         chapter_id,
         dto["manuscripts"],
         tuple(dto["uncertain_fragments"]),
         req.context.user,
     )
     resp.media = ApiChapterSchema().dump(updated_chapter)
Пример #21
0
    def on_get(self, req: falcon.Request, resp: falcon.Response):
        barcode = req.get_param("barcode", required=True)
        deepest_only = req.get_param_as_bool("deepest_only", default=False)
        blacklist = req.get_param_as_bool("blacklist", default=False)
        model = ModelRegistry.get()
        predicted = model.predict_from_barcode(barcode,
                                               deepest_only=deepest_only)

        if predicted:
            if blacklist:
                predicted = filter_blacklisted_categories(predicted)

            categories = [{
                "category": category,
                "confidence": confidence
            } for category, confidence in predicted]

        categories = categories or []
        resp.media = {"categories": categories}
Пример #22
0
    def on_post(self, req: falcon.Request, resp: falcon.Response, ip: str = None):
        results = list()
        with geoip2.database.Reader(self.geo_path) as reader:
            for ip in req.media.get("ips", None):
                try:
                    lookup = reader.city(ip)
                    results.append(
                        {
                            "city": lookup.city.name,
                            "continent": lookup.continent.name,
                            "lat": lookup.location.latitude,
                            "lon": lookup.location.longitude,
                            "country": lookup.country.name,
                        }
                    )
                except geoip2.errors.AddressNotFoundError:  # pragma: no cover
                    raise falcon.HTTPBadRequest("Bad Request", "No response for query.")

        resp.media = results
Пример #23
0
 def on_post(self, req: falcon.Request, res: falcon.Response):
     id = generate_new_id()
     chars = [None] * self.length
     first_idx = randint(0, self.length - 7)
     second_idx = randint(first_idx + 3, self.length - 4)
     words = list(self.words)
     first = choice(words)
     second = choice(words)
     self._overwrite_merge(chars, first, first_idx)
     self._overwrite_merge(chars, second, second_idx)
     for i, each in enumerate(chars):
         if not each:
             self._try_random_letter(i, chars)
     c = self._db.cursor()
     c.execute(
         "INSERT INTO [captcha_tokens] ([id], [answer], [time]) VALUES (?, ?, ?)",
         (id, first + second, time.time()))
     self._db.commit()
     res.media = {"id": id, "question": "".join(chars)}
Пример #24
0
    def on_patch(self,
                 req: Request,
                 resp: Response,
                 *,
                 tag_id: str,
                 paper_id=None,
                 layer_id=None):
        session = Session(bind=SQL_ENGINE)
        layer_tag = self.tkb.get_layer_tag(session, tag_id)
        params = json.load(req.stream)

        resp.media = {"id": tag_id}

        if "name" in params:
            layer_tag.name = params["name"]
            resp.media["name"] = params["name"]

        session.commit()
        session.close()
Пример #25
0
 def on_get(self, req: falcon.Request, res: falcon.Response, place_id):
     """ GET a single place """
     c = self._db.cursor()
     row = c.execute(
         """
      SELECT {}
      FROM place
      WHERE id=? AND (creator_id=? OR is_public=1)
      """.format(",".join(f"[{field}]" for field in PlaceModel.fields)),
         (place_id, req.context['user']['id'])).fetchone()
     if not row:
         raise falcon.HTTPNotFound(
             title="No place found with id {} or unauthorized".format(
                 place_id))
     place = PlaceModel.from_db(row)
     if place.external_file_name:
         with open(os.path.join(self._path, place.external_file_name)) as f:
             place.rich_description = f.read()
     res.media = place.to_dict()
Пример #26
0
    def _db_user_to_response(self, req: Request, resp: Response,
                             db_user: ScimApiUser):
        location = self.url_for("Users", db_user.scim_id)
        meta = Meta(
            location=location,
            last_modified=db_user.last_modified,
            resource_type=SCIMResourceType.USER,
            created=db_user.created,
            version=db_user.version,
        )

        schemas = [SCIMSchema.CORE_20_USER]
        if db_user.profiles:
            schemas.append(SCIMSchema.NUTID_USER_V1)

        # Convert one type of Profile into another
        _profiles = {
            k: Profile(attributes=v.attributes, data=v.data)
            for k, v in db_user.profiles.items()
        }

        user = UserResponse(
            id=db_user.scim_id,
            external_id=db_user.external_id,
            name=Name(**asdict(db_user.name)),
            emails=[Email(**asdict(email)) for email in db_user.emails],
            phone_numbers=[
                PhoneNumber(**asdict(number))
                for number in db_user.phone_numbers
            ],
            preferred_language=db_user.preferred_language,
            groups=self._get_user_groups(req=req, db_user=db_user),
            meta=meta,
            schemas=list(
                schemas
            ),  # extra list() needed to work with _both_ mypy and marshmallow
            nutid_user_v1=NutidUserExtensionV1(profiles=_profiles),
        )

        resp.set_header("Location", location)
        resp.set_header("ETag", make_etag(db_user.version))
        resp.media = UserResponseSchema().dump(user)
    def on_get(
        self,
        _,
        resp: falcon.Response,
        genre: str,
        category: str,
        index: str,
        stage: str,
        name: str,
        number: str,
    ) -> None:
        chapter_id = create_chapter_id(genre, category, index, stage, name)

        try:
            line, manuscripts = self._corpus.find_line(chapter_id, int(number))
            schema = LineDetailsSchema(context={"manuscripts": manuscripts})
            resp.media = schema.dump(line)
        except (IndexError, ValueError) as error:
            raise NotFoundError(
                f"{chapter_id} line {number} not found.") from error
Пример #28
0
    def on_delete(self, req: Request, resp: Response, *, paper_id: str,
                  layer_id: str, bbx_id: str):
        assert bbx_id != ""

        session = Session(bind=SQL_ENGINE)
        paper = self.tkb.get_paper(session, paper_id)
        annot = paper.get_annotation_layer(layer_id)

        annot.delete_box(bbx_id)
        annot.save()

        resp.media = {"message": "success"}

        # refresh title.
        info = paper.get_annotation_info(layer_id)
        if info.class_ == "header":
            paper.title = "__undef__"

        session.commit()
        session.close()
Пример #29
0
 def on_get(self, req: falcon.Request, res: falcon.Response):
     """ Retrieve a list of all factions """
     c = self._db.cursor()
     rows = c.execute(
         """
     SELECT id, name, description, is_public, count(DISTINCT character_id) FROM (
         SELECT [id], [name], [description], [faction].[is_public], character_id FROM faction
         left outer JOIN character_faction cf on faction.id = cf.faction_id and cf.is_public = 1
         WHERE campaign_id = ? AND (faction.is_public = 1 OR faction.creator_id = ?)
     ) GROUP BY id, name, description, is_public;
     """, (req.context["user"]["campaign"], req.context["user"]["id"]))
     factions = []
     for row in rows:
         factions.append({
             "id": row[0],
             "name": row[1],
             "description": row[2],
             "is_public": row[3],
             "num_members": row[4]
         })
     res.media = factions
Пример #30
0
    def on_post(self, req: Request, resp: Response):
        """Exchange user credentials for a new token.
        
        The payload must contain the ``username`` and ``password`` fields.
        
        Raises
        ------
        falcon.HTTPUnauthorized
            If the given credentials are invalid.
        """

        username = req.media["username"]
        password = req.media["password"]

        if not self.db.check_user(username, password):
            raise falcon.HTTPUnauthorized("Invalid credentials.")

        token = str(uuid4())
        self.db.save_token(username, token)

        resp.media = {"token": token, "user": self.db.get_user(username)}