Exemplo n.º 1
0
        def validate_python(self, value, state):
            if value in ['default']:
                msg = M(self, 'invalid_group', state)
                raise formencode.Invalid(msg, value, state,
                    error_dict=dict(users_group_name=msg)
                )
            #check if group is unique
            old_ugname = None
            if edit:
                old_id = old_data.get('users_group_id')
                old_ugname = UserGroup.get(old_id).users_group_name

            if old_ugname != value or not edit:
                is_existing_group = UserGroup.get_by_group_name(value,
                                                        case_insensitive=True)
                if is_existing_group:
                    msg = M(self, 'group_exist', state, usergroup=value)
                    raise formencode.Invalid(msg, value, state,
                        error_dict=dict(users_group_name=msg)
                    )

            if re.match(r'^[a-zA-Z0-9]{1}[a-zA-Z0-9\-\_\.]+$', value) is None:
                msg = M(self, 'invalid_usergroup_name', state)
                raise formencode.Invalid(msg, value, state,
                    error_dict=dict(users_group_name=msg)
                )
Exemplo n.º 2
0
 def create(self, name, active=True):
     try:
         new = UserGroup()
         new.users_group_name = name
         new.users_group_active = active
         self.sa.add(new)
         return new
     except Exception:
         log.error(traceback.format_exc())
         raise
Exemplo n.º 3
0
    def test_global_perms_on_group(self, repo_create, repo_create_write,
                                   user_group_create, repo_group_create,
                                   fork_create, expect_error,
                                   expect_form_error,
                                   inherit_default_permissions):
        self.log_user()
        users_group_name = TEST_USER_GROUP + 'another2'
        response = self.app.post(
            url('users_groups'), {
                'users_group_name': users_group_name,
                'user_group_description': 'DESC',
                'active': True,
                'csrf_token': self.csrf_token
            })

        ug = UserGroup.get_by_group_name(users_group_name)
        user_group_link = link_to(
            users_group_name,
            url('edit_users_group', user_group_id=ug.users_group_id))
        assert_session_flash(response,
                             'Created user group %s' % user_group_link)
        response.follow()

        # ENABLE REPO CREATE ON A GROUP
        perm_params = {
            'inherit_default_permissions': False,
            'default_repo_create': repo_create,
            'default_repo_create_on_write': repo_create_write,
            'default_user_group_create': user_group_create,
            'default_repo_group_create': repo_group_create,
            'default_fork_create': fork_create,
            'default_inherit_default_permissions': inherit_default_permissions,
            '_method': 'put',
            'csrf_token': self.csrf_token,
        }
        response = self.app.post(url('edit_user_group_global_perms',
                                     user_group_id=ug.users_group_id),
                                 params=perm_params)

        if expect_form_error:
            assert response.status_int == 200
            response.mustcontain('Value must be one of')
        else:
            if expect_error:
                msg = 'An error occurred during permissions saving'
            else:
                msg = 'User Group global permissions updated successfully'
                ug = UserGroup.get_by_group_name(users_group_name)
                del perm_params['_method']
                del perm_params['csrf_token']
                del perm_params['inherit_default_permissions']
                assert perm_params == ug.get_default_perms()
            assert_session_flash(response, msg)

        fixture.destroy_user_group(users_group_name)
Exemplo n.º 4
0
 def create_user_group(self, name, **kwargs):
     if "skip_if_exists" in kwargs:
         del kwargs["skip_if_exists"]
         gr = UserGroup.get_by_group_name(group_name=name)
         if gr:
             return gr
     form_data = self._get_user_group_create_params(name, **kwargs)
     owner = kwargs.get("cur_user", TEST_USER_ADMIN_LOGIN)
     user_group = UserGroupModel().create(
         name=form_data["users_group_name"], owner=owner, active=form_data["users_group_active"]
     )
     Session().commit()
     user_group = UserGroup.get_by_group_name(user_group.users_group_name)
     return user_group
Exemplo n.º 5
0
 def create_user_group(self, name, **kwargs):
     if 'skip_if_exists' in kwargs:
         del kwargs['skip_if_exists']
         gr = UserGroup.get_by_group_name(group_name=name)
         if gr:
             return gr
     form_data = self._get_user_group_create_params(name, **kwargs)
     owner = kwargs.get('cur_user', TEST_USER_ADMIN_LOGIN)
     user_group = UserGroupModel().create(
         name=form_data['users_group_name'],
         owner=owner,
         active=form_data['users_group_active'])
     Session().commit()
     user_group = UserGroup.get_by_group_name(user_group.users_group_name)
     return user_group
Exemplo n.º 6
0
    def enforce_groups(self, user, groups, extern_type=None):
        user = self._get_user(user)
        log.debug('Enforcing groups %s on user %s', groups, user)
        current_groups = user.group_member
        # find the external created groups
        externals = [
            x.users_group for x in current_groups
            if 'extern_type' in x.users_group.group_data
        ]

        # calculate from what groups user should be removed
        # externals that are not in groups
        for gr in externals:
            if gr.users_group_name not in groups:
                log.debug('Removing user %s from user group %s', user, gr)
                self.remove_user_from_group(gr, user)

        # now we calculate in which groups user should be == groups params
        owner = User.get_first_super_admin().username
        for gr in set(groups):
            existing_group = UserGroup.get_by_group_name(gr)
            if not existing_group:
                desc = 'Automatically created from plugin:%s' % extern_type
                # we use first admin account to set the owner of the group
                existing_group = UserGroupModel().create(
                    gr, desc, owner, group_data={'extern_type': extern_type})

            # we can only add users to special groups created via plugins
            managed = 'extern_type' in existing_group.group_data
            if managed:
                log.debug('Adding user %s to user group %s', user, gr)
                UserGroupModel().add_user_to_group(existing_group, user)
            else:
                log.debug('Skipping addition to group %s since it is '
                          'not managed by auth plugins' % gr)
