Esempio n. 1
0
 def get(self, cfs_id):
     """Get cfs details"""
     try:
         cfs = CfS.get(id=cfs_id)
     except CfS.DoesNotExist:
         abort(404, message='CfS not found')
     return cfs
Esempio n. 2
0
    def post(self, truck_sheet_id, order_sheet_id):
        """
        Publish a planning.

        Both the truck availability sheet and the order sheet cannot be used
        already in another planning. If that is the case, a 400 response will
        be returned.

        `Truck_sheet_id` and `order_sheet_id` can both be the primary key of
        the sheets, or `latest` to use the latest sheet.
        """
        truck_sheet = TruckSheet.query.get_sheet_or_404(truck_sheet_id)

        order_sheet = OrderSheet.query.get_sheet_or_404(order_sheet_id)

        # Check if either one of the sheet already has a planning
        if truck_sheet.planning is None and order_sheet.planning is None:
            # Create a new planning
            planning = Planning(truck_sheet.id, order_sheet.id,
                                current_user.id)
            db.session.add(planning)
            db.session.commit()
            return planning

        # One of the sheets is already used in a planning
        abort(400,
              message='Truck sheet or order sheet is already '
              'used in a published planning')
Esempio n. 3
0
    def get(self, params, creditorId):
        """Return a collection of creditor's recent log entries.

        The returned object will be a fragment (a page) of a paginated
        list. The paginated list contains recent log entries. The
        returned fragment, and all the subsequent fragments, will be
        sorted in chronological order (smaller `entryId`s go
        first).

        """

        n = current_app.config['APP_LOG_ENTRIES_PER_PAGE']
        try:
            log_entries, last_log_entry_id = procedures.get_log_entries(
                creditorId,
                count=n,
                prev=params['prev'],
            )
        except procedures.CreditorDoesNotExist:
            abort(404)

        if len(log_entries) < n:
            # The last page does not have a 'next' link.
            return {
                'uri': request.full_path,
                'items': log_entries,
                'forthcoming': f'?prev={last_log_entry_id}',
            }

        return {
            'uri': request.full_path,
            'items': log_entries,
            'next': f'?prev={log_entries[-1].entry_id}',
        }
Esempio n. 4
0
    def get(self, address_id):
        """Get address by ID"""

        address = Address.query.get(address_id)
        if address is None:
            abort(404, message='Item not found.')
        return address
Esempio n. 5
0
def on_stale_token():
    abort(
        401,
        message=gettext(
            "Unauthorized to access this resource without a valid and fesh api token.\n"
            "Request a new fresh api token from the login resource."),
    )
    def get(self, namespace: str, **kwargs: Any):
        if not namespace or not namespace.isdigit():
            abort(
                HTTPStatus.BAD_REQUEST,
                message=gettext(
                    "The requested namespace id has the wrong format!"),
            )
        namespace_id = int(namespace)
        found_namespace: Optional[Namespace] = Namespace.query.filter(
            Namespace.id == namespace_id).first()

        if found_namespace is None:
            abort(HTTPStatus.NOT_FOUND,
                  message=gettext("Namespace not found."))

        return ApiResponse(
            links=[
                ApiLink(
                    href=url_for(
                        "api-v1.NamespacesView",
                        _external=True,
                        **{"item-count": 50},
                        sort="name",
                    ),
                    rel=("first", "page", "up", "collection", "ont-namespace"),
                    resource_type="ont-namespace",
                    schema=url_for("api-v1.ApiSchemaView",
                                   schema_id="Namespace",
                                   _external=True),
                ),
                *nav_links_for_namespace(found_namespace),
                *action_links_for_namespace(found_namespace),
            ],
            data=namespace_to_namespace_data(found_namespace),
        )
Esempio n. 7
0
 def get(self, social_id):
     """Get social details"""
     try:
         social = Social.get(id=social_id)
     except Social.DoesNotExist:
         abort(404, message='No such social')
     return social
Esempio n. 8
0
    def post(self, data: typing.Dict):
        """用户登录

        登录成功的响应首部中会带有 Set-Cookie 字段,设置 cookie
        ---
        :param data:
        :return:
        """
        if current_user.is_authenticated:
            return current_user, 200

        # check 验证码
        # key = current_config.CAPTCHA_FORMAT.format(data['captcha_key'])
        # if redis.connection.get(key) != data['captcha_code']:
        #     abort(400, message="captcha error, please print the wright captcha code!")

        # 验证登录
        if data.get("username"):
            user = MainUser.query.filter_by(username=data['username']).first()
        elif data.get("email"):
            user = MainUser.query.filter_by(username=data['email']).first()
        else:
            abort(401, message='required either username or email!!!')
            return

        if user is not None \
                and user.check_password(data['password']):

            login_user(user, remember=data['remember_me'])

            return user
        else:
            abort(401, message='error username or password')
