Пример #1
0
 def command(self):
     self._load_config()
     cmd = self.args[0] if len(self.args) else 'list'
     if cmd == 'list':
         args = self.args
         if 'list' in args:
             del args[args.index('list')]
         self.list(args)
         return
     
     assert len(self.args) == 4, "Not enough parameters!" + RIGHTS_HELP
     cmd, subj, role, obj = self.args
     subj = self.find_subject(unicode(subj))
     role = self.ensure_role(unicode(role))
     objs = self.find_objects(unicode(obj))
     for obj in objs:
         try:
             if cmd == 'make':
                 if isinstance(subj, model.User):
                     model.add_user_to_role(subj, role, obj)
                 elif isinstance(subj, model.AuthorizationGroup):
                     model.add_authorization_group_to_role(subj, role, obj)
                 print "made", 
             elif cmd == 'remove':
                 if isinstance(subj, model.User):
                     model.remove_user_from_role(subj, role, obj)
                 elif isinstance(subj, model.AuthorizationGroup):
                     model.remove_authorization_group_from_role(subj, role, obj)
                 print "remove",
         except NoResultFound, e:
             print "! not found",
         self.print_row(subj, role, obj)
Пример #2
0
 def command(self):
     self._load_config()
     cmd = self.args[0] if len(self.args) else 'list'
     if cmd == 'list':
         self.list()
         return
     
     assert len(self.args) == 4, "Not enough paramters!" + RIGHTS_HELP
     cmd, subj, role, obj = self.args
     subj = self.find_subject(unicode(subj))
     role = self.ensure_role(unicode(role))
     obj = self.find_object(unicode(obj))
     if cmd == 'make':
         if isinstance(subj, model.User):
             model.add_user_to_role(subj, role, obj)
         elif isinstance(subj, model.AuthorizationGroup):
             model.add_authorization_group_to_role(subj, role, obj)
         print "made", 
     elif cmd == 'remove':
         if isinstance(subj, model.User):
             model.remove_user_from_role(subj, role, obj)
         elif isinstance(subj, model.AuthorizationGroup):
             model.remove_authorization_group_from_role(subj, role, obj)
         print "remove", 
     model.repo.commit_and_remove()
     self.print_row(subj, role, obj)
Пример #3
0
    def command(self):
        self._load_config()
        cmd = self.args[0] if len(self.args) else 'list'
        if cmd == 'list':
            args = self.args
            if 'list' in args:
                del args[args.index('list')]
            self.list(args)
            return

        assert len(self.args) == 4, "Not enough parameters!" + RIGHTS_HELP
        cmd, subj, role, obj = self.args
        subj = self.find_subject(unicode(subj))
        role = self.ensure_role(unicode(role))
        objs = self.find_objects(unicode(obj))
        for obj in objs:
            try:
                if cmd == 'make':
                    if isinstance(subj, model.User):
                        model.add_user_to_role(subj, role, obj)
                    elif isinstance(subj, model.AuthorizationGroup):
                        model.add_authorization_group_to_role(subj, role, obj)
                    print "made",
                elif cmd == 'remove':
                    if isinstance(subj, model.User):
                        model.remove_user_from_role(subj, role, obj)
                    elif isinstance(subj, model.AuthorizationGroup):
                        model.remove_authorization_group_from_role(
                            subj, role, obj)
                    print "remove",
            except NoResultFound, e:
                print "! not found",
            self.print_row(subj, role, obj)
Пример #4
0
    def setup_class(self):
        CreateTestData.create()
        model.repo.new_revision()
        model.Session.add(model.Package(name=u'testpkgag'))
        model.Session.add(model.Group(name=u'testgroupag'))
        model.Session.add(model.User(name=u'ag_member'))
        model.Session.add(model.User(name=u'ag_admin'))
        model.Session.add(model.User(name=u'ag_notmember'))
        model.Session.add(model.AuthorizationGroup(name=u'authz_group'))
        model.repo.commit_and_remove()

        pkg = model.Package.by_name(u'testpkgag')
        grp = model.Group.by_name(u'testgroupag')
        authzgrp = model.AuthorizationGroup.by_name(u'authz_group')
        member = model.User.by_name(u'ag_member')
        admin = model.User.by_name(u'ag_admin')
    
        model.setup_default_user_roles(authzgrp, [admin])
        model.add_authorization_group_to_role(authzgrp, model.Role.ADMIN, pkg)
        model.add_authorization_group_to_role(authzgrp, model.Role.ADMIN, grp)
        model.add_user_to_authorization_group(member, authzgrp, model.Role.EDITOR)
        model.repo.commit_and_remove()

        self.authorizer = ckan.authz.Authorizer()
        self.pkg = model.Package.by_name(u'testpkgag')
        self.grp = model.Group.by_name(u'testgroupag')
        self.member = model.User.by_name(u'ag_member')
        self.admin = model.User.by_name(u'ag_admin')
        self.notmember = model.User.by_name(u'ag_notmember')
        self.authzgrp = model.AuthorizationGroup.by_name(u'authz_group')