Exemplo n.º 7
0
    def test_delete(self):
        self.log_user()
        users_group_name = TEST_USER_GROUP + 'another'
        response = self.app.post(
            url('users_groups'), {
                'users_group_name': users_group_name,
                'user_group_description': 'DESC',
                'active': True,
                'csrf_token': self.csrf_token
            })

        user_group_link = link_to(
            users_group_name,
            url('edit_users_group',
                user_group_id=UserGroup.get_by_group_name(
                    users_group_name).users_group_id))
        assert_session_flash(response,
                             'Created user group %s' % user_group_link)

        group = Session().query(UserGroup).filter(
            UserGroup.users_group_name == users_group_name).one()

        response = self.app.post(url('delete_users_group',
                                     user_group_id=group.users_group_id),
                                 params={
                                     '_method': 'delete',
                                     'csrf_token': self.csrf_token
                                 })

        group = Session().query(UserGroup).filter(
            UserGroup.users_group_name == users_group_name).scalar()

        assert group is None
Exemplo n.º 8
0
    def create(self, name, owner, active=True):
        try:
            new_user_group = UserGroup()
            new_user_group.user = self._get_user(owner)
            new_user_group.users_group_name = name
            new_user_group.users_group_active = active
            self.sa.add(new_user_group)
            perm_obj = self._create_default_perms(new_user_group)
            self.sa.add(perm_obj)

            self.grant_user_permission(user_group=new_user_group, user=owner, perm="usergroup.admin")

            return new_user_group
        except Exception:
            log.error(traceback.format_exc())
            raise
Exemplo n.º 9
0
    def __load_defaults(self, user_group_id):
        """
        Load defaults settings for edit, and update

        :param user_group_id:
        """
        user_group = UserGroup.get_or_404(user_group_id)
        data = user_group.get_dict()

        ug_model = UserGroupModel()

        data.update({
            'create_repo_perm':
            ug_model.has_perm(user_group, 'hg.create.repository'),
            'create_user_group_perm':
            ug_model.has_perm(user_group, 'hg.usergroup.create.true'),
            'fork_repo_perm':
            ug_model.has_perm(user_group, 'hg.fork.repository'),
        })

        # fill user group users
        for p in user_group.user_user_group_to_perm:
            data.update(
                {'u_perm_%s' % p.user.username: p.permission.permission_name})

        for p in user_group.user_group_user_group_to_perm:
            data.update({
                'g_perm_%s' % p.user_group.users_group_name:
                p.permission.permission_name
            })

        return data
Exemplo n.º 10
0
    def step_12(self):
        self.klass.create_permissions()
        Session().commit()

        self.klass.populate_default_permissions()
        Session().commit()

        #fix all usergroups
        ug_model = UserGroupModel()
        for ug in UserGroup.get_all():
            perm_obj = ug_model._create_default_perms(ug)
            Session().add(perm_obj)
        Session().commit()

        adm = User.get_first_admin()
        # fix owners of UserGroup
        for ug in Session().query(UserGroup).all():
            ug.user_id = adm.user_id
            Session().add(ug)
        Session().commit()

        # fix owners of RepoGroup
        for ug in Session().query(RepoGroup).all():
            ug.user_id = adm.user_id
            Session().add(ug)
        Session().commit()
Exemplo n.º 11
0
    def edit_perms_summary(self, user_group_id):
        user_group_id = safe_int(user_group_id)
        c.user_group = UserGroup.get_or_404(user_group_id)
        c.active = 'perms_summary'
        permissions = {
            'repositories': {},
            'repositories_groups': {},
        }
        ugroup_repo_perms = UserGroupRepoToPerm.query()\
            .options(joinedload(UserGroupRepoToPerm.permission))\
            .options(joinedload(UserGroupRepoToPerm.repository))\
            .filter(UserGroupRepoToPerm.users_group_id == user_group_id)\
            .all()

        for gr in ugroup_repo_perms:
            permissions['repositories'][gr.repository.repo_name]  \
                = gr.permission.permission_name

        ugroup_group_perms = UserGroupRepoGroupToPerm.query()\
            .options(joinedload(UserGroupRepoGroupToPerm.permission))\
            .options(joinedload(UserGroupRepoGroupToPerm.group))\
            .filter(UserGroupRepoGroupToPerm.users_group_id == user_group_id)\
            .all()

        for gr in ugroup_group_perms:
            permissions['repositories_groups'][gr.group.group_name] \
                = gr.permission.permission_name
        c.permissions = permissions
        return render('admin/user_groups/user_group_edit.html')
Exemplo n.º 12
0
    def update_perms(self, user_group_id):
        """
        grant permission for given usergroup

        :param user_group_id:
        """
        user_group_id = safe_int(user_group_id)
        c.user_group = UserGroup.get_or_404(user_group_id)
        form = UserGroupPermsForm()().to_python(request.POST)

        if not c.rhodecode_user.is_admin:
            if self._revoke_perms_on_yourself(form):
                msg = _('Cannot change permission for yourself as admin')
                h.flash(msg, category='warning')
                return redirect(
                    url('edit_user_group_perms', user_group_id=user_group_id))

        try:
            UserGroupModel().update_permissions(user_group_id,
                                                form['perm_additions'],
                                                form['perm_updates'],
                                                form['perm_deletions'])
        except RepoGroupAssignmentError:
            h.flash(_('Target group cannot be the same'), category='error')
            return redirect(
                url('edit_user_group_perms', user_group_id=user_group_id))
        #TODO: implement this
        #action_logger(c.rhodecode_user, 'admin_changed_repo_permissions',
        #              repo_name, self.ip_addr, self.sa)
        Session().commit()
        h.flash(_('User Group permissions updated'), category='success')
        return redirect(
            url('edit_user_group_perms', user_group_id=user_group_id))
