Ejemplo n.º 1
0
 def create(self, name, active=True):
     try:
         new = UsersGroup()
         new.users_group_name = name
         new.users_group_active = active
         self.sa.add(new)
         return new
     except:
         log.error(traceback.format_exc())
         raise
Ejemplo n.º 2
0
    def get_users_group(self, apiuser, group_name):
        """"
        Get users group by name

        :param apiuser:
        :param group_name:
        """

        users_group = UsersGroup.get_by_group_name(group_name)
        if not users_group:
            return None

        members = []
        for user in users_group.members:
            user = user.user
            members.append(dict(id=user.user_id,
                            username=user.username,
                            firstname=user.name,
                            lastname=user.lastname,
                            email=user.email,
                            active=user.active,
                            admin=user.admin,
                            ldap=user.ldap_dn))

        return dict(id=users_group.users_group_id,
                    group_name=users_group.users_group_name,
                    active=users_group.users_group_active,
                    members=members)
Ejemplo n.º 3
0
    def add_user_to_users_group(self, apiuser, group_name, username):
        """"
        Add a user to a users group

        :param apiuser:
        :param group_name:
        :param username:
        """

        try:
            users_group = UsersGroup.get_by_group_name(group_name)
            if not users_group:
                raise JSONRPCError('unknown users group %s' % group_name)

            user = User.get_by_username(username)
            if user is None:
                raise JSONRPCError('unknown user %s' % username)

            ugm = UsersGroupModel().add_user_to_group(users_group, user)
            success = True if ugm != True else False
            msg = 'added member %s to users group %s' % (username, group_name)
            msg = msg if success else 'User is already in that group'
            Session.commit()

            return dict(
                id=ugm.users_group_member_id if ugm != True else None,
                success=success,
                msg=msg
            )
        except Exception:
            log.error(traceback.format_exc())
            raise JSONRPCError('failed to add users group member')
Ejemplo n.º 4
0
    def add_user_to_users_group(self, apiuser, group_name, user_name):
        """"
        Add a user to a group

        :param apiuser
        :param group_name
        :param user_name
        """

        try:
            users_group = UsersGroup.get_by_group_name(group_name)
            if not users_group:
                raise JSONRPCError('unknown users group %s' % group_name)

            try:
                user = User.get_by_username(user_name)
            except NoResultFound:
                raise JSONRPCError('unknown user %s' % user_name)

            ugm = UsersGroupModel().add_user_to_group(users_group, user)

            return dict(id=ugm.users_group_member_id,
                        msg='created new users group member')
        except Exception:
            log.error(traceback.format_exc())
            raise JSONRPCError('failed to create users group member')
Ejemplo n.º 5
0
    def revoke_users_group_permission(self, apiuser, repo_name, group_name):
        """
        Revoke permission for users group on given repository

        :param repo_name:
        :param group_name:
        """

        try:
            repo = Repository.get_by_repo_name(repo_name)
            if repo is None:
                raise JSONRPCError('unknown repository %s' % repo)

            user_group = UsersGroup.get_by_group_name(group_name)
            if user_group is None:
                raise JSONRPCError('unknown users group %s' % user_group)

            RepoModel().revoke_users_group_permission(repo=repo_name,
                                                      group_name=group_name)

            Session.commit()
            return dict(
                msg='Revoked perm for group: %s in repo: %s' % (
                    group_name, repo_name
                )
            )
        except Exception:
            log.error(traceback.format_exc())
            raise JSONRPCError(
                'failed to edit permission %(repo)s for %(usersgr)s' % dict(
                    usersgr=group_name, repo=repo_name
                )
            )
Ejemplo n.º 6
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 = UsersGroup.get_or_404(id)

        c.users_group.permissions = {}
        c.group_members_obj = [x.user for x in c.users_group.members]
        c.group_members = [(x.user_id, x.username) for x in
                           c.group_members_obj]
        c.available_members = [(x.user_id, x.username) for x in
                               User.query().all()]
        ug_model = UsersGroupModel()
        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
        )