Пример #5
0
    def setup_class(self):
        CreateTestData.create()
        model.repo.new_revision()
        model.Session.add(model.Package(name=u"testpkgag"))
        model.Session.add(model.Group(name=u"testgroupag"))
        model.Session.add(model.User(name=u"ag_member"))
        model.Session.add(model.User(name=u"ag_admin"))
        model.Session.add(model.User(name=u"ag_notmember"))
        model.Session.add(model.AuthorizationGroup(name=u"authz_group"))
        model.repo.commit_and_remove()

        pkg = model.Package.by_name(u"testpkgag")
        grp = model.Group.by_name(u"testgroupag")
        authzgrp = model.AuthorizationGroup.by_name(u"authz_group")
        member = model.User.by_name(u"ag_member")
        admin = model.User.by_name(u"ag_admin")

        model.setup_default_user_roles(authzgrp, [admin])
        model.add_authorization_group_to_role(authzgrp, model.Role.ADMIN, pkg)
        model.add_authorization_group_to_role(authzgrp, model.Role.ADMIN, grp)
        model.add_user_to_authorization_group(member, authzgrp, model.Role.EDITOR)
        model.repo.commit_and_remove()

        self.authorizer = ckan.authz.Authorizer()
        self.pkg = model.Package.by_name(u"testpkgag")
        self.grp = model.Group.by_name(u"testgroupag")
        self.member = model.User.by_name(u"ag_member")
        self.admin = model.User.by_name(u"ag_admin")
        self.notmember = model.User.by_name(u"ag_notmember")
        self.authzgrp = model.AuthorizationGroup.by_name(u"authz_group")
Пример #6
0
 def create(self, package):
     # take my first authzgroup
     # and give it the editor role on this package
     user = model.User.by_name(c.user)
     authzgroups = user and user.authorization_groups
     authzgroup = authzgroups and authzgroups[0]
     if authzgroup:
         role = "editor"
         model.add_authorization_group_to_role(authzgroup, role, package)
Пример #7
0
 def setup_class(cls):
     # setup test data including testsysadmin user
     CreateTestData.create()
     # Creating a couple of authorization groups, which are enough to break
     # some things just by their existence
     for ag_name in [u'anauthzgroup', u'anotherauthzgroup']:
         ag=model.AuthorizationGroup.by_name(ag_name) 
         if not ag: #may already exist, if not create
             ag=model.AuthorizationGroup(name=ag_name)
             model.Session.add(ag)
     model.Session.commit()
     #they are especially dangerous if they have a role on the System
     ag = model.AuthorizationGroup.by_name(u'anauthzgroup')
     model.add_authorization_group_to_role(ag, u'editor', model.System())
     model.Session.commit()
Пример #8
0
 def setup_class(cls):
     # setup test data including testsysadmin user
     CreateTestData.create()
     # Creating a couple of authorization groups, which are enough to break
     # some things just by their existence
     for ag_name in [u'anauthzgroup', u'anotherauthzgroup']:
         ag=model.AuthorizationGroup.by_name(ag_name) 
         if not ag: #may already exist, if not create
             ag=model.AuthorizationGroup(name=ag_name)
             model.Session.add(ag)
     model.Session.commit()
     #they are especially dangerous if they have a role on the System
     ag = model.AuthorizationGroup.by_name(u'anauthzgroup')
     model.add_authorization_group_to_role(ag, u'editor', model.System())
     model.Session.commit()
Пример #9
0
 def setup_class(cls):
     config = appconfig('config:test.ini', relative_to=conf_dir)
     wsgiapp = make_app(config.global_conf, **config.local_conf)
     cls.app = paste.fixture.TestApp(wsgiapp)
     # setup test data including testsysadmin user
     CreateTestData.create()
     # Creating a couple of authorization groups, which are enough to break
     # some things just by their existence
     for ag_name in [u'anauthzgroup', u'anotherauthzgroup']:
         ag=model.AuthorizationGroup.by_name(ag_name) 
         if not ag: #may already exist, if not create
             ag=model.AuthorizationGroup(name=ag_name)
             model.Session.add(ag)
     model.Session.commit()
     #they are especially dangerous if they have a role on the System
     ag = model.AuthorizationGroup.by_name(u'anauthzgroup')
     model.add_authorization_group_to_role(ag, u'editor', model.System())
     model.Session.commit()
Пример #10
0
    def test_4_add_twice_remove_twice_for_authzgroups(self):
        aag = model.AuthorizationGroup.by_name(u'anauthzgroup')
        war = model.Package.by_name(u'warandpeace')

        def aag_roles():
            return [x.role \
             for x in model.Session.query(model.PackageRole).all() \
             if x.authorized_group and x.authorized_group.name=='anauthzgroup' and x.package.name==u'warandpeace']
          
        assert len(aag_roles()) == 0, "wrong number of roles for anauthzgroup"
        model.add_authorization_group_to_role(aag, model.Role.ADMIN, war)
        model.repo.commit_and_remove()
        assert len(aag_roles()) == 1, "wrong number of roles for anauthzgroup"
        model.add_authorization_group_to_role(aag, model.Role.ADMIN, war)
        model.repo.commit_and_remove()

        assert len(aag_roles()) == 1, "wrong number of roles for anauthzgroup"
        model.remove_authorization_group_from_role(aag, model.Role.ADMIN, war)
        assert len(aag_roles()) == 0, "wrong number of roles for anauthzgroup"
        model.remove_authorization_group_from_role(aag, model.Role.ADMIN, war)
        assert len(aag_roles()) == 0, "wrong number of roles for anauthzgroup"
