##// END OF EJS Templates
fix(permissions): Invalidate cache on changing the default permissions...
super-admin -
r5186:76f12b03 default
parent child Browse files
Show More
@@ -1,606 +1,609 b''
1 # Copyright (C) 2010-2023 RhodeCode GmbH
1 # Copyright (C) 2010-2023 RhodeCode GmbH
2 #
2 #
3 # This program is free software: you can redistribute it and/or modify
3 # This program is free software: you can redistribute it and/or modify
4 # it under the terms of the GNU Affero General Public License, version 3
4 # it under the terms of the GNU Affero General Public License, version 3
5 # (only), as published by the Free Software Foundation.
5 # (only), as published by the Free Software Foundation.
6 #
6 #
7 # This program is distributed in the hope that it will be useful,
7 # This program is distributed in the hope that it will be useful,
8 # but WITHOUT ANY WARRANTY; without even the implied warranty of
8 # but WITHOUT ANY WARRANTY; without even the implied warranty of
9 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
9 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 # GNU General Public License for more details.
10 # GNU General Public License for more details.
11 #
11 #
12 # You should have received a copy of the GNU Affero General Public License
12 # You should have received a copy of the GNU Affero General Public License
13 # along with this program. If not, see <http://www.gnu.org/licenses/>.
13 # along with this program. If not, see <http://www.gnu.org/licenses/>.
14 #
14 #
15 # This program is dual-licensed. If you wish to learn more about the
15 # This program is dual-licensed. If you wish to learn more about the
16 # RhodeCode Enterprise Edition, including its added features, Support services,
16 # RhodeCode Enterprise Edition, including its added features, Support services,
17 # and proprietary license terms, please see https://rhodecode.com/licenses/
17 # and proprietary license terms, please see https://rhodecode.com/licenses/
18
18
19 """
19 """
20 permissions model for RhodeCode
20 permissions model for RhodeCode
21 """
21 """
22 import collections
22 import collections
23 import logging
23 import logging
24 import traceback
24 import traceback
25
25
26 from sqlalchemy.exc import DatabaseError
26 from sqlalchemy.exc import DatabaseError
27
27
28 from rhodecode import events
28 from rhodecode import events
29 from rhodecode.model import BaseModel
29 from rhodecode.model import BaseModel
30 from rhodecode.model.db import (
30 from rhodecode.model.db import (
31 User, Permission, UserToPerm, UserRepoToPerm, UserRepoGroupToPerm,
31 User, Permission, UserToPerm, UserRepoToPerm, UserRepoGroupToPerm,
32 UserUserGroupToPerm, UserGroup, UserGroupToPerm, UserToRepoBranchPermission)
32 UserUserGroupToPerm, UserGroup, UserGroupToPerm, UserToRepoBranchPermission)
33 from rhodecode.lib.utils2 import str2bool, safe_int
33 from rhodecode.lib.utils2 import str2bool, safe_int
34
34
35 log = logging.getLogger(__name__)
35 log = logging.getLogger(__name__)
36
36
37
37
38 class PermissionModel(BaseModel):
38 class PermissionModel(BaseModel):
39 """
39 """
40 Permissions model for RhodeCode
40 Permissions model for RhodeCode
41 """
41 """
42 FORKING_DISABLED = 'hg.fork.none'
42 FORKING_DISABLED = 'hg.fork.none'
43 FORKING_ENABLED = 'hg.fork.repository'
43 FORKING_ENABLED = 'hg.fork.repository'
44
44
45 cls = Permission
45 cls = Permission
46 global_perms = {
46 global_perms = {
47 'default_repo_create': None,
47 'default_repo_create': None,
48 # special case for create repos on write access to group
48 # special case for create repos on write access to group
49 'default_repo_create_on_write': None,
49 'default_repo_create_on_write': None,
50 'default_repo_group_create': None,
50 'default_repo_group_create': None,
51 'default_user_group_create': None,
51 'default_user_group_create': None,
52 'default_fork_create': None,
52 'default_fork_create': None,
53 'default_inherit_default_permissions': None,
53 'default_inherit_default_permissions': None,
54 'default_register': None,
54 'default_register': None,
55 'default_password_reset': None,
55 'default_password_reset': None,
56 'default_extern_activate': None,
56 'default_extern_activate': None,
57
57
58 # object permissions below
58 # object permissions below
59 'default_repo_perm': None,
59 'default_repo_perm': None,
60 'default_group_perm': None,
60 'default_group_perm': None,
61 'default_user_group_perm': None,
61 'default_user_group_perm': None,
62
62
63 # branch
63 # branch
64 'default_branch_perm': None,
64 'default_branch_perm': None,
65 }
65 }
66
66
67 def set_global_permission_choices(self, c_obj, gettext_translator):
67 def set_global_permission_choices(self, c_obj, gettext_translator):
68 _ = gettext_translator
68 _ = gettext_translator
69
69
70 c_obj.repo_perms_choices = [
70 c_obj.repo_perms_choices = [
71 ('repository.none', _('None'),),
71 ('repository.none', _('None'),),
72 ('repository.read', _('Read'),),
72 ('repository.read', _('Read'),),
73 ('repository.write', _('Write'),),
73 ('repository.write', _('Write'),),
74 ('repository.admin', _('Admin'),)]
74 ('repository.admin', _('Admin'),)]
75
75
76 c_obj.group_perms_choices = [
76 c_obj.group_perms_choices = [
77 ('group.none', _('None'),),
77 ('group.none', _('None'),),
78 ('group.read', _('Read'),),
78 ('group.read', _('Read'),),
79 ('group.write', _('Write'),),
79 ('group.write', _('Write'),),
80 ('group.admin', _('Admin'),)]
80 ('group.admin', _('Admin'),)]
81
81
82 c_obj.user_group_perms_choices = [
82 c_obj.user_group_perms_choices = [
83 ('usergroup.none', _('None'),),
83 ('usergroup.none', _('None'),),
84 ('usergroup.read', _('Read'),),
84 ('usergroup.read', _('Read'),),
85 ('usergroup.write', _('Write'),),
85 ('usergroup.write', _('Write'),),
86 ('usergroup.admin', _('Admin'),)]
86 ('usergroup.admin', _('Admin'),)]
87
87
88 c_obj.branch_perms_choices = [
88 c_obj.branch_perms_choices = [
89 ('branch.none', _('Protected/No Access'),),
89 ('branch.none', _('Protected/No Access'),),
90 ('branch.merge', _('Web merge'),),
90 ('branch.merge', _('Web merge'),),
91 ('branch.push', _('Push'),),
91 ('branch.push', _('Push'),),
92 ('branch.push_force', _('Force Push'),)]
92 ('branch.push_force', _('Force Push'),)]
93
93
94 c_obj.register_choices = [
94 c_obj.register_choices = [
95 ('hg.register.none', _('Disabled')),
95 ('hg.register.none', _('Disabled')),
96 ('hg.register.manual_activate', _('Allowed with manual account activation')),
96 ('hg.register.manual_activate', _('Allowed with manual account activation')),
97 ('hg.register.auto_activate', _('Allowed with automatic account activation'))]
97 ('hg.register.auto_activate', _('Allowed with automatic account activation'))]
98
98
99 c_obj.password_reset_choices = [
99 c_obj.password_reset_choices = [
100 ('hg.password_reset.enabled', _('Allow password recovery')),
100 ('hg.password_reset.enabled', _('Allow password recovery')),
101 ('hg.password_reset.hidden', _('Hide password recovery link')),
101 ('hg.password_reset.hidden', _('Hide password recovery link')),
102 ('hg.password_reset.disabled', _('Disable password recovery'))]
102 ('hg.password_reset.disabled', _('Disable password recovery'))]
103
103
104 c_obj.extern_activate_choices = [
104 c_obj.extern_activate_choices = [
105 ('hg.extern_activate.manual', _('Manual activation of external account')),
105 ('hg.extern_activate.manual', _('Manual activation of external account')),
106 ('hg.extern_activate.auto', _('Automatic activation of external account'))]
106 ('hg.extern_activate.auto', _('Automatic activation of external account'))]
107
107
108 c_obj.repo_create_choices = [
108 c_obj.repo_create_choices = [
109 ('hg.create.none', _('Disabled')),
109 ('hg.create.none', _('Disabled')),
110 ('hg.create.repository', _('Enabled'))]
110 ('hg.create.repository', _('Enabled'))]
111
111
112 c_obj.repo_create_on_write_choices = [
112 c_obj.repo_create_on_write_choices = [
113 ('hg.create.write_on_repogroup.false', _('Disabled')),
113 ('hg.create.write_on_repogroup.false', _('Disabled')),
114 ('hg.create.write_on_repogroup.true', _('Enabled'))]
114 ('hg.create.write_on_repogroup.true', _('Enabled'))]
115
115
116 c_obj.user_group_create_choices = [
116 c_obj.user_group_create_choices = [
117 ('hg.usergroup.create.false', _('Disabled')),
117 ('hg.usergroup.create.false', _('Disabled')),
118 ('hg.usergroup.create.true', _('Enabled'))]
118 ('hg.usergroup.create.true', _('Enabled'))]
119
119
120 c_obj.repo_group_create_choices = [
120 c_obj.repo_group_create_choices = [
121 ('hg.repogroup.create.false', _('Disabled')),
121 ('hg.repogroup.create.false', _('Disabled')),
122 ('hg.repogroup.create.true', _('Enabled'))]
122 ('hg.repogroup.create.true', _('Enabled'))]
123
123
124 c_obj.fork_choices = [
124 c_obj.fork_choices = [
125 (self.FORKING_DISABLED, _('Disabled')),
125 (self.FORKING_DISABLED, _('Disabled')),
126 (self.FORKING_ENABLED, _('Enabled'))]
126 (self.FORKING_ENABLED, _('Enabled'))]
127
127
128 c_obj.inherit_default_permission_choices = [
128 c_obj.inherit_default_permission_choices = [
129 ('hg.inherit_default_perms.false', _('Disabled')),
129 ('hg.inherit_default_perms.false', _('Disabled')),
130 ('hg.inherit_default_perms.true', _('Enabled'))]
130 ('hg.inherit_default_perms.true', _('Enabled'))]
131
131
132 def get_default_perms(self, object_perms, suffix):
132 def get_default_perms(self, object_perms, suffix):
133 defaults = {}
133 defaults = {}
134 for perm in object_perms:
134 for perm in object_perms:
135 # perms
135 # perms
136 if perm.permission.permission_name.startswith('repository.'):
136 if perm.permission.permission_name.startswith('repository.'):
137 defaults['default_repo_perm' + suffix] = perm.permission.permission_name
137 defaults['default_repo_perm' + suffix] = perm.permission.permission_name
138
138
139 if perm.permission.permission_name.startswith('group.'):
139 if perm.permission.permission_name.startswith('group.'):
140 defaults['default_group_perm' + suffix] = perm.permission.permission_name
140 defaults['default_group_perm' + suffix] = perm.permission.permission_name
141
141
142 if perm.permission.permission_name.startswith('usergroup.'):
142 if perm.permission.permission_name.startswith('usergroup.'):
143 defaults['default_user_group_perm' + suffix] = perm.permission.permission_name
143 defaults['default_user_group_perm' + suffix] = perm.permission.permission_name
144
144
145 # branch
145 # branch
146 if perm.permission.permission_name.startswith('branch.'):
146 if perm.permission.permission_name.startswith('branch.'):
147 defaults['default_branch_perm' + suffix] = perm.permission.permission_name
147 defaults['default_branch_perm' + suffix] = perm.permission.permission_name
148
148
149 # creation of objects
149 # creation of objects
150 if perm.permission.permission_name.startswith('hg.create.write_on_repogroup'):
150 if perm.permission.permission_name.startswith('hg.create.write_on_repogroup'):
151 defaults['default_repo_create_on_write' + suffix] = perm.permission.permission_name
151 defaults['default_repo_create_on_write' + suffix] = perm.permission.permission_name
152
152
153 elif perm.permission.permission_name.startswith('hg.create.'):
153 elif perm.permission.permission_name.startswith('hg.create.'):
154 defaults['default_repo_create' + suffix] = perm.permission.permission_name
154 defaults['default_repo_create' + suffix] = perm.permission.permission_name
155
155
156 if perm.permission.permission_name.startswith('hg.fork.'):
156 if perm.permission.permission_name.startswith('hg.fork.'):
157 defaults['default_fork_create' + suffix] = perm.permission.permission_name
157 defaults['default_fork_create' + suffix] = perm.permission.permission_name
158
158
159 if perm.permission.permission_name.startswith('hg.inherit_default_perms.'):
159 if perm.permission.permission_name.startswith('hg.inherit_default_perms.'):
160 defaults['default_inherit_default_permissions' + suffix] = perm.permission.permission_name
160 defaults['default_inherit_default_permissions' + suffix] = perm.permission.permission_name
161
161
162 if perm.permission.permission_name.startswith('hg.repogroup.'):
162 if perm.permission.permission_name.startswith('hg.repogroup.'):
163 defaults['default_repo_group_create' + suffix] = perm.permission.permission_name
163 defaults['default_repo_group_create' + suffix] = perm.permission.permission_name
164
164
165 if perm.permission.permission_name.startswith('hg.usergroup.'):
165 if perm.permission.permission_name.startswith('hg.usergroup.'):
166 defaults['default_user_group_create' + suffix] = perm.permission.permission_name
166 defaults['default_user_group_create' + suffix] = perm.permission.permission_name
167
167
168 # registration and external account activation
168 # registration and external account activation
169 if perm.permission.permission_name.startswith('hg.register.'):
169 if perm.permission.permission_name.startswith('hg.register.'):
170 defaults['default_register' + suffix] = perm.permission.permission_name
170 defaults['default_register' + suffix] = perm.permission.permission_name
171
171
172 if perm.permission.permission_name.startswith('hg.password_reset.'):
172 if perm.permission.permission_name.startswith('hg.password_reset.'):
173 defaults['default_password_reset' + suffix] = perm.permission.permission_name
173 defaults['default_password_reset' + suffix] = perm.permission.permission_name
174
174
175 if perm.permission.permission_name.startswith('hg.extern_activate.'):
175 if perm.permission.permission_name.startswith('hg.extern_activate.'):
176 defaults['default_extern_activate' + suffix] = perm.permission.permission_name
176 defaults['default_extern_activate' + suffix] = perm.permission.permission_name
177
177
178 return defaults
178 return defaults
179
179
180 def _make_new_user_perm(self, user, perm_name):
180 def _make_new_user_perm(self, user, perm_name):
181 log.debug('Creating new user permission:%s', perm_name)
181 log.debug('Creating new user permission:%s', perm_name)
182 new_perm = Permission.get_by_key(perm_name)
182 new_perm = Permission.get_by_key(perm_name)
183 if not new_perm:
183 if not new_perm:
184 raise ValueError(f'permission with name {perm_name} not found')
184 raise ValueError(f'permission with name {perm_name} not found')
185
185
186 new = UserToPerm()
186 new = UserToPerm()
187 new.user = user
187 new.user = user
188 new.permission = new_perm
188 new.permission = new_perm
189 return new
189 return new
190
190
191 def _make_new_user_group_perm(self, user_group, perm_name):
191 def _make_new_user_group_perm(self, user_group, perm_name):
192 log.debug('Creating new user group permission:%s', perm_name)
192 log.debug('Creating new user group permission:%s', perm_name)
193 new_perm = Permission.get_by_key(perm_name)
193 new_perm = Permission.get_by_key(perm_name)
194 if not new_perm:
194 if not new_perm:
195 raise ValueError(f'permission with name {perm_name} not found')
195 raise ValueError(f'permission with name {perm_name} not found')
196
196
197 new = UserGroupToPerm()
197 new = UserGroupToPerm()
198 new.users_group = user_group
198 new.users_group = user_group
199 new.permission = new_perm
199 new.permission = new_perm
200 return new
200 return new
201
201
202 def _keep_perm(self, perm_name, keep_fields):
202 def _keep_perm(self, perm_name, keep_fields):
203 def get_pat(field_name):
203 def get_pat(field_name):
204 return {
204 return {
205 # global perms
205 # global perms
206 'default_repo_create': 'hg.create.',
206 'default_repo_create': 'hg.create.',
207 # special case for create repos on write access to group
207 # special case for create repos on write access to group
208 'default_repo_create_on_write': 'hg.create.write_on_repogroup.',
208 'default_repo_create_on_write': 'hg.create.write_on_repogroup.',
209 'default_repo_group_create': 'hg.repogroup.create.',
209 'default_repo_group_create': 'hg.repogroup.create.',
210 'default_user_group_create': 'hg.usergroup.create.',
210 'default_user_group_create': 'hg.usergroup.create.',
211 'default_fork_create': 'hg.fork.',
211 'default_fork_create': 'hg.fork.',
212 'default_inherit_default_permissions': 'hg.inherit_default_perms.',
212 'default_inherit_default_permissions': 'hg.inherit_default_perms.',
213
213
214 # application perms
214 # application perms
215 'default_register': 'hg.register.',
215 'default_register': 'hg.register.',
216 'default_password_reset': 'hg.password_reset.',
216 'default_password_reset': 'hg.password_reset.',
217 'default_extern_activate': 'hg.extern_activate.',
217 'default_extern_activate': 'hg.extern_activate.',
218
218
219 # object permissions below
219 # object permissions below
220 'default_repo_perm': 'repository.',
220 'default_repo_perm': 'repository.',
221 'default_group_perm': 'group.',
221 'default_group_perm': 'group.',
222 'default_user_group_perm': 'usergroup.',
222 'default_user_group_perm': 'usergroup.',
223 # branch
223 # branch
224 'default_branch_perm': 'branch.',
224 'default_branch_perm': 'branch.',
225
225
226 }[field_name]
226 }[field_name]
227 for field in keep_fields:
227 for field in keep_fields:
228 pat = get_pat(field)
228 pat = get_pat(field)
229 if perm_name.startswith(pat):
229 if perm_name.startswith(pat):
230 return True
230 return True
231 return False
231 return False
232
232
233 def _clear_object_perm(self, object_perms, preserve=None):
233 def _clear_object_perm(self, object_perms, preserve=None):
234 preserve = preserve or []
234 preserve = preserve or []
235 _deleted = []
235 _deleted = []
236 for perm in object_perms:
236 for perm in object_perms:
237 perm_name = perm.permission.permission_name
237 perm_name = perm.permission.permission_name
238 if not self._keep_perm(perm_name, keep_fields=preserve):
238 if not self._keep_perm(perm_name, keep_fields=preserve):
239 _deleted.append(perm_name)
239 _deleted.append(perm_name)
240 self.sa.delete(perm)
240 self.sa.delete(perm)
241 return _deleted
241 return _deleted
242
242
243 def _clear_user_perms(self, user_id, preserve=None):
243 def _clear_user_perms(self, user_id, preserve=None):
244 perms = self.sa.query(UserToPerm)\
244 perms = self.sa.query(UserToPerm)\
245 .filter(UserToPerm.user_id == user_id)\
245 .filter(UserToPerm.user_id == user_id)\
246 .all()
246 .all()
247 return self._clear_object_perm(perms, preserve=preserve)
247 return self._clear_object_perm(perms, preserve=preserve)
248
248
249 def _clear_user_group_perms(self, user_group_id, preserve=None):
249 def _clear_user_group_perms(self, user_group_id, preserve=None):
250 perms = self.sa.query(UserGroupToPerm)\
250 perms = self.sa.query(UserGroupToPerm)\
251 .filter(UserGroupToPerm.users_group_id == user_group_id)\
251 .filter(UserGroupToPerm.users_group_id == user_group_id)\
252 .all()
252 .all()
253 return self._clear_object_perm(perms, preserve=preserve)
253 return self._clear_object_perm(perms, preserve=preserve)
254
254
255 def _set_new_object_perms(self, obj_type, to_object, form_result, preserve=None):
255 def _set_new_object_perms(self, obj_type, to_object, form_result, preserve=None):
256 # clear current entries, to make this function idempotent
256 # clear current entries, to make this function idempotent
257 # it will fix even if we define more permissions or permissions
257 # it will fix even if we define more permissions or permissions
258 # are somehow missing
258 # are somehow missing
259 preserve = preserve or []
259 preserve = preserve or []
260 _global_perms = self.global_perms.copy()
260 _global_perms = self.global_perms.copy()
261 if obj_type not in ['user', 'user_group']:
261 if obj_type not in ['user', 'user_group']:
262 raise ValueError("obj_type must be on of 'user' or 'user_group'")
262 raise ValueError("obj_type must be on of 'user' or 'user_group'")
263 global_perms = len(_global_perms)
263 global_perms = len(_global_perms)
264 default_user_perms = len(Permission.DEFAULT_USER_PERMISSIONS)
264 default_user_perms = len(Permission.DEFAULT_USER_PERMISSIONS)
265 if global_perms != default_user_perms:
265 if global_perms != default_user_perms:
266 raise Exception(
266 raise Exception(
267 'Inconsistent permissions definition. Got {} vs {}'.format(
267 'Inconsistent permissions definition. Got {} vs {}'.format(
268 global_perms, default_user_perms))
268 global_perms, default_user_perms))
269
269
270 if obj_type == 'user':
270 if obj_type == 'user':
271 self._clear_user_perms(to_object.user_id, preserve)
271 self._clear_user_perms(to_object.user_id, preserve)
272 if obj_type == 'user_group':
272 if obj_type == 'user_group':
273 self._clear_user_group_perms(to_object.users_group_id, preserve)
273 self._clear_user_group_perms(to_object.users_group_id, preserve)
274
274
275 # now kill the keys that we want to preserve from the form.
275 # now kill the keys that we want to preserve from the form.
276 for key in preserve:
276 for key in preserve:
277 del _global_perms[key]
277 del _global_perms[key]
278
278
279 for k in _global_perms.copy():
279 for k in _global_perms.copy():
280 _global_perms[k] = form_result[k]
280 _global_perms[k] = form_result[k]
281
281
282 # at that stage we validate all are passed inside form_result
282 # at that stage we validate all are passed inside form_result
283 for _perm_key, perm_value in _global_perms.items():
283 for _perm_key, perm_value in _global_perms.items():
284 if perm_value is None:
284 if perm_value is None:
285 raise ValueError('Missing permission for {}'.format(_perm_key))
285 raise ValueError('Missing permission for {}'.format(_perm_key))
286
286
287 if obj_type == 'user':
287 if obj_type == 'user':
288 p = self._make_new_user_perm(to_object, perm_value)
288 p = self._make_new_user_perm(to_object, perm_value)
289 self.sa.add(p)
289 self.sa.add(p)
290 if obj_type == 'user_group':
290 if obj_type == 'user_group':
291 p = self._make_new_user_group_perm(to_object, perm_value)
291 p = self._make_new_user_group_perm(to_object, perm_value)
292 self.sa.add(p)
292 self.sa.add(p)
293
293
294 def _set_new_user_perms(self, user, form_result, preserve=None):
294 def _set_new_user_perms(self, user, form_result, preserve=None):
295 return self._set_new_object_perms(
295 return self._set_new_object_perms(
296 'user', user, form_result, preserve)
296 'user', user, form_result, preserve)
297
297
298 def _set_new_user_group_perms(self, user_group, form_result, preserve=None):
298 def _set_new_user_group_perms(self, user_group, form_result, preserve=None):
299 return self._set_new_object_perms(
299 return self._set_new_object_perms(
300 'user_group', user_group, form_result, preserve)
300 'user_group', user_group, form_result, preserve)
301
301
302 def set_new_user_perms(self, user, form_result):
302 def set_new_user_perms(self, user, form_result):
303 # calculate what to preserve from what is given in form_result
303 # calculate what to preserve from what is given in form_result
304 preserve = set(self.global_perms.keys()).difference(set(form_result.keys()))
304 preserve = set(self.global_perms.keys()).difference(set(form_result.keys()))
305 return self._set_new_user_perms(user, form_result, preserve)
305 return self._set_new_user_perms(user, form_result, preserve)
306
306
307 def set_new_user_group_perms(self, user_group, form_result):
307 def set_new_user_group_perms(self, user_group, form_result):
308 # calculate what to preserve from what is given in form_result
308 # calculate what to preserve from what is given in form_result
309 preserve = set(self.global_perms.keys()).difference(set(form_result.keys()))
309 preserve = set(self.global_perms.keys()).difference(set(form_result.keys()))
310 return self._set_new_user_group_perms(user_group, form_result, preserve)
310 return self._set_new_user_group_perms(user_group, form_result, preserve)
311
311
312 def create_permissions(self):
312 def create_permissions(self):
313 """
313 """
314 Create permissions for whole system
314 Create permissions for whole system
315 """
315 """
316 for p in Permission.PERMS:
316 for p in Permission.PERMS:
317 if not Permission.get_by_key(p[0]):
317 if not Permission.get_by_key(p[0]):
318 new_perm = Permission()
318 new_perm = Permission()
319 new_perm.permission_name = p[0]
319 new_perm.permission_name = p[0]
320 new_perm.permission_longname = p[0] # translation err with p[1]
320 new_perm.permission_longname = p[0] # translation err with p[1]
321 self.sa.add(new_perm)
321 self.sa.add(new_perm)
322
322
323 def _create_default_object_permission(self, obj_type, obj, obj_perms,
323 def _create_default_object_permission(self, obj_type, obj, obj_perms,
324 force=False):
324 force=False):
325 if obj_type not in ['user', 'user_group']:
325 if obj_type not in ['user', 'user_group']:
326 raise ValueError("obj_type must be on of 'user' or 'user_group'")
326 raise ValueError("obj_type must be on of 'user' or 'user_group'")
327
327
328 def _get_group(perm_name):
328 def _get_group(perm_name):
329 return '.'.join(perm_name.split('.')[:1])
329 return '.'.join(perm_name.split('.')[:1])
330
330
331 defined_perms_groups = list(map(
331 defined_perms_groups = list(map(
332 _get_group, (x.permission.permission_name for x in obj_perms)))
332 _get_group, (x.permission.permission_name for x in obj_perms)))
333 log.debug('GOT ALREADY DEFINED:%s', obj_perms)
333 log.debug('GOT ALREADY DEFINED:%s', obj_perms)
334
334
335 if force:
335 if force:
336 self._clear_object_perm(obj_perms)
336 self._clear_object_perm(obj_perms)
337 self.sa.commit()
337 self.sa.commit()
338 defined_perms_groups = []
338 defined_perms_groups = []
339 # for every default permission that needs to be created, we check if
339 # for every default permission that needs to be created, we check if
340 # it's group is already defined, if it's not we create default perm
340 # it's group is already defined, if it's not we create default perm
341 for perm_name in Permission.DEFAULT_USER_PERMISSIONS:
341 for perm_name in Permission.DEFAULT_USER_PERMISSIONS:
342 gr = _get_group(perm_name)
342 gr = _get_group(perm_name)
343 if gr not in defined_perms_groups:
343 if gr not in defined_perms_groups:
344 log.debug('GR:%s not found, creating permission %s',
344 log.debug('GR:%s not found, creating permission %s',
345 gr, perm_name)
345 gr, perm_name)
346 if obj_type == 'user':
346 if obj_type == 'user':
347 new_perm = self._make_new_user_perm(obj, perm_name)
347 new_perm = self._make_new_user_perm(obj, perm_name)
348 self.sa.add(new_perm)
348 self.sa.add(new_perm)
349 if obj_type == 'user_group':
349 if obj_type == 'user_group':
350 new_perm = self._make_new_user_group_perm(obj, perm_name)
350 new_perm = self._make_new_user_group_perm(obj, perm_name)
351 self.sa.add(new_perm)
351 self.sa.add(new_perm)
352
352
353 def create_default_user_permissions(self, user, force=False):
353 def create_default_user_permissions(self, user, force=False):
354 """
354 """
355 Creates only missing default permissions for user, if force is set it
355 Creates only missing default permissions for user, if force is set it
356 resets the default permissions for that user
356 resets the default permissions for that user
357
357
358 :param user:
358 :param user:
359 :param force:
359 :param force:
360 """
360 """
361 user = self._get_user(user)
361 user = self._get_user(user)
362 obj_perms = UserToPerm.query().filter(UserToPerm.user == user).all()
362 obj_perms = UserToPerm.query().filter(UserToPerm.user == user).all()
363 return self._create_default_object_permission(
363 return self._create_default_object_permission(
364 'user', user, obj_perms, force)
364 'user', user, obj_perms, force)
365
365
366 def create_default_user_group_permissions(self, user_group, force=False):
366 def create_default_user_group_permissions(self, user_group, force=False):
367 """
367 """
368 Creates only missing default permissions for user group, if force is
368 Creates only missing default permissions for user group, if force is
369 set it resets the default permissions for that user group
369 set it resets the default permissions for that user group
370
370
371 :param user_group:
371 :param user_group:
372 :param force:
372 :param force:
373 """
373 """
374 user_group = self._get_user_group(user_group)
374 user_group = self._get_user_group(user_group)
375 obj_perms = UserToPerm.query().filter(UserGroupToPerm.users_group == user_group).all()
375 obj_perms = UserToPerm.query().filter(UserGroupToPerm.users_group == user_group).all()
376 return self._create_default_object_permission(
376 return self._create_default_object_permission(
377 'user_group', user_group, obj_perms, force)
377 'user_group', user_group, obj_perms, force)
378
378
379 def update_application_permissions(self, form_result):
379 def update_application_permissions(self, form_result):
380 if 'perm_user_id' in form_result:
380 if 'perm_user_id' in form_result:
381 perm_user = User.get(safe_int(form_result['perm_user_id']))
381 perm_user = User.get(safe_int(form_result['perm_user_id']))
382 else:
382 else:
383 # used mostly to do lookup for default user
383 # used mostly to do lookup for default user
384 perm_user = User.get_by_username(form_result['perm_user_name'])
384 perm_user = User.get_by_username(form_result['perm_user_name'])
385
385
386 try:
386 try:
387 # stage 1 set anonymous access
387 # stage 1 set anonymous access
388 if perm_user.username == User.DEFAULT_USER:
388 if perm_user.username == User.DEFAULT_USER:
389 perm_user.active = str2bool(form_result['anonymous'])
389 perm_user.active = str2bool(form_result['anonymous'])
390 self.sa.add(perm_user)
390 self.sa.add(perm_user)
391
391
392 # stage 2 reset defaults and set them from form data
392 # stage 2 reset defaults and set them from form data
393 self._set_new_user_perms(perm_user, form_result, preserve=[
393 self._set_new_user_perms(perm_user, form_result, preserve=[
394 'default_repo_perm',
394 'default_repo_perm',
395 'default_group_perm',
395 'default_group_perm',
396 'default_user_group_perm',
396 'default_user_group_perm',
397 'default_branch_perm',
397 'default_branch_perm',
398
398
399 'default_repo_group_create',
399 'default_repo_group_create',
400 'default_user_group_create',
400 'default_user_group_create',
401 'default_repo_create_on_write',
401 'default_repo_create_on_write',
402 'default_repo_create',
402 'default_repo_create',
403 'default_fork_create',
403 'default_fork_create',
404 'default_inherit_default_permissions'])
404 'default_inherit_default_permissions'])
405
405
406 self.sa.commit()
406 self.sa.commit()
407 except (DatabaseError,):
407 except (DatabaseError,):
408 log.error(traceback.format_exc())
408 log.error(traceback.format_exc())
409 self.sa.rollback()
409 self.sa.rollback()
410 raise
410 raise
411
411
412 def update_user_permissions(self, form_result):
412 def update_user_permissions(self, form_result):
413 if 'perm_user_id' in form_result:
413 if 'perm_user_id' in form_result:
414 perm_user = User.get(safe_int(form_result['perm_user_id']))
414 perm_user = User.get(safe_int(form_result['perm_user_id']))
415 else:
415 else:
416 # used mostly to do lookup for default user
416 # used mostly to do lookup for default user
417 perm_user = User.get_by_username(form_result['perm_user_name'])
417 perm_user = User.get_by_username(form_result['perm_user_name'])
418 try:
418 try:
419 # stage 2 reset defaults and set them from form data
419 # stage 2 reset defaults and set them from form data
420 self._set_new_user_perms(perm_user, form_result, preserve=[
420 self._set_new_user_perms(perm_user, form_result, preserve=[
421 'default_repo_perm',
421 'default_repo_perm',
422 'default_group_perm',
422 'default_group_perm',
423 'default_user_group_perm',
423 'default_user_group_perm',
424 'default_branch_perm',
424 'default_branch_perm',
425
425
426 'default_register',
426 'default_register',
427 'default_password_reset',
427 'default_password_reset',
428 'default_extern_activate'])
428 'default_extern_activate'])
429 self.sa.commit()
429 self.sa.commit()
430 except (DatabaseError,):
430 except (DatabaseError,):
431 log.error(traceback.format_exc())
431 log.error(traceback.format_exc())
432 self.sa.rollback()
432 self.sa.rollback()
433 raise
433 raise
434
434
435 def update_user_group_permissions(self, form_result):
435 def update_user_group_permissions(self, form_result):
436 if 'perm_user_group_id' in form_result:
436 if 'perm_user_group_id' in form_result:
437 perm_user_group = UserGroup.get(safe_int(form_result['perm_user_group_id']))
437 perm_user_group = UserGroup.get(safe_int(form_result['perm_user_group_id']))
438 else:
438 else:
439 # used mostly to do lookup for default user
439 # used mostly to do lookup for default user
440 perm_user_group = UserGroup.get_by_group_name(form_result['perm_user_group_name'])
440 perm_user_group = UserGroup.get_by_group_name(form_result['perm_user_group_name'])
441 try:
441 try:
442 # stage 2 reset defaults and set them from form data
442 # stage 2 reset defaults and set them from form data
443 self._set_new_user_group_perms(perm_user_group, form_result, preserve=[
443 self._set_new_user_group_perms(perm_user_group, form_result, preserve=[
444 'default_repo_perm',
444 'default_repo_perm',
445 'default_group_perm',
445 'default_group_perm',
446 'default_user_group_perm',
446 'default_user_group_perm',
447 'default_branch_perm',
447 'default_branch_perm',
448
448
449 'default_register',
449 'default_register',
450 'default_password_reset',
450 'default_password_reset',
451 'default_extern_activate'])
451 'default_extern_activate'])
452 self.sa.commit()
452 self.sa.commit()
453 except (DatabaseError,):
453 except (DatabaseError,):
454 log.error(traceback.format_exc())
454 log.error(traceback.format_exc())
455 self.sa.rollback()
455 self.sa.rollback()
456 raise
456 raise
457
457
458 def update_object_permissions(self, form_result):
458 def update_object_permissions(self, form_result):
459 if 'perm_user_id' in form_result:
459 if 'perm_user_id' in form_result:
460 perm_user = User.get(safe_int(form_result['perm_user_id']))
460 perm_user = User.get(safe_int(form_result['perm_user_id']))
461 else:
461 else:
462 # used mostly to do lookup for default user
462 # used mostly to do lookup for default user
463 perm_user = User.get_by_username(form_result['perm_user_name'])
463 perm_user = User.get_by_username(form_result['perm_user_name'])
464 try:
464 try:
465
465
466 # stage 2 reset defaults and set them from form data
466 # stage 2 reset defaults and set them from form data
467 self._set_new_user_perms(perm_user, form_result, preserve=[
467 self._set_new_user_perms(perm_user, form_result, preserve=[
468 'default_repo_group_create',
468 'default_repo_group_create',
469 'default_user_group_create',
469 'default_user_group_create',
470 'default_repo_create_on_write',
470 'default_repo_create_on_write',
471 'default_repo_create',
471 'default_repo_create',
472 'default_fork_create',
472 'default_fork_create',
473 'default_inherit_default_permissions',
473 'default_inherit_default_permissions',
474 'default_branch_perm',
474 'default_branch_perm',
475
475
476 'default_register',
476 'default_register',
477 'default_password_reset',
477 'default_password_reset',
478 'default_extern_activate'])
478 'default_extern_activate'])
479
479
480 # overwrite default repo permissions
480 # overwrite default repo permissions
481 if form_result['overwrite_default_repo']:
481 if form_result['overwrite_default_repo']:
482 _def_name = form_result['default_repo_perm'].split('repository.')[-1]
482 _def_name = form_result['default_repo_perm'].split('repository.')[-1]
483 _def = Permission.get_by_key('repository.' + _def_name)
483 _def = Permission.get_by_key('repository.' + _def_name)
484 for r2p in self.sa.query(UserRepoToPerm)\
484 for r2p in self.sa.query(UserRepoToPerm)\
485 .filter(UserRepoToPerm.user == perm_user)\
485 .filter(UserRepoToPerm.user == perm_user)\
486 .all():
486 .all():
487 # don't reset PRIVATE repositories
487 # don't reset PRIVATE repositories
488 if not r2p.repository.private:
488 if not r2p.repository.private:
489 r2p.permission = _def
489 r2p.permission = _def
490 self.sa.add(r2p)
490 self.sa.add(r2p)
491
491
492 # overwrite default repo group permissions
492 # overwrite default repo group permissions
493 if form_result['overwrite_default_group']:
493 if form_result['overwrite_default_group']:
494 _def_name = form_result['default_group_perm'].split('group.')[-1]
494 _def_name = form_result['default_group_perm'].split('group.')[-1]
495 _def = Permission.get_by_key('group.' + _def_name)
495 _def = Permission.get_by_key('group.' + _def_name)
496 for g2p in self.sa.query(UserRepoGroupToPerm)\
496 for g2p in self.sa.query(UserRepoGroupToPerm)\
497 .filter(UserRepoGroupToPerm.user == perm_user)\
497 .filter(UserRepoGroupToPerm.user == perm_user)\
498 .all():
498 .all():
499 g2p.permission = _def
499 g2p.permission = _def
500 self.sa.add(g2p)
500 self.sa.add(g2p)
501
501
502 # overwrite default user group permissions
502 # overwrite default user group permissions
503 if form_result['overwrite_default_user_group']:
503 if form_result['overwrite_default_user_group']:
504 _def_name = form_result['default_user_group_perm'].split('usergroup.')[-1]
504 _def_name = form_result['default_user_group_perm'].split('usergroup.')[-1]
505 # user groups
505 # user groups
506 _def = Permission.get_by_key('usergroup.' + _def_name)
506 _def = Permission.get_by_key('usergroup.' + _def_name)
507 for g2p in self.sa.query(UserUserGroupToPerm)\
507 for g2p in self.sa.query(UserUserGroupToPerm)\
508 .filter(UserUserGroupToPerm.user == perm_user)\
508 .filter(UserUserGroupToPerm.user == perm_user)\
509 .all():
509 .all():
510 g2p.permission = _def
510 g2p.permission = _def
511 self.sa.add(g2p)
511 self.sa.add(g2p)
512
512
513 # COMMIT
513 # COMMIT
514 self.sa.commit()
514 self.sa.commit()
515 except (DatabaseError,):
515 except (DatabaseError,):
516 log.exception('Failed to set default object permissions')
516 log.exception('Failed to set default object permissions')
517 self.sa.rollback()
517 self.sa.rollback()
518 raise
518 raise
519
519
520 # because we've FORCED and update here, make sure we reset all permissions cache
521 PermissionModel().trigger_permission_flush()
522
520 def update_branch_permissions(self, form_result):
523 def update_branch_permissions(self, form_result):
521 if 'perm_user_id' in form_result:
524 if 'perm_user_id' in form_result:
522 perm_user = User.get(safe_int(form_result['perm_user_id']))
525 perm_user = User.get(safe_int(form_result['perm_user_id']))
523 else:
526 else:
524 # used mostly to do lookup for default user
527 # used mostly to do lookup for default user
525 perm_user = User.get_by_username(form_result['perm_user_name'])
528 perm_user = User.get_by_username(form_result['perm_user_name'])
526 try:
529 try:
527
530
528 # stage 2 reset defaults and set them from form data
531 # stage 2 reset defaults and set them from form data
529 self._set_new_user_perms(perm_user, form_result, preserve=[
532 self._set_new_user_perms(perm_user, form_result, preserve=[
530 'default_repo_perm',
533 'default_repo_perm',
531 'default_group_perm',
534 'default_group_perm',
532 'default_user_group_perm',
535 'default_user_group_perm',
533
536
534 'default_repo_group_create',
537 'default_repo_group_create',
535 'default_user_group_create',
538 'default_user_group_create',
536 'default_repo_create_on_write',
539 'default_repo_create_on_write',
537 'default_repo_create',
540 'default_repo_create',
538 'default_fork_create',
541 'default_fork_create',
539 'default_inherit_default_permissions',
542 'default_inherit_default_permissions',
540
543
541 'default_register',
544 'default_register',
542 'default_password_reset',
545 'default_password_reset',
543 'default_extern_activate'])
546 'default_extern_activate'])
544
547
545 # overwrite default branch permissions
548 # overwrite default branch permissions
546 if form_result['overwrite_default_branch']:
549 if form_result['overwrite_default_branch']:
547 _def_name = \
550 _def_name = \
548 form_result['default_branch_perm'].split('branch.')[-1]
551 form_result['default_branch_perm'].split('branch.')[-1]
549
552
550 _def = Permission.get_by_key('branch.' + _def_name)
553 _def = Permission.get_by_key('branch.' + _def_name)
551
554
552 user_perms = UserToRepoBranchPermission.query()\
555 user_perms = UserToRepoBranchPermission.query()\
553 .join(UserToRepoBranchPermission.user_repo_to_perm)\
556 .join(UserToRepoBranchPermission.user_repo_to_perm)\
554 .filter(UserRepoToPerm.user == perm_user).all()
557 .filter(UserRepoToPerm.user == perm_user).all()
555
558
556 for g2p in user_perms:
559 for g2p in user_perms:
557 g2p.permission = _def
560 g2p.permission = _def
558 self.sa.add(g2p)
561 self.sa.add(g2p)
559
562
560 # COMMIT
563 # COMMIT
561 self.sa.commit()
564 self.sa.commit()
562 except (DatabaseError,):
565 except (DatabaseError,):
563 log.exception('Failed to set default branch permissions')
566 log.exception('Failed to set default branch permissions')
564 self.sa.rollback()
567 self.sa.rollback()
565 raise
568 raise
566
569
567 def get_users_with_repo_write(self, db_repo):
570 def get_users_with_repo_write(self, db_repo):
568 write_plus = ['repository.write', 'repository.admin']
571 write_plus = ['repository.write', 'repository.admin']
569 default_user_id = User.get_default_user_id()
572 default_user_id = User.get_default_user_id()
570 user_write_permissions = collections.OrderedDict()
573 user_write_permissions = collections.OrderedDict()
571
574
572 # write or higher and DEFAULT user for inheritance
575 # write or higher and DEFAULT user for inheritance
573 for perm in db_repo.permissions():
576 for perm in db_repo.permissions():
574 if perm.permission in write_plus or perm.user_id == default_user_id:
577 if perm.permission in write_plus or perm.user_id == default_user_id:
575 user_write_permissions[perm.user_id] = perm
578 user_write_permissions[perm.user_id] = perm
576 return user_write_permissions
579 return user_write_permissions
577
580
578 def get_user_groups_with_repo_write(self, db_repo):
581 def get_user_groups_with_repo_write(self, db_repo):
579 write_plus = ['repository.write', 'repository.admin']
582 write_plus = ['repository.write', 'repository.admin']
580 user_group_write_permissions = collections.OrderedDict()
583 user_group_write_permissions = collections.OrderedDict()
581
584
582 # write or higher and DEFAULT user for inheritance
585 # write or higher and DEFAULT user for inheritance
583 for p in db_repo.permission_user_groups():
586 for p in db_repo.permission_user_groups():
584 if p.permission in write_plus:
587 if p.permission in write_plus:
585 user_group_write_permissions[p.users_group_id] = p
588 user_group_write_permissions[p.users_group_id] = p
586 return user_group_write_permissions
589 return user_group_write_permissions
587
590
588 def trigger_permission_flush(self, affected_user_ids=None):
591 def trigger_permission_flush(self, affected_user_ids=None):
589 affected_user_ids = affected_user_ids or User.get_all_user_ids()
592 affected_user_ids = affected_user_ids or User.get_all_user_ids()
590 events.trigger(events.UserPermissionsChange(affected_user_ids))
593 events.trigger(events.UserPermissionsChange(affected_user_ids))
591
594
592 def flush_user_permission_caches(self, changes, affected_user_ids=None):
595 def flush_user_permission_caches(self, changes, affected_user_ids=None):
593 affected_user_ids = affected_user_ids or []
596 affected_user_ids = affected_user_ids or []
594
597
595 for change in changes['added'] + changes['updated'] + changes['deleted']:
598 for change in changes['added'] + changes['updated'] + changes['deleted']:
596 if change['type'] == 'user':
599 if change['type'] == 'user':
597 affected_user_ids.append(change['id'])
600 affected_user_ids.append(change['id'])
598 if change['type'] == 'user_group':
601 if change['type'] == 'user_group':
599 user_group = UserGroup.get(safe_int(change['id']))
602 user_group = UserGroup.get(safe_int(change['id']))
600 if user_group:
603 if user_group:
601 group_members_ids = [x.user_id for x in user_group.members]
604 group_members_ids = [x.user_id for x in user_group.members]
602 affected_user_ids.extend(group_members_ids)
605 affected_user_ids.extend(group_members_ids)
603
606
604 self.trigger_permission_flush(affected_user_ids)
607 self.trigger_permission_flush(affected_user_ids)
605
608
606 return affected_user_ids
609 return affected_user_ids
General Comments 0
You need to be logged in to leave comments. Login now