def add_foreign_keys(self, current_context, data, session, configurations):
        """Controls if the list of foreign keys is an existing foreign key data. How to use:
            The configurtations must like: [('foreign_key_at_target_context, target_context)]"""

        for config in configurations:
            try:
                if config[0] == 'page_id':
                    """If the post referenced by the page_id is not post_type of type term-page, return error."""

                    el = self.get_existing_foreing_id(data, config[0],
                                                      config[1], session, True)
                    if el and el.post_type and el.post_type.type != 'term-page':
                        raise BadRequestError('The Post_Type \'' +
                                              el.post_type.name +
                                              '\' of the parent post is \'' +
                                              el.post_type.type +
                                              '\' It must be \'term-page\'.')

                setattr(
                    current_context, config[0],
                    self.get_existing_foreing_id(data, config[0], config[1],
                                                 session))

            except Exception as e:
                raise BadRequestError(str(e))
Beispiel #2
0
    def raise_if_has_different_parent_reference(self, data, session,
                                                configurations):
        """Verify if the given data has the same foreign data that its parent. How to use:
            The configuration must like: [('parent_key','referenced_key', 'context_target')]"""

        errors = []
        for config in configurations:
            try:
                if config[0] in data and config[1] in data:
                    parent = session.query(getattr(
                        config[2],
                        config[1])).filter_by(id=int(data[config[0]])).first()
                    if parent:
                        if parent[0] != int(data[config[1]]):
                            errors.append(
                                'The ' + config[1] +
                                ' must be the same as your father\'s, witch is: '
                                + str(parent[0]) + '.')
                    else:
                        raise BadRequestError('The given ' +
                                              config[2].__tablename__ +
                                              ' was not found.')
                        break

            except Exception as e:
                raise BadRequestError(str(e))

        if errors:
            raise BadRequestError(errors)
    def add_foreign_keys(self, current_context, data, session, configurations):
        """Controls if the list of foreign keys is an existing foreign key data. How to use:
            The configurtations must like: [('foreign_key_at_target_context, target_context)]"""

        for config in configurations:
            try:
                setattr(current_context, config[0], None)

                if getattr(current_context,
                           'origin') == 'configuration' and config[
                               0] == 'user_id' and 'user_id' in data:
                    raise BadRequestError(
                        'If the \'origin\' is \'configuration\' you dont have to send the \'user_id\'.'
                    )

                if getattr(current_context, 'origin') == 'user' and config[
                        0] == 'configuration_id' and 'configuration_id' in data:
                    raise BadRequestError(
                        'If the \'origin\' is \'user\' you dont have to send the \'configuration_id\'.'
                    )

                setattr(
                    current_context, config[0],
                    self.get_existing_foreing_id(data, config[0], config[1],
                                                 session))

            except Exception as e:
                raise BadRequestError(str(e))
        def fn(session, taxonomy):
            if taxonomy.terms:
                raise BadRequestError(
                    'You cannot delete this Taxonomy because it has a related Term'
                )

            if taxonomy.post_types:
                raise BadRequestError(
                    'You cannot delete this Taxonomy because it has a related Post_Type'
                )

            session.delete(taxonomy)
            session.commit()
            return self.handle_success(None, None, 'delete', 'Taxonomy', id)
Beispiel #5
0
    def get(self, args):
        """Returns a list of data recovered from model.
            Before applies the received query params arguments."""

        fb = FilterBuilder(Field, args)
        fb.set_equals_filters(['type', 'grouper_id', 'post_id'])

        try:
            fb.set_and_or_filter('s', 'or', [{
                'field': 'name',
                'type': 'like'
            }, {
                'field': 'description',
                'type': 'like'
            }])
        except Exception as e:
            raise BadRequestError(str(e))

        self.set_protection_to_child_post(fb)
        query = self.session.query(Field).join(
            *self.joins,
            isouter=True).filter(*fb.get_filter()).order_by(*fb.get_order_by())
        result = Paginate(query, fb.get_page(), fb.get_limit())
        schema = FieldSchema(many=True,
                             exclude=self.get_exclude_fields(
                                 args, ['post', 'grouper']))
        return self.handle_success(result, schema, 'get', 'Field')