Пример #11
0
    def test_4_add_twice_remove_twice_for_authzgroups(self):
        aag = model.AuthorizationGroup.by_name(u'anauthzgroup')
        war = model.Package.by_name(u'warandpeace')

        def aag_roles():
            return [x.role \
             for x in model.Session.query(model.PackageRole).all() \
             if x.authorized_group and x.authorized_group.name=='anauthzgroup' and x.package.name==u'warandpeace']

        assert len(aag_roles()) == 0, "wrong number of roles for anauthzgroup"
        model.add_authorization_group_to_role(aag, model.Role.ADMIN, war)
        model.repo.commit_and_remove()
        assert len(aag_roles()) == 1, "wrong number of roles for anauthzgroup"
        model.add_authorization_group_to_role(aag, model.Role.ADMIN, war)
        model.repo.commit_and_remove()

        assert len(aag_roles()) == 1, "wrong number of roles for anauthzgroup"
        model.remove_authorization_group_from_role(aag, model.Role.ADMIN, war)
        assert len(aag_roles()) == 0, "wrong number of roles for anauthzgroup"
        model.remove_authorization_group_from_role(aag, model.Role.ADMIN, war)
        assert len(aag_roles()) == 0, "wrong number of roles for anauthzgroup"
Пример #12
0
    def make_or_remove_roles(cls, cmd, subj, role, obj, except_on_error=False, do_commit=True):
        '''Tool to make or remove a role using the names of objects, rather
        than the actual objects.
        cmd - 'make' or 'remove'
        subj - name of subject object (e.g. 'dave-admin')
        role - name of role (e.g. 'editor')
        obj - names of an objects to apply the role to (e.g. 'river-stats' or 'all')
        '''
        from ckan import model
        log = logging.getLogger(__name__)

        subj = cls.find_subject(unicode(subj))
        role = cls.ensure_role(unicode(role))
        objs = cls.find_objects(unicode(obj))
        for obj in objs:
            try:
                if cmd == 'make':
                    if isinstance(subj, model.User):
                        model.add_user_to_role(subj, role, obj)
                    elif isinstance(subj, model.AuthorizationGroup):
                        model.add_authorization_group_to_role(subj, role, obj)
                    log.debug('Role made')
                elif cmd == 'remove':
                    if isinstance(subj, model.User):
                        model.remove_user_from_role(subj, role, obj)
                    elif isinstance(subj, model.AuthorizationGroup):
                        model.remove_authorization_group_from_role(subj, role, obj)
                    log.debug('Role removed')
                else:
                    raise NotImplementedError
            except NoResultFound, e:
                log.error('Cannot find object for role %s: %s', str(e), cmd)
                if except_on_error:
                    raise RightsToolError('Cannot %s right: %s %s %s', cmd, subj, role, obj)
            log.debug(cls.get_printable_row(subj, role, obj,
                                            exists=(cmd=='make')))
Пример #13
0
    def make_or_remove_roles(cls, cmd, subj, role, obj, except_on_error=False, do_commit=True):
        '''Tool to make or remove a role using the names of objects, rather
        than the actual objects.
        cmd - 'make' or 'remove'
        subj - name of subject object (e.g. 'dave-admin')
        role - name of role (e.g. 'editor')
        obj - names of an objects to apply the role to (e.g. 'river-stats' or 'all')
        '''
        from ckan import model
        log = logging.getLogger(__name__)

        subj = cls.find_subject(unicode(subj))
        role = cls.ensure_role(unicode(role))
        objs = cls.find_objects(unicode(obj))
        for obj in objs:
            try:
                if cmd == 'make':
                    if isinstance(subj, model.User):
                        model.add_user_to_role(subj, role, obj)
                    elif isinstance(subj, model.AuthorizationGroup):
                        model.add_authorization_group_to_role(subj, role, obj)
                    log.debug('Role made')
                elif cmd == 'remove':
                    if isinstance(subj, model.User):
                        model.remove_user_from_role(subj, role, obj)
                    elif isinstance(subj, model.AuthorizationGroup):
                        model.remove_authorization_group_from_role(subj, role, obj)
                    log.debug('Role removed')
                else:
                    raise NotImplementedError
            except NoResultFound, e:
                log.error('Cannot find object for role %s: %s', str(e), cmd)
                if except_on_error:
                    raise RightsToolError('Cannot %s right: %s %s %s', cmd, subj, role, obj)
            log.debug(cls.get_printable_row(subj, role, obj,
                                            exists=(cmd=='make')))
Пример #14
0
        def action_save_form(users_or_authz_groups):
            # The permissions grid has been saved
            # which is a grid of checkboxes named user$role
            rpi = request.params.items()

            # The grid passes us a list of the users/roles that were displayed
            submitted = [ a for (a,b) in rpi if (b == u'submitted')]
            # and also those which were checked
            checked = [ a for (a,b) in rpi if (b == u'on')]

            # from which we can deduce true/false for each user/role combination
            # that was displayed in the form
            table_dict={}
            for a in submitted:
                table_dict[a]=False
            for a in checked:
                table_dict[a]=True

            # now we'll split up the user$role strings to make a dictionary from 
            # (user,role) to True/False, which tells us what we need to do.
            new_user_role_dict={}
            for (ur,val) in table_dict.items():
                u,r = ur.split('$')
                new_user_role_dict[(u,r)] = val
               
            # we get the current user/role assignments 
            # and make a dictionary of them
            current_uors = model.Session.query(model.SystemRole).all()

            if users_or_authz_groups=='users':
                current_users_roles = [( uor.user.name, uor.role) for uor in current_uors if uor.user]
            elif users_or_authz_groups=='authz_groups':
                current_users_roles = [( uor.authorized_group.name, uor.role) for uor in current_uors if uor.authorized_group]        
            else:
                assert False, "shouldn't be here"

            current_user_role_dict={}
            for (u,r) in current_users_roles:
                current_user_role_dict[(u,r)]=True

            # and now we can loop through our dictionary of desired states
            # checking whether a change needs to be made, and if so making it

            # WORRY: Here it seems that we have to check whether someone is already assigned
            # a role, in order to avoid assigning it twice, or attempting to delete it when
            # it doesn't exist. Otherwise problems occur. However this doesn't affect the 
            # index page, which would seem to be prone to suffer the same effect. 
            # Why the difference?

            if users_or_authz_groups=='users':
                for ((u,r), val) in new_user_role_dict.items():
                    if val:
                        if not ((u,r) in current_user_role_dict):
                            model.add_user_to_role(model.User.by_name(u),r,model.System())
                    else:
                        if ((u,r) in current_user_role_dict):
                            model.remove_user_from_role(model.User.by_name(u),r,model.System())
            elif users_or_authz_groups=='authz_groups':
                for ((u,r), val) in new_user_role_dict.items():
                    if val:
                        if not ((u,r) in current_user_role_dict):
                            model.add_authorization_group_to_role(model.AuthorizationGroup.by_name(u),r,model.System())
                    else:
                        if ((u,r) in current_user_role_dict):
                            model.remove_authorization_group_from_role(model.AuthorizationGroup.by_name(u),r,model.System())
            else:
                assert False, "shouldn't be here"


            # finally commit the change to the database
            model.Session.commit()
            h.flash_success(_("Changes Saved"))