Exemplo n.º 13
0
    def step_12(self):
        self.klass.create_permissions()
        Session().commit()

        self.klass.populate_default_permissions()
        Session().commit()

        #fix all usergroups
        ug_model = UserGroupModel()
        for ug in UserGroup.get_all():
            perm_obj = ug_model._create_default_perms(ug)
            Session().add(perm_obj)
        Session().commit()

        adm = User.get_first_admin()
        # fix owners of UserGroup
        for ug in Session().query(UserGroup).all():
            ug.user_id = adm.user_id
            Session().add(ug)
        Session().commit()

        # fix owners of RepoGroup
        for ug in Session().query(RepoGroup).all():
            ug.user_id = adm.user_id
            Session().add(ug)
        Session().commit()
Exemplo n.º 14
0
    def __load_defaults(self, user_group_id):
        """
        Load defaults settings for edit, and update

        :param user_group_id:
        """
        user_group = UserGroup.get_or_404(user_group_id)
        data = user_group.get_dict()

        ug_model = UserGroupModel()

        data.update({
            'create_repo_perm': ug_model.has_perm(user_group,
                                                  'hg.create.repository'),
            'create_user_group_perm': ug_model.has_perm(user_group,
                                                  'hg.usergroup.create.true'),
            'fork_repo_perm': ug_model.has_perm(user_group,
                                                'hg.fork.repository'),
        })

        # fill user group users
        for p in user_group.user_user_group_to_perm:
            data.update({'u_perm_%s' % p.user.username:
                             p.permission.permission_name})

        for p in user_group.user_group_user_group_to_perm:
            data.update({'g_perm_%s' % p.user_group.users_group_name:
                             p.permission.permission_name})

        return data
Exemplo n.º 15
0
    def create(self, name, owner, active=True):
        try:
            new_user_group = UserGroup()
            new_user_group.user = self._get_user(owner)
            new_user_group.users_group_name = name
            new_user_group.users_group_active = active
            self.sa.add(new_user_group)
            perm_obj = self._create_default_perms(new_user_group)
            self.sa.add(perm_obj)

            self.grant_user_permission(user_group=new_user_group,
                                       user=owner,
                                       perm='usergroup.admin')

            return new_user_group
        except Exception:
            log.error(traceback.format_exc())
            raise
Exemplo n.º 16
0
    def index(self, format='html'):
        """GET /users_groups: All items in the collection"""
        # url('users_groups')

        group_iter = UserGroupList(UserGroup().query().all(),
                                   perm_set=['usergroup.admin'])
        sk = lambda g: g.users_group_name
        c.users_groups_list = sorted(group_iter, key=sk)
        return render('admin/users_groups/users_groups.html')
Exemplo n.º 17
0
def get_user_group_slug(request):
    _group = request.environ['pylons.routes_dict'].get('id')
    try:
        _group = UserGroup.get(_group)
        if _group:
            _group = _group.users_group_name
    except Exception:
        log.debug(traceback.format_exc())
        #catch all failures here
        pass

    return _group
Exemplo n.º 18
0
    def update_global_perms(self, user_group_id):
        """PUT /users_perm/user_group_id: Update an existing item"""
        # url('users_group_perm', user_group_id=ID, method='put')
        user_group_id = safe_int(user_group_id)
        user_group = UserGroup.get_or_404(user_group_id)
        c.active = 'global_perms'

        try:
            # first stage that verifies the checkbox
            _form = UserIndividualPermissionsForm()
            form_result = _form.to_python(dict(request.POST))
            inherit_perms = form_result['inherit_default_permissions']
            user_group.inherit_default_permissions = inherit_perms
            Session().add(user_group)

            if not inherit_perms:
                # only update the individual ones if we un check the flag
                _form = UserPermissionsForm(
                    [x[0] for x in c.repo_create_choices],
                    [x[0] for x in c.repo_create_on_write_choices],
                    [x[0] for x in c.repo_group_create_choices],
                    [x[0] for x in c.user_group_create_choices],
                    [x[0] for x in c.fork_choices],
                    [x[0] for x in c.inherit_default_permission_choices])()

                form_result = _form.to_python(dict(request.POST))
                form_result.update(
                    {'perm_user_group_id': user_group.users_group_id})

                PermissionModel().update_user_group_permissions(form_result)

            Session().commit()
            h.flash(_('User Group global permissions updated successfully'),
                    category='success')

        except formencode.Invalid as errors:
            defaults = errors.value
            c.user_group = user_group
            return htmlfill.render(
                render('admin/user_groups/user_group_edit.html'),
                defaults=defaults,
                errors=errors.error_dict or {},
                prefix_error=False,
                encoding="UTF-8",
                force_defaults=False)

        except Exception:
            log.exception("Exception during permissions saving")
            h.flash(_('An error occurred during permissions saving'),
                    category='error')

        return redirect(
            url('edit_user_group_global_perms', user_group_id=user_group_id))
Exemplo n.º 19
0
def get_user_group_slug(request):
    _group = request.environ['pylons.routes_dict'].get('id')
    try:
        _group = UserGroup.get(_group)
        if _group:
            _group = _group.users_group_name
    except Exception:
        log.debug(traceback.format_exc())
        #catch all failures here
        pass

    return _group