Esempio n. 9
0
 def get(self, id: UUID):
     """Get user by id"""
     try:
         user = service.get_user_by_id(id)
         return user
     except TupleNotFound:
         abort(404)
Esempio n. 10
0
 def delete(self, username: str):
     """Deletes an existing user"""
     try:
         user: Annotator = Annotator.objects.get(username=username)
         user.delete()
     except DoesNotExist:
         abort(404, message="User not found in database")
Esempio n. 11
0
    def delete(self, agenda_id):
        """Delete an Agenda [Protected]

        Args:
            new_data ([type]): [description]
            agenda_id (int): The Agenda id
        """

        user_id = get_jwt_identity()
        user = user_crud.get(user_id)
        agenda = agenda_crud.get(agenda_id)
        if not agenda:
            abort(404, message="Agenda does not exist")
        meeting_id = agenda_crud.get_meeting_id(agenda=agenda)
        if not user.is_superuser:
            meeting_id = agenda_crud.get_meeting_id(agenda=agenda)
            meeting = meeting_crud.get(meeting_id)
            if not meeting_crud.is_user_meeting(user_id=user_id,
                                                meeting=meeting):
                abort(
                    401,
                    message="You don't have permission to remove this agenda")
        meeting_crud.update_meeting_endtime(meeting_id, -(agenda.set_duration))
        agenda_crud.remove(agenda_id)
        return {'msg': 'Agenda Removed'}
Esempio n. 12
0
    def get(self, person_id):
        """Get person by ID"""

        person = Person.query.get(person_id)
        if person is None:
            abort(404, message='Item not found.')
        return person
Esempio n. 13
0
 def delete(self, person_id):
     """Delete pet"""
     person = Person.query.get(person_id)
     if person is None:
         abort(404, message='Item not found.')
     session.delete(person)
     session.commit()
Esempio n. 14
0
    def get(self, data):
        """获取赛文"""
        articles_query: BaseQuery = db.session.qeury(CompArticle) \
            .filter_by(platform=data["platform"]) \
            .join(CompArticle.group, aliased=True) \
            .filter(group_id=data['group_id'])

        if "comp_type" in data:
            articles_query = articles_query.filter_by(
                comp_type=data['comp_type'])

        mode = data['mode']
        date = data.get(
            "date",  # 默认使用当前日期
            datetime.datetime.now().date())
        if mode == "past":  # 查看历史赛文
            articles_query = articles_query.filter(CompArticle.date <= date)\
                .order_by(desc(CompArticle.date))
        elif mode == "future":  # 未开始的赛文
            articles_query = articles_query.filter(CompArticle.date >= date) \
                .order_by(asc(CompArticle.date))
        else:
            abort(400, message="'mode' must be 'past' or 'future'!")

        return articles_query
Esempio n. 15
0
 def _check_path_params(self, namespace: str):
     if not namespace or not namespace.isdigit():
         abort(
             HTTPStatus.BAD_REQUEST,
             message=gettext(
                 "The requested namespace id has the wrong format!"),
         )
Esempio n. 16
0
 def patch(self, data: Any, id: UUID):
     """Update user by id"""
     try:
         user = service.update_by_id(id, data)
         return user
     except TupleNotFound:
         abort(404)
    def post(self, namespace_data):
        existing: bool = (DB.session.query(literal(True)).filter(
            Namespace.query.filter(
                Namespace.name == namespace_data["name"]).exists()).scalar())
        if existing:
            abort(
                400,
                f"Name {namespace_data['name']} is already used for another Namespace!",
            )
        namespace = Namespace(**namespace_data)
        DB.session.add(namespace)
        DB.session.commit()

        namespace_link = namespace_to_namespace_data(namespace).self
        namespace_data = namespace_to_api_response(namespace)

        return ApiResponse(
            links=[namespace_link],
            embedded=[namespace_data],
            data=NewApiObject(
                self=ApiLink(
                    href=url_for("api-v1.NamespacesView", _external=True),
                    rel=(
                        "create",
                        "post",
                        "ont-namespace",
                    ),
                    resource_type="new",
                ),
                new=namespace_link,
            ),
        )