Пример #15
0
    def create(cls, auth_profile="", package_type=None):
        import ckan.model as model
        model.Session.remove()
        rev = model.repo.new_revision()
        # same name as user we create below
        rev.author = cls.author
        rev.message = u'''Creating test data.
 * Package: annakarenina
 * Package: warandpeace
 * Associated tags, etc etc
'''
        if auth_profile == "publisher":
            publisher_group = model.Group(name=u"publisher_group", type="publisher")

        cls.pkg_names = [u'annakarenina', u'warandpeace']
        pkg1 = model.Package(name=cls.pkg_names[0], type=package_type)
        if auth_profile == "publisher":
            pkg1.group = publisher_group
        model.Session.add(pkg1)
        pkg1.title = u'A Novel By Tolstoy'
        pkg1.version = u'0.7a'
        pkg1.url = u'http://www.annakarenina.com'
        # put an & in the url string to test escaping
        if 'alt_url' in model.Resource.get_extra_columns():
            configured_extras = ({'alt_url': u'alt123'},
                                 {'alt_url': u'alt345'})
        else:
            configured_extras = ({}, {})
        pr1 = model.Resource(
            url=u'http://www.annakarenina.com/download/x=1&y=2',
            format=u'plain text',
            description=u'Full text. Needs escaping: " Umlaut: \xfc',
            hash=u'abc123',
            extras={'size_extra': u'123'},
            **configured_extras[0]
            )
        pr2 = model.Resource(
            url=u'http://www.annakarenina.com/index.json',
            format=u'json',
            description=u'Index of the novel',
            hash=u'def456',
            extras={'size_extra': u'345'},
            **configured_extras[1]
            )
        model.Session.add(pr1)
        model.Session.add(pr2)
        pkg1.resources.append(pr1)
        pkg1.resources.append(pr2)
        pkg1.notes = u'''Some test notes

### A 3rd level heading

**Some bolded text.**

*Some italicized text.*

Foreign characters:
u with umlaut \xfc
66-style quote \u201c
foreign word: th\xfcmb

Needs escaping:
left arrow <

<http://ckan.net/>

'''
        pkg2 = model.Package(name=cls.pkg_names[1], type=package_type)
        tag1 = model.Tag(name=u'russian')
        tag2 = model.Tag(name=u'tolstoy')

        if auth_profile == "publisher":
            pkg2.group = publisher_group

        # Flexible tag, allows spaces, upper-case,
        # and all punctuation except commas
        tag3 = model.Tag(name=u'Flexible \u30a1')

        for obj in [pkg2, tag1, tag2, tag3]:
            model.Session.add(obj)
        pkg1.add_tags([tag1, tag2, tag3])
        pkg2.add_tags([ tag1, tag3 ])
        cls.tag_names = [ t.name for t in (tag1, tag2, tag3) ]
        pkg1.license_id = u'other-open'
        pkg2.license_id = u'cc-nc' # closed license
        pkg2.title = u'A Wonderful Story'
        pkg1.extras = {u'genre':'romantic novel',
                       u'original media':'book'}
        # group
        david = model.Group(name=u'david',
                             title=u'Dave\'s books',
                             description=u'These are books that David likes.',
                             type=auth_profile or 'group')
        roger = model.Group(name=u'roger',
                             title=u'Roger\'s books',
                             description=u'Roger likes these books.',
                             type=auth_profile or 'group')
        for obj in [david, roger]:
            model.Session.add(obj)

        cls.group_names.add(u'david')
        cls.group_names.add(u'roger')

        model.Session.flush()

        model.Session.add(model.Member(table_id=pkg1.id, table_name='package', group=david))
        model.Session.add(model.Member(table_id=pkg2.id, table_name='package', group=david))
        model.Session.add(model.Member(table_id=pkg1.id, table_name='package', group=roger))
        # authz
        model.Session.add_all([
            model.User(name=u'tester', apikey=u'tester', password=u'tester'),
            model.User(name=u'joeadmin', password=u'joeadmin'),
            model.User(name=u'annafan', about=u'I love reading Annakarenina. My site: <a href="http://anna.com">anna.com</a>', password=u'annafan'),
            model.User(name=u'russianfan', password=u'russianfan'),
            model.User(name=u'testsysadmin', password=u'testsysadmin'),
            ])
        cls.user_refs.extend([u'tester', u'joeadmin', u'annafan', u'russianfan', u'testsysadmin'])
        model.repo.commit_and_remove()

        visitor = model.User.by_name(model.PSEUDO_USER__VISITOR)
        anna = model.Package.by_name(u'annakarenina')
        war = model.Package.by_name(u'warandpeace')
        annafan = model.User.by_name(u'annafan')
        russianfan = model.User.by_name(u'russianfan')
        model.setup_default_user_roles(anna, [annafan])
        model.setup_default_user_roles(war, [russianfan])
        model.add_user_to_role(visitor, model.Role.ADMIN, war)
        david = model.Group.by_name(u'david')
        roger = model.Group.by_name(u'roger')
        model.setup_default_user_roles(david, [russianfan])
        model.setup_default_user_roles(roger, [russianfan])
        model.add_user_to_role(visitor, model.Role.ADMIN, roger)
        testsysadmin = model.User.by_name(u'testsysadmin')
        model.add_user_to_role(testsysadmin, model.Role.ADMIN, model.System())

        model.repo.commit_and_remove()

        # Create a couple of authorization groups
        for ag_name in [u'anauthzgroup', u'anotherauthzgroup']:
            ag=model.AuthorizationGroup.by_name(ag_name)
            if not ag: #may already exist, if not create
                ag=model.AuthorizationGroup(name=ag_name)
                model.Session.add(ag)

        model.repo.commit_and_remove()

        # and give them a range of roles on various things
        ag = model.AuthorizationGroup.by_name(u'anauthzgroup')
        aag = model.AuthorizationGroup.by_name(u'anotherauthzgroup')
        pkg = model.Package.by_name(u'warandpeace')
        g = model.Group.by_name('david')

        model.add_authorization_group_to_role(ag, u'editor', model.System())
        model.add_authorization_group_to_role(ag, u'reader', pkg)
        model.add_authorization_group_to_role(ag, u'admin', aag)
        model.add_authorization_group_to_role(aag, u'editor', ag)
        model.add_authorization_group_to_role(ag, u'editor', g)

        model.repo.commit_and_remove()