Exemplo n.º 20
0
    def edit(self, id, format='html'):
        """GET /users_groups/id/edit: Form to edit an existing item"""
        # url('edit_users_group', id=ID)

        c.users_group = UserGroup.get_or_404(id)
        self.__load_data(id)

        defaults = self.__load_defaults(id)

        return htmlfill.render(
            render('admin/users_groups/users_group_edit.html'),
            defaults=defaults,
            encoding="UTF-8",
            force_defaults=False)
Exemplo n.º 21
0
    def edit_members(self, user_group_id):
        user_group_id = safe_int(user_group_id)
        c.user_group = UserGroup.get_or_404(user_group_id)
        c.active = 'members'
        c.group_members_obj = sorted((x.user for x in c.user_group.members),
                                     key=lambda u: u.username.lower())

        group_members = [(x.user_id, x.username) for x in c.group_members_obj]

        if request.is_xhr:
            return jsonify(lambda *a, **k: {'members': group_members})

        c.group_members = group_members
        return render('admin/user_groups/user_group_edit.html')
Exemplo n.º 22
0
    def update_perm(self, id):
        """PUT /users_perm/id: Update an existing item"""
        # url('users_group_perm', id=ID, method='put')

        users_group = UserGroup.get_or_404(id)
        grant_create_perm = str2bool(request.POST.get('create_repo_perm'))
        grant_fork_perm = str2bool(request.POST.get('fork_repo_perm'))
        inherit_perms = str2bool(
            request.POST.get('inherit_default_permissions'))

        usergroup_model = UserGroupModel()

        try:
            users_group.inherit_default_permissions = inherit_perms
            Session().add(users_group)

            if grant_create_perm:
                usergroup_model.revoke_perm(id, 'hg.create.none')
                usergroup_model.grant_perm(id, 'hg.create.repository')
                h.flash(
                    _("Granted 'repository create' permission to user group"),
                    category='success')
            else:
                usergroup_model.revoke_perm(id, 'hg.create.repository')
                usergroup_model.grant_perm(id, 'hg.create.none')
                h.flash(
                    _("Revoked 'repository create' permission to user group"),
                    category='success')

            if grant_fork_perm:
                usergroup_model.revoke_perm(id, 'hg.fork.none')
                usergroup_model.grant_perm(id, 'hg.fork.repository')
                h.flash(
                    _("Granted 'repository fork' permission to user group"),
                    category='success')
            else:
                usergroup_model.revoke_perm(id, 'hg.fork.repository')
                usergroup_model.grant_perm(id, 'hg.fork.none')
                h.flash(
                    _("Revoked 'repository fork' permission to user group"),
                    category='success')

            Session().commit()
        except Exception:
            log.error(traceback.format_exc())
            h.flash(_('An error occurred during permissions saving'),
                    category='error')

        return redirect(url('edit_users_group', id=id))
Exemplo n.º 23
0
    def edit(self, id, format='html'):
        """GET /users_groups/id/edit: Form to edit an existing item"""
        # url('edit_users_group', id=ID)

        c.users_group = UserGroup.get_or_404(id)
        self.__load_data(id)

        defaults = self.__load_defaults(id)

        return htmlfill.render(
            render('admin/users_groups/users_group_edit.html'),
            defaults=defaults,
            encoding="UTF-8",
            force_defaults=False
        )
Exemplo n.º 24
0
    def edit_global_perms(self, user_group_id):
        user_group_id = safe_int(user_group_id)
        c.user_group = UserGroup.get_or_404(user_group_id)
        c.active = 'global_perms'

        c.default_user = User.get_default_user()
        defaults = c.user_group.get_dict()
        defaults.update(c.default_user.get_default_perms(suffix='_inherited'))
        defaults.update(c.user_group.get_default_perms())

        return htmlfill.render(
            render('admin/user_groups/user_group_edit.html'),
            defaults=defaults,
            encoding="UTF-8",
            force_defaults=False)
Exemplo n.º 25
0
    def __load_defaults(self, user_group_id):
        """
        Load defaults settings for edit, and update

        :param user_group_id:
        """
        user_group = UserGroup.get_or_404(user_group_id)
        data = user_group.get_dict()
        # fill owner
        if user_group.user:
            data.update({'user': user_group.user.username})
        else:
            replacement_user = User.get_first_super_admin().username
            data.update({'user': replacement_user})
        return data
Exemplo n.º 26
0
 def delete(self, id):
     """DELETE /users_groups/id: Delete an existing item"""
     # Forms posted to this method should contain a hidden field:
     #    <input type="hidden" name="_method" value="DELETE" />
     # Or using helpers:
     #    h.form(url('users_group', id=ID),
     #           method='delete')
     # url('users_group', id=ID)
     usr_gr = UserGroup.get_or_404(id)
     try:
         UserGroupModel().delete(usr_gr)
         Session().commit()
         h.flash(_('Successfully deleted user group'), category='success')
     except UserGroupsAssignedException, e:
         h.flash(e, category='error')
Exemplo n.º 27
0
 def delete(self, id):
     """DELETE /users_groups/id: Delete an existing item"""
     # Forms posted to this method should contain a hidden field:
     #    <input type="hidden" name="_method" value="DELETE" />
     # Or using helpers:
     #    h.form(url('users_group', id=ID),
     #           method='delete')
     # url('users_group', id=ID)
     usr_gr = UserGroup.get_or_404(id)
     try:
         UserGroupModel().delete(usr_gr)
         Session().commit()
         h.flash(_('Successfully deleted user group'), category='success')
     except UserGroupsAssignedException, e:
         h.flash(e, category='error')