Ejemplo n.º 7
0
    def get_users_group(self, apiuser, group_name):
        """"
        Get users group by name

        :param apiuser:
        :param group_name:
        """

        users_group = UsersGroup.get_by_group_name(group_name)
        if not users_group:
            return None

        members = []
        for user in users_group.members:
            user = user.user
            members.append(dict(id=user.user_id,
                            username=user.username,
                            firstname=user.name,
                            lastname=user.lastname,
                            email=user.email,
                            active=user.active,
                            admin=user.admin,
                            ldap=user.ldap_dn))

        return dict(id=users_group.users_group_id,
                    name=users_group.users_group_name,
                    active=users_group.users_group_active,
                    members=members)
Ejemplo n.º 8
0
    def get_users_groups(self, apiuser):
        """"
        Get all users groups

        :param apiuser:
        """

        result = []
        for users_group in UsersGroup.getAll():
            members = []
            for user in users_group.members:
                user = user.user
                members.append(dict(id=user.user_id,
                                username=user.username,
                                firstname=user.name,
                                lastname=user.lastname,
                                email=user.email,
                                active=user.active,
                                admin=user.admin,
                                ldap=user.ldap_dn))

            result.append(dict(id=users_group.users_group_id,
                                name=users_group.users_group_name,
                                active=users_group.users_group_active,
                                members=members))
        return result
Ejemplo n.º 9
0
    def get_users_groups(self, apiuser):
        """"
        Get all users groups

        :param apiuser:
        """

        result = []
        for users_group in UsersGroup.getAll():
            members = []
            for user in users_group.members:
                user = user.user
                members.append(dict(id=user.user_id,
                                username=user.username,
                                firstname=user.name,
                                lastname=user.lastname,
                                email=user.email,
                                active=user.active,
                                admin=user.admin,
                                ldap=user.ldap_dn))

            result.append(dict(id=users_group.users_group_id,
                                group_name=users_group.users_group_name,
                                active=users_group.users_group_active,
                                members=members))
        return result
Ejemplo n.º 10
0
    def remove_user_from_users_group(self, apiuser, group_name, username):
        """
        Remove user from a group

        :param apiuser
        :param group_name
        :param username
        """

        try:
            users_group = UsersGroup.get_by_group_name(group_name)
            if not users_group:
                raise JSONRPCError('unknown users group %s' % group_name)

            user = User.get_by_username(username)
            if user is None:
                raise JSONRPCError('unknown user %s' % username)

            success = UsersGroupModel().remove_user_from_group(users_group, user)
            msg = 'removed member %s from users group %s' % (username, group_name)
            msg = msg if success else "User wasn't in group"
            Session.commit()
            return dict(success=success, msg=msg)
        except Exception:
            log.error(traceback.format_exc())
            raise JSONRPCError('failed to remove user from group')
Ejemplo n.º 11
0
    def test_enable_repository_read_on_group(self):
        self.log_user()
        users_group_name = TEST_USERS_GROUP + 'another2'
        response = self.app.post(url('users_groups'),
                                 {'users_group_name': users_group_name,
                                  'active':True})
        response.follow()

        ug = UsersGroup.get_by_group_name(users_group_name)
        self.checkSessionFlash(response,
                               'created users group %s' % users_group_name)

        response = self.app.put(url('users_group_perm', id=ug.users_group_id),
                                 {'create_repo_perm': True})

        response.follow()
        ug = UsersGroup.get_by_group_name(users_group_name)
        p = Permission.get_by_key('hg.create.repository')
        # check if user has this perm
        perms = UsersGroupToPerm.query()\
            .filter(UsersGroupToPerm.users_group == ug).all()
        perms = [[x.__dict__['users_group_id'],
                  x.__dict__['permission_id'],] for x in perms]
        self.assertEqual(
            perms,
            [[ug.users_group_id, p.permission_id]]
        )

        # DELETE !
        ug = UsersGroup.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 = self.Session.query(UsersGroup)\
                           .filter(UsersGroup.users_group_name ==
                                   users_group_name).scalar()

        self.assertEqual(gr, None)
        p = Permission.get_by_key('hg.create.repository')
        perms = UsersGroupToPerm.query()\
            .filter(UsersGroupToPerm.users_group_id == ugid).all()
        perms = [[x.__dict__['users_group_id'],
                  x.__dict__['permission_id'],] for x in perms]
        self.assertEqual(
            perms,
            []
        )