Пример #16
0
    def create(cls):
        import ckan.model as model

        model.Session.remove()
        rev = model.repo.new_revision()
        # same name as user we create below
        rev.author = cls.author
        rev.message = u"""Creating test data.
 * Package: annakarenina
 * Package: warandpeace
 * Associated tags, etc etc
"""
        cls.pkg_names = [u"annakarenina", u"warandpeace"]
        pkg1 = model.Package(name=cls.pkg_names[0])
        model.Session.add(pkg1)
        pkg1.title = u"A Novel By Tolstoy"
        pkg1.version = u"0.7a"
        pkg1.url = u"http://www.annakarenina.com"
        # put an & in the url string to test escaping
        if "alt_url" in model.Resource.get_extra_columns():
            configured_extras = ({"alt_url": u"alt123"}, {"alt_url": u"alt345"})
        else:
            configured_extras = ({}, {})
        pr1 = model.Resource(
            url=u"http://www.annakarenina.com/download/x=1&y=2",
            format=u"plain text",
            description=u'Full text. Needs escaping: " Umlaut: \xfc',
            hash=u"abc123",
            extras={"size_extra": u"123"},
            **configured_extras[0]
        )
        pr2 = model.Resource(
            url=u"http://www.annakarenina.com/index.json",
            format=u"json",
            description=u"Index of the novel",
            hash=u"def456",
            extras={"size_extra": u"345"},
            **configured_extras[1]
        )
        model.Session.add(pr1)
        model.Session.add(pr2)
        pkg1.resources.append(pr1)
        pkg1.resources.append(pr2)
        pkg1.notes = u"""Some test notes

### A 3rd level heading

**Some bolded text.**

*Some italicized text.*

Foreign characters:
u with umlaut \xfc
66-style quote \u201c
foreign word: th\xfcmb
 
Needs escaping:
left arrow <

<http://ckan.net/>

"""
        pkg2 = model.Package(name=cls.pkg_names[1])
        tag1 = model.Tag(name=u"russian")
        tag2 = model.Tag(name=u"tolstoy")

        # Flexible tag, allows spaces, upper-case,
        # and all punctuation except commas
        tag3 = model.Tag(name=u"Flexible \u30a1")

        for obj in [pkg2, tag1, tag2, tag3]:
            model.Session.add(obj)
        pkg1.tags = [tag1, tag2, tag3]
        pkg2.tags = [tag1, tag3]
        cls.tag_names = [t.name for t in (tag1, tag2, tag3)]
        pkg1.license_id = u"other-open"
        pkg2.license_id = u"cc-nc"  # closed license
        pkg2.title = u"A Wonderful Story"
        pkg1.extras = {u"genre": "romantic novel", u"original media": "book"}
        # group
        david = model.Group(name=u"david", title=u"Dave's books", description=u"These are books that David likes.")
        roger = model.Group(name=u"roger", title=u"Roger's books", description=u"Roger likes these books.")
        for obj in [david, roger]:
            model.Session.add(obj)

        cls.group_names.add(u"david")
        cls.group_names.add(u"roger")
        model.Session.add(model.PackageGroup(package=pkg1, group=david))
        model.Session.add(model.PackageGroup(package=pkg2, group=david))
        model.Session.add(model.PackageGroup(package=pkg1, group=roger))
        # authz
        model.Session.add_all(
            [
                model.User(name=u"tester", apikey=u"tester", password=u"tester"),
                model.User(name=u"joeadmin", password=u"joeadmin"),
                model.User(
                    name=u"annafan",
                    about=u'I love reading Annakarenina. My site: <a href="http://anna.com">anna.com</a>',
                    password=u"annafan",
                ),
                model.User(name=u"russianfan", password=u"russianfan"),
                model.User(name=u"testsysadmin", password=u"testsysadmin"),
            ]
        )
        cls.user_refs.extend([u"tester", u"joeadmin", u"annafan", u"russianfan", u"testsysadmin"])
        model.repo.commit_and_remove()

        visitor = model.User.by_name(model.PSEUDO_USER__VISITOR)
        anna = model.Package.by_name(u"annakarenina")
        war = model.Package.by_name(u"warandpeace")
        annafan = model.User.by_name(u"annafan")
        russianfan = model.User.by_name(u"russianfan")
        model.setup_default_user_roles(anna, [annafan])
        model.setup_default_user_roles(war, [russianfan])
        model.add_user_to_role(visitor, model.Role.ADMIN, war)
        david = model.Group.by_name(u"david")
        roger = model.Group.by_name(u"roger")
        model.setup_default_user_roles(david, [russianfan])
        model.setup_default_user_roles(roger, [russianfan])
        model.add_user_to_role(visitor, model.Role.ADMIN, roger)
        testsysadmin = model.User.by_name(u"testsysadmin")
        model.add_user_to_role(testsysadmin, model.Role.ADMIN, model.System())

        model.repo.commit_and_remove()

        # Create a couple of authorization groups
        for ag_name in [u"anauthzgroup", u"anotherauthzgroup"]:
            ag = model.AuthorizationGroup.by_name(ag_name)
            if not ag:  # may already exist, if not create
                ag = model.AuthorizationGroup(name=ag_name)
                model.Session.add(ag)

        model.repo.commit_and_remove()

        # and give them a range of roles on various things
        ag = model.AuthorizationGroup.by_name(u"anauthzgroup")
        aag = model.AuthorizationGroup.by_name(u"anotherauthzgroup")
        pkg = model.Package.by_name(u"warandpeace")
        g = model.Group.by_name("david")

        model.add_authorization_group_to_role(ag, u"editor", model.System())
        model.add_authorization_group_to_role(ag, u"reader", pkg)
        model.add_authorization_group_to_role(ag, u"admin", aag)
        model.add_authorization_group_to_role(aag, u"editor", ag)
        model.add_authorization_group_to_role(ag, u"editor", g)

        model.repo.commit_and_remove()
