Пример #1
0
 def __load_defaults(self):
     acl_groups = RepoGroupList(RepoGroup.query().all(),
                            perm_set=['group.write', 'group.admin'])
     c.repo_groups = RepoGroup.groups_choices(groups=acl_groups)
     c.repo_groups_choices = map(lambda k: unicode(k[0]), c.repo_groups)
     choices, c.landing_revs = ScmModel().get_repo_landing_revs()
     c.landing_revs_choices = choices
     c.can_update = Ui.get_by_key(Ui.HOOK_UPDATE).ui_active
Пример #2
0
    def test_remove_group(self):
        sg1 = fixture.create_repo_group(u'deleteme')
        self.__delete_group(sg1.group_id)

        self.assertEqual(RepoGroup.get(sg1.group_id), None)
        self.assertFalse(self.__check_path('deteteme'))

        sg1 = fixture.create_repo_group(u'deleteme', group_parent_id=self.g1.group_id)
        self.__delete_group(sg1.group_id)

        self.assertEqual(RepoGroup.get(sg1.group_id), None)
        self.assertFalse(self.__check_path('test1', 'deteteme'))
Пример #3
0
    def test_remove_group(self):
        sg1 = fixture.create_repo_group('deleteme')
        self.__delete_group(sg1.group_id)

        self.assertEqual(RepoGroup.get(sg1.group_id), None)
        self.assertFalse(self.__check_path('deteteme'))

        sg1 = fixture.create_repo_group('deleteme', group_parent_id=self.g1.group_id)
        self.__delete_group(sg1.group_id)

        self.assertEqual(RepoGroup.get(sg1.group_id), None)
        self.assertFalse(self.__check_path('test1', 'deteteme'))
Пример #4
0
    def test_remove_group(self):
        sg1 = fixture.create_repo_group(u'deleteme')
        self.__delete_group(sg1.group_id)

        assert RepoGroup.get(sg1.group_id) == None
        assert not self.__check_path('deteteme')

        sg1 = fixture.create_repo_group(u'deleteme', parent_group_id=self.g1.group_id)
        self.__delete_group(sg1.group_id)

        assert RepoGroup.get(sg1.group_id) == None
        assert not self.__check_path('test1', 'deteteme')
Пример #5
0
    def test_remove_group(self):
        sg1 = fixture.create_repo_group('deleteme')
        self.__delete_group(sg1.group_id)

        assert RepoGroup.get(sg1.group_id) is None
        assert not self.__check_path('deteteme')

        sg1 = fixture.create_repo_group('deleteme', parent_group_id=self.g1.group_id)
        self.__delete_group(sg1.group_id)

        assert RepoGroup.get(sg1.group_id) is None
        assert not self.__check_path('test1', 'deteteme')
Пример #6
0
    def show(self, group_name):
        c.active = 'settings'

        c.group = c.repo_group = RepoGroup.guess_instance(group_name)

        groups = RepoGroup.query(sorted=True).filter_by(parent_group=c.group).all()
        repo_groups_list = self.scm_model.get_repo_groups(groups)

        repos_list = Repository.query(sorted=True).filter_by(group=c.group).all()
        c.data = RepoModel().get_repos_as_dict(repos_list,
                                               repo_groups_list=repo_groups_list,
                                               short_name=True)

        return render('admin/repo_groups/repo_group_show.html')
Пример #7
0
    def update(self, repo_group, kwargs):
        try:
            repo_group = RepoGroup.guess_instance(repo_group)
            old_path = repo_group.full_path

            # change properties
            if 'group_description' in kwargs:
                repo_group.group_description = kwargs['group_description']
            if 'parent_group_id' in kwargs:
                repo_group.parent_group_id = kwargs['parent_group_id']
            if 'enable_locking' in kwargs:
                repo_group.enable_locking = kwargs['enable_locking']

            if 'parent_group_id' in kwargs:
                assert kwargs['parent_group_id'] != u'-1', kwargs # RepoGroupForm should have converted to None
                repo_group.parent_group = RepoGroup.get(kwargs['parent_group_id'])
            if 'group_name' in kwargs:
                repo_group.group_name = repo_group.get_new_name(kwargs['group_name'])
            new_path = repo_group.full_path
            Session().add(repo_group)

            # iterate over all members of this groups and do fixes
            # set locking if given
            # if obj is a repoGroup also fix the name of the group according
            # to the parent
            # if obj is a Repo fix it's name
            # this can be potentially heavy operation
            for obj in repo_group.recursive_groups_and_repos():
                #set the value from it's parent
                obj.enable_locking = repo_group.enable_locking
                if isinstance(obj, RepoGroup):
                    new_name = obj.get_new_name(obj.name)
                    log.debug('Fixing group %s to new name %s' \
                                % (obj.group_name, new_name))
                    obj.group_name = new_name
                elif isinstance(obj, Repository):
                    # we need to get all repositories from this new group and
                    # rename them accordingly to new group path
                    new_name = obj.get_new_name(obj.just_name)
                    log.debug('Fixing repo %s to new name %s' \
                                % (obj.repo_name, new_name))
                    obj.repo_name = new_name

            self._rename_group(old_path, new_path)

            return repo_group
        except Exception:
            log.error(traceback.format_exc())
            raise
Пример #8
0
    def show(self, group_name):
        c.active = 'settings'

        c.group = c.repo_group = RepoGroup.guess_instance(group_name)

        groups = RepoGroup.query(sorted=True).filter_by(parent_group=c.group).all()
        c.groups = self.scm_model.get_repo_groups(groups)

        repos_list = Repository.query(sorted=True).filter_by(group=c.group).all()
        repos_data = RepoModel().get_repos_as_dict(repos_list=repos_list,
                                                   admin=False, short_name=True)
        # data used to render the grid
        c.data = repos_data

        return render('admin/repo_groups/repo_group_show.html')
Пример #9
0
 def create_repo_group(self, name, **kwargs):
     if 'skip_if_exists' in kwargs:
         del kwargs['skip_if_exists']
         gr = RepoGroup.get_by_group_name(group_name=name)
         if gr:
             return gr
     form_data = self._get_group_create_params(group_name=name, **kwargs)
     owner = kwargs.get('cur_user', TEST_USER_ADMIN_LOGIN)
     gr = RepoGroupModel().create(
         group_name=form_data['group_name'],
         group_description=form_data['group_name'],
         owner=owner, parent=form_data['group_parent_id'])
     Session().commit()
     gr = RepoGroup.get_by_group_name(gr.group_name)
     return gr
Пример #10
0
 def create_repo_group(self, name, **kwargs):
     if 'skip_if_exists' in kwargs:
         del kwargs['skip_if_exists']
         gr = RepoGroup.get_by_group_name(group_name=name)
         if gr:
             return gr
     form_data = self._get_group_create_params(group_name=name, **kwargs)
     owner = kwargs.get('cur_user', TEST_USER_ADMIN_LOGIN)
     gr = RepoGroupModel().create(group_name=form_data['group_name'],
                                  group_description=form_data['group_name'],
                                  owner=owner,
                                  parent=form_data['group_parent_id'])
     Session().commit()
     gr = RepoGroup.get_by_group_name(gr.group_name)
     return gr