Exemplo n.º 28
0
 def update_user_group_permissions(self, form_result):
     if 'perm_user_group_id' in form_result:
         perm_user_group = UserGroup.get(
             safe_int(form_result['perm_user_group_id']))
     else:
         # used mostly to do lookup for default user
         perm_user_group = UserGroup.get_by_group_name(
             form_result['perm_user_group_name'])
     try:
         # stage 2 reset defaults and set them from form data
         self._set_new_user_group_perms(perm_user_group,
                                        form_result,
                                        preserve=[
                                            'default_repo_perm',
                                            'default_group_perm',
                                            'default_user_group_perm',
                                            'default_register',
                                            'default_extern_activate'
                                        ])
         self.sa.commit()
     except (DatabaseError, ):
         log.error(traceback.format_exc())
         self.sa.rollback()
         raise
Exemplo n.º 29
0
    def update(self, user_group_id):
        """PUT /user_groups/user_group_id: Update an existing item"""
        # Forms posted to this method should contain a hidden field:
        #    <input type="hidden" name="_method" value="PUT" />
        # Or using helpers:
        #    h.form(url('users_group', user_group_id=ID),
        #           method='put')
        # url('users_group', user_group_id=ID)

        user_group_id = safe_int(user_group_id)
        c.user_group = UserGroup.get_or_404(user_group_id)
        c.active = 'settings'
        self.__load_data(user_group_id)

        available_members = [safe_unicode(x[0]) for x in c.available_members]

        users_group_form = UserGroupForm(edit=True,
                                         old_data=c.user_group.get_dict(),
                                         available_members=available_members,
                                         allow_disabled=True)()

        try:
            form_result = users_group_form.to_python(request.POST)
            UserGroupModel().update(c.user_group, form_result)
            gr = form_result['users_group_name']
            action_logger(c.rhodecode_user,
                          'admin_updated_users_group:%s' % gr, None,
                          self.ip_addr, self.sa)
            h.flash(_('Updated user group %s') % gr, category='success')
            Session().commit()
        except formencode.Invalid as errors:
            defaults = errors.value
            e = errors.error_dict or {}

            return htmlfill.render(
                render('admin/user_groups/user_group_edit.html'),
                defaults=defaults,
                errors=e,
                prefix_error=False,
                encoding="UTF-8",
                force_defaults=False)
        except Exception:
            log.exception("Exception during update of user group")
            h.flash(_('Error occurred during update of user group %s') %
                    request.POST.get('users_group_name'),
                    category='error')

        return redirect(url('edit_users_group', user_group_id=user_group_id))
Exemplo n.º 30
0
    def edit(self, user_group_id):
        """GET /user_groups/user_group_id/edit: Form to edit an existing item"""
        # url('edit_users_group', user_group_id=ID)

        user_group_id = safe_int(user_group_id)
        c.user_group = UserGroup.get_or_404(user_group_id)
        c.active = 'settings'
        self.__load_data(user_group_id)

        defaults = self.__load_defaults(user_group_id)

        return htmlfill.render(
            render('admin/user_groups/user_group_edit.html'),
            defaults=defaults,
            encoding="UTF-8",
            force_defaults=False)
Exemplo n.º 31
0
    def edit_advanced(self, user_group_id):
        user_group_id = safe_int(user_group_id)
        c.user_group = UserGroup.get_or_404(user_group_id)
        c.active = 'advanced'
        c.group_members_obj = sorted((x.user for x in c.user_group.members),
                                     key=lambda u: u.username.lower())

        c.group_to_repos = sorted(
            (x.repository for x in c.user_group.users_group_repo_to_perm),
            key=lambda u: u.repo_name.lower())

        c.group_to_repo_groups = sorted(
            (x.group for x in c.user_group.users_group_repo_group_to_perm),
            key=lambda u: u.group_name.lower())

        return render('admin/user_groups/user_group_edit.html')
Exemplo n.º 32
0
def test_create_and_remove(test_user):
    usr = test_user

    # make user group
    user_group = fixture.create_user_group('some_example_group')
    Session().commit()

    UserGroupModel().add_user_to_group(user_group, usr)
    Session().commit()

    assert UserGroup.get(user_group.users_group_id) == user_group
    assert UserGroupMember.query().count() == 1
    UserModel().delete(usr.user_id)
    Session().commit()

    assert UserGroupMember.query().all() == []
Exemplo n.º 33
0
    def update(self, id):
        """PUT /users_groups/id: Update an existing item"""
        # Forms posted to this method should contain a hidden field:
        #    <input type="hidden" name="_method" value="PUT" />
        # Or using helpers:
        #    h.form(url('users_group', id=ID),
        #           method='put')
        # url('users_group', id=ID)

        c.users_group = UserGroup.get_or_404(id)
        self._load_data(id)

        available_members = [safe_unicode(x[0]) for x in c.available_members]

        users_group_form = UserGroupForm(edit=True,
                                         old_data=c.users_group.get_dict(),
                                         available_members=available_members)()

        try:
            form_result = users_group_form.to_python(request.POST)
            UserGroupModel().update(c.users_group, form_result)
            gr = form_result['users_group_name']
            action_logger(self.rhodecode_user,
                          'admin_updated_users_group:%s' % gr, None,
                          self.ip_addr, self.sa)
            h.flash(_('Updated user group %s') % gr, category='success')
            Session().commit()
        except formencode.Invalid, errors:
            ug_model = UserGroupModel()
            defaults = errors.value
            e = errors.error_dict or {}
            defaults.update({
                'create_repo_perm':
                ug_model.has_perm(id, 'hg.create.repository'),
                'fork_repo_perm':
                ug_model.has_perm(id, 'hg.fork.repository'),
                '_method':
                'put'
            })

            return htmlfill.render(
                render('admin/users_groups/users_group_edit.html'),
                defaults=defaults,
                errors=e,
                prefix_error=False,
                encoding="UTF-8")