Пример #17
0
        def action_save_form(users_or_authz_groups):
            # The permissions grid has been saved
            # which is a grid of checkboxes named user$role
            rpi = request.params.items()

            # The grid passes us a list of the users/roles that were displayed
            submitted = [a for (a, b) in rpi if (b == u'submitted')]
            # and also those which were checked
            checked = [a for (a, b) in rpi if (b == u'on')]

            # from which we can deduce true/false for each user/role combination
            # that was displayed in the form
            table_dict = {}
            for a in submitted:
                table_dict[a] = False
            for a in checked:
                table_dict[a] = True

            # now we'll split up the user$role strings to make a dictionary from
            # (user,role) to True/False, which tells us what we need to do.
            new_user_role_dict = {}
            for (ur, val) in table_dict.items():
                u, r = ur.split('$')
                new_user_role_dict[(u, r)] = val

            # we get the current user/role assignments
            # and make a dictionary of them
            current_uors = model.Session.query(model.SystemRole).all()

            if users_or_authz_groups == 'users':
                current_users_roles = [(uor.user.name, uor.role)
                                       for uor in current_uors if uor.user]
            elif users_or_authz_groups == 'authz_groups':
                current_users_roles = [(uor.authorized_group.name, uor.role)
                                       for uor in current_uors
                                       if uor.authorized_group]
            else:
                assert False, "shouldn't be here"

            current_user_role_dict = {}
            for (u, r) in current_users_roles:
                current_user_role_dict[(u, r)] = True

            # and now we can loop through our dictionary of desired states
            # checking whether a change needs to be made, and if so making it

            # WORRY: Here it seems that we have to check whether someone is already assigned
            # a role, in order to avoid assigning it twice, or attempting to delete it when
            # it doesn't exist. Otherwise problems occur. However this doesn't affect the
            # index page, which would seem to be prone to suffer the same effect.
            # Why the difference?

            if users_or_authz_groups == 'users':
                for ((u, r), val) in new_user_role_dict.items():
                    if val:
                        if not ((u, r) in current_user_role_dict):
                            model.add_user_to_role(model.User.by_name(u), r,
                                                   model.System())
                    else:
                        if ((u, r) in current_user_role_dict):
                            model.remove_user_from_role(
                                model.User.by_name(u), r, model.System())
            elif users_or_authz_groups == 'authz_groups':
                for ((u, r), val) in new_user_role_dict.items():
                    if val:
                        if not ((u, r) in current_user_role_dict):
                            model.add_authorization_group_to_role(
                                model.AuthorizationGroup.by_name(u), r,
                                model.System())
                    else:
                        if ((u, r) in current_user_role_dict):
                            model.remove_authorization_group_from_role(
                                model.AuthorizationGroup.by_name(u), r,
                                model.System())
            else:
                assert False, "shouldn't be here"

            # finally commit the change to the database
            model.Session.commit()
            h.flash_success(_("Changes Saved"))