Beispiel #6
0
    def get(self, args):
        """Returns a list of data recovered from model.
            Before applies the received query params arguments."""

        fb = FilterBuilder(Configuration, args)
        fb.set_equals_filters(['language_id'])

        try:
            fb.set_and_or_filter('s', 'or', [{
                'field': 'title',
                'type': 'like'
            }, {
                'field': 'description',
                'type': 'like'
            }])
        except Exception as e:
            raise BadRequestError(str(e))

        query = self.session.query(Configuration).filter(
            *fb.get_filter()).order_by(*fb.get_order_by())
        result = Paginate(query, fb.get_page(), fb.get_limit())
        schema = ConfigurationSchema(many=True,
                                     exclude=self.get_exclude_fields(
                                         args, ['language', 'socials']))
        return self.handle_success(result, schema, 'get', 'Configuration')
    def get(self, args):
        """Returns a list of data recovered from model.
            Before applies the received query params arguments."""

        fb = FilterBuilder(Comment, args)
        fb.set_like_filters(['comment', 'origin_ip', 'origin_agent'])
        fb.set_equals_filters(
            ['status', 'parent_id', 'user_id', 'post_id', 'language_id'])

        try:
            fb.set_date_filter('created', date_modifier=args['date_modifier'])
            fb.set_between_dates_filter(
                'created',
                not_between=args['not_between'],
                compare_date_time_one=args['compare_date_time_one'],
                compare_date_time_two=args['compare_date_time_two'])
        except Exception as e:
            raise BadRequestError(str(e))

        query = self.session.query(Comment).filter(*fb.get_filter()).order_by(
            *fb.get_order_by())
        result = Paginate(query, fb.get_page(), fb.get_limit())
        schema = CommentSchema(
            many=True,
            exclude=self.get_exclude_fields(
                args, ['user', 'language', 'parent', 'children', 'post']))
        return self.handle_success(result, schema, 'get', 'Comment')
Beispiel #8
0
    def validate_before(self,
                        process,
                        data,
                        validator_context,
                        session,
                        id=None):
        """Validates the given data using the given validator before runs the given process."""

        if (data):
            validator = validator_context(data)
            if (validator.is_valid(id=id)):
                return process(session, data)
            else:
                raise BadRequestError(validator.get_errors())
        else:
            raise BadRequestError('No data sent.')
Beispiel #9
0
    def set_any_reference_as_null_to_delete(self, instance, request, session,
                                            configurations):
        """Sets the given foreign key at the given Model as None to allow delete the given instance.
            Note that this only occurs if the 'remove_foreign_key' passed by request param was equals 1.
            How to use: The configuration must like: [(foreign_key_at_target_context, target_context)]"""

        errors = []
        for config in configurations:
            try:
                if 'remove_foreign_keys' in request.args and request.args[
                        'remove_foreign_keys'] == '1':
                    filter = (getattr(config[1], config[0]) == instance.id, )
                    elements = session.query(config[1]).filter(*filter).all()
                    for element in elements:
                        setattr(element, config[0], None)
                else:
                    filter = (getattr(config[1], config[0]) == instance.id, )
                    element = session.query(getattr(
                        config[1], 'id')).filter(*filter).first()
                    if element:
                        errors.append('You cannot delete this ' +
                                      instance.__class__.__name__ +
                                      ' because it has a related ' +
                                      config[1].__tablename__)

            except Exception as e:
                errors.append(str(e))

        if errors:
            raise BadRequestError(errors)
Beispiel #10
0
    def get(self, args):
        """Returns a list of data recovered from model.
            Before applies the received query params arguments."""

        fb = FilterBuilder(Term, args)
        fb.set_like_filters(['parent_id', 'taxonomy_id', 'language_id'])

        try:
            fb.set_and_or_filter('s', 'or', [{
                'field': 'name',
                'type': 'like'
            }, {
                'field': 'display_name',
                'type': 'like'
            }, {
                'field': 'description',
                'type': 'like'
            }])
        except Exception as e:
            raise BadRequestError(str(e))

        query = self.session.query(Term).filter(*fb.get_filter()).order_by(
            *fb.get_order_by())
        result = Paginate(query, fb.get_page(), fb.get_limit())
        schema = TermSchema(
            many=True,
            exclude=self.get_exclude_fields(
                args, ['language', 'parent', 'children', 'taxonomy']))
        return self.handle_success(result, schema, 'get', 'Term')