Exemplo n.º 34
0
    def update(self, id):
        """PUT /users_groups/id: Update an existing item"""
        # Forms posted to this method should contain a hidden field:
        #    <input type="hidden" name="_method" value="PUT" />
        # Or using helpers:
        #    h.form(url('users_group', id=ID),
        #           method='put')
        # url('users_group', id=ID)

        c.users_group = UserGroup.get_or_404(id)
        self.__load_data(id)

        available_members = [safe_unicode(x[0]) for x in c.available_members]

        users_group_form = UserGroupForm(edit=True,
                                          old_data=c.users_group.get_dict(),
                                          available_members=available_members)()

        try:
            form_result = users_group_form.to_python(request.POST)
            UserGroupModel().update(c.users_group, form_result)
            gr = form_result['users_group_name']
            action_logger(self.rhodecode_user,
                          'admin_updated_users_group:%s' % gr,
                          None, self.ip_addr, self.sa)
            h.flash(_('Updated user group %s') % gr, category='success')
            Session().commit()
        except formencode.Invalid, errors:
            ug_model = UserGroupModel()
            defaults = errors.value
            e = errors.error_dict or {}
            defaults.update({
                'create_repo_perm': ug_model.has_perm(id,
                                                      'hg.create.repository'),
                'fork_repo_perm': ug_model.has_perm(id,
                                                    'hg.fork.repository'),
                '_method': 'put'
            })

            return htmlfill.render(
                render('admin/users_groups/users_group_edit.html'),
                defaults=defaults,
                errors=e,
                prefix_error=False,
                encoding="UTF-8")
Exemplo n.º 35
0
    def test_create(self):
        self.log_user()
        users_group_name = TEST_USER_GROUP
        response = self.app.post(
            url('users_groups'), {
                'users_group_name': users_group_name,
                'user_group_description': 'DESC',
                'active': True,
                'csrf_token': self.csrf_token
            })

        user_group_link = link_to(
            users_group_name,
            url('edit_users_group',
                user_group_id=UserGroup.get_by_group_name(
                    users_group_name).users_group_id))
        assert_session_flash(response,
                             'Created user group %s' % user_group_link)
Exemplo n.º 36
0
    def update_perm(self, id):
        """PUT /users_perm/id: Update an existing item"""
        # url('users_group_perm', id=ID, method='put')

        users_group = UserGroup.get_or_404(id)
        grant_create_perm = str2bool(request.POST.get('create_repo_perm'))
        grant_fork_perm = str2bool(request.POST.get('fork_repo_perm'))
        inherit_perms = str2bool(request.POST.get('inherit_default_permissions'))

        usergroup_model = UserGroupModel()

        try:
            users_group.inherit_default_permissions = inherit_perms
            Session().add(users_group)

            if grant_create_perm:
                usergroup_model.revoke_perm(id, 'hg.create.none')
                usergroup_model.grant_perm(id, 'hg.create.repository')
                h.flash(_("Granted 'repository create' permission to user group"),
                        category='success')
            else:
                usergroup_model.revoke_perm(id, 'hg.create.repository')
                usergroup_model.grant_perm(id, 'hg.create.none')
                h.flash(_("Revoked 'repository create' permission to user group"),
                        category='success')

            if grant_fork_perm:
                usergroup_model.revoke_perm(id, 'hg.fork.none')
                usergroup_model.grant_perm(id, 'hg.fork.repository')
                h.flash(_("Granted 'repository fork' permission to user group"),
                        category='success')
            else:
                usergroup_model.revoke_perm(id, 'hg.fork.repository')
                usergroup_model.grant_perm(id, 'hg.fork.none')
                h.flash(_("Revoked 'repository fork' permission to user group"),
                        category='success')

            Session().commit()
        except Exception:
            log.error(traceback.format_exc())
            h.flash(_('An error occurred during permissions saving'),
                    category='error')

        return redirect(url('edit_users_group', id=id))
Exemplo n.º 37
0
    def update_perm(self, id):
        """PUT /users_perm/id: Update an existing item"""
        # url('users_group_perm', id=ID, method='put')

        users_group = UserGroup.get_or_404(id)

        try:
            form = CustomDefaultPermissionsForm()()
            form_result = form.to_python(request.POST)

            inherit_perms = form_result['inherit_default_permissions']
            users_group.inherit_default_permissions = inherit_perms
            Session().add(users_group)
            usergroup_model = UserGroupModel()

            defs = UserGroupToPerm.query()\
                .filter(UserGroupToPerm.users_group == users_group)\
                .all()
            for ug in defs:
                Session().delete(ug)

            if form_result['create_repo_perm']:
                usergroup_model.grant_perm(id, 'hg.create.repository')
            else:
                usergroup_model.grant_perm(id, 'hg.create.none')
            if form_result['create_user_group_perm']:
                usergroup_model.grant_perm(id, 'hg.usergroup.create.true')
            else:
                usergroup_model.grant_perm(id, 'hg.usergroup.create.false')
            if form_result['fork_repo_perm']:
                usergroup_model.grant_perm(id, 'hg.fork.repository')
            else:
                usergroup_model.grant_perm(id, 'hg.fork.none')

            h.flash(_("Updated permissions"), category='success')
            Session().commit()
        except Exception:
            log.error(traceback.format_exc())
            h.flash(_('An error occurred during permissions saving'),
                    category='error')

        return redirect(url('edit_users_group', id=id))