Ejemplo n.º 12
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 value.get("private"):
                            # set none for default when updating to
                            # private repo
                            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 = (
                            UsersGroup.query()
                            .filter(UsersGroup.users_group_active == True)
                            .filter(UsersGroup.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
Ejemplo n.º 13
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 = UsersGroup.get(old_id).users_group_name

            if old_ugname != value or not edit:
                is_existing_group = UsersGroup.get_by_group_name(value, case_insensitive=True)
                if is_existing_group:
                    msg = M(self, "group_exist", state, usersgroup=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_usersgroup_name", state)
                raise formencode.Invalid(msg, value, state, error_dict=dict(users_group_name=msg))
Ejemplo n.º 14
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 = UsersGroup.get(id)
        c.group_members_obj = [x.user for x in c.users_group.members]
        c.group_members = [(x.user_id, x.username) for x in
                           c.group_members_obj]

        c.available_members = [(x.user_id, x.username) for x in
                               User.query().all()]

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

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

        try:
            form_result = users_group_form.to_python(request.POST)
            UsersGroupModel().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 users group %s') % gr, category='success')
            Session().commit()
        except formencode.Invalid, errors:
            ug_model = UsersGroupModel()
            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")
Ejemplo n.º 15
0
 def create_users_group(self, apiuser, name, active):
     """
     Creates an new usergroup
     
     :param name:
     :param active:
     """
     form_data = {"users_group_name": name, "users_group_active": active}
     try:
         ug = UsersGroup.create(form_data)
         return {"id": ug.users_group_id, "msg": "created new users group %s" % name}
     except Exception:
         log.error(traceback.format_exc())
         raise JSONRPCError("failed to create group %s" % name)
Ejemplo n.º 16
0
        def validate_python(self, value, state):
            if value in ['default']:
                raise formencode.Invalid(_('Invalid group name'), value, state)
            #check if group is unique
            old_ugname = None
            if edit:
                old_ugname = UsersGroup.get(
                            old_data.get('users_group_id')).users_group_name

            if old_ugname != value or not edit:
                if UsersGroup.get_by_group_name(value, cache=False,
                                               case_insensitive=True):
                    raise formencode.Invalid(_('This users group '
                                               'already exists') , value,
                                             state)


            if re.match(r'^[a-zA-Z0-9]{1}[a-zA-Z0-9\-\_\.]+$', value) is None:
                raise formencode.Invalid(_('Group name may only contain '
                                           'alphanumeric characters '
                                           'underscores, periods or dashes '
                                           'and must begin with alphanumeric '
                                           'character'), value, state)
Ejemplo n.º 17
0
        def validate_python(self, value, state):
            if value in ['default']:
                raise formencode.Invalid(_('Invalid group name'), value, state)
            #check if group is unique
            old_ugname = None
            if edit:
                old_ugname = UsersGroup.get(
                            old_data.get('users_group_id')).users_group_name

            if old_ugname != value or not edit:
                if UsersGroup.get_by_group_name(value, cache=False,
                                               case_insensitive=True):
                    raise formencode.Invalid(_('This users group '
                                               'already exists'), value,
                                             state)

            if re.match(r'^[a-zA-Z0-9]{1}[a-zA-Z0-9\-\_\.]+$', value) is None:
                raise formencode.Invalid(
                    _('RepoGroup name may only contain  alphanumeric characters '
                      'underscores, periods or dashes and must begin with '
                      'alphanumeric character'),
                    value,
                    state
                )
Ejemplo n.º 18
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 = UsersGroup.get_or_404(id)
     try:
         UsersGroupModel().delete(usr_gr)
         Session().commit()
         h.flash(_('successfully deleted users group'), category='success')
     except UsersGroupsAssignedException, e:
         h.flash(e, category='error')
Ejemplo n.º 19
0
        def to_python(self, value, state):
            perms_update = []
            perms_new = []
            # build a list of permission to update and new permission to create
            for k, v in value.items():
                # means new added member to permissions
                if k.startswith('perm_new_member'):
                    new_perm = value.get('perm_new_member', False)
                    new_member = value.get('perm_new_member_name', False)
                    new_type = value.get('perm_new_member_type')

                    if new_member and new_perm:
                        if (new_member, new_perm, new_type) not in perms_new:
                            perms_new.append((new_member, new_perm, new_type))
                elif k.startswith('u_perm_') or k.startswith('g_perm_'):
                    member = k[7:]
                    t = {'u': 'user',
                         'g': 'users_group'
                    }[k[0]]
                    if member == 'default':
                        if value.get('private'):
                            # set none for default when updating to private repo
                            v = EMPTY_PERM
                    perms_update.append((member, v, t))

            value['perms_updates'] = perms_update
            value['perms_new'] = 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 = UsersGroup.query()\
                            .filter(UsersGroup.users_group_active == True)\
                            .filter(UsersGroup.users_group_name == k).one()

                except Exception:
                    msg = self.message('perm_new_member_name',
                                         state=State_obj)
                    raise formencode.Invalid(
                        msg, value, state, error_dict={'perm_new_member_name': msg}
                    )
            return value
Ejemplo n.º 20
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 = UsersGroup.get(id)
        c.group_members_obj = [x.user for x in c.users_group.members]
        c.group_members = [(x.user_id, x.username)
                           for x in c.group_members_obj]

        c.available_members = [(x.user_id, x.username)
                               for x in self.sa.query(User).all()]

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

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

        try:
            form_result = users_group_form.to_python(request.POST)
            UsersGroupModel().update(c.users_group, form_result)
            h.flash(_('updated users group %s') \
                        % form_result['users_group_name'],
                    category='success')
            #action_logger(self.rhodecode_user, 'new_user', '', '', self.sa)
            Session.commit()
        except formencode.Invalid, errors:
            e = errors.error_dict or {}

            perm = Permission.get_by_key('hg.create.repository')
            e.update(
                {'create_repo_perm': UsersGroupModel().has_perm(id, perm)})

            return htmlfill.render(
                render('admin/users_groups/users_group_edit.html'),
                defaults=errors.value,
                errors=e,
                prefix_error=False,
                encoding="UTF-8")
Ejemplo n.º 21
0
    def update_perm(self, id):
        """PUT /users_perm/id: Update an existing item"""
        # url('users_group_perm', id=ID, method='put')

        users_group = UsersGroup.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'))

        usersgroup_model = UsersGroupModel()

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

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

            if grant_fork_perm:
                usersgroup_model.revoke_perm(id, 'hg.fork.none')
                usersgroup_model.grant_perm(id, 'hg.fork.repository')
                h.flash(_("Granted 'repository fork' permission to users group"),
                        category='success')
            else:
                usersgroup_model.revoke_perm(id, 'hg.fork.repository')
                usersgroup_model.grant_perm(id, 'hg.fork.none')
                h.flash(_("Revoked 'repository fork' permission to users 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))
Ejemplo n.º 22
0
    def create_users_group(self, apiuser, name, active=True):
        """
        Creates an new usergroup

        :param name:
        :param active:
        """

        if self.get_users_group(apiuser, name):
            raise JSONRPCError("users group %s already exist" % name)

        try:
            form_data = dict(users_group_name=name,
                             users_group_active=active)
            ug = UsersGroup.create(form_data)
            return dict(id=ug.users_group_id,
                        msg='created new users group %s' % name)
        except Exception:
            log.error(traceback.format_exc())
            raise JSONRPCError('failed to create group %s' % name)
Ejemplo n.º 23
0
    def test_create_and_remove(self):
        usr = UserModel().create_or_update(username=u'test_user', password=u'qweqwe',
                                     email=u'*****@*****.**',
                                     name=u'u1', lastname=u'u1')
        Session.commit()
        self.assertEqual(User.get_by_username(u'test_user'), usr)

        # make users group
        users_group = UsersGroupModel().create('some_example_group')
        Session.commit()

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

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

        self.assertEqual(UsersGroupMember.query().all(), [])
Ejemplo n.º 24
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 = UsersGroup.get_or_404(id)
        self._load_data(id)

        ug_model = UsersGroupModel()
        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
        )
Ejemplo n.º 25
0
    def test_create_and_remove(self):
        usr = UserModel().create_or_update(username=u'test_user',
                                           password=u'qweqwe',
                                           email=u'*****@*****.**',
                                           name=u'u1',
                                           lastname=u'u1')
        Session.commit()
        self.assertEqual(User.get_by_username(u'test_user'), usr)

        # make users group
        users_group = UsersGroupModel().create('some_example_group')
        Session.commit()

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

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

        self.assertEqual(UsersGroupMember.query().all(), [])
Ejemplo n.º 26
0
    def grant_users_group_permission(self, apiuser, repo_name, group_name, perm):
        """
        Grant permission for users group on given repository, or update
        existing one if found

        :param repo_name:
        :param group_name:
        :param perm:
        """

        try:
            repo = Repository.get_by_repo_name(repo_name)
            if repo is None:
                raise JSONRPCError('unknown repository %s' % repo)

            user_group = UsersGroup.get_by_group_name(group_name)
            if user_group is None:
                raise JSONRPCError('unknown users group %s' % user_group)

            RepoModel().grant_users_group_permission(repo=repo_name,
                                                     group_name=group_name,
                                                     perm=perm)

            Session.commit()
            return dict(
                msg='Granted perm: %s for group: %s in repo: %s' % (
                    perm, group_name, repo_name
                )
            )
        except Exception:
            log.error(traceback.format_exc())
            raise JSONRPCError(
                'failed to edit permission %(repo)s for %(usersgr)s' % dict(
                    usersgr=group_name, repo=repo_name
                )
            )
Ejemplo n.º 27
0
 def get(self, users_group_id, cache=False):
     return UsersGroup.get(users_group_id)
Ejemplo n.º 28
0
    def test_enable_repository_read_on_group(self):
        self.log_user()
        users_group_name = TEST_USERS_GROUP + 'another2'
        response = self.app.post(url('users_groups'),
                                 {'users_group_name': users_group_name,
                                  'active': True})
        response.follow()

        ug = UsersGroup.get_by_group_name(users_group_name)
        self.checkSessionFlash(response,
                               'created users 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 = UsersGroup.get_by_group_name(users_group_name)
        p = Permission.get_by_key('hg.create.repository')
        p2 = Permission.get_by_key('hg.fork.none')
        # check if user has this perms, they should be here since
        # defaults are on
        perms = UsersGroupToPerm.query()\
            .filter(UsersGroupToPerm.users_group == ug).all()

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

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

        response.follow()
        ug = UsersGroup.get_by_group_name(users_group_name)
        p = Permission.get_by_key('hg.create.none')
        p2 = Permission.get_by_key('hg.fork.none')
        # check if user has this perms, they should be here since
        # defaults are on
        perms = UsersGroupToPerm.query()\
            .filter(UsersGroupToPerm.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]])
        )

        # DELETE !
        ug = UsersGroup.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 = self.Session.query(UsersGroup)\
                           .filter(UsersGroup.users_group_name ==
                                   users_group_name).scalar()

        self.assertEqual(gr, None)
        p = Permission.get_by_key('hg.create.repository')
        perms = UsersGroupToPerm.query()\
            .filter(UsersGroupToPerm.users_group_id == ugid).all()
        perms = [[x.users_group_id,
                  x.permission_id, ] for x in perms]
        self.assertEqual(
            perms,
            []
        )
Ejemplo n.º 29
0
    def update(self, repo_name, form_data):
        try:
            cur_repo = self.get_by_repo_name(repo_name, cache=False)

            # update permissions
            for member, perm, member_type in form_data['perms_updates']:
                if member_type == 'user':
                    r2p = self.sa.query(RepoToPerm)\
                            .filter(RepoToPerm.user == User.get_by_username(member))\
                            .filter(RepoToPerm.repository == cur_repo)\
                            .one()

                    r2p.permission = self.sa.query(Permission)\
                                        .filter(Permission.permission_name ==
                                                perm).scalar()
                    self.sa.add(r2p)
                else:
                    g2p = self.sa.query(UsersGroupRepoToPerm)\
                            .filter(UsersGroupRepoToPerm.users_group ==
                                    UsersGroup.get_by_group_name(member))\
                            .filter(UsersGroupRepoToPerm.repository ==
                                    cur_repo).one()

                    g2p.permission = self.sa.query(Permission)\
                                        .filter(Permission.permission_name ==
                                                perm).scalar()
                    self.sa.add(g2p)

            # set new permissions
            for member, perm, member_type in form_data['perms_new']:
                if member_type == 'user':
                    r2p = RepoToPerm()
                    r2p.repository = cur_repo
                    r2p.user = User.get_by_username(member)

                    r2p.permission = self.sa.query(Permission)\
                                        .filter(Permission.
                                                permission_name == perm)\
                                                .scalar()
                    self.sa.add(r2p)
                else:
                    g2p = UsersGroupRepoToPerm()
                    g2p.repository = cur_repo
                    g2p.users_group = UsersGroup.get_by_group_name(member)
                    g2p.permission = self.sa.query(Permission)\
                                        .filter(Permission.
                                                permission_name == perm)\
                                                .scalar()
                    self.sa.add(g2p)

            # update current repo
            for k, v in form_data.items():
                if k == 'user':
                    cur_repo.user = User.get_by_username(v)
                elif k == 'repo_name':
                    pass
                elif k == 'repo_group':
                    cur_repo.group_id = v

                else:
                    setattr(cur_repo, k, v)

            new_name = cur_repo.get_new_name(form_data['repo_name'])
            cur_repo.repo_name = new_name

            self.sa.add(cur_repo)

            if repo_name != new_name:
                # rename repository
                self.__rename_repo(old=repo_name, new=new_name)

            self.sa.commit()
            return cur_repo
        except:
            log.error(traceback.format_exc())
            self.sa.rollback()
            raise
Ejemplo n.º 30
0
 def get_by_name(self, name, cache=False, case_insensitive=False):
     return UsersGroup.get_by_group_name(name, cache, case_insensitive)
Ejemplo n.º 31
0
    def update(self, repo_name, form_data):
        try:
            cur_repo = self.get_by_repo_name(repo_name, cache=False)

            # update permissions
            for member, perm, member_type in form_data["perms_updates"]:
                if member_type == "user":
                    r2p = (
                        self.sa.query(RepoToPerm)
                        .filter(RepoToPerm.user == User.by_username(member))
                        .filter(RepoToPerm.repository == cur_repo)
                        .one()
                    )

                    r2p.permission = self.sa.query(Permission).filter(Permission.permission_name == perm).scalar()
                    self.sa.add(r2p)
                else:
                    g2p = (
                        self.sa.query(UsersGroupRepoToPerm)
                        .filter(UsersGroupRepoToPerm.users_group == UsersGroup.get_by_group_name(member))
                        .filter(UsersGroupRepoToPerm.repository == cur_repo)
                        .one()
                    )

                    g2p.permission = self.sa.query(Permission).filter(Permission.permission_name == perm).scalar()
                    self.sa.add(g2p)

            # set new permissions
            for member, perm, member_type in form_data["perms_new"]:
                if member_type == "user":
                    r2p = RepoToPerm()
                    r2p.repository = cur_repo
                    r2p.user = User.by_username(member)

                    r2p.permission = self.sa.query(Permission).filter(Permission.permission_name == perm).scalar()
                    self.sa.add(r2p)
                else:
                    g2p = UsersGroupRepoToPerm()
                    g2p.repository = cur_repo
                    g2p.users_group = UsersGroup.get_by_group_name(member)
                    g2p.permission = self.sa.query(Permission).filter(Permission.permission_name == perm).scalar()
                    self.sa.add(g2p)

            # update current repo
            for k, v in form_data.items():
                if k == "user":
                    cur_repo.user = User.by_username(v)
                elif k == "repo_name":
                    cur_repo.repo_name = form_data["repo_name_full"]
                elif k == "repo_group":
                    cur_repo.group_id = v

                else:
                    setattr(cur_repo, k, v)

            self.sa.add(cur_repo)

            if repo_name != form_data["repo_name_full"]:
                # rename repository
                self.__rename_repo(old=repo_name, new=form_data["repo_name_full"])

            self.sa.commit()
        except:
            log.error(traceback.format_exc())
            self.sa.rollback()
            raise