Beispiel #11
0
    def get_authorized_passport(self,
                                from_where='Authorization',
                                verify_blacklist=True,
                                token_key='token'):
        """Get the authorized user based on the given token. This can come from Authorization or Request."""

        token: None

        if from_where == 'Authorization':
            token = request.headers.get('Authorization')

        elif from_where == 'Request':
            data = request.get_json()
            if token_key in data and data[token_key] != '':
                token = data[token_key]

        else:
            raise BadRequestError('Invalid resource origin.')

        if token:

            if verify_blacklist:
                blacklist = self.session.query(
                    Blacklist.id).filter_by(value=token).first()
                if blacklist:
                    raise NotAuthorizedError('Token revoked.')

            try:
                access = decode_token(token)
                if 'identity' in access:
                    identity = access['identity']
                    if 'id' in identity and 'login' in identity and 'role' in identity:
                        user = self.session.query(User).filter_by(
                            login=identity['login']).first()
                        if user:
                            return {'user': user, 'access': access}
                        else:
                            raise NotFoundError('No user found.')
                    else:
                        raise BadRequestError('Invalid identity.')
                else:
                    raise BadRequestError('Invalid Token.')
            except Exception as e:
                raise NotAuthorizedError('Token already expired.')
        else:
            raise NotAuthorizedError('No Token send.')
Beispiel #12
0
 def fn(session, term):
     if term.posts:
         raise BadRequestError(
             'You cannot delete this Term because it has a related Post.'
         )
     self.set_children_as_null_to_delete(term, Term, session)
     session.delete(term)
     session.commit()
     return self.handle_success(None, None, 'delete', 'Term', id)
Beispiel #13
0
    def raise_if_has_term_and_not_is_post_page(self, data, session):
        """Raise an error if the Post has terms but it does not is from a Post_Type with type 'post-page'"""

        if 'terms' in data and data['terms']:
            if 'post_type_id' in data and Checker().can_be_integer(data['post_type_id']):
                post_type = session.query(PostType.type).filter_by(id=int(data['post_type_id'])).first()
                if post_type and post_type[0]:
                    if post_type[0] != 'post-page':
                        raise BadRequestError('The Post_Type of the Post must be settled as type \'post-page\' to have Terms.')
Beispiel #14
0
        def fn(session, sector):

            if sector.menus:
                raise BadRequestError(
                    'You cannot delete this Sector because it has a related Menu.'
                )

            session.delete(sector)
            session.commit()
            return self.handle_success(None, None, 'delete', 'Sector', id)
Beispiel #15
0
            def fn(session, post):
                Helper().fill_object_from_data(post, data, ['name', 'title', 'description', 'status', 'is_protected', 'has_comments'])
                post.publish_on = Helper().get_null_if_empty(data['publish_on'])
                post.expire_on = Helper().get_null_if_empty(data['expire_on'])
                post.edited = Helper().get_current_datetime()
                self.add_foreign_keys(post, data, session, [('parent_id', Post), ('post_type_id', PostType), ('language_id', Language), ('user_id', User)])
                self.raise_if_has_term_and_not_is_post_page(data, session)
                self.edit_many_to_many_relationship('terms', post, data, Term, session)

                if post.parent_id and int(post.parent_id) == int(id):
                    raise BadRequestError('The Post cannot be parent of yourself.')

                session.commit()
                return self.handle_success(None, None, 'update', 'Post', post.id)