Пример #18
0
    def create(cls, auth_profile="", package_type=None):
        model.Session.remove()
        rev = model.repo.new_revision()
        # same name as user we create below
        rev.author = cls.author
        rev.message = u'''Creating test data.
 * Package: annakarenina
 * Package: warandpeace
 * Associated tags, etc etc
'''
        if auth_profile == "publisher":
            organization_group = model.Group(name=u"organization_group", type="organization")

        cls.pkg_names = [u'annakarenina', u'warandpeace']
        pkg1 = model.Package(name=cls.pkg_names[0], type=package_type)
        if auth_profile == "publisher":
            pkg1.group = organization_group
        model.Session.add(pkg1)
        pkg1.title = u'A Novel By Tolstoy'
        pkg1.version = u'0.7a'
        pkg1.url = u'http://www.annakarenina.com'
        # put an & in the url string to test escaping
        if 'alt_url' in model.Resource.get_extra_columns():
            configured_extras = ({'alt_url': u'alt123'},
                                 {'alt_url': u'alt345'})
        else:
            configured_extras = ({}, {})
        pr1 = model.Resource(
            url=u'http://www.annakarenina.com/download/x=1&y=2',
            format=u'plain text',
            description=u'Full text. Needs escaping: " Umlaut: \xfc',
            hash=u'abc123',
            extras={'size_extra': u'123'},
            **configured_extras[0]
            )
        pr2 = model.Resource(
            url=u'http://www.annakarenina.com/index.json',
            format=u'json',
            description=u'Index of the novel',
            hash=u'def456',
            extras={'size_extra': u'345'},
            **configured_extras[1]
            )
        model.Session.add(pr1)
        model.Session.add(pr2)
        pkg1.resource_groups_all[0].resources_all.append(pr1)
        pkg1.resource_groups_all[0].resources_all.append(pr2)
        pkg1.notes = u'''Some test notes

### A 3rd level heading

**Some bolded text.**

*Some italicized text.*

Foreign characters:
u with umlaut \xfc
66-style quote \u201c
foreign word: th\xfcmb

Needs escaping:
left arrow <

<http://ckan.net/>

'''
        pkg2 = model.Package(name=cls.pkg_names[1], type=package_type)
        tag1 = model.Tag(name=u'russian')
        tag2 = model.Tag(name=u'tolstoy')

        if auth_profile == "publisher":
            pkg2.group = organization_group

        # Flexible tag, allows spaces, upper-case,
        # and all punctuation except commas
        tag3 = model.Tag(name=u'Flexible \u30a1')

        for obj in [pkg2, tag1, tag2, tag3]:
            model.Session.add(obj)
        pkg1.add_tags([tag1, tag2, tag3])
        pkg2.add_tags([ tag1, tag3 ])
        cls.tag_names = [ t.name for t in (tag1, tag2, tag3) ]
        pkg1.license_id = u'other-open'
        pkg2.license_id = u'cc-nc' # closed license
        pkg2.title = u'A Wonderful Story'
        pkg1.extras = {u'genre':'romantic novel',
                       u'original media':'book'}
        # group
        david = model.Group(name=u'david',
                             title=u'Dave\'s books',
                             description=u'These are books that David likes.',
                             type=auth_profile or 'group')
        roger = model.Group(name=u'roger',
                             title=u'Roger\'s books',
                             description=u'Roger likes these books.',
                             type=auth_profile or 'group')
        for obj in [david, roger]:
            model.Session.add(obj)

        cls.group_names.add(u'david')
        cls.group_names.add(u'roger')

        model.Session.flush()

        model.Session.add(model.Member(table_id=pkg1.id, table_name='package', group=david))
        model.Session.add(model.Member(table_id=pkg2.id, table_name='package', group=david))
        model.Session.add(model.Member(table_id=pkg1.id, table_name='package', group=roger))
        # authz
        model.Session.add_all([
            model.User(name=u'tester', apikey=u'tester', password=u'tester'),
            model.User(name=u'joeadmin', password=u'joeadmin'),
            model.User(name=u'annafan', about=u'I love reading Annakarenina. My site: <a href="http://anna.com">anna.com</a>', password=u'annafan'),
            model.User(name=u'russianfan', password=u'russianfan'),
            model.User(name=u'testsysadmin', password=u'testsysadmin'),
            ])
        cls.user_refs.extend([u'tester', u'joeadmin', u'annafan', u'russianfan', u'testsysadmin'])
        model.repo.commit_and_remove()

        visitor = model.User.by_name(model.PSEUDO_USER__VISITOR)
        anna = model.Package.by_name(u'annakarenina')
        war = model.Package.by_name(u'warandpeace')
        annafan = model.User.by_name(u'annafan')
        russianfan = model.User.by_name(u'russianfan')
        model.setup_default_user_roles(anna, [annafan])
        model.setup_default_user_roles(war, [russianfan])
        model.add_user_to_role(visitor, model.Role.ADMIN, war)
        david = model.Group.by_name(u'david')
        roger = model.Group.by_name(u'roger')
        model.setup_default_user_roles(david, [russianfan])
        model.setup_default_user_roles(roger, [russianfan])
        model.add_user_to_role(visitor, model.Role.ADMIN, roger)
        testsysadmin = model.User.by_name(u'testsysadmin')
        model.add_user_to_role(testsysadmin, model.Role.ADMIN, model.System())

        model.repo.commit_and_remove()

        # Create a couple of authorization groups
        for ag_name in [u'anauthzgroup', u'anotherauthzgroup']:
            ag=model.AuthorizationGroup.by_name(ag_name)
            if not ag: #may already exist, if not create
                ag=model.AuthorizationGroup(name=ag_name)
                model.Session.add(ag)

        model.repo.commit_and_remove()

        # and give them a range of roles on various things
        ag = model.AuthorizationGroup.by_name(u'anauthzgroup')
        aag = model.AuthorizationGroup.by_name(u'anotherauthzgroup')
        pkg = model.Package.by_name(u'warandpeace')
        g = model.Group.by_name('david')

        model.add_authorization_group_to_role(ag, u'editor', model.System())
        model.add_authorization_group_to_role(ag, u'reader', pkg)
        model.add_authorization_group_to_role(ag, u'admin', aag)
        model.add_authorization_group_to_role(aag, u'editor', ag)
        model.add_authorization_group_to_role(ag, u'editor', g)

        model.repo.commit_and_remove()