Exemplo n.º 38
0
    def update_perm(self, id):
        """PUT /users_perm/id: Update an existing item"""
        # url('users_group_perm', id=ID, method='put')

        users_group = UserGroup.get_or_404(id)

        try:
            form = CustomDefaultPermissionsForm()()
            form_result = form.to_python(request.POST)

            inherit_perms = form_result['inherit_default_permissions']
            users_group.inherit_default_permissions = inherit_perms
            Session().add(users_group)
            usergroup_model = UserGroupModel()

            defs = UserGroupToPerm.query()\
                .filter(UserGroupToPerm.users_group == users_group)\
                .all()
            for ug in defs:
                Session().delete(ug)

            if form_result['create_repo_perm']:
                usergroup_model.grant_perm(id, 'hg.create.repository')
            else:
                usergroup_model.grant_perm(id, 'hg.create.none')
            if form_result['create_user_group_perm']:
                usergroup_model.grant_perm(id, 'hg.usergroup.create.true')
            else:
                usergroup_model.grant_perm(id, 'hg.usergroup.create.false')
            if form_result['fork_repo_perm']:
                usergroup_model.grant_perm(id, 'hg.fork.repository')
            else:
                usergroup_model.grant_perm(id, 'hg.fork.none')

            h.flash(_("Updated permissions"), category='success')
            Session().commit()
        except Exception:
            log.error(traceback.format_exc())
            h.flash(_('An error occurred during permissions saving'),
                    category='error')

        return redirect(url('edit_users_group', id=id))
Exemplo n.º 39
0
    def index(self):
        """GET /users_groups: All items in the collection"""
        # url('users_groups')

        from rhodecode.lib.utils import PartialRenderer
        _render = PartialRenderer('data_table/_dt_elements.html')

        def user_group_name(user_group_id, user_group_name):
            return _render("user_group_name", user_group_id, user_group_name)

        def user_group_actions(user_group_id, user_group_name):
            return _render("user_group_actions", user_group_id,
                           user_group_name)

        ## json generate
        group_iter = UserGroupList(UserGroup.query().all(),
                                   perm_set=['usergroup.admin'])

        user_groups_data = []
        for user_gr in group_iter:
            user_groups_data.append({
                "group_name":
                user_group_name(user_gr.users_group_id,
                                h.escape(user_gr.users_group_name)),
                "group_name_raw":
                user_gr.users_group_name,
                "desc":
                h.escape(user_gr.user_group_description),
                "members":
                len(user_gr.members),
                "active":
                h.bool2icon(user_gr.users_group_active),
                "owner":
                h.escape(h.link_to_user(user_gr.user.username)),
                "action":
                user_group_actions(user_gr.users_group_id,
                                   user_gr.users_group_name)
            })

        c.data = json.dumps(user_groups_data)
        return render('admin/user_groups/user_groups.html')
Exemplo n.º 40
0
    def edit(self, id, format='html'):
        """GET /users_groups/id/edit: Form to edit an existing item"""
        # url('edit_users_group', id=ID)

        c.users_group = UserGroup.get_or_404(id)
        self._load_data(id)

        ug_model = UserGroupModel()
        defaults = c.users_group.get_dict()
        defaults.update({
            'create_repo_perm':
            ug_model.has_perm(c.users_group, 'hg.create.repository'),
            'fork_repo_perm':
            ug_model.has_perm(c.users_group, 'hg.fork.repository'),
        })

        return htmlfill.render(
            render('admin/users_groups/users_group_edit.html'),
            defaults=defaults,
            encoding="UTF-8",
            force_defaults=False)
Exemplo n.º 41
0
    def test_create_and_remove(self):
        usr = UserModel().create_or_update(username=u'test_user',
                                           password=u'qweqwe',
                                     email=u'*****@*****.**',
                                     firstname=u'u1', lastname=u'u1')
        Session().commit()
        self.assertEqual(User.get_by_username(u'test_user'), usr)

        # make user group
        users_group = UserGroupModel().create('some_example_group')
        Session().commit()

        UserGroupModel().add_user_to_group(users_group, usr)
        Session().commit()

        self.assertEqual(UserGroup.get(users_group.users_group_id), users_group)
        self.assertEqual(UserGroupMember.query().count(), 1)
        UserModel().delete(usr.user_id)
        Session().commit()

        self.assertEqual(UserGroupMember.query().all(), [])
Exemplo n.º 42
0
    def edit(self, id, format='html'):
        """GET /users_groups/id/edit: Form to edit an existing item"""
        # url('edit_users_group', id=ID)

        c.users_group = UserGroup.get_or_404(id)
        self._load_data(id)

        ug_model = UserGroupModel()
        defaults = c.users_group.get_dict()
        defaults.update({
            'create_repo_perm': ug_model.has_perm(c.users_group,
                                                  'hg.create.repository'),
            'fork_repo_perm': ug_model.has_perm(c.users_group,
                                                'hg.fork.repository'),
        })

        return htmlfill.render(
            render('admin/users_groups/users_group_edit.html'),
            defaults=defaults,
            encoding="UTF-8",
            force_defaults=False
        )