Пример #11
0
        def validate_python(self, value, state):
            # TODO WRITE VALIDATIONS
            group_name = value.get('group_name')
            group_parent_id = value.get('group_parent_id')

            # slugify repo group just in case :)
            slug = repo_name_slug(group_name)

            # check for parent of self
            parent_of_self = lambda: (old_data['group_id'] == int(
                group_parent_id) if group_parent_id else False)
            if edit and parent_of_self():
                msg = M(self, 'group_parent_id', state)
                raise formencode.Invalid(msg,
                                         value,
                                         state,
                                         error_dict=dict(group_parent_id=msg))

            old_gname = None
            if edit:
                old_gname = RepoGroup.get(old_data.get('group_id')).group_name

            if old_gname != group_name or not edit:

                # check group
                gr = RepoGroup.query()\
                      .filter(RepoGroup.group_name == slug)\
                      .filter(RepoGroup.group_parent_id == group_parent_id)\
                      .scalar()

                if gr:
                    msg = M(self, 'group_exists', state, group_name=slug)
                    raise formencode.Invalid(msg,
                                             value,
                                             state,
                                             error_dict=dict(group_name=msg))

                # check for same repo
                repo = Repository.query()\
                      .filter(Repository.repo_name == slug)\
                      .scalar()

                if repo:
                    msg = M(self, 'repo_exists', state, group_name=slug)
                    raise formencode.Invalid(msg,
                                             value,
                                             state,
                                             error_dict=dict(group_name=msg))
Пример #12
0
    def show(self, group_name):
        """GET /repo_groups/group_name: Show a specific item"""
        # url('repos_group', group_name=GROUP_NAME)
        c.active = 'settings'

        c.group = c.repo_group = RepoGroupModel()._get_repo_group(group_name)
        c.group_repos = c.group.repositories.all()

        #overwrite our cached list with current filter
        c.repo_cnt = 0

        groups = RepoGroup.query().order_by(RepoGroup.group_name)\
            .filter(RepoGroup.group_parent_id == c.group.group_id).all()
        c.groups = self.scm_model.get_repo_groups(groups)

        c.repos_list = Repository.query()\
                        .filter(Repository.group_id == c.group.group_id)\
                        .order_by(func.lower(Repository.repo_name))\
                        .all()

        repos_data = RepoModel().get_repos_as_dict(repos_list=c.repos_list,
                                                   admin=False)
        #json used to render the grid
        c.data = json.dumps(repos_data)

        return render('admin/repo_groups/repo_group_show.html')
Пример #13
0
    def grant_user_group_permission(self, repo_group, group_name, perm):
        """
        Grant permission for user group on given repository group, or update
        existing one if found

        :param repo_group: Instance of RepoGroup, repositories_group_id,
            or repositories_group name
        :param group_name: Instance of UserGroup, users_group_id,
            or user group name
        :param perm: Instance of Permission, or permission_name
        """
        repo_group = RepoGroup.guess_instance(repo_group)
        group_name = UserGroup.guess_instance(group_name)
        permission = Permission.guess_instance(perm)

        # check if we have that permission already
        obj = UserGroupRepoGroupToPerm.query() \
            .filter(UserGroupRepoGroupToPerm.group == repo_group) \
            .filter(UserGroupRepoGroupToPerm.users_group == group_name) \
            .scalar()

        if obj is None:
            # create new
            obj = UserGroupRepoGroupToPerm()
            Session().add(obj)

        obj.group = repo_group
        obj.users_group = group_name
        obj.permission = permission
        log.debug('Granted perm %s to %s on %s', perm, group_name, repo_group)
        return obj
Пример #14
0
    def test_update_group_parent(self):

        sg1 = fixture.create_repo_group('initial', group_parent_id=self.g1.group_id)

        new_sg1 = _update_group(sg1.group_id, 'after', parent_id=self.g1.group_id)
        self.assertTrue(self.__check_path('test1', 'after'))
        self.assertEqual(RepoGroup.get_by_group_name('test1/initial'), None)

        new_sg1 = _update_group(sg1.group_id, 'after', parent_id=self.g3.group_id)
        self.assertTrue(self.__check_path('test3', 'after'))
        self.assertEqual(RepoGroup.get_by_group_name('test3/initial'), None)

        new_sg1 = _update_group(sg1.group_id, 'hello')
        self.assertTrue(self.__check_path('hello'))

        self.assertEqual(RepoGroup.get_by_group_name('hello'), new_sg1)
Пример #15
0
    def update(self, repo, **kwargs):
        try:
            cur_repo = self._get_repo(repo)
            org_repo_name = cur_repo.repo_name
            if 'user' in kwargs:
                cur_repo.user = User.get_by_username(kwargs['user'])

            if 'repo_group' in kwargs:
                cur_repo.group = RepoGroup.get(kwargs['repo_group'])
            log.debug('Updating repo %s with params:%s' % (cur_repo, kwargs))
            for strip, k in [
                (1, 'repo_enable_downloads'),
                (1, 'repo_description'),
                (1, 'repo_enable_locking'),
                (1, 'repo_landing_rev'),
                (1, 'repo_private'),
                (1, 'repo_enable_statistics'),
                (0, 'clone_uri'),
            ]:
                if k in kwargs:
                    val = kwargs[k]
                    if strip:
                        k = remove_prefix(k, 'repo_')
                    if k == 'clone_uri':
                        from kallithea.model.validators import Missing
                        _change = kwargs.get('clone_uri_change')
                        if _change == Missing:
                            # we don't change the value, so use original one
                            val = cur_repo.clone_uri

                    setattr(cur_repo, k, val)

            new_name = cur_repo.get_new_name(kwargs['repo_name'])
            cur_repo.repo_name = new_name
            #if private flag is set, reset default permission to NONE

            if kwargs.get('repo_private'):
                EMPTY_PERM = 'repository.none'
                RepoModel().grant_user_permission(repo=cur_repo,
                                                  user='******',
                                                  perm=EMPTY_PERM)
                #handle extra fields
            for field in filter(lambda k: k.startswith(RepositoryField.PREFIX),
                                kwargs):
                k = RepositoryField.un_prefix_key(field)
                ex_field = RepositoryField.get_by_key_name(key=k,
                                                           repo=cur_repo)
                if ex_field:
                    ex_field.field_value = kwargs[field]
                    self.sa.add(ex_field)
            self.sa.add(cur_repo)

            if org_repo_name != new_name:
                # rename repository
                self._rename_filesystem_repo(old=org_repo_name, new=new_name)

            return cur_repo
        except Exception:
            log.error(traceback.format_exc())
            raise
Пример #16
0
    def delete(self, group_name):
        gr = c.repo_group = RepoGroup.guess_instance(group_name)
        repos = gr.repositories.all()
        if repos:
            h.flash(_('This group contains %s repositories and cannot be '
                      'deleted') % len(repos),
                    category='warning')
            raise HTTPFound(location=url('repos_groups'))

        children = gr.children.all()
        if children:
            h.flash(
                _('This group contains %s subgroups and cannot be deleted' %
                  (len(children))),
                category='warning')
            raise HTTPFound(location=url('repos_groups'))

        try:
            RepoGroupModel().delete(group_name)
            Session().commit()
            h.flash(_('Removed repository group %s') % group_name,
                    category='success')
            #TODO: in future action_logger(, '', '', '')
        except Exception:
            log.error(traceback.format_exc())
            h.flash(
                _('Error occurred during deletion of repository group %s') %
                group_name,
                category='error')

        if gr.parent_group:
            raise HTTPFound(location=url(
                'repos_group_home', group_name=gr.parent_group.group_name))
        raise HTTPFound(location=url('repos_groups'))
Пример #17
0
    def test_update_group_parent(self):

        sg1 = fixture.create_repo_group(u'initial', parent_group_id=self.g1.group_id)

        new_sg1 = _update_repo_group(sg1.group_id, u'after', parent_id=self.g1.group_id)
        assert self.__check_path('test1', 'after')
        assert RepoGroup.get_by_group_name(u'test1/initial') == None

        new_sg1 = _update_repo_group(sg1.group_id, u'after', parent_id=self.g3.group_id)
        assert self.__check_path('test3', 'after')
        assert RepoGroup.get_by_group_name(u'test3/initial') == None

        new_sg1 = _update_repo_group(sg1.group_id, u'hello')
        assert self.__check_path('hello')

        assert RepoGroup.get_by_group_name(u'hello') == new_sg1