Beispiel #16
0
    def delete(self, id, request):
        """Deletes, if it is possible, the row whose id corresponding with the requested id."""

        if id == 1:
            raise BadRequestError(
                'The Primary configuration row cannot be deleted.')

        def fn(session, configuration):
            session.delete(configuration)
            session.commit()
            return self.handle_success(None, None, 'delete', 'Configuration',
                                       id)

        return self.run_if_exists(fn, Configuration, id, self.session)
            def fn(session, menu_item):
                Helper().fill_object_from_data(menu_item, data, ['type', 'behavior', 'url', 'title', 'order'])
                self.raise_if_has_different_parent_reference(data, session, [('parent_id', 'menu_id', MenuItem)])

                if 'target_id' in data and data['target_id'] != '':
                    menu_item.target_id = data['target_id']

                self.add_foreign_keys(menu_item, data, session, [('parent_id', MenuItem), ('menu_id', Menu)])

                if menu_item.parent_id and int(menu_item.parent_id) == int(id):
                    raise BadRequestError('The MenuItem cannot be parent of yourself.')

                session.commit()
                return self.handle_success(None, None, 'update', 'MenuItem', menu_item.id)
    def get(self, args):
        """Returns a list of data recovered from model.
            Before applies the received query params arguments."""

        fb = FilterBuilder(Variable, args)

        try:
            fb.set_and_or_filter('s', 'or', [{'field':'key', 'type':'like'}, {'field':'value', 'type':'like'}])
        except Exception as e:
            raise BadRequestError(str(e))

        query = self.session.query(Variable).filter(*fb.get_filter()).order_by(*fb.get_order_by())
        result = Paginate(query, fb.get_page(), fb.get_limit())
        schema = VariableSchema(many=True)
        return self.handle_success(result, schema, 'get', 'Variable')
Beispiel #19
0
    def add_foreign_keys_field_type(self,
                                    field_type,
                                    current_context,
                                    data,
                                    session,
                                    configurations,
                                    id=None):
        """Controls if the list of foreign keys is an existing foreign key data. How to use:
            The configurtations must like: [('foreign_key_at_target_context, target_context)]"""

        errors = []
        for config in configurations:
            try:
                if config[0] == 'field_id':
                    el = self.get_existing_foreing_id(data, config[0],
                                                      config[1], session, True)

                    if el:

                        if el.type != field_type:
                            errors.append(
                                'The Field referenced by the \'field_id\' is not configured as '
                                + field_type + '.')

                        if not id or (data['field_id'] !=
                                      current_context.field_id):
                            filter = (or_(FieldContent.field_id == el.id,
                                          FieldText.field_id == el.id,
                                          FieldFile.field_id == el.id), )
                            el_childs = session.query(
                                FieldContent.id, FieldFile.id,
                                FieldText.id).filter(*filter).first()

                            if el_childs:
                                errors.append(
                                    'The Field referenced by the \'field_id\' already has a field type.'
                                )

                setattr(
                    current_context, config[0],
                    self.get_existing_foreing_id(data, config[0], config[1],
                                                 session))
            except Exception as e:
                errors.append('Could not find the given foreign key \'' +
                              str(config[0]) + '\'')

        if errors:
            raise BadRequestError(errors)
Beispiel #20
0
            def fn(session, term):
                Helper().fill_object_from_data(term, data, [
                    'name', 'display_name', 'description', 'parent_id',
                    'page_id', 'taxonomy_id', 'language_id'
                ])
                self.add_foreign_keys(term, data, session,
                                      [('parent_id', Term), ('page_id', Post),
                                       ('language_id', Language),
                                       ('taxonomy_id', Taxonomy)])

                if term.parent_id and int(term.parent_id) == int(id):
                    raise BadRequestError(
                        'The Term cannot be parent of yourself.')

                session.commit()
                return self.handle_success(None, None, 'update', 'Term',
                                           term.id)
Beispiel #21
0
    def is_foreigners(self, configurations, session):
        """Verifies if is a foreigner on any given context at configuration, if so, return errors. How to use:
            The configuration must like: [(current_context, foreign_key_at_target_context, target_context)]"""

        errors = []
        for config in configurations:
            filter = (getattr(config[2],
                              config[1]) == getattr(config[0], 'id'), )
            element = session.query(getattr(config[2],
                                            'id')).filter(*filter).first()
            if element:
                errors.append('You cannot delete this ' +
                              config[0].__class__.__name__ +
                              ' because it has a related ' +
                              config[2].__tablename__)

        if errors:
            raise BadRequestError(errors)