Exemplo n.º 43
0
    def set_user_group_perm_member(self, id):
        """
        grant permission for given usergroup

        :param id:
        """
        user_group = UserGroup.get_or_404(id)
        form = UserGroupPermsForm()().to_python(request.POST)

        # set the permissions !
        try:
            UserGroupModel()._update_permissions(user_group, form['perms_new'],
                                                 form['perms_updates'])
        except RepoGroupAssignmentError:
            h.flash(_('Target group cannot be the same'), category='error')
            return redirect(url('edit_users_group', id=id))
        #TODO: implement this
        #action_logger(self.rhodecode_user, 'admin_changed_repo_permissions',
        #              repo_name, self.ip_addr, self.sa)
        Session().commit()
        h.flash(_('User Group permissions updated'), category='success')
        return redirect(url('edit_users_group', id=id))
    def test_enable_repository_read_on_group(self):
        self.log_user()
        users_group_name = TEST_USER_GROUP + 'another2'
        response = self.app.post(url('users_groups'),
                                 {'users_group_name': users_group_name,
                                  'active': True})
        response.follow()

        ug = UserGroup.get_by_group_name(users_group_name)
        self.checkSessionFlash(response,
                               'Created user group %s' % users_group_name)
        ## ENABLE REPO CREATE ON A GROUP
        response = self.app.put(url('users_group_perm', id=ug.users_group_id),
                                 {'create_repo_perm': True})

        response.follow()
        ug = UserGroup.get_by_group_name(users_group_name)
        p = Permission.get_by_key('hg.create.repository')
        p2 = Permission.get_by_key('hg.usergroup.create.false')
        p3 = Permission.get_by_key('hg.fork.none')
        # check if user has this perms, they should be here since
        # defaults are on
        perms = UserGroupToPerm.query()\
            .filter(UserGroupToPerm.users_group == ug).all()

        self.assertEqual(
            sorted([[x.users_group_id, x.permission_id, ] for x in perms]),
            sorted([[ug.users_group_id, p.permission_id],
                    [ug.users_group_id, p2.permission_id],
                    [ug.users_group_id, p3.permission_id]])
        )

        ## DISABLE REPO CREATE ON A GROUP
        response = self.app.put(url('users_group_perm', id=ug.users_group_id),
                                    {})

        response.follow()
        ug = UserGroup.get_by_group_name(users_group_name)
        p = Permission.get_by_key('hg.create.none')
        p2 = Permission.get_by_key('hg.usergroup.create.false')
        p3 = Permission.get_by_key('hg.fork.none')

        # check if user has this perms, they should be here since
        # defaults are on
        perms = UserGroupToPerm.query()\
            .filter(UserGroupToPerm.users_group == ug).all()

        self.assertEqual(
            sorted([[x.users_group_id, x.permission_id, ] for x in perms]),
            sorted([[ug.users_group_id, p.permission_id],
                    [ug.users_group_id, p2.permission_id],
                    [ug.users_group_id, p3.permission_id]])
        )

        # DELETE !
        ug = UserGroup.get_by_group_name(users_group_name)
        ugid = ug.users_group_id
        response = self.app.delete(url('users_group', id=ug.users_group_id))
        response = response.follow()
        gr = Session().query(UserGroup)\
                           .filter(UserGroup.users_group_name ==
                                   users_group_name).scalar()

        self.assertEqual(gr, None)
        p = Permission.get_by_key('hg.create.repository')
        perms = UserGroupToPerm.query()\
            .filter(UserGroupToPerm.users_group_id == ugid).all()
        perms = [[x.users_group_id,
                  x.permission_id, ] for x in perms]
        self.assertEqual(
            perms,
            []
        )
Exemplo n.º 45
0
 def get(self, users_group_id, cache=False):
     return UserGroup.get(users_group_id)
Exemplo n.º 46
0
 def get_by_name(self, name, cache=False, case_insensitive=False):
     return UserGroup.get_by_group_name(name, cache, case_insensitive)
Exemplo n.º 47
0
        def to_python(self, value, state):
            perms_update = OrderedSet()
            perms_new = OrderedSet()
            # build a list of permission to update and new permission to create

            #CLEAN OUT ORG VALUE FROM NEW MEMBERS, and group them using
            new_perms_group = defaultdict(dict)
            for k, v in value.copy().iteritems():
                if k.startswith('perm_new_member'):
                    del value[k]
                    _type, part = k.split('perm_new_member_')
                    args = part.split('_')
                    if len(args) == 1:
                        new_perms_group[args[0]]['perm'] = v
                    elif len(args) == 2:
                        _key, pos = args
                        new_perms_group[pos][_key] = v

            # fill new permissions in order of how they were added
            for k in sorted(map(int, new_perms_group.keys())):
                perm_dict = new_perms_group[str(k)]
                new_member = perm_dict.get('name')
                new_perm = perm_dict.get('perm')
                new_type = perm_dict.get('type')
                if new_member and new_perm and new_type:
                    perms_new.add((new_member, new_perm, new_type))

            for k, v in value.iteritems():
                if k.startswith('u_perm_') or k.startswith('g_perm_'):
                    member = k[7:]
                    t = {'u': 'user',
                         'g': 'users_group'
                    }[k[0]]
                    if member == 'default':
                        if str2bool(value.get('repo_private')):
                            # set none for default when updating to
                            # private repo protects agains form manipulation
                            v = EMPTY_PERM
                    perms_update.add((member, v, t))

            value['perms_updates'] = list(perms_update)
            value['perms_new'] = list(perms_new)

            # update permissions
            for k, v, t in perms_new:
                try:
                    if t is 'user':
                        self.user_db = User.query()\
                            .filter(User.active == True)\
                            .filter(User.username == k).one()
                    if t is 'users_group':
                        self.user_db = UserGroup.query()\
                            .filter(UserGroup.users_group_active == True)\
                            .filter(UserGroup.users_group_name == k).one()

                except Exception:
                    log.exception('Updated permission failed')
                    msg = M(self, 'perm_new_member_type', state)
                    raise formencode.Invalid(msg, value, state,
                        error_dict=dict(perm_new_member_name=msg)
                    )
            return value