Пример #18
0
    def update_perms(self, group_name):
        """
        Update permissions for given repository group

        :param group_name:
        """

        c.repo_group = RepoGroup.guess_instance(group_name)
        valid_recursive_choices = ['none', 'repos', 'groups', 'all']
        form_result = RepoGroupPermsForm(valid_recursive_choices)().to_python(
            request.POST)
        if not request.authuser.is_admin:
            if self._revoke_perms_on_yourself(form_result):
                msg = _('Cannot revoke permission for yourself as admin')
                h.flash(msg, category='warning')
                raise HTTPFound(location=url('edit_repo_group_perms',
                                             group_name=group_name))
        recursive = form_result['recursive']
        # iterate over all members(if in recursive mode) of this groups and
        # set the permissions !
        # this can be potentially heavy operation
        RepoGroupModel()._update_permissions(c.repo_group,
                                             form_result['perms_new'],
                                             form_result['perms_updates'],
                                             recursive)
        #TODO: implement this
        #action_logger(request.authuser, 'admin_changed_repo_permissions',
        #              repo_name, request.ip_addr)
        Session().commit()
        h.flash(_('Repository group permissions updated'), category='success')
        raise HTTPFound(
            location=url('edit_repo_group_perms', group_name=group_name))
Пример #19
0
        def _c():
            log.debug('generating switcher repo/groups list')
            all_repos = Repository.query(sorted=True).all()
            repo_iter = self.scm_model.get_repos(all_repos)
            all_groups = RepoGroup.query(sorted=True).all()
            repo_groups_iter = self.scm_model.get_repo_groups(all_groups)

            res = [{
                    'text': _('Groups'),
                    'children': [
                       {'id': obj.group_name,
                        'text': obj.group_name,
                        'type': 'group',
                        'obj': {}}
                       for obj in repo_groups_iter
                    ],
                   },
                   {
                    'text': _('Repositories'),
                    'children': [
                       {'id': obj.repo_name,
                        'text': obj.repo_name,
                        'type': 'repo',
                        'obj': obj.get_dict()}
                       for obj in repo_iter
                    ],
                   }]

            data = {
                'more': False,
                'results': res,
            }
            return data
Пример #20
0
    def test_update_group_parent(self):

        sg1 = fixture.create_repo_group(u'initial', group_parent_id=self.g1.group_id)

        new_sg1 = _update_group(sg1.group_id, u'after', parent_id=self.g1.group_id)
        self.assertTrue(self.__check_path('test1', 'after'))
        self.assertEqual(RepoGroup.get_by_group_name(u'test1/initial'), None)

        new_sg1 = _update_group(sg1.group_id, u'after', parent_id=self.g3.group_id)
        self.assertTrue(self.__check_path('test3', 'after'))
        self.assertEqual(RepoGroup.get_by_group_name(u'test3/initial'), None)

        new_sg1 = _update_group(sg1.group_id, u'hello')
        self.assertTrue(self.__check_path('hello'))

        self.assertEqual(RepoGroup.get_by_group_name(u'hello'), new_sg1)
Пример #21
0
    def test_update_group_parent(self):

        sg1 = fixture.create_repo_group('initial', parent_group_id=self.g1.group_id)

        new_sg1 = _update_repo_group(sg1.group_id, 'after', parent_id=self.g1.group_id)
        assert self.__check_path('test1', 'after')
        assert RepoGroup.get_by_group_name('test1/initial') is None

        new_sg1 = _update_repo_group(sg1.group_id, 'after', parent_id=self.g3.group_id)
        assert self.__check_path('test3', 'after')
        assert RepoGroup.get_by_group_name('test3/initial') == None

        new_sg1 = _update_repo_group(sg1.group_id, 'hello')
        assert self.__check_path('hello')

        assert RepoGroup.get_by_group_name('hello') == new_sg1
Пример #22
0
    def delete(self, group_name):
        gr = c.repo_group = RepoGroup.guess_instance(group_name)
        repos = gr.repositories.all()
        if repos:
            h.flash(_('This group contains %s repositories and cannot be '
                      'deleted') % len(repos), category='warning')
            raise HTTPFound(location=url('repos_groups'))

        children = gr.children.all()
        if children:
            h.flash(_('This group contains %s subgroups and cannot be deleted'
                      % (len(children))), category='warning')
            raise HTTPFound(location=url('repos_groups'))

        try:
            RepoGroupModel().delete(group_name)
            Session().commit()
            h.flash(_('Removed repository group %s') % group_name,
                    category='success')
            #TODO: in future action_logger(, '', '', '')
        except Exception:
            log.error(traceback.format_exc())
            h.flash(_('Error occurred during deletion of repository group %s')
                    % group_name, category='error')

        if gr.parent_group:
            raise HTTPFound(location=url('repos_group_home', group_name=gr.parent_group.group_name))
        raise HTTPFound(location=url('repos_groups'))
Пример #23
0
def permissions_setup_func(group_name='g0',
                           perm='group.read',
                           recursive='all',
                           user_id=None):
    """
    Resets all permissions to perm attribute
    """
    if not user_id:
        user_id = test_u1_id
        # called by the @with_setup decorator also reset the default user stuff
        permissions_setup_func(group_name,
                               perm,
                               recursive,
                               user_id=User.get_default_user().user_id)

    repo_group = RepoGroup.get_by_group_name(group_name=group_name)
    if not repo_group:
        raise Exception('Cannot get group %s' % group_name)

    perms_updates = [[user_id, perm, 'user']]
    RepoGroupModel()._update_permissions(repo_group,
                                         perms_updates=perms_updates,
                                         recursive=recursive,
                                         check_perms=False)
    Session().commit()
Пример #24
0
    def show(self, group_name):
        """GET /repo_groups/group_name: Show a specific item"""
        # url('repos_group', group_name=GROUP_NAME)
        c.active = 'settings'

        c.group = c.repo_group = RepoGroupModel()._get_repo_group(group_name)
        c.group_repos = c.group.repositories.all()

        #overwrite our cached list with current filter
        c.repo_cnt = 0

        groups = RepoGroup.query().order_by(RepoGroup.group_name)\
            .filter(RepoGroup.group_parent_id == c.group.group_id).all()
        c.groups = self.scm_model.get_repo_groups(groups)

        c.repos_list = Repository.query()\
                        .filter(Repository.group_id == c.group.group_id)\
                        .order_by(func.lower(Repository.repo_name))\
                        .all()

        repos_data = RepoModel().get_repos_as_dict(repos_list=c.repos_list,
                                                   admin=False)
        #json used to render the grid
        c.data = json.dumps(repos_data)

        return render('admin/repo_groups/repo_group_show.html')
Пример #25
0
    def update_perms(self, group_name):
        """
        Update permissions for given repository group

        :param group_name:
        """

        c.repo_group = RepoGroup.guess_instance(group_name)
        valid_recursive_choices = ['none', 'repos', 'groups', 'all']
        form_result = RepoGroupPermsForm(valid_recursive_choices)().to_python(request.POST)
        if not request.authuser.is_admin:
            if self._revoke_perms_on_yourself(form_result):
                msg = _('Cannot revoke permission for yourself as admin')
                h.flash(msg, category='warning')
                raise HTTPFound(location=url('edit_repo_group_perms', group_name=group_name))
        recursive = form_result['recursive']
        # iterate over all members(if in recursive mode) of this groups and
        # set the permissions !
        # this can be potentially heavy operation
        RepoGroupModel()._update_permissions(c.repo_group,
                                             form_result['perms_new'],
                                             form_result['perms_updates'],
                                             recursive)
        #TODO: implement this
        #action_logger(request.authuser, 'admin_changed_repo_permissions',
        #              repo_name, request.ip_addr)
        Session().commit()
        h.flash(_('Repository group permissions updated'), category='success')
        raise HTTPFound(location=url('edit_repo_group_perms', group_name=group_name))