Beispiel #22
0
    def add_foreign_keys(self, current_context, data, session, configurations):
        """Controls if the list of foreign keys is an existing foreign key data. How to use:
            The configurtations must like: [('foreign_key_at_target_context, target_context)]"""

        errors = []
        for config in configurations:
            try:
                el = self.get_existing_foreing_id(data, config[0], config[1],
                                                  session)
                setattr(
                    current_context, config[0],
                    self.get_existing_foreing_id(data, config[0], config[1],
                                                 session))
            except Exception as e:
                errors.append('Could not find the given foreign key \'' +
                              str(config[0]) + '\'')

        if errors:
            raise BadRequestError(errors)
            def fn(session, comment):
                Helper().fill_object_from_data(
                    comment, data,
                    ['comment', 'status', 'origin_ip', 'origin_agent'])
                self.raise_if_has_different_parent_reference(
                    data, session, [('parent_id', 'post_id', Comment),
                                    ('parent_id', 'language_id', Comment)])
                self.add_foreign_keys(comment, data, session,
                                      [('user_id', User), ('post_id', Post),
                                       ('language_id', Language),
                                       ('parent_id', Comment)])

                if comment.parent_id and int(comment.parent_id) == int(id):
                    raise BadRequestError(
                        'The Comment cannot be parent of yourself.')

                session.commit()
                return self.handle_success(None, None, 'update', 'Comment',
                                           comment.id)
Beispiel #24
0
    def get(self, args):
        """Returns a list of data recovered from model.
            Before applies the received query params arguments."""

        fb = FilterBuilder(Post, args)
        fb.set_equals_filters(['status', 'user_id', 'parent_id', 'post_type_id', 'language_id'])
        self.joins.append(FieldContent)
        self.joins.append(FieldText)

        if (args['term_id'] and args['term_id'] != '' and Checker().can_be_integer(args['term_id'])):
            fb.set_like_filter('term_id', joined=Term, joined_key='id')
            self.joins.append(Post.terms)

        try:
            fb.set_date_filter('created', date_modifier=args['date_modifier'])
            fb.set_between_dates_filter(
                'created', not_between=args['not_between'],
                compare_date_time_one=args['compare_date_time_one'],
                compare_date_time_two=args['compare_date_time_two']
            )
            fb.set_and_or_filter('s', 'or', [
                {'field': 'name', 'type': 'like'},
                {'field': 'title', 'type': 'like'},
                {'field': 'description', 'type': 'like'},
                {'field': 'content', 'type': 'like', 'kwargs': {'joined': FieldContent}},
                {'field': 'content', 'type': 'like', 'kwargs': {'joined': FieldText}}
            ])

            if not self.the_logged_user:
                fb.set_range_of_dates_filter()
                fb.filter += (Post.status == 'publish',)
            self.set_can_see_protected()
            if not self.can_see_protected:
                fb.filter += (Post.is_protected != True,)

        except Exception as e:
            raise BadRequestError(str(e))

        query = self.session.query(Post).join(*self.joins, isouter=True).filter(*fb.get_filter()).order_by(*fb.get_order_by())
        result = Paginate(query, fb.get_page(), fb.get_limit())
        schema = PostSchema(many=True, exclude=self.get_exclude_fields(args, [
            'user', 'language', 'parent', 'children', 'post_type', 'nests', 'groupers', 'terms']))
        return self.handle_success(result, schema, 'get', 'Post')
    def raise_if_has_identical_capability(self, data, session, id=None):	
        """Verifies if already exists another capability with exactly same values, if so, returns this."""	

        filter = (	
            Capability.type == data['type'],
            Capability.can_write == data['can_write'],	
            Capability.can_read == data['can_read'],	
            Capability.can_delete == data['can_delete'],
            Capability.only_themselves == data['only_themselves'],
        )

        if 'target_id' in data:	
            filter += (Capability.target_id == int(data['target_id']),)


        if id:	
            filter += (Capability.id != id,)	

        capability = session.query(Capability).filter(*filter).first()	

        if not capability:
            return capability
        else:
            raise BadRequestError('The capability ' + str(capability.id) + ' has exactly the same configurations.')
 def fn(session, capability):
     if capability.roles:
         raise BadRequestError('You cannot delete this Capability because it has a related Role.')
     session.delete(capability)
     session.commit()
     return self.handle_success(None, None, 'delete', 'Capability', id)