##// END OF EJS Templates
auth: XHRRequired decorator is no longer required....
marcink -
r1999:6219530b default
parent child Browse files
Show More
@@ -1,419 +1,419 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2011-2017 RhodeCode GmbH
3 # Copyright (C) 2011-2017 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 """
21 """
22 User Groups crud controller for pylons
22 User Groups crud controller for pylons
23 """
23 """
24
24
25 import logging
25 import logging
26 import formencode
26 import formencode
27
27
28 import peppercorn
28 import peppercorn
29 from formencode import htmlfill
29 from formencode import htmlfill
30 from pylons import request, tmpl_context as c, url, config
30 from pylons import request, tmpl_context as c, url, config
31 from pylons.controllers.util import redirect
31 from pylons.controllers.util import redirect
32 from pylons.i18n.translation import _
32 from pylons.i18n.translation import _
33
33
34 from sqlalchemy.orm import joinedload
34 from sqlalchemy.orm import joinedload
35
35
36 from rhodecode.lib import auth
36 from rhodecode.lib import auth
37 from rhodecode.lib import helpers as h
37 from rhodecode.lib import helpers as h
38 from rhodecode.lib import audit_logger
38 from rhodecode.lib import audit_logger
39 from rhodecode.lib.ext_json import json
39 from rhodecode.lib.ext_json import json
40 from rhodecode.lib.exceptions import UserGroupAssignedException,\
40 from rhodecode.lib.exceptions import UserGroupAssignedException,\
41 RepoGroupAssignmentError
41 RepoGroupAssignmentError
42 from rhodecode.lib.utils import jsonify
42 from rhodecode.lib.utils import jsonify
43 from rhodecode.lib.utils2 import safe_unicode, str2bool, safe_int
43 from rhodecode.lib.utils2 import safe_unicode, str2bool, safe_int
44 from rhodecode.lib.auth import (
44 from rhodecode.lib.auth import (
45 LoginRequired, NotAnonymous, HasUserGroupPermissionAnyDecorator,
45 LoginRequired, NotAnonymous, HasUserGroupPermissionAnyDecorator,
46 HasPermissionAnyDecorator, XHRRequired)
46 HasPermissionAnyDecorator)
47 from rhodecode.lib.base import BaseController, render
47 from rhodecode.lib.base import BaseController, render
48 from rhodecode.model.permission import PermissionModel
48 from rhodecode.model.permission import PermissionModel
49 from rhodecode.model.scm import UserGroupList
49 from rhodecode.model.scm import UserGroupList
50 from rhodecode.model.user_group import UserGroupModel
50 from rhodecode.model.user_group import UserGroupModel
51 from rhodecode.model.db import (
51 from rhodecode.model.db import (
52 User, UserGroup, UserGroupRepoToPerm, UserGroupRepoGroupToPerm)
52 User, UserGroup, UserGroupRepoToPerm, UserGroupRepoGroupToPerm)
53 from rhodecode.model.forms import (
53 from rhodecode.model.forms import (
54 UserGroupForm, UserGroupPermsForm, UserIndividualPermissionsForm,
54 UserGroupForm, UserGroupPermsForm, UserIndividualPermissionsForm,
55 UserPermissionsForm)
55 UserPermissionsForm)
56 from rhodecode.model.meta import Session
56 from rhodecode.model.meta import Session
57
57
58
58
59 log = logging.getLogger(__name__)
59 log = logging.getLogger(__name__)
60
60
61
61
62 class UserGroupsController(BaseController):
62 class UserGroupsController(BaseController):
63 """REST Controller styled on the Atom Publishing Protocol"""
63 """REST Controller styled on the Atom Publishing Protocol"""
64
64
65 @LoginRequired()
65 @LoginRequired()
66 def __before__(self):
66 def __before__(self):
67 super(UserGroupsController, self).__before__()
67 super(UserGroupsController, self).__before__()
68 c.available_permissions = config['available_permissions']
68 c.available_permissions = config['available_permissions']
69 PermissionModel().set_global_permission_choices(c, gettext_translator=_)
69 PermissionModel().set_global_permission_choices(c, gettext_translator=_)
70
70
71 def __load_data(self, user_group_id):
71 def __load_data(self, user_group_id):
72 c.group_members_obj = [x.user for x in c.user_group.members]
72 c.group_members_obj = [x.user for x in c.user_group.members]
73 c.group_members_obj.sort(key=lambda u: u.username.lower())
73 c.group_members_obj.sort(key=lambda u: u.username.lower())
74 c.group_members = [(x.user_id, x.username) for x in c.group_members_obj]
74 c.group_members = [(x.user_id, x.username) for x in c.group_members_obj]
75
75
76 def __load_defaults(self, user_group_id):
76 def __load_defaults(self, user_group_id):
77 """
77 """
78 Load defaults settings for edit, and update
78 Load defaults settings for edit, and update
79
79
80 :param user_group_id:
80 :param user_group_id:
81 """
81 """
82 user_group = UserGroup.get_or_404(user_group_id)
82 user_group = UserGroup.get_or_404(user_group_id)
83 data = user_group.get_dict()
83 data = user_group.get_dict()
84 # fill owner
84 # fill owner
85 if user_group.user:
85 if user_group.user:
86 data.update({'user': user_group.user.username})
86 data.update({'user': user_group.user.username})
87 else:
87 else:
88 replacement_user = User.get_first_super_admin().username
88 replacement_user = User.get_first_super_admin().username
89 data.update({'user': replacement_user})
89 data.update({'user': replacement_user})
90 return data
90 return data
91
91
92 def _revoke_perms_on_yourself(self, form_result):
92 def _revoke_perms_on_yourself(self, form_result):
93 _updates = filter(lambda u: c.rhodecode_user.user_id == int(u[0]),
93 _updates = filter(lambda u: c.rhodecode_user.user_id == int(u[0]),
94 form_result['perm_updates'])
94 form_result['perm_updates'])
95 _additions = filter(lambda u: c.rhodecode_user.user_id == int(u[0]),
95 _additions = filter(lambda u: c.rhodecode_user.user_id == int(u[0]),
96 form_result['perm_additions'])
96 form_result['perm_additions'])
97 _deletions = filter(lambda u: c.rhodecode_user.user_id == int(u[0]),
97 _deletions = filter(lambda u: c.rhodecode_user.user_id == int(u[0]),
98 form_result['perm_deletions'])
98 form_result['perm_deletions'])
99 admin_perm = 'usergroup.admin'
99 admin_perm = 'usergroup.admin'
100 if _updates and _updates[0][1] != admin_perm or \
100 if _updates and _updates[0][1] != admin_perm or \
101 _additions and _additions[0][1] != admin_perm or \
101 _additions and _additions[0][1] != admin_perm or \
102 _deletions and _deletions[0][1] != admin_perm:
102 _deletions and _deletions[0][1] != admin_perm:
103 return True
103 return True
104 return False
104 return False
105
105
106 @HasPermissionAnyDecorator('hg.admin', 'hg.usergroup.create.true')
106 @HasPermissionAnyDecorator('hg.admin', 'hg.usergroup.create.true')
107 @auth.CSRFRequired()
107 @auth.CSRFRequired()
108 def create(self):
108 def create(self):
109
109
110 users_group_form = UserGroupForm()()
110 users_group_form = UserGroupForm()()
111 try:
111 try:
112 form_result = users_group_form.to_python(dict(request.POST))
112 form_result = users_group_form.to_python(dict(request.POST))
113 user_group = UserGroupModel().create(
113 user_group = UserGroupModel().create(
114 name=form_result['users_group_name'],
114 name=form_result['users_group_name'],
115 description=form_result['user_group_description'],
115 description=form_result['user_group_description'],
116 owner=c.rhodecode_user.user_id,
116 owner=c.rhodecode_user.user_id,
117 active=form_result['users_group_active'])
117 active=form_result['users_group_active'])
118 Session().flush()
118 Session().flush()
119 creation_data = user_group.get_api_data()
119 creation_data = user_group.get_api_data()
120 user_group_name = form_result['users_group_name']
120 user_group_name = form_result['users_group_name']
121
121
122 audit_logger.store_web(
122 audit_logger.store_web(
123 'user_group.create', action_data={'data': creation_data},
123 'user_group.create', action_data={'data': creation_data},
124 user=c.rhodecode_user)
124 user=c.rhodecode_user)
125
125
126 user_group_link = h.link_to(
126 user_group_link = h.link_to(
127 h.escape(user_group_name),
127 h.escape(user_group_name),
128 url('edit_users_group', user_group_id=user_group.users_group_id))
128 url('edit_users_group', user_group_id=user_group.users_group_id))
129 h.flash(h.literal(_('Created user group %(user_group_link)s')
129 h.flash(h.literal(_('Created user group %(user_group_link)s')
130 % {'user_group_link': user_group_link}),
130 % {'user_group_link': user_group_link}),
131 category='success')
131 category='success')
132 Session().commit()
132 Session().commit()
133 except formencode.Invalid as errors:
133 except formencode.Invalid as errors:
134 return htmlfill.render(
134 return htmlfill.render(
135 render('admin/user_groups/user_group_add.mako'),
135 render('admin/user_groups/user_group_add.mako'),
136 defaults=errors.value,
136 defaults=errors.value,
137 errors=errors.error_dict or {},
137 errors=errors.error_dict or {},
138 prefix_error=False,
138 prefix_error=False,
139 encoding="UTF-8",
139 encoding="UTF-8",
140 force_defaults=False)
140 force_defaults=False)
141 except Exception:
141 except Exception:
142 log.exception("Exception creating user group")
142 log.exception("Exception creating user group")
143 h.flash(_('Error occurred during creation of user group %s') \
143 h.flash(_('Error occurred during creation of user group %s') \
144 % request.POST.get('users_group_name'), category='error')
144 % request.POST.get('users_group_name'), category='error')
145
145
146 return redirect(
146 return redirect(
147 url('edit_users_group', user_group_id=user_group.users_group_id))
147 url('edit_users_group', user_group_id=user_group.users_group_id))
148
148
149 @HasPermissionAnyDecorator('hg.admin', 'hg.usergroup.create.true')
149 @HasPermissionAnyDecorator('hg.admin', 'hg.usergroup.create.true')
150 def new(self):
150 def new(self):
151 """GET /user_groups/new: Form to create a new item"""
151 """GET /user_groups/new: Form to create a new item"""
152 # url('new_users_group')
152 # url('new_users_group')
153 return render('admin/user_groups/user_group_add.mako')
153 return render('admin/user_groups/user_group_add.mako')
154
154
155 @HasUserGroupPermissionAnyDecorator('usergroup.admin')
155 @HasUserGroupPermissionAnyDecorator('usergroup.admin')
156 @auth.CSRFRequired()
156 @auth.CSRFRequired()
157 def update(self, user_group_id):
157 def update(self, user_group_id):
158
158
159 user_group_id = safe_int(user_group_id)
159 user_group_id = safe_int(user_group_id)
160 c.user_group = UserGroup.get_or_404(user_group_id)
160 c.user_group = UserGroup.get_or_404(user_group_id)
161 c.active = 'settings'
161 c.active = 'settings'
162 self.__load_data(user_group_id)
162 self.__load_data(user_group_id)
163
163
164 users_group_form = UserGroupForm(
164 users_group_form = UserGroupForm(
165 edit=True, old_data=c.user_group.get_dict(), allow_disabled=True)()
165 edit=True, old_data=c.user_group.get_dict(), allow_disabled=True)()
166
166
167 old_values = c.user_group.get_api_data()
167 old_values = c.user_group.get_api_data()
168 try:
168 try:
169 form_result = users_group_form.to_python(request.POST)
169 form_result = users_group_form.to_python(request.POST)
170 pstruct = peppercorn.parse(request.POST.items())
170 pstruct = peppercorn.parse(request.POST.items())
171 form_result['users_group_members'] = pstruct['user_group_members']
171 form_result['users_group_members'] = pstruct['user_group_members']
172
172
173 user_group, added_members, removed_members = \
173 user_group, added_members, removed_members = \
174 UserGroupModel().update(c.user_group, form_result)
174 UserGroupModel().update(c.user_group, form_result)
175 updated_user_group = form_result['users_group_name']
175 updated_user_group = form_result['users_group_name']
176
176
177 audit_logger.store_web(
177 audit_logger.store_web(
178 'user_group.edit', action_data={'old_data': old_values},
178 'user_group.edit', action_data={'old_data': old_values},
179 user=c.rhodecode_user)
179 user=c.rhodecode_user)
180
180
181 # TODO(marcink): use added/removed to set user_group.edit.member.add
181 # TODO(marcink): use added/removed to set user_group.edit.member.add
182
182
183 h.flash(_('Updated user group %s') % updated_user_group,
183 h.flash(_('Updated user group %s') % updated_user_group,
184 category='success')
184 category='success')
185 Session().commit()
185 Session().commit()
186 except formencode.Invalid as errors:
186 except formencode.Invalid as errors:
187 defaults = errors.value
187 defaults = errors.value
188 e = errors.error_dict or {}
188 e = errors.error_dict or {}
189
189
190 return htmlfill.render(
190 return htmlfill.render(
191 render('admin/user_groups/user_group_edit.mako'),
191 render('admin/user_groups/user_group_edit.mako'),
192 defaults=defaults,
192 defaults=defaults,
193 errors=e,
193 errors=e,
194 prefix_error=False,
194 prefix_error=False,
195 encoding="UTF-8",
195 encoding="UTF-8",
196 force_defaults=False)
196 force_defaults=False)
197 except Exception:
197 except Exception:
198 log.exception("Exception during update of user group")
198 log.exception("Exception during update of user group")
199 h.flash(_('Error occurred during update of user group %s')
199 h.flash(_('Error occurred during update of user group %s')
200 % request.POST.get('users_group_name'), category='error')
200 % request.POST.get('users_group_name'), category='error')
201
201
202 return redirect(url('edit_users_group', user_group_id=user_group_id))
202 return redirect(url('edit_users_group', user_group_id=user_group_id))
203
203
204 @HasUserGroupPermissionAnyDecorator('usergroup.admin')
204 @HasUserGroupPermissionAnyDecorator('usergroup.admin')
205 @auth.CSRFRequired()
205 @auth.CSRFRequired()
206 def delete(self, user_group_id):
206 def delete(self, user_group_id):
207 user_group_id = safe_int(user_group_id)
207 user_group_id = safe_int(user_group_id)
208 c.user_group = UserGroup.get_or_404(user_group_id)
208 c.user_group = UserGroup.get_or_404(user_group_id)
209 force = str2bool(request.POST.get('force'))
209 force = str2bool(request.POST.get('force'))
210
210
211 old_values = c.user_group.get_api_data()
211 old_values = c.user_group.get_api_data()
212 try:
212 try:
213 UserGroupModel().delete(c.user_group, force=force)
213 UserGroupModel().delete(c.user_group, force=force)
214 audit_logger.store_web(
214 audit_logger.store_web(
215 'user.delete', action_data={'old_data': old_values},
215 'user.delete', action_data={'old_data': old_values},
216 user=c.rhodecode_user)
216 user=c.rhodecode_user)
217 Session().commit()
217 Session().commit()
218 h.flash(_('Successfully deleted user group'), category='success')
218 h.flash(_('Successfully deleted user group'), category='success')
219 except UserGroupAssignedException as e:
219 except UserGroupAssignedException as e:
220 h.flash(str(e), category='error')
220 h.flash(str(e), category='error')
221 except Exception:
221 except Exception:
222 log.exception("Exception during deletion of user group")
222 log.exception("Exception during deletion of user group")
223 h.flash(_('An error occurred during deletion of user group'),
223 h.flash(_('An error occurred during deletion of user group'),
224 category='error')
224 category='error')
225 return redirect(url('users_groups'))
225 return redirect(url('users_groups'))
226
226
227 @HasUserGroupPermissionAnyDecorator('usergroup.admin')
227 @HasUserGroupPermissionAnyDecorator('usergroup.admin')
228 def edit(self, user_group_id):
228 def edit(self, user_group_id):
229 """GET /user_groups/user_group_id/edit: Form to edit an existing item"""
229 """GET /user_groups/user_group_id/edit: Form to edit an existing item"""
230 # url('edit_users_group', user_group_id=ID)
230 # url('edit_users_group', user_group_id=ID)
231
231
232 user_group_id = safe_int(user_group_id)
232 user_group_id = safe_int(user_group_id)
233 c.user_group = UserGroup.get_or_404(user_group_id)
233 c.user_group = UserGroup.get_or_404(user_group_id)
234 c.active = 'settings'
234 c.active = 'settings'
235 self.__load_data(user_group_id)
235 self.__load_data(user_group_id)
236
236
237 defaults = self.__load_defaults(user_group_id)
237 defaults = self.__load_defaults(user_group_id)
238
238
239 return htmlfill.render(
239 return htmlfill.render(
240 render('admin/user_groups/user_group_edit.mako'),
240 render('admin/user_groups/user_group_edit.mako'),
241 defaults=defaults,
241 defaults=defaults,
242 encoding="UTF-8",
242 encoding="UTF-8",
243 force_defaults=False
243 force_defaults=False
244 )
244 )
245
245
246 @HasUserGroupPermissionAnyDecorator('usergroup.admin')
246 @HasUserGroupPermissionAnyDecorator('usergroup.admin')
247 def edit_perms(self, user_group_id):
247 def edit_perms(self, user_group_id):
248 user_group_id = safe_int(user_group_id)
248 user_group_id = safe_int(user_group_id)
249 c.user_group = UserGroup.get_or_404(user_group_id)
249 c.user_group = UserGroup.get_or_404(user_group_id)
250 c.active = 'perms'
250 c.active = 'perms'
251
251
252 defaults = {}
252 defaults = {}
253 # fill user group users
253 # fill user group users
254 for p in c.user_group.user_user_group_to_perm:
254 for p in c.user_group.user_user_group_to_perm:
255 defaults.update({'u_perm_%s' % p.user.user_id:
255 defaults.update({'u_perm_%s' % p.user.user_id:
256 p.permission.permission_name})
256 p.permission.permission_name})
257
257
258 for p in c.user_group.user_group_user_group_to_perm:
258 for p in c.user_group.user_group_user_group_to_perm:
259 defaults.update({'g_perm_%s' % p.user_group.users_group_id:
259 defaults.update({'g_perm_%s' % p.user_group.users_group_id:
260 p.permission.permission_name})
260 p.permission.permission_name})
261
261
262 return htmlfill.render(
262 return htmlfill.render(
263 render('admin/user_groups/user_group_edit.mako'),
263 render('admin/user_groups/user_group_edit.mako'),
264 defaults=defaults,
264 defaults=defaults,
265 encoding="UTF-8",
265 encoding="UTF-8",
266 force_defaults=False
266 force_defaults=False
267 )
267 )
268
268
269 @HasUserGroupPermissionAnyDecorator('usergroup.admin')
269 @HasUserGroupPermissionAnyDecorator('usergroup.admin')
270 @auth.CSRFRequired()
270 @auth.CSRFRequired()
271 def update_perms(self, user_group_id):
271 def update_perms(self, user_group_id):
272 """
272 """
273 grant permission for given usergroup
273 grant permission for given usergroup
274
274
275 :param user_group_id:
275 :param user_group_id:
276 """
276 """
277 user_group_id = safe_int(user_group_id)
277 user_group_id = safe_int(user_group_id)
278 c.user_group = UserGroup.get_or_404(user_group_id)
278 c.user_group = UserGroup.get_or_404(user_group_id)
279 form = UserGroupPermsForm()().to_python(request.POST)
279 form = UserGroupPermsForm()().to_python(request.POST)
280
280
281 if not c.rhodecode_user.is_admin:
281 if not c.rhodecode_user.is_admin:
282 if self._revoke_perms_on_yourself(form):
282 if self._revoke_perms_on_yourself(form):
283 msg = _('Cannot change permission for yourself as admin')
283 msg = _('Cannot change permission for yourself as admin')
284 h.flash(msg, category='warning')
284 h.flash(msg, category='warning')
285 return redirect(url('edit_user_group_perms', user_group_id=user_group_id))
285 return redirect(url('edit_user_group_perms', user_group_id=user_group_id))
286
286
287 try:
287 try:
288 UserGroupModel().update_permissions(user_group_id,
288 UserGroupModel().update_permissions(user_group_id,
289 form['perm_additions'], form['perm_updates'], form['perm_deletions'])
289 form['perm_additions'], form['perm_updates'], form['perm_deletions'])
290 except RepoGroupAssignmentError:
290 except RepoGroupAssignmentError:
291 h.flash(_('Target group cannot be the same'), category='error')
291 h.flash(_('Target group cannot be the same'), category='error')
292 return redirect(url('edit_user_group_perms', user_group_id=user_group_id))
292 return redirect(url('edit_user_group_perms', user_group_id=user_group_id))
293
293
294 # TODO(marcink): implement global permissions
294 # TODO(marcink): implement global permissions
295 # audit_log.store_web('user_group.edit.permissions')
295 # audit_log.store_web('user_group.edit.permissions')
296 Session().commit()
296 Session().commit()
297 h.flash(_('User Group permissions updated'), category='success')
297 h.flash(_('User Group permissions updated'), category='success')
298 return redirect(url('edit_user_group_perms', user_group_id=user_group_id))
298 return redirect(url('edit_user_group_perms', user_group_id=user_group_id))
299
299
300
300
301
301
302 @HasUserGroupPermissionAnyDecorator('usergroup.admin')
302 @HasUserGroupPermissionAnyDecorator('usergroup.admin')
303 def edit_global_perms(self, user_group_id):
303 def edit_global_perms(self, user_group_id):
304 user_group_id = safe_int(user_group_id)
304 user_group_id = safe_int(user_group_id)
305 c.user_group = UserGroup.get_or_404(user_group_id)
305 c.user_group = UserGroup.get_or_404(user_group_id)
306 c.active = 'global_perms'
306 c.active = 'global_perms'
307
307
308 c.default_user = User.get_default_user()
308 c.default_user = User.get_default_user()
309 defaults = c.user_group.get_dict()
309 defaults = c.user_group.get_dict()
310 defaults.update(c.default_user.get_default_perms(suffix='_inherited'))
310 defaults.update(c.default_user.get_default_perms(suffix='_inherited'))
311 defaults.update(c.user_group.get_default_perms())
311 defaults.update(c.user_group.get_default_perms())
312
312
313 return htmlfill.render(
313 return htmlfill.render(
314 render('admin/user_groups/user_group_edit.mako'),
314 render('admin/user_groups/user_group_edit.mako'),
315 defaults=defaults,
315 defaults=defaults,
316 encoding="UTF-8",
316 encoding="UTF-8",
317 force_defaults=False
317 force_defaults=False
318 )
318 )
319
319
320 @HasUserGroupPermissionAnyDecorator('usergroup.admin')
320 @HasUserGroupPermissionAnyDecorator('usergroup.admin')
321 @auth.CSRFRequired()
321 @auth.CSRFRequired()
322 def update_global_perms(self, user_group_id):
322 def update_global_perms(self, user_group_id):
323 user_group_id = safe_int(user_group_id)
323 user_group_id = safe_int(user_group_id)
324 user_group = UserGroup.get_or_404(user_group_id)
324 user_group = UserGroup.get_or_404(user_group_id)
325 c.active = 'global_perms'
325 c.active = 'global_perms'
326
326
327 try:
327 try:
328 # first stage that verifies the checkbox
328 # first stage that verifies the checkbox
329 _form = UserIndividualPermissionsForm()
329 _form = UserIndividualPermissionsForm()
330 form_result = _form.to_python(dict(request.POST))
330 form_result = _form.to_python(dict(request.POST))
331 inherit_perms = form_result['inherit_default_permissions']
331 inherit_perms = form_result['inherit_default_permissions']
332 user_group.inherit_default_permissions = inherit_perms
332 user_group.inherit_default_permissions = inherit_perms
333 Session().add(user_group)
333 Session().add(user_group)
334
334
335 if not inherit_perms:
335 if not inherit_perms:
336 # only update the individual ones if we un check the flag
336 # only update the individual ones if we un check the flag
337 _form = UserPermissionsForm(
337 _form = UserPermissionsForm(
338 [x[0] for x in c.repo_create_choices],
338 [x[0] for x in c.repo_create_choices],
339 [x[0] for x in c.repo_create_on_write_choices],
339 [x[0] for x in c.repo_create_on_write_choices],
340 [x[0] for x in c.repo_group_create_choices],
340 [x[0] for x in c.repo_group_create_choices],
341 [x[0] for x in c.user_group_create_choices],
341 [x[0] for x in c.user_group_create_choices],
342 [x[0] for x in c.fork_choices],
342 [x[0] for x in c.fork_choices],
343 [x[0] for x in c.inherit_default_permission_choices])()
343 [x[0] for x in c.inherit_default_permission_choices])()
344
344
345 form_result = _form.to_python(dict(request.POST))
345 form_result = _form.to_python(dict(request.POST))
346 form_result.update({'perm_user_group_id': user_group.users_group_id})
346 form_result.update({'perm_user_group_id': user_group.users_group_id})
347
347
348 PermissionModel().update_user_group_permissions(form_result)
348 PermissionModel().update_user_group_permissions(form_result)
349
349
350 Session().commit()
350 Session().commit()
351 h.flash(_('User Group global permissions updated successfully'),
351 h.flash(_('User Group global permissions updated successfully'),
352 category='success')
352 category='success')
353
353
354 except formencode.Invalid as errors:
354 except formencode.Invalid as errors:
355 defaults = errors.value
355 defaults = errors.value
356 c.user_group = user_group
356 c.user_group = user_group
357 return htmlfill.render(
357 return htmlfill.render(
358 render('admin/user_groups/user_group_edit.mako'),
358 render('admin/user_groups/user_group_edit.mako'),
359 defaults=defaults,
359 defaults=defaults,
360 errors=errors.error_dict or {},
360 errors=errors.error_dict or {},
361 prefix_error=False,
361 prefix_error=False,
362 encoding="UTF-8",
362 encoding="UTF-8",
363 force_defaults=False)
363 force_defaults=False)
364 except Exception:
364 except Exception:
365 log.exception("Exception during permissions saving")
365 log.exception("Exception during permissions saving")
366 h.flash(_('An error occurred during permissions saving'),
366 h.flash(_('An error occurred during permissions saving'),
367 category='error')
367 category='error')
368
368
369 return redirect(url('edit_user_group_global_perms', user_group_id=user_group_id))
369 return redirect(url('edit_user_group_global_perms', user_group_id=user_group_id))
370
370
371 @HasUserGroupPermissionAnyDecorator('usergroup.admin')
371 @HasUserGroupPermissionAnyDecorator('usergroup.admin')
372 def edit_advanced(self, user_group_id):
372 def edit_advanced(self, user_group_id):
373 user_group_id = safe_int(user_group_id)
373 user_group_id = safe_int(user_group_id)
374 c.user_group = UserGroup.get_or_404(user_group_id)
374 c.user_group = UserGroup.get_or_404(user_group_id)
375 c.active = 'advanced'
375 c.active = 'advanced'
376 c.group_members_obj = sorted(
376 c.group_members_obj = sorted(
377 (x.user for x in c.user_group.members),
377 (x.user for x in c.user_group.members),
378 key=lambda u: u.username.lower())
378 key=lambda u: u.username.lower())
379
379
380 c.group_to_repos = sorted(
380 c.group_to_repos = sorted(
381 (x.repository for x in c.user_group.users_group_repo_to_perm),
381 (x.repository for x in c.user_group.users_group_repo_to_perm),
382 key=lambda u: u.repo_name.lower())
382 key=lambda u: u.repo_name.lower())
383
383
384 c.group_to_repo_groups = sorted(
384 c.group_to_repo_groups = sorted(
385 (x.group for x in c.user_group.users_group_repo_group_to_perm),
385 (x.group for x in c.user_group.users_group_repo_group_to_perm),
386 key=lambda u: u.group_name.lower())
386 key=lambda u: u.group_name.lower())
387
387
388 return render('admin/user_groups/user_group_edit.mako')
388 return render('admin/user_groups/user_group_edit.mako')
389
389
390 @HasUserGroupPermissionAnyDecorator('usergroup.admin')
390 @HasUserGroupPermissionAnyDecorator('usergroup.admin')
391 def edit_advanced_set_synchronization(self, user_group_id):
391 def edit_advanced_set_synchronization(self, user_group_id):
392 user_group_id = safe_int(user_group_id)
392 user_group_id = safe_int(user_group_id)
393 user_group = UserGroup.get_or_404(user_group_id)
393 user_group = UserGroup.get_or_404(user_group_id)
394
394
395 existing = user_group.group_data.get('extern_type')
395 existing = user_group.group_data.get('extern_type')
396
396
397 if existing:
397 if existing:
398 new_state = user_group.group_data
398 new_state = user_group.group_data
399 new_state['extern_type'] = None
399 new_state['extern_type'] = None
400 else:
400 else:
401 new_state = user_group.group_data
401 new_state = user_group.group_data
402 new_state['extern_type'] = 'manual'
402 new_state['extern_type'] = 'manual'
403 new_state['extern_type_set_by'] = c.rhodecode_user.username
403 new_state['extern_type_set_by'] = c.rhodecode_user.username
404
404
405 try:
405 try:
406 user_group.group_data = new_state
406 user_group.group_data = new_state
407 Session().add(user_group)
407 Session().add(user_group)
408 Session().commit()
408 Session().commit()
409
409
410 h.flash(_('User Group synchronization updated successfully'),
410 h.flash(_('User Group synchronization updated successfully'),
411 category='success')
411 category='success')
412 except Exception:
412 except Exception:
413 log.exception("Exception during sync settings saving")
413 log.exception("Exception during sync settings saving")
414 h.flash(_('An error occurred during synchronization update'),
414 h.flash(_('An error occurred during synchronization update'),
415 category='error')
415 category='error')
416
416
417 return redirect(
417 return redirect(
418 url('edit_user_group_advanced', user_group_id=user_group_id))
418 url('edit_user_group_advanced', user_group_id=user_group_id))
419
419
@@ -1,2018 +1,1996 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2010-2017 RhodeCode GmbH
3 # Copyright (C) 2010-2017 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 """
21 """
22 authentication and permission libraries
22 authentication and permission libraries
23 """
23 """
24
24
25 import os
25 import os
26 import inspect
26 import inspect
27 import collections
27 import collections
28 import fnmatch
28 import fnmatch
29 import hashlib
29 import hashlib
30 import itertools
30 import itertools
31 import logging
31 import logging
32 import random
32 import random
33 import traceback
33 import traceback
34 from functools import wraps
34 from functools import wraps
35
35
36 import ipaddress
36 import ipaddress
37 from pyramid.httpexceptions import HTTPForbidden, HTTPFound, HTTPNotFound
37 from pyramid.httpexceptions import HTTPForbidden, HTTPFound, HTTPNotFound
38 from pylons.i18n.translation import _
38 from pylons.i18n.translation import _
39 # NOTE(marcink): this has to be removed only after pyramid migration,
39 # NOTE(marcink): this has to be removed only after pyramid migration,
40 # replace with _ = request.translate
40 # replace with _ = request.translate
41 from sqlalchemy.orm.exc import ObjectDeletedError
41 from sqlalchemy.orm.exc import ObjectDeletedError
42 from sqlalchemy.orm import joinedload
42 from sqlalchemy.orm import joinedload
43 from zope.cachedescriptors.property import Lazy as LazyProperty
43 from zope.cachedescriptors.property import Lazy as LazyProperty
44
44
45 import rhodecode
45 import rhodecode
46 from rhodecode.model import meta
46 from rhodecode.model import meta
47 from rhodecode.model.meta import Session
47 from rhodecode.model.meta import Session
48 from rhodecode.model.user import UserModel
48 from rhodecode.model.user import UserModel
49 from rhodecode.model.db import (
49 from rhodecode.model.db import (
50 User, Repository, Permission, UserToPerm, UserGroupToPerm, UserGroupMember,
50 User, Repository, Permission, UserToPerm, UserGroupToPerm, UserGroupMember,
51 UserIpMap, UserApiKeys, RepoGroup)
51 UserIpMap, UserApiKeys, RepoGroup)
52 from rhodecode.lib import caches
52 from rhodecode.lib import caches
53 from rhodecode.lib.utils2 import safe_unicode, aslist, safe_str, md5
53 from rhodecode.lib.utils2 import safe_unicode, aslist, safe_str, md5
54 from rhodecode.lib.utils import (
54 from rhodecode.lib.utils import (
55 get_repo_slug, get_repo_group_slug, get_user_group_slug)
55 get_repo_slug, get_repo_group_slug, get_user_group_slug)
56 from rhodecode.lib.caching_query import FromCache
56 from rhodecode.lib.caching_query import FromCache
57
57
58
58
59 if rhodecode.is_unix:
59 if rhodecode.is_unix:
60 import bcrypt
60 import bcrypt
61
61
62 log = logging.getLogger(__name__)
62 log = logging.getLogger(__name__)
63
63
64 csrf_token_key = "csrf_token"
64 csrf_token_key = "csrf_token"
65
65
66
66
67 class PasswordGenerator(object):
67 class PasswordGenerator(object):
68 """
68 """
69 This is a simple class for generating password from different sets of
69 This is a simple class for generating password from different sets of
70 characters
70 characters
71 usage::
71 usage::
72
72
73 passwd_gen = PasswordGenerator()
73 passwd_gen = PasswordGenerator()
74 #print 8-letter password containing only big and small letters
74 #print 8-letter password containing only big and small letters
75 of alphabet
75 of alphabet
76 passwd_gen.gen_password(8, passwd_gen.ALPHABETS_BIG_SMALL)
76 passwd_gen.gen_password(8, passwd_gen.ALPHABETS_BIG_SMALL)
77 """
77 """
78 ALPHABETS_NUM = r'''1234567890'''
78 ALPHABETS_NUM = r'''1234567890'''
79 ALPHABETS_SMALL = r'''qwertyuiopasdfghjklzxcvbnm'''
79 ALPHABETS_SMALL = r'''qwertyuiopasdfghjklzxcvbnm'''
80 ALPHABETS_BIG = r'''QWERTYUIOPASDFGHJKLZXCVBNM'''
80 ALPHABETS_BIG = r'''QWERTYUIOPASDFGHJKLZXCVBNM'''
81 ALPHABETS_SPECIAL = r'''`-=[]\;',./~!@#$%^&*()_+{}|:"<>?'''
81 ALPHABETS_SPECIAL = r'''`-=[]\;',./~!@#$%^&*()_+{}|:"<>?'''
82 ALPHABETS_FULL = ALPHABETS_BIG + ALPHABETS_SMALL \
82 ALPHABETS_FULL = ALPHABETS_BIG + ALPHABETS_SMALL \
83 + ALPHABETS_NUM + ALPHABETS_SPECIAL
83 + ALPHABETS_NUM + ALPHABETS_SPECIAL
84 ALPHABETS_ALPHANUM = ALPHABETS_BIG + ALPHABETS_SMALL + ALPHABETS_NUM
84 ALPHABETS_ALPHANUM = ALPHABETS_BIG + ALPHABETS_SMALL + ALPHABETS_NUM
85 ALPHABETS_BIG_SMALL = ALPHABETS_BIG + ALPHABETS_SMALL
85 ALPHABETS_BIG_SMALL = ALPHABETS_BIG + ALPHABETS_SMALL
86 ALPHABETS_ALPHANUM_BIG = ALPHABETS_BIG + ALPHABETS_NUM
86 ALPHABETS_ALPHANUM_BIG = ALPHABETS_BIG + ALPHABETS_NUM
87 ALPHABETS_ALPHANUM_SMALL = ALPHABETS_SMALL + ALPHABETS_NUM
87 ALPHABETS_ALPHANUM_SMALL = ALPHABETS_SMALL + ALPHABETS_NUM
88
88
89 def __init__(self, passwd=''):
89 def __init__(self, passwd=''):
90 self.passwd = passwd
90 self.passwd = passwd
91
91
92 def gen_password(self, length, type_=None):
92 def gen_password(self, length, type_=None):
93 if type_ is None:
93 if type_ is None:
94 type_ = self.ALPHABETS_FULL
94 type_ = self.ALPHABETS_FULL
95 self.passwd = ''.join([random.choice(type_) for _ in xrange(length)])
95 self.passwd = ''.join([random.choice(type_) for _ in xrange(length)])
96 return self.passwd
96 return self.passwd
97
97
98
98
99 class _RhodeCodeCryptoBase(object):
99 class _RhodeCodeCryptoBase(object):
100 ENC_PREF = None
100 ENC_PREF = None
101
101
102 def hash_create(self, str_):
102 def hash_create(self, str_):
103 """
103 """
104 hash the string using
104 hash the string using
105
105
106 :param str_: password to hash
106 :param str_: password to hash
107 """
107 """
108 raise NotImplementedError
108 raise NotImplementedError
109
109
110 def hash_check_with_upgrade(self, password, hashed):
110 def hash_check_with_upgrade(self, password, hashed):
111 """
111 """
112 Returns tuple in which first element is boolean that states that
112 Returns tuple in which first element is boolean that states that
113 given password matches it's hashed version, and the second is new hash
113 given password matches it's hashed version, and the second is new hash
114 of the password, in case this password should be migrated to new
114 of the password, in case this password should be migrated to new
115 cipher.
115 cipher.
116 """
116 """
117 checked_hash = self.hash_check(password, hashed)
117 checked_hash = self.hash_check(password, hashed)
118 return checked_hash, None
118 return checked_hash, None
119
119
120 def hash_check(self, password, hashed):
120 def hash_check(self, password, hashed):
121 """
121 """
122 Checks matching password with it's hashed value.
122 Checks matching password with it's hashed value.
123
123
124 :param password: password
124 :param password: password
125 :param hashed: password in hashed form
125 :param hashed: password in hashed form
126 """
126 """
127 raise NotImplementedError
127 raise NotImplementedError
128
128
129 def _assert_bytes(self, value):
129 def _assert_bytes(self, value):
130 """
130 """
131 Passing in an `unicode` object can lead to hard to detect issues
131 Passing in an `unicode` object can lead to hard to detect issues
132 if passwords contain non-ascii characters. Doing a type check
132 if passwords contain non-ascii characters. Doing a type check
133 during runtime, so that such mistakes are detected early on.
133 during runtime, so that such mistakes are detected early on.
134 """
134 """
135 if not isinstance(value, str):
135 if not isinstance(value, str):
136 raise TypeError(
136 raise TypeError(
137 "Bytestring required as input, got %r." % (value, ))
137 "Bytestring required as input, got %r." % (value, ))
138
138
139
139
140 class _RhodeCodeCryptoBCrypt(_RhodeCodeCryptoBase):
140 class _RhodeCodeCryptoBCrypt(_RhodeCodeCryptoBase):
141 ENC_PREF = ('$2a$10', '$2b$10')
141 ENC_PREF = ('$2a$10', '$2b$10')
142
142
143 def hash_create(self, str_):
143 def hash_create(self, str_):
144 self._assert_bytes(str_)
144 self._assert_bytes(str_)
145 return bcrypt.hashpw(str_, bcrypt.gensalt(10))
145 return bcrypt.hashpw(str_, bcrypt.gensalt(10))
146
146
147 def hash_check_with_upgrade(self, password, hashed):
147 def hash_check_with_upgrade(self, password, hashed):
148 """
148 """
149 Returns tuple in which first element is boolean that states that
149 Returns tuple in which first element is boolean that states that
150 given password matches it's hashed version, and the second is new hash
150 given password matches it's hashed version, and the second is new hash
151 of the password, in case this password should be migrated to new
151 of the password, in case this password should be migrated to new
152 cipher.
152 cipher.
153
153
154 This implements special upgrade logic which works like that:
154 This implements special upgrade logic which works like that:
155 - check if the given password == bcrypted hash, if yes then we
155 - check if the given password == bcrypted hash, if yes then we
156 properly used password and it was already in bcrypt. Proceed
156 properly used password and it was already in bcrypt. Proceed
157 without any changes
157 without any changes
158 - if bcrypt hash check is not working try with sha256. If hash compare
158 - if bcrypt hash check is not working try with sha256. If hash compare
159 is ok, it means we using correct but old hashed password. indicate
159 is ok, it means we using correct but old hashed password. indicate
160 hash change and proceed
160 hash change and proceed
161 """
161 """
162
162
163 new_hash = None
163 new_hash = None
164
164
165 # regular pw check
165 # regular pw check
166 password_match_bcrypt = self.hash_check(password, hashed)
166 password_match_bcrypt = self.hash_check(password, hashed)
167
167
168 # now we want to know if the password was maybe from sha256
168 # now we want to know if the password was maybe from sha256
169 # basically calling _RhodeCodeCryptoSha256().hash_check()
169 # basically calling _RhodeCodeCryptoSha256().hash_check()
170 if not password_match_bcrypt:
170 if not password_match_bcrypt:
171 if _RhodeCodeCryptoSha256().hash_check(password, hashed):
171 if _RhodeCodeCryptoSha256().hash_check(password, hashed):
172 new_hash = self.hash_create(password) # make new bcrypt hash
172 new_hash = self.hash_create(password) # make new bcrypt hash
173 password_match_bcrypt = True
173 password_match_bcrypt = True
174
174
175 return password_match_bcrypt, new_hash
175 return password_match_bcrypt, new_hash
176
176
177 def hash_check(self, password, hashed):
177 def hash_check(self, password, hashed):
178 """
178 """
179 Checks matching password with it's hashed value.
179 Checks matching password with it's hashed value.
180
180
181 :param password: password
181 :param password: password
182 :param hashed: password in hashed form
182 :param hashed: password in hashed form
183 """
183 """
184 self._assert_bytes(password)
184 self._assert_bytes(password)
185 try:
185 try:
186 return bcrypt.hashpw(password, hashed) == hashed
186 return bcrypt.hashpw(password, hashed) == hashed
187 except ValueError as e:
187 except ValueError as e:
188 # we're having a invalid salt here probably, we should not crash
188 # we're having a invalid salt here probably, we should not crash
189 # just return with False as it would be a wrong password.
189 # just return with False as it would be a wrong password.
190 log.debug('Failed to check password hash using bcrypt %s',
190 log.debug('Failed to check password hash using bcrypt %s',
191 safe_str(e))
191 safe_str(e))
192
192
193 return False
193 return False
194
194
195
195
196 class _RhodeCodeCryptoSha256(_RhodeCodeCryptoBase):
196 class _RhodeCodeCryptoSha256(_RhodeCodeCryptoBase):
197 ENC_PREF = '_'
197 ENC_PREF = '_'
198
198
199 def hash_create(self, str_):
199 def hash_create(self, str_):
200 self._assert_bytes(str_)
200 self._assert_bytes(str_)
201 return hashlib.sha256(str_).hexdigest()
201 return hashlib.sha256(str_).hexdigest()
202
202
203 def hash_check(self, password, hashed):
203 def hash_check(self, password, hashed):
204 """
204 """
205 Checks matching password with it's hashed value.
205 Checks matching password with it's hashed value.
206
206
207 :param password: password
207 :param password: password
208 :param hashed: password in hashed form
208 :param hashed: password in hashed form
209 """
209 """
210 self._assert_bytes(password)
210 self._assert_bytes(password)
211 return hashlib.sha256(password).hexdigest() == hashed
211 return hashlib.sha256(password).hexdigest() == hashed
212
212
213
213
214 class _RhodeCodeCryptoMd5(_RhodeCodeCryptoBase):
214 class _RhodeCodeCryptoMd5(_RhodeCodeCryptoBase):
215 ENC_PREF = '_'
215 ENC_PREF = '_'
216
216
217 def hash_create(self, str_):
217 def hash_create(self, str_):
218 self._assert_bytes(str_)
218 self._assert_bytes(str_)
219 return hashlib.md5(str_).hexdigest()
219 return hashlib.md5(str_).hexdigest()
220
220
221 def hash_check(self, password, hashed):
221 def hash_check(self, password, hashed):
222 """
222 """
223 Checks matching password with it's hashed value.
223 Checks matching password with it's hashed value.
224
224
225 :param password: password
225 :param password: password
226 :param hashed: password in hashed form
226 :param hashed: password in hashed form
227 """
227 """
228 self._assert_bytes(password)
228 self._assert_bytes(password)
229 return hashlib.md5(password).hexdigest() == hashed
229 return hashlib.md5(password).hexdigest() == hashed
230
230
231
231
232 def crypto_backend():
232 def crypto_backend():
233 """
233 """
234 Return the matching crypto backend.
234 Return the matching crypto backend.
235
235
236 Selection is based on if we run tests or not, we pick md5 backend to run
236 Selection is based on if we run tests or not, we pick md5 backend to run
237 tests faster since BCRYPT is expensive to calculate
237 tests faster since BCRYPT is expensive to calculate
238 """
238 """
239 if rhodecode.is_test:
239 if rhodecode.is_test:
240 RhodeCodeCrypto = _RhodeCodeCryptoMd5()
240 RhodeCodeCrypto = _RhodeCodeCryptoMd5()
241 else:
241 else:
242 RhodeCodeCrypto = _RhodeCodeCryptoBCrypt()
242 RhodeCodeCrypto = _RhodeCodeCryptoBCrypt()
243
243
244 return RhodeCodeCrypto
244 return RhodeCodeCrypto
245
245
246
246
247 def get_crypt_password(password):
247 def get_crypt_password(password):
248 """
248 """
249 Create the hash of `password` with the active crypto backend.
249 Create the hash of `password` with the active crypto backend.
250
250
251 :param password: The cleartext password.
251 :param password: The cleartext password.
252 :type password: unicode
252 :type password: unicode
253 """
253 """
254 password = safe_str(password)
254 password = safe_str(password)
255 return crypto_backend().hash_create(password)
255 return crypto_backend().hash_create(password)
256
256
257
257
258 def check_password(password, hashed):
258 def check_password(password, hashed):
259 """
259 """
260 Check if the value in `password` matches the hash in `hashed`.
260 Check if the value in `password` matches the hash in `hashed`.
261
261
262 :param password: The cleartext password.
262 :param password: The cleartext password.
263 :type password: unicode
263 :type password: unicode
264
264
265 :param hashed: The expected hashed version of the password.
265 :param hashed: The expected hashed version of the password.
266 :type hashed: The hash has to be passed in in text representation.
266 :type hashed: The hash has to be passed in in text representation.
267 """
267 """
268 password = safe_str(password)
268 password = safe_str(password)
269 return crypto_backend().hash_check(password, hashed)
269 return crypto_backend().hash_check(password, hashed)
270
270
271
271
272 def generate_auth_token(data, salt=None):
272 def generate_auth_token(data, salt=None):
273 """
273 """
274 Generates API KEY from given string
274 Generates API KEY from given string
275 """
275 """
276
276
277 if salt is None:
277 if salt is None:
278 salt = os.urandom(16)
278 salt = os.urandom(16)
279 return hashlib.sha1(safe_str(data) + salt).hexdigest()
279 return hashlib.sha1(safe_str(data) + salt).hexdigest()
280
280
281
281
282 class CookieStoreWrapper(object):
282 class CookieStoreWrapper(object):
283
283
284 def __init__(self, cookie_store):
284 def __init__(self, cookie_store):
285 self.cookie_store = cookie_store
285 self.cookie_store = cookie_store
286
286
287 def __repr__(self):
287 def __repr__(self):
288 return 'CookieStore<%s>' % (self.cookie_store)
288 return 'CookieStore<%s>' % (self.cookie_store)
289
289
290 def get(self, key, other=None):
290 def get(self, key, other=None):
291 if isinstance(self.cookie_store, dict):
291 if isinstance(self.cookie_store, dict):
292 return self.cookie_store.get(key, other)
292 return self.cookie_store.get(key, other)
293 elif isinstance(self.cookie_store, AuthUser):
293 elif isinstance(self.cookie_store, AuthUser):
294 return self.cookie_store.__dict__.get(key, other)
294 return self.cookie_store.__dict__.get(key, other)
295
295
296
296
297 def _cached_perms_data(user_id, scope, user_is_admin,
297 def _cached_perms_data(user_id, scope, user_is_admin,
298 user_inherit_default_permissions, explicit, algo):
298 user_inherit_default_permissions, explicit, algo):
299
299
300 permissions = PermissionCalculator(
300 permissions = PermissionCalculator(
301 user_id, scope, user_is_admin, user_inherit_default_permissions,
301 user_id, scope, user_is_admin, user_inherit_default_permissions,
302 explicit, algo)
302 explicit, algo)
303 return permissions.calculate()
303 return permissions.calculate()
304
304
305
305
306 class PermOrigin(object):
306 class PermOrigin(object):
307 ADMIN = 'superadmin'
307 ADMIN = 'superadmin'
308
308
309 REPO_USER = 'user:%s'
309 REPO_USER = 'user:%s'
310 REPO_USERGROUP = 'usergroup:%s'
310 REPO_USERGROUP = 'usergroup:%s'
311 REPO_OWNER = 'repo.owner'
311 REPO_OWNER = 'repo.owner'
312 REPO_DEFAULT = 'repo.default'
312 REPO_DEFAULT = 'repo.default'
313 REPO_PRIVATE = 'repo.private'
313 REPO_PRIVATE = 'repo.private'
314
314
315 REPOGROUP_USER = 'user:%s'
315 REPOGROUP_USER = 'user:%s'
316 REPOGROUP_USERGROUP = 'usergroup:%s'
316 REPOGROUP_USERGROUP = 'usergroup:%s'
317 REPOGROUP_OWNER = 'group.owner'
317 REPOGROUP_OWNER = 'group.owner'
318 REPOGROUP_DEFAULT = 'group.default'
318 REPOGROUP_DEFAULT = 'group.default'
319
319
320 USERGROUP_USER = 'user:%s'
320 USERGROUP_USER = 'user:%s'
321 USERGROUP_USERGROUP = 'usergroup:%s'
321 USERGROUP_USERGROUP = 'usergroup:%s'
322 USERGROUP_OWNER = 'usergroup.owner'
322 USERGROUP_OWNER = 'usergroup.owner'
323 USERGROUP_DEFAULT = 'usergroup.default'
323 USERGROUP_DEFAULT = 'usergroup.default'
324
324
325
325
326 class PermOriginDict(dict):
326 class PermOriginDict(dict):
327 """
327 """
328 A special dict used for tracking permissions along with their origins.
328 A special dict used for tracking permissions along with their origins.
329
329
330 `__setitem__` has been overridden to expect a tuple(perm, origin)
330 `__setitem__` has been overridden to expect a tuple(perm, origin)
331 `__getitem__` will return only the perm
331 `__getitem__` will return only the perm
332 `.perm_origin_stack` will return the stack of (perm, origin) set per key
332 `.perm_origin_stack` will return the stack of (perm, origin) set per key
333
333
334 >>> perms = PermOriginDict()
334 >>> perms = PermOriginDict()
335 >>> perms['resource'] = 'read', 'default'
335 >>> perms['resource'] = 'read', 'default'
336 >>> perms['resource']
336 >>> perms['resource']
337 'read'
337 'read'
338 >>> perms['resource'] = 'write', 'admin'
338 >>> perms['resource'] = 'write', 'admin'
339 >>> perms['resource']
339 >>> perms['resource']
340 'write'
340 'write'
341 >>> perms.perm_origin_stack
341 >>> perms.perm_origin_stack
342 {'resource': [('read', 'default'), ('write', 'admin')]}
342 {'resource': [('read', 'default'), ('write', 'admin')]}
343 """
343 """
344
344
345 def __init__(self, *args, **kw):
345 def __init__(self, *args, **kw):
346 dict.__init__(self, *args, **kw)
346 dict.__init__(self, *args, **kw)
347 self.perm_origin_stack = {}
347 self.perm_origin_stack = {}
348
348
349 def __setitem__(self, key, (perm, origin)):
349 def __setitem__(self, key, (perm, origin)):
350 self.perm_origin_stack.setdefault(key, []).append((perm, origin))
350 self.perm_origin_stack.setdefault(key, []).append((perm, origin))
351 dict.__setitem__(self, key, perm)
351 dict.__setitem__(self, key, perm)
352
352
353
353
354 class PermissionCalculator(object):
354 class PermissionCalculator(object):
355
355
356 def __init__(
356 def __init__(
357 self, user_id, scope, user_is_admin,
357 self, user_id, scope, user_is_admin,
358 user_inherit_default_permissions, explicit, algo):
358 user_inherit_default_permissions, explicit, algo):
359 self.user_id = user_id
359 self.user_id = user_id
360 self.user_is_admin = user_is_admin
360 self.user_is_admin = user_is_admin
361 self.inherit_default_permissions = user_inherit_default_permissions
361 self.inherit_default_permissions = user_inherit_default_permissions
362 self.explicit = explicit
362 self.explicit = explicit
363 self.algo = algo
363 self.algo = algo
364
364
365 scope = scope or {}
365 scope = scope or {}
366 self.scope_repo_id = scope.get('repo_id')
366 self.scope_repo_id = scope.get('repo_id')
367 self.scope_repo_group_id = scope.get('repo_group_id')
367 self.scope_repo_group_id = scope.get('repo_group_id')
368 self.scope_user_group_id = scope.get('user_group_id')
368 self.scope_user_group_id = scope.get('user_group_id')
369
369
370 self.default_user_id = User.get_default_user(cache=True).user_id
370 self.default_user_id = User.get_default_user(cache=True).user_id
371
371
372 self.permissions_repositories = PermOriginDict()
372 self.permissions_repositories = PermOriginDict()
373 self.permissions_repository_groups = PermOriginDict()
373 self.permissions_repository_groups = PermOriginDict()
374 self.permissions_user_groups = PermOriginDict()
374 self.permissions_user_groups = PermOriginDict()
375 self.permissions_global = set()
375 self.permissions_global = set()
376
376
377 self.default_repo_perms = Permission.get_default_repo_perms(
377 self.default_repo_perms = Permission.get_default_repo_perms(
378 self.default_user_id, self.scope_repo_id)
378 self.default_user_id, self.scope_repo_id)
379 self.default_repo_groups_perms = Permission.get_default_group_perms(
379 self.default_repo_groups_perms = Permission.get_default_group_perms(
380 self.default_user_id, self.scope_repo_group_id)
380 self.default_user_id, self.scope_repo_group_id)
381 self.default_user_group_perms = \
381 self.default_user_group_perms = \
382 Permission.get_default_user_group_perms(
382 Permission.get_default_user_group_perms(
383 self.default_user_id, self.scope_user_group_id)
383 self.default_user_id, self.scope_user_group_id)
384
384
385 def calculate(self):
385 def calculate(self):
386 if self.user_is_admin:
386 if self.user_is_admin:
387 return self._admin_permissions()
387 return self._admin_permissions()
388
388
389 self._calculate_global_default_permissions()
389 self._calculate_global_default_permissions()
390 self._calculate_global_permissions()
390 self._calculate_global_permissions()
391 self._calculate_default_permissions()
391 self._calculate_default_permissions()
392 self._calculate_repository_permissions()
392 self._calculate_repository_permissions()
393 self._calculate_repository_group_permissions()
393 self._calculate_repository_group_permissions()
394 self._calculate_user_group_permissions()
394 self._calculate_user_group_permissions()
395 return self._permission_structure()
395 return self._permission_structure()
396
396
397 def _admin_permissions(self):
397 def _admin_permissions(self):
398 """
398 """
399 admin user have all default rights for repositories
399 admin user have all default rights for repositories
400 and groups set to admin
400 and groups set to admin
401 """
401 """
402 self.permissions_global.add('hg.admin')
402 self.permissions_global.add('hg.admin')
403 self.permissions_global.add('hg.create.write_on_repogroup.true')
403 self.permissions_global.add('hg.create.write_on_repogroup.true')
404
404
405 # repositories
405 # repositories
406 for perm in self.default_repo_perms:
406 for perm in self.default_repo_perms:
407 r_k = perm.UserRepoToPerm.repository.repo_name
407 r_k = perm.UserRepoToPerm.repository.repo_name
408 p = 'repository.admin'
408 p = 'repository.admin'
409 self.permissions_repositories[r_k] = p, PermOrigin.ADMIN
409 self.permissions_repositories[r_k] = p, PermOrigin.ADMIN
410
410
411 # repository groups
411 # repository groups
412 for perm in self.default_repo_groups_perms:
412 for perm in self.default_repo_groups_perms:
413 rg_k = perm.UserRepoGroupToPerm.group.group_name
413 rg_k = perm.UserRepoGroupToPerm.group.group_name
414 p = 'group.admin'
414 p = 'group.admin'
415 self.permissions_repository_groups[rg_k] = p, PermOrigin.ADMIN
415 self.permissions_repository_groups[rg_k] = p, PermOrigin.ADMIN
416
416
417 # user groups
417 # user groups
418 for perm in self.default_user_group_perms:
418 for perm in self.default_user_group_perms:
419 u_k = perm.UserUserGroupToPerm.user_group.users_group_name
419 u_k = perm.UserUserGroupToPerm.user_group.users_group_name
420 p = 'usergroup.admin'
420 p = 'usergroup.admin'
421 self.permissions_user_groups[u_k] = p, PermOrigin.ADMIN
421 self.permissions_user_groups[u_k] = p, PermOrigin.ADMIN
422
422
423 return self._permission_structure()
423 return self._permission_structure()
424
424
425 def _calculate_global_default_permissions(self):
425 def _calculate_global_default_permissions(self):
426 """
426 """
427 global permissions taken from the default user
427 global permissions taken from the default user
428 """
428 """
429 default_global_perms = UserToPerm.query()\
429 default_global_perms = UserToPerm.query()\
430 .filter(UserToPerm.user_id == self.default_user_id)\
430 .filter(UserToPerm.user_id == self.default_user_id)\
431 .options(joinedload(UserToPerm.permission))
431 .options(joinedload(UserToPerm.permission))
432
432
433 for perm in default_global_perms:
433 for perm in default_global_perms:
434 self.permissions_global.add(perm.permission.permission_name)
434 self.permissions_global.add(perm.permission.permission_name)
435
435
436 def _calculate_global_permissions(self):
436 def _calculate_global_permissions(self):
437 """
437 """
438 Set global system permissions with user permissions or permissions
438 Set global system permissions with user permissions or permissions
439 taken from the user groups of the current user.
439 taken from the user groups of the current user.
440
440
441 The permissions include repo creating, repo group creating, forking
441 The permissions include repo creating, repo group creating, forking
442 etc.
442 etc.
443 """
443 """
444
444
445 # now we read the defined permissions and overwrite what we have set
445 # now we read the defined permissions and overwrite what we have set
446 # before those can be configured from groups or users explicitly.
446 # before those can be configured from groups or users explicitly.
447
447
448 # TODO: johbo: This seems to be out of sync, find out the reason
448 # TODO: johbo: This seems to be out of sync, find out the reason
449 # for the comment below and update it.
449 # for the comment below and update it.
450
450
451 # In case we want to extend this list we should be always in sync with
451 # In case we want to extend this list we should be always in sync with
452 # User.DEFAULT_USER_PERMISSIONS definitions
452 # User.DEFAULT_USER_PERMISSIONS definitions
453 _configurable = frozenset([
453 _configurable = frozenset([
454 'hg.fork.none', 'hg.fork.repository',
454 'hg.fork.none', 'hg.fork.repository',
455 'hg.create.none', 'hg.create.repository',
455 'hg.create.none', 'hg.create.repository',
456 'hg.usergroup.create.false', 'hg.usergroup.create.true',
456 'hg.usergroup.create.false', 'hg.usergroup.create.true',
457 'hg.repogroup.create.false', 'hg.repogroup.create.true',
457 'hg.repogroup.create.false', 'hg.repogroup.create.true',
458 'hg.create.write_on_repogroup.false',
458 'hg.create.write_on_repogroup.false',
459 'hg.create.write_on_repogroup.true',
459 'hg.create.write_on_repogroup.true',
460 'hg.inherit_default_perms.false', 'hg.inherit_default_perms.true'
460 'hg.inherit_default_perms.false', 'hg.inherit_default_perms.true'
461 ])
461 ])
462
462
463 # USER GROUPS comes first user group global permissions
463 # USER GROUPS comes first user group global permissions
464 user_perms_from_users_groups = Session().query(UserGroupToPerm)\
464 user_perms_from_users_groups = Session().query(UserGroupToPerm)\
465 .options(joinedload(UserGroupToPerm.permission))\
465 .options(joinedload(UserGroupToPerm.permission))\
466 .join((UserGroupMember, UserGroupToPerm.users_group_id ==
466 .join((UserGroupMember, UserGroupToPerm.users_group_id ==
467 UserGroupMember.users_group_id))\
467 UserGroupMember.users_group_id))\
468 .filter(UserGroupMember.user_id == self.user_id)\
468 .filter(UserGroupMember.user_id == self.user_id)\
469 .order_by(UserGroupToPerm.users_group_id)\
469 .order_by(UserGroupToPerm.users_group_id)\
470 .all()
470 .all()
471
471
472 # need to group here by groups since user can be in more than
472 # need to group here by groups since user can be in more than
473 # one group, so we get all groups
473 # one group, so we get all groups
474 _explicit_grouped_perms = [
474 _explicit_grouped_perms = [
475 [x, list(y)] for x, y in
475 [x, list(y)] for x, y in
476 itertools.groupby(user_perms_from_users_groups,
476 itertools.groupby(user_perms_from_users_groups,
477 lambda _x: _x.users_group)]
477 lambda _x: _x.users_group)]
478
478
479 for gr, perms in _explicit_grouped_perms:
479 for gr, perms in _explicit_grouped_perms:
480 # since user can be in multiple groups iterate over them and
480 # since user can be in multiple groups iterate over them and
481 # select the lowest permissions first (more explicit)
481 # select the lowest permissions first (more explicit)
482 # TODO: marcink: do this^^
482 # TODO: marcink: do this^^
483
483
484 # group doesn't inherit default permissions so we actually set them
484 # group doesn't inherit default permissions so we actually set them
485 if not gr.inherit_default_permissions:
485 if not gr.inherit_default_permissions:
486 # NEED TO IGNORE all previously set configurable permissions
486 # NEED TO IGNORE all previously set configurable permissions
487 # and replace them with explicitly set from this user
487 # and replace them with explicitly set from this user
488 # group permissions
488 # group permissions
489 self.permissions_global = self.permissions_global.difference(
489 self.permissions_global = self.permissions_global.difference(
490 _configurable)
490 _configurable)
491 for perm in perms:
491 for perm in perms:
492 self.permissions_global.add(perm.permission.permission_name)
492 self.permissions_global.add(perm.permission.permission_name)
493
493
494 # user explicit global permissions
494 # user explicit global permissions
495 user_perms = Session().query(UserToPerm)\
495 user_perms = Session().query(UserToPerm)\
496 .options(joinedload(UserToPerm.permission))\
496 .options(joinedload(UserToPerm.permission))\
497 .filter(UserToPerm.user_id == self.user_id).all()
497 .filter(UserToPerm.user_id == self.user_id).all()
498
498
499 if not self.inherit_default_permissions:
499 if not self.inherit_default_permissions:
500 # NEED TO IGNORE all configurable permissions and
500 # NEED TO IGNORE all configurable permissions and
501 # replace them with explicitly set from this user permissions
501 # replace them with explicitly set from this user permissions
502 self.permissions_global = self.permissions_global.difference(
502 self.permissions_global = self.permissions_global.difference(
503 _configurable)
503 _configurable)
504 for perm in user_perms:
504 for perm in user_perms:
505 self.permissions_global.add(perm.permission.permission_name)
505 self.permissions_global.add(perm.permission.permission_name)
506
506
507 def _calculate_default_permissions(self):
507 def _calculate_default_permissions(self):
508 """
508 """
509 Set default user permissions for repositories, repository groups
509 Set default user permissions for repositories, repository groups
510 taken from the default user.
510 taken from the default user.
511
511
512 Calculate inheritance of object permissions based on what we have now
512 Calculate inheritance of object permissions based on what we have now
513 in GLOBAL permissions. We check if .false is in GLOBAL since this is
513 in GLOBAL permissions. We check if .false is in GLOBAL since this is
514 explicitly set. Inherit is the opposite of .false being there.
514 explicitly set. Inherit is the opposite of .false being there.
515
515
516 .. note::
516 .. note::
517
517
518 the syntax is little bit odd but what we need to check here is
518 the syntax is little bit odd but what we need to check here is
519 the opposite of .false permission being in the list so even for
519 the opposite of .false permission being in the list so even for
520 inconsistent state when both .true/.false is there
520 inconsistent state when both .true/.false is there
521 .false is more important
521 .false is more important
522
522
523 """
523 """
524 user_inherit_object_permissions = not ('hg.inherit_default_perms.false'
524 user_inherit_object_permissions = not ('hg.inherit_default_perms.false'
525 in self.permissions_global)
525 in self.permissions_global)
526
526
527 # defaults for repositories, taken from `default` user permissions
527 # defaults for repositories, taken from `default` user permissions
528 # on given repo
528 # on given repo
529 for perm in self.default_repo_perms:
529 for perm in self.default_repo_perms:
530 r_k = perm.UserRepoToPerm.repository.repo_name
530 r_k = perm.UserRepoToPerm.repository.repo_name
531 o = PermOrigin.REPO_DEFAULT
531 o = PermOrigin.REPO_DEFAULT
532 if perm.Repository.private and not (
532 if perm.Repository.private and not (
533 perm.Repository.user_id == self.user_id):
533 perm.Repository.user_id == self.user_id):
534 # disable defaults for private repos,
534 # disable defaults for private repos,
535 p = 'repository.none'
535 p = 'repository.none'
536 o = PermOrigin.REPO_PRIVATE
536 o = PermOrigin.REPO_PRIVATE
537 elif perm.Repository.user_id == self.user_id:
537 elif perm.Repository.user_id == self.user_id:
538 # set admin if owner
538 # set admin if owner
539 p = 'repository.admin'
539 p = 'repository.admin'
540 o = PermOrigin.REPO_OWNER
540 o = PermOrigin.REPO_OWNER
541 else:
541 else:
542 p = perm.Permission.permission_name
542 p = perm.Permission.permission_name
543 # if we decide this user isn't inheriting permissions from
543 # if we decide this user isn't inheriting permissions from
544 # default user we set him to .none so only explicit
544 # default user we set him to .none so only explicit
545 # permissions work
545 # permissions work
546 if not user_inherit_object_permissions:
546 if not user_inherit_object_permissions:
547 p = 'repository.none'
547 p = 'repository.none'
548 self.permissions_repositories[r_k] = p, o
548 self.permissions_repositories[r_k] = p, o
549
549
550 # defaults for repository groups taken from `default` user permission
550 # defaults for repository groups taken from `default` user permission
551 # on given group
551 # on given group
552 for perm in self.default_repo_groups_perms:
552 for perm in self.default_repo_groups_perms:
553 rg_k = perm.UserRepoGroupToPerm.group.group_name
553 rg_k = perm.UserRepoGroupToPerm.group.group_name
554 o = PermOrigin.REPOGROUP_DEFAULT
554 o = PermOrigin.REPOGROUP_DEFAULT
555 if perm.RepoGroup.user_id == self.user_id:
555 if perm.RepoGroup.user_id == self.user_id:
556 # set admin if owner
556 # set admin if owner
557 p = 'group.admin'
557 p = 'group.admin'
558 o = PermOrigin.REPOGROUP_OWNER
558 o = PermOrigin.REPOGROUP_OWNER
559 else:
559 else:
560 p = perm.Permission.permission_name
560 p = perm.Permission.permission_name
561
561
562 # if we decide this user isn't inheriting permissions from default
562 # if we decide this user isn't inheriting permissions from default
563 # user we set him to .none so only explicit permissions work
563 # user we set him to .none so only explicit permissions work
564 if not user_inherit_object_permissions:
564 if not user_inherit_object_permissions:
565 p = 'group.none'
565 p = 'group.none'
566 self.permissions_repository_groups[rg_k] = p, o
566 self.permissions_repository_groups[rg_k] = p, o
567
567
568 # defaults for user groups taken from `default` user permission
568 # defaults for user groups taken from `default` user permission
569 # on given user group
569 # on given user group
570 for perm in self.default_user_group_perms:
570 for perm in self.default_user_group_perms:
571 u_k = perm.UserUserGroupToPerm.user_group.users_group_name
571 u_k = perm.UserUserGroupToPerm.user_group.users_group_name
572 o = PermOrigin.USERGROUP_DEFAULT
572 o = PermOrigin.USERGROUP_DEFAULT
573 if perm.UserGroup.user_id == self.user_id:
573 if perm.UserGroup.user_id == self.user_id:
574 # set admin if owner
574 # set admin if owner
575 p = 'usergroup.admin'
575 p = 'usergroup.admin'
576 o = PermOrigin.USERGROUP_OWNER
576 o = PermOrigin.USERGROUP_OWNER
577 else:
577 else:
578 p = perm.Permission.permission_name
578 p = perm.Permission.permission_name
579
579
580 # if we decide this user isn't inheriting permissions from default
580 # if we decide this user isn't inheriting permissions from default
581 # user we set him to .none so only explicit permissions work
581 # user we set him to .none so only explicit permissions work
582 if not user_inherit_object_permissions:
582 if not user_inherit_object_permissions:
583 p = 'usergroup.none'
583 p = 'usergroup.none'
584 self.permissions_user_groups[u_k] = p, o
584 self.permissions_user_groups[u_k] = p, o
585
585
586 def _calculate_repository_permissions(self):
586 def _calculate_repository_permissions(self):
587 """
587 """
588 Repository permissions for the current user.
588 Repository permissions for the current user.
589
589
590 Check if the user is part of user groups for this repository and
590 Check if the user is part of user groups for this repository and
591 fill in the permission from it. `_choose_permission` decides of which
591 fill in the permission from it. `_choose_permission` decides of which
592 permission should be selected based on selected method.
592 permission should be selected based on selected method.
593 """
593 """
594
594
595 # user group for repositories permissions
595 # user group for repositories permissions
596 user_repo_perms_from_user_group = Permission\
596 user_repo_perms_from_user_group = Permission\
597 .get_default_repo_perms_from_user_group(
597 .get_default_repo_perms_from_user_group(
598 self.user_id, self.scope_repo_id)
598 self.user_id, self.scope_repo_id)
599
599
600 multiple_counter = collections.defaultdict(int)
600 multiple_counter = collections.defaultdict(int)
601 for perm in user_repo_perms_from_user_group:
601 for perm in user_repo_perms_from_user_group:
602 r_k = perm.UserGroupRepoToPerm.repository.repo_name
602 r_k = perm.UserGroupRepoToPerm.repository.repo_name
603 ug_k = perm.UserGroupRepoToPerm.users_group.users_group_name
603 ug_k = perm.UserGroupRepoToPerm.users_group.users_group_name
604 multiple_counter[r_k] += 1
604 multiple_counter[r_k] += 1
605 p = perm.Permission.permission_name
605 p = perm.Permission.permission_name
606 o = PermOrigin.REPO_USERGROUP % ug_k
606 o = PermOrigin.REPO_USERGROUP % ug_k
607
607
608 if perm.Repository.user_id == self.user_id:
608 if perm.Repository.user_id == self.user_id:
609 # set admin if owner
609 # set admin if owner
610 p = 'repository.admin'
610 p = 'repository.admin'
611 o = PermOrigin.REPO_OWNER
611 o = PermOrigin.REPO_OWNER
612 else:
612 else:
613 if multiple_counter[r_k] > 1:
613 if multiple_counter[r_k] > 1:
614 cur_perm = self.permissions_repositories[r_k]
614 cur_perm = self.permissions_repositories[r_k]
615 p = self._choose_permission(p, cur_perm)
615 p = self._choose_permission(p, cur_perm)
616 self.permissions_repositories[r_k] = p, o
616 self.permissions_repositories[r_k] = p, o
617
617
618 # user explicit permissions for repositories, overrides any specified
618 # user explicit permissions for repositories, overrides any specified
619 # by the group permission
619 # by the group permission
620 user_repo_perms = Permission.get_default_repo_perms(
620 user_repo_perms = Permission.get_default_repo_perms(
621 self.user_id, self.scope_repo_id)
621 self.user_id, self.scope_repo_id)
622 for perm in user_repo_perms:
622 for perm in user_repo_perms:
623 r_k = perm.UserRepoToPerm.repository.repo_name
623 r_k = perm.UserRepoToPerm.repository.repo_name
624 o = PermOrigin.REPO_USER % perm.UserRepoToPerm.user.username
624 o = PermOrigin.REPO_USER % perm.UserRepoToPerm.user.username
625 # set admin if owner
625 # set admin if owner
626 if perm.Repository.user_id == self.user_id:
626 if perm.Repository.user_id == self.user_id:
627 p = 'repository.admin'
627 p = 'repository.admin'
628 o = PermOrigin.REPO_OWNER
628 o = PermOrigin.REPO_OWNER
629 else:
629 else:
630 p = perm.Permission.permission_name
630 p = perm.Permission.permission_name
631 if not self.explicit:
631 if not self.explicit:
632 cur_perm = self.permissions_repositories.get(
632 cur_perm = self.permissions_repositories.get(
633 r_k, 'repository.none')
633 r_k, 'repository.none')
634 p = self._choose_permission(p, cur_perm)
634 p = self._choose_permission(p, cur_perm)
635 self.permissions_repositories[r_k] = p, o
635 self.permissions_repositories[r_k] = p, o
636
636
637 def _calculate_repository_group_permissions(self):
637 def _calculate_repository_group_permissions(self):
638 """
638 """
639 Repository group permissions for the current user.
639 Repository group permissions for the current user.
640
640
641 Check if the user is part of user groups for repository groups and
641 Check if the user is part of user groups for repository groups and
642 fill in the permissions from it. `_choose_permmission` decides of which
642 fill in the permissions from it. `_choose_permmission` decides of which
643 permission should be selected based on selected method.
643 permission should be selected based on selected method.
644 """
644 """
645 # user group for repo groups permissions
645 # user group for repo groups permissions
646 user_repo_group_perms_from_user_group = Permission\
646 user_repo_group_perms_from_user_group = Permission\
647 .get_default_group_perms_from_user_group(
647 .get_default_group_perms_from_user_group(
648 self.user_id, self.scope_repo_group_id)
648 self.user_id, self.scope_repo_group_id)
649
649
650 multiple_counter = collections.defaultdict(int)
650 multiple_counter = collections.defaultdict(int)
651 for perm in user_repo_group_perms_from_user_group:
651 for perm in user_repo_group_perms_from_user_group:
652 g_k = perm.UserGroupRepoGroupToPerm.group.group_name
652 g_k = perm.UserGroupRepoGroupToPerm.group.group_name
653 ug_k = perm.UserGroupRepoGroupToPerm.users_group.users_group_name
653 ug_k = perm.UserGroupRepoGroupToPerm.users_group.users_group_name
654 o = PermOrigin.REPOGROUP_USERGROUP % ug_k
654 o = PermOrigin.REPOGROUP_USERGROUP % ug_k
655 multiple_counter[g_k] += 1
655 multiple_counter[g_k] += 1
656 p = perm.Permission.permission_name
656 p = perm.Permission.permission_name
657 if perm.RepoGroup.user_id == self.user_id:
657 if perm.RepoGroup.user_id == self.user_id:
658 # set admin if owner, even for member of other user group
658 # set admin if owner, even for member of other user group
659 p = 'group.admin'
659 p = 'group.admin'
660 o = PermOrigin.REPOGROUP_OWNER
660 o = PermOrigin.REPOGROUP_OWNER
661 else:
661 else:
662 if multiple_counter[g_k] > 1:
662 if multiple_counter[g_k] > 1:
663 cur_perm = self.permissions_repository_groups[g_k]
663 cur_perm = self.permissions_repository_groups[g_k]
664 p = self._choose_permission(p, cur_perm)
664 p = self._choose_permission(p, cur_perm)
665 self.permissions_repository_groups[g_k] = p, o
665 self.permissions_repository_groups[g_k] = p, o
666
666
667 # user explicit permissions for repository groups
667 # user explicit permissions for repository groups
668 user_repo_groups_perms = Permission.get_default_group_perms(
668 user_repo_groups_perms = Permission.get_default_group_perms(
669 self.user_id, self.scope_repo_group_id)
669 self.user_id, self.scope_repo_group_id)
670 for perm in user_repo_groups_perms:
670 for perm in user_repo_groups_perms:
671 rg_k = perm.UserRepoGroupToPerm.group.group_name
671 rg_k = perm.UserRepoGroupToPerm.group.group_name
672 u_k = perm.UserRepoGroupToPerm.user.username
672 u_k = perm.UserRepoGroupToPerm.user.username
673 o = PermOrigin.REPOGROUP_USER % u_k
673 o = PermOrigin.REPOGROUP_USER % u_k
674
674
675 if perm.RepoGroup.user_id == self.user_id:
675 if perm.RepoGroup.user_id == self.user_id:
676 # set admin if owner
676 # set admin if owner
677 p = 'group.admin'
677 p = 'group.admin'
678 o = PermOrigin.REPOGROUP_OWNER
678 o = PermOrigin.REPOGROUP_OWNER
679 else:
679 else:
680 p = perm.Permission.permission_name
680 p = perm.Permission.permission_name
681 if not self.explicit:
681 if not self.explicit:
682 cur_perm = self.permissions_repository_groups.get(
682 cur_perm = self.permissions_repository_groups.get(
683 rg_k, 'group.none')
683 rg_k, 'group.none')
684 p = self._choose_permission(p, cur_perm)
684 p = self._choose_permission(p, cur_perm)
685 self.permissions_repository_groups[rg_k] = p, o
685 self.permissions_repository_groups[rg_k] = p, o
686
686
687 def _calculate_user_group_permissions(self):
687 def _calculate_user_group_permissions(self):
688 """
688 """
689 User group permissions for the current user.
689 User group permissions for the current user.
690 """
690 """
691 # user group for user group permissions
691 # user group for user group permissions
692 user_group_from_user_group = Permission\
692 user_group_from_user_group = Permission\
693 .get_default_user_group_perms_from_user_group(
693 .get_default_user_group_perms_from_user_group(
694 self.user_id, self.scope_user_group_id)
694 self.user_id, self.scope_user_group_id)
695
695
696 multiple_counter = collections.defaultdict(int)
696 multiple_counter = collections.defaultdict(int)
697 for perm in user_group_from_user_group:
697 for perm in user_group_from_user_group:
698 g_k = perm.UserGroupUserGroupToPerm\
698 g_k = perm.UserGroupUserGroupToPerm\
699 .target_user_group.users_group_name
699 .target_user_group.users_group_name
700 u_k = perm.UserGroupUserGroupToPerm\
700 u_k = perm.UserGroupUserGroupToPerm\
701 .user_group.users_group_name
701 .user_group.users_group_name
702 o = PermOrigin.USERGROUP_USERGROUP % u_k
702 o = PermOrigin.USERGROUP_USERGROUP % u_k
703 multiple_counter[g_k] += 1
703 multiple_counter[g_k] += 1
704 p = perm.Permission.permission_name
704 p = perm.Permission.permission_name
705
705
706 if perm.UserGroup.user_id == self.user_id:
706 if perm.UserGroup.user_id == self.user_id:
707 # set admin if owner, even for member of other user group
707 # set admin if owner, even for member of other user group
708 p = 'usergroup.admin'
708 p = 'usergroup.admin'
709 o = PermOrigin.USERGROUP_OWNER
709 o = PermOrigin.USERGROUP_OWNER
710 else:
710 else:
711 if multiple_counter[g_k] > 1:
711 if multiple_counter[g_k] > 1:
712 cur_perm = self.permissions_user_groups[g_k]
712 cur_perm = self.permissions_user_groups[g_k]
713 p = self._choose_permission(p, cur_perm)
713 p = self._choose_permission(p, cur_perm)
714 self.permissions_user_groups[g_k] = p, o
714 self.permissions_user_groups[g_k] = p, o
715
715
716 # user explicit permission for user groups
716 # user explicit permission for user groups
717 user_user_groups_perms = Permission.get_default_user_group_perms(
717 user_user_groups_perms = Permission.get_default_user_group_perms(
718 self.user_id, self.scope_user_group_id)
718 self.user_id, self.scope_user_group_id)
719 for perm in user_user_groups_perms:
719 for perm in user_user_groups_perms:
720 ug_k = perm.UserUserGroupToPerm.user_group.users_group_name
720 ug_k = perm.UserUserGroupToPerm.user_group.users_group_name
721 u_k = perm.UserUserGroupToPerm.user.username
721 u_k = perm.UserUserGroupToPerm.user.username
722 o = PermOrigin.USERGROUP_USER % u_k
722 o = PermOrigin.USERGROUP_USER % u_k
723
723
724 if perm.UserGroup.user_id == self.user_id:
724 if perm.UserGroup.user_id == self.user_id:
725 # set admin if owner
725 # set admin if owner
726 p = 'usergroup.admin'
726 p = 'usergroup.admin'
727 o = PermOrigin.USERGROUP_OWNER
727 o = PermOrigin.USERGROUP_OWNER
728 else:
728 else:
729 p = perm.Permission.permission_name
729 p = perm.Permission.permission_name
730 if not self.explicit:
730 if not self.explicit:
731 cur_perm = self.permissions_user_groups.get(
731 cur_perm = self.permissions_user_groups.get(
732 ug_k, 'usergroup.none')
732 ug_k, 'usergroup.none')
733 p = self._choose_permission(p, cur_perm)
733 p = self._choose_permission(p, cur_perm)
734 self.permissions_user_groups[ug_k] = p, o
734 self.permissions_user_groups[ug_k] = p, o
735
735
736 def _choose_permission(self, new_perm, cur_perm):
736 def _choose_permission(self, new_perm, cur_perm):
737 new_perm_val = Permission.PERM_WEIGHTS[new_perm]
737 new_perm_val = Permission.PERM_WEIGHTS[new_perm]
738 cur_perm_val = Permission.PERM_WEIGHTS[cur_perm]
738 cur_perm_val = Permission.PERM_WEIGHTS[cur_perm]
739 if self.algo == 'higherwin':
739 if self.algo == 'higherwin':
740 if new_perm_val > cur_perm_val:
740 if new_perm_val > cur_perm_val:
741 return new_perm
741 return new_perm
742 return cur_perm
742 return cur_perm
743 elif self.algo == 'lowerwin':
743 elif self.algo == 'lowerwin':
744 if new_perm_val < cur_perm_val:
744 if new_perm_val < cur_perm_val:
745 return new_perm
745 return new_perm
746 return cur_perm
746 return cur_perm
747
747
748 def _permission_structure(self):
748 def _permission_structure(self):
749 return {
749 return {
750 'global': self.permissions_global,
750 'global': self.permissions_global,
751 'repositories': self.permissions_repositories,
751 'repositories': self.permissions_repositories,
752 'repositories_groups': self.permissions_repository_groups,
752 'repositories_groups': self.permissions_repository_groups,
753 'user_groups': self.permissions_user_groups,
753 'user_groups': self.permissions_user_groups,
754 }
754 }
755
755
756
756
757 def allowed_auth_token_access(view_name, auth_token, whitelist=None):
757 def allowed_auth_token_access(view_name, auth_token, whitelist=None):
758 """
758 """
759 Check if given controller_name is in whitelist of auth token access
759 Check if given controller_name is in whitelist of auth token access
760 """
760 """
761 if not whitelist:
761 if not whitelist:
762 from rhodecode import CONFIG
762 from rhodecode import CONFIG
763 whitelist = aslist(
763 whitelist = aslist(
764 CONFIG.get('api_access_controllers_whitelist'), sep=',')
764 CONFIG.get('api_access_controllers_whitelist'), sep=',')
765 # backward compat translation
765 # backward compat translation
766 compat = {
766 compat = {
767 # old controller, new VIEW
767 # old controller, new VIEW
768 'ChangesetController:*': 'RepoCommitsView:*',
768 'ChangesetController:*': 'RepoCommitsView:*',
769 'ChangesetController:changeset_patch': 'RepoCommitsView:repo_commit_patch',
769 'ChangesetController:changeset_patch': 'RepoCommitsView:repo_commit_patch',
770 'ChangesetController:changeset_raw': 'RepoCommitsView:repo_commit_raw',
770 'ChangesetController:changeset_raw': 'RepoCommitsView:repo_commit_raw',
771 'FilesController:raw': 'RepoCommitsView:repo_commit_raw',
771 'FilesController:raw': 'RepoCommitsView:repo_commit_raw',
772 'FilesController:archivefile': 'RepoFilesView:repo_archivefile',
772 'FilesController:archivefile': 'RepoFilesView:repo_archivefile',
773 'GistsController:*': 'GistView:*',
773 'GistsController:*': 'GistView:*',
774 }
774 }
775
775
776 log.debug(
776 log.debug(
777 'Allowed views for AUTH TOKEN access: %s' % (whitelist,))
777 'Allowed views for AUTH TOKEN access: %s' % (whitelist,))
778 auth_token_access_valid = False
778 auth_token_access_valid = False
779
779
780 for entry in whitelist:
780 for entry in whitelist:
781 token_match = True
781 token_match = True
782 if entry in compat:
782 if entry in compat:
783 # translate from old Controllers to Pyramid Views
783 # translate from old Controllers to Pyramid Views
784 entry = compat[entry]
784 entry = compat[entry]
785
785
786 if '@' in entry:
786 if '@' in entry:
787 # specific AuthToken
787 # specific AuthToken
788 entry, allowed_token = entry.split('@', 1)
788 entry, allowed_token = entry.split('@', 1)
789 token_match = auth_token == allowed_token
789 token_match = auth_token == allowed_token
790
790
791 if fnmatch.fnmatch(view_name, entry) and token_match:
791 if fnmatch.fnmatch(view_name, entry) and token_match:
792 auth_token_access_valid = True
792 auth_token_access_valid = True
793 break
793 break
794
794
795 if auth_token_access_valid:
795 if auth_token_access_valid:
796 log.debug('view: `%s` matches entry in whitelist: %s'
796 log.debug('view: `%s` matches entry in whitelist: %s'
797 % (view_name, whitelist))
797 % (view_name, whitelist))
798 else:
798 else:
799 msg = ('view: `%s` does *NOT* match any entry in whitelist: %s'
799 msg = ('view: `%s` does *NOT* match any entry in whitelist: %s'
800 % (view_name, whitelist))
800 % (view_name, whitelist))
801 if auth_token:
801 if auth_token:
802 # if we use auth token key and don't have access it's a warning
802 # if we use auth token key and don't have access it's a warning
803 log.warning(msg)
803 log.warning(msg)
804 else:
804 else:
805 log.debug(msg)
805 log.debug(msg)
806
806
807 return auth_token_access_valid
807 return auth_token_access_valid
808
808
809
809
810 class AuthUser(object):
810 class AuthUser(object):
811 """
811 """
812 A simple object that handles all attributes of user in RhodeCode
812 A simple object that handles all attributes of user in RhodeCode
813
813
814 It does lookup based on API key,given user, or user present in session
814 It does lookup based on API key,given user, or user present in session
815 Then it fills all required information for such user. It also checks if
815 Then it fills all required information for such user. It also checks if
816 anonymous access is enabled and if so, it returns default user as logged in
816 anonymous access is enabled and if so, it returns default user as logged in
817 """
817 """
818 GLOBAL_PERMS = [x[0] for x in Permission.PERMS]
818 GLOBAL_PERMS = [x[0] for x in Permission.PERMS]
819
819
820 def __init__(self, user_id=None, api_key=None, username=None, ip_addr=None):
820 def __init__(self, user_id=None, api_key=None, username=None, ip_addr=None):
821
821
822 self.user_id = user_id
822 self.user_id = user_id
823 self._api_key = api_key
823 self._api_key = api_key
824
824
825 self.api_key = None
825 self.api_key = None
826 self.feed_token = ''
826 self.feed_token = ''
827 self.username = username
827 self.username = username
828 self.ip_addr = ip_addr
828 self.ip_addr = ip_addr
829 self.name = ''
829 self.name = ''
830 self.lastname = ''
830 self.lastname = ''
831 self.first_name = ''
831 self.first_name = ''
832 self.last_name = ''
832 self.last_name = ''
833 self.email = ''
833 self.email = ''
834 self.is_authenticated = False
834 self.is_authenticated = False
835 self.admin = False
835 self.admin = False
836 self.inherit_default_permissions = False
836 self.inherit_default_permissions = False
837 self.password = ''
837 self.password = ''
838
838
839 self.anonymous_user = None # propagated on propagate_data
839 self.anonymous_user = None # propagated on propagate_data
840 self.propagate_data()
840 self.propagate_data()
841 self._instance = None
841 self._instance = None
842 self._permissions_scoped_cache = {} # used to bind scoped calculation
842 self._permissions_scoped_cache = {} # used to bind scoped calculation
843
843
844 @LazyProperty
844 @LazyProperty
845 def permissions(self):
845 def permissions(self):
846 return self.get_perms(user=self, cache=False)
846 return self.get_perms(user=self, cache=False)
847
847
848 def permissions_with_scope(self, scope):
848 def permissions_with_scope(self, scope):
849 """
849 """
850 Call the get_perms function with scoped data. The scope in that function
850 Call the get_perms function with scoped data. The scope in that function
851 narrows the SQL calls to the given ID of objects resulting in fetching
851 narrows the SQL calls to the given ID of objects resulting in fetching
852 Just particular permission we want to obtain. If scope is an empty dict
852 Just particular permission we want to obtain. If scope is an empty dict
853 then it basically narrows the scope to GLOBAL permissions only.
853 then it basically narrows the scope to GLOBAL permissions only.
854
854
855 :param scope: dict
855 :param scope: dict
856 """
856 """
857 if 'repo_name' in scope:
857 if 'repo_name' in scope:
858 obj = Repository.get_by_repo_name(scope['repo_name'])
858 obj = Repository.get_by_repo_name(scope['repo_name'])
859 if obj:
859 if obj:
860 scope['repo_id'] = obj.repo_id
860 scope['repo_id'] = obj.repo_id
861 _scope = {
861 _scope = {
862 'repo_id': -1,
862 'repo_id': -1,
863 'user_group_id': -1,
863 'user_group_id': -1,
864 'repo_group_id': -1,
864 'repo_group_id': -1,
865 }
865 }
866 _scope.update(scope)
866 _scope.update(scope)
867 cache_key = "_".join(map(safe_str, reduce(lambda a, b: a+b,
867 cache_key = "_".join(map(safe_str, reduce(lambda a, b: a+b,
868 _scope.items())))
868 _scope.items())))
869 if cache_key not in self._permissions_scoped_cache:
869 if cache_key not in self._permissions_scoped_cache:
870 # store in cache to mimic how the @LazyProperty works,
870 # store in cache to mimic how the @LazyProperty works,
871 # the difference here is that we use the unique key calculated
871 # the difference here is that we use the unique key calculated
872 # from params and values
872 # from params and values
873 res = self.get_perms(user=self, cache=False, scope=_scope)
873 res = self.get_perms(user=self, cache=False, scope=_scope)
874 self._permissions_scoped_cache[cache_key] = res
874 self._permissions_scoped_cache[cache_key] = res
875 return self._permissions_scoped_cache[cache_key]
875 return self._permissions_scoped_cache[cache_key]
876
876
877 def get_instance(self):
877 def get_instance(self):
878 return User.get(self.user_id)
878 return User.get(self.user_id)
879
879
880 def update_lastactivity(self):
880 def update_lastactivity(self):
881 if self.user_id:
881 if self.user_id:
882 User.get(self.user_id).update_lastactivity()
882 User.get(self.user_id).update_lastactivity()
883
883
884 def propagate_data(self):
884 def propagate_data(self):
885 """
885 """
886 Fills in user data and propagates values to this instance. Maps fetched
886 Fills in user data and propagates values to this instance. Maps fetched
887 user attributes to this class instance attributes
887 user attributes to this class instance attributes
888 """
888 """
889 log.debug('AuthUser: starting data propagation for new potential user')
889 log.debug('AuthUser: starting data propagation for new potential user')
890 user_model = UserModel()
890 user_model = UserModel()
891 anon_user = self.anonymous_user = User.get_default_user(cache=True)
891 anon_user = self.anonymous_user = User.get_default_user(cache=True)
892 is_user_loaded = False
892 is_user_loaded = False
893
893
894 # lookup by userid
894 # lookup by userid
895 if self.user_id is not None and self.user_id != anon_user.user_id:
895 if self.user_id is not None and self.user_id != anon_user.user_id:
896 log.debug('Trying Auth User lookup by USER ID: `%s`', self.user_id)
896 log.debug('Trying Auth User lookup by USER ID: `%s`', self.user_id)
897 is_user_loaded = user_model.fill_data(self, user_id=self.user_id)
897 is_user_loaded = user_model.fill_data(self, user_id=self.user_id)
898
898
899 # try go get user by api key
899 # try go get user by api key
900 elif self._api_key and self._api_key != anon_user.api_key:
900 elif self._api_key and self._api_key != anon_user.api_key:
901 log.debug('Trying Auth User lookup by API KEY: `%s`', self._api_key)
901 log.debug('Trying Auth User lookup by API KEY: `%s`', self._api_key)
902 is_user_loaded = user_model.fill_data(self, api_key=self._api_key)
902 is_user_loaded = user_model.fill_data(self, api_key=self._api_key)
903
903
904 # lookup by username
904 # lookup by username
905 elif self.username:
905 elif self.username:
906 log.debug('Trying Auth User lookup by USER NAME: `%s`', self.username)
906 log.debug('Trying Auth User lookup by USER NAME: `%s`', self.username)
907 is_user_loaded = user_model.fill_data(self, username=self.username)
907 is_user_loaded = user_model.fill_data(self, username=self.username)
908 else:
908 else:
909 log.debug('No data in %s that could been used to log in', self)
909 log.debug('No data in %s that could been used to log in', self)
910
910
911 if not is_user_loaded:
911 if not is_user_loaded:
912 log.debug('Failed to load user. Fallback to default user')
912 log.debug('Failed to load user. Fallback to default user')
913 # if we cannot authenticate user try anonymous
913 # if we cannot authenticate user try anonymous
914 if anon_user.active:
914 if anon_user.active:
915 user_model.fill_data(self, user_id=anon_user.user_id)
915 user_model.fill_data(self, user_id=anon_user.user_id)
916 # then we set this user is logged in
916 # then we set this user is logged in
917 self.is_authenticated = True
917 self.is_authenticated = True
918 else:
918 else:
919 # in case of disabled anonymous user we reset some of the
919 # in case of disabled anonymous user we reset some of the
920 # parameters so such user is "corrupted", skipping the fill_data
920 # parameters so such user is "corrupted", skipping the fill_data
921 for attr in ['user_id', 'username', 'admin', 'active']:
921 for attr in ['user_id', 'username', 'admin', 'active']:
922 setattr(self, attr, None)
922 setattr(self, attr, None)
923 self.is_authenticated = False
923 self.is_authenticated = False
924
924
925 if not self.username:
925 if not self.username:
926 self.username = 'None'
926 self.username = 'None'
927
927
928 log.debug('AuthUser: propagated user is now %s', self)
928 log.debug('AuthUser: propagated user is now %s', self)
929
929
930 def get_perms(self, user, scope=None, explicit=True, algo='higherwin',
930 def get_perms(self, user, scope=None, explicit=True, algo='higherwin',
931 cache=False):
931 cache=False):
932 """
932 """
933 Fills user permission attribute with permissions taken from database
933 Fills user permission attribute with permissions taken from database
934 works for permissions given for repositories, and for permissions that
934 works for permissions given for repositories, and for permissions that
935 are granted to groups
935 are granted to groups
936
936
937 :param user: instance of User object from database
937 :param user: instance of User object from database
938 :param explicit: In case there are permissions both for user and a group
938 :param explicit: In case there are permissions both for user and a group
939 that user is part of, explicit flag will defiine if user will
939 that user is part of, explicit flag will defiine if user will
940 explicitly override permissions from group, if it's False it will
940 explicitly override permissions from group, if it's False it will
941 make decision based on the algo
941 make decision based on the algo
942 :param algo: algorithm to decide what permission should be choose if
942 :param algo: algorithm to decide what permission should be choose if
943 it's multiple defined, eg user in two different groups. It also
943 it's multiple defined, eg user in two different groups. It also
944 decides if explicit flag is turned off how to specify the permission
944 decides if explicit flag is turned off how to specify the permission
945 for case when user is in a group + have defined separate permission
945 for case when user is in a group + have defined separate permission
946 """
946 """
947 user_id = user.user_id
947 user_id = user.user_id
948 user_is_admin = user.is_admin
948 user_is_admin = user.is_admin
949
949
950 # inheritance of global permissions like create repo/fork repo etc
950 # inheritance of global permissions like create repo/fork repo etc
951 user_inherit_default_permissions = user.inherit_default_permissions
951 user_inherit_default_permissions = user.inherit_default_permissions
952
952
953 log.debug('Computing PERMISSION tree for scope %s' % (scope, ))
953 log.debug('Computing PERMISSION tree for scope %s' % (scope, ))
954 compute = caches.conditional_cache(
954 compute = caches.conditional_cache(
955 'short_term', 'cache_desc',
955 'short_term', 'cache_desc',
956 condition=cache, func=_cached_perms_data)
956 condition=cache, func=_cached_perms_data)
957 result = compute(user_id, scope, user_is_admin,
957 result = compute(user_id, scope, user_is_admin,
958 user_inherit_default_permissions, explicit, algo)
958 user_inherit_default_permissions, explicit, algo)
959
959
960 result_repr = []
960 result_repr = []
961 for k in result:
961 for k in result:
962 result_repr.append((k, len(result[k])))
962 result_repr.append((k, len(result[k])))
963
963
964 log.debug('PERMISSION tree computed %s' % (result_repr,))
964 log.debug('PERMISSION tree computed %s' % (result_repr,))
965 return result
965 return result
966
966
967 @property
967 @property
968 def is_default(self):
968 def is_default(self):
969 return self.username == User.DEFAULT_USER
969 return self.username == User.DEFAULT_USER
970
970
971 @property
971 @property
972 def is_admin(self):
972 def is_admin(self):
973 return self.admin
973 return self.admin
974
974
975 @property
975 @property
976 def is_user_object(self):
976 def is_user_object(self):
977 return self.user_id is not None
977 return self.user_id is not None
978
978
979 @property
979 @property
980 def repositories_admin(self):
980 def repositories_admin(self):
981 """
981 """
982 Returns list of repositories you're an admin of
982 Returns list of repositories you're an admin of
983 """
983 """
984 return [
984 return [
985 x[0] for x in self.permissions['repositories'].iteritems()
985 x[0] for x in self.permissions['repositories'].iteritems()
986 if x[1] == 'repository.admin']
986 if x[1] == 'repository.admin']
987
987
988 @property
988 @property
989 def repository_groups_admin(self):
989 def repository_groups_admin(self):
990 """
990 """
991 Returns list of repository groups you're an admin of
991 Returns list of repository groups you're an admin of
992 """
992 """
993 return [
993 return [
994 x[0] for x in self.permissions['repositories_groups'].iteritems()
994 x[0] for x in self.permissions['repositories_groups'].iteritems()
995 if x[1] == 'group.admin']
995 if x[1] == 'group.admin']
996
996
997 @property
997 @property
998 def user_groups_admin(self):
998 def user_groups_admin(self):
999 """
999 """
1000 Returns list of user groups you're an admin of
1000 Returns list of user groups you're an admin of
1001 """
1001 """
1002 return [
1002 return [
1003 x[0] for x in self.permissions['user_groups'].iteritems()
1003 x[0] for x in self.permissions['user_groups'].iteritems()
1004 if x[1] == 'usergroup.admin']
1004 if x[1] == 'usergroup.admin']
1005
1005
1006 @property
1006 @property
1007 def ip_allowed(self):
1007 def ip_allowed(self):
1008 """
1008 """
1009 Checks if ip_addr used in constructor is allowed from defined list of
1009 Checks if ip_addr used in constructor is allowed from defined list of
1010 allowed ip_addresses for user
1010 allowed ip_addresses for user
1011
1011
1012 :returns: boolean, True if ip is in allowed ip range
1012 :returns: boolean, True if ip is in allowed ip range
1013 """
1013 """
1014 # check IP
1014 # check IP
1015 inherit = self.inherit_default_permissions
1015 inherit = self.inherit_default_permissions
1016 return AuthUser.check_ip_allowed(self.user_id, self.ip_addr,
1016 return AuthUser.check_ip_allowed(self.user_id, self.ip_addr,
1017 inherit_from_default=inherit)
1017 inherit_from_default=inherit)
1018 @property
1018 @property
1019 def personal_repo_group(self):
1019 def personal_repo_group(self):
1020 return RepoGroup.get_user_personal_repo_group(self.user_id)
1020 return RepoGroup.get_user_personal_repo_group(self.user_id)
1021
1021
1022 @classmethod
1022 @classmethod
1023 def check_ip_allowed(cls, user_id, ip_addr, inherit_from_default):
1023 def check_ip_allowed(cls, user_id, ip_addr, inherit_from_default):
1024 allowed_ips = AuthUser.get_allowed_ips(
1024 allowed_ips = AuthUser.get_allowed_ips(
1025 user_id, cache=True, inherit_from_default=inherit_from_default)
1025 user_id, cache=True, inherit_from_default=inherit_from_default)
1026 if check_ip_access(source_ip=ip_addr, allowed_ips=allowed_ips):
1026 if check_ip_access(source_ip=ip_addr, allowed_ips=allowed_ips):
1027 log.debug('IP:%s is in range of %s' % (ip_addr, allowed_ips))
1027 log.debug('IP:%s is in range of %s' % (ip_addr, allowed_ips))
1028 return True
1028 return True
1029 else:
1029 else:
1030 log.info('Access for IP:%s forbidden, '
1030 log.info('Access for IP:%s forbidden, '
1031 'not in %s' % (ip_addr, allowed_ips))
1031 'not in %s' % (ip_addr, allowed_ips))
1032 return False
1032 return False
1033
1033
1034 def __repr__(self):
1034 def __repr__(self):
1035 return "<AuthUser('id:%s[%s] ip:%s auth:%s')>"\
1035 return "<AuthUser('id:%s[%s] ip:%s auth:%s')>"\
1036 % (self.user_id, self.username, self.ip_addr, self.is_authenticated)
1036 % (self.user_id, self.username, self.ip_addr, self.is_authenticated)
1037
1037
1038 def set_authenticated(self, authenticated=True):
1038 def set_authenticated(self, authenticated=True):
1039 if self.user_id != self.anonymous_user.user_id:
1039 if self.user_id != self.anonymous_user.user_id:
1040 self.is_authenticated = authenticated
1040 self.is_authenticated = authenticated
1041
1041
1042 def get_cookie_store(self):
1042 def get_cookie_store(self):
1043 return {
1043 return {
1044 'username': self.username,
1044 'username': self.username,
1045 'password': md5(self.password),
1045 'password': md5(self.password),
1046 'user_id': self.user_id,
1046 'user_id': self.user_id,
1047 'is_authenticated': self.is_authenticated
1047 'is_authenticated': self.is_authenticated
1048 }
1048 }
1049
1049
1050 @classmethod
1050 @classmethod
1051 def from_cookie_store(cls, cookie_store):
1051 def from_cookie_store(cls, cookie_store):
1052 """
1052 """
1053 Creates AuthUser from a cookie store
1053 Creates AuthUser from a cookie store
1054
1054
1055 :param cls:
1055 :param cls:
1056 :param cookie_store:
1056 :param cookie_store:
1057 """
1057 """
1058 user_id = cookie_store.get('user_id')
1058 user_id = cookie_store.get('user_id')
1059 username = cookie_store.get('username')
1059 username = cookie_store.get('username')
1060 api_key = cookie_store.get('api_key')
1060 api_key = cookie_store.get('api_key')
1061 return AuthUser(user_id, api_key, username)
1061 return AuthUser(user_id, api_key, username)
1062
1062
1063 @classmethod
1063 @classmethod
1064 def get_allowed_ips(cls, user_id, cache=False, inherit_from_default=False):
1064 def get_allowed_ips(cls, user_id, cache=False, inherit_from_default=False):
1065 _set = set()
1065 _set = set()
1066
1066
1067 if inherit_from_default:
1067 if inherit_from_default:
1068 default_ips = UserIpMap.query().filter(
1068 default_ips = UserIpMap.query().filter(
1069 UserIpMap.user == User.get_default_user(cache=True))
1069 UserIpMap.user == User.get_default_user(cache=True))
1070 if cache:
1070 if cache:
1071 default_ips = default_ips.options(
1071 default_ips = default_ips.options(
1072 FromCache("sql_cache_short", "get_user_ips_default"))
1072 FromCache("sql_cache_short", "get_user_ips_default"))
1073
1073
1074 # populate from default user
1074 # populate from default user
1075 for ip in default_ips:
1075 for ip in default_ips:
1076 try:
1076 try:
1077 _set.add(ip.ip_addr)
1077 _set.add(ip.ip_addr)
1078 except ObjectDeletedError:
1078 except ObjectDeletedError:
1079 # since we use heavy caching sometimes it happens that
1079 # since we use heavy caching sometimes it happens that
1080 # we get deleted objects here, we just skip them
1080 # we get deleted objects here, we just skip them
1081 pass
1081 pass
1082
1082
1083 user_ips = UserIpMap.query().filter(UserIpMap.user_id == user_id)
1083 user_ips = UserIpMap.query().filter(UserIpMap.user_id == user_id)
1084 if cache:
1084 if cache:
1085 user_ips = user_ips.options(
1085 user_ips = user_ips.options(
1086 FromCache("sql_cache_short", "get_user_ips_%s" % user_id))
1086 FromCache("sql_cache_short", "get_user_ips_%s" % user_id))
1087
1087
1088 for ip in user_ips:
1088 for ip in user_ips:
1089 try:
1089 try:
1090 _set.add(ip.ip_addr)
1090 _set.add(ip.ip_addr)
1091 except ObjectDeletedError:
1091 except ObjectDeletedError:
1092 # since we use heavy caching sometimes it happens that we get
1092 # since we use heavy caching sometimes it happens that we get
1093 # deleted objects here, we just skip them
1093 # deleted objects here, we just skip them
1094 pass
1094 pass
1095 return _set or set(['0.0.0.0/0', '::/0'])
1095 return _set or set(['0.0.0.0/0', '::/0'])
1096
1096
1097
1097
1098 def set_available_permissions(config):
1098 def set_available_permissions(config):
1099 """
1099 """
1100 This function will propagate pylons globals with all available defined
1100 This function will propagate pylons globals with all available defined
1101 permission given in db. We don't want to check each time from db for new
1101 permission given in db. We don't want to check each time from db for new
1102 permissions since adding a new permission also requires application restart
1102 permissions since adding a new permission also requires application restart
1103 ie. to decorate new views with the newly created permission
1103 ie. to decorate new views with the newly created permission
1104
1104
1105 :param config: current pylons config instance
1105 :param config: current pylons config instance
1106
1106
1107 """
1107 """
1108 log.info('getting information about all available permissions')
1108 log.info('getting information about all available permissions')
1109 try:
1109 try:
1110 sa = meta.Session
1110 sa = meta.Session
1111 all_perms = sa.query(Permission).all()
1111 all_perms = sa.query(Permission).all()
1112 config['available_permissions'] = [x.permission_name for x in all_perms]
1112 config['available_permissions'] = [x.permission_name for x in all_perms]
1113 except Exception:
1113 except Exception:
1114 log.error(traceback.format_exc())
1114 log.error(traceback.format_exc())
1115 finally:
1115 finally:
1116 meta.Session.remove()
1116 meta.Session.remove()
1117
1117
1118
1118
1119 def get_csrf_token(session=None, force_new=False, save_if_missing=True):
1119 def get_csrf_token(session=None, force_new=False, save_if_missing=True):
1120 """
1120 """
1121 Return the current authentication token, creating one if one doesn't
1121 Return the current authentication token, creating one if one doesn't
1122 already exist and the save_if_missing flag is present.
1122 already exist and the save_if_missing flag is present.
1123
1123
1124 :param session: pass in the pylons session, else we use the global ones
1124 :param session: pass in the pylons session, else we use the global ones
1125 :param force_new: force to re-generate the token and store it in session
1125 :param force_new: force to re-generate the token and store it in session
1126 :param save_if_missing: save the newly generated token if it's missing in
1126 :param save_if_missing: save the newly generated token if it's missing in
1127 session
1127 session
1128 """
1128 """
1129 # NOTE(marcink): probably should be replaced with below one from pyramid 1.9
1129 # NOTE(marcink): probably should be replaced with below one from pyramid 1.9
1130 # from pyramid.csrf import get_csrf_token
1130 # from pyramid.csrf import get_csrf_token
1131
1131
1132 if not session:
1132 if not session:
1133 from pylons import session
1133 from pylons import session
1134
1134
1135 if (csrf_token_key not in session and save_if_missing) or force_new:
1135 if (csrf_token_key not in session and save_if_missing) or force_new:
1136 token = hashlib.sha1(str(random.getrandbits(128))).hexdigest()
1136 token = hashlib.sha1(str(random.getrandbits(128))).hexdigest()
1137 session[csrf_token_key] = token
1137 session[csrf_token_key] = token
1138 if hasattr(session, 'save'):
1138 if hasattr(session, 'save'):
1139 session.save()
1139 session.save()
1140 return session.get(csrf_token_key)
1140 return session.get(csrf_token_key)
1141
1141
1142
1142
1143 def get_request(perm_class):
1143 def get_request(perm_class):
1144 from pyramid.threadlocal import get_current_request
1144 from pyramid.threadlocal import get_current_request
1145 pyramid_request = get_current_request()
1145 pyramid_request = get_current_request()
1146 if not pyramid_request:
1146 if not pyramid_request:
1147 # return global request of pylons in case pyramid isn't available
1147 # return global request of pylons in case pyramid isn't available
1148 # NOTE(marcink): this should be removed after migration to pyramid
1148 # NOTE(marcink): this should be removed after migration to pyramid
1149 from pylons import request
1149 from pylons import request
1150 return request
1150 return request
1151 return pyramid_request
1151 return pyramid_request
1152
1152
1153
1153
1154 # CHECK DECORATORS
1154 # CHECK DECORATORS
1155 class CSRFRequired(object):
1155 class CSRFRequired(object):
1156 """
1156 """
1157 Decorator for authenticating a form
1157 Decorator for authenticating a form
1158
1158
1159 This decorator uses an authorization token stored in the client's
1159 This decorator uses an authorization token stored in the client's
1160 session for prevention of certain Cross-site request forgery (CSRF)
1160 session for prevention of certain Cross-site request forgery (CSRF)
1161 attacks (See
1161 attacks (See
1162 http://en.wikipedia.org/wiki/Cross-site_request_forgery for more
1162 http://en.wikipedia.org/wiki/Cross-site_request_forgery for more
1163 information).
1163 information).
1164
1164
1165 For use with the ``webhelpers.secure_form`` helper functions.
1165 For use with the ``webhelpers.secure_form`` helper functions.
1166
1166
1167 """
1167 """
1168 def __init__(self, token=csrf_token_key, header='X-CSRF-Token',
1168 def __init__(self, token=csrf_token_key, header='X-CSRF-Token',
1169 except_methods=None):
1169 except_methods=None):
1170 self.token = token
1170 self.token = token
1171 self.header = header
1171 self.header = header
1172 self.except_methods = except_methods or []
1172 self.except_methods = except_methods or []
1173
1173
1174 def __call__(self, func):
1174 def __call__(self, func):
1175 return get_cython_compat_decorator(self.__wrapper, func)
1175 return get_cython_compat_decorator(self.__wrapper, func)
1176
1176
1177 def _get_csrf(self, _request):
1177 def _get_csrf(self, _request):
1178 return _request.POST.get(self.token, _request.headers.get(self.header))
1178 return _request.POST.get(self.token, _request.headers.get(self.header))
1179
1179
1180 def check_csrf(self, _request, cur_token):
1180 def check_csrf(self, _request, cur_token):
1181 supplied_token = self._get_csrf(_request)
1181 supplied_token = self._get_csrf(_request)
1182 return supplied_token and supplied_token == cur_token
1182 return supplied_token and supplied_token == cur_token
1183
1183
1184 def _get_request(self):
1184 def _get_request(self):
1185 return get_request(self)
1185 return get_request(self)
1186
1186
1187 def __wrapper(self, func, *fargs, **fkwargs):
1187 def __wrapper(self, func, *fargs, **fkwargs):
1188 request = self._get_request()
1188 request = self._get_request()
1189
1189
1190 if request.method in self.except_methods:
1190 if request.method in self.except_methods:
1191 return func(*fargs, **fkwargs)
1191 return func(*fargs, **fkwargs)
1192
1192
1193 cur_token = get_csrf_token(save_if_missing=False)
1193 cur_token = get_csrf_token(save_if_missing=False)
1194 if self.check_csrf(request, cur_token):
1194 if self.check_csrf(request, cur_token):
1195 if request.POST.get(self.token):
1195 if request.POST.get(self.token):
1196 del request.POST[self.token]
1196 del request.POST[self.token]
1197 return func(*fargs, **fkwargs)
1197 return func(*fargs, **fkwargs)
1198 else:
1198 else:
1199 reason = 'token-missing'
1199 reason = 'token-missing'
1200 supplied_token = self._get_csrf(request)
1200 supplied_token = self._get_csrf(request)
1201 if supplied_token and cur_token != supplied_token:
1201 if supplied_token and cur_token != supplied_token:
1202 reason = 'token-mismatch [%s:%s]' % (
1202 reason = 'token-mismatch [%s:%s]' % (
1203 cur_token or ''[:6], supplied_token or ''[:6])
1203 cur_token or ''[:6], supplied_token or ''[:6])
1204
1204
1205 csrf_message = \
1205 csrf_message = \
1206 ("Cross-site request forgery detected, request denied. See "
1206 ("Cross-site request forgery detected, request denied. See "
1207 "http://en.wikipedia.org/wiki/Cross-site_request_forgery for "
1207 "http://en.wikipedia.org/wiki/Cross-site_request_forgery for "
1208 "more information.")
1208 "more information.")
1209 log.warn('Cross-site request forgery detected, request %r DENIED: %s '
1209 log.warn('Cross-site request forgery detected, request %r DENIED: %s '
1210 'REMOTE_ADDR:%s, HEADERS:%s' % (
1210 'REMOTE_ADDR:%s, HEADERS:%s' % (
1211 request, reason, request.remote_addr, request.headers))
1211 request, reason, request.remote_addr, request.headers))
1212
1212
1213 raise HTTPForbidden(explanation=csrf_message)
1213 raise HTTPForbidden(explanation=csrf_message)
1214
1214
1215
1215
1216 class LoginRequired(object):
1216 class LoginRequired(object):
1217 """
1217 """
1218 Must be logged in to execute this function else
1218 Must be logged in to execute this function else
1219 redirect to login page
1219 redirect to login page
1220
1220
1221 :param api_access: if enabled this checks only for valid auth token
1221 :param api_access: if enabled this checks only for valid auth token
1222 and grants access based on valid token
1222 and grants access based on valid token
1223 """
1223 """
1224 def __init__(self, auth_token_access=None):
1224 def __init__(self, auth_token_access=None):
1225 self.auth_token_access = auth_token_access
1225 self.auth_token_access = auth_token_access
1226
1226
1227 def __call__(self, func):
1227 def __call__(self, func):
1228 return get_cython_compat_decorator(self.__wrapper, func)
1228 return get_cython_compat_decorator(self.__wrapper, func)
1229
1229
1230 def _get_request(self):
1230 def _get_request(self):
1231 return get_request(self)
1231 return get_request(self)
1232
1232
1233 def __wrapper(self, func, *fargs, **fkwargs):
1233 def __wrapper(self, func, *fargs, **fkwargs):
1234 from rhodecode.lib import helpers as h
1234 from rhodecode.lib import helpers as h
1235 cls = fargs[0]
1235 cls = fargs[0]
1236 user = cls._rhodecode_user
1236 user = cls._rhodecode_user
1237 request = self._get_request()
1237 request = self._get_request()
1238
1238
1239 loc = "%s:%s" % (cls.__class__.__name__, func.__name__)
1239 loc = "%s:%s" % (cls.__class__.__name__, func.__name__)
1240 log.debug('Starting login restriction checks for user: %s' % (user,))
1240 log.debug('Starting login restriction checks for user: %s' % (user,))
1241 # check if our IP is allowed
1241 # check if our IP is allowed
1242 ip_access_valid = True
1242 ip_access_valid = True
1243 if not user.ip_allowed:
1243 if not user.ip_allowed:
1244 h.flash(h.literal(_('IP %s not allowed' % (user.ip_addr,))),
1244 h.flash(h.literal(_('IP %s not allowed' % (user.ip_addr,))),
1245 category='warning')
1245 category='warning')
1246 ip_access_valid = False
1246 ip_access_valid = False
1247
1247
1248 # check if we used an APIKEY and it's a valid one
1248 # check if we used an APIKEY and it's a valid one
1249 # defined white-list of controllers which API access will be enabled
1249 # defined white-list of controllers which API access will be enabled
1250 _auth_token = request.GET.get(
1250 _auth_token = request.GET.get(
1251 'auth_token', '') or request.GET.get('api_key', '')
1251 'auth_token', '') or request.GET.get('api_key', '')
1252 auth_token_access_valid = allowed_auth_token_access(
1252 auth_token_access_valid = allowed_auth_token_access(
1253 loc, auth_token=_auth_token)
1253 loc, auth_token=_auth_token)
1254
1254
1255 # explicit controller is enabled or API is in our whitelist
1255 # explicit controller is enabled or API is in our whitelist
1256 if self.auth_token_access or auth_token_access_valid:
1256 if self.auth_token_access or auth_token_access_valid:
1257 log.debug('Checking AUTH TOKEN access for %s' % (cls,))
1257 log.debug('Checking AUTH TOKEN access for %s' % (cls,))
1258 db_user = user.get_instance()
1258 db_user = user.get_instance()
1259
1259
1260 if db_user:
1260 if db_user:
1261 if self.auth_token_access:
1261 if self.auth_token_access:
1262 roles = self.auth_token_access
1262 roles = self.auth_token_access
1263 else:
1263 else:
1264 roles = [UserApiKeys.ROLE_HTTP]
1264 roles = [UserApiKeys.ROLE_HTTP]
1265 token_match = db_user.authenticate_by_token(
1265 token_match = db_user.authenticate_by_token(
1266 _auth_token, roles=roles)
1266 _auth_token, roles=roles)
1267 else:
1267 else:
1268 log.debug('Unable to fetch db instance for auth user: %s', user)
1268 log.debug('Unable to fetch db instance for auth user: %s', user)
1269 token_match = False
1269 token_match = False
1270
1270
1271 if _auth_token and token_match:
1271 if _auth_token and token_match:
1272 auth_token_access_valid = True
1272 auth_token_access_valid = True
1273 log.debug('AUTH TOKEN ****%s is VALID' % (_auth_token[-4:],))
1273 log.debug('AUTH TOKEN ****%s is VALID' % (_auth_token[-4:],))
1274 else:
1274 else:
1275 auth_token_access_valid = False
1275 auth_token_access_valid = False
1276 if not _auth_token:
1276 if not _auth_token:
1277 log.debug("AUTH TOKEN *NOT* present in request")
1277 log.debug("AUTH TOKEN *NOT* present in request")
1278 else:
1278 else:
1279 log.warning(
1279 log.warning(
1280 "AUTH TOKEN ****%s *NOT* valid" % _auth_token[-4:])
1280 "AUTH TOKEN ****%s *NOT* valid" % _auth_token[-4:])
1281
1281
1282 log.debug('Checking if %s is authenticated @ %s' % (user.username, loc))
1282 log.debug('Checking if %s is authenticated @ %s' % (user.username, loc))
1283 reason = 'RHODECODE_AUTH' if user.is_authenticated \
1283 reason = 'RHODECODE_AUTH' if user.is_authenticated \
1284 else 'AUTH_TOKEN_AUTH'
1284 else 'AUTH_TOKEN_AUTH'
1285
1285
1286 if ip_access_valid and (
1286 if ip_access_valid and (
1287 user.is_authenticated or auth_token_access_valid):
1287 user.is_authenticated or auth_token_access_valid):
1288 log.info(
1288 log.info(
1289 'user %s authenticating with:%s IS authenticated on func %s'
1289 'user %s authenticating with:%s IS authenticated on func %s'
1290 % (user, reason, loc))
1290 % (user, reason, loc))
1291
1291
1292 # update user data to check last activity
1292 # update user data to check last activity
1293 user.update_lastactivity()
1293 user.update_lastactivity()
1294 Session().commit()
1294 Session().commit()
1295 return func(*fargs, **fkwargs)
1295 return func(*fargs, **fkwargs)
1296 else:
1296 else:
1297 log.warning(
1297 log.warning(
1298 'user %s authenticating with:%s NOT authenticated on '
1298 'user %s authenticating with:%s NOT authenticated on '
1299 'func: %s: IP_ACCESS:%s AUTH_TOKEN_ACCESS:%s'
1299 'func: %s: IP_ACCESS:%s AUTH_TOKEN_ACCESS:%s'
1300 % (user, reason, loc, ip_access_valid,
1300 % (user, reason, loc, ip_access_valid,
1301 auth_token_access_valid))
1301 auth_token_access_valid))
1302 # we preserve the get PARAM
1302 # we preserve the get PARAM
1303 came_from = request.path_qs
1303 came_from = request.path_qs
1304 log.debug('redirecting to login page with %s' % (came_from,))
1304 log.debug('redirecting to login page with %s' % (came_from,))
1305 raise HTTPFound(
1305 raise HTTPFound(
1306 h.route_path('login', _query={'came_from': came_from}))
1306 h.route_path('login', _query={'came_from': came_from}))
1307
1307
1308
1308
1309 class NotAnonymous(object):
1309 class NotAnonymous(object):
1310 """
1310 """
1311 Must be logged in to execute this function else
1311 Must be logged in to execute this function else
1312 redirect to login page
1312 redirect to login page
1313 """
1313 """
1314
1314
1315 def __call__(self, func):
1315 def __call__(self, func):
1316 return get_cython_compat_decorator(self.__wrapper, func)
1316 return get_cython_compat_decorator(self.__wrapper, func)
1317
1317
1318 def _get_request(self):
1318 def _get_request(self):
1319 return get_request(self)
1319 return get_request(self)
1320
1320
1321 def __wrapper(self, func, *fargs, **fkwargs):
1321 def __wrapper(self, func, *fargs, **fkwargs):
1322 import rhodecode.lib.helpers as h
1322 import rhodecode.lib.helpers as h
1323 cls = fargs[0]
1323 cls = fargs[0]
1324 self.user = cls._rhodecode_user
1324 self.user = cls._rhodecode_user
1325 request = self._get_request()
1325 request = self._get_request()
1326
1326
1327 log.debug('Checking if user is not anonymous @%s' % cls)
1327 log.debug('Checking if user is not anonymous @%s' % cls)
1328
1328
1329 anonymous = self.user.username == User.DEFAULT_USER
1329 anonymous = self.user.username == User.DEFAULT_USER
1330
1330
1331 if anonymous:
1331 if anonymous:
1332 came_from = request.path_qs
1332 came_from = request.path_qs
1333 h.flash(_('You need to be a registered user to '
1333 h.flash(_('You need to be a registered user to '
1334 'perform this action'),
1334 'perform this action'),
1335 category='warning')
1335 category='warning')
1336 raise HTTPFound(
1336 raise HTTPFound(
1337 h.route_path('login', _query={'came_from': came_from}))
1337 h.route_path('login', _query={'came_from': came_from}))
1338 else:
1338 else:
1339 return func(*fargs, **fkwargs)
1339 return func(*fargs, **fkwargs)
1340
1340
1341
1341
1342 class XHRRequired(object):
1343 # TODO(marcink): remove this in favor of the predicates in pyramid routes
1344
1345 def __call__(self, func):
1346 return get_cython_compat_decorator(self.__wrapper, func)
1347
1348 def _get_request(self):
1349 return get_request(self)
1350
1351 def __wrapper(self, func, *fargs, **fkwargs):
1352 from pylons.controllers.util import abort
1353 request = self._get_request()
1354
1355 log.debug('Checking if request is XMLHttpRequest (XHR)')
1356 xhr_message = 'This is not a valid XMLHttpRequest (XHR) request'
1357
1358 if not request.is_xhr:
1359 abort(400, detail=xhr_message)
1360
1361 return func(*fargs, **fkwargs)
1362
1363
1364 class PermsDecorator(object):
1342 class PermsDecorator(object):
1365 """
1343 """
1366 Base class for controller decorators, we extract the current user from
1344 Base class for controller decorators, we extract the current user from
1367 the class itself, which has it stored in base controllers
1345 the class itself, which has it stored in base controllers
1368 """
1346 """
1369
1347
1370 def __init__(self, *required_perms):
1348 def __init__(self, *required_perms):
1371 self.required_perms = set(required_perms)
1349 self.required_perms = set(required_perms)
1372
1350
1373 def __call__(self, func):
1351 def __call__(self, func):
1374 return get_cython_compat_decorator(self.__wrapper, func)
1352 return get_cython_compat_decorator(self.__wrapper, func)
1375
1353
1376 def _get_request(self):
1354 def _get_request(self):
1377 return get_request(self)
1355 return get_request(self)
1378
1356
1379 def _get_came_from(self):
1357 def _get_came_from(self):
1380 _request = self._get_request()
1358 _request = self._get_request()
1381
1359
1382 # both pylons/pyramid has this attribute
1360 # both pylons/pyramid has this attribute
1383 return _request.path_qs
1361 return _request.path_qs
1384
1362
1385 def __wrapper(self, func, *fargs, **fkwargs):
1363 def __wrapper(self, func, *fargs, **fkwargs):
1386 import rhodecode.lib.helpers as h
1364 import rhodecode.lib.helpers as h
1387 cls = fargs[0]
1365 cls = fargs[0]
1388 _user = cls._rhodecode_user
1366 _user = cls._rhodecode_user
1389
1367
1390 log.debug('checking %s permissions %s for %s %s',
1368 log.debug('checking %s permissions %s for %s %s',
1391 self.__class__.__name__, self.required_perms, cls, _user)
1369 self.__class__.__name__, self.required_perms, cls, _user)
1392
1370
1393 if self.check_permissions(_user):
1371 if self.check_permissions(_user):
1394 log.debug('Permission granted for %s %s', cls, _user)
1372 log.debug('Permission granted for %s %s', cls, _user)
1395 return func(*fargs, **fkwargs)
1373 return func(*fargs, **fkwargs)
1396
1374
1397 else:
1375 else:
1398 log.debug('Permission denied for %s %s', cls, _user)
1376 log.debug('Permission denied for %s %s', cls, _user)
1399 anonymous = _user.username == User.DEFAULT_USER
1377 anonymous = _user.username == User.DEFAULT_USER
1400
1378
1401 if anonymous:
1379 if anonymous:
1402 came_from = self._get_came_from()
1380 came_from = self._get_came_from()
1403 h.flash(_('You need to be signed in to view this page'),
1381 h.flash(_('You need to be signed in to view this page'),
1404 category='warning')
1382 category='warning')
1405 raise HTTPFound(
1383 raise HTTPFound(
1406 h.route_path('login', _query={'came_from': came_from}))
1384 h.route_path('login', _query={'came_from': came_from}))
1407
1385
1408 else:
1386 else:
1409 # redirect with 404 to prevent resource discovery
1387 # redirect with 404 to prevent resource discovery
1410 raise HTTPNotFound()
1388 raise HTTPNotFound()
1411
1389
1412 def check_permissions(self, user):
1390 def check_permissions(self, user):
1413 """Dummy function for overriding"""
1391 """Dummy function for overriding"""
1414 raise NotImplementedError(
1392 raise NotImplementedError(
1415 'You have to write this function in child class')
1393 'You have to write this function in child class')
1416
1394
1417
1395
1418 class HasPermissionAllDecorator(PermsDecorator):
1396 class HasPermissionAllDecorator(PermsDecorator):
1419 """
1397 """
1420 Checks for access permission for all given predicates. All of them
1398 Checks for access permission for all given predicates. All of them
1421 have to be meet in order to fulfill the request
1399 have to be meet in order to fulfill the request
1422 """
1400 """
1423
1401
1424 def check_permissions(self, user):
1402 def check_permissions(self, user):
1425 perms = user.permissions_with_scope({})
1403 perms = user.permissions_with_scope({})
1426 if self.required_perms.issubset(perms['global']):
1404 if self.required_perms.issubset(perms['global']):
1427 return True
1405 return True
1428 return False
1406 return False
1429
1407
1430
1408
1431 class HasPermissionAnyDecorator(PermsDecorator):
1409 class HasPermissionAnyDecorator(PermsDecorator):
1432 """
1410 """
1433 Checks for access permission for any of given predicates. In order to
1411 Checks for access permission for any of given predicates. In order to
1434 fulfill the request any of predicates must be meet
1412 fulfill the request any of predicates must be meet
1435 """
1413 """
1436
1414
1437 def check_permissions(self, user):
1415 def check_permissions(self, user):
1438 perms = user.permissions_with_scope({})
1416 perms = user.permissions_with_scope({})
1439 if self.required_perms.intersection(perms['global']):
1417 if self.required_perms.intersection(perms['global']):
1440 return True
1418 return True
1441 return False
1419 return False
1442
1420
1443
1421
1444 class HasRepoPermissionAllDecorator(PermsDecorator):
1422 class HasRepoPermissionAllDecorator(PermsDecorator):
1445 """
1423 """
1446 Checks for access permission for all given predicates for specific
1424 Checks for access permission for all given predicates for specific
1447 repository. All of them have to be meet in order to fulfill the request
1425 repository. All of them have to be meet in order to fulfill the request
1448 """
1426 """
1449 def _get_repo_name(self):
1427 def _get_repo_name(self):
1450 _request = self._get_request()
1428 _request = self._get_request()
1451 return get_repo_slug(_request)
1429 return get_repo_slug(_request)
1452
1430
1453 def check_permissions(self, user):
1431 def check_permissions(self, user):
1454 perms = user.permissions
1432 perms = user.permissions
1455 repo_name = self._get_repo_name()
1433 repo_name = self._get_repo_name()
1456
1434
1457 try:
1435 try:
1458 user_perms = set([perms['repositories'][repo_name]])
1436 user_perms = set([perms['repositories'][repo_name]])
1459 except KeyError:
1437 except KeyError:
1460 log.debug('cannot locate repo with name: `%s` in permissions defs',
1438 log.debug('cannot locate repo with name: `%s` in permissions defs',
1461 repo_name)
1439 repo_name)
1462 return False
1440 return False
1463
1441
1464 log.debug('checking `%s` permissions for repo `%s`',
1442 log.debug('checking `%s` permissions for repo `%s`',
1465 user_perms, repo_name)
1443 user_perms, repo_name)
1466 if self.required_perms.issubset(user_perms):
1444 if self.required_perms.issubset(user_perms):
1467 return True
1445 return True
1468 return False
1446 return False
1469
1447
1470
1448
1471 class HasRepoPermissionAnyDecorator(PermsDecorator):
1449 class HasRepoPermissionAnyDecorator(PermsDecorator):
1472 """
1450 """
1473 Checks for access permission for any of given predicates for specific
1451 Checks for access permission for any of given predicates for specific
1474 repository. In order to fulfill the request any of predicates must be meet
1452 repository. In order to fulfill the request any of predicates must be meet
1475 """
1453 """
1476 def _get_repo_name(self):
1454 def _get_repo_name(self):
1477 _request = self._get_request()
1455 _request = self._get_request()
1478 return get_repo_slug(_request)
1456 return get_repo_slug(_request)
1479
1457
1480 def check_permissions(self, user):
1458 def check_permissions(self, user):
1481 perms = user.permissions
1459 perms = user.permissions
1482 repo_name = self._get_repo_name()
1460 repo_name = self._get_repo_name()
1483
1461
1484 try:
1462 try:
1485 user_perms = set([perms['repositories'][repo_name]])
1463 user_perms = set([perms['repositories'][repo_name]])
1486 except KeyError:
1464 except KeyError:
1487 log.debug(
1465 log.debug(
1488 'cannot locate repo with name: `%s` in permissions defs',
1466 'cannot locate repo with name: `%s` in permissions defs',
1489 repo_name)
1467 repo_name)
1490 return False
1468 return False
1491
1469
1492 log.debug('checking `%s` permissions for repo `%s`',
1470 log.debug('checking `%s` permissions for repo `%s`',
1493 user_perms, repo_name)
1471 user_perms, repo_name)
1494 if self.required_perms.intersection(user_perms):
1472 if self.required_perms.intersection(user_perms):
1495 return True
1473 return True
1496 return False
1474 return False
1497
1475
1498
1476
1499 class HasRepoGroupPermissionAllDecorator(PermsDecorator):
1477 class HasRepoGroupPermissionAllDecorator(PermsDecorator):
1500 """
1478 """
1501 Checks for access permission for all given predicates for specific
1479 Checks for access permission for all given predicates for specific
1502 repository group. All of them have to be meet in order to
1480 repository group. All of them have to be meet in order to
1503 fulfill the request
1481 fulfill the request
1504 """
1482 """
1505 def _get_repo_group_name(self):
1483 def _get_repo_group_name(self):
1506 _request = self._get_request()
1484 _request = self._get_request()
1507 return get_repo_group_slug(_request)
1485 return get_repo_group_slug(_request)
1508
1486
1509 def check_permissions(self, user):
1487 def check_permissions(self, user):
1510 perms = user.permissions
1488 perms = user.permissions
1511 group_name = self._get_repo_group_name()
1489 group_name = self._get_repo_group_name()
1512 try:
1490 try:
1513 user_perms = set([perms['repositories_groups'][group_name]])
1491 user_perms = set([perms['repositories_groups'][group_name]])
1514 except KeyError:
1492 except KeyError:
1515 log.debug(
1493 log.debug(
1516 'cannot locate repo group with name: `%s` in permissions defs',
1494 'cannot locate repo group with name: `%s` in permissions defs',
1517 group_name)
1495 group_name)
1518 return False
1496 return False
1519
1497
1520 log.debug('checking `%s` permissions for repo group `%s`',
1498 log.debug('checking `%s` permissions for repo group `%s`',
1521 user_perms, group_name)
1499 user_perms, group_name)
1522 if self.required_perms.issubset(user_perms):
1500 if self.required_perms.issubset(user_perms):
1523 return True
1501 return True
1524 return False
1502 return False
1525
1503
1526
1504
1527 class HasRepoGroupPermissionAnyDecorator(PermsDecorator):
1505 class HasRepoGroupPermissionAnyDecorator(PermsDecorator):
1528 """
1506 """
1529 Checks for access permission for any of given predicates for specific
1507 Checks for access permission for any of given predicates for specific
1530 repository group. In order to fulfill the request any
1508 repository group. In order to fulfill the request any
1531 of predicates must be met
1509 of predicates must be met
1532 """
1510 """
1533 def _get_repo_group_name(self):
1511 def _get_repo_group_name(self):
1534 _request = self._get_request()
1512 _request = self._get_request()
1535 return get_repo_group_slug(_request)
1513 return get_repo_group_slug(_request)
1536
1514
1537 def check_permissions(self, user):
1515 def check_permissions(self, user):
1538 perms = user.permissions
1516 perms = user.permissions
1539 group_name = self._get_repo_group_name()
1517 group_name = self._get_repo_group_name()
1540
1518
1541 try:
1519 try:
1542 user_perms = set([perms['repositories_groups'][group_name]])
1520 user_perms = set([perms['repositories_groups'][group_name]])
1543 except KeyError:
1521 except KeyError:
1544 log.debug(
1522 log.debug(
1545 'cannot locate repo group with name: `%s` in permissions defs',
1523 'cannot locate repo group with name: `%s` in permissions defs',
1546 group_name)
1524 group_name)
1547 return False
1525 return False
1548
1526
1549 log.debug('checking `%s` permissions for repo group `%s`',
1527 log.debug('checking `%s` permissions for repo group `%s`',
1550 user_perms, group_name)
1528 user_perms, group_name)
1551 if self.required_perms.intersection(user_perms):
1529 if self.required_perms.intersection(user_perms):
1552 return True
1530 return True
1553 return False
1531 return False
1554
1532
1555
1533
1556 class HasUserGroupPermissionAllDecorator(PermsDecorator):
1534 class HasUserGroupPermissionAllDecorator(PermsDecorator):
1557 """
1535 """
1558 Checks for access permission for all given predicates for specific
1536 Checks for access permission for all given predicates for specific
1559 user group. All of them have to be meet in order to fulfill the request
1537 user group. All of them have to be meet in order to fulfill the request
1560 """
1538 """
1561 def _get_user_group_name(self):
1539 def _get_user_group_name(self):
1562 _request = self._get_request()
1540 _request = self._get_request()
1563 return get_user_group_slug(_request)
1541 return get_user_group_slug(_request)
1564
1542
1565 def check_permissions(self, user):
1543 def check_permissions(self, user):
1566 perms = user.permissions
1544 perms = user.permissions
1567 group_name = self._get_user_group_name()
1545 group_name = self._get_user_group_name()
1568 try:
1546 try:
1569 user_perms = set([perms['user_groups'][group_name]])
1547 user_perms = set([perms['user_groups'][group_name]])
1570 except KeyError:
1548 except KeyError:
1571 return False
1549 return False
1572
1550
1573 if self.required_perms.issubset(user_perms):
1551 if self.required_perms.issubset(user_perms):
1574 return True
1552 return True
1575 return False
1553 return False
1576
1554
1577
1555
1578 class HasUserGroupPermissionAnyDecorator(PermsDecorator):
1556 class HasUserGroupPermissionAnyDecorator(PermsDecorator):
1579 """
1557 """
1580 Checks for access permission for any of given predicates for specific
1558 Checks for access permission for any of given predicates for specific
1581 user group. In order to fulfill the request any of predicates must be meet
1559 user group. In order to fulfill the request any of predicates must be meet
1582 """
1560 """
1583 def _get_user_group_name(self):
1561 def _get_user_group_name(self):
1584 _request = self._get_request()
1562 _request = self._get_request()
1585 return get_user_group_slug(_request)
1563 return get_user_group_slug(_request)
1586
1564
1587 def check_permissions(self, user):
1565 def check_permissions(self, user):
1588 perms = user.permissions
1566 perms = user.permissions
1589 group_name = self._get_user_group_name()
1567 group_name = self._get_user_group_name()
1590 try:
1568 try:
1591 user_perms = set([perms['user_groups'][group_name]])
1569 user_perms = set([perms['user_groups'][group_name]])
1592 except KeyError:
1570 except KeyError:
1593 return False
1571 return False
1594
1572
1595 if self.required_perms.intersection(user_perms):
1573 if self.required_perms.intersection(user_perms):
1596 return True
1574 return True
1597 return False
1575 return False
1598
1576
1599
1577
1600 # CHECK FUNCTIONS
1578 # CHECK FUNCTIONS
1601 class PermsFunction(object):
1579 class PermsFunction(object):
1602 """Base function for other check functions"""
1580 """Base function for other check functions"""
1603
1581
1604 def __init__(self, *perms):
1582 def __init__(self, *perms):
1605 self.required_perms = set(perms)
1583 self.required_perms = set(perms)
1606 self.repo_name = None
1584 self.repo_name = None
1607 self.repo_group_name = None
1585 self.repo_group_name = None
1608 self.user_group_name = None
1586 self.user_group_name = None
1609
1587
1610 def __bool__(self):
1588 def __bool__(self):
1611 frame = inspect.currentframe()
1589 frame = inspect.currentframe()
1612 stack_trace = traceback.format_stack(frame)
1590 stack_trace = traceback.format_stack(frame)
1613 log.error('Checking bool value on a class instance of perm '
1591 log.error('Checking bool value on a class instance of perm '
1614 'function is not allowed: %s' % ''.join(stack_trace))
1592 'function is not allowed: %s' % ''.join(stack_trace))
1615 # rather than throwing errors, here we always return False so if by
1593 # rather than throwing errors, here we always return False so if by
1616 # accident someone checks truth for just an instance it will always end
1594 # accident someone checks truth for just an instance it will always end
1617 # up in returning False
1595 # up in returning False
1618 return False
1596 return False
1619 __nonzero__ = __bool__
1597 __nonzero__ = __bool__
1620
1598
1621 def __call__(self, check_location='', user=None):
1599 def __call__(self, check_location='', user=None):
1622 if not user:
1600 if not user:
1623 log.debug('Using user attribute from global request')
1601 log.debug('Using user attribute from global request')
1624 # TODO: remove this someday,put as user as attribute here
1602 # TODO: remove this someday,put as user as attribute here
1625 request = self._get_request()
1603 request = self._get_request()
1626 user = request.user
1604 user = request.user
1627
1605
1628 # init auth user if not already given
1606 # init auth user if not already given
1629 if not isinstance(user, AuthUser):
1607 if not isinstance(user, AuthUser):
1630 log.debug('Wrapping user %s into AuthUser', user)
1608 log.debug('Wrapping user %s into AuthUser', user)
1631 user = AuthUser(user.user_id)
1609 user = AuthUser(user.user_id)
1632
1610
1633 cls_name = self.__class__.__name__
1611 cls_name = self.__class__.__name__
1634 check_scope = self._get_check_scope(cls_name)
1612 check_scope = self._get_check_scope(cls_name)
1635 check_location = check_location or 'unspecified location'
1613 check_location = check_location or 'unspecified location'
1636
1614
1637 log.debug('checking cls:%s %s usr:%s %s @ %s', cls_name,
1615 log.debug('checking cls:%s %s usr:%s %s @ %s', cls_name,
1638 self.required_perms, user, check_scope, check_location)
1616 self.required_perms, user, check_scope, check_location)
1639 if not user:
1617 if not user:
1640 log.warning('Empty user given for permission check')
1618 log.warning('Empty user given for permission check')
1641 return False
1619 return False
1642
1620
1643 if self.check_permissions(user):
1621 if self.check_permissions(user):
1644 log.debug('Permission to repo:`%s` GRANTED for user:`%s` @ %s',
1622 log.debug('Permission to repo:`%s` GRANTED for user:`%s` @ %s',
1645 check_scope, user, check_location)
1623 check_scope, user, check_location)
1646 return True
1624 return True
1647
1625
1648 else:
1626 else:
1649 log.debug('Permission to repo:`%s` DENIED for user:`%s` @ %s',
1627 log.debug('Permission to repo:`%s` DENIED for user:`%s` @ %s',
1650 check_scope, user, check_location)
1628 check_scope, user, check_location)
1651 return False
1629 return False
1652
1630
1653 def _get_request(self):
1631 def _get_request(self):
1654 return get_request(self)
1632 return get_request(self)
1655
1633
1656 def _get_check_scope(self, cls_name):
1634 def _get_check_scope(self, cls_name):
1657 return {
1635 return {
1658 'HasPermissionAll': 'GLOBAL',
1636 'HasPermissionAll': 'GLOBAL',
1659 'HasPermissionAny': 'GLOBAL',
1637 'HasPermissionAny': 'GLOBAL',
1660 'HasRepoPermissionAll': 'repo:%s' % self.repo_name,
1638 'HasRepoPermissionAll': 'repo:%s' % self.repo_name,
1661 'HasRepoPermissionAny': 'repo:%s' % self.repo_name,
1639 'HasRepoPermissionAny': 'repo:%s' % self.repo_name,
1662 'HasRepoGroupPermissionAll': 'repo_group:%s' % self.repo_group_name,
1640 'HasRepoGroupPermissionAll': 'repo_group:%s' % self.repo_group_name,
1663 'HasRepoGroupPermissionAny': 'repo_group:%s' % self.repo_group_name,
1641 'HasRepoGroupPermissionAny': 'repo_group:%s' % self.repo_group_name,
1664 'HasUserGroupPermissionAll': 'user_group:%s' % self.user_group_name,
1642 'HasUserGroupPermissionAll': 'user_group:%s' % self.user_group_name,
1665 'HasUserGroupPermissionAny': 'user_group:%s' % self.user_group_name,
1643 'HasUserGroupPermissionAny': 'user_group:%s' % self.user_group_name,
1666 }.get(cls_name, '?:%s' % cls_name)
1644 }.get(cls_name, '?:%s' % cls_name)
1667
1645
1668 def check_permissions(self, user):
1646 def check_permissions(self, user):
1669 """Dummy function for overriding"""
1647 """Dummy function for overriding"""
1670 raise Exception('You have to write this function in child class')
1648 raise Exception('You have to write this function in child class')
1671
1649
1672
1650
1673 class HasPermissionAll(PermsFunction):
1651 class HasPermissionAll(PermsFunction):
1674 def check_permissions(self, user):
1652 def check_permissions(self, user):
1675 perms = user.permissions_with_scope({})
1653 perms = user.permissions_with_scope({})
1676 if self.required_perms.issubset(perms.get('global')):
1654 if self.required_perms.issubset(perms.get('global')):
1677 return True
1655 return True
1678 return False
1656 return False
1679
1657
1680
1658
1681 class HasPermissionAny(PermsFunction):
1659 class HasPermissionAny(PermsFunction):
1682 def check_permissions(self, user):
1660 def check_permissions(self, user):
1683 perms = user.permissions_with_scope({})
1661 perms = user.permissions_with_scope({})
1684 if self.required_perms.intersection(perms.get('global')):
1662 if self.required_perms.intersection(perms.get('global')):
1685 return True
1663 return True
1686 return False
1664 return False
1687
1665
1688
1666
1689 class HasRepoPermissionAll(PermsFunction):
1667 class HasRepoPermissionAll(PermsFunction):
1690 def __call__(self, repo_name=None, check_location='', user=None):
1668 def __call__(self, repo_name=None, check_location='', user=None):
1691 self.repo_name = repo_name
1669 self.repo_name = repo_name
1692 return super(HasRepoPermissionAll, self).__call__(check_location, user)
1670 return super(HasRepoPermissionAll, self).__call__(check_location, user)
1693
1671
1694 def _get_repo_name(self):
1672 def _get_repo_name(self):
1695 if not self.repo_name:
1673 if not self.repo_name:
1696 _request = self._get_request()
1674 _request = self._get_request()
1697 self.repo_name = get_repo_slug(_request)
1675 self.repo_name = get_repo_slug(_request)
1698 return self.repo_name
1676 return self.repo_name
1699
1677
1700 def check_permissions(self, user):
1678 def check_permissions(self, user):
1701 self.repo_name = self._get_repo_name()
1679 self.repo_name = self._get_repo_name()
1702 perms = user.permissions
1680 perms = user.permissions
1703 try:
1681 try:
1704 user_perms = set([perms['repositories'][self.repo_name]])
1682 user_perms = set([perms['repositories'][self.repo_name]])
1705 except KeyError:
1683 except KeyError:
1706 return False
1684 return False
1707 if self.required_perms.issubset(user_perms):
1685 if self.required_perms.issubset(user_perms):
1708 return True
1686 return True
1709 return False
1687 return False
1710
1688
1711
1689
1712 class HasRepoPermissionAny(PermsFunction):
1690 class HasRepoPermissionAny(PermsFunction):
1713 def __call__(self, repo_name=None, check_location='', user=None):
1691 def __call__(self, repo_name=None, check_location='', user=None):
1714 self.repo_name = repo_name
1692 self.repo_name = repo_name
1715 return super(HasRepoPermissionAny, self).__call__(check_location, user)
1693 return super(HasRepoPermissionAny, self).__call__(check_location, user)
1716
1694
1717 def _get_repo_name(self):
1695 def _get_repo_name(self):
1718 if not self.repo_name:
1696 if not self.repo_name:
1719 _request = self._get_request()
1697 _request = self._get_request()
1720 self.repo_name = get_repo_slug(_request)
1698 self.repo_name = get_repo_slug(_request)
1721 return self.repo_name
1699 return self.repo_name
1722
1700
1723 def check_permissions(self, user):
1701 def check_permissions(self, user):
1724 self.repo_name = self._get_repo_name()
1702 self.repo_name = self._get_repo_name()
1725 perms = user.permissions
1703 perms = user.permissions
1726 try:
1704 try:
1727 user_perms = set([perms['repositories'][self.repo_name]])
1705 user_perms = set([perms['repositories'][self.repo_name]])
1728 except KeyError:
1706 except KeyError:
1729 return False
1707 return False
1730 if self.required_perms.intersection(user_perms):
1708 if self.required_perms.intersection(user_perms):
1731 return True
1709 return True
1732 return False
1710 return False
1733
1711
1734
1712
1735 class HasRepoGroupPermissionAny(PermsFunction):
1713 class HasRepoGroupPermissionAny(PermsFunction):
1736 def __call__(self, group_name=None, check_location='', user=None):
1714 def __call__(self, group_name=None, check_location='', user=None):
1737 self.repo_group_name = group_name
1715 self.repo_group_name = group_name
1738 return super(HasRepoGroupPermissionAny, self).__call__(
1716 return super(HasRepoGroupPermissionAny, self).__call__(
1739 check_location, user)
1717 check_location, user)
1740
1718
1741 def check_permissions(self, user):
1719 def check_permissions(self, user):
1742 perms = user.permissions
1720 perms = user.permissions
1743 try:
1721 try:
1744 user_perms = set(
1722 user_perms = set(
1745 [perms['repositories_groups'][self.repo_group_name]])
1723 [perms['repositories_groups'][self.repo_group_name]])
1746 except KeyError:
1724 except KeyError:
1747 return False
1725 return False
1748 if self.required_perms.intersection(user_perms):
1726 if self.required_perms.intersection(user_perms):
1749 return True
1727 return True
1750 return False
1728 return False
1751
1729
1752
1730
1753 class HasRepoGroupPermissionAll(PermsFunction):
1731 class HasRepoGroupPermissionAll(PermsFunction):
1754 def __call__(self, group_name=None, check_location='', user=None):
1732 def __call__(self, group_name=None, check_location='', user=None):
1755 self.repo_group_name = group_name
1733 self.repo_group_name = group_name
1756 return super(HasRepoGroupPermissionAll, self).__call__(
1734 return super(HasRepoGroupPermissionAll, self).__call__(
1757 check_location, user)
1735 check_location, user)
1758
1736
1759 def check_permissions(self, user):
1737 def check_permissions(self, user):
1760 perms = user.permissions
1738 perms = user.permissions
1761 try:
1739 try:
1762 user_perms = set(
1740 user_perms = set(
1763 [perms['repositories_groups'][self.repo_group_name]])
1741 [perms['repositories_groups'][self.repo_group_name]])
1764 except KeyError:
1742 except KeyError:
1765 return False
1743 return False
1766 if self.required_perms.issubset(user_perms):
1744 if self.required_perms.issubset(user_perms):
1767 return True
1745 return True
1768 return False
1746 return False
1769
1747
1770
1748
1771 class HasUserGroupPermissionAny(PermsFunction):
1749 class HasUserGroupPermissionAny(PermsFunction):
1772 def __call__(self, user_group_name=None, check_location='', user=None):
1750 def __call__(self, user_group_name=None, check_location='', user=None):
1773 self.user_group_name = user_group_name
1751 self.user_group_name = user_group_name
1774 return super(HasUserGroupPermissionAny, self).__call__(
1752 return super(HasUserGroupPermissionAny, self).__call__(
1775 check_location, user)
1753 check_location, user)
1776
1754
1777 def check_permissions(self, user):
1755 def check_permissions(self, user):
1778 perms = user.permissions
1756 perms = user.permissions
1779 try:
1757 try:
1780 user_perms = set([perms['user_groups'][self.user_group_name]])
1758 user_perms = set([perms['user_groups'][self.user_group_name]])
1781 except KeyError:
1759 except KeyError:
1782 return False
1760 return False
1783 if self.required_perms.intersection(user_perms):
1761 if self.required_perms.intersection(user_perms):
1784 return True
1762 return True
1785 return False
1763 return False
1786
1764
1787
1765
1788 class HasUserGroupPermissionAll(PermsFunction):
1766 class HasUserGroupPermissionAll(PermsFunction):
1789 def __call__(self, user_group_name=None, check_location='', user=None):
1767 def __call__(self, user_group_name=None, check_location='', user=None):
1790 self.user_group_name = user_group_name
1768 self.user_group_name = user_group_name
1791 return super(HasUserGroupPermissionAll, self).__call__(
1769 return super(HasUserGroupPermissionAll, self).__call__(
1792 check_location, user)
1770 check_location, user)
1793
1771
1794 def check_permissions(self, user):
1772 def check_permissions(self, user):
1795 perms = user.permissions
1773 perms = user.permissions
1796 try:
1774 try:
1797 user_perms = set([perms['user_groups'][self.user_group_name]])
1775 user_perms = set([perms['user_groups'][self.user_group_name]])
1798 except KeyError:
1776 except KeyError:
1799 return False
1777 return False
1800 if self.required_perms.issubset(user_perms):
1778 if self.required_perms.issubset(user_perms):
1801 return True
1779 return True
1802 return False
1780 return False
1803
1781
1804
1782
1805 # SPECIAL VERSION TO HANDLE MIDDLEWARE AUTH
1783 # SPECIAL VERSION TO HANDLE MIDDLEWARE AUTH
1806 class HasPermissionAnyMiddleware(object):
1784 class HasPermissionAnyMiddleware(object):
1807 def __init__(self, *perms):
1785 def __init__(self, *perms):
1808 self.required_perms = set(perms)
1786 self.required_perms = set(perms)
1809
1787
1810 def __call__(self, user, repo_name):
1788 def __call__(self, user, repo_name):
1811 # repo_name MUST be unicode, since we handle keys in permission
1789 # repo_name MUST be unicode, since we handle keys in permission
1812 # dict by unicode
1790 # dict by unicode
1813 repo_name = safe_unicode(repo_name)
1791 repo_name = safe_unicode(repo_name)
1814 user = AuthUser(user.user_id)
1792 user = AuthUser(user.user_id)
1815 log.debug(
1793 log.debug(
1816 'Checking VCS protocol permissions %s for user:%s repo:`%s`',
1794 'Checking VCS protocol permissions %s for user:%s repo:`%s`',
1817 self.required_perms, user, repo_name)
1795 self.required_perms, user, repo_name)
1818
1796
1819 if self.check_permissions(user, repo_name):
1797 if self.check_permissions(user, repo_name):
1820 log.debug('Permission to repo:`%s` GRANTED for user:%s @ %s',
1798 log.debug('Permission to repo:`%s` GRANTED for user:%s @ %s',
1821 repo_name, user, 'PermissionMiddleware')
1799 repo_name, user, 'PermissionMiddleware')
1822 return True
1800 return True
1823
1801
1824 else:
1802 else:
1825 log.debug('Permission to repo:`%s` DENIED for user:%s @ %s',
1803 log.debug('Permission to repo:`%s` DENIED for user:%s @ %s',
1826 repo_name, user, 'PermissionMiddleware')
1804 repo_name, user, 'PermissionMiddleware')
1827 return False
1805 return False
1828
1806
1829 def check_permissions(self, user, repo_name):
1807 def check_permissions(self, user, repo_name):
1830 perms = user.permissions_with_scope({'repo_name': repo_name})
1808 perms = user.permissions_with_scope({'repo_name': repo_name})
1831
1809
1832 try:
1810 try:
1833 user_perms = set([perms['repositories'][repo_name]])
1811 user_perms = set([perms['repositories'][repo_name]])
1834 except Exception:
1812 except Exception:
1835 log.exception('Error while accessing user permissions')
1813 log.exception('Error while accessing user permissions')
1836 return False
1814 return False
1837
1815
1838 if self.required_perms.intersection(user_perms):
1816 if self.required_perms.intersection(user_perms):
1839 return True
1817 return True
1840 return False
1818 return False
1841
1819
1842
1820
1843 # SPECIAL VERSION TO HANDLE API AUTH
1821 # SPECIAL VERSION TO HANDLE API AUTH
1844 class _BaseApiPerm(object):
1822 class _BaseApiPerm(object):
1845 def __init__(self, *perms):
1823 def __init__(self, *perms):
1846 self.required_perms = set(perms)
1824 self.required_perms = set(perms)
1847
1825
1848 def __call__(self, check_location=None, user=None, repo_name=None,
1826 def __call__(self, check_location=None, user=None, repo_name=None,
1849 group_name=None, user_group_name=None):
1827 group_name=None, user_group_name=None):
1850 cls_name = self.__class__.__name__
1828 cls_name = self.__class__.__name__
1851 check_scope = 'global:%s' % (self.required_perms,)
1829 check_scope = 'global:%s' % (self.required_perms,)
1852 if repo_name:
1830 if repo_name:
1853 check_scope += ', repo_name:%s' % (repo_name,)
1831 check_scope += ', repo_name:%s' % (repo_name,)
1854
1832
1855 if group_name:
1833 if group_name:
1856 check_scope += ', repo_group_name:%s' % (group_name,)
1834 check_scope += ', repo_group_name:%s' % (group_name,)
1857
1835
1858 if user_group_name:
1836 if user_group_name:
1859 check_scope += ', user_group_name:%s' % (user_group_name,)
1837 check_scope += ', user_group_name:%s' % (user_group_name,)
1860
1838
1861 log.debug(
1839 log.debug(
1862 'checking cls:%s %s %s @ %s'
1840 'checking cls:%s %s %s @ %s'
1863 % (cls_name, self.required_perms, check_scope, check_location))
1841 % (cls_name, self.required_perms, check_scope, check_location))
1864 if not user:
1842 if not user:
1865 log.debug('Empty User passed into arguments')
1843 log.debug('Empty User passed into arguments')
1866 return False
1844 return False
1867
1845
1868 # process user
1846 # process user
1869 if not isinstance(user, AuthUser):
1847 if not isinstance(user, AuthUser):
1870 user = AuthUser(user.user_id)
1848 user = AuthUser(user.user_id)
1871 if not check_location:
1849 if not check_location:
1872 check_location = 'unspecified'
1850 check_location = 'unspecified'
1873 if self.check_permissions(user.permissions, repo_name, group_name,
1851 if self.check_permissions(user.permissions, repo_name, group_name,
1874 user_group_name):
1852 user_group_name):
1875 log.debug('Permission to repo:`%s` GRANTED for user:`%s` @ %s',
1853 log.debug('Permission to repo:`%s` GRANTED for user:`%s` @ %s',
1876 check_scope, user, check_location)
1854 check_scope, user, check_location)
1877 return True
1855 return True
1878
1856
1879 else:
1857 else:
1880 log.debug('Permission to repo:`%s` DENIED for user:`%s` @ %s',
1858 log.debug('Permission to repo:`%s` DENIED for user:`%s` @ %s',
1881 check_scope, user, check_location)
1859 check_scope, user, check_location)
1882 return False
1860 return False
1883
1861
1884 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1862 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1885 user_group_name=None):
1863 user_group_name=None):
1886 """
1864 """
1887 implement in child class should return True if permissions are ok,
1865 implement in child class should return True if permissions are ok,
1888 False otherwise
1866 False otherwise
1889
1867
1890 :param perm_defs: dict with permission definitions
1868 :param perm_defs: dict with permission definitions
1891 :param repo_name: repo name
1869 :param repo_name: repo name
1892 """
1870 """
1893 raise NotImplementedError()
1871 raise NotImplementedError()
1894
1872
1895
1873
1896 class HasPermissionAllApi(_BaseApiPerm):
1874 class HasPermissionAllApi(_BaseApiPerm):
1897 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1875 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1898 user_group_name=None):
1876 user_group_name=None):
1899 if self.required_perms.issubset(perm_defs.get('global')):
1877 if self.required_perms.issubset(perm_defs.get('global')):
1900 return True
1878 return True
1901 return False
1879 return False
1902
1880
1903
1881
1904 class HasPermissionAnyApi(_BaseApiPerm):
1882 class HasPermissionAnyApi(_BaseApiPerm):
1905 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1883 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1906 user_group_name=None):
1884 user_group_name=None):
1907 if self.required_perms.intersection(perm_defs.get('global')):
1885 if self.required_perms.intersection(perm_defs.get('global')):
1908 return True
1886 return True
1909 return False
1887 return False
1910
1888
1911
1889
1912 class HasRepoPermissionAllApi(_BaseApiPerm):
1890 class HasRepoPermissionAllApi(_BaseApiPerm):
1913 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1891 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1914 user_group_name=None):
1892 user_group_name=None):
1915 try:
1893 try:
1916 _user_perms = set([perm_defs['repositories'][repo_name]])
1894 _user_perms = set([perm_defs['repositories'][repo_name]])
1917 except KeyError:
1895 except KeyError:
1918 log.warning(traceback.format_exc())
1896 log.warning(traceback.format_exc())
1919 return False
1897 return False
1920 if self.required_perms.issubset(_user_perms):
1898 if self.required_perms.issubset(_user_perms):
1921 return True
1899 return True
1922 return False
1900 return False
1923
1901
1924
1902
1925 class HasRepoPermissionAnyApi(_BaseApiPerm):
1903 class HasRepoPermissionAnyApi(_BaseApiPerm):
1926 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1904 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1927 user_group_name=None):
1905 user_group_name=None):
1928 try:
1906 try:
1929 _user_perms = set([perm_defs['repositories'][repo_name]])
1907 _user_perms = set([perm_defs['repositories'][repo_name]])
1930 except KeyError:
1908 except KeyError:
1931 log.warning(traceback.format_exc())
1909 log.warning(traceback.format_exc())
1932 return False
1910 return False
1933 if self.required_perms.intersection(_user_perms):
1911 if self.required_perms.intersection(_user_perms):
1934 return True
1912 return True
1935 return False
1913 return False
1936
1914
1937
1915
1938 class HasRepoGroupPermissionAnyApi(_BaseApiPerm):
1916 class HasRepoGroupPermissionAnyApi(_BaseApiPerm):
1939 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1917 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1940 user_group_name=None):
1918 user_group_name=None):
1941 try:
1919 try:
1942 _user_perms = set([perm_defs['repositories_groups'][group_name]])
1920 _user_perms = set([perm_defs['repositories_groups'][group_name]])
1943 except KeyError:
1921 except KeyError:
1944 log.warning(traceback.format_exc())
1922 log.warning(traceback.format_exc())
1945 return False
1923 return False
1946 if self.required_perms.intersection(_user_perms):
1924 if self.required_perms.intersection(_user_perms):
1947 return True
1925 return True
1948 return False
1926 return False
1949
1927
1950
1928
1951 class HasRepoGroupPermissionAllApi(_BaseApiPerm):
1929 class HasRepoGroupPermissionAllApi(_BaseApiPerm):
1952 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1930 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1953 user_group_name=None):
1931 user_group_name=None):
1954 try:
1932 try:
1955 _user_perms = set([perm_defs['repositories_groups'][group_name]])
1933 _user_perms = set([perm_defs['repositories_groups'][group_name]])
1956 except KeyError:
1934 except KeyError:
1957 log.warning(traceback.format_exc())
1935 log.warning(traceback.format_exc())
1958 return False
1936 return False
1959 if self.required_perms.issubset(_user_perms):
1937 if self.required_perms.issubset(_user_perms):
1960 return True
1938 return True
1961 return False
1939 return False
1962
1940
1963
1941
1964 class HasUserGroupPermissionAnyApi(_BaseApiPerm):
1942 class HasUserGroupPermissionAnyApi(_BaseApiPerm):
1965 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1943 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1966 user_group_name=None):
1944 user_group_name=None):
1967 try:
1945 try:
1968 _user_perms = set([perm_defs['user_groups'][user_group_name]])
1946 _user_perms = set([perm_defs['user_groups'][user_group_name]])
1969 except KeyError:
1947 except KeyError:
1970 log.warning(traceback.format_exc())
1948 log.warning(traceback.format_exc())
1971 return False
1949 return False
1972 if self.required_perms.intersection(_user_perms):
1950 if self.required_perms.intersection(_user_perms):
1973 return True
1951 return True
1974 return False
1952 return False
1975
1953
1976
1954
1977 def check_ip_access(source_ip, allowed_ips=None):
1955 def check_ip_access(source_ip, allowed_ips=None):
1978 """
1956 """
1979 Checks if source_ip is a subnet of any of allowed_ips.
1957 Checks if source_ip is a subnet of any of allowed_ips.
1980
1958
1981 :param source_ip:
1959 :param source_ip:
1982 :param allowed_ips: list of allowed ips together with mask
1960 :param allowed_ips: list of allowed ips together with mask
1983 """
1961 """
1984 log.debug('checking if ip:%s is subnet of %s' % (source_ip, allowed_ips))
1962 log.debug('checking if ip:%s is subnet of %s' % (source_ip, allowed_ips))
1985 source_ip_address = ipaddress.ip_address(safe_unicode(source_ip))
1963 source_ip_address = ipaddress.ip_address(safe_unicode(source_ip))
1986 if isinstance(allowed_ips, (tuple, list, set)):
1964 if isinstance(allowed_ips, (tuple, list, set)):
1987 for ip in allowed_ips:
1965 for ip in allowed_ips:
1988 ip = safe_unicode(ip)
1966 ip = safe_unicode(ip)
1989 try:
1967 try:
1990 network_address = ipaddress.ip_network(ip, strict=False)
1968 network_address = ipaddress.ip_network(ip, strict=False)
1991 if source_ip_address in network_address:
1969 if source_ip_address in network_address:
1992 log.debug('IP %s is network %s' %
1970 log.debug('IP %s is network %s' %
1993 (source_ip_address, network_address))
1971 (source_ip_address, network_address))
1994 return True
1972 return True
1995 # for any case we cannot determine the IP, don't crash just
1973 # for any case we cannot determine the IP, don't crash just
1996 # skip it and log as error, we want to say forbidden still when
1974 # skip it and log as error, we want to say forbidden still when
1997 # sending bad IP
1975 # sending bad IP
1998 except Exception:
1976 except Exception:
1999 log.error(traceback.format_exc())
1977 log.error(traceback.format_exc())
2000 continue
1978 continue
2001 return False
1979 return False
2002
1980
2003
1981
2004 def get_cython_compat_decorator(wrapper, func):
1982 def get_cython_compat_decorator(wrapper, func):
2005 """
1983 """
2006 Creates a cython compatible decorator. The previously used
1984 Creates a cython compatible decorator. The previously used
2007 decorator.decorator() function seems to be incompatible with cython.
1985 decorator.decorator() function seems to be incompatible with cython.
2008
1986
2009 :param wrapper: __wrapper method of the decorator class
1987 :param wrapper: __wrapper method of the decorator class
2010 :param func: decorated function
1988 :param func: decorated function
2011 """
1989 """
2012 @wraps(func)
1990 @wraps(func)
2013 def local_wrapper(*args, **kwds):
1991 def local_wrapper(*args, **kwds):
2014 return wrapper(func, *args, **kwds)
1992 return wrapper(func, *args, **kwds)
2015 local_wrapper.__wrapped__ = func
1993 local_wrapper.__wrapped__ = func
2016 return local_wrapper
1994 return local_wrapper
2017
1995
2018
1996
General Comments 0
You need to be logged in to leave comments. Login now