Пример #26
0
        def validate_python(self, value, state):
            gr = RepoGroup.get(value)
            gr_name = gr.group_name if gr is not None else None # None means ROOT location

            # create repositories with write permission on group is set to true
            create_on_write = HasPermissionAny('hg.create.write_on_repogroup.true')()
            group_admin = HasRepoGroupPermissionAny('group.admin')(gr_name,
                                            'can write into group validator')
            group_write = HasRepoGroupPermissionAny('group.write')(gr_name,
                                            'can write into group validator')
            forbidden = not (group_admin or (group_write and create_on_write))
            can_create_repos = HasPermissionAny('hg.admin', 'hg.create.repository')
            gid = (old_data['repo_group'].get('group_id')
                   if (old_data and 'repo_group' in old_data) else None)
            value_changed = gid != value
            new = not old_data
            # do check if we changed the value, there's a case that someone got
            # revoked write permissions to a repository, he still created, we
            # don't need to check permission if he didn't change the value of
            # groups in form box
            if value_changed or new:
                #parent group need to be existing
                if gr and forbidden:
                    msg = M(self, 'permission_denied', state)
                    raise formencode.Invalid(msg, value, state,
                        error_dict=dict(repo_type=msg)
                    )
                ## check if we can write to root location !
                elif gr is None and not can_create_repos():
                    msg = M(self, 'permission_denied_root', state)
                    raise formencode.Invalid(msg, value, state,
                        error_dict=dict(repo_type=msg)
                    )
def permissions_setup_func(group_name='g0',
                           perm='group.read',
                           recursive='all',
                           user_id=None):
    """
    Resets all permissions to perm attribute
    """
    if not user_id:
        user_id = test_u1_id
        permissions_setup_func(group_name,
                               perm,
                               recursive,
                               user_id=kallithea.DEFAULT_USER_ID)

    repo_group = RepoGroup.get_by_group_name(group_name=group_name)
    if not repo_group:
        raise Exception('Cannot get group %s' % group_name)

    # Start with a baseline that current group can read recursive
    perms_updates = [[user_id, 'group.read', 'user']]
    RepoGroupModel()._update_permissions(repo_group,
                                         perms_updates=perms_updates,
                                         recursive='all',
                                         check_perms=False)

    perms_updates = [[user_id, perm, 'user']]
    RepoGroupModel()._update_permissions(repo_group,
                                         perms_updates=perms_updates,
                                         recursive=recursive,
                                         check_perms=False)
    Session().commit()
Пример #28
0
        def _c():
            log.debug('generating switcher repo/groups list')
            all_repos = Repository.query().order_by(Repository.repo_name).all()
            repo_iter = self.scm_model.get_repos(all_repos)
            all_groups = RepoGroup.query().order_by(RepoGroup.group_name).all()
            repo_groups_iter = self.scm_model.get_repo_groups(all_groups)

            res = [{
                    'text': _('Groups'),
                    'children': [
                       {'id': obj.group_name,
                        'text': obj.group_name,
                        'type': 'group',
                        'obj': {}}
                       for obj in repo_groups_iter
                    ],
                   },
                   {
                    'text': _('Repositories'),
                    'children': [
                       {'id': obj.repo_name,
                        'text': obj.repo_name,
                        'type': 'repo',
                        'obj': obj.get_dict()}
                       for obj in repo_iter
                    ],
                   }]

            data = {
                'more': False,
                'results': res,
            }
            return data
def permissions_setup_func(group_name='g0', perm='group.read', recursive='all',
                           user_id=None):
    """
    Resets all permissions to perm attribute
    """
    if not user_id:
        user_id = test_u1_id
        permissions_setup_func(group_name, perm, recursive,
                               user_id=User.get_default_user().user_id)

    repo_group = RepoGroup.get_by_group_name(group_name=group_name)
    if not repo_group:
        raise Exception('Cannot get group %s' % group_name)

    # Start with a baseline that current group can read recursive
    perms_updates = [[user_id, 'group.read', 'user']]
    RepoGroupModel()._update_permissions(repo_group,
                                         perms_updates=perms_updates,
                                         recursive='all', check_perms=False)

    perms_updates = [[user_id, perm, 'user']]
    RepoGroupModel()._update_permissions(repo_group,
                                         perms_updates=perms_updates,
                                         recursive=recursive, check_perms=False)
    Session().commit()
Пример #30
0
        def validate_python(self, value, state):
            # TODO WRITE VALIDATIONS
            group_name = value.get('group_name')
            group_parent_id = value.get('group_parent_id')

            # slugify repo group just in case :)
            slug = repo_name_slug(group_name)

            # check for parent of self
            parent_of_self = lambda: (
                old_data['group_id'] == group_parent_id
                if group_parent_id else False
            )
            if edit and parent_of_self():
                msg = M(self, 'group_parent_id', state)
                raise formencode.Invalid(msg, value, state,
                    error_dict=dict(group_parent_id=msg)
                )

            old_gname = None
            if edit:
                old_gname = RepoGroup.get(old_data.get('group_id')).group_name

            if old_gname != group_name or not edit:

                # check group
                gr = RepoGroup.query() \
                      .filter(RepoGroup.group_name == slug) \
                      .filter(RepoGroup.group_parent_id == group_parent_id) \
                      .scalar()

                if gr is not None:
                    msg = M(self, 'group_exists', state, group_name=slug)
                    raise formencode.Invalid(msg, value, state,
                            error_dict=dict(group_name=msg)
                    )

                # check for same repo
                repo = Repository.query() \
                      .filter(Repository.repo_name == slug) \
                      .scalar()

                if repo is not None:
                    msg = M(self, 'repo_exists', state, group_name=slug)
                    raise formencode.Invalid(msg, value, state,
                            error_dict=dict(group_name=msg)
                    )
Пример #31
0
 def delete(self, repo_group, force_delete=False):
     repo_group = RepoGroup.guess_instance(repo_group)
     try:
         Session().delete(repo_group)
         self._delete_group(repo_group, force_delete)
     except Exception:
         log.error('Error removing repo_group %s', repo_group)
         raise
Пример #32
0
def AvailableRepoGroupChoices(top_perms, repo_group_perm_level, extras=()):
    """Return group_id,string tuples with choices for all the repo groups where
    the user has the necessary permissions.

    Top level is -1.
    """
    groups = RepoGroup.query().all()
    if HasPermissionAny('hg.admin')('available repo groups'):
        groups.append(None)
    else:
        groups = list(RepoGroupList(groups, perm_level=repo_group_perm_level))
        if top_perms and HasPermissionAny(*top_perms)('available repo groups'):
            groups.append(None)
        for extra in extras:
            if not any(rg == extra for rg in groups):
                groups.append(extra)
    return RepoGroup.groups_choices(groups=groups)
Пример #33
0
 def get_repo_groups(self, groups=None):
     """Return the repo groups the user has access to
     If no groups are specified, use top level groups.
     """
     if groups is None:
         groups = RepoGroup.query() \
             .filter(RepoGroup.parent_group_id == None).all()
     return RepoGroupList(groups, perm_level='read')
Пример #34
0
 def get_repo_groups(self, groups=None):
     """Return the repo groups the user has access to
     If no groups are specified, use top level groups.
     """
     if groups is None:
         groups = RepoGroup.query() \
             .filter(RepoGroup.group_parent_id == None).all()
     return RepoGroupList(groups)
