##// END OF EJS Templates
Permissions on group can be set in recursive mode setting defined permission to all children...
marcink -
r2820:c0cc8f8a beta
parent child Browse files
Show More
@@ -0,0 +1,116 b''
1 import os
2 import unittest
3 import functools
4 from rhodecode.tests import *
5
6
7 from rhodecode.model.repos_group import ReposGroupModel
8 from rhodecode.model.repo import RepoModel
9 from rhodecode.model.db import RepoGroup, Repository, User
10 from rhodecode.model.user import UserModel
11
12 from rhodecode.lib.auth import AuthUser
13 from rhodecode.model.meta import Session
14
15
16 def _make_group(path, desc='desc', parent_id=None,
17 skip_if_exists=False):
18
19 gr = RepoGroup.get_by_group_name(path)
20 if gr and skip_if_exists:
21 return gr
22 if isinstance(parent_id, RepoGroup):
23 parent_id = parent_id.group_id
24 gr = ReposGroupModel().create(path, desc, parent_id)
25 return gr
26
27
28 def _make_repo(name, repos_group=None, repo_type='hg'):
29 return RepoModel().create_repo(name, repo_type, 'desc',
30 TEST_USER_ADMIN_LOGIN,
31 repos_group=repos_group)
32
33
34 def _destroy_project_tree(test_u1_id):
35 Session.remove()
36 repos_group = RepoGroup.get_by_group_name(group_name='g0')
37 for el in reversed(repos_group.recursive_groups_and_repos()):
38 if isinstance(el, Repository):
39 RepoModel().delete(el)
40 elif isinstance(el, RepoGroup):
41 ReposGroupModel().delete(el, force_delete=True)
42
43 u = User.get(test_u1_id)
44 Session().delete(u)
45 Session().commit()
46
47
48 def _create_project_tree():
49 """
50 Creates a tree of groups and repositories to test permissions
51
52 structure
53 [g0] - group `g0` with 3 subgroups
54 |
55 |__[g0_1] group g0_1 with 2 groups 0 repos
56 | |
57 | |__[g0_1_1] group g0_1_1 with 1 group 2 repos
58 | | |__<g0/g0_1/g0_1_1/g0_1_1_r1>
59 | | |__<g0/g0_1/g0_1_1/g0_1_1_r2>
60 | |__<g0/g0_1/g0_1_r1>
61 |
62 |__[g0_2] 2 repos
63 | |
64 | |__<g0/g0_2/g0_2_r1>
65 | |__<g0/g0_2/g0_2_r2>
66 |
67 |__[g0_3] 1 repo
68 |
69 |_<g0/g0_3/g0_3_r1>
70
71 """
72 test_u1 = UserModel().create_or_update(
73 username=u'test_u1', password=u'qweqwe',
74 email=u'test_u1@rhodecode.org', firstname=u'test_u1', lastname=u'test_u1'
75 )
76 g0 = _make_group('g0')
77 g0_1 = _make_group('g0_1', parent_id=g0)
78 g0_1_1 = _make_group('g0_1_1', parent_id=g0_1)
79 g0_1_1_r1 = _make_repo('g0/g0_1/g0_1_1/g0_1_1_r1', repos_group=g0_1_1)
80 g0_1_1_r2 = _make_repo('g0/g0_1/g0_1_1/g0_1_1_r2', repos_group=g0_1_1)
81 g0_1_r1 = _make_repo('g0/g0_1/g0_1_r1', repos_group=g0_1)
82 g0_2 = _make_group('g0_2', parent_id=g0)
83 g0_2_r1 = _make_repo('g0/g0_2/g0_2_r1', repos_group=g0_2)
84 g0_2_r2 = _make_repo('g0/g0_2/g0_2_r2', repos_group=g0_2)
85 g0_3 = _make_group('g0_3', parent_id=g0)
86 g0_3_r1 = _make_repo('g0/g0_3/g0_3_r1', repos_group=g0_3)
87 return test_u1
88
89
90 def expected_count(group_name, objects=False):
91 repos_group = RepoGroup.get_by_group_name(group_name=group_name)
92 objs = repos_group.recursive_groups_and_repos()
93 if objects:
94 return objs
95 return len(objs)
96
97
98 def _check_expected_count(items, repo_items, expected):
99 should_be = len(items + repo_items)
100 there_are = len(expected)
101 assert should_be == there_are, ('%s != %s' % ((items + repo_items), expected))
102
103
104 def check_tree_perms(obj_name, repo_perm, prefix, expected_perm):
105 assert repo_perm == expected_perm, ('obj:`%s` got perm:`%s` should:`%s`'
106 % (obj_name, repo_perm, expected_perm))
107
108
109 def _get_perms(filter_='', recursive=True, key=None, test_u1_id=None):
110 test_u1 = AuthUser(user_id=test_u1_id)
111 for k, v in test_u1.permissions[key].items():
112 if recursive and k.startswith(filter_):
113 yield k, v
114 elif not recursive:
115 if k == filter_:
116 yield k, v
@@ -0,0 +1,161 b''
1 import os
2 import unittest
3 import functools
4 from rhodecode.tests import *
5
6 from rhodecode.model.repos_group import ReposGroupModel
7 from rhodecode.model.db import RepoGroup, Repository, User
8
9 from rhodecode.model.meta import Session
10 from nose.tools import with_setup
11 from rhodecode.tests.models.common import _create_project_tree, check_tree_perms, \
12 _get_perms, _check_expected_count, expected_count, _destroy_project_tree
13 from rhodecode.model.repo import RepoModel
14
15
16 test_u1_id = None
17 _get_repo_perms = None
18 _get_group_perms = None
19
20
21 def permissions_setup_func(group_name='g0', perm='group.read', recursive=True):
22 """
23 Resets all permissions to perm attribute
24 """
25 repos_group = RepoGroup.get_by_group_name(group_name=group_name)
26 if not repos_group:
27 raise Exception('Cannot get group %s' % group_name)
28 perms_updates = [[test_u1_id, perm, 'user']]
29 ReposGroupModel()._update_permissions(repos_group,
30 perms_updates=perms_updates,
31 recursive=recursive)
32 Session().commit()
33
34
35 def setup_module():
36 global test_u1_id, _get_repo_perms, _get_group_perms
37 test_u1 = _create_project_tree()
38 Session().commit()
39 test_u1_id = test_u1.user_id
40 _get_repo_perms = functools.partial(_get_perms, key='repositories',
41 test_u1_id=test_u1_id)
42 _get_group_perms = functools.partial(_get_perms, key='repositories_groups',
43 test_u1_id=test_u1_id)
44
45
46 def teardown_module():
47 _destroy_project_tree(test_u1_id)
48
49
50 @with_setup(permissions_setup_func)
51 def test_user_permissions_on_group_without_recursive_mode():
52 # set permission to g0 non-recursive mode
53 recursive = False
54 group = 'g0'
55 permissions_setup_func(group, 'group.write', recursive=recursive)
56
57 items = [x for x in _get_repo_perms(group, recursive)]
58 expected = 0
59 assert len(items) == expected, ' %s != %s' % (len(items), expected)
60 for name, perm in items:
61 yield check_tree_perms, name, perm, group, 'repository.read'
62
63 items = [x for x in _get_group_perms(group, recursive)]
64 expected = 1
65 assert len(items) == expected, ' %s != %s' % (len(items), expected)
66 for name, perm in items:
67 yield check_tree_perms, name, perm, group, 'group.write'
68
69
70 @with_setup(permissions_setup_func)
71 def test_user_permissions_on_group_without_recursive_mode_subgroup():
72 # set permission to g0 non-recursive mode
73 recursive = False
74 group = 'g0/g0_1'
75 permissions_setup_func(group, 'group.write', recursive=recursive)
76
77 items = [x for x in _get_repo_perms(group, recursive)]
78 expected = 0
79 assert len(items) == expected, ' %s != %s' % (len(items), expected)
80 for name, perm in items:
81 yield check_tree_perms, name, perm, group, 'repository.read'
82
83 items = [x for x in _get_group_perms(group, recursive)]
84 expected = 1
85 assert len(items) == expected, ' %s != %s' % (len(items), expected)
86 for name, perm in items:
87 yield check_tree_perms, name, perm, group, 'group.write'
88
89
90 @with_setup(permissions_setup_func)
91 def test_user_permissions_on_group_with_recursive_mode():
92
93 # set permission to g0 recursive mode, all children including
94 # other repos and groups should have this permission now set !
95 recursive = True
96 group = 'g0'
97 permissions_setup_func(group, 'group.write', recursive=recursive)
98
99 repo_items = [x for x in _get_repo_perms(group, recursive)]
100 items = [x for x in _get_group_perms(group, recursive)]
101 _check_expected_count(items, repo_items, expected_count(group, True))
102
103 for name, perm in repo_items:
104 yield check_tree_perms, name, perm, group, 'repository.write'
105
106 for name, perm in items:
107 yield check_tree_perms, name, perm, group, 'group.write'
108
109
110 @with_setup(permissions_setup_func)
111 def test_user_permissions_on_group_with_recursive_mode_inner_group():
112 ## set permission to g0_3 group to none
113 recursive = True
114 group = 'g0/g0_3'
115 permissions_setup_func(group, 'group.none', recursive=recursive)
116
117 repo_items = [x for x in _get_repo_perms(group, recursive)]
118 items = [x for x in _get_group_perms(group, recursive)]
119 _check_expected_count(items, repo_items, expected_count(group, True))
120
121 for name, perm in repo_items:
122 yield check_tree_perms, name, perm, group, 'repository.none'
123
124 for name, perm in items:
125 yield check_tree_perms, name, perm, group, 'group.none'
126
127
128 @with_setup(permissions_setup_func)
129 def test_user_permissions_on_group_with_recursive_mode_deepest():
130 ## set permission to g0_3 group to none
131 recursive = True
132 group = 'g0/g0_1/g0_1_1'
133 permissions_setup_func(group, 'group.write', recursive=recursive)
134
135 repo_items = [x for x in _get_repo_perms(group, recursive)]
136 items = [x for x in _get_group_perms(group, recursive)]
137 _check_expected_count(items, repo_items, expected_count(group, True))
138
139 for name, perm in repo_items:
140 yield check_tree_perms, name, perm, group, 'repository.write'
141
142 for name, perm in items:
143 yield check_tree_perms, name, perm, group, 'group.write'
144
145
146 @with_setup(permissions_setup_func)
147 def test_user_permissions_on_group_with_recursive_mode_only_with_repos():
148 ## set permission to g0_3 group to none
149 recursive = True
150 group = 'g0/g0_2'
151 permissions_setup_func(group, 'group.admin', recursive=recursive)
152
153 repo_items = [x for x in _get_repo_perms(group, recursive)]
154 items = [x for x in _get_group_perms(group, recursive)]
155 _check_expected_count(items, repo_items, expected_count(group, True))
156
157 for name, perm in repo_items:
158 yield check_tree_perms, name, perm, group, 'repository.admin'
159
160 for name, perm in items:
161 yield check_tree_perms, name, perm, group, 'group.admin'
@@ -0,0 +1,170 b''
1 import os
2 import unittest
3 import functools
4 from rhodecode.tests import *
5
6 from rhodecode.model.repos_group import ReposGroupModel
7 from rhodecode.model.db import RepoGroup, Repository, User
8
9 from rhodecode.model.meta import Session
10 from nose.tools import with_setup
11 from rhodecode.tests.models.common import _create_project_tree, check_tree_perms, \
12 _get_perms, _check_expected_count, expected_count, _destroy_project_tree
13 from rhodecode.model.users_group import UsersGroupModel
14 from rhodecode.model.repo import RepoModel
15
16
17 test_u2_id = None
18 test_u2_gr_id = None
19 _get_repo_perms = None
20 _get_group_perms = None
21
22
23 def permissions_setup_func(group_name='g0', perm='group.read', recursive=True):
24 """
25 Resets all permissions to perm attribute
26 """
27 repos_group = RepoGroup.get_by_group_name(group_name=group_name)
28 if not repos_group:
29 raise Exception('Cannot get group %s' % group_name)
30 perms_updates = [[test_u2_gr_id, perm, 'users_group']]
31 ReposGroupModel()._update_permissions(repos_group,
32 perms_updates=perms_updates,
33 recursive=recursive)
34 Session().commit()
35
36
37 def setup_module():
38 global test_u2_id, test_u2_gr_id, _get_repo_perms, _get_group_perms
39 test_u2 = _create_project_tree()
40 Session().commit()
41 test_u2_id = test_u2.user_id
42
43 gr1 = UsersGroupModel().create(name='perms_group_1')
44 Session().commit()
45 test_u2_gr_id = gr1.users_group_id
46 UsersGroupModel().add_user_to_group(gr1, user=test_u2_id)
47 Session().commit()
48
49 _get_repo_perms = functools.partial(_get_perms, key='repositories',
50 test_u1_id=test_u2_id)
51 _get_group_perms = functools.partial(_get_perms, key='repositories_groups',
52 test_u1_id=test_u2_id)
53
54
55 def teardown_module():
56 _destroy_project_tree(test_u2_id)
57
58
59 @with_setup(permissions_setup_func)
60 def test_user_permissions_on_group_without_recursive_mode():
61 # set permission to g0 non-recursive mode
62 recursive = False
63 group = 'g0'
64 permissions_setup_func(group, 'group.write', recursive=recursive)
65
66 items = [x for x in _get_repo_perms(group, recursive)]
67 expected = 0
68 assert len(items) == expected, ' %s != %s' % (len(items), expected)
69 for name, perm in items:
70 yield check_tree_perms, name, perm, group, 'repository.read'
71
72 items = [x for x in _get_group_perms(group, recursive)]
73 expected = 1
74 assert len(items) == expected, ' %s != %s' % (len(items), expected)
75 for name, perm in items:
76 yield check_tree_perms, name, perm, group, 'group.write'
77
78
79 @with_setup(permissions_setup_func)
80 def test_user_permissions_on_group_without_recursive_mode_subgroup():
81 # set permission to g0 non-recursive mode
82 recursive = False
83 group = 'g0/g0_1'
84 permissions_setup_func(group, 'group.write', recursive=recursive)
85
86 items = [x for x in _get_repo_perms(group, recursive)]
87 expected = 0
88 assert len(items) == expected, ' %s != %s' % (len(items), expected)
89 for name, perm in items:
90 yield check_tree_perms, name, perm, group, 'repository.read'
91
92 items = [x for x in _get_group_perms(group, recursive)]
93 expected = 1
94 assert len(items) == expected, ' %s != %s' % (len(items), expected)
95 for name, perm in items:
96 yield check_tree_perms, name, perm, group, 'group.write'
97
98
99 @with_setup(permissions_setup_func)
100 def test_user_permissions_on_group_with_recursive_mode():
101
102 # set permission to g0 recursive mode, all children including
103 # other repos and groups should have this permission now set !
104 recursive = True
105 group = 'g0'
106 permissions_setup_func(group, 'group.write', recursive=recursive)
107
108 repo_items = [x for x in _get_repo_perms(group, recursive)]
109 items = [x for x in _get_group_perms(group, recursive)]
110 _check_expected_count(items, repo_items, expected_count(group, True))
111
112 for name, perm in repo_items:
113 yield check_tree_perms, name, perm, group, 'repository.write'
114
115 for name, perm in items:
116 yield check_tree_perms, name, perm, group, 'group.write'
117
118
119 @with_setup(permissions_setup_func)
120 def test_user_permissions_on_group_with_recursive_mode_inner_group():
121 ## set permission to g0_3 group to none
122 recursive = True
123 group = 'g0/g0_3'
124 permissions_setup_func(group, 'group.none', recursive=recursive)
125
126 repo_items = [x for x in _get_repo_perms(group, recursive)]
127 items = [x for x in _get_group_perms(group, recursive)]
128 _check_expected_count(items, repo_items, expected_count(group, True))
129
130 for name, perm in repo_items:
131 yield check_tree_perms, name, perm, group, 'repository.none'
132
133 for name, perm in items:
134 yield check_tree_perms, name, perm, group, 'group.none'
135
136
137 @with_setup(permissions_setup_func)
138 def test_user_permissions_on_group_with_recursive_mode_deepest():
139 ## set permission to g0_3 group to none
140 recursive = True
141 group = 'g0/g0_1/g0_1_1'
142 permissions_setup_func(group, 'group.write', recursive=recursive)
143
144 repo_items = [x for x in _get_repo_perms(group, recursive)]
145 items = [x for x in _get_group_perms(group, recursive)]
146 _check_expected_count(items, repo_items, expected_count(group, True))
147
148 for name, perm in repo_items:
149 yield check_tree_perms, name, perm, group, 'repository.write'
150
151 for name, perm in items:
152 yield check_tree_perms, name, perm, group, 'group.write'
153
154
155 @with_setup(permissions_setup_func)
156 def test_user_permissions_on_group_with_recursive_mode_only_with_repos():
157 ## set permission to g0_3 group to none
158 recursive = True
159 group = 'g0/g0_2'
160 permissions_setup_func(group, 'group.admin', recursive=recursive)
161
162 repo_items = [x for x in _get_repo_perms(group, recursive)]
163 items = [x for x in _get_group_perms(group, recursive)]
164 _check_expected_count(items, repo_items, expected_count(group, True))
165
166 for name, perm in repo_items:
167 yield check_tree_perms, name, perm, group, 'repository.admin'
168
169 for name, perm in items:
170 yield check_tree_perms, name, perm, group, 'group.admin'
@@ -45,6 +45,7 b' from rhodecode.model.forms import ReposG'
45 from rhodecode.model.meta import Session
45 from rhodecode.model.meta import Session
46 from rhodecode.model.repo import RepoModel
46 from rhodecode.model.repo import RepoModel
47 from webob.exc import HTTPInternalServerError, HTTPNotFound
47 from webob.exc import HTTPInternalServerError, HTTPNotFound
48 from rhodecode.lib.utils2 import str2bool
48
49
49 log = logging.getLogger(__name__)
50 log = logging.getLogger(__name__)
50
51
@@ -227,10 +228,11 b' class ReposGroupsController(BaseControll'
227
228
228 :param group_name:
229 :param group_name:
229 """
230 """
230
231 try:
231 try:
232 ReposGroupModel().revoke_user_permission(
232 recursive = str2bool(request.POST.get('recursive', False))
233 repos_group=group_name, user=request.POST['user_id']
233 ReposGroupModel().delete_permission(
234 repos_group=group_name, obj=request.POST['user_id'],
235 obj_type='user', recursive=recursive
234 )
236 )
235 Session().commit()
237 Session().commit()
236 except Exception:
238 except Exception:
@@ -248,9 +250,10 b' class ReposGroupsController(BaseControll'
248 """
250 """
249
251
250 try:
252 try:
251 ReposGroupModel().revoke_users_group_permission(
253 recursive = str2bool(request.POST.get('recursive', False))
252 repos_group=group_name,
254 ReposGroupModel().delete_permission(
253 group_name=request.POST['users_group_id']
255 repos_group=group_name, obj=request.POST['users_group_id'],
256 obj_type='users_group', recursive=recursive
254 )
257 )
255 Session().commit()
258 Session().commit()
256 except Exception:
259 except Exception:
@@ -128,6 +128,7 b' def ReposGroupForm(edit=False, old_data='
128 testValueList=True,
128 testValueList=True,
129 if_missing=None, not_empty=False)
129 if_missing=None, not_empty=False)
130 enable_locking = v.StringBoolean(if_missing=False)
130 enable_locking = v.StringBoolean(if_missing=False)
131 recursive = v.StringBoolean(if_missing=False)
131 chained_validators = [v.ValidReposGroup(edit, old_data),
132 chained_validators = [v.ValidReposGroup(edit, old_data),
132 v.ValidPerms('group')]
133 v.ValidPerms('group')]
133
134
@@ -368,6 +368,7 b' class RepoModel(BaseModel):'
368 obj.user = user
368 obj.user = user
369 obj.permission = permission
369 obj.permission = permission
370 self.sa.add(obj)
370 self.sa.add(obj)
371 log.debug('Granted perm %s to %s on %s' % (perm, user, repo))
371
372
372 def revoke_user_permission(self, repo, user):
373 def revoke_user_permission(self, repo, user):
373 """
374 """
@@ -383,8 +384,10 b' class RepoModel(BaseModel):'
383 obj = self.sa.query(UserRepoToPerm)\
384 obj = self.sa.query(UserRepoToPerm)\
384 .filter(UserRepoToPerm.repository == repo)\
385 .filter(UserRepoToPerm.repository == repo)\
385 .filter(UserRepoToPerm.user == user)\
386 .filter(UserRepoToPerm.user == user)\
386 .one()
387 .scalar()
388 if obj:
387 self.sa.delete(obj)
389 self.sa.delete(obj)
390 log.debug('Revoked perm on %s on %s' % (repo, user))
388
391
389 def grant_users_group_permission(self, repo, group_name, perm):
392 def grant_users_group_permission(self, repo, group_name, perm):
390 """
393 """
@@ -414,6 +417,7 b' class RepoModel(BaseModel):'
414 obj.users_group = group_name
417 obj.users_group = group_name
415 obj.permission = permission
418 obj.permission = permission
416 self.sa.add(obj)
419 self.sa.add(obj)
420 log.debug('Granted perm %s to %s on %s' % (perm, group_name, repo))
417
421
418 def revoke_users_group_permission(self, repo, group_name):
422 def revoke_users_group_permission(self, repo, group_name):
419 """
423 """
@@ -429,8 +433,10 b' class RepoModel(BaseModel):'
429 obj = self.sa.query(UsersGroupRepoToPerm)\
433 obj = self.sa.query(UsersGroupRepoToPerm)\
430 .filter(UsersGroupRepoToPerm.repository == repo)\
434 .filter(UsersGroupRepoToPerm.repository == repo)\
431 .filter(UsersGroupRepoToPerm.users_group == group_name)\
435 .filter(UsersGroupRepoToPerm.users_group == group_name)\
432 .one()
436 .scalar()
437 if obj:
433 self.sa.delete(obj)
438 self.sa.delete(obj)
439 log.debug('Revoked perm to %s on %s' % (repo, group_name))
434
440
435 def delete_stats(self, repo_name):
441 def delete_stats(self, repo_name):
436 """
442 """
@@ -32,7 +32,7 b' from rhodecode.lib.utils2 import LazyPro'
32
32
33 from rhodecode.model import BaseModel
33 from rhodecode.model import BaseModel
34 from rhodecode.model.db import RepoGroup, RhodeCodeUi, UserRepoGroupToPerm, \
34 from rhodecode.model.db import RepoGroup, RhodeCodeUi, UserRepoGroupToPerm, \
35 User, Permission, UsersGroupRepoGroupToPerm, UsersGroup
35 User, Permission, UsersGroupRepoGroupToPerm, UsersGroup, Repository
36
36
37 log = logging.getLogger(__name__)
37 log = logging.getLogger(__name__)
38
38
@@ -115,11 +115,12 b' class ReposGroupModel(BaseModel):'
115 'existing dir %s' % new_path)
115 'existing dir %s' % new_path)
116 shutil.move(old_path, new_path)
116 shutil.move(old_path, new_path)
117
117
118 def __delete_group(self, group):
118 def __delete_group(self, group, force_delete=False):
119 """
119 """
120 Deletes a group from a filesystem
120 Deletes a group from a filesystem
121
121
122 :param group: instance of group from database
122 :param group: instance of group from database
123 :param force_delete: use shutil rmtree to remove all objects
123 """
124 """
124 paths = group.full_path.split(RepoGroup.url_sep())
125 paths = group.full_path.split(RepoGroup.url_sep())
125 paths = os.sep.join(paths)
126 paths = os.sep.join(paths)
@@ -127,7 +128,10 b' class ReposGroupModel(BaseModel):'
127 rm_path = os.path.join(self.repos_path, paths)
128 rm_path = os.path.join(self.repos_path, paths)
128 if os.path.isdir(rm_path):
129 if os.path.isdir(rm_path):
129 # delete only if that path really exists
130 # delete only if that path really exists
130 os.rmdir(rm_path)
131 if force_delete:
132 shutil.rmtree(rm_path)
133 else:
134 os.rmdir(rm_path) # this raises an exception when there are still objects inside
131
135
132 def create(self, group_name, group_description, parent=None, just_db=False):
136 def create(self, group_name, group_description, parent=None, just_db=False):
133 try:
137 try:
@@ -150,32 +154,79 b' class ReposGroupModel(BaseModel):'
150 log.error(traceback.format_exc())
154 log.error(traceback.format_exc())
151 raise
155 raise
152
156
157 def _update_permissions(self, repos_group, perms_new=None,
158 perms_updates=None, recursive=False):
159 from rhodecode.model.repo import RepoModel
160 if not perms_new:
161 perms_new = []
162 if not perms_updates:
163 perms_updates = []
164
165 def _set_perm_user(obj, user, perm):
166 if isinstance(obj, RepoGroup):
167 ReposGroupModel().grant_user_permission(
168 repos_group=obj, user=user, perm=perm
169 )
170 elif isinstance(obj, Repository):
171 # we set group permission but we have to switch to repo
172 # permission
173 perm = perm.replace('group.', 'repository.')
174 RepoModel().grant_user_permission(
175 repo=obj, user=user, perm=perm
176 )
177
178 def _set_perm_group(obj, users_group, perm):
179 if isinstance(obj, RepoGroup):
180 ReposGroupModel().grant_users_group_permission(
181 repos_group=obj, group_name=users_group, perm=perm
182 )
183 elif isinstance(obj, Repository):
184 # we set group permission but we have to switch to repo
185 # permission
186 perm = perm.replace('group.', 'repository.')
187 RepoModel().grant_users_group_permission(
188 repo=obj, group_name=users_group, perm=perm
189 )
190 updates = []
191 log.debug('Now updating permissions for %s in recursive mode:%s'
192 % (repos_group, recursive))
193
194 for obj in repos_group.recursive_groups_and_repos():
195 if not recursive:
196 obj = repos_group
197
198 # update permissions
199 for member, perm, member_type in perms_updates:
200 ## set for user
201 if member_type == 'user':
202 # this updates also current one if found
203 _set_perm_user(obj, user=member, perm=perm)
204 ## set for users group
205 else:
206 _set_perm_group(obj, users_group=member, perm=perm)
207 # set new permissions
208 for member, perm, member_type in perms_new:
209 if member_type == 'user':
210 _set_perm_user(obj, user=member, perm=perm)
211 else:
212 _set_perm_group(obj, users_group=member, perm=perm)
213 updates.append(obj)
214 #if it's not recursive call
215 # break the loop and don't proceed with other changes
216 if not recursive:
217 break
218 return updates
219
153 def update(self, repos_group_id, form_data):
220 def update(self, repos_group_id, form_data):
154
221
155 try:
222 try:
156 repos_group = RepoGroup.get(repos_group_id)
223 repos_group = RepoGroup.get(repos_group_id)
157
224 recursive = form_data['recursive']
158 # update permissions
225 # iterate over all members(if in recursive mode) of this groups and
159 for member, perm, member_type in form_data['perms_updates']:
226 # set the permissions !
160 if member_type == 'user':
227 # this can be potentially heavy operation
161 # this updates also current one if found
228 self._update_permissions(repos_group, form_data['perms_new'],
162 ReposGroupModel().grant_user_permission(
229 form_data['perms_updates'], recursive)
163 repos_group=repos_group, user=member, perm=perm
164 )
165 else:
166 ReposGroupModel().grant_users_group_permission(
167 repos_group=repos_group, group_name=member, perm=perm
168 )
169 # set new permissions
170 for member, perm, member_type in form_data['perms_new']:
171 if member_type == 'user':
172 ReposGroupModel().grant_user_permission(
173 repos_group=repos_group, user=member, perm=perm
174 )
175 else:
176 ReposGroupModel().grant_users_group_permission(
177 repos_group=repos_group, group_name=member, perm=perm
178 )
179
230
180 old_path = repos_group.full_path
231 old_path = repos_group.full_path
181
232
@@ -191,7 +242,6 b' class ReposGroupModel(BaseModel):'
191
242
192 # iterate over all members of this groups and set the locking !
243 # iterate over all members of this groups and set the locking !
193 # this can be potentially heavy operation
244 # this can be potentially heavy operation
194
195 for obj in repos_group.recursive_groups_and_repos():
245 for obj in repos_group.recursive_groups_and_repos():
196 #set the value from it's parent
246 #set the value from it's parent
197 obj.enable_locking = repos_group.enable_locking
247 obj.enable_locking = repos_group.enable_locking
@@ -210,15 +260,54 b' class ReposGroupModel(BaseModel):'
210 log.error(traceback.format_exc())
260 log.error(traceback.format_exc())
211 raise
261 raise
212
262
213 def delete(self, repos_group):
263 def delete(self, repos_group, force_delete=False):
214 repos_group = self._get_repos_group(repos_group)
264 repos_group = self._get_repos_group(repos_group)
215 try:
265 try:
216 self.sa.delete(repos_group)
266 self.sa.delete(repos_group)
217 self.__delete_group(repos_group)
267 self.__delete_group(repos_group, force_delete)
218 except:
268 except:
219 log.exception('Error removing repos_group %s' % repos_group)
269 log.exception('Error removing repos_group %s' % repos_group)
220 raise
270 raise
221
271
272 def delete_permission(self, repos_group, obj, obj_type, recursive):
273 """
274 Revokes permission for repos_group for given obj(user or users_group),
275 obj_type can be user or users group
276
277 :param repos_group:
278 :param obj: user or users group id
279 :param obj_type: user or users group type
280 :param recursive: recurse to all children of group
281 """
282 from rhodecode.model.repo import RepoModel
283 repos_group = self._get_repos_group(repos_group)
284
285 for el in repos_group.recursive_groups_and_repos():
286 if not recursive:
287 # if we don't recurse set the permission on only the top level
288 # object
289 el = repos_group
290
291 if isinstance(el, RepoGroup):
292 if obj_type == 'user':
293 ReposGroupModel().revoke_user_permission(el, user=obj)
294 elif obj_type == 'users_group':
295 ReposGroupModel().revoke_users_group_permission(el, group_name=obj)
296 else:
297 raise Exception('undefined object type %s' % obj_type)
298 elif isinstance(el, Repository):
299 if obj_type == 'user':
300 RepoModel().revoke_user_permission(el, user=obj)
301 elif obj_type == 'users_group':
302 RepoModel().revoke_users_group_permission(el, group_name=obj)
303 else:
304 raise Exception('undefined object type %s' % obj_type)
305
306 #if it's not recursive call
307 # break the loop and don't proceed with other changes
308 if not recursive:
309 break
310
222 def grant_user_permission(self, repos_group, user, perm):
311 def grant_user_permission(self, repos_group, user, perm):
223 """
312 """
224 Grant permission for user on given repositories group, or update
313 Grant permission for user on given repositories group, or update
@@ -246,6 +335,7 b' class ReposGroupModel(BaseModel):'
246 obj.user = user
335 obj.user = user
247 obj.permission = permission
336 obj.permission = permission
248 self.sa.add(obj)
337 self.sa.add(obj)
338 log.debug('Granted perm %s to %s on %s' % (perm, user, repos_group))
249
339
250 def revoke_user_permission(self, repos_group, user):
340 def revoke_user_permission(self, repos_group, user):
251 """
341 """
@@ -262,8 +352,10 b' class ReposGroupModel(BaseModel):'
262 obj = self.sa.query(UserRepoGroupToPerm)\
352 obj = self.sa.query(UserRepoGroupToPerm)\
263 .filter(UserRepoGroupToPerm.user == user)\
353 .filter(UserRepoGroupToPerm.user == user)\
264 .filter(UserRepoGroupToPerm.group == repos_group)\
354 .filter(UserRepoGroupToPerm.group == repos_group)\
265 .one()
355 .scalar()
356 if obj:
266 self.sa.delete(obj)
357 self.sa.delete(obj)
358 log.debug('Revoked perm on %s on %s' % (repos_group, user))
267
359
268 def grant_users_group_permission(self, repos_group, group_name, perm):
360 def grant_users_group_permission(self, repos_group, group_name, perm):
269 """
361 """
@@ -294,6 +386,7 b' class ReposGroupModel(BaseModel):'
294 obj.users_group = group_name
386 obj.users_group = group_name
295 obj.permission = permission
387 obj.permission = permission
296 self.sa.add(obj)
388 self.sa.add(obj)
389 log.debug('Granted perm %s to %s on %s' % (perm, group_name, repos_group))
297
390
298 def revoke_users_group_permission(self, repos_group, group_name):
391 def revoke_users_group_permission(self, repos_group, group_name):
299 """
392 """
@@ -310,5 +403,7 b' class ReposGroupModel(BaseModel):'
310 obj = self.sa.query(UsersGroupRepoGroupToPerm)\
403 obj = self.sa.query(UsersGroupRepoGroupToPerm)\
311 .filter(UsersGroupRepoGroupToPerm.group == repos_group)\
404 .filter(UsersGroupRepoGroupToPerm.group == repos_group)\
312 .filter(UsersGroupRepoGroupToPerm.users_group == group_name)\
405 .filter(UsersGroupRepoGroupToPerm.users_group == group_name)\
313 .one()
406 .scalar()
407 if obj:
314 self.sa.delete(obj)
408 self.sa.delete(obj)
409 log.debug('Revoked perm to %s on %s' % (repos_group, group_name))
@@ -564,7 +564,7 b' class UserModel(BaseModel):'
564 rg_k = perm.UserRepoGroupToPerm.group.group_name
564 rg_k = perm.UserRepoGroupToPerm.group.group_name
565 p = perm.Permission.permission_name
565 p = perm.Permission.permission_name
566 cur_perm = user.permissions[GK][rg_k]
566 cur_perm = user.permissions[GK][rg_k]
567 if PERM_WEIGHTS[p] > PERM_WEIGHTS[cur_perm]:
567 if PERM_WEIGHTS[p] > PERM_WEIGHTS[cur_perm] or 1: # disable check
568 user.permissions[GK][rg_k] = p
568 user.permissions[GK][rg_k] = p
569
569
570 # REPO GROUP + USER GROUP
570 # REPO GROUP + USER GROUP
@@ -588,7 +588,7 b' class UserModel(BaseModel):'
588 cur_perm = user.permissions[GK][g_k]
588 cur_perm = user.permissions[GK][g_k]
589 # overwrite permission only if it's greater than permission
589 # overwrite permission only if it's greater than permission
590 # given from other sources
590 # given from other sources
591 if PERM_WEIGHTS[p] > PERM_WEIGHTS[cur_perm]:
591 if PERM_WEIGHTS[p] > PERM_WEIGHTS[cur_perm] or 1: # disable check
592 user.permissions[GK][g_k] = p
592 user.permissions[GK][g_k] = p
593
593
594 return user
594 return user
@@ -499,9 +499,9 b" def ValidPerms(type_='repo'):"
499 # fill new permissions in order of how they were added
499 # fill new permissions in order of how they were added
500 for k in sorted(map(int, new_perms_group.keys())):
500 for k in sorted(map(int, new_perms_group.keys())):
501 perm_dict = new_perms_group[str(k)]
501 perm_dict = new_perms_group[str(k)]
502 new_member = perm_dict['name']
502 new_member = perm_dict.get('name')
503 new_perm = perm_dict['perm']
503 new_perm = perm_dict.get('perm')
504 new_type = perm_dict['type']
504 new_type = perm_dict.get('type')
505 if new_member and new_perm and new_type:
505 if new_member and new_perm and new_type:
506 perms_new.add((new_member, new_perm, new_type))
506 perms_new.add((new_member, new_perm, new_type))
507
507
@@ -68,6 +68,12 b''
68 </span>
68 </span>
69 </td>
69 </td>
70 </tr>
70 </tr>
71 <tr>
72 <td colspan="6">
73 ${h.checkbox('recursive',value="True", label=_('apply to parents'))}
74 <span class="help-block">${_('Set or revoke permission to all children of that group, including repositories and other groups')}</span>
75 </td>
76 </tr>
71 </table>
77 </table>
72 <script type="text/javascript">
78 <script type="text/javascript">
73 function ajaxActionUser(user_id, field_id) {
79 function ajaxActionUser(user_id, field_id) {
@@ -81,7 +87,8 b' function ajaxActionUser(user_id, field_i'
81 alert("${_('Failed to remove user')}");
87 alert("${_('Failed to remove user')}");
82 },
88 },
83 };
89 };
84 var postData = '_method=delete&user_id=' + user_id;
90 var recursive = YUD.get('recursive').checked;
91 var postData = '_method=delete&recursive={0}&user_id={1}'.format(recursive,user_id);
85 var request = YAHOO.util.Connect.asyncRequest('POST', sUrl, callback, postData);
92 var request = YAHOO.util.Connect.asyncRequest('POST', sUrl, callback, postData);
86 };
93 };
87
94
@@ -96,7 +103,8 b' function ajaxActionUsersGroup(users_grou'
96 alert("${_('Failed to remove users group')}");
103 alert("${_('Failed to remove users group')}");
97 },
104 },
98 };
105 };
99 var postData = '_method=delete&users_group_id='+users_group_id;
106 var recursive = YUD.get('recursive').checked;
107 var postData = '_method=delete&recursive={0}&users_group_id={1}'.format(recursive,users_group_id);
100 var request = YAHOO.util.Connect.asyncRequest('POST', sUrl, callback, postData);
108 var request = YAHOO.util.Connect.asyncRequest('POST', sUrl, callback, postData);
101 };
109 };
102
110
@@ -291,4 +291,3 b' class TestCompareController(TestControll'
291 finally:
291 finally:
292 RepoModel().delete(r2_id)
292 RepoModel().delete(r2_id)
293 RepoModel().delete(r1_id)
293 RepoModel().delete(r1_id)
294
@@ -1,7 +1,7 b''
1 import os
1 import os
2 import unittest
2 import unittest
3 from rhodecode.tests import *
3 from rhodecode.tests import *
4
4 from rhodecode.tests.models.common import _make_group
5 from rhodecode.model.repos_group import ReposGroupModel
5 from rhodecode.model.repos_group import ReposGroupModel
6 from rhodecode.model.repo import RepoModel
6 from rhodecode.model.repo import RepoModel
7 from rhodecode.model.db import RepoGroup, User, UsersGroupRepoGroupToPerm
7 from rhodecode.model.db import RepoGroup, User, UsersGroupRepoGroupToPerm
@@ -12,16 +12,6 b' from rhodecode.model.users_group import '
12 from rhodecode.lib.auth import AuthUser
12 from rhodecode.lib.auth import AuthUser
13
13
14
14
15 def _make_group(path, desc='desc', parent_id=None,
16 skip_if_exists=False):
17
18 gr = RepoGroup.get_by_group_name(path)
19 if gr and skip_if_exists:
20 return gr
21
22 gr = ReposGroupModel().create(path, desc, parent_id)
23 return gr
24
25
15
26 class TestPermissions(unittest.TestCase):
16 class TestPermissions(unittest.TestCase):
27 def __init__(self, methodName='runTest'):
17 def __init__(self, methodName='runTest'):
@@ -4,7 +4,7 b' from rhodecode.tests import *'
4
4
5 from rhodecode.model.repos_group import ReposGroupModel
5 from rhodecode.model.repos_group import ReposGroupModel
6 from rhodecode.model.repo import RepoModel
6 from rhodecode.model.repo import RepoModel
7 from rhodecode.model.db import RepoGroup, User
7 from rhodecode.model.db import RepoGroup, User, Repository
8 from rhodecode.model.meta import Session
8 from rhodecode.model.meta import Session
9 from sqlalchemy.exc import IntegrityError
9 from sqlalchemy.exc import IntegrityError
10
10
@@ -15,7 +15,8 b" def _make_group(path, desc='desc', paren"
15 gr = RepoGroup.get_by_group_name(path)
15 gr = RepoGroup.get_by_group_name(path)
16 if gr and skip_if_exists:
16 if gr and skip_if_exists:
17 return gr
17 return gr
18
18 if isinstance(parent_id, RepoGroup):
19 parent_id = parent_id.group_id
19 gr = ReposGroupModel().create(path, desc, parent_id)
20 gr = ReposGroupModel().create(path, desc, parent_id)
20 return gr
21 return gr
21
22
@@ -54,7 +55,8 b' class TestReposGroups(unittest.TestCase)'
54 group_parent_id=parent_id,
55 group_parent_id=parent_id,
55 perms_updates=[],
56 perms_updates=[],
56 perms_new=[],
57 perms_new=[],
57 enable_locking=False
58 enable_locking=False,
59 recursive=False
58 )
60 )
59 gr = ReposGroupModel().update(id_, form_data)
61 gr = ReposGroupModel().update(id_, form_data)
60 return gr
62 return gr
@@ -132,7 +134,8 b' class TestReposGroups(unittest.TestCase)'
132 repo_type='hg',
134 repo_type='hg',
133 clone_uri=None,
135 clone_uri=None,
134 landing_rev='tip',
136 landing_rev='tip',
135 enable_locking=False)
137 enable_locking=False,
138 recursive=False)
136 cur_user = User.get_by_username(TEST_USER_ADMIN_LOGIN)
139 cur_user = User.get_by_username(TEST_USER_ADMIN_LOGIN)
137 r = RepoModel().create(form_data, cur_user)
140 r = RepoModel().create(form_data, cur_user)
138
141
General Comments 0
You need to be logged in to leave comments. Login now