Esempio n. 18
0
 def get(self, pagination, year):
     """List ticket posts"""
     try:
         event = Event.get(year=year)
     except Event.DoesNotExist:
         abort(404, message='Event does not exist')
     return paginate(event.tickets, pagination)
 def _check_item_circle(
     self,
     item_target: TaxonomyItem,
     item_source: TaxonomyItem,
     original_target: Optional[TaxonomyItem] = None,
 ):
     """Check for a path from target to source which would form a circular dependency. Abort if such a path is found!"""
     if original_target is None:
         original_target = item_target
     relation: TaxonomyItemRelation
     for relation in item_target.current_related:
         if relation.taxonomy_item_target.deleted_on is not None:
             continue  # exclude deleted items as targets
         if relation.taxonomy_item_target_id == item_source.id:
             abort(
                 HTTPStatus.CONFLICT,
                 message=gettext(
                     "Cannot add a relation from %(target)s to %(source)s as it would create a circle!",
                     target=original_target.name,
                     source=item_source.name,
                 ),
             )
         else:
             self._check_item_circle(
                 item_target=relation.taxonomy_item_target,
                 item_source=item_source,
                 original_target=original_target,
             )
Esempio n. 20
0
 def get(self, year):
     """Get event details"""
     try:
         event = Event.get(year=year)
     except Event.DoesNotExist:
         abort(404, message='No such event')
     return event
Esempio n. 21
0
 def delete(self, item_id):
     """Delete an event"""
     item = Event.get_by_id(item_id)
     if item is None:
         abort(404)
     blp.check_etag(item, EventSchema)
     item.delete()
Esempio n. 22
0
 def get(self, pagination, year):
     """Get list of halls"""
     try:
         event = Event.get(year=int(year))
     except Event.DoesNotExist:
         abort(404, message='No such event')
     return paginate(event.halls, pagination)
Esempio n. 23
0
def on_user_load_error(identity: str):
    abort(
        401,
        message=gettext(
            "The user with the id '%(userid)s' could not be loaded.",
            userid=identity),
    )
Esempio n. 24
0
 def get(self, hall_id):
     """Get hall details"""
     try:
         hall = Hall.get(id=hall_id)
     except Hall.DoesNotExist:
         abort(404, message='No such hall')
     return hall
Esempio n. 25
0
 def get(self, talk_id):
     """Get talk details"""
     try:
         talk = Talk.get(id=talk_id)
     except Talk.DoesNotExist:
         abort(404, message='No such talk')
     return talk
Esempio n. 26
0
 def inner(*args: Any, **kwargs: Any) -> Any:
     if not all(
             permission in [p.name for p in current_user.permissions]
             for permission in permissions):
         logger.error(f"{current_user.email}不具备{permissions}")
         abort(403, message="禁止访问")
     return func(*args, **kwargs)
Esempio n. 27
0
    def get(self, new_data):
        """[Admin] Reveal of users in the system - [PROTECTED]

        Args:
            Skip (int): number of entries to skip
            [defaults to '0' if not provided],
            Limit (int): the limit of number of data released
            [defaults to '100' if not provided]
        """

        user_id = get_jwt_identity()
        user = user_crud.get(user_id)
        if not user.is_superuser:
            abort(401,
                  message="You do not have permission to view this endpoint")
        if 'limit' in new_data and 'skip' in new_data:
            users = user_crud.get_multi(skip=new_data['skip'],
                                        limit=new_data['limit'])
        elif 'limit' in new_data:
            users = user_crud.get_multi(limit=new_data['limit'])
        elif 'skip' in new_data:
            users = user_crud.get_multi(skip=new_data['skip'])
        else:
            users = user_crud.get_multi()

        return users
Esempio n. 28
0
 def get(self):
     root = current_app.config['PROJECT_ROOT']
     key_path = f'{root}/secret.key'
     with open(key_path, 'rb') as key_file:
         key = key_file.read()
         f = Fernet(key)
         data = json.loads(get_jwt_identity())
         uid = data['uid']
         domain = data['domain']
         username = f'{uid}@{domain}'
         password = f.decrypt(data['password'].encode()).decode('utf-8')
     folders = SortedDict()
     try:
         imap = imaplib.IMAP4_SSL(host, port)
     except gaierror:
         abort(404, message=f'Host {host} not found!')
     try:
         resp, data = imap.login(username, password)
     except imaplib.IMAP4.error:
         abort(403, message='Login failed!')
     if resp == 'OK':
         resp, data = imap.list('""', '*')
         if resp == 'OK':
             for mbox in data:
                 parse_mailbox(bytes.decode(mbox), folders)
     return {'folders': folders}
Esempio n. 29
0
 def get(self, slug):
     '''Get blog post'''
     try:
         blogPost = BlogPost.get(slug=slug)
     except BlogPost.DoesNotExist:
         abort(404, message='Blog post not found')
     return blogPost
Esempio n. 30
0
 def get(self, pagination, year):
     """Get list of sponsors"""
     try:
         event = Event.get(year=int(year))
     except Event.DoesNotExist:
         abort(404, message='Event not found')
     return paginate(event.cfs, pagination)