Пример #35
0
def AvailableRepoGroupChoices(top_perms, repo_group_perms, extras=()):
    """Return group_id,string tuples with choices for all the repo groups where
    the user has the necessary permissions.

    Top level is -1.
    """
    groups = RepoGroup.query().all()
    if HasPermissionAll('hg.admin')('available repo groups'):
        groups.append(None)
    else:
        groups = list(RepoGroupList(groups, perm_set=repo_group_perms))
        if top_perms and HasPermissionAny(*top_perms)('available repo groups'):
            groups.append(None)
        for extra in extras:
            if not any(rg == extra for rg in groups):
                groups.append(extra)
    return RepoGroup.groups_choices(groups=groups)
Пример #36
0
        def _validate_python(self, value, state):
            # TODO WRITE VALIDATIONS
            group_name = value.get('group_name')
            parent_group_id = value.get('parent_group_id')

            # slugify repo group just in case :)
            slug = repo_name_slug(group_name)

            # check for parent of self
            if edit and parent_group_id and old_data[
                    'group_id'] == parent_group_id:
                msg = self.message('parent_group_id', state)
                raise formencode.Invalid(msg,
                                         value,
                                         state,
                                         error_dict=dict(parent_group_id=msg))

            old_gname = None
            if edit:
                old_gname = RepoGroup.get(old_data.get('group_id')).group_name

            if old_gname != group_name or not edit:

                # check group
                gr = RepoGroup.query() \
                      .filter(func.lower(RepoGroup.group_name) == func.lower(slug)) \
                      .filter(RepoGroup.parent_group_id == parent_group_id) \
                      .scalar()
                if gr is not None:
                    msg = self.message('group_exists', state, group_name=slug)
                    raise formencode.Invalid(msg,
                                             value,
                                             state,
                                             error_dict=dict(group_name=msg))

                # check for same repo
                repo = Repository.query() \
                      .filter(func.lower(Repository.repo_name) == func.lower(slug)) \
                      .scalar()
                if repo is not None:
                    msg = self.message('repo_exists', state, group_name=slug)
                    raise formencode.Invalid(msg,
                                             value,
                                             state,
                                             error_dict=dict(group_name=msg))
Пример #37
0
def user_and_repo_group_fail():
    username = '******'
    groupname = 'repogroup_fail'
    user = fixture.create_user(name=username)
    repo_group = fixture.create_repo_group(name=groupname, cur_user=username)
    yield user, repo_group
    # cleanup
    if RepoGroup.get_by_group_name(groupname):
        fixture.destroy_repo_group(repo_group)
Пример #38
0
    def test_create_in_group(self):
        self.log_user()

        ## create GROUP
        group_name = 'sometest_%s' % self.REPO_TYPE
        gr = RepoGroupModel().create(group_name=group_name,
                                     group_description='test',
                                     owner=TEST_USER_ADMIN_LOGIN)
        Session().commit()

        repo_name = 'ingroup'
        repo_name_full = RepoGroup.url_sep().join([group_name, repo_name])
        description = 'description for newly created repo'
        response = self.app.post(
            url('repos'),
            fixture._get_repo_create_params(
                repo_private=False,
                repo_name=repo_name,
                repo_type=self.REPO_TYPE,
                repo_description=description,
                repo_group=gr.group_id,
            ))
        ## run the check page that triggers the flash message
        response = self.app.get(
            url('repo_check_home', repo_name=repo_name_full))
        self.assertEqual(response.json, {u'result': True})
        self.checkSessionFlash(
            response, 'Created repository <a href="/%s">%s</a>' %
            (repo_name_full, repo_name_full))
        # test if the repo was created in the database
        new_repo = Session().query(Repository)\
            .filter(Repository.repo_name == repo_name_full).one()
        new_repo_id = new_repo.repo_id

        self.assertEqual(new_repo.repo_name, repo_name_full)
        self.assertEqual(new_repo.description, description)

        # test if the repository is visible in the list ?
        response = self.app.get(url('summary_home', repo_name=repo_name_full))
        response.mustcontain(repo_name_full)
        response.mustcontain(self.REPO_TYPE)

        inherited_perms = UserRepoToPerm.query()\
            .filter(UserRepoToPerm.repository_id == new_repo_id).all()
        self.assertEqual(len(inherited_perms), 1)

        # test if the repository was created on filesystem
        try:
            vcs.get_repo(os.path.join(TESTS_TMP_PATH, repo_name_full))
        except vcs.exceptions.VCSError:
            RepoGroupModel().delete(group_name)
            Session().commit()
            self.fail('no repo %s in filesystem' % repo_name)

        RepoModel().delete(repo_name_full)
        RepoGroupModel().delete(group_name)
        Session().commit()
Пример #39
0
    def __load_defaults(self, allow_empty_group=False, exclude_group_ids=[]):
        if HasPermissionAll('hg.admin')('group edit'):
            #we're global admin, we're ok and we can create TOP level groups
            allow_empty_group = True

        #override the choices for this form, we need to filter choices
        #and display only those we have ADMIN right
        groups_with_admin_rights = RepoGroupList(RepoGroup.query().all(),
                                                 perm_set=['group.admin'])
        c.repo_groups = RepoGroup.groups_choices(groups=groups_with_admin_rights,
                                                 show_empty_group=allow_empty_group)
        # exclude filtered ids
        c.repo_groups = filter(lambda x: x[0] not in exclude_group_ids,
                               c.repo_groups)
        c.repo_groups_choices = map(lambda k: unicode(k[0]), c.repo_groups)
        repo_model = RepoModel()
        c.users_array = repo_model.get_users_js()
        c.user_groups_array = repo_model.get_user_groups_js()
Пример #40
0
    def update(self, repo, **kwargs):
        try:
            cur_repo = self._get_repo(repo)
            org_repo_name = cur_repo.repo_name
            if 'user' in kwargs:
                cur_repo.user = User.get_by_username(kwargs['user'])

            if 'repo_group' in kwargs:
                cur_repo.group = RepoGroup.get(kwargs['repo_group'])
            log.debug('Updating repo %s with params:%s' % (cur_repo, kwargs))
            for strip, k in [(1, 'repo_enable_downloads'),
                             (1, 'repo_description'),
                             (1, 'repo_enable_locking'),
                             (1, 'repo_landing_rev'),
                             (1, 'repo_private'),
                             (1, 'repo_enable_statistics'),
                             (0, 'clone_uri'),]:
                if k in kwargs:
                    val = kwargs[k]
                    if strip:
                        k = remove_prefix(k, 'repo_')
                    if k == 'clone_uri':
                        from kallithea.model.validators import Missing
                        _change = kwargs.get('clone_uri_change')
                        if _change == Missing:
                            # we don't change the value, so use original one
                            val = cur_repo.clone_uri

                    setattr(cur_repo, k, val)

            new_name = cur_repo.get_new_name(kwargs['repo_name'])
            cur_repo.repo_name = new_name
            #if private flag is set, reset default permission to NONE

            if kwargs.get('repo_private'):
                EMPTY_PERM = 'repository.none'
                RepoModel().grant_user_permission(
                    repo=cur_repo, user='******', perm=EMPTY_PERM
                )
                #handle extra fields
            for field in filter(lambda k: k.startswith(RepositoryField.PREFIX),
                                kwargs):
                k = RepositoryField.un_prefix_key(field)
                ex_field = RepositoryField.get_by_key_name(key=k, repo=cur_repo)
                if ex_field:
                    ex_field.field_value = kwargs[field]
                    self.sa.add(ex_field)
            self.sa.add(cur_repo)

            if org_repo_name != new_name:
                # rename repository
                self._rename_filesystem_repo(old=org_repo_name, new=new_name)

            return cur_repo
        except Exception:
            log.error(traceback.format_exc())
            raise