Пример #19
0
    def _add_user_object_role(self, users_or_authz_groups, current_uors, domain_object):
        '''
        current_uors: in order to avoid either creating a role twice or deleting one which is
        non-existent, we need to get the users' current roles (if any)
        '''
        # The user is attempting to set new roles for a named user
        new_user = request.params.get('new_user_name')
        # this is the list of roles whose boxes were ticked
        checked_roles = [ a for (a,b) in request.params.items() if (b == u'on')]
        # this is the list of all the roles that were in the submitted form
        submitted_roles = [ a for (a,b) in request.params.items() if (b == u'submitted')]

        # from this we can make a dictionary of the desired states
        # i.e. true for the ticked boxes, false for the unticked
        desired_roles = {}
        for r in submitted_roles:
            desired_roles[r]=False
        for r in checked_roles:
            desired_roles[r]=True

        if users_or_authz_groups=='users':
            current_roles = [uor.role for uor in current_uors if ( uor.user and uor.user.name == new_user )]
            user_object = model.User.by_name(new_user)
            if user_object==None:
                # The submitted user does not exist. Bail with flash message
                h.flash_error(_('unknown user:'******'authz_groups':
            current_roles = [uor.role for uor in current_uors if ( uor.authorized_group and uor.authorized_group.name == new_user )]
            user_object = model.AuthorizationGroup.by_name(new_user)
            if user_object==None:
                # The submitted user does not exist. Bail with flash message
                h.flash_error(_('unknown authorization group:') + str (new_user))
            else:
                # Whenever our desired state is different from our current state, change it.
                for (r,val) in desired_roles.items():
                    if val:
                        if (r not in current_roles):
                            model.add_authorization_group_to_role(user_object,
                                    r, domain_object)
                    else:
                        if (r in current_roles):
                            model.remove_authorization_group_from_role(user_object,
                                    r, domain_object)
                h.flash_success(_("Authorization Group Added"))

        else:
            assert False, "shouldn't be here"

        # and finally commit all these changes to the database
        model.repo.commit_and_remove()
Пример #20
0
    def _update_user_object_roles(self, users_or_authz_groups, current_uors, domain_object):
        '''Update user object roles for this object.

        :param domain_object: the domain object for whom we are adding the user
        object role.
        '''
        # The permissions grid has been saved
        # which is a grid of checkboxes named user$role
        rpi = request.params.items()

        # The grid passes us a list of the users/roles that were displayed
        submitted = [ a for (a,b) in rpi if (b == u'submitted')]
        # and also those which were checked
        checked = [ a for (a,b) in rpi if (b == u'on')]

        # from which we can deduce true/false for each user/role combination
        # that was displayed in the form
        table_dict={}
        for a in submitted:
            table_dict[a]=False
        for a in checked:
            table_dict[a]=True

        # now we'll split up the user$role strings to make a dictionary from 
        # (user,role) to True/False, which tells us what we need to do.
        new_user_role_dict={}
        for (ur,val) in table_dict.items():
            u,r = ur.split('$')
            new_user_role_dict[(u,r)] = val
           
        if users_or_authz_groups=='users':
            current_users_roles = [( uor.user.name, uor.role) for uor in current_uors if uor.user]
        elif users_or_authz_groups=='authz_groups':
            current_users_roles = [( uor.authorized_group.name, uor.role) for uor in current_uors if uor.authorized_group]        
        else:
            assert False, "shouldn't be here"

        current_user_role_dict={}
        for (u,r) in current_users_roles:
            current_user_role_dict[(u,r)]=True

        # and now we can loop through our dictionary of desired states
        # checking whether a change needs to be made, and if so making it

        # Here we check whether someone is already assigned a role, in order
        # to avoid assigning it twice, or attempting to delete it when it
        # doesn't exist. Otherwise problems can occur.
        if users_or_authz_groups=='users':
            for ((u,r), val) in new_user_role_dict.items():
                if val:
                    if not ((u,r) in current_user_role_dict):
                        model.add_user_to_role(model.User.by_name(u),r,domain_object)
                else:
                    if ((u,r) in current_user_role_dict):
                        model.remove_user_from_role(model.User.by_name(u),r,domain_object)
        elif users_or_authz_groups=='authz_groups':
            for ((u,r), val) in new_user_role_dict.items():
                if val:
                    if not ((u,r) in current_user_role_dict):
                        model.add_authorization_group_to_role(model.AuthorizationGroup.by_name(u),r,domain_object)
                else:
                    if ((u,r) in current_user_role_dict):
                        model.remove_authorization_group_from_role(model.AuthorizationGroup.by_name(u),r,domain_object)
        else:
            assert False, "shouldn't be here"

        # finally commit the change to the database
        model.repo.commit_and_remove()
        h.flash_success(_("Changes Saved"))