Пример #41
0
    def create(self,
               group_name,
               group_description,
               owner,
               parent=None,
               just_db=False,
               copy_permissions=False):
        try:
            user = self._get_user(owner)
            parent_group = self._get_repo_group(parent)
            new_repo_group = RepoGroup()
            new_repo_group.user = user
            new_repo_group.group_description = group_description or group_name
            new_repo_group.parent_group = parent_group
            new_repo_group.group_name = new_repo_group.get_new_name(group_name)

            self.sa.add(new_repo_group)

            # create an ADMIN permission for owner except if we're super admin,
            # later owner should go into the owner field of groups
            if not user.is_admin:
                self.grant_user_permission(repo_group=new_repo_group,
                                           user=owner,
                                           perm='group.admin')

            if parent_group and copy_permissions:
                # copy permissions from parent
                user_perms = UserRepoGroupToPerm.query() \
                    .filter(UserRepoGroupToPerm.group == parent_group).all()

                group_perms = UserGroupRepoGroupToPerm.query() \
                    .filter(UserGroupRepoGroupToPerm.group == parent_group).all()

                for perm in user_perms:
                    # don't copy over the permission for user who is creating
                    # this group, if he is not super admin he get's admin
                    # permission set above
                    if perm.user != user or user.is_admin:
                        UserRepoGroupToPerm.create(perm.user, new_repo_group,
                                                   perm.permission)

                for perm in group_perms:
                    UserGroupRepoGroupToPerm.create(perm.users_group,
                                                    new_repo_group,
                                                    perm.permission)
            else:
                perm_obj = self._create_default_perms(new_repo_group)
                self.sa.add(perm_obj)

            if not just_db:
                # we need to flush here, in order to check if database won't
                # throw any exceptions, create filesystem dirs at the very end
                self.sa.flush()
                self._create_group(new_repo_group.group_name)

            return new_repo_group
        except Exception:
            log.error(traceback.format_exc())
            raise
Пример #42
0
    def __load_defaults(self, repo=None):
        acl_groups = RepoGroupList(RepoGroup.query().all(),
                               perm_set=['group.write', 'group.admin'])
        c.repo_groups = RepoGroup.groups_choices(groups=acl_groups)
        c.repo_groups_choices = map(lambda k: unicode(k[0]), c.repo_groups)

        # in case someone no longer have a group.write access to a repository
        # pre fill the list with this entry, we don't care if this is the same
        # but it will allow saving repo data properly.

        repo_group = None
        if repo:
            repo_group = repo.group
        if repo_group and unicode(repo_group.group_id) not in c.repo_groups_choices:
            c.repo_groups_choices.append(unicode(repo_group.group_id))
            c.repo_groups.append(RepoGroup._generate_choice(repo_group))

        choices, c.landing_revs = ScmModel().get_repo_landing_revs()
        c.landing_revs_choices = choices
Пример #43
0
 def create_repo_group(self, name, parent_group_id=None, **kwargs):
     assert '/' not in name, (name, kwargs
                              )  # use group_parent_id to make nested groups
     if 'skip_if_exists' in kwargs:
         del kwargs['skip_if_exists']
         gr = RepoGroup.get_by_group_name(group_name=name)
         if gr:
             return gr
     form_data = self._get_repo_group_create_params(group_name=name,
                                                    **kwargs)
     gr = RepoGroupModel().create(
         group_name=form_data['group_name'],
         group_description=form_data['group_name'],
         parent=parent_group_id,
         owner=kwargs.get('cur_user', TEST_USER_ADMIN_LOGIN),
     )
     Session().commit()
     gr = RepoGroup.get_by_group_name(gr.group_name)
     return gr
Пример #44
0
 def show_by_name(self, group_name):
     """
     This is a proxy that does a lookup group_name -> id, and shows
     the group by id view instead
     """
     group_name = group_name.rstrip('/')
     id_ = RepoGroup.get_by_group_name(group_name)
     if id_:
         return self.show(group_name)
     raise HTTPNotFound
Пример #45
0
 def show_by_name(self, group_name):
     """
     This is a proxy that does a lookup group_name -> id, and shows
     the group by id view instead
     """
     group_name = group_name.rstrip('/')
     id_ = RepoGroup.get_by_group_name(group_name)
     if id_:
         return self.show(group_name)
     raise HTTPNotFound
Пример #46
0
    def __load_defaults(self, allow_empty_group=False, exclude_group_ids=[]):
        if HasPermissionAll('hg.admin')('group edit'):
            #we're global admin, we're ok and we can create TOP level groups
            allow_empty_group = True

        #override the choices for this form, we need to filter choices
        #and display only those we have ADMIN right
        groups_with_admin_rights = RepoGroupList(RepoGroup.query().all(),
                                                 perm_set=['group.admin'])
        c.repo_groups = RepoGroup.groups_choices(
            groups=groups_with_admin_rights,
            show_empty_group=allow_empty_group)
        # exclude filtered ids
        c.repo_groups = filter(lambda x: x[0] not in exclude_group_ids,
                               c.repo_groups)
        c.repo_groups_choices = map(lambda k: unicode(k[0]), c.repo_groups)
        repo_model = RepoModel()
        c.users_array = repo_model.get_users_js()
        c.user_groups_array = repo_model.get_user_groups_js()
Пример #47
0
    def index(self, format='html'):
        """GET /repo_groups: All items in the collection"""
        # url('repos_groups')
        _list = RepoGroup.query()\
                    .order_by(func.lower(RepoGroup.group_name))\
                    .all()
        group_iter = RepoGroupList(_list, perm_set=['group.admin'])
        repo_groups_data = []
        total_records = len(group_iter)
        _tmpl_lookup = kallithea.CONFIG['pylons.app_globals'].mako_lookup
        template = _tmpl_lookup.get_template('data_table/_dt_elements.html')

        repo_group_name = lambda repo_group_name, children_groups: (
            template.get_def("repo_group_name").render(
                repo_group_name, children_groups, _=_, h=h, c=c))
        repo_group_actions = lambda repo_group_id, repo_group_name, gr_count: (
            template.get_def("repo_group_actions").render(repo_group_id,
                                                          repo_group_name,
                                                          gr_count,
                                                          _=_,
                                                          h=h,
                                                          c=c,
                                                          ungettext=ungettext))

        for repo_gr in group_iter:
            children_groups = map(
                h.safe_unicode,
                itertools.chain((g.name for g in repo_gr.parents),
                                (x.name for x in [repo_gr])))
            repo_count = repo_gr.repositories.count()
            repo_groups_data.append({
                "raw_name":
                repo_gr.group_name,
                "group_name":
                repo_group_name(repo_gr.group_name, children_groups),
                "desc":
                repo_gr.group_description,
                "repos":
                repo_count,
                "owner":
                h.person(repo_gr.user),
                "action":
                repo_group_actions(repo_gr.group_id, repo_gr.group_name,
                                   repo_count)
            })

        c.data = json.dumps({
            "totalRecords": total_records,
            "startIndex": 0,
            "sort": None,
            "dir": "asc",
            "records": repo_groups_data
        })

        return render('admin/repo_groups/repo_groups.html')
Пример #48
0
    def update(self, repo, **kwargs):
        try:
            cur_repo = Repository.guess_instance(repo)
            org_repo_name = cur_repo.repo_name
            if 'owner' in kwargs:
                cur_repo.owner = User.get_by_username(kwargs['owner'])

            if 'repo_group' in kwargs:
                assert kwargs[
                    'repo_group'] != u'-1', kwargs  # RepoForm should have converted to None
                cur_repo.group = RepoGroup.get(kwargs['repo_group'])
                cur_repo.repo_name = cur_repo.get_new_name(cur_repo.just_name)
            log.debug('Updating repo %s with params:%s', cur_repo, kwargs)
            for k in [
                    'repo_enable_downloads',
                    'repo_description',
                    'repo_enable_locking',
                    'repo_landing_rev',
                    'repo_private',
                    'repo_enable_statistics',
            ]:
                if k in kwargs:
                    setattr(cur_repo, remove_prefix(k, 'repo_'), kwargs[k])
            clone_uri = kwargs.get('clone_uri')
            if clone_uri is not None and clone_uri != cur_repo.clone_uri_hidden:
                cur_repo.clone_uri = clone_uri

            if 'repo_name' in kwargs:
                cur_repo.repo_name = cur_repo.get_new_name(kwargs['repo_name'])

            #if private flag is set, reset default permission to NONE
            if kwargs.get('repo_private'):
                EMPTY_PERM = 'repository.none'
                RepoModel().grant_user_permission(repo=cur_repo,
                                                  user='******',
                                                  perm=EMPTY_PERM)
                #handle extra fields
            for field in filter(lambda k: k.startswith(RepositoryField.PREFIX),
                                kwargs):
                k = RepositoryField.un_prefix_key(field)
                ex_field = RepositoryField.get_by_key_name(key=k,
                                                           repo=cur_repo)
                if ex_field:
                    ex_field.field_value = kwargs[field]

            if org_repo_name != cur_repo.repo_name:
                # rename repository
                self._rename_filesystem_repo(old=org_repo_name,
                                             new=cur_repo.repo_name)

            return cur_repo
        except Exception:
            log.error(traceback.format_exc())
            raise
Пример #49
0
    def __load_defaults(self, repo=None):
        acl_groups = RepoGroupList(RepoGroup.query().all(),
                                   perm_set=['group.write', 'group.admin'])
        c.repo_groups = RepoGroup.groups_choices(groups=acl_groups)
        c.repo_groups_choices = map(lambda k: unicode(k[0]), c.repo_groups)

        # in case someone no longer have a group.write access to a repository
        # pre fill the list with this entry, we don't care if this is the same
        # but it will allow saving repo data properly.

        repo_group = None
        if repo:
            repo_group = repo.group
        if repo_group and unicode(
                repo_group.group_id) not in c.repo_groups_choices:
            c.repo_groups_choices.append(unicode(repo_group.group_id))
            c.repo_groups.append(RepoGroup._generate_choice(repo_group))

        choices, c.landing_revs = ScmModel().get_repo_landing_revs()
        c.landing_revs_choices = choices
Пример #50
0
        def _to_python(self, value, state):
            repo_name = repo_name_slug(value.get('repo_name', ''))
            repo_group = value.get('repo_group')
            if repo_group:
                gr = RepoGroup.get(repo_group)
                group_path = gr.full_path
                group_name = gr.group_name
                # value needs to be aware of group name in order to check
                # db key This is an actual just the name to store in the
                # database
                repo_name_full = group_path + RepoGroup.url_sep() + repo_name
            else:
                group_name = group_path = ''
                repo_name_full = repo_name

            value['repo_name'] = repo_name
            value['repo_name_full'] = repo_name_full
            value['group_path'] = group_path
            value['group_name'] = group_name
            return value
Пример #51
0
        def _to_python(self, value, state):
            repo_name = repo_name_slug(value.get('repo_name', ''))
            repo_group = value.get('repo_group')
            if repo_group:
                gr = RepoGroup.get(repo_group)
                group_path = gr.full_path
                group_name = gr.group_name
                # value needs to be aware of group name in order to check
                # db key This is an actual just the name to store in the
                # database
                repo_name_full = group_path + RepoGroup.url_sep() + repo_name
            else:
                group_name = group_path = ''
                repo_name_full = repo_name

            value['repo_name'] = repo_name
            value['repo_name_full'] = repo_name_full
            value['group_path'] = group_path
            value['group_name'] = group_name
            return value
Пример #52
0
    def test_create_in_group(self):
        self.log_user()

        ## create GROUP
        group_name = 'sometest_%s' % self.REPO_TYPE
        gr = RepoGroupModel().create(group_name=group_name,
                                     group_description='test',
                                     owner=TEST_USER_ADMIN_LOGIN)
        Session().commit()

        repo_name = 'ingroup'
        repo_name_full = RepoGroup.url_sep().join([group_name, repo_name])
        description = 'description for newly created repo'
        response = self.app.post(url('repos'),
                        fixture._get_repo_create_params(repo_private=False,
                                                repo_name=repo_name,
                                                repo_type=self.REPO_TYPE,
                                                repo_description=description,
                                                repo_group=gr.group_id,
                                                _authentication_token=self.authentication_token()))
        ## run the check page that triggers the flash message
        response = self.app.get(url('repo_check_home', repo_name=repo_name_full))
        self.assertEqual(response.json, {u'result': True})
        self.checkSessionFlash(response,
                               'Created repository <a href="/%s">%s</a>'
                               % (repo_name_full, repo_name_full))
        # test if the repo was created in the database
        new_repo = Session().query(Repository)\
            .filter(Repository.repo_name == repo_name_full).one()
        new_repo_id = new_repo.repo_id

        self.assertEqual(new_repo.repo_name, repo_name_full)
        self.assertEqual(new_repo.description, description)

        # test if the repository is visible in the list ?
        response = self.app.get(url('summary_home', repo_name=repo_name_full))
        response.mustcontain(repo_name_full)
        response.mustcontain(self.REPO_TYPE)

        inherited_perms = UserRepoToPerm.query()\
            .filter(UserRepoToPerm.repository_id == new_repo_id).all()
        self.assertEqual(len(inherited_perms), 1)

        # test if the repository was created on filesystem
        try:
            vcs.get_repo(os.path.join(TESTS_TMP_PATH, repo_name_full))
        except vcs.exceptions.VCSError:
            RepoGroupModel().delete(group_name)
            Session().commit()
            self.fail('no repo %s in filesystem' % repo_name)

        RepoModel().delete(repo_name_full)
        RepoGroupModel().delete(group_name)
        Session().commit()
Пример #53
0
    def test_repo_in_group_permissions(self):
        self.g1 = fixture.create_repo_group(u'group1', skip_if_exists=True)
        self.g2 = fixture.create_repo_group(u'group2', skip_if_exists=True)
        # both perms should be read !
        u1_auth = AuthUser(user_id=self.u1.user_id)
        assert u1_auth.permissions['repositories_groups'] == {u'group1': u'group.read', u'group2': u'group.read'}

        a1_auth = AuthUser(user_id=self.anon.user_id)
        assert a1_auth.permissions['repositories_groups'] == {u'group1': u'group.read', u'group2': u'group.read'}

        #Change perms to none for both groups
        RepoGroupModel().grant_user_permission(repo_group=self.g1,
                                               user=self.anon,
                                               perm='group.none')
        RepoGroupModel().grant_user_permission(repo_group=self.g2,
                                               user=self.anon,
                                               perm='group.none')

        u1_auth = AuthUser(user_id=self.u1.user_id)
        assert u1_auth.permissions['repositories_groups'] == {u'group1': u'group.none', u'group2': u'group.none'}

        a1_auth = AuthUser(user_id=self.anon.user_id)
        assert a1_auth.permissions['repositories_groups'] == {u'group1': u'group.none', u'group2': u'group.none'}

        # add repo to group
        name = RepoGroup.url_sep().join([self.g1.group_name, 'test_perm'])
        self.test_repo = fixture.create_repo(name=name,
                                             repo_type='hg',
                                             repo_group=self.g1,
                                             cur_user=self.u1,)

        u1_auth = AuthUser(user_id=self.u1.user_id)
        assert u1_auth.permissions['repositories_groups'] == {u'group1': u'group.none', u'group2': u'group.none'}

        a1_auth = AuthUser(user_id=self.anon.user_id)
        assert a1_auth.permissions['repositories_groups'] == {u'group1': u'group.none', u'group2': u'group.none'}

        #grant permission for u2 !
        RepoGroupModel().grant_user_permission(repo_group=self.g1, user=self.u2,
                                               perm='group.read')
        RepoGroupModel().grant_user_permission(repo_group=self.g2, user=self.u2,
                                               perm='group.read')
        Session().commit()
        assert self.u1 != self.u2
        #u1 and anon should have not change perms while u2 should !
        u1_auth = AuthUser(user_id=self.u1.user_id)
        assert u1_auth.permissions['repositories_groups'] == {u'group1': u'group.none', u'group2': u'group.none'}

        u2_auth = AuthUser(user_id=self.u2.user_id)
        assert u2_auth.permissions['repositories_groups'] == {u'group1': u'group.read', u'group2': u'group.read'}

        a1_auth = AuthUser(user_id=self.anon.user_id)
        assert a1_auth.permissions['repositories_groups'] == {u'group1': u'group.none', u'group2': u'group.none'}
Пример #54
0
    def edit_repo_group_perms(self, group_name):
        c.active = 'perms'
        c.repo_group = RepoGroup.guess_instance(group_name)
        self.__load_defaults()
        defaults = self.__load_data(c.repo_group.group_id)

        return htmlfill.render(
            render('admin/repo_groups/repo_group_edit.html'),
            defaults=defaults,
            encoding="UTF-8",
            force_defaults=False
        )
Пример #55
0
def _destroy_project_tree(test_u1_id):
    Session.remove()
    repo_group = RepoGroup.get_by_group_name(group_name='g0')
    for el in reversed(repo_group.recursive_groups_and_repos()):
        if isinstance(el, Repository):
            RepoModel().delete(el)
        elif isinstance(el, RepoGroup):
            RepoGroupModel().delete(el, force_delete=True)

    u = User.get(test_u1_id)
    Session().delete(u)
    Session().commit()
Пример #56
0
    def fixup_groups(self):
        def_usr = User.get_default_user()
        for g in RepoGroup.query().all():
            g.group_name = g.get_new_name(g.name)
            # get default perm
            default = UserRepoGroupToPerm.query() \
                .filter(UserRepoGroupToPerm.group == g) \
                .filter(UserRepoGroupToPerm.user == def_usr) \
                .scalar()

            if default is None:
                log.debug('missing default permission for group %s adding', g)
                RepoGroupModel()._create_default_perms(g)
Пример #57
0
def map_groups(path):
    """
    Given a full path to a repository, create all nested groups that this
    repo is inside. This function creates parent-child relationships between
    groups and creates default perms for all new groups.

    :param paths: full path to repository
    """
    sa = meta.Session()
    groups = path.split(Repository.url_sep())
    parent = None
    group = None

    # last element is repo in nested groups structure
    groups = groups[:-1]
    rgm = RepoGroupModel(sa)
    owner = User.get_first_admin()
    for lvl, group_name in enumerate(groups):
        group_name = u'/'.join(groups[:lvl] + [group_name])
        group = RepoGroup.get_by_group_name(group_name)
        desc = '%s group' % group_name

        # skip folders that are now removed repos
        if REMOVED_REPO_PAT.match(group_name):
            break

        if group is None:
            log.debug('creating group level: %s group_name: %s',
                      lvl, group_name)
            group = RepoGroup(group_name, parent)
            group.group_description = desc
            group.user = owner
            sa.add(group)
            perm_obj = rgm._create_default_perms(group)
            sa.add(perm_obj)
            sa.flush()

        parent = group
    return group
Пример #58
0
    def update(self, repo, **kwargs):
        try:
            cur_repo = self._get_repo(repo)
            org_repo_name = cur_repo.repo_name
            if 'user' in kwargs:
                cur_repo.user = User.get_by_username(kwargs['user'])

            if 'repo_group' in kwargs:
                cur_repo.group = RepoGroup.get(kwargs['repo_group'])
            log.debug('Updating repo %s with params:%s', cur_repo, kwargs)
            for k in ['repo_enable_downloads',
                      'repo_description',
                      'repo_enable_locking',
                      'repo_landing_rev',
                      'repo_private',
                      'repo_enable_statistics',
                      ]:
                if k in kwargs:
                    setattr(cur_repo, remove_prefix(k, 'repo_'), kwargs[k])
            clone_uri = kwargs.get('clone_uri')
            if clone_uri is not None and clone_uri != cur_repo.clone_uri_hidden:
                cur_repo.clone_uri = clone_uri

            new_name = cur_repo.get_new_name(kwargs['repo_name'])
            cur_repo.repo_name = new_name
            #if private flag is set, reset default permission to NONE

            if kwargs.get('repo_private'):
                EMPTY_PERM = 'repository.none'
                RepoModel().grant_user_permission(
                    repo=cur_repo, user='******', perm=EMPTY_PERM
                )
                #handle extra fields
            for field in filter(lambda k: k.startswith(RepositoryField.PREFIX),
                                kwargs):
                k = RepositoryField.un_prefix_key(field)
                ex_field = RepositoryField.get_by_key_name(key=k, repo=cur_repo)
                if ex_field:
                    ex_field.field_value = kwargs[field]
                    self.sa.add(ex_field)
            self.sa.add(cur_repo)

            if org_repo_name != new_name:
                # rename repository
                self._rename_filesystem_repo(old=org_repo_name, new=new_name)

            return cur_repo
        except Exception:
            log.error(traceback.format_exc())
            raise
Пример #59
0
    def edit(self, group_name):
        c.active = 'settings'

        c.repo_group = RepoGroup.guess_instance(group_name)
        self.__load_defaults(extras=[c.repo_group.parent_group],
                             exclude=[c.repo_group])
        defaults = self.__load_data(c.repo_group.group_id)

        return htmlfill.render(
            render('admin/repo_groups/repo_group_edit.html'),
            defaults=defaults,
            encoding="UTF-8",
            force_defaults=False
        )
Пример #60
0
    def create_repository(self):
        """GET /_admin/create_repository: Form to create a new item"""
        new_repo = request.GET.get('repo', '')
        parent_group = request.GET.get('parent_group')
        if not HasPermissionAny('hg.admin', 'hg.create.repository')():
            #you're not super admin nor have global create permissions,
            #but maybe you have at least write permission to a parent group ?
            _gr = RepoGroup.get(parent_group)
            gr_name = _gr.group_name if _gr else None
            # create repositories with write permission on group is set to true
            create_on_write = HasPermissionAny('hg.create.write_on_repogroup.true')()
            group_admin = HasRepoGroupPermissionAny('group.admin')(group_name=gr_name)
            group_write = HasRepoGroupPermissionAny('group.write')(group_name=gr_name)
            if not (group_admin or (group_write and create_on_write)):
                raise HTTPForbidden

        acl_groups = RepoGroupList(RepoGroup.query().all(),
                               perm_set=['group.write', 'group.admin'])
        c.repo_groups = RepoGroup.groups_choices(groups=acl_groups)
        c.repo_groups_choices = map(lambda k: unicode(k[0]), c.repo_groups)
        choices, c.landing_revs = ScmModel().get_repo_landing_revs()

        c.new_repo = repo_name_slug(new_repo)

        ## apply the defaults from defaults page
        defaults = Setting.get_default_repo_settings(strip_prefix=True)
        if parent_group:
            defaults.update({'repo_group': parent_group})

        return htmlfill.render(
            render('admin/repos/repo_add.html'),
            defaults=defaults,
            errors={},
            prefix_error=False,
            encoding="UTF-8",
            force_defaults=False)