Show More
The requested changes are too big and content was truncated. Show full diff
@@ -1,505 +1,570 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | |
|
3 | 3 | # Copyright (C) 2016-2017 RhodeCode GmbH |
|
4 | 4 | # |
|
5 | 5 | # This program is free software: you can redistribute it and/or modify |
|
6 | 6 | # it under the terms of the GNU Affero General Public License, version 3 |
|
7 | 7 | # (only), as published by the Free Software Foundation. |
|
8 | 8 | # |
|
9 | 9 | # This program is distributed in the hope that it will be useful, |
|
10 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of |
|
11 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|
12 | 12 | # GNU General Public License for more details. |
|
13 | 13 | # |
|
14 | 14 | # You should have received a copy of the GNU Affero General Public License |
|
15 | 15 | # along with this program. If not, see <http://www.gnu.org/licenses/>. |
|
16 | 16 | # |
|
17 | 17 | # This program is dual-licensed. If you wish to learn more about the |
|
18 | 18 | # RhodeCode Enterprise Edition, including its added features, Support services, |
|
19 | 19 | # and proprietary license terms, please see https://rhodecode.com/licenses/ |
|
20 | 20 | |
|
21 | 21 | import time |
|
22 | 22 | import logging |
|
23 | 23 | import operator |
|
24 | 24 | |
|
25 | 25 | from pyramid.httpexceptions import HTTPFound |
|
26 | 26 | |
|
27 | 27 | from rhodecode.lib import helpers as h |
|
28 | 28 | from rhodecode.lib.utils2 import StrictAttributeDict, safe_int, datetime_to_time |
|
29 | 29 | from rhodecode.lib.vcs.exceptions import RepositoryRequirementError |
|
30 | 30 | from rhodecode.model import repo |
|
31 | 31 | from rhodecode.model import repo_group |
|
32 | 32 | from rhodecode.model import user_group |
|
33 | from rhodecode.model import user | |
|
33 | 34 | from rhodecode.model.db import User |
|
34 | 35 | from rhodecode.model.scm import ScmModel |
|
35 | 36 | |
|
36 | 37 | log = logging.getLogger(__name__) |
|
37 | 38 | |
|
38 | 39 | |
|
39 | 40 | ADMIN_PREFIX = '/_admin' |
|
40 | 41 | STATIC_FILE_PREFIX = '/_static' |
|
41 | 42 | |
|
42 | 43 | URL_NAME_REQUIREMENTS = { |
|
43 | 44 | # group name can have a slash in them, but they must not end with a slash |
|
44 | 45 | 'group_name': r'.*?[^/]', |
|
45 | 46 | 'repo_group_name': r'.*?[^/]', |
|
46 | 47 | # repo names can have a slash in them, but they must not end with a slash |
|
47 | 48 | 'repo_name': r'.*?[^/]', |
|
48 | 49 | # file path eats up everything at the end |
|
49 | 50 | 'f_path': r'.*', |
|
50 | 51 | # reference types |
|
51 | 52 | 'source_ref_type': '(branch|book|tag|rev|\%\(source_ref_type\)s)', |
|
52 | 53 | 'target_ref_type': '(branch|book|tag|rev|\%\(target_ref_type\)s)', |
|
53 | 54 | } |
|
54 | 55 | |
|
55 | 56 | |
|
56 | 57 | def add_route_with_slash(config,name, pattern, **kw): |
|
57 | 58 | config.add_route(name, pattern, **kw) |
|
58 | 59 | if not pattern.endswith('/'): |
|
59 | 60 | config.add_route(name + '_slash', pattern + '/', **kw) |
|
60 | 61 | |
|
61 | 62 | |
|
62 | 63 | def add_route_requirements(route_path, requirements=URL_NAME_REQUIREMENTS): |
|
63 | 64 | """ |
|
64 | 65 | Adds regex requirements to pyramid routes using a mapping dict |
|
65 | 66 | e.g:: |
|
66 | 67 | add_route_requirements('{repo_name}/settings') |
|
67 | 68 | """ |
|
68 | 69 | for key, regex in requirements.items(): |
|
69 | 70 | route_path = route_path.replace('{%s}' % key, '{%s:%s}' % (key, regex)) |
|
70 | 71 | return route_path |
|
71 | 72 | |
|
72 | 73 | |
|
73 | 74 | def get_format_ref_id(repo): |
|
74 | 75 | """Returns a `repo` specific reference formatter function""" |
|
75 | 76 | if h.is_svn(repo): |
|
76 | 77 | return _format_ref_id_svn |
|
77 | 78 | else: |
|
78 | 79 | return _format_ref_id |
|
79 | 80 | |
|
80 | 81 | |
|
81 | 82 | def _format_ref_id(name, raw_id): |
|
82 | 83 | """Default formatting of a given reference `name`""" |
|
83 | 84 | return name |
|
84 | 85 | |
|
85 | 86 | |
|
86 | 87 | def _format_ref_id_svn(name, raw_id): |
|
87 | 88 | """Special way of formatting a reference for Subversion including path""" |
|
88 | 89 | return '%s@%s' % (name, raw_id) |
|
89 | 90 | |
|
90 | 91 | |
|
91 | 92 | class TemplateArgs(StrictAttributeDict): |
|
92 | 93 | pass |
|
93 | 94 | |
|
94 | 95 | |
|
95 | 96 | class BaseAppView(object): |
|
96 | 97 | |
|
97 | 98 | def __init__(self, context, request): |
|
98 | 99 | self.request = request |
|
99 | 100 | self.context = context |
|
100 | 101 | self.session = request.session |
|
101 | 102 | self._rhodecode_user = request.user # auth user |
|
102 | 103 | self._rhodecode_db_user = self._rhodecode_user.get_instance() |
|
103 | 104 | self._maybe_needs_password_change( |
|
104 | 105 | request.matched_route.name, self._rhodecode_db_user) |
|
105 | 106 | |
|
106 | 107 | def _maybe_needs_password_change(self, view_name, user_obj): |
|
107 | 108 | log.debug('Checking if user %s needs password change on view %s', |
|
108 | 109 | user_obj, view_name) |
|
109 | 110 | skip_user_views = [ |
|
110 | 111 | 'logout', 'login', |
|
111 | 112 | 'my_account_password', 'my_account_password_update' |
|
112 | 113 | ] |
|
113 | 114 | |
|
114 | 115 | if not user_obj: |
|
115 | 116 | return |
|
116 | 117 | |
|
117 | 118 | if user_obj.username == User.DEFAULT_USER: |
|
118 | 119 | return |
|
119 | 120 | |
|
120 | 121 | now = time.time() |
|
121 | 122 | should_change = user_obj.user_data.get('force_password_change') |
|
122 | 123 | change_after = safe_int(should_change) or 0 |
|
123 | 124 | if should_change and now > change_after: |
|
124 | 125 | log.debug('User %s requires password change', user_obj) |
|
125 | 126 | h.flash('You are required to change your password', 'warning', |
|
126 | 127 | ignore_duplicate=True) |
|
127 | 128 | |
|
128 | 129 | if view_name not in skip_user_views: |
|
129 | 130 | raise HTTPFound( |
|
130 | 131 | self.request.route_path('my_account_password')) |
|
131 | 132 | |
|
132 | 133 | def _log_creation_exception(self, e, repo_name): |
|
133 | 134 | _ = self.request.translate |
|
134 | 135 | reason = None |
|
135 | 136 | if len(e.args) == 2: |
|
136 | 137 | reason = e.args[1] |
|
137 | 138 | |
|
138 | 139 | if reason == 'INVALID_CERTIFICATE': |
|
139 | 140 | log.exception( |
|
140 | 141 | 'Exception creating a repository: invalid certificate') |
|
141 | 142 | msg = (_('Error creating repository %s: invalid certificate') |
|
142 | 143 | % repo_name) |
|
143 | 144 | else: |
|
144 | 145 | log.exception("Exception creating a repository") |
|
145 | 146 | msg = (_('Error creating repository %s') |
|
146 | 147 | % repo_name) |
|
147 | 148 | return msg |
|
148 | 149 | |
|
149 | 150 | def _get_local_tmpl_context(self, include_app_defaults=False): |
|
150 | 151 | c = TemplateArgs() |
|
151 | 152 | c.auth_user = self.request.user |
|
152 | 153 | # TODO(marcink): migrate the usage of c.rhodecode_user to c.auth_user |
|
153 | 154 | c.rhodecode_user = self.request.user |
|
154 | 155 | |
|
155 | 156 | if include_app_defaults: |
|
156 | 157 | # NOTE(marcink): after full pyramid migration include_app_defaults |
|
157 | 158 | # should be turned on by default |
|
158 | 159 | from rhodecode.lib.base import attach_context_attributes |
|
159 | 160 | attach_context_attributes(c, self.request, self.request.user.user_id) |
|
160 | 161 | |
|
161 | 162 | return c |
|
162 | 163 | |
|
163 | 164 | def _register_global_c(self, tmpl_args): |
|
164 | 165 | """ |
|
165 | 166 | Registers attributes to pylons global `c` |
|
166 | 167 | """ |
|
167 | 168 | |
|
168 | 169 | # TODO(marcink): remove once pyramid migration is finished |
|
169 | 170 | from pylons import tmpl_context as c |
|
170 | 171 | try: |
|
171 | 172 | for k, v in tmpl_args.items(): |
|
172 | 173 | setattr(c, k, v) |
|
173 | 174 | except TypeError: |
|
174 | 175 | log.exception('Failed to register pylons C') |
|
175 | 176 | pass |
|
176 | 177 | |
|
177 | 178 | def _get_template_context(self, tmpl_args): |
|
178 | 179 | self._register_global_c(tmpl_args) |
|
179 | 180 | |
|
180 | 181 | local_tmpl_args = { |
|
181 | 182 | 'defaults': {}, |
|
182 | 183 | 'errors': {}, |
|
183 | 184 | # register a fake 'c' to be used in templates instead of global |
|
184 | 185 | # pylons c, after migration to pyramid we should rename it to 'c' |
|
185 | 186 | # make sure we replace usage of _c in templates too |
|
186 | 187 | '_c': tmpl_args |
|
187 | 188 | } |
|
188 | 189 | local_tmpl_args.update(tmpl_args) |
|
189 | 190 | return local_tmpl_args |
|
190 | 191 | |
|
191 | 192 | def load_default_context(self): |
|
192 | 193 | """ |
|
193 | 194 | example: |
|
194 | 195 | |
|
195 | 196 | def load_default_context(self): |
|
196 | 197 | c = self._get_local_tmpl_context() |
|
197 | 198 | c.custom_var = 'foobar' |
|
198 | 199 | self._register_global_c(c) |
|
199 | 200 | return c |
|
200 | 201 | """ |
|
201 | 202 | raise NotImplementedError('Needs implementation in view class') |
|
202 | 203 | |
|
203 | 204 | |
|
204 | 205 | class RepoAppView(BaseAppView): |
|
205 | 206 | |
|
206 | 207 | def __init__(self, context, request): |
|
207 | 208 | super(RepoAppView, self).__init__(context, request) |
|
208 | 209 | self.db_repo = request.db_repo |
|
209 | 210 | self.db_repo_name = self.db_repo.repo_name |
|
210 | 211 | self.db_repo_pull_requests = ScmModel().get_pull_requests(self.db_repo) |
|
211 | 212 | |
|
212 | 213 | def _handle_missing_requirements(self, error): |
|
213 | 214 | log.error( |
|
214 | 215 | 'Requirements are missing for repository %s: %s', |
|
215 | 216 | self.db_repo_name, error.message) |
|
216 | 217 | |
|
217 | 218 | def _get_local_tmpl_context(self, include_app_defaults=False): |
|
218 | 219 | _ = self.request.translate |
|
219 | 220 | c = super(RepoAppView, self)._get_local_tmpl_context( |
|
220 | 221 | include_app_defaults=include_app_defaults) |
|
221 | 222 | |
|
222 | 223 | # register common vars for this type of view |
|
223 | 224 | c.rhodecode_db_repo = self.db_repo |
|
224 | 225 | c.repo_name = self.db_repo_name |
|
225 | 226 | c.repository_pull_requests = self.db_repo_pull_requests |
|
226 | 227 | |
|
227 | 228 | c.repository_requirements_missing = False |
|
228 | 229 | try: |
|
229 | 230 | self.rhodecode_vcs_repo = self.db_repo.scm_instance() |
|
230 | 231 | except RepositoryRequirementError as e: |
|
231 | 232 | c.repository_requirements_missing = True |
|
232 | 233 | self._handle_missing_requirements(e) |
|
233 | 234 | self.rhodecode_vcs_repo = None |
|
234 | 235 | |
|
235 | 236 | if (not c.repository_requirements_missing |
|
236 | 237 | and self.rhodecode_vcs_repo is None): |
|
237 | 238 | # unable to fetch this repo as vcs instance, report back to user |
|
238 | 239 | h.flash(_( |
|
239 | 240 | "The repository `%(repo_name)s` cannot be loaded in filesystem. " |
|
240 | 241 | "Please check if it exist, or is not damaged.") % |
|
241 | 242 | {'repo_name': c.repo_name}, |
|
242 | 243 | category='error', ignore_duplicate=True) |
|
243 | 244 | raise HTTPFound(h.route_path('home')) |
|
244 | 245 | |
|
245 | 246 | return c |
|
246 | 247 | |
|
247 | 248 | def _get_f_path(self, matchdict, default=None): |
|
248 | 249 | f_path = matchdict.get('f_path') |
|
249 | 250 | if f_path: |
|
250 | 251 | # fix for multiple initial slashes that causes errors for GIT |
|
251 | 252 | return f_path.lstrip('/') |
|
252 | 253 | |
|
253 | 254 | return default |
|
254 | 255 | |
|
255 | 256 | |
|
256 | 257 | class RepoGroupAppView(BaseAppView): |
|
257 | 258 | def __init__(self, context, request): |
|
258 | 259 | super(RepoGroupAppView, self).__init__(context, request) |
|
259 | 260 | self.db_repo_group = request.db_repo_group |
|
260 | 261 | self.db_repo_group_name = self.db_repo_group.group_name |
|
261 | 262 | |
|
262 | 263 | |
|
263 | 264 | class UserGroupAppView(BaseAppView): |
|
264 | 265 | def __init__(self, context, request): |
|
265 | 266 | super(UserGroupAppView, self).__init__(context, request) |
|
266 | 267 | self.db_user_group = request.db_user_group |
|
267 | 268 | self.db_user_group_name = self.db_user_group.users_group_name |
|
268 | 269 | |
|
269 | 270 | |
|
271 | class UserAppView(BaseAppView): | |
|
272 | def __init__(self, context, request): | |
|
273 | super(UserAppView, self).__init__(context, request) | |
|
274 | self.db_user = request.db_user | |
|
275 | self.db_user_id = self.db_user.user_id | |
|
276 | ||
|
277 | _ = self.request.translate | |
|
278 | if not request.db_user_supports_default: | |
|
279 | if self.db_user.username == User.DEFAULT_USER: | |
|
280 | h.flash(_("Editing user `{}` is disabled.".format( | |
|
281 | User.DEFAULT_USER)), category='warning') | |
|
282 | raise HTTPFound(h.route_path('users')) | |
|
283 | ||
|
284 | ||
|
270 | 285 | class DataGridAppView(object): |
|
271 | 286 | """ |
|
272 | 287 | Common class to have re-usable grid rendering components |
|
273 | 288 | """ |
|
274 | 289 | |
|
275 | 290 | def _extract_ordering(self, request, column_map=None): |
|
276 | 291 | column_map = column_map or {} |
|
277 | 292 | column_index = safe_int(request.GET.get('order[0][column]')) |
|
278 | 293 | order_dir = request.GET.get( |
|
279 | 294 | 'order[0][dir]', 'desc') |
|
280 | 295 | order_by = request.GET.get( |
|
281 | 296 | 'columns[%s][data][sort]' % column_index, 'name_raw') |
|
282 | 297 | |
|
283 | 298 | # translate datatable to DB columns |
|
284 | 299 | order_by = column_map.get(order_by) or order_by |
|
285 | 300 | |
|
286 | 301 | search_q = request.GET.get('search[value]') |
|
287 | 302 | return search_q, order_by, order_dir |
|
288 | 303 | |
|
289 | 304 | def _extract_chunk(self, request): |
|
290 | 305 | start = safe_int(request.GET.get('start'), 0) |
|
291 | 306 | length = safe_int(request.GET.get('length'), 25) |
|
292 | 307 | draw = safe_int(request.GET.get('draw')) |
|
293 | 308 | return draw, start, length |
|
294 | 309 | |
|
295 | 310 | def _get_order_col(self, order_by, model): |
|
296 | 311 | if isinstance(order_by, basestring): |
|
297 | 312 | try: |
|
298 | 313 | return operator.attrgetter(order_by)(model) |
|
299 | 314 | except AttributeError: |
|
300 | 315 | return None |
|
301 | 316 | else: |
|
302 | 317 | return order_by |
|
303 | 318 | |
|
304 | 319 | |
|
305 | 320 | class BaseReferencesView(RepoAppView): |
|
306 | 321 | """ |
|
307 | 322 | Base for reference view for branches, tags and bookmarks. |
|
308 | 323 | """ |
|
309 | 324 | def load_default_context(self): |
|
310 | 325 | c = self._get_local_tmpl_context() |
|
311 | 326 | |
|
312 | 327 | self._register_global_c(c) |
|
313 | 328 | return c |
|
314 | 329 | |
|
315 | 330 | def load_refs_context(self, ref_items, partials_template): |
|
316 | 331 | _render = self.request.get_partial_renderer(partials_template) |
|
317 | 332 | pre_load = ["author", "date", "message"] |
|
318 | 333 | |
|
319 | 334 | is_svn = h.is_svn(self.rhodecode_vcs_repo) |
|
320 | 335 | is_hg = h.is_hg(self.rhodecode_vcs_repo) |
|
321 | 336 | |
|
322 | 337 | format_ref_id = get_format_ref_id(self.rhodecode_vcs_repo) |
|
323 | 338 | |
|
324 | 339 | closed_refs = {} |
|
325 | 340 | if is_hg: |
|
326 | 341 | closed_refs = self.rhodecode_vcs_repo.branches_closed |
|
327 | 342 | |
|
328 | 343 | data = [] |
|
329 | 344 | for ref_name, commit_id in ref_items: |
|
330 | 345 | commit = self.rhodecode_vcs_repo.get_commit( |
|
331 | 346 | commit_id=commit_id, pre_load=pre_load) |
|
332 | 347 | closed = ref_name in closed_refs |
|
333 | 348 | |
|
334 | 349 | # TODO: johbo: Unify generation of reference links |
|
335 | 350 | use_commit_id = '/' in ref_name or is_svn |
|
336 | 351 | |
|
337 | 352 | if use_commit_id: |
|
338 | 353 | files_url = h.route_path( |
|
339 | 354 | 'repo_files', |
|
340 | 355 | repo_name=self.db_repo_name, |
|
341 | 356 | f_path=ref_name if is_svn else '', |
|
342 | 357 | commit_id=commit_id) |
|
343 | 358 | |
|
344 | 359 | else: |
|
345 | 360 | files_url = h.route_path( |
|
346 | 361 | 'repo_files', |
|
347 | 362 | repo_name=self.db_repo_name, |
|
348 | 363 | f_path=ref_name if is_svn else '', |
|
349 | 364 | commit_id=ref_name, |
|
350 | 365 | _query=dict(at=ref_name)) |
|
351 | 366 | |
|
352 | 367 | data.append({ |
|
353 | 368 | "name": _render('name', ref_name, files_url, closed), |
|
354 | 369 | "name_raw": ref_name, |
|
355 | 370 | "date": _render('date', commit.date), |
|
356 | 371 | "date_raw": datetime_to_time(commit.date), |
|
357 | 372 | "author": _render('author', commit.author), |
|
358 | 373 | "commit": _render( |
|
359 | 374 | 'commit', commit.message, commit.raw_id, commit.idx), |
|
360 | 375 | "commit_raw": commit.idx, |
|
361 | 376 | "compare": _render( |
|
362 | 377 | 'compare', format_ref_id(ref_name, commit.raw_id)), |
|
363 | 378 | }) |
|
364 | 379 | |
|
365 | 380 | return data |
|
366 | 381 | |
|
367 | 382 | |
|
368 | 383 | class RepoRoutePredicate(object): |
|
369 | 384 | def __init__(self, val, config): |
|
370 | 385 | self.val = val |
|
371 | 386 | |
|
372 | 387 | def text(self): |
|
373 | 388 | return 'repo_route = %s' % self.val |
|
374 | 389 | |
|
375 | 390 | phash = text |
|
376 | 391 | |
|
377 | 392 | def __call__(self, info, request): |
|
378 | 393 | |
|
379 | 394 | if hasattr(request, 'vcs_call'): |
|
380 | 395 | # skip vcs calls |
|
381 | 396 | return |
|
382 | 397 | |
|
383 | 398 | repo_name = info['match']['repo_name'] |
|
384 | 399 | repo_model = repo.RepoModel() |
|
385 | 400 | by_name_match = repo_model.get_by_repo_name(repo_name, cache=True) |
|
386 | 401 | |
|
387 | 402 | def redirect_if_creating(db_repo): |
|
388 | 403 | if db_repo.repo_state in [repo.Repository.STATE_PENDING]: |
|
389 | 404 | raise HTTPFound( |
|
390 | 405 | request.route_path('repo_creating', |
|
391 | 406 | repo_name=db_repo.repo_name)) |
|
392 | 407 | |
|
393 | 408 | if by_name_match: |
|
394 | 409 | # register this as request object we can re-use later |
|
395 | 410 | request.db_repo = by_name_match |
|
396 | 411 | redirect_if_creating(by_name_match) |
|
397 | 412 | return True |
|
398 | 413 | |
|
399 | 414 | by_id_match = repo_model.get_repo_by_id(repo_name) |
|
400 | 415 | if by_id_match: |
|
401 | 416 | request.db_repo = by_id_match |
|
402 | 417 | redirect_if_creating(by_id_match) |
|
403 | 418 | return True |
|
404 | 419 | |
|
405 | 420 | return False |
|
406 | 421 | |
|
407 | 422 | |
|
408 | 423 | class RepoTypeRoutePredicate(object): |
|
409 | 424 | def __init__(self, val, config): |
|
410 | 425 | self.val = val or ['hg', 'git', 'svn'] |
|
411 | 426 | |
|
412 | 427 | def text(self): |
|
413 | 428 | return 'repo_accepted_type = %s' % self.val |
|
414 | 429 | |
|
415 | 430 | phash = text |
|
416 | 431 | |
|
417 | 432 | def __call__(self, info, request): |
|
418 | 433 | if hasattr(request, 'vcs_call'): |
|
419 | 434 | # skip vcs calls |
|
420 | 435 | return |
|
421 | 436 | |
|
422 | 437 | rhodecode_db_repo = request.db_repo |
|
423 | 438 | |
|
424 | 439 | log.debug( |
|
425 | 440 | '%s checking repo type for %s in %s', |
|
426 | 441 | self.__class__.__name__, rhodecode_db_repo.repo_type, self.val) |
|
427 | 442 | |
|
428 | 443 | if rhodecode_db_repo.repo_type in self.val: |
|
429 | 444 | return True |
|
430 | 445 | else: |
|
431 | 446 | log.warning('Current view is not supported for repo type:%s', |
|
432 | 447 | rhodecode_db_repo.repo_type) |
|
433 | 448 | # |
|
434 | 449 | # h.flash(h.literal( |
|
435 | 450 | # _('Action not supported for %s.' % rhodecode_repo.alias)), |
|
436 | 451 | # category='warning') |
|
437 | 452 | # return redirect( |
|
438 | 453 | # route_path('repo_summary', repo_name=cls.rhodecode_db_repo.repo_name)) |
|
439 | 454 | |
|
440 | 455 | return False |
|
441 | 456 | |
|
442 | 457 | |
|
443 | 458 | class RepoGroupRoutePredicate(object): |
|
444 | 459 | def __init__(self, val, config): |
|
445 | 460 | self.val = val |
|
446 | 461 | |
|
447 | 462 | def text(self): |
|
448 | 463 | return 'repo_group_route = %s' % self.val |
|
449 | 464 | |
|
450 | 465 | phash = text |
|
451 | 466 | |
|
452 | 467 | def __call__(self, info, request): |
|
453 | 468 | if hasattr(request, 'vcs_call'): |
|
454 | 469 | # skip vcs calls |
|
455 | 470 | return |
|
456 | 471 | |
|
457 | 472 | repo_group_name = info['match']['repo_group_name'] |
|
458 | 473 | repo_group_model = repo_group.RepoGroupModel() |
|
459 | 474 | by_name_match = repo_group_model.get_by_group_name( |
|
460 | 475 | repo_group_name, cache=True) |
|
461 | 476 | |
|
462 | 477 | if by_name_match: |
|
463 | 478 | # register this as request object we can re-use later |
|
464 | 479 | request.db_repo_group = by_name_match |
|
465 | 480 | return True |
|
466 | 481 | |
|
467 | 482 | return False |
|
468 | 483 | |
|
469 | 484 | |
|
470 | 485 | class UserGroupRoutePredicate(object): |
|
471 | 486 | def __init__(self, val, config): |
|
472 | 487 | self.val = val |
|
473 | 488 | |
|
474 | 489 | def text(self): |
|
475 | 490 | return 'user_group_route = %s' % self.val |
|
476 | 491 | |
|
477 | 492 | phash = text |
|
478 | 493 | |
|
479 | 494 | def __call__(self, info, request): |
|
480 | 495 | if hasattr(request, 'vcs_call'): |
|
481 | 496 | # skip vcs calls |
|
482 | 497 | return |
|
483 | 498 | |
|
484 | 499 | user_group_id = info['match']['user_group_id'] |
|
485 | 500 | user_group_model = user_group.UserGroup() |
|
486 |
by_ |
|
|
501 | by_id_match = user_group_model.get( | |
|
487 | 502 | user_group_id, cache=True) |
|
488 | 503 | |
|
489 |
if by_ |
|
|
504 | if by_id_match: | |
|
490 | 505 | # register this as request object we can re-use later |
|
491 |
request.db_user_group = by_ |
|
|
506 | request.db_user_group = by_id_match | |
|
492 | 507 | return True |
|
493 | 508 | |
|
494 | 509 | return False |
|
495 | 510 | |
|
496 | 511 | |
|
512 | class UserRoutePredicateBase(object): | |
|
513 | supports_default = None | |
|
514 | ||
|
515 | def __init__(self, val, config): | |
|
516 | self.val = val | |
|
517 | ||
|
518 | def text(self): | |
|
519 | raise NotImplementedError() | |
|
520 | ||
|
521 | def __call__(self, info, request): | |
|
522 | if hasattr(request, 'vcs_call'): | |
|
523 | # skip vcs calls | |
|
524 | return | |
|
525 | ||
|
526 | user_id = info['match']['user_id'] | |
|
527 | user_model = user.User() | |
|
528 | by_id_match = user_model.get( | |
|
529 | user_id, cache=True) | |
|
530 | ||
|
531 | if by_id_match: | |
|
532 | # register this as request object we can re-use later | |
|
533 | request.db_user = by_id_match | |
|
534 | request.db_user_supports_default = self.supports_default | |
|
535 | return True | |
|
536 | ||
|
537 | return False | |
|
538 | ||
|
539 | ||
|
540 | class UserRoutePredicate(UserRoutePredicateBase): | |
|
541 | supports_default = False | |
|
542 | ||
|
543 | def text(self): | |
|
544 | return 'user_route = %s' % self.val | |
|
545 | ||
|
546 | phash = text | |
|
547 | ||
|
548 | ||
|
549 | class UserRouteWithDefaultPredicate(UserRoutePredicateBase): | |
|
550 | supports_default = True | |
|
551 | ||
|
552 | def text(self): | |
|
553 | return 'user_with_default_route = %s' % self.val | |
|
554 | ||
|
555 | phash = text | |
|
556 | ||
|
557 | ||
|
497 | 558 | def includeme(config): |
|
498 | 559 | config.add_route_predicate( |
|
499 | 560 | 'repo_route', RepoRoutePredicate) |
|
500 | 561 | config.add_route_predicate( |
|
501 | 562 | 'repo_accepted_types', RepoTypeRoutePredicate) |
|
502 | 563 | config.add_route_predicate( |
|
503 | 564 | 'repo_group_route', RepoGroupRoutePredicate) |
|
504 | 565 | config.add_route_predicate( |
|
505 | 566 | 'user_group_route', UserGroupRoutePredicate) |
|
567 | config.add_route_predicate( | |
|
568 | 'user_route_with_default', UserRouteWithDefaultPredicate) | |
|
569 | config.add_route_predicate( | |
|
570 | 'user_route', UserRoutePredicate) No newline at end of file |
@@ -1,253 +1,312 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | |
|
3 | 3 | # Copyright (C) 2016-2017 RhodeCode GmbH |
|
4 | 4 | # |
|
5 | 5 | # This program is free software: you can redistribute it and/or modify |
|
6 | 6 | # it under the terms of the GNU Affero General Public License, version 3 |
|
7 | 7 | # (only), as published by the Free Software Foundation. |
|
8 | 8 | # |
|
9 | 9 | # This program is distributed in the hope that it will be useful, |
|
10 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of |
|
11 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|
12 | 12 | # GNU General Public License for more details. |
|
13 | 13 | # |
|
14 | 14 | # You should have received a copy of the GNU Affero General Public License |
|
15 | 15 | # along with this program. If not, see <http://www.gnu.org/licenses/>. |
|
16 | 16 | # |
|
17 | 17 | # This program is dual-licensed. If you wish to learn more about the |
|
18 | 18 | # RhodeCode Enterprise Edition, including its added features, Support services, |
|
19 | 19 | # and proprietary license terms, please see https://rhodecode.com/licenses/ |
|
20 | 20 | |
|
21 | 21 | |
|
22 | 22 | from rhodecode.apps.admin.navigation import NavigationRegistry |
|
23 | 23 | from rhodecode.config.routing import ADMIN_PREFIX |
|
24 | 24 | from rhodecode.lib.utils2 import str2bool |
|
25 | 25 | |
|
26 | 26 | |
|
27 | 27 | def admin_routes(config): |
|
28 | 28 | """ |
|
29 | 29 | Admin prefixed routes |
|
30 | 30 | """ |
|
31 | 31 | |
|
32 | 32 | config.add_route( |
|
33 | 33 | name='admin_audit_logs', |
|
34 | 34 | pattern='/audit_logs') |
|
35 | 35 | |
|
36 | 36 | config.add_route( |
|
37 | 37 | name='admin_audit_log_entry', |
|
38 | 38 | pattern='/audit_logs/{audit_log_id}') |
|
39 | 39 | |
|
40 | 40 | config.add_route( |
|
41 | 41 | name='pull_requests_global_0', # backward compat |
|
42 | 42 | pattern='/pull_requests/{pull_request_id:\d+}') |
|
43 | 43 | config.add_route( |
|
44 | 44 | name='pull_requests_global_1', # backward compat |
|
45 | 45 | pattern='/pull-requests/{pull_request_id:\d+}') |
|
46 | 46 | config.add_route( |
|
47 | 47 | name='pull_requests_global', |
|
48 | 48 | pattern='/pull-request/{pull_request_id:\d+}') |
|
49 | 49 | |
|
50 | 50 | config.add_route( |
|
51 | 51 | name='admin_settings_open_source', |
|
52 | 52 | pattern='/settings/open_source') |
|
53 | 53 | config.add_route( |
|
54 | 54 | name='admin_settings_vcs_svn_generate_cfg', |
|
55 | 55 | pattern='/settings/vcs/svn_generate_cfg') |
|
56 | 56 | |
|
57 | 57 | config.add_route( |
|
58 | 58 | name='admin_settings_system', |
|
59 | 59 | pattern='/settings/system') |
|
60 | 60 | config.add_route( |
|
61 | 61 | name='admin_settings_system_update', |
|
62 | 62 | pattern='/settings/system/updates') |
|
63 | 63 | |
|
64 | 64 | config.add_route( |
|
65 | 65 | name='admin_settings_sessions', |
|
66 | 66 | pattern='/settings/sessions') |
|
67 | 67 | config.add_route( |
|
68 | 68 | name='admin_settings_sessions_cleanup', |
|
69 | 69 | pattern='/settings/sessions/cleanup') |
|
70 | 70 | |
|
71 | 71 | config.add_route( |
|
72 | 72 | name='admin_settings_process_management', |
|
73 | 73 | pattern='/settings/process_management') |
|
74 | 74 | config.add_route( |
|
75 | 75 | name='admin_settings_process_management_signal', |
|
76 | 76 | pattern='/settings/process_management/signal') |
|
77 | 77 | |
|
78 | 78 | # default settings |
|
79 | 79 | config.add_route( |
|
80 | 80 | name='admin_defaults_repositories', |
|
81 | 81 | pattern='/defaults/repositories') |
|
82 | 82 | config.add_route( |
|
83 | 83 | name='admin_defaults_repositories_update', |
|
84 | 84 | pattern='/defaults/repositories/update') |
|
85 | 85 | |
|
86 | 86 | # global permissions |
|
87 | 87 | |
|
88 | 88 | config.add_route( |
|
89 | 89 | name='admin_permissions_application', |
|
90 | 90 | pattern='/permissions/application') |
|
91 | 91 | config.add_route( |
|
92 | 92 | name='admin_permissions_application_update', |
|
93 | 93 | pattern='/permissions/application/update') |
|
94 | 94 | |
|
95 | 95 | config.add_route( |
|
96 | 96 | name='admin_permissions_global', |
|
97 | 97 | pattern='/permissions/global') |
|
98 | 98 | config.add_route( |
|
99 | 99 | name='admin_permissions_global_update', |
|
100 | 100 | pattern='/permissions/global/update') |
|
101 | 101 | |
|
102 | 102 | config.add_route( |
|
103 | 103 | name='admin_permissions_object', |
|
104 | 104 | pattern='/permissions/object') |
|
105 | 105 | config.add_route( |
|
106 | 106 | name='admin_permissions_object_update', |
|
107 | 107 | pattern='/permissions/object/update') |
|
108 | 108 | |
|
109 | 109 | config.add_route( |
|
110 | 110 | name='admin_permissions_ips', |
|
111 | 111 | pattern='/permissions/ips') |
|
112 | 112 | |
|
113 | 113 | config.add_route( |
|
114 | 114 | name='admin_permissions_overview', |
|
115 | 115 | pattern='/permissions/overview') |
|
116 | 116 | |
|
117 | 117 | config.add_route( |
|
118 | 118 | name='admin_permissions_auth_token_access', |
|
119 | 119 | pattern='/permissions/auth_token_access') |
|
120 | 120 | |
|
121 | 121 | config.add_route( |
|
122 | 122 | name='admin_permissions_ssh_keys', |
|
123 | 123 | pattern='/permissions/ssh_keys') |
|
124 | 124 | config.add_route( |
|
125 | 125 | name='admin_permissions_ssh_keys_data', |
|
126 | 126 | pattern='/permissions/ssh_keys/data') |
|
127 | 127 | config.add_route( |
|
128 | 128 | name='admin_permissions_ssh_keys_update', |
|
129 | 129 | pattern='/permissions/ssh_keys/update') |
|
130 | 130 | |
|
131 | 131 | # users admin |
|
132 | 132 | config.add_route( |
|
133 | 133 | name='users', |
|
134 | 134 | pattern='/users') |
|
135 | 135 | |
|
136 | 136 | config.add_route( |
|
137 | 137 | name='users_data', |
|
138 | 138 | pattern='/users_data') |
|
139 | 139 | |
|
140 | config.add_route( | |
|
141 | name='users_create', | |
|
142 | pattern='/users/create') | |
|
143 | ||
|
144 | config.add_route( | |
|
145 | name='users_new', | |
|
146 | pattern='/users/new') | |
|
147 | ||
|
148 | # user management | |
|
149 | config.add_route( | |
|
150 | name='user_edit', | |
|
151 | pattern='/users/{user_id:\d+}/edit', | |
|
152 | user_route=True) | |
|
153 | config.add_route( | |
|
154 | name='user_edit_advanced', | |
|
155 | pattern='/users/{user_id:\d+}/edit/advanced', | |
|
156 | user_route=True) | |
|
157 | config.add_route( | |
|
158 | name='user_edit_global_perms', | |
|
159 | pattern='/users/{user_id:\d+}/edit/global_permissions', | |
|
160 | user_route=True) | |
|
161 | config.add_route( | |
|
162 | name='user_edit_global_perms_update', | |
|
163 | pattern='/users/{user_id:\d+}/edit/global_permissions/update', | |
|
164 | user_route=True) | |
|
165 | config.add_route( | |
|
166 | name='user_update', | |
|
167 | pattern='/users/{user_id:\d+}/update', | |
|
168 | user_route=True) | |
|
169 | config.add_route( | |
|
170 | name='user_delete', | |
|
171 | pattern='/users/{user_id:\d+}/delete', | |
|
172 | user_route=True) | |
|
173 | config.add_route( | |
|
174 | name='user_force_password_reset', | |
|
175 | pattern='/users/{user_id:\d+}/password_reset', | |
|
176 | user_route=True) | |
|
177 | config.add_route( | |
|
178 | name='user_create_personal_repo_group', | |
|
179 | pattern='/users/{user_id:\d+}/create_repo_group', | |
|
180 | user_route=True) | |
|
181 | ||
|
140 | 182 | # user auth tokens |
|
141 | 183 | config.add_route( |
|
142 | 184 | name='edit_user_auth_tokens', |
|
143 |
pattern='/users/{user_id:\d+}/edit/auth_tokens' |
|
|
185 | pattern='/users/{user_id:\d+}/edit/auth_tokens', | |
|
186 | user_route=True) | |
|
144 | 187 | config.add_route( |
|
145 | 188 | name='edit_user_auth_tokens_add', |
|
146 |
pattern='/users/{user_id:\d+}/edit/auth_tokens/new' |
|
|
189 | pattern='/users/{user_id:\d+}/edit/auth_tokens/new', | |
|
190 | user_route=True) | |
|
147 | 191 | config.add_route( |
|
148 | 192 | name='edit_user_auth_tokens_delete', |
|
149 |
pattern='/users/{user_id:\d+}/edit/auth_tokens/delete' |
|
|
193 | pattern='/users/{user_id:\d+}/edit/auth_tokens/delete', | |
|
194 | user_route=True) | |
|
150 | 195 | |
|
151 | 196 | # user ssh keys |
|
152 | 197 | config.add_route( |
|
153 | 198 | name='edit_user_ssh_keys', |
|
154 |
pattern='/users/{user_id:\d+}/edit/ssh_keys' |
|
|
199 | pattern='/users/{user_id:\d+}/edit/ssh_keys', | |
|
200 | user_route=True) | |
|
155 | 201 | config.add_route( |
|
156 | 202 | name='edit_user_ssh_keys_generate_keypair', |
|
157 |
pattern='/users/{user_id:\d+}/edit/ssh_keys/generate' |
|
|
203 | pattern='/users/{user_id:\d+}/edit/ssh_keys/generate', | |
|
204 | user_route=True) | |
|
158 | 205 | config.add_route( |
|
159 | 206 | name='edit_user_ssh_keys_add', |
|
160 |
pattern='/users/{user_id:\d+}/edit/ssh_keys/new' |
|
|
207 | pattern='/users/{user_id:\d+}/edit/ssh_keys/new', | |
|
208 | user_route=True) | |
|
161 | 209 | config.add_route( |
|
162 | 210 | name='edit_user_ssh_keys_delete', |
|
163 |
pattern='/users/{user_id:\d+}/edit/ssh_keys/delete' |
|
|
211 | pattern='/users/{user_id:\d+}/edit/ssh_keys/delete', | |
|
212 | user_route=True) | |
|
164 | 213 | |
|
165 | 214 | # user emails |
|
166 | 215 | config.add_route( |
|
167 | 216 | name='edit_user_emails', |
|
168 |
pattern='/users/{user_id:\d+}/edit/emails' |
|
|
217 | pattern='/users/{user_id:\d+}/edit/emails', | |
|
218 | user_route=True) | |
|
169 | 219 | config.add_route( |
|
170 | 220 | name='edit_user_emails_add', |
|
171 |
pattern='/users/{user_id:\d+}/edit/emails/new' |
|
|
221 | pattern='/users/{user_id:\d+}/edit/emails/new', | |
|
222 | user_route=True) | |
|
172 | 223 | config.add_route( |
|
173 | 224 | name='edit_user_emails_delete', |
|
174 |
pattern='/users/{user_id:\d+}/edit/emails/delete' |
|
|
225 | pattern='/users/{user_id:\d+}/edit/emails/delete', | |
|
226 | user_route=True) | |
|
175 | 227 | |
|
176 | 228 | # user IPs |
|
177 | 229 | config.add_route( |
|
178 | 230 | name='edit_user_ips', |
|
179 |
pattern='/users/{user_id:\d+}/edit/ips' |
|
|
231 | pattern='/users/{user_id:\d+}/edit/ips', | |
|
232 | user_route=True) | |
|
180 | 233 | config.add_route( |
|
181 | 234 | name='edit_user_ips_add', |
|
182 |
pattern='/users/{user_id:\d+}/edit/ips/new' |
|
|
235 | pattern='/users/{user_id:\d+}/edit/ips/new', | |
|
236 | user_route_with_default=True) # enabled for default user too | |
|
183 | 237 | config.add_route( |
|
184 | 238 | name='edit_user_ips_delete', |
|
185 |
pattern='/users/{user_id:\d+}/edit/ips/delete' |
|
|
239 | pattern='/users/{user_id:\d+}/edit/ips/delete', | |
|
240 | user_route_with_default=True) # enabled for default user too | |
|
186 | 241 | |
|
187 | 242 | # user perms |
|
188 | 243 | config.add_route( |
|
189 | 244 | name='edit_user_perms_summary', |
|
190 |
pattern='/users/{user_id:\d+}/edit/permissions_summary' |
|
|
245 | pattern='/users/{user_id:\d+}/edit/permissions_summary', | |
|
246 | user_route=True) | |
|
191 | 247 | config.add_route( |
|
192 | 248 | name='edit_user_perms_summary_json', |
|
193 |
pattern='/users/{user_id:\d+}/edit/permissions_summary/json' |
|
|
249 | pattern='/users/{user_id:\d+}/edit/permissions_summary/json', | |
|
250 | user_route=True) | |
|
194 | 251 | |
|
195 | 252 | # user user groups management |
|
196 | 253 | config.add_route( |
|
197 | 254 | name='edit_user_groups_management', |
|
198 |
pattern='/users/{user_id:\d+}/edit/groups_management' |
|
|
255 | pattern='/users/{user_id:\d+}/edit/groups_management', | |
|
256 | user_route=True) | |
|
199 | 257 | |
|
200 | 258 | config.add_route( |
|
201 | 259 | name='edit_user_groups_management_updates', |
|
202 |
pattern='/users/{user_id:\d+}/edit/edit_user_groups_management/updates' |
|
|
260 | pattern='/users/{user_id:\d+}/edit/edit_user_groups_management/updates', | |
|
261 | user_route=True) | |
|
203 | 262 | |
|
204 | 263 | # user audit logs |
|
205 | 264 | config.add_route( |
|
206 | 265 | name='edit_user_audit_logs', |
|
207 | pattern='/users/{user_id:\d+}/edit/audit') | |
|
266 | pattern='/users/{user_id:\d+}/edit/audit', user_route=True) | |
|
208 | 267 | |
|
209 | 268 | # user-groups admin |
|
210 | 269 | config.add_route( |
|
211 | 270 | name='user_groups', |
|
212 | 271 | pattern='/user_groups') |
|
213 | 272 | |
|
214 | 273 | config.add_route( |
|
215 | 274 | name='user_groups_data', |
|
216 | 275 | pattern='/user_groups_data') |
|
217 | 276 | |
|
218 | 277 | config.add_route( |
|
219 | 278 | name='user_groups_new', |
|
220 | 279 | pattern='/user_groups/new') |
|
221 | 280 | |
|
222 | 281 | config.add_route( |
|
223 | 282 | name='user_groups_create', |
|
224 | 283 | pattern='/user_groups/create') |
|
225 | 284 | |
|
226 | 285 | # repos admin |
|
227 | 286 | config.add_route( |
|
228 | 287 | name='repos', |
|
229 | 288 | pattern='/repos') |
|
230 | 289 | |
|
231 | 290 | config.add_route( |
|
232 | 291 | name='repo_new', |
|
233 | 292 | pattern='/repos/new') |
|
234 | 293 | |
|
235 | 294 | config.add_route( |
|
236 | 295 | name='repo_create', |
|
237 | 296 | pattern='/repos/create') |
|
238 | 297 | |
|
239 | 298 | |
|
240 | 299 | def includeme(config): |
|
241 | 300 | settings = config.get_settings() |
|
242 | 301 | |
|
243 | 302 | # Create admin navigation registry and add it to the pyramid registry. |
|
244 | 303 | labs_active = str2bool(settings.get('labs_settings_active', False)) |
|
245 | 304 | navigation_registry = NavigationRegistry(labs_active=labs_active) |
|
246 | 305 | config.registry.registerUtility(navigation_registry) |
|
247 | 306 | |
|
248 | 307 | # main admin routes |
|
249 | 308 | config.add_route(name='admin_home', pattern=ADMIN_PREFIX) |
|
250 | 309 | config.include(admin_routes, route_prefix=ADMIN_PREFIX) |
|
251 | 310 | |
|
252 | 311 | # Scan module for configuration decorators. |
|
253 | 312 | config.scan('.views', ignore='.tests') |
This diff has been collapsed as it changes many lines, (516 lines changed) Show them Hide them | |||
@@ -1,281 +1,783 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | |
|
3 | 3 | # Copyright (C) 2010-2017 RhodeCode GmbH |
|
4 | 4 | # |
|
5 | 5 | # This program is free software: you can redistribute it and/or modify |
|
6 | 6 | # it under the terms of the GNU Affero General Public License, version 3 |
|
7 | 7 | # (only), as published by the Free Software Foundation. |
|
8 | 8 | # |
|
9 | 9 | # This program is distributed in the hope that it will be useful, |
|
10 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of |
|
11 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|
12 | 12 | # GNU General Public License for more details. |
|
13 | 13 | # |
|
14 | 14 | # You should have received a copy of the GNU Affero General Public License |
|
15 | 15 | # along with this program. If not, see <http://www.gnu.org/licenses/>. |
|
16 | 16 | # |
|
17 | 17 | # This program is dual-licensed. If you wish to learn more about the |
|
18 | 18 | # RhodeCode Enterprise Edition, including its added features, Support services, |
|
19 | 19 | # and proprietary license terms, please see https://rhodecode.com/licenses/ |
|
20 | 20 | |
|
21 | 21 | import pytest |
|
22 | from sqlalchemy.orm.exc import NoResultFound | |
|
22 | 23 | |
|
23 | from rhodecode.model.db import User, UserApiKeys, UserEmailMap | |
|
24 | from rhodecode.lib import auth | |
|
25 | from rhodecode.lib import helpers as h | |
|
26 | from rhodecode.model import validators | |
|
27 | from rhodecode.model.db import User, UserApiKeys, UserEmailMap, Repository | |
|
24 | 28 | from rhodecode.model.meta import Session |
|
25 | 29 | from rhodecode.model.user import UserModel |
|
26 | 30 | |
|
27 | 31 | from rhodecode.tests import ( |
|
28 | 32 | TestController, TEST_USER_REGULAR_LOGIN, assert_session_flash) |
|
29 | 33 | from rhodecode.tests.fixture import Fixture |
|
30 | 34 | |
|
31 | 35 | fixture = Fixture() |
|
32 | 36 | |
|
33 | 37 | |
|
34 | 38 | def route_path(name, params=None, **kwargs): |
|
35 | 39 | import urllib |
|
36 | 40 | from rhodecode.apps._base import ADMIN_PREFIX |
|
37 | 41 | |
|
38 | 42 | base_url = { |
|
39 | 43 | 'users': |
|
40 | 44 | ADMIN_PREFIX + '/users', |
|
41 | 45 | 'users_data': |
|
42 | 46 | ADMIN_PREFIX + '/users_data', |
|
47 | 'users_create': | |
|
48 | ADMIN_PREFIX + '/users/create', | |
|
49 | 'users_new': | |
|
50 | ADMIN_PREFIX + '/users/new', | |
|
51 | 'user_edit': | |
|
52 | ADMIN_PREFIX + '/users/{user_id}/edit', | |
|
53 | 'user_edit_advanced': | |
|
54 | ADMIN_PREFIX + '/users/{user_id}/edit/advanced', | |
|
55 | 'user_edit_global_perms': | |
|
56 | ADMIN_PREFIX + '/users/{user_id}/edit/global_permissions', | |
|
57 | 'user_edit_global_perms_update': | |
|
58 | ADMIN_PREFIX + '/users/{user_id}/edit/global_permissions/update', | |
|
59 | 'user_update': | |
|
60 | ADMIN_PREFIX + '/users/{user_id}/update', | |
|
61 | 'user_delete': | |
|
62 | ADMIN_PREFIX + '/users/{user_id}/delete', | |
|
63 | 'user_force_password_reset': | |
|
64 | ADMIN_PREFIX + '/users/{user_id}/password_reset', | |
|
65 | 'user_create_personal_repo_group': | |
|
66 | ADMIN_PREFIX + '/users/{user_id}/create_repo_group', | |
|
67 | ||
|
43 | 68 | 'edit_user_auth_tokens': |
|
44 | 69 | ADMIN_PREFIX + '/users/{user_id}/edit/auth_tokens', |
|
45 | 70 | 'edit_user_auth_tokens_add': |
|
46 | 71 | ADMIN_PREFIX + '/users/{user_id}/edit/auth_tokens/new', |
|
47 | 72 | 'edit_user_auth_tokens_delete': |
|
48 | 73 | ADMIN_PREFIX + '/users/{user_id}/edit/auth_tokens/delete', |
|
49 | 74 | |
|
50 | 75 | 'edit_user_emails': |
|
51 | 76 | ADMIN_PREFIX + '/users/{user_id}/edit/emails', |
|
52 | 77 | 'edit_user_emails_add': |
|
53 | 78 | ADMIN_PREFIX + '/users/{user_id}/edit/emails/new', |
|
54 | 79 | 'edit_user_emails_delete': |
|
55 | 80 | ADMIN_PREFIX + '/users/{user_id}/edit/emails/delete', |
|
56 | 81 | |
|
57 | 82 | 'edit_user_ips': |
|
58 | 83 | ADMIN_PREFIX + '/users/{user_id}/edit/ips', |
|
59 | 84 | 'edit_user_ips_add': |
|
60 | 85 | ADMIN_PREFIX + '/users/{user_id}/edit/ips/new', |
|
61 | 86 | 'edit_user_ips_delete': |
|
62 | 87 | ADMIN_PREFIX + '/users/{user_id}/edit/ips/delete', |
|
88 | ||
|
89 | 'edit_user_perms_summary': | |
|
90 | ADMIN_PREFIX + '/users/{user_id}/edit/permissions_summary', | |
|
91 | 'edit_user_perms_summary_json': | |
|
92 | ADMIN_PREFIX + '/users/{user_id}/edit/permissions_summary/json', | |
|
93 | ||
|
94 | 'edit_user_audit_logs': | |
|
95 | ADMIN_PREFIX + '/users/{user_id}/edit/audit', | |
|
96 | ||
|
63 | 97 | }[name].format(**kwargs) |
|
64 | 98 | |
|
65 | 99 | if params: |
|
66 | 100 | base_url = '{}?{}'.format(base_url, urllib.urlencode(params)) |
|
67 | 101 | return base_url |
|
68 | 102 | |
|
69 | 103 | |
|
70 | 104 | class TestAdminUsersView(TestController): |
|
71 | 105 | |
|
72 | 106 | def test_show_users(self): |
|
73 | 107 | self.log_user() |
|
74 | 108 | self.app.get(route_path('users')) |
|
75 | 109 | |
|
76 | 110 | def test_show_users_data(self, xhr_header): |
|
77 | 111 | self.log_user() |
|
78 | 112 | response = self.app.get(route_path( |
|
79 | 113 | 'users_data'), extra_environ=xhr_header) |
|
80 | 114 | |
|
81 | 115 | all_users = User.query().filter( |
|
82 | 116 | User.username != User.DEFAULT_USER).count() |
|
83 | 117 | assert response.json['recordsTotal'] == all_users |
|
84 | 118 | |
|
85 | 119 | def test_show_users_data_filtered(self, xhr_header): |
|
86 | 120 | self.log_user() |
|
87 | 121 | response = self.app.get(route_path( |
|
88 | 122 | 'users_data', params={'search[value]': 'empty_search'}), |
|
89 | 123 | extra_environ=xhr_header) |
|
90 | 124 | |
|
91 | 125 | all_users = User.query().filter( |
|
92 | 126 | User.username != User.DEFAULT_USER).count() |
|
93 | 127 | assert response.json['recordsTotal'] == all_users |
|
94 | 128 | assert response.json['recordsFiltered'] == 0 |
|
95 | 129 | |
|
96 | 130 | def test_auth_tokens_default_user(self): |
|
97 | 131 | self.log_user() |
|
98 | 132 | user = User.get_default_user() |
|
99 | 133 | response = self.app.get( |
|
100 | 134 | route_path('edit_user_auth_tokens', user_id=user.user_id), |
|
101 | 135 | status=302) |
|
102 | 136 | |
|
103 | 137 | def test_auth_tokens(self): |
|
104 | 138 | self.log_user() |
|
105 | 139 | |
|
106 | 140 | user = User.get_by_username(TEST_USER_REGULAR_LOGIN) |
|
107 | 141 | response = self.app.get( |
|
108 | 142 | route_path('edit_user_auth_tokens', user_id=user.user_id)) |
|
109 | 143 | for token in user.auth_tokens: |
|
110 | 144 | response.mustcontain(token) |
|
111 | 145 | response.mustcontain('never') |
|
112 | 146 | |
|
113 | 147 | @pytest.mark.parametrize("desc, lifetime", [ |
|
114 | 148 | ('forever', -1), |
|
115 | 149 | ('5mins', 60*5), |
|
116 | 150 | ('30days', 60*60*24*30), |
|
117 | 151 | ]) |
|
118 | 152 | def test_add_auth_token(self, desc, lifetime, user_util): |
|
119 | 153 | self.log_user() |
|
120 | 154 | user = user_util.create_user() |
|
121 | 155 | user_id = user.user_id |
|
122 | 156 | |
|
123 | 157 | response = self.app.post( |
|
124 | 158 | route_path('edit_user_auth_tokens_add', user_id=user_id), |
|
125 | 159 | {'description': desc, 'lifetime': lifetime, |
|
126 | 160 | 'csrf_token': self.csrf_token}) |
|
127 | 161 | assert_session_flash(response, 'Auth token successfully created') |
|
128 | 162 | |
|
129 | 163 | response = response.follow() |
|
130 | 164 | user = User.get(user_id) |
|
131 | 165 | for auth_token in user.auth_tokens: |
|
132 | 166 | response.mustcontain(auth_token) |
|
133 | 167 | |
|
134 | 168 | def test_delete_auth_token(self, user_util): |
|
135 | 169 | self.log_user() |
|
136 | 170 | user = user_util.create_user() |
|
137 | 171 | user_id = user.user_id |
|
138 | 172 | keys = user.auth_tokens |
|
139 | 173 | assert 2 == len(keys) |
|
140 | 174 | |
|
141 | 175 | response = self.app.post( |
|
142 | 176 | route_path('edit_user_auth_tokens_add', user_id=user_id), |
|
143 | 177 | {'description': 'desc', 'lifetime': -1, |
|
144 | 178 | 'csrf_token': self.csrf_token}) |
|
145 | 179 | assert_session_flash(response, 'Auth token successfully created') |
|
146 | 180 | response.follow() |
|
147 | 181 | |
|
148 | 182 | # now delete our key |
|
149 | 183 | keys = UserApiKeys.query().filter(UserApiKeys.user_id == user_id).all() |
|
150 | 184 | assert 3 == len(keys) |
|
151 | 185 | |
|
152 | 186 | response = self.app.post( |
|
153 | 187 | route_path('edit_user_auth_tokens_delete', user_id=user_id), |
|
154 | 188 | {'del_auth_token': keys[0].user_api_key_id, |
|
155 | 189 | 'csrf_token': self.csrf_token}) |
|
156 | 190 | |
|
157 | 191 | assert_session_flash(response, 'Auth token successfully deleted') |
|
158 | 192 | keys = UserApiKeys.query().filter(UserApiKeys.user_id == user_id).all() |
|
159 | 193 | assert 2 == len(keys) |
|
160 | 194 | |
|
161 | 195 | def test_ips(self): |
|
162 | 196 | self.log_user() |
|
163 | 197 | user = User.get_by_username(TEST_USER_REGULAR_LOGIN) |
|
164 | 198 | response = self.app.get(route_path('edit_user_ips', user_id=user.user_id)) |
|
165 | 199 | response.mustcontain('All IP addresses are allowed') |
|
166 | 200 | |
|
167 | 201 | @pytest.mark.parametrize("test_name, ip, ip_range, failure", [ |
|
168 | 202 | ('127/24', '127.0.0.1/24', '127.0.0.0 - 127.0.0.255', False), |
|
169 | 203 | ('10/32', '10.0.0.10/32', '10.0.0.10 - 10.0.0.10', False), |
|
170 | 204 | ('0/16', '0.0.0.0/16', '0.0.0.0 - 0.0.255.255', False), |
|
171 | 205 | ('0/8', '0.0.0.0/8', '0.0.0.0 - 0.255.255.255', False), |
|
172 | 206 | ('127_bad_mask', '127.0.0.1/99', '127.0.0.1 - 127.0.0.1', True), |
|
173 | 207 | ('127_bad_ip', 'foobar', 'foobar', True), |
|
174 | 208 | ]) |
|
175 | 209 | def test_ips_add(self, user_util, test_name, ip, ip_range, failure): |
|
176 | 210 | self.log_user() |
|
177 | 211 | user = user_util.create_user(username=test_name) |
|
178 | 212 | user_id = user.user_id |
|
179 | 213 | |
|
180 | 214 | response = self.app.post( |
|
181 | 215 | route_path('edit_user_ips_add', user_id=user_id), |
|
182 | 216 | params={'new_ip': ip, 'csrf_token': self.csrf_token}) |
|
183 | 217 | |
|
184 | 218 | if failure: |
|
185 | 219 | assert_session_flash( |
|
186 | 220 | response, 'Please enter a valid IPv4 or IpV6 address') |
|
187 | 221 | response = self.app.get(route_path('edit_user_ips', user_id=user_id)) |
|
188 | 222 | |
|
189 | 223 | response.mustcontain(no=[ip]) |
|
190 | 224 | response.mustcontain(no=[ip_range]) |
|
191 | 225 | |
|
192 | 226 | else: |
|
193 | 227 | response = self.app.get(route_path('edit_user_ips', user_id=user_id)) |
|
194 | 228 | response.mustcontain(ip) |
|
195 | 229 | response.mustcontain(ip_range) |
|
196 | 230 | |
|
197 | 231 | def test_ips_delete(self, user_util): |
|
198 | 232 | self.log_user() |
|
199 | 233 | user = user_util.create_user() |
|
200 | 234 | user_id = user.user_id |
|
201 | 235 | ip = '127.0.0.1/32' |
|
202 | 236 | ip_range = '127.0.0.1 - 127.0.0.1' |
|
203 | 237 | new_ip = UserModel().add_extra_ip(user_id, ip) |
|
204 | 238 | Session().commit() |
|
205 | 239 | new_ip_id = new_ip.ip_id |
|
206 | 240 | |
|
207 | 241 | response = self.app.get(route_path('edit_user_ips', user_id=user_id)) |
|
208 | 242 | response.mustcontain(ip) |
|
209 | 243 | response.mustcontain(ip_range) |
|
210 | 244 | |
|
211 | 245 | self.app.post( |
|
212 | 246 | route_path('edit_user_ips_delete', user_id=user_id), |
|
213 | 247 | params={'del_ip_id': new_ip_id, 'csrf_token': self.csrf_token}) |
|
214 | 248 | |
|
215 | 249 | response = self.app.get(route_path('edit_user_ips', user_id=user_id)) |
|
216 | 250 | response.mustcontain('All IP addresses are allowed') |
|
217 | 251 | response.mustcontain(no=[ip]) |
|
218 | 252 | response.mustcontain(no=[ip_range]) |
|
219 | 253 | |
|
220 | 254 | def test_emails(self): |
|
221 | 255 | self.log_user() |
|
222 | 256 | user = User.get_by_username(TEST_USER_REGULAR_LOGIN) |
|
223 | response = self.app.get(route_path('edit_user_emails', user_id=user.user_id)) | |
|
257 | response = self.app.get( | |
|
258 | route_path('edit_user_emails', user_id=user.user_id)) | |
|
224 | 259 | response.mustcontain('No additional emails specified') |
|
225 | 260 | |
|
226 | 261 | def test_emails_add(self, user_util): |
|
227 | 262 | self.log_user() |
|
228 | 263 | user = user_util.create_user() |
|
229 | 264 | user_id = user.user_id |
|
230 | 265 | |
|
231 | 266 | self.app.post( |
|
232 | 267 | route_path('edit_user_emails_add', user_id=user_id), |
|
233 | 268 | params={'new_email': 'example@rhodecode.com', |
|
234 | 269 | 'csrf_token': self.csrf_token}) |
|
235 | 270 | |
|
236 | response = self.app.get(route_path('edit_user_emails', user_id=user_id)) | |
|
271 | response = self.app.get( | |
|
272 | route_path('edit_user_emails', user_id=user_id)) | |
|
237 | 273 | response.mustcontain('example@rhodecode.com') |
|
238 | 274 | |
|
239 | 275 | def test_emails_add_existing_email(self, user_util, user_regular): |
|
240 | 276 | existing_email = user_regular.email |
|
241 | 277 | |
|
242 | 278 | self.log_user() |
|
243 | 279 | user = user_util.create_user() |
|
244 | 280 | user_id = user.user_id |
|
245 | 281 | |
|
246 | 282 | response = self.app.post( |
|
247 | 283 | route_path('edit_user_emails_add', user_id=user_id), |
|
248 | 284 | params={'new_email': existing_email, |
|
249 | 285 | 'csrf_token': self.csrf_token}) |
|
250 | 286 | assert_session_flash( |
|
251 | 287 | response, 'This e-mail address is already taken') |
|
252 | 288 | |
|
253 | response = self.app.get(route_path('edit_user_emails', user_id=user_id)) | |
|
289 | response = self.app.get( | |
|
290 | route_path('edit_user_emails', user_id=user_id)) | |
|
254 | 291 | response.mustcontain(no=[existing_email]) |
|
255 | 292 | |
|
256 | 293 | def test_emails_delete(self, user_util): |
|
257 | 294 | self.log_user() |
|
258 | 295 | user = user_util.create_user() |
|
259 | 296 | user_id = user.user_id |
|
260 | 297 | |
|
261 | 298 | self.app.post( |
|
262 | 299 | route_path('edit_user_emails_add', user_id=user_id), |
|
263 | 300 | params={'new_email': 'example@rhodecode.com', |
|
264 | 301 | 'csrf_token': self.csrf_token}) |
|
265 | 302 | |
|
266 | response = self.app.get(route_path('edit_user_emails', user_id=user_id)) | |
|
303 | response = self.app.get( | |
|
304 | route_path('edit_user_emails', user_id=user_id)) | |
|
267 | 305 | response.mustcontain('example@rhodecode.com') |
|
268 | 306 | |
|
269 | 307 | user_email = UserEmailMap.query()\ |
|
270 | 308 | .filter(UserEmailMap.email == 'example@rhodecode.com') \ |
|
271 | 309 | .filter(UserEmailMap.user_id == user_id)\ |
|
272 | 310 | .one() |
|
273 | 311 | |
|
274 | 312 | del_email_id = user_email.email_id |
|
275 | 313 | self.app.post( |
|
276 | 314 | route_path('edit_user_emails_delete', user_id=user_id), |
|
277 | 315 | params={'del_email_id': del_email_id, |
|
278 | 316 | 'csrf_token': self.csrf_token}) |
|
279 | 317 | |
|
280 | response = self.app.get(route_path('edit_user_emails', user_id=user_id)) | |
|
281 | response.mustcontain(no=['example@rhodecode.com']) No newline at end of file | |
|
318 | response = self.app.get( | |
|
319 | route_path('edit_user_emails', user_id=user_id)) | |
|
320 | response.mustcontain(no=['example@rhodecode.com']) | |
|
321 | ||
|
322 | ||
|
323 | def test_create(self, request, xhr_header): | |
|
324 | self.log_user() | |
|
325 | username = 'newtestuser' | |
|
326 | password = 'test12' | |
|
327 | password_confirmation = password | |
|
328 | name = 'name' | |
|
329 | lastname = 'lastname' | |
|
330 | email = 'mail@mail.com' | |
|
331 | ||
|
332 | self.app.get(route_path('users_new')) | |
|
333 | ||
|
334 | response = self.app.post(route_path('users_create'), params={ | |
|
335 | 'username': username, | |
|
336 | 'password': password, | |
|
337 | 'password_confirmation': password_confirmation, | |
|
338 | 'firstname': name, | |
|
339 | 'active': True, | |
|
340 | 'lastname': lastname, | |
|
341 | 'extern_name': 'rhodecode', | |
|
342 | 'extern_type': 'rhodecode', | |
|
343 | 'email': email, | |
|
344 | 'csrf_token': self.csrf_token, | |
|
345 | }) | |
|
346 | user_link = h.link_to( | |
|
347 | username, | |
|
348 | route_path( | |
|
349 | 'user_edit', user_id=User.get_by_username(username).user_id)) | |
|
350 | assert_session_flash(response, 'Created user %s' % (user_link,)) | |
|
351 | ||
|
352 | @request.addfinalizer | |
|
353 | def cleanup(): | |
|
354 | fixture.destroy_user(username) | |
|
355 | Session().commit() | |
|
356 | ||
|
357 | new_user = User.query().filter(User.username == username).one() | |
|
358 | ||
|
359 | assert new_user.username == username | |
|
360 | assert auth.check_password(password, new_user.password) | |
|
361 | assert new_user.name == name | |
|
362 | assert new_user.lastname == lastname | |
|
363 | assert new_user.email == email | |
|
364 | ||
|
365 | response = self.app.get(route_path('users_data'), | |
|
366 | extra_environ=xhr_header) | |
|
367 | response.mustcontain(username) | |
|
368 | ||
|
369 | def test_create_err(self): | |
|
370 | self.log_user() | |
|
371 | username = 'new_user' | |
|
372 | password = '' | |
|
373 | name = 'name' | |
|
374 | lastname = 'lastname' | |
|
375 | email = 'errmail.com' | |
|
376 | ||
|
377 | self.app.get(route_path('users_new')) | |
|
378 | ||
|
379 | response = self.app.post(route_path('users_create'), params={ | |
|
380 | 'username': username, | |
|
381 | 'password': password, | |
|
382 | 'name': name, | |
|
383 | 'active': False, | |
|
384 | 'lastname': lastname, | |
|
385 | 'email': email, | |
|
386 | 'csrf_token': self.csrf_token, | |
|
387 | }) | |
|
388 | ||
|
389 | msg = validators.ValidUsername( | |
|
390 | False, {})._messages['system_invalid_username'] | |
|
391 | msg = h.html_escape(msg % {'username': 'new_user'}) | |
|
392 | response.mustcontain('<span class="error-message">%s</span>' % msg) | |
|
393 | response.mustcontain( | |
|
394 | '<span class="error-message">Please enter a value</span>') | |
|
395 | response.mustcontain( | |
|
396 | '<span class="error-message">An email address must contain a' | |
|
397 | ' single @</span>') | |
|
398 | ||
|
399 | def get_user(): | |
|
400 | Session().query(User).filter(User.username == username).one() | |
|
401 | ||
|
402 | with pytest.raises(NoResultFound): | |
|
403 | get_user() | |
|
404 | ||
|
405 | def test_new(self): | |
|
406 | self.log_user() | |
|
407 | self.app.get(route_path('users_new')) | |
|
408 | ||
|
409 | @pytest.mark.parametrize("name, attrs", [ | |
|
410 | ('firstname', {'firstname': 'new_username'}), | |
|
411 | ('lastname', {'lastname': 'new_username'}), | |
|
412 | ('admin', {'admin': True}), | |
|
413 | ('admin', {'admin': False}), | |
|
414 | ('extern_type', {'extern_type': 'ldap'}), | |
|
415 | ('extern_type', {'extern_type': None}), | |
|
416 | ('extern_name', {'extern_name': 'test'}), | |
|
417 | ('extern_name', {'extern_name': None}), | |
|
418 | ('active', {'active': False}), | |
|
419 | ('active', {'active': True}), | |
|
420 | ('email', {'email': 'some@email.com'}), | |
|
421 | ('language', {'language': 'de'}), | |
|
422 | ('language', {'language': 'en'}), | |
|
423 | # ('new_password', {'new_password': 'foobar123', | |
|
424 | # 'password_confirmation': 'foobar123'}) | |
|
425 | ]) | |
|
426 | def test_update(self, name, attrs, user_util): | |
|
427 | self.log_user() | |
|
428 | usr = user_util.create_user( | |
|
429 | password='qweqwe', | |
|
430 | email='testme@rhodecode.org', | |
|
431 | extern_type='rhodecode', | |
|
432 | extern_name='xxx', | |
|
433 | ) | |
|
434 | user_id = usr.user_id | |
|
435 | Session().commit() | |
|
436 | ||
|
437 | params = usr.get_api_data() | |
|
438 | cur_lang = params['language'] or 'en' | |
|
439 | params.update({ | |
|
440 | 'password_confirmation': '', | |
|
441 | 'new_password': '', | |
|
442 | 'language': cur_lang, | |
|
443 | 'csrf_token': self.csrf_token, | |
|
444 | }) | |
|
445 | params.update({'new_password': ''}) | |
|
446 | params.update(attrs) | |
|
447 | if name == 'email': | |
|
448 | params['emails'] = [attrs['email']] | |
|
449 | elif name == 'extern_type': | |
|
450 | # cannot update this via form, expected value is original one | |
|
451 | params['extern_type'] = "rhodecode" | |
|
452 | elif name == 'extern_name': | |
|
453 | # cannot update this via form, expected value is original one | |
|
454 | params['extern_name'] = 'xxx' | |
|
455 | # special case since this user is not | |
|
456 | # logged in yet his data is not filled | |
|
457 | # so we use creation data | |
|
458 | ||
|
459 | response = self.app.post( | |
|
460 | route_path('user_update', user_id=usr.user_id), params) | |
|
461 | assert response.status_int == 302 | |
|
462 | assert_session_flash(response, 'User updated successfully') | |
|
463 | ||
|
464 | updated_user = User.get(user_id) | |
|
465 | updated_params = updated_user.get_api_data() | |
|
466 | updated_params.update({'password_confirmation': ''}) | |
|
467 | updated_params.update({'new_password': ''}) | |
|
468 | ||
|
469 | del params['csrf_token'] | |
|
470 | assert params == updated_params | |
|
471 | ||
|
472 | def test_update_and_migrate_password( | |
|
473 | self, autologin_user, real_crypto_backend, user_util): | |
|
474 | ||
|
475 | user = user_util.create_user() | |
|
476 | temp_user = user.username | |
|
477 | user.password = auth._RhodeCodeCryptoSha256().hash_create( | |
|
478 | b'test123') | |
|
479 | Session().add(user) | |
|
480 | Session().commit() | |
|
481 | ||
|
482 | params = user.get_api_data() | |
|
483 | ||
|
484 | params.update({ | |
|
485 | 'password_confirmation': 'qweqwe123', | |
|
486 | 'new_password': 'qweqwe123', | |
|
487 | 'language': 'en', | |
|
488 | 'csrf_token': autologin_user.csrf_token, | |
|
489 | }) | |
|
490 | ||
|
491 | response = self.app.post( | |
|
492 | route_path('user_update', user_id=user.user_id), params) | |
|
493 | assert response.status_int == 302 | |
|
494 | assert_session_flash(response, 'User updated successfully') | |
|
495 | ||
|
496 | # new password should be bcrypted, after log-in and transfer | |
|
497 | user = User.get_by_username(temp_user) | |
|
498 | assert user.password.startswith('$') | |
|
499 | ||
|
500 | updated_user = User.get_by_username(temp_user) | |
|
501 | updated_params = updated_user.get_api_data() | |
|
502 | updated_params.update({'password_confirmation': 'qweqwe123'}) | |
|
503 | updated_params.update({'new_password': 'qweqwe123'}) | |
|
504 | ||
|
505 | del params['csrf_token'] | |
|
506 | assert params == updated_params | |
|
507 | ||
|
508 | def test_delete(self): | |
|
509 | self.log_user() | |
|
510 | username = 'newtestuserdeleteme' | |
|
511 | ||
|
512 | fixture.create_user(name=username) | |
|
513 | ||
|
514 | new_user = Session().query(User)\ | |
|
515 | .filter(User.username == username).one() | |
|
516 | response = self.app.post( | |
|
517 | route_path('user_delete', user_id=new_user.user_id), | |
|
518 | params={'csrf_token': self.csrf_token}) | |
|
519 | ||
|
520 | assert_session_flash(response, 'Successfully deleted user') | |
|
521 | ||
|
522 | def test_delete_owner_of_repository(self, request, user_util): | |
|
523 | self.log_user() | |
|
524 | obj_name = 'test_repo' | |
|
525 | usr = user_util.create_user() | |
|
526 | username = usr.username | |
|
527 | fixture.create_repo(obj_name, cur_user=usr.username) | |
|
528 | ||
|
529 | new_user = Session().query(User)\ | |
|
530 | .filter(User.username == username).one() | |
|
531 | response = self.app.post( | |
|
532 | route_path('user_delete', user_id=new_user.user_id), | |
|
533 | params={'csrf_token': self.csrf_token}) | |
|
534 | ||
|
535 | msg = 'user "%s" still owns 1 repositories and cannot be removed. ' \ | |
|
536 | 'Switch owners or remove those repositories:%s' % (username, | |
|
537 | obj_name) | |
|
538 | assert_session_flash(response, msg) | |
|
539 | fixture.destroy_repo(obj_name) | |
|
540 | ||
|
541 | def test_delete_owner_of_repository_detaching(self, request, user_util): | |
|
542 | self.log_user() | |
|
543 | obj_name = 'test_repo' | |
|
544 | usr = user_util.create_user(auto_cleanup=False) | |
|
545 | username = usr.username | |
|
546 | fixture.create_repo(obj_name, cur_user=usr.username) | |
|
547 | ||
|
548 | new_user = Session().query(User)\ | |
|
549 | .filter(User.username == username).one() | |
|
550 | response = self.app.post( | |
|
551 | route_path('user_delete', user_id=new_user.user_id), | |
|
552 | params={'user_repos': 'detach', 'csrf_token': self.csrf_token}) | |
|
553 | ||
|
554 | msg = 'Detached 1 repositories' | |
|
555 | assert_session_flash(response, msg) | |
|
556 | fixture.destroy_repo(obj_name) | |
|
557 | ||
|
558 | def test_delete_owner_of_repository_deleting(self, request, user_util): | |
|
559 | self.log_user() | |
|
560 | obj_name = 'test_repo' | |
|
561 | usr = user_util.create_user(auto_cleanup=False) | |
|
562 | username = usr.username | |
|
563 | fixture.create_repo(obj_name, cur_user=usr.username) | |
|
564 | ||
|
565 | new_user = Session().query(User)\ | |
|
566 | .filter(User.username == username).one() | |
|
567 | response = self.app.post( | |
|
568 | route_path('user_delete', user_id=new_user.user_id), | |
|
569 | params={'user_repos': 'delete', 'csrf_token': self.csrf_token}) | |
|
570 | ||
|
571 | msg = 'Deleted 1 repositories' | |
|
572 | assert_session_flash(response, msg) | |
|
573 | ||
|
574 | def test_delete_owner_of_repository_group(self, request, user_util): | |
|
575 | self.log_user() | |
|
576 | obj_name = 'test_group' | |
|
577 | usr = user_util.create_user() | |
|
578 | username = usr.username | |
|
579 | fixture.create_repo_group(obj_name, cur_user=usr.username) | |
|
580 | ||
|
581 | new_user = Session().query(User)\ | |
|
582 | .filter(User.username == username).one() | |
|
583 | response = self.app.post( | |
|
584 | route_path('user_delete', user_id=new_user.user_id), | |
|
585 | params={'csrf_token': self.csrf_token}) | |
|
586 | ||
|
587 | msg = 'user "%s" still owns 1 repository groups and cannot be removed. ' \ | |
|
588 | 'Switch owners or remove those repository groups:%s' % (username, | |
|
589 | obj_name) | |
|
590 | assert_session_flash(response, msg) | |
|
591 | fixture.destroy_repo_group(obj_name) | |
|
592 | ||
|
593 | def test_delete_owner_of_repository_group_detaching(self, request, user_util): | |
|
594 | self.log_user() | |
|
595 | obj_name = 'test_group' | |
|
596 | usr = user_util.create_user(auto_cleanup=False) | |
|
597 | username = usr.username | |
|
598 | fixture.create_repo_group(obj_name, cur_user=usr.username) | |
|
599 | ||
|
600 | new_user = Session().query(User)\ | |
|
601 | .filter(User.username == username).one() | |
|
602 | response = self.app.post( | |
|
603 | route_path('user_delete', user_id=new_user.user_id), | |
|
604 | params={'user_repo_groups': 'delete', 'csrf_token': self.csrf_token}) | |
|
605 | ||
|
606 | msg = 'Deleted 1 repository groups' | |
|
607 | assert_session_flash(response, msg) | |
|
608 | ||
|
609 | def test_delete_owner_of_repository_group_deleting(self, request, user_util): | |
|
610 | self.log_user() | |
|
611 | obj_name = 'test_group' | |
|
612 | usr = user_util.create_user(auto_cleanup=False) | |
|
613 | username = usr.username | |
|
614 | fixture.create_repo_group(obj_name, cur_user=usr.username) | |
|
615 | ||
|
616 | new_user = Session().query(User)\ | |
|
617 | .filter(User.username == username).one() | |
|
618 | response = self.app.post( | |
|
619 | route_path('user_delete', user_id=new_user.user_id), | |
|
620 | params={'user_repo_groups': 'detach', 'csrf_token': self.csrf_token}) | |
|
621 | ||
|
622 | msg = 'Detached 1 repository groups' | |
|
623 | assert_session_flash(response, msg) | |
|
624 | fixture.destroy_repo_group(obj_name) | |
|
625 | ||
|
626 | def test_delete_owner_of_user_group(self, request, user_util): | |
|
627 | self.log_user() | |
|
628 | obj_name = 'test_user_group' | |
|
629 | usr = user_util.create_user() | |
|
630 | username = usr.username | |
|
631 | fixture.create_user_group(obj_name, cur_user=usr.username) | |
|
632 | ||
|
633 | new_user = Session().query(User)\ | |
|
634 | .filter(User.username == username).one() | |
|
635 | response = self.app.post( | |
|
636 | route_path('user_delete', user_id=new_user.user_id), | |
|
637 | params={'csrf_token': self.csrf_token}) | |
|
638 | ||
|
639 | msg = 'user "%s" still owns 1 user groups and cannot be removed. ' \ | |
|
640 | 'Switch owners or remove those user groups:%s' % (username, | |
|
641 | obj_name) | |
|
642 | assert_session_flash(response, msg) | |
|
643 | fixture.destroy_user_group(obj_name) | |
|
644 | ||
|
645 | def test_delete_owner_of_user_group_detaching(self, request, user_util): | |
|
646 | self.log_user() | |
|
647 | obj_name = 'test_user_group' | |
|
648 | usr = user_util.create_user(auto_cleanup=False) | |
|
649 | username = usr.username | |
|
650 | fixture.create_user_group(obj_name, cur_user=usr.username) | |
|
651 | ||
|
652 | new_user = Session().query(User)\ | |
|
653 | .filter(User.username == username).one() | |
|
654 | try: | |
|
655 | response = self.app.post( | |
|
656 | route_path('user_delete', user_id=new_user.user_id), | |
|
657 | params={'user_user_groups': 'detach', | |
|
658 | 'csrf_token': self.csrf_token}) | |
|
659 | ||
|
660 | msg = 'Detached 1 user groups' | |
|
661 | assert_session_flash(response, msg) | |
|
662 | finally: | |
|
663 | fixture.destroy_user_group(obj_name) | |
|
664 | ||
|
665 | def test_delete_owner_of_user_group_deleting(self, request, user_util): | |
|
666 | self.log_user() | |
|
667 | obj_name = 'test_user_group' | |
|
668 | usr = user_util.create_user(auto_cleanup=False) | |
|
669 | username = usr.username | |
|
670 | fixture.create_user_group(obj_name, cur_user=usr.username) | |
|
671 | ||
|
672 | new_user = Session().query(User)\ | |
|
673 | .filter(User.username == username).one() | |
|
674 | response = self.app.post( | |
|
675 | route_path('user_delete', user_id=new_user.user_id), | |
|
676 | params={'user_user_groups': 'delete', 'csrf_token': self.csrf_token}) | |
|
677 | ||
|
678 | msg = 'Deleted 1 user groups' | |
|
679 | assert_session_flash(response, msg) | |
|
680 | ||
|
681 | def test_edit(self, user_util): | |
|
682 | self.log_user() | |
|
683 | user = user_util.create_user() | |
|
684 | self.app.get(route_path('user_edit', user_id=user.user_id)) | |
|
685 | ||
|
686 | def test_edit_default_user_redirect(self): | |
|
687 | self.log_user() | |
|
688 | user = User.get_default_user() | |
|
689 | self.app.get(route_path('user_edit', user_id=user.user_id), status=302) | |
|
690 | ||
|
691 | @pytest.mark.parametrize( | |
|
692 | 'repo_create, repo_create_write, user_group_create, repo_group_create,' | |
|
693 | 'fork_create, inherit_default_permissions, expect_error,' | |
|
694 | 'expect_form_error', [ | |
|
695 | ('hg.create.none', 'hg.create.write_on_repogroup.false', | |
|
696 | 'hg.usergroup.create.false', 'hg.repogroup.create.false', | |
|
697 | 'hg.fork.none', 'hg.inherit_default_perms.false', False, False), | |
|
698 | ('hg.create.repository', 'hg.create.write_on_repogroup.false', | |
|
699 | 'hg.usergroup.create.false', 'hg.repogroup.create.false', | |
|
700 | 'hg.fork.none', 'hg.inherit_default_perms.false', False, False), | |
|
701 | ('hg.create.repository', 'hg.create.write_on_repogroup.true', | |
|
702 | 'hg.usergroup.create.true', 'hg.repogroup.create.true', | |
|
703 | 'hg.fork.repository', 'hg.inherit_default_perms.false', False, | |
|
704 | False), | |
|
705 | ('hg.create.XXX', 'hg.create.write_on_repogroup.true', | |
|
706 | 'hg.usergroup.create.true', 'hg.repogroup.create.true', | |
|
707 | 'hg.fork.repository', 'hg.inherit_default_perms.false', False, | |
|
708 | True), | |
|
709 | ('', '', '', '', '', '', True, False), | |
|
710 | ]) | |
|
711 | def test_global_perms_on_user( | |
|
712 | self, repo_create, repo_create_write, user_group_create, | |
|
713 | repo_group_create, fork_create, expect_error, expect_form_error, | |
|
714 | inherit_default_permissions, user_util): | |
|
715 | self.log_user() | |
|
716 | user = user_util.create_user() | |
|
717 | uid = user.user_id | |
|
718 | ||
|
719 | # ENABLE REPO CREATE ON A GROUP | |
|
720 | perm_params = { | |
|
721 | 'inherit_default_permissions': False, | |
|
722 | 'default_repo_create': repo_create, | |
|
723 | 'default_repo_create_on_write': repo_create_write, | |
|
724 | 'default_user_group_create': user_group_create, | |
|
725 | 'default_repo_group_create': repo_group_create, | |
|
726 | 'default_fork_create': fork_create, | |
|
727 | 'default_inherit_default_permissions': inherit_default_permissions, | |
|
728 | 'csrf_token': self.csrf_token, | |
|
729 | } | |
|
730 | response = self.app.post( | |
|
731 | route_path('user_edit_global_perms_update', user_id=uid), | |
|
732 | params=perm_params) | |
|
733 | ||
|
734 | if expect_form_error: | |
|
735 | assert response.status_int == 200 | |
|
736 | response.mustcontain('Value must be one of') | |
|
737 | else: | |
|
738 | if expect_error: | |
|
739 | msg = 'An error occurred during permissions saving' | |
|
740 | else: | |
|
741 | msg = 'User global permissions updated successfully' | |
|
742 | ug = User.get(uid) | |
|
743 | del perm_params['inherit_default_permissions'] | |
|
744 | del perm_params['csrf_token'] | |
|
745 | assert perm_params == ug.get_default_perms() | |
|
746 | assert_session_flash(response, msg) | |
|
747 | ||
|
748 | def test_global_permissions_initial_values(self, user_util): | |
|
749 | self.log_user() | |
|
750 | user = user_util.create_user() | |
|
751 | uid = user.user_id | |
|
752 | response = self.app.get( | |
|
753 | route_path('user_edit_global_perms', user_id=uid)) | |
|
754 | default_user = User.get_default_user() | |
|
755 | default_permissions = default_user.get_default_perms() | |
|
756 | assert_response = response.assert_response() | |
|
757 | expected_permissions = ( | |
|
758 | 'default_repo_create', 'default_repo_create_on_write', | |
|
759 | 'default_fork_create', 'default_repo_group_create', | |
|
760 | 'default_user_group_create', 'default_inherit_default_permissions') | |
|
761 | for permission in expected_permissions: | |
|
762 | css_selector = '[name={}][checked=checked]'.format(permission) | |
|
763 | element = assert_response.get_element(css_selector) | |
|
764 | assert element.value == default_permissions[permission] | |
|
765 | ||
|
766 | def test_perms_summary_page(self): | |
|
767 | user = self.log_user() | |
|
768 | response = self.app.get( | |
|
769 | route_path('edit_user_perms_summary', user_id=user['user_id'])) | |
|
770 | for repo in Repository.query().all(): | |
|
771 | response.mustcontain(repo.repo_name) | |
|
772 | ||
|
773 | def test_perms_summary_page_json(self): | |
|
774 | user = self.log_user() | |
|
775 | response = self.app.get( | |
|
776 | route_path('edit_user_perms_summary_json', user_id=user['user_id'])) | |
|
777 | for repo in Repository.query().all(): | |
|
778 | response.mustcontain(repo.repo_name) | |
|
779 | ||
|
780 | def test_audit_log_page(self): | |
|
781 | user = self.log_user() | |
|
782 | self.app.get( | |
|
783 | route_path('edit_user_audit_logs', user_id=user['user_id'])) |
This diff has been collapsed as it changes many lines, (691 lines changed) Show them Hide them | |||
@@ -1,668 +1,1177 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | |
|
3 | 3 | # Copyright (C) 2016-2017 RhodeCode GmbH |
|
4 | 4 | # |
|
5 | 5 | # This program is free software: you can redistribute it and/or modify |
|
6 | 6 | # it under the terms of the GNU Affero General Public License, version 3 |
|
7 | 7 | # (only), as published by the Free Software Foundation. |
|
8 | 8 | # |
|
9 | 9 | # This program is distributed in the hope that it will be useful, |
|
10 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of |
|
11 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|
12 | 12 | # GNU General Public License for more details. |
|
13 | 13 | # |
|
14 | 14 | # You should have received a copy of the GNU Affero General Public License |
|
15 | 15 | # along with this program. If not, see <http://www.gnu.org/licenses/>. |
|
16 | 16 | # |
|
17 | 17 | # This program is dual-licensed. If you wish to learn more about the |
|
18 | 18 | # RhodeCode Enterprise Edition, including its added features, Support services, |
|
19 | 19 | # and proprietary license terms, please see https://rhodecode.com/licenses/ |
|
20 | 20 | |
|
21 | import time | |
|
22 | 21 | import logging |
|
23 | 22 | import datetime |
|
24 | 23 | import formencode |
|
25 | 24 | import formencode.htmlfill |
|
26 | 25 | |
|
27 | 26 | from pyramid.httpexceptions import HTTPFound |
|
28 | 27 | from pyramid.view import view_config |
|
29 | from sqlalchemy.sql.functions import coalesce | |
|
30 | from sqlalchemy.exc import IntegrityError | |
|
28 | from pyramid.renderers import render | |
|
29 | from pyramid.response import Response | |
|
31 | 30 | |
|
32 | from rhodecode.apps._base import BaseAppView, DataGridAppView | |
|
31 | from rhodecode.apps._base import BaseAppView, DataGridAppView, UserAppView | |
|
33 | 32 | from rhodecode.apps.ssh_support import SshKeyFileChangeEvent |
|
33 | from rhodecode.authentication.plugins import auth_rhodecode | |
|
34 | 34 | from rhodecode.events import trigger |
|
35 | 35 | |
|
36 | 36 | from rhodecode.lib import audit_logger |
|
37 | from rhodecode.lib.exceptions import ( | |
|
38 | UserCreationError, UserOwnsReposException, UserOwnsRepoGroupsException, | |
|
39 | UserOwnsUserGroupsException, DefaultUserException) | |
|
37 | 40 | from rhodecode.lib.ext_json import json |
|
38 | 41 | from rhodecode.lib.auth import ( |
|
39 | 42 | LoginRequired, HasPermissionAllDecorator, CSRFRequired) |
|
40 | 43 | from rhodecode.lib import helpers as h |
|
41 | from rhodecode.lib.utils2 import safe_int, safe_unicode | |
|
44 | from rhodecode.lib.utils2 import safe_int, safe_unicode, AttributeDict | |
|
42 | 45 | from rhodecode.model.auth_token import AuthTokenModel |
|
46 | from rhodecode.model.forms import ( | |
|
47 | UserForm, UserIndividualPermissionsForm, UserPermissionsForm) | |
|
48 | from rhodecode.model.permission import PermissionModel | |
|
49 | from rhodecode.model.repo_group import RepoGroupModel | |
|
43 | 50 | from rhodecode.model.ssh_key import SshKeyModel |
|
44 | 51 | from rhodecode.model.user import UserModel |
|
45 | 52 | from rhodecode.model.user_group import UserGroupModel |
|
46 | 53 | from rhodecode.model.db import ( |
|
47 | or_, User, UserIpMap, UserEmailMap, UserApiKeys, UserSshKeys) | |
|
54 | or_, coalesce,IntegrityError, User, UserGroup, UserIpMap, UserEmailMap, | |
|
55 | UserApiKeys, UserSshKeys, RepoGroup) | |
|
48 | 56 | from rhodecode.model.meta import Session |
|
49 | 57 | |
|
50 | 58 | log = logging.getLogger(__name__) |
|
51 | 59 | |
|
52 | 60 | |
|
53 | 61 | class AdminUsersView(BaseAppView, DataGridAppView): |
|
54 | ALLOW_SCOPED_TOKENS = False | |
|
55 | """ | |
|
56 | This view has alternative version inside EE, if modified please take a look | |
|
57 | in there as well. | |
|
58 | """ | |
|
59 | 62 | |
|
60 | 63 | def load_default_context(self): |
|
61 | 64 | c = self._get_local_tmpl_context() |
|
62 | c.allow_scoped_tokens = self.ALLOW_SCOPED_TOKENS | |
|
63 | 65 | self._register_global_c(c) |
|
64 | 66 | return c |
|
65 | 67 | |
|
66 | def _redirect_for_default_user(self, username): | |
|
67 | _ = self.request.translate | |
|
68 | if username == User.DEFAULT_USER: | |
|
69 | h.flash(_("You can't edit this user"), category='warning') | |
|
70 | # TODO(marcink): redirect to 'users' admin panel once this | |
|
71 | # is a pyramid view | |
|
72 | raise HTTPFound('/') | |
|
73 | ||
|
74 | 68 | @LoginRequired() |
|
75 | 69 | @HasPermissionAllDecorator('hg.admin') |
|
76 | 70 | @view_config( |
|
77 | 71 | route_name='users', request_method='GET', |
|
78 | 72 | renderer='rhodecode:templates/admin/users/users.mako') |
|
79 | 73 | def users_list(self): |
|
80 | 74 | c = self.load_default_context() |
|
81 | 75 | return self._get_template_context(c) |
|
82 | 76 | |
|
83 | 77 | @LoginRequired() |
|
84 | 78 | @HasPermissionAllDecorator('hg.admin') |
|
85 | 79 | @view_config( |
|
86 | 80 | # renderer defined below |
|
87 | 81 | route_name='users_data', request_method='GET', |
|
88 | 82 | renderer='json_ext', xhr=True) |
|
89 | 83 | def users_list_data(self): |
|
90 | 84 | column_map = { |
|
91 | 85 | 'first_name': 'name', |
|
92 | 86 | 'last_name': 'lastname', |
|
93 | 87 | } |
|
94 | 88 | draw, start, limit = self._extract_chunk(self.request) |
|
95 | 89 | search_q, order_by, order_dir = self._extract_ordering( |
|
96 | 90 | self.request, column_map=column_map) |
|
97 | 91 | |
|
98 | 92 | _render = self.request.get_partial_renderer( |
|
99 | 93 | 'data_table/_dt_elements.mako') |
|
100 | 94 | |
|
101 | 95 | def user_actions(user_id, username): |
|
102 | 96 | return _render("user_actions", user_id, username) |
|
103 | 97 | |
|
104 | 98 | users_data_total_count = User.query()\ |
|
105 | 99 | .filter(User.username != User.DEFAULT_USER) \ |
|
106 | 100 | .count() |
|
107 | 101 | |
|
108 | 102 | # json generate |
|
109 | 103 | base_q = User.query().filter(User.username != User.DEFAULT_USER) |
|
110 | 104 | |
|
111 | 105 | if search_q: |
|
112 | 106 | like_expression = u'%{}%'.format(safe_unicode(search_q)) |
|
113 | 107 | base_q = base_q.filter(or_( |
|
114 | 108 | User.username.ilike(like_expression), |
|
115 | 109 | User._email.ilike(like_expression), |
|
116 | 110 | User.name.ilike(like_expression), |
|
117 | 111 | User.lastname.ilike(like_expression), |
|
118 | 112 | )) |
|
119 | 113 | |
|
120 | 114 | users_data_total_filtered_count = base_q.count() |
|
121 | 115 | |
|
122 | 116 | sort_col = getattr(User, order_by, None) |
|
123 | 117 | if sort_col: |
|
124 | 118 | if order_dir == 'asc': |
|
125 | 119 | # handle null values properly to order by NULL last |
|
126 | 120 | if order_by in ['last_activity']: |
|
127 | 121 | sort_col = coalesce(sort_col, datetime.date.max) |
|
128 | 122 | sort_col = sort_col.asc() |
|
129 | 123 | else: |
|
130 | 124 | # handle null values properly to order by NULL last |
|
131 | 125 | if order_by in ['last_activity']: |
|
132 | 126 | sort_col = coalesce(sort_col, datetime.date.min) |
|
133 | 127 | sort_col = sort_col.desc() |
|
134 | 128 | |
|
135 | 129 | base_q = base_q.order_by(sort_col) |
|
136 | 130 | base_q = base_q.offset(start).limit(limit) |
|
137 | 131 | |
|
138 | 132 | users_list = base_q.all() |
|
139 | 133 | |
|
140 | 134 | users_data = [] |
|
141 | 135 | for user in users_list: |
|
142 | 136 | users_data.append({ |
|
143 | 137 | "username": h.gravatar_with_user(self.request, user.username), |
|
144 | 138 | "email": user.email, |
|
145 | 139 | "first_name": user.first_name, |
|
146 | 140 | "last_name": user.last_name, |
|
147 | 141 | "last_login": h.format_date(user.last_login), |
|
148 | 142 | "last_activity": h.format_date(user.last_activity), |
|
149 | 143 | "active": h.bool2icon(user.active), |
|
150 | 144 | "active_raw": user.active, |
|
151 | 145 | "admin": h.bool2icon(user.admin), |
|
152 | 146 | "extern_type": user.extern_type, |
|
153 | 147 | "extern_name": user.extern_name, |
|
154 | 148 | "action": user_actions(user.user_id, user.username), |
|
155 | 149 | }) |
|
156 | 150 | |
|
157 | 151 | data = ({ |
|
158 | 152 | 'draw': draw, |
|
159 | 153 | 'data': users_data, |
|
160 | 154 | 'recordsTotal': users_data_total_count, |
|
161 | 155 | 'recordsFiltered': users_data_total_filtered_count, |
|
162 | 156 | }) |
|
163 | 157 | |
|
164 | 158 | return data |
|
165 | 159 | |
|
160 | def _set_personal_repo_group_template_vars(self, c_obj): | |
|
161 | DummyUser = AttributeDict({ | |
|
162 | 'username': '${username}', | |
|
163 | 'user_id': '${user_id}', | |
|
164 | }) | |
|
165 | c_obj.default_create_repo_group = RepoGroupModel() \ | |
|
166 | .get_default_create_personal_repo_group() | |
|
167 | c_obj.personal_repo_group_name = RepoGroupModel() \ | |
|
168 | .get_personal_group_name(DummyUser) | |
|
169 | ||
|
170 | @LoginRequired() | |
|
171 | @HasPermissionAllDecorator('hg.admin') | |
|
172 | @view_config( | |
|
173 | route_name='users_new', request_method='GET', | |
|
174 | renderer='rhodecode:templates/admin/users/user_add.mako') | |
|
175 | def users_new(self): | |
|
176 | _ = self.request.translate | |
|
177 | c = self.load_default_context() | |
|
178 | c.default_extern_type = auth_rhodecode.RhodeCodeAuthPlugin.name | |
|
179 | self._set_personal_repo_group_template_vars(c) | |
|
180 | return self._get_template_context(c) | |
|
181 | ||
|
182 | @LoginRequired() | |
|
183 | @HasPermissionAllDecorator('hg.admin') | |
|
184 | @CSRFRequired() | |
|
185 | @view_config( | |
|
186 | route_name='users_create', request_method='POST', | |
|
187 | renderer='rhodecode:templates/admin/users/user_add.mako') | |
|
188 | def users_create(self): | |
|
189 | _ = self.request.translate | |
|
190 | c = self.load_default_context() | |
|
191 | c.default_extern_type = auth_rhodecode.RhodeCodeAuthPlugin.name | |
|
192 | user_model = UserModel() | |
|
193 | user_form = UserForm()() | |
|
194 | try: | |
|
195 | form_result = user_form.to_python(dict(self.request.POST)) | |
|
196 | user = user_model.create(form_result) | |
|
197 | Session().flush() | |
|
198 | creation_data = user.get_api_data() | |
|
199 | username = form_result['username'] | |
|
200 | ||
|
201 | audit_logger.store_web( | |
|
202 | 'user.create', action_data={'data': creation_data}, | |
|
203 | user=c.rhodecode_user) | |
|
204 | ||
|
205 | user_link = h.link_to( | |
|
206 | h.escape(username), | |
|
207 | h.route_path('user_edit', user_id=user.user_id)) | |
|
208 | h.flash(h.literal(_('Created user %(user_link)s') | |
|
209 | % {'user_link': user_link}), category='success') | |
|
210 | Session().commit() | |
|
211 | except formencode.Invalid as errors: | |
|
212 | self._set_personal_repo_group_template_vars(c) | |
|
213 | data = render( | |
|
214 | 'rhodecode:templates/admin/users/user_add.mako', | |
|
215 | self._get_template_context(c), self.request) | |
|
216 | html = formencode.htmlfill.render( | |
|
217 | data, | |
|
218 | defaults=errors.value, | |
|
219 | errors=errors.error_dict or {}, | |
|
220 | prefix_error=False, | |
|
221 | encoding="UTF-8", | |
|
222 | force_defaults=False | |
|
223 | ) | |
|
224 | return Response(html) | |
|
225 | except UserCreationError as e: | |
|
226 | h.flash(e, 'error') | |
|
227 | except Exception: | |
|
228 | log.exception("Exception creation of user") | |
|
229 | h.flash(_('Error occurred during creation of user %s') | |
|
230 | % self.request.POST.get('username'), category='error') | |
|
231 | raise HTTPFound(h.route_path('users')) | |
|
232 | ||
|
233 | ||
|
234 | class UsersView(UserAppView): | |
|
235 | ALLOW_SCOPED_TOKENS = False | |
|
236 | """ | |
|
237 | This view has alternative version inside EE, if modified please take a look | |
|
238 | in there as well. | |
|
239 | """ | |
|
240 | ||
|
241 | def load_default_context(self): | |
|
242 | c = self._get_local_tmpl_context() | |
|
243 | c.allow_scoped_tokens = self.ALLOW_SCOPED_TOKENS | |
|
244 | c.allowed_languages = [ | |
|
245 | ('en', 'English (en)'), | |
|
246 | ('de', 'German (de)'), | |
|
247 | ('fr', 'French (fr)'), | |
|
248 | ('it', 'Italian (it)'), | |
|
249 | ('ja', 'Japanese (ja)'), | |
|
250 | ('pl', 'Polish (pl)'), | |
|
251 | ('pt', 'Portuguese (pt)'), | |
|
252 | ('ru', 'Russian (ru)'), | |
|
253 | ('zh', 'Chinese (zh)'), | |
|
254 | ] | |
|
255 | req = self.request | |
|
256 | ||
|
257 | c.available_permissions = req.registry.settings['available_permissions'] | |
|
258 | PermissionModel().set_global_permission_choices( | |
|
259 | c, gettext_translator=req.translate) | |
|
260 | ||
|
261 | self._register_global_c(c) | |
|
262 | return c | |
|
263 | ||
|
264 | @LoginRequired() | |
|
265 | @HasPermissionAllDecorator('hg.admin') | |
|
266 | @CSRFRequired() | |
|
267 | @view_config( | |
|
268 | route_name='user_update', request_method='POST', | |
|
269 | renderer='rhodecode:templates/admin/users/user_edit.mako') | |
|
270 | def user_update(self): | |
|
271 | _ = self.request.translate | |
|
272 | c = self.load_default_context() | |
|
273 | ||
|
274 | user_id = self.db_user_id | |
|
275 | c.user = self.db_user | |
|
276 | ||
|
277 | c.active = 'profile' | |
|
278 | c.extern_type = c.user.extern_type | |
|
279 | c.extern_name = c.user.extern_name | |
|
280 | c.perm_user = c.user.AuthUser(ip_addr=self.request.remote_addr) | |
|
281 | available_languages = [x[0] for x in c.allowed_languages] | |
|
282 | _form = UserForm(edit=True, available_languages=available_languages, | |
|
283 | old_data={'user_id': user_id, | |
|
284 | 'email': c.user.email})() | |
|
285 | form_result = {} | |
|
286 | old_values = c.user.get_api_data() | |
|
287 | try: | |
|
288 | form_result = _form.to_python(dict(self.request.POST)) | |
|
289 | skip_attrs = ['extern_type', 'extern_name'] | |
|
290 | # TODO: plugin should define if username can be updated | |
|
291 | if c.extern_type != "rhodecode": | |
|
292 | # forbid updating username for external accounts | |
|
293 | skip_attrs.append('username') | |
|
294 | ||
|
295 | UserModel().update_user( | |
|
296 | user_id, skip_attrs=skip_attrs, **form_result) | |
|
297 | ||
|
298 | audit_logger.store_web( | |
|
299 | 'user.edit', action_data={'old_data': old_values}, | |
|
300 | user=c.rhodecode_user) | |
|
301 | ||
|
302 | Session().commit() | |
|
303 | h.flash(_('User updated successfully'), category='success') | |
|
304 | except formencode.Invalid as errors: | |
|
305 | data = render( | |
|
306 | 'rhodecode:templates/admin/users/user_edit.mako', | |
|
307 | self._get_template_context(c), self.request) | |
|
308 | html = formencode.htmlfill.render( | |
|
309 | data, | |
|
310 | defaults=errors.value, | |
|
311 | errors=errors.error_dict or {}, | |
|
312 | prefix_error=False, | |
|
313 | encoding="UTF-8", | |
|
314 | force_defaults=False | |
|
315 | ) | |
|
316 | return Response(html) | |
|
317 | except UserCreationError as e: | |
|
318 | h.flash(e, 'error') | |
|
319 | except Exception: | |
|
320 | log.exception("Exception updating user") | |
|
321 | h.flash(_('Error occurred during update of user %s') | |
|
322 | % form_result.get('username'), category='error') | |
|
323 | raise HTTPFound(h.route_path('user_edit', user_id=user_id)) | |
|
324 | ||
|
325 | @LoginRequired() | |
|
326 | @HasPermissionAllDecorator('hg.admin') | |
|
327 | @CSRFRequired() | |
|
328 | @view_config( | |
|
329 | route_name='user_delete', request_method='POST', | |
|
330 | renderer='rhodecode:templates/admin/users/user_edit.mako') | |
|
331 | def user_delete(self): | |
|
332 | _ = self.request.translate | |
|
333 | c = self.load_default_context() | |
|
334 | c.user = self.db_user | |
|
335 | ||
|
336 | _repos = c.user.repositories | |
|
337 | _repo_groups = c.user.repository_groups | |
|
338 | _user_groups = c.user.user_groups | |
|
339 | ||
|
340 | handle_repos = None | |
|
341 | handle_repo_groups = None | |
|
342 | handle_user_groups = None | |
|
343 | # dummy call for flash of handle | |
|
344 | set_handle_flash_repos = lambda: None | |
|
345 | set_handle_flash_repo_groups = lambda: None | |
|
346 | set_handle_flash_user_groups = lambda: None | |
|
347 | ||
|
348 | if _repos and self.request.POST.get('user_repos'): | |
|
349 | do = self.request.POST['user_repos'] | |
|
350 | if do == 'detach': | |
|
351 | handle_repos = 'detach' | |
|
352 | set_handle_flash_repos = lambda: h.flash( | |
|
353 | _('Detached %s repositories') % len(_repos), | |
|
354 | category='success') | |
|
355 | elif do == 'delete': | |
|
356 | handle_repos = 'delete' | |
|
357 | set_handle_flash_repos = lambda: h.flash( | |
|
358 | _('Deleted %s repositories') % len(_repos), | |
|
359 | category='success') | |
|
360 | ||
|
361 | if _repo_groups and self.request.POST.get('user_repo_groups'): | |
|
362 | do = self.request.POST['user_repo_groups'] | |
|
363 | if do == 'detach': | |
|
364 | handle_repo_groups = 'detach' | |
|
365 | set_handle_flash_repo_groups = lambda: h.flash( | |
|
366 | _('Detached %s repository groups') % len(_repo_groups), | |
|
367 | category='success') | |
|
368 | elif do == 'delete': | |
|
369 | handle_repo_groups = 'delete' | |
|
370 | set_handle_flash_repo_groups = lambda: h.flash( | |
|
371 | _('Deleted %s repository groups') % len(_repo_groups), | |
|
372 | category='success') | |
|
373 | ||
|
374 | if _user_groups and self.request.POST.get('user_user_groups'): | |
|
375 | do = self.request.POST['user_user_groups'] | |
|
376 | if do == 'detach': | |
|
377 | handle_user_groups = 'detach' | |
|
378 | set_handle_flash_user_groups = lambda: h.flash( | |
|
379 | _('Detached %s user groups') % len(_user_groups), | |
|
380 | category='success') | |
|
381 | elif do == 'delete': | |
|
382 | handle_user_groups = 'delete' | |
|
383 | set_handle_flash_user_groups = lambda: h.flash( | |
|
384 | _('Deleted %s user groups') % len(_user_groups), | |
|
385 | category='success') | |
|
386 | ||
|
387 | old_values = c.user.get_api_data() | |
|
388 | try: | |
|
389 | UserModel().delete(c.user, handle_repos=handle_repos, | |
|
390 | handle_repo_groups=handle_repo_groups, | |
|
391 | handle_user_groups=handle_user_groups) | |
|
392 | ||
|
393 | audit_logger.store_web( | |
|
394 | 'user.delete', action_data={'old_data': old_values}, | |
|
395 | user=c.rhodecode_user) | |
|
396 | ||
|
397 | Session().commit() | |
|
398 | set_handle_flash_repos() | |
|
399 | set_handle_flash_repo_groups() | |
|
400 | set_handle_flash_user_groups() | |
|
401 | h.flash(_('Successfully deleted user'), category='success') | |
|
402 | except (UserOwnsReposException, UserOwnsRepoGroupsException, | |
|
403 | UserOwnsUserGroupsException, DefaultUserException) as e: | |
|
404 | h.flash(e, category='warning') | |
|
405 | except Exception: | |
|
406 | log.exception("Exception during deletion of user") | |
|
407 | h.flash(_('An error occurred during deletion of user'), | |
|
408 | category='error') | |
|
409 | raise HTTPFound(h.route_path('users')) | |
|
410 | ||
|
411 | @LoginRequired() | |
|
412 | @HasPermissionAllDecorator('hg.admin') | |
|
413 | @view_config( | |
|
414 | route_name='user_edit', request_method='GET', | |
|
415 | renderer='rhodecode:templates/admin/users/user_edit.mako') | |
|
416 | def user_edit(self): | |
|
417 | _ = self.request.translate | |
|
418 | c = self.load_default_context() | |
|
419 | c.user = self.db_user | |
|
420 | ||
|
421 | c.active = 'profile' | |
|
422 | c.extern_type = c.user.extern_type | |
|
423 | c.extern_name = c.user.extern_name | |
|
424 | c.perm_user = c.user.AuthUser(ip_addr=self.request.remote_addr) | |
|
425 | ||
|
426 | defaults = c.user.get_dict() | |
|
427 | defaults.update({'language': c.user.user_data.get('language')}) | |
|
428 | ||
|
429 | data = render( | |
|
430 | 'rhodecode:templates/admin/users/user_edit.mako', | |
|
431 | self._get_template_context(c), self.request) | |
|
432 | html = formencode.htmlfill.render( | |
|
433 | data, | |
|
434 | defaults=defaults, | |
|
435 | encoding="UTF-8", | |
|
436 | force_defaults=False | |
|
437 | ) | |
|
438 | return Response(html) | |
|
439 | ||
|
440 | @LoginRequired() | |
|
441 | @HasPermissionAllDecorator('hg.admin') | |
|
442 | @view_config( | |
|
443 | route_name='user_edit_advanced', request_method='GET', | |
|
444 | renderer='rhodecode:templates/admin/users/user_edit.mako') | |
|
445 | def user_edit_advanced(self): | |
|
446 | _ = self.request.translate | |
|
447 | c = self.load_default_context() | |
|
448 | ||
|
449 | user_id = self.db_user_id | |
|
450 | c.user = self.db_user | |
|
451 | ||
|
452 | c.active = 'advanced' | |
|
453 | c.personal_repo_group = RepoGroup.get_user_personal_repo_group(user_id) | |
|
454 | c.personal_repo_group_name = RepoGroupModel()\ | |
|
455 | .get_personal_group_name(c.user) | |
|
456 | ||
|
457 | c.user_to_review_rules = sorted( | |
|
458 | (x.user for x in c.user.user_review_rules), | |
|
459 | key=lambda u: u.username.lower()) | |
|
460 | ||
|
461 | c.first_admin = User.get_first_super_admin() | |
|
462 | defaults = c.user.get_dict() | |
|
463 | ||
|
464 | # Interim workaround if the user participated on any pull requests as a | |
|
465 | # reviewer. | |
|
466 | has_review = len(c.user.reviewer_pull_requests) | |
|
467 | c.can_delete_user = not has_review | |
|
468 | c.can_delete_user_message = '' | |
|
469 | inactive_link = h.link_to( | |
|
470 | 'inactive', h.route_path('user_edit', user_id=user_id, _anchor='active')) | |
|
471 | if has_review == 1: | |
|
472 | c.can_delete_user_message = h.literal(_( | |
|
473 | 'The user participates as reviewer in {} pull request and ' | |
|
474 | 'cannot be deleted. \nYou can set the user to ' | |
|
475 | '"{}" instead of deleting it.').format( | |
|
476 | has_review, inactive_link)) | |
|
477 | elif has_review: | |
|
478 | c.can_delete_user_message = h.literal(_( | |
|
479 | 'The user participates as reviewer in {} pull requests and ' | |
|
480 | 'cannot be deleted. \nYou can set the user to ' | |
|
481 | '"{}" instead of deleting it.').format( | |
|
482 | has_review, inactive_link)) | |
|
483 | ||
|
484 | data = render( | |
|
485 | 'rhodecode:templates/admin/users/user_edit.mako', | |
|
486 | self._get_template_context(c), self.request) | |
|
487 | html = formencode.htmlfill.render( | |
|
488 | data, | |
|
489 | defaults=defaults, | |
|
490 | encoding="UTF-8", | |
|
491 | force_defaults=False | |
|
492 | ) | |
|
493 | return Response(html) | |
|
494 | ||
|
495 | @LoginRequired() | |
|
496 | @HasPermissionAllDecorator('hg.admin') | |
|
497 | @view_config( | |
|
498 | route_name='user_edit_global_perms', request_method='GET', | |
|
499 | renderer='rhodecode:templates/admin/users/user_edit.mako') | |
|
500 | def user_edit_global_perms(self): | |
|
501 | _ = self.request.translate | |
|
502 | c = self.load_default_context() | |
|
503 | c.user = self.db_user | |
|
504 | ||
|
505 | c.active = 'global_perms' | |
|
506 | ||
|
507 | c.default_user = User.get_default_user() | |
|
508 | defaults = c.user.get_dict() | |
|
509 | defaults.update(c.default_user.get_default_perms(suffix='_inherited')) | |
|
510 | defaults.update(c.default_user.get_default_perms()) | |
|
511 | defaults.update(c.user.get_default_perms()) | |
|
512 | ||
|
513 | data = render( | |
|
514 | 'rhodecode:templates/admin/users/user_edit.mako', | |
|
515 | self._get_template_context(c), self.request) | |
|
516 | html = formencode.htmlfill.render( | |
|
517 | data, | |
|
518 | defaults=defaults, | |
|
519 | encoding="UTF-8", | |
|
520 | force_defaults=False | |
|
521 | ) | |
|
522 | return Response(html) | |
|
523 | ||
|
524 | @LoginRequired() | |
|
525 | @HasPermissionAllDecorator('hg.admin') | |
|
526 | @CSRFRequired() | |
|
527 | @view_config( | |
|
528 | route_name='user_edit_global_perms_update', request_method='POST', | |
|
529 | renderer='rhodecode:templates/admin/users/user_edit.mako') | |
|
530 | def user_edit_global_perms_update(self): | |
|
531 | _ = self.request.translate | |
|
532 | c = self.load_default_context() | |
|
533 | ||
|
534 | user_id = self.db_user_id | |
|
535 | c.user = self.db_user | |
|
536 | ||
|
537 | c.active = 'global_perms' | |
|
538 | try: | |
|
539 | # first stage that verifies the checkbox | |
|
540 | _form = UserIndividualPermissionsForm() | |
|
541 | form_result = _form.to_python(dict(self.request.POST)) | |
|
542 | inherit_perms = form_result['inherit_default_permissions'] | |
|
543 | c.user.inherit_default_permissions = inherit_perms | |
|
544 | Session().add(c.user) | |
|
545 | ||
|
546 | if not inherit_perms: | |
|
547 | # only update the individual ones if we un check the flag | |
|
548 | _form = UserPermissionsForm( | |
|
549 | [x[0] for x in c.repo_create_choices], | |
|
550 | [x[0] for x in c.repo_create_on_write_choices], | |
|
551 | [x[0] for x in c.repo_group_create_choices], | |
|
552 | [x[0] for x in c.user_group_create_choices], | |
|
553 | [x[0] for x in c.fork_choices], | |
|
554 | [x[0] for x in c.inherit_default_permission_choices])() | |
|
555 | ||
|
556 | form_result = _form.to_python(dict(self.request.POST)) | |
|
557 | form_result.update({'perm_user_id': c.user.user_id}) | |
|
558 | ||
|
559 | PermissionModel().update_user_permissions(form_result) | |
|
560 | ||
|
561 | # TODO(marcink): implement global permissions | |
|
562 | # audit_log.store_web('user.edit.permissions') | |
|
563 | ||
|
564 | Session().commit() | |
|
565 | h.flash(_('User global permissions updated successfully'), | |
|
566 | category='success') | |
|
567 | ||
|
568 | except formencode.Invalid as errors: | |
|
569 | data = render( | |
|
570 | 'rhodecode:templates/admin/users/user_edit.mako', | |
|
571 | self._get_template_context(c), self.request) | |
|
572 | html = formencode.htmlfill.render( | |
|
573 | data, | |
|
574 | defaults=errors.value, | |
|
575 | errors=errors.error_dict or {}, | |
|
576 | prefix_error=False, | |
|
577 | encoding="UTF-8", | |
|
578 | force_defaults=False | |
|
579 | ) | |
|
580 | return Response(html) | |
|
581 | except Exception: | |
|
582 | log.exception("Exception during permissions saving") | |
|
583 | h.flash(_('An error occurred during permissions saving'), | |
|
584 | category='error') | |
|
585 | raise HTTPFound(h.route_path('user_edit_global_perms', user_id=user_id)) | |
|
586 | ||
|
587 | @LoginRequired() | |
|
588 | @HasPermissionAllDecorator('hg.admin') | |
|
589 | @CSRFRequired() | |
|
590 | @view_config( | |
|
591 | route_name='user_force_password_reset', request_method='POST', | |
|
592 | renderer='rhodecode:templates/admin/users/user_edit.mako') | |
|
593 | def user_force_password_reset(self): | |
|
594 | """ | |
|
595 | toggle reset password flag for this user | |
|
596 | """ | |
|
597 | _ = self.request.translate | |
|
598 | c = self.load_default_context() | |
|
599 | ||
|
600 | user_id = self.db_user_id | |
|
601 | c.user = self.db_user | |
|
602 | ||
|
603 | try: | |
|
604 | old_value = c.user.user_data.get('force_password_change') | |
|
605 | c.user.update_userdata(force_password_change=not old_value) | |
|
606 | ||
|
607 | if old_value: | |
|
608 | msg = _('Force password change disabled for user') | |
|
609 | audit_logger.store_web( | |
|
610 | 'user.edit.password_reset.disabled', | |
|
611 | user=c.rhodecode_user) | |
|
612 | else: | |
|
613 | msg = _('Force password change enabled for user') | |
|
614 | audit_logger.store_web( | |
|
615 | 'user.edit.password_reset.enabled', | |
|
616 | user=c.rhodecode_user) | |
|
617 | ||
|
618 | Session().commit() | |
|
619 | h.flash(msg, category='success') | |
|
620 | except Exception: | |
|
621 | log.exception("Exception during password reset for user") | |
|
622 | h.flash(_('An error occurred during password reset for user'), | |
|
623 | category='error') | |
|
624 | ||
|
625 | raise HTTPFound(h.route_path('user_edit_advanced', user_id=user_id)) | |
|
626 | ||
|
627 | @LoginRequired() | |
|
628 | @HasPermissionAllDecorator('hg.admin') | |
|
629 | @CSRFRequired() | |
|
630 | @view_config( | |
|
631 | route_name='user_create_personal_repo_group', request_method='POST', | |
|
632 | renderer='rhodecode:templates/admin/users/user_edit.mako') | |
|
633 | def user_create_personal_repo_group(self): | |
|
634 | """ | |
|
635 | Create personal repository group for this user | |
|
636 | """ | |
|
637 | from rhodecode.model.repo_group import RepoGroupModel | |
|
638 | ||
|
639 | _ = self.request.translate | |
|
640 | c = self.load_default_context() | |
|
641 | ||
|
642 | user_id = self.db_user_id | |
|
643 | c.user = self.db_user | |
|
644 | ||
|
645 | personal_repo_group = RepoGroup.get_user_personal_repo_group( | |
|
646 | c.user.user_id) | |
|
647 | if personal_repo_group: | |
|
648 | raise HTTPFound(h.route_path('user_edit_advanced', user_id=user_id)) | |
|
649 | ||
|
650 | personal_repo_group_name = RepoGroupModel().get_personal_group_name( | |
|
651 | c.user) | |
|
652 | named_personal_group = RepoGroup.get_by_group_name( | |
|
653 | personal_repo_group_name) | |
|
654 | try: | |
|
655 | ||
|
656 | if named_personal_group and named_personal_group.user_id == c.user.user_id: | |
|
657 | # migrate the same named group, and mark it as personal | |
|
658 | named_personal_group.personal = True | |
|
659 | Session().add(named_personal_group) | |
|
660 | Session().commit() | |
|
661 | msg = _('Linked repository group `%s` as personal' % ( | |
|
662 | personal_repo_group_name,)) | |
|
663 | h.flash(msg, category='success') | |
|
664 | elif not named_personal_group: | |
|
665 | RepoGroupModel().create_personal_repo_group(c.user) | |
|
666 | ||
|
667 | msg = _('Created repository group `%s`' % ( | |
|
668 | personal_repo_group_name,)) | |
|
669 | h.flash(msg, category='success') | |
|
670 | else: | |
|
671 | msg = _('Repository group `%s` is already taken' % ( | |
|
672 | personal_repo_group_name,)) | |
|
673 | h.flash(msg, category='warning') | |
|
674 | except Exception: | |
|
675 | log.exception("Exception during repository group creation") | |
|
676 | msg = _( | |
|
677 | 'An error occurred during repository group creation for user') | |
|
678 | h.flash(msg, category='error') | |
|
679 | Session().rollback() | |
|
680 | ||
|
681 | raise HTTPFound(h.route_path('user_edit_advanced', user_id=user_id)) | |
|
682 | ||
|
166 | 683 | @LoginRequired() |
|
167 | 684 | @HasPermissionAllDecorator('hg.admin') |
|
168 | 685 | @view_config( |
|
169 | 686 | route_name='edit_user_auth_tokens', request_method='GET', |
|
170 | 687 | renderer='rhodecode:templates/admin/users/user_edit.mako') |
|
171 | 688 | def auth_tokens(self): |
|
172 | 689 | _ = self.request.translate |
|
173 | 690 | c = self.load_default_context() |
|
174 | ||
|
175 | user_id = self.request.matchdict.get('user_id') | |
|
176 | c.user = User.get_or_404(user_id) | |
|
177 | self._redirect_for_default_user(c.user.username) | |
|
691 | c.user = self.db_user | |
|
178 | 692 | |
|
179 | 693 | c.active = 'auth_tokens' |
|
180 | 694 | |
|
181 | 695 | c.lifetime_values = AuthTokenModel.get_lifetime_values(translator=_) |
|
182 | 696 | c.role_values = [ |
|
183 | 697 | (x, AuthTokenModel.cls._get_role_name(x)) |
|
184 | 698 | for x in AuthTokenModel.cls.ROLES] |
|
185 | 699 | c.role_options = [(c.role_values, _("Role"))] |
|
186 | 700 | c.user_auth_tokens = AuthTokenModel().get_auth_tokens( |
|
187 | 701 | c.user.user_id, show_expired=True) |
|
188 | 702 | return self._get_template_context(c) |
|
189 | 703 | |
|
190 | 704 | def maybe_attach_token_scope(self, token): |
|
191 | 705 | # implemented in EE edition |
|
192 | 706 | pass |
|
193 | 707 | |
|
194 | 708 | @LoginRequired() |
|
195 | 709 | @HasPermissionAllDecorator('hg.admin') |
|
196 | 710 | @CSRFRequired() |
|
197 | 711 | @view_config( |
|
198 | 712 | route_name='edit_user_auth_tokens_add', request_method='POST') |
|
199 | 713 | def auth_tokens_add(self): |
|
200 | 714 | _ = self.request.translate |
|
201 | 715 | c = self.load_default_context() |
|
202 | 716 | |
|
203 |
user_id = self. |
|
|
204 |
c.user = |
|
|
205 | ||
|
206 | self._redirect_for_default_user(c.user.username) | |
|
717 | user_id = self.db_user_id | |
|
718 | c.user = self.db_user | |
|
207 | 719 | |
|
208 | 720 | user_data = c.user.get_api_data() |
|
209 | 721 | lifetime = safe_int(self.request.POST.get('lifetime'), -1) |
|
210 | 722 | description = self.request.POST.get('description') |
|
211 | 723 | role = self.request.POST.get('role') |
|
212 | 724 | |
|
213 | 725 | token = AuthTokenModel().create( |
|
214 | 726 | c.user.user_id, description, lifetime, role) |
|
215 | 727 | token_data = token.get_api_data() |
|
216 | 728 | |
|
217 | 729 | self.maybe_attach_token_scope(token) |
|
218 | 730 | audit_logger.store_web( |
|
219 | 731 | 'user.edit.token.add', action_data={ |
|
220 | 732 | 'data': {'token': token_data, 'user': user_data}}, |
|
221 | 733 | user=self._rhodecode_user, ) |
|
222 | 734 | Session().commit() |
|
223 | 735 | |
|
224 | 736 | h.flash(_("Auth token successfully created"), category='success') |
|
225 | 737 | return HTTPFound(h.route_path('edit_user_auth_tokens', user_id=user_id)) |
|
226 | 738 | |
|
227 | 739 | @LoginRequired() |
|
228 | 740 | @HasPermissionAllDecorator('hg.admin') |
|
229 | 741 | @CSRFRequired() |
|
230 | 742 | @view_config( |
|
231 | 743 | route_name='edit_user_auth_tokens_delete', request_method='POST') |
|
232 | 744 | def auth_tokens_delete(self): |
|
233 | 745 | _ = self.request.translate |
|
234 | 746 | c = self.load_default_context() |
|
235 | 747 | |
|
236 |
user_id = self. |
|
|
237 |
c.user = |
|
|
238 | self._redirect_for_default_user(c.user.username) | |
|
748 | user_id = self.db_user_id | |
|
749 | c.user = self.db_user | |
|
750 | ||
|
239 | 751 | user_data = c.user.get_api_data() |
|
240 | 752 | |
|
241 | 753 | del_auth_token = self.request.POST.get('del_auth_token') |
|
242 | 754 | |
|
243 | 755 | if del_auth_token: |
|
244 | 756 | token = UserApiKeys.get_or_404(del_auth_token) |
|
245 | 757 | token_data = token.get_api_data() |
|
246 | 758 | |
|
247 | 759 | AuthTokenModel().delete(del_auth_token, c.user.user_id) |
|
248 | 760 | audit_logger.store_web( |
|
249 | 761 | 'user.edit.token.delete', action_data={ |
|
250 | 762 | 'data': {'token': token_data, 'user': user_data}}, |
|
251 | 763 | user=self._rhodecode_user,) |
|
252 | 764 | Session().commit() |
|
253 | 765 | h.flash(_("Auth token successfully deleted"), category='success') |
|
254 | 766 | |
|
255 | 767 | return HTTPFound(h.route_path('edit_user_auth_tokens', user_id=user_id)) |
|
256 | 768 | |
|
257 | 769 | @LoginRequired() |
|
258 | 770 | @HasPermissionAllDecorator('hg.admin') |
|
259 | 771 | @view_config( |
|
260 | 772 | route_name='edit_user_ssh_keys', request_method='GET', |
|
261 | 773 | renderer='rhodecode:templates/admin/users/user_edit.mako') |
|
262 | 774 | def ssh_keys(self): |
|
263 | 775 | _ = self.request.translate |
|
264 | 776 | c = self.load_default_context() |
|
265 | ||
|
266 | user_id = self.request.matchdict.get('user_id') | |
|
267 | c.user = User.get_or_404(user_id) | |
|
268 | self._redirect_for_default_user(c.user.username) | |
|
777 | c.user = self.db_user | |
|
269 | 778 | |
|
270 | 779 | c.active = 'ssh_keys' |
|
271 | 780 | c.default_key = self.request.GET.get('default_key') |
|
272 | 781 | c.user_ssh_keys = SshKeyModel().get_ssh_keys(c.user.user_id) |
|
273 | 782 | return self._get_template_context(c) |
|
274 | 783 | |
|
275 | 784 | @LoginRequired() |
|
276 | 785 | @HasPermissionAllDecorator('hg.admin') |
|
277 | 786 | @view_config( |
|
278 | 787 | route_name='edit_user_ssh_keys_generate_keypair', request_method='GET', |
|
279 | 788 | renderer='rhodecode:templates/admin/users/user_edit.mako') |
|
280 | 789 | def ssh_keys_generate_keypair(self): |
|
281 | 790 | _ = self.request.translate |
|
282 | 791 | c = self.load_default_context() |
|
283 | 792 | |
|
284 | user_id = self.request.matchdict.get('user_id') | |
|
285 | c.user = User.get_or_404(user_id) | |
|
286 | self._redirect_for_default_user(c.user.username) | |
|
793 | c.user = self.db_user | |
|
287 | 794 | |
|
288 | 795 | c.active = 'ssh_keys_generate' |
|
289 | 796 | comment = 'RhodeCode-SSH {}'.format(c.user.email or '') |
|
290 | 797 | c.private, c.public = SshKeyModel().generate_keypair(comment=comment) |
|
291 | 798 | |
|
292 | 799 | return self._get_template_context(c) |
|
293 | 800 | |
|
294 | 801 | @LoginRequired() |
|
295 | 802 | @HasPermissionAllDecorator('hg.admin') |
|
296 | 803 | @CSRFRequired() |
|
297 | 804 | @view_config( |
|
298 | 805 | route_name='edit_user_ssh_keys_add', request_method='POST') |
|
299 | 806 | def ssh_keys_add(self): |
|
300 | 807 | _ = self.request.translate |
|
301 | 808 | c = self.load_default_context() |
|
302 | 809 | |
|
303 |
user_id = self. |
|
|
304 |
c.user = |
|
|
305 | ||
|
306 | self._redirect_for_default_user(c.user.username) | |
|
810 | user_id = self.db_user_id | |
|
811 | c.user = self.db_user | |
|
307 | 812 | |
|
308 | 813 | user_data = c.user.get_api_data() |
|
309 | 814 | key_data = self.request.POST.get('key_data') |
|
310 | 815 | description = self.request.POST.get('description') |
|
311 | 816 | |
|
312 | 817 | try: |
|
313 | 818 | if not key_data: |
|
314 | 819 | raise ValueError('Please add a valid public key') |
|
315 | 820 | |
|
316 | 821 | key = SshKeyModel().parse_key(key_data.strip()) |
|
317 | 822 | fingerprint = key.hash_md5() |
|
318 | 823 | |
|
319 | 824 | ssh_key = SshKeyModel().create( |
|
320 | 825 | c.user.user_id, fingerprint, key_data, description) |
|
321 | 826 | ssh_key_data = ssh_key.get_api_data() |
|
322 | 827 | |
|
323 | 828 | audit_logger.store_web( |
|
324 | 829 | 'user.edit.ssh_key.add', action_data={ |
|
325 | 830 | 'data': {'ssh_key': ssh_key_data, 'user': user_data}}, |
|
326 | 831 | user=self._rhodecode_user, ) |
|
327 | 832 | Session().commit() |
|
328 | 833 | |
|
329 | 834 | # Trigger an event on change of keys. |
|
330 | 835 | trigger(SshKeyFileChangeEvent(), self.request.registry) |
|
331 | 836 | |
|
332 | 837 | h.flash(_("Ssh Key successfully created"), category='success') |
|
333 | 838 | |
|
334 | 839 | except IntegrityError: |
|
335 | 840 | log.exception("Exception during ssh key saving") |
|
336 | 841 | h.flash(_('An error occurred during ssh key saving: {}').format( |
|
337 | 842 | 'Such key already exists, please use a different one'), |
|
338 | 843 | category='error') |
|
339 | 844 | except Exception as e: |
|
340 | 845 | log.exception("Exception during ssh key saving") |
|
341 | 846 | h.flash(_('An error occurred during ssh key saving: {}').format(e), |
|
342 | 847 | category='error') |
|
343 | 848 | |
|
344 | 849 | return HTTPFound( |
|
345 | 850 | h.route_path('edit_user_ssh_keys', user_id=user_id)) |
|
346 | 851 | |
|
347 | 852 | @LoginRequired() |
|
348 | 853 | @HasPermissionAllDecorator('hg.admin') |
|
349 | 854 | @CSRFRequired() |
|
350 | 855 | @view_config( |
|
351 | 856 | route_name='edit_user_ssh_keys_delete', request_method='POST') |
|
352 | 857 | def ssh_keys_delete(self): |
|
353 | 858 | _ = self.request.translate |
|
354 | 859 | c = self.load_default_context() |
|
355 | 860 | |
|
356 |
user_id = self. |
|
|
357 |
c.user = |
|
|
358 | self._redirect_for_default_user(c.user.username) | |
|
861 | user_id = self.db_user_id | |
|
862 | c.user = self.db_user | |
|
863 | ||
|
359 | 864 | user_data = c.user.get_api_data() |
|
360 | 865 | |
|
361 | 866 | del_ssh_key = self.request.POST.get('del_ssh_key') |
|
362 | 867 | |
|
363 | 868 | if del_ssh_key: |
|
364 | 869 | ssh_key = UserSshKeys.get_or_404(del_ssh_key) |
|
365 | 870 | ssh_key_data = ssh_key.get_api_data() |
|
366 | 871 | |
|
367 | 872 | SshKeyModel().delete(del_ssh_key, c.user.user_id) |
|
368 | 873 | audit_logger.store_web( |
|
369 | 874 | 'user.edit.ssh_key.delete', action_data={ |
|
370 | 875 | 'data': {'ssh_key': ssh_key_data, 'user': user_data}}, |
|
371 | 876 | user=self._rhodecode_user,) |
|
372 | 877 | Session().commit() |
|
373 | 878 | # Trigger an event on change of keys. |
|
374 | 879 | trigger(SshKeyFileChangeEvent(), self.request.registry) |
|
375 | 880 | h.flash(_("Ssh key successfully deleted"), category='success') |
|
376 | 881 | |
|
377 | 882 | return HTTPFound(h.route_path('edit_user_ssh_keys', user_id=user_id)) |
|
378 | 883 | |
|
379 | 884 | @LoginRequired() |
|
380 | 885 | @HasPermissionAllDecorator('hg.admin') |
|
381 | 886 | @view_config( |
|
382 | 887 | route_name='edit_user_emails', request_method='GET', |
|
383 | 888 | renderer='rhodecode:templates/admin/users/user_edit.mako') |
|
384 | 889 | def emails(self): |
|
385 | 890 | _ = self.request.translate |
|
386 | 891 | c = self.load_default_context() |
|
387 | ||
|
388 | user_id = self.request.matchdict.get('user_id') | |
|
389 | c.user = User.get_or_404(user_id) | |
|
390 | self._redirect_for_default_user(c.user.username) | |
|
892 | c.user = self.db_user | |
|
391 | 893 | |
|
392 | 894 | c.active = 'emails' |
|
393 | 895 | c.user_email_map = UserEmailMap.query() \ |
|
394 | 896 | .filter(UserEmailMap.user == c.user).all() |
|
395 | 897 | |
|
396 | 898 | return self._get_template_context(c) |
|
397 | 899 | |
|
398 | 900 | @LoginRequired() |
|
399 | 901 | @HasPermissionAllDecorator('hg.admin') |
|
400 | 902 | @CSRFRequired() |
|
401 | 903 | @view_config( |
|
402 | 904 | route_name='edit_user_emails_add', request_method='POST') |
|
403 | 905 | def emails_add(self): |
|
404 | 906 | _ = self.request.translate |
|
405 | 907 | c = self.load_default_context() |
|
406 | 908 | |
|
407 |
user_id = self. |
|
|
408 |
c.user = |
|
|
409 | self._redirect_for_default_user(c.user.username) | |
|
909 | user_id = self.db_user_id | |
|
910 | c.user = self.db_user | |
|
410 | 911 | |
|
411 | 912 | email = self.request.POST.get('new_email') |
|
412 | 913 | user_data = c.user.get_api_data() |
|
413 | 914 | try: |
|
414 | 915 | UserModel().add_extra_email(c.user.user_id, email) |
|
415 | 916 | audit_logger.store_web( |
|
416 |
'user.edit.email.add', |
|
|
917 | 'user.edit.email.add', | |
|
918 | action_data={'email': email, 'user': user_data}, | |
|
417 | 919 | user=self._rhodecode_user) |
|
418 | 920 | Session().commit() |
|
419 | 921 | h.flash(_("Added new email address `%s` for user account") % email, |
|
420 | 922 | category='success') |
|
421 | 923 | except formencode.Invalid as error: |
|
422 | 924 | h.flash(h.escape(error.error_dict['email']), category='error') |
|
925 | except IntegrityError: | |
|
926 | log.warning("Email %s already exists", email) | |
|
927 | h.flash(_('Email `{}` is already registered for another user.').format(email), | |
|
928 | category='error') | |
|
423 | 929 | except Exception: |
|
424 | 930 | log.exception("Exception during email saving") |
|
425 | 931 | h.flash(_('An error occurred during email saving'), |
|
426 | 932 | category='error') |
|
427 | 933 | raise HTTPFound(h.route_path('edit_user_emails', user_id=user_id)) |
|
428 | 934 | |
|
429 | 935 | @LoginRequired() |
|
430 | 936 | @HasPermissionAllDecorator('hg.admin') |
|
431 | 937 | @CSRFRequired() |
|
432 | 938 | @view_config( |
|
433 | 939 | route_name='edit_user_emails_delete', request_method='POST') |
|
434 | 940 | def emails_delete(self): |
|
435 | 941 | _ = self.request.translate |
|
436 | 942 | c = self.load_default_context() |
|
437 | 943 | |
|
438 |
user_id = self. |
|
|
439 |
c.user = |
|
|
440 | self._redirect_for_default_user(c.user.username) | |
|
944 | user_id = self.db_user_id | |
|
945 | c.user = self.db_user | |
|
441 | 946 | |
|
442 | 947 | email_id = self.request.POST.get('del_email_id') |
|
443 | 948 | user_model = UserModel() |
|
444 | 949 | |
|
445 | 950 | email = UserEmailMap.query().get(email_id).email |
|
446 | 951 | user_data = c.user.get_api_data() |
|
447 | 952 | user_model.delete_extra_email(c.user.user_id, email_id) |
|
448 | 953 | audit_logger.store_web( |
|
449 |
'user.edit.email.delete', |
|
|
954 | 'user.edit.email.delete', | |
|
955 | action_data={'email': email, 'user': user_data}, | |
|
450 | 956 | user=self._rhodecode_user) |
|
451 | 957 | Session().commit() |
|
452 | 958 | h.flash(_("Removed email address from user account"), |
|
453 | 959 | category='success') |
|
454 | 960 | raise HTTPFound(h.route_path('edit_user_emails', user_id=user_id)) |
|
455 | 961 | |
|
456 | 962 | @LoginRequired() |
|
457 | 963 | @HasPermissionAllDecorator('hg.admin') |
|
458 | 964 | @view_config( |
|
459 | 965 | route_name='edit_user_ips', request_method='GET', |
|
460 | 966 | renderer='rhodecode:templates/admin/users/user_edit.mako') |
|
461 | 967 | def ips(self): |
|
462 | 968 | _ = self.request.translate |
|
463 | 969 | c = self.load_default_context() |
|
464 | ||
|
465 | user_id = self.request.matchdict.get('user_id') | |
|
466 | c.user = User.get_or_404(user_id) | |
|
467 | self._redirect_for_default_user(c.user.username) | |
|
970 | c.user = self.db_user | |
|
468 | 971 | |
|
469 | 972 | c.active = 'ips' |
|
470 | 973 | c.user_ip_map = UserIpMap.query() \ |
|
471 | 974 | .filter(UserIpMap.user == c.user).all() |
|
472 | 975 | |
|
473 | 976 | c.inherit_default_ips = c.user.inherit_default_permissions |
|
474 | 977 | c.default_user_ip_map = UserIpMap.query() \ |
|
475 | 978 | .filter(UserIpMap.user == User.get_default_user()).all() |
|
476 | 979 | |
|
477 | 980 | return self._get_template_context(c) |
|
478 | 981 | |
|
479 | 982 | @LoginRequired() |
|
480 | 983 | @HasPermissionAllDecorator('hg.admin') |
|
481 | 984 | @CSRFRequired() |
|
482 | 985 | @view_config( |
|
483 | 986 | route_name='edit_user_ips_add', request_method='POST') |
|
987 | # NOTE(marcink): this view is allowed for default users, as we can | |
|
988 | # edit their IP white list | |
|
484 | 989 | def ips_add(self): |
|
485 | 990 | _ = self.request.translate |
|
486 | 991 | c = self.load_default_context() |
|
487 | 992 | |
|
488 |
user_id = self. |
|
|
489 |
c.user = |
|
|
490 | # NOTE(marcink): this view is allowed for default users, as we can | |
|
491 | # edit their IP white list | |
|
993 | user_id = self.db_user_id | |
|
994 | c.user = self.db_user | |
|
492 | 995 | |
|
493 | 996 | user_model = UserModel() |
|
494 | 997 | desc = self.request.POST.get('description') |
|
495 | 998 | try: |
|
496 | 999 | ip_list = user_model.parse_ip_range( |
|
497 | 1000 | self.request.POST.get('new_ip')) |
|
498 | 1001 | except Exception as e: |
|
499 | 1002 | ip_list = [] |
|
500 | 1003 | log.exception("Exception during ip saving") |
|
501 | 1004 | h.flash(_('An error occurred during ip saving:%s' % (e,)), |
|
502 | 1005 | category='error') |
|
503 | 1006 | added = [] |
|
504 | 1007 | user_data = c.user.get_api_data() |
|
505 | 1008 | for ip in ip_list: |
|
506 | 1009 | try: |
|
507 | 1010 | user_model.add_extra_ip(c.user.user_id, ip, desc) |
|
508 | 1011 | audit_logger.store_web( |
|
509 |
'user.edit.ip.add', |
|
|
1012 | 'user.edit.ip.add', | |
|
1013 | action_data={'ip': ip, 'user': user_data}, | |
|
510 | 1014 | user=self._rhodecode_user) |
|
511 | 1015 | Session().commit() |
|
512 | 1016 | added.append(ip) |
|
513 | 1017 | except formencode.Invalid as error: |
|
514 | 1018 | msg = error.error_dict['ip'] |
|
515 | 1019 | h.flash(msg, category='error') |
|
516 | 1020 | except Exception: |
|
517 | 1021 | log.exception("Exception during ip saving") |
|
518 | 1022 | h.flash(_('An error occurred during ip saving'), |
|
519 | 1023 | category='error') |
|
520 | 1024 | if added: |
|
521 | 1025 | h.flash( |
|
522 | 1026 | _("Added ips %s to user whitelist") % (', '.join(ip_list), ), |
|
523 | 1027 | category='success') |
|
524 | 1028 | if 'default_user' in self.request.POST: |
|
525 | 1029 | # case for editing global IP list we do it for 'DEFAULT' user |
|
526 | 1030 | raise HTTPFound(h.route_path('admin_permissions_ips')) |
|
527 | 1031 | raise HTTPFound(h.route_path('edit_user_ips', user_id=user_id)) |
|
528 | 1032 | |
|
529 | 1033 | @LoginRequired() |
|
530 | 1034 | @HasPermissionAllDecorator('hg.admin') |
|
531 | 1035 | @CSRFRequired() |
|
532 | 1036 | @view_config( |
|
533 | 1037 | route_name='edit_user_ips_delete', request_method='POST') |
|
1038 | # NOTE(marcink): this view is allowed for default users, as we can | |
|
1039 | # edit their IP white list | |
|
534 | 1040 | def ips_delete(self): |
|
535 | 1041 | _ = self.request.translate |
|
536 | 1042 | c = self.load_default_context() |
|
537 | 1043 | |
|
538 |
user_id = self. |
|
|
539 |
c.user = |
|
|
540 | # NOTE(marcink): this view is allowed for default users, as we can | |
|
541 | # edit their IP white list | |
|
1044 | user_id = self.db_user_id | |
|
1045 | c.user = self.db_user | |
|
542 | 1046 | |
|
543 | 1047 | ip_id = self.request.POST.get('del_ip_id') |
|
544 | 1048 | user_model = UserModel() |
|
545 | 1049 | user_data = c.user.get_api_data() |
|
546 | 1050 | ip = UserIpMap.query().get(ip_id).ip_addr |
|
547 | 1051 | user_model.delete_extra_ip(c.user.user_id, ip_id) |
|
548 | 1052 | audit_logger.store_web( |
|
549 | 1053 | 'user.edit.ip.delete', action_data={'ip': ip, 'user': user_data}, |
|
550 | 1054 | user=self._rhodecode_user) |
|
551 | 1055 | Session().commit() |
|
552 | 1056 | h.flash(_("Removed ip address from user whitelist"), category='success') |
|
553 | 1057 | |
|
554 | 1058 | if 'default_user' in self.request.POST: |
|
555 | 1059 | # case for editing global IP list we do it for 'DEFAULT' user |
|
556 | 1060 | raise HTTPFound(h.route_path('admin_permissions_ips')) |
|
557 | 1061 | raise HTTPFound(h.route_path('edit_user_ips', user_id=user_id)) |
|
558 | 1062 | |
|
559 | 1063 | @LoginRequired() |
|
560 | 1064 | @HasPermissionAllDecorator('hg.admin') |
|
561 | 1065 | @view_config( |
|
562 | 1066 | route_name='edit_user_groups_management', request_method='GET', |
|
563 | 1067 | renderer='rhodecode:templates/admin/users/user_edit.mako') |
|
564 | 1068 | def groups_management(self): |
|
565 | 1069 | c = self.load_default_context() |
|
1070 | c.user = self.db_user | |
|
1071 | c.data = c.user.group_member | |
|
566 | 1072 | |
|
567 | user_id = self.request.matchdict.get('user_id') | |
|
568 | c.user = User.get_or_404(user_id) | |
|
569 | c.data = c.user.group_member | |
|
570 | self._redirect_for_default_user(c.user.username) | |
|
571 | 1073 | groups = [UserGroupModel.get_user_groups_as_dict(group.users_group) |
|
572 | 1074 | for group in c.user.group_member] |
|
573 | 1075 | c.groups = json.dumps(groups) |
|
574 | 1076 | c.active = 'groups' |
|
575 | 1077 | |
|
576 | 1078 | return self._get_template_context(c) |
|
577 | 1079 | |
|
578 | 1080 | @LoginRequired() |
|
579 | 1081 | @HasPermissionAllDecorator('hg.admin') |
|
580 | 1082 | @CSRFRequired() |
|
581 | 1083 | @view_config( |
|
582 | 1084 | route_name='edit_user_groups_management_updates', request_method='POST') |
|
583 | 1085 | def groups_management_updates(self): |
|
584 | 1086 | _ = self.request.translate |
|
585 | 1087 | c = self.load_default_context() |
|
586 | 1088 | |
|
587 |
user_id = self. |
|
|
588 |
c.user = |
|
|
589 | self._redirect_for_default_user(c.user.username) | |
|
1089 | user_id = self.db_user_id | |
|
1090 | c.user = self.db_user | |
|
590 | 1091 | |
|
591 | 1092 | user_groups = set(self.request.POST.getall('users_group_id')) |
|
592 | 1093 | user_groups_objects = [] |
|
593 | 1094 | |
|
594 | 1095 | for ugid in user_groups: |
|
595 | 1096 | user_groups_objects.append( |
|
596 | 1097 | UserGroupModel().get_group(safe_int(ugid))) |
|
597 | 1098 | user_group_model = UserGroupModel() |
|
598 | user_group_model.change_groups(c.user, user_groups_objects) | |
|
1099 | added_to_groups, removed_from_groups = \ | |
|
1100 | user_group_model.change_groups(c.user, user_groups_objects) | |
|
1101 | ||
|
1102 | user_data = c.user.get_api_data() | |
|
1103 | for user_group_id in added_to_groups: | |
|
1104 | user_group = UserGroup.get(user_group_id) | |
|
1105 | old_values = user_group.get_api_data() | |
|
1106 | audit_logger.store_web( | |
|
1107 | 'user_group.edit.member.add', | |
|
1108 | action_data={'user': user_data, 'old_data': old_values}, | |
|
1109 | user=self._rhodecode_user) | |
|
1110 | ||
|
1111 | for user_group_id in removed_from_groups: | |
|
1112 | user_group = UserGroup.get(user_group_id) | |
|
1113 | old_values = user_group.get_api_data() | |
|
1114 | audit_logger.store_web( | |
|
1115 | 'user_group.edit.member.delete', | |
|
1116 | action_data={'user': user_data, 'old_data': old_values}, | |
|
1117 | user=self._rhodecode_user) | |
|
599 | 1118 | |
|
600 | 1119 | Session().commit() |
|
601 | 1120 | c.active = 'user_groups_management' |
|
602 | 1121 | h.flash(_("Groups successfully changed"), category='success') |
|
603 | 1122 | |
|
604 | 1123 | return HTTPFound(h.route_path( |
|
605 | 1124 | 'edit_user_groups_management', user_id=user_id)) |
|
606 | 1125 | |
|
607 | 1126 | @LoginRequired() |
|
608 | 1127 | @HasPermissionAllDecorator('hg.admin') |
|
609 | 1128 | @view_config( |
|
610 | 1129 | route_name='edit_user_audit_logs', request_method='GET', |
|
611 | 1130 | renderer='rhodecode:templates/admin/users/user_edit.mako') |
|
612 | 1131 | def user_audit_logs(self): |
|
613 | 1132 | _ = self.request.translate |
|
614 | 1133 | c = self.load_default_context() |
|
1134 | c.user = self.db_user | |
|
615 | 1135 | |
|
616 | user_id = self.request.matchdict.get('user_id') | |
|
617 | c.user = User.get_or_404(user_id) | |
|
618 | self._redirect_for_default_user(c.user.username) | |
|
619 | 1136 | c.active = 'audit' |
|
620 | 1137 | |
|
621 | 1138 | p = safe_int(self.request.GET.get('page', 1), 1) |
|
622 | 1139 | |
|
623 | 1140 | filter_term = self.request.GET.get('filter') |
|
624 | 1141 | user_log = UserModel().get_user_log(c.user, filter_term) |
|
625 | 1142 | |
|
626 | 1143 | def url_generator(**kw): |
|
627 | 1144 | if filter_term: |
|
628 | 1145 | kw['filter'] = filter_term |
|
629 | 1146 | return self.request.current_route_path(_query=kw) |
|
630 | 1147 | |
|
631 | 1148 | c.audit_logs = h.Page( |
|
632 | 1149 | user_log, page=p, items_per_page=10, url=url_generator) |
|
633 | 1150 | c.filter_term = filter_term |
|
634 | 1151 | return self._get_template_context(c) |
|
635 | 1152 | |
|
636 | 1153 | @LoginRequired() |
|
637 | 1154 | @HasPermissionAllDecorator('hg.admin') |
|
638 | 1155 | @view_config( |
|
639 | 1156 | route_name='edit_user_perms_summary', request_method='GET', |
|
640 | 1157 | renderer='rhodecode:templates/admin/users/user_edit.mako') |
|
641 | 1158 | def user_perms_summary(self): |
|
642 | 1159 | _ = self.request.translate |
|
643 | 1160 | c = self.load_default_context() |
|
644 | ||
|
645 | user_id = self.request.matchdict.get('user_id') | |
|
646 | c.user = User.get_or_404(user_id) | |
|
647 | self._redirect_for_default_user(c.user.username) | |
|
1161 | c.user = self.db_user | |
|
648 | 1162 | |
|
649 | 1163 | c.active = 'perms_summary' |
|
650 | 1164 | c.perm_user = c.user.AuthUser(ip_addr=self.request.remote_addr) |
|
651 | 1165 | |
|
652 | 1166 | return self._get_template_context(c) |
|
653 | 1167 | |
|
654 | 1168 | @LoginRequired() |
|
655 | 1169 | @HasPermissionAllDecorator('hg.admin') |
|
656 | 1170 | @view_config( |
|
657 | 1171 | route_name='edit_user_perms_summary_json', request_method='GET', |
|
658 | 1172 | renderer='json_ext') |
|
659 | 1173 | def user_perms_summary_json(self): |
|
660 | 1174 | self.load_default_context() |
|
661 | ||
|
662 | user_id = self.request.matchdict.get('user_id') | |
|
663 | user = User.get_or_404(user_id) | |
|
664 | self._redirect_for_default_user(user.username) | |
|
665 | ||
|
666 | perm_user = user.AuthUser(ip_addr=self.request.remote_addr) | |
|
1175 | perm_user = self.db_user.AuthUser(ip_addr=self.request.remote_addr) | |
|
667 | 1176 | |
|
668 | 1177 | return perm_user.permissions |
@@ -1,182 +1,182 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | |
|
3 | 3 | # Copyright (C) 2010-2017 RhodeCode GmbH |
|
4 | 4 | # |
|
5 | 5 | # This program is free software: you can redistribute it and/or modify |
|
6 | 6 | # it under the terms of the GNU Affero General Public License, version 3 |
|
7 | 7 | # (only), as published by the Free Software Foundation. |
|
8 | 8 | # |
|
9 | 9 | # This program is distributed in the hope that it will be useful, |
|
10 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of |
|
11 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|
12 | 12 | # GNU General Public License for more details. |
|
13 | 13 | # |
|
14 | 14 | # You should have received a copy of the GNU Affero General Public License |
|
15 | 15 | # along with this program. If not, see <http://www.gnu.org/licenses/>. |
|
16 | 16 | # |
|
17 | 17 | # This program is dual-licensed. If you wish to learn more about the |
|
18 | 18 | # RhodeCode Enterprise Edition, including its added features, Support services, |
|
19 | 19 | # and proprietary license terms, please see https://rhodecode.com/licenses/ |
|
20 | 20 | |
|
21 | 21 | """ |
|
22 | 22 | Pylons environment configuration |
|
23 | 23 | """ |
|
24 | 24 | |
|
25 | 25 | import os |
|
26 | 26 | import logging |
|
27 | 27 | import rhodecode |
|
28 | 28 | import platform |
|
29 | 29 | import re |
|
30 | 30 | import io |
|
31 | 31 | |
|
32 | 32 | from mako.lookup import TemplateLookup |
|
33 | 33 | from pylons.configuration import PylonsConfig |
|
34 | 34 | from pylons.error import handle_mako_error |
|
35 | 35 | from pyramid.settings import asbool |
|
36 | 36 | |
|
37 | 37 | # ------------------------------------------------------------------------------ |
|
38 | 38 | # CELERY magic until refactor - issue #4163 - import order matters here: |
|
39 | 39 | from rhodecode.lib import celerypylons # this must be first, celerypylons |
|
40 | 40 | # sets config settings upon import |
|
41 | 41 | |
|
42 | 42 | import rhodecode.integrations # any modules using celery task |
|
43 | 43 | # decorators should be added afterwards: |
|
44 | 44 | # ------------------------------------------------------------------------------ |
|
45 | 45 | |
|
46 | 46 | from rhodecode.lib import app_globals |
|
47 | 47 | from rhodecode.config import utils |
|
48 | 48 | from rhodecode.config.routing import make_map |
|
49 | 49 | from rhodecode.config.jsroutes import generate_jsroutes_content |
|
50 | 50 | |
|
51 | 51 | from rhodecode.lib import helpers |
|
52 | 52 | from rhodecode.lib.auth import set_available_permissions |
|
53 | 53 | from rhodecode.lib.utils import ( |
|
54 | 54 | repo2db_mapper, make_db_config, set_rhodecode_config, |
|
55 | 55 | load_rcextensions) |
|
56 | 56 | from rhodecode.lib.utils2 import str2bool, aslist |
|
57 | 57 | from rhodecode.lib.vcs import connect_vcs, start_vcs_server |
|
58 | 58 | from rhodecode.model.scm import ScmModel |
|
59 | 59 | |
|
60 | 60 | log = logging.getLogger(__name__) |
|
61 | 61 | |
|
62 | 62 | def load_environment(global_conf, app_conf, initial=False, |
|
63 | 63 | test_env=None, test_index=None): |
|
64 | 64 | """ |
|
65 | 65 | Configure the Pylons environment via the ``pylons.config`` |
|
66 | 66 | object |
|
67 | 67 | """ |
|
68 | 68 | config = PylonsConfig() |
|
69 | 69 | |
|
70 | 70 | |
|
71 | 71 | # Pylons paths |
|
72 | 72 | root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) |
|
73 | 73 | paths = { |
|
74 | 74 | 'root': root, |
|
75 | 75 | 'controllers': os.path.join(root, 'controllers'), |
|
76 | 76 | 'static_files': os.path.join(root, 'public'), |
|
77 | 77 | 'templates': [os.path.join(root, 'templates')], |
|
78 | 78 | } |
|
79 | 79 | |
|
80 | 80 | # Initialize config with the basic options |
|
81 | 81 | config.init_app(global_conf, app_conf, package='rhodecode', paths=paths) |
|
82 | 82 | |
|
83 | 83 | # store some globals into rhodecode |
|
84 | 84 | rhodecode.CELERY_ENABLED = str2bool(config['app_conf'].get('use_celery')) |
|
85 | 85 | rhodecode.CELERY_EAGER = str2bool( |
|
86 | 86 | config['app_conf'].get('celery.always.eager')) |
|
87 | 87 | |
|
88 | 88 | config['routes.map'] = make_map(config) |
|
89 | 89 | |
|
90 | 90 | config['pylons.app_globals'] = app_globals.Globals(config) |
|
91 | 91 | config['pylons.h'] = helpers |
|
92 | 92 | rhodecode.CONFIG = config |
|
93 | 93 | |
|
94 | 94 | load_rcextensions(root_path=config['here']) |
|
95 | 95 | |
|
96 | 96 | # Setup cache object as early as possible |
|
97 | 97 | import pylons |
|
98 | 98 | pylons.cache._push_object(config['pylons.app_globals'].cache) |
|
99 | 99 | |
|
100 | 100 | # Create the Mako TemplateLookup, with the default auto-escaping |
|
101 | 101 | config['pylons.app_globals'].mako_lookup = TemplateLookup( |
|
102 | 102 | directories=paths['templates'], |
|
103 | 103 | error_handler=handle_mako_error, |
|
104 | 104 | module_directory=os.path.join(app_conf['cache_dir'], 'templates'), |
|
105 | 105 | input_encoding='utf-8', default_filters=['escape'], |
|
106 | 106 | imports=['from webhelpers.html import escape']) |
|
107 | 107 | |
|
108 | 108 | # sets the c attribute access when don't existing attribute are accessed |
|
109 | 109 | config['pylons.strict_tmpl_context'] = True |
|
110 | 110 | |
|
111 | 111 | # configure channelstream |
|
112 | 112 | config['channelstream_config'] = { |
|
113 | 113 | 'enabled': asbool(config.get('channelstream.enabled', False)), |
|
114 | 114 | 'server': config.get('channelstream.server'), |
|
115 | 115 | 'secret': config.get('channelstream.secret') |
|
116 | 116 | } |
|
117 | 117 | |
|
118 | set_available_permissions(config) | |
|
119 | 118 | db_cfg = make_db_config(clear_session=True) |
|
120 | 119 | |
|
121 | 120 | repos_path = list(db_cfg.items('paths'))[0][1] |
|
122 | 121 | config['base_path'] = repos_path |
|
123 | 122 | |
|
124 | 123 | # store db config also in main global CONFIG |
|
125 | 124 | set_rhodecode_config(config) |
|
126 | 125 | |
|
127 | 126 | # configure instance id |
|
128 | 127 | utils.set_instance_id(config) |
|
129 | 128 | |
|
130 | 129 | # CONFIGURATION OPTIONS HERE (note: all config options will override |
|
131 | 130 | # any Pylons config options) |
|
132 | 131 | |
|
133 | 132 | # store config reference into our module to skip import magic of pylons |
|
134 | 133 | rhodecode.CONFIG.update(config) |
|
135 | 134 | |
|
136 | 135 | return config |
|
137 | 136 | |
|
138 | 137 | |
|
139 | 138 | def load_pyramid_environment(global_config, settings): |
|
140 | 139 | # Some parts of the code expect a merge of global and app settings. |
|
141 | 140 | settings_merged = global_config.copy() |
|
142 | 141 | settings_merged.update(settings) |
|
143 | 142 | |
|
144 | 143 | # Store the settings to make them available to other modules. |
|
145 | 144 | rhodecode.PYRAMID_SETTINGS = settings_merged |
|
146 | 145 | # NOTE(marcink): needs to be enabled after full port to pyramid |
|
147 | 146 | # rhodecode.CONFIG = config |
|
148 | 147 | |
|
149 | 148 | # If this is a test run we prepare the test environment like |
|
150 | 149 | # creating a test database, test search index and test repositories. |
|
151 | 150 | # This has to be done before the database connection is initialized. |
|
152 | 151 | if settings['is_test']: |
|
153 | 152 | rhodecode.is_test = True |
|
154 | 153 | rhodecode.disable_error_handler = True |
|
155 | 154 | |
|
156 | 155 | utils.initialize_test_environment(settings_merged) |
|
157 | 156 | |
|
158 | 157 | # Initialize the database connection. |
|
159 | 158 | utils.initialize_database(settings_merged) |
|
160 | 159 | |
|
161 | 160 | # Limit backends to `vcs.backends` from configuration |
|
162 | 161 | for alias in rhodecode.BACKENDS.keys(): |
|
163 | 162 | if alias not in settings['vcs.backends']: |
|
164 | 163 | del rhodecode.BACKENDS[alias] |
|
165 | 164 | log.info('Enabled VCS backends: %s', rhodecode.BACKENDS.keys()) |
|
166 | 165 | |
|
167 | 166 | # initialize vcs client and optionally run the server if enabled |
|
168 | 167 | vcs_server_uri = settings['vcs.server'] |
|
169 | 168 | vcs_server_enabled = settings['vcs.server.enable'] |
|
170 | 169 | start_server = ( |
|
171 | 170 | settings['vcs.start_server'] and |
|
172 | 171 | not int(os.environ.get('RC_VCSSERVER_TEST_DISABLE', '0'))) |
|
173 | 172 | |
|
174 | 173 | if vcs_server_enabled and start_server: |
|
175 | 174 | log.info("Starting vcsserver") |
|
176 | 175 | start_vcs_server(server_and_port=vcs_server_uri, |
|
177 | 176 | protocol=utils.get_vcs_server_protocol(settings), |
|
178 | 177 | log_level=settings['vcs.server.log_level']) |
|
179 | 178 | |
|
180 | 179 | utils.configure_vcs(settings) |
|
180 | ||
|
181 | 181 | if vcs_server_enabled: |
|
182 | 182 | connect_vcs(vcs_server_uri, utils.get_vcs_server_protocol(settings)) |
@@ -1,536 +1,542 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | |
|
3 | 3 | # Copyright (C) 2010-2017 RhodeCode GmbH |
|
4 | 4 | # |
|
5 | 5 | # This program is free software: you can redistribute it and/or modify |
|
6 | 6 | # it under the terms of the GNU Affero General Public License, version 3 |
|
7 | 7 | # (only), as published by the Free Software Foundation. |
|
8 | 8 | # |
|
9 | 9 | # This program is distributed in the hope that it will be useful, |
|
10 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of |
|
11 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|
12 | 12 | # GNU General Public License for more details. |
|
13 | 13 | # |
|
14 | 14 | # You should have received a copy of the GNU Affero General Public License |
|
15 | 15 | # along with this program. If not, see <http://www.gnu.org/licenses/>. |
|
16 | 16 | # |
|
17 | 17 | # This program is dual-licensed. If you wish to learn more about the |
|
18 | 18 | # RhodeCode Enterprise Edition, including its added features, Support services, |
|
19 | 19 | # and proprietary license terms, please see https://rhodecode.com/licenses/ |
|
20 | 20 | |
|
21 | 21 | """ |
|
22 | 22 | Pylons middleware initialization |
|
23 | 23 | """ |
|
24 | 24 | import logging |
|
25 | 25 | import traceback |
|
26 | 26 | from collections import OrderedDict |
|
27 | 27 | |
|
28 | 28 | from paste.registry import RegistryManager |
|
29 | 29 | from paste.gzipper import make_gzip_middleware |
|
30 | 30 | from pylons.wsgiapp import PylonsApp |
|
31 | 31 | from pyramid.authorization import ACLAuthorizationPolicy |
|
32 | 32 | from pyramid.config import Configurator |
|
33 | 33 | from pyramid.settings import asbool, aslist |
|
34 | 34 | from pyramid.wsgi import wsgiapp |
|
35 | 35 | from pyramid.httpexceptions import ( |
|
36 | 36 | HTTPException, HTTPError, HTTPInternalServerError, HTTPFound) |
|
37 | 37 | from pyramid.events import ApplicationCreated |
|
38 | 38 | from pyramid.renderers import render_to_response |
|
39 | 39 | from routes.middleware import RoutesMiddleware |
|
40 | 40 | import rhodecode |
|
41 | 41 | |
|
42 | 42 | from rhodecode.model import meta |
|
43 | 43 | from rhodecode.config import patches |
|
44 | from rhodecode.config import utils as config_utils | |
|
44 | 45 | from rhodecode.config.routing import STATIC_FILE_PREFIX |
|
45 | 46 | from rhodecode.config.environment import ( |
|
46 | 47 | load_environment, load_pyramid_environment) |
|
47 | 48 | |
|
48 | 49 | from rhodecode.lib.vcs import VCSCommunicationError |
|
49 | 50 | from rhodecode.lib.exceptions import VCSServerUnavailable |
|
50 | 51 | from rhodecode.lib.middleware.appenlight import wrap_in_appenlight_if_enabled |
|
51 | 52 | from rhodecode.lib.middleware.error_handling import ( |
|
52 | 53 | PylonsErrorHandlingMiddleware) |
|
53 | 54 | from rhodecode.lib.middleware.https_fixup import HttpsFixup |
|
54 | 55 | from rhodecode.lib.middleware.vcs import VCSMiddleware |
|
55 | 56 | from rhodecode.lib.plugins.utils import register_rhodecode_plugin |
|
56 | 57 | from rhodecode.lib.utils2 import aslist as rhodecode_aslist, AttributeDict |
|
57 | 58 | from rhodecode.subscribers import ( |
|
58 | 59 | scan_repositories_if_enabled, write_js_routes_if_enabled, |
|
59 | write_metadata_if_needed) | |
|
60 | write_metadata_if_needed, inject_app_settings) | |
|
60 | 61 | |
|
61 | 62 | |
|
62 | 63 | log = logging.getLogger(__name__) |
|
63 | 64 | |
|
64 | 65 | |
|
65 | 66 | # this is used to avoid avoid the route lookup overhead in routesmiddleware |
|
66 | 67 | # for certain routes which won't go to pylons to - eg. static files, debugger |
|
67 | 68 | # it is only needed for the pylons migration and can be removed once complete |
|
68 | 69 | class SkippableRoutesMiddleware(RoutesMiddleware): |
|
69 | 70 | """ Routes middleware that allows you to skip prefixes """ |
|
70 | 71 | |
|
71 | 72 | def __init__(self, *args, **kw): |
|
72 | 73 | self.skip_prefixes = kw.pop('skip_prefixes', []) |
|
73 | 74 | super(SkippableRoutesMiddleware, self).__init__(*args, **kw) |
|
74 | 75 | |
|
75 | 76 | def __call__(self, environ, start_response): |
|
76 | 77 | for prefix in self.skip_prefixes: |
|
77 | 78 | if environ['PATH_INFO'].startswith(prefix): |
|
78 | 79 | # added to avoid the case when a missing /_static route falls |
|
79 | 80 | # through to pylons and causes an exception as pylons is |
|
80 | 81 | # expecting wsgiorg.routingargs to be set in the environ |
|
81 | 82 | # by RoutesMiddleware. |
|
82 | 83 | if 'wsgiorg.routing_args' not in environ: |
|
83 | 84 | environ['wsgiorg.routing_args'] = (None, {}) |
|
84 | 85 | return self.app(environ, start_response) |
|
85 | 86 | |
|
86 | 87 | return super(SkippableRoutesMiddleware, self).__call__( |
|
87 | 88 | environ, start_response) |
|
88 | 89 | |
|
89 | 90 | |
|
90 | 91 | def make_app(global_conf, static_files=True, **app_conf): |
|
91 | 92 | """Create a Pylons WSGI application and return it |
|
92 | 93 | |
|
93 | 94 | ``global_conf`` |
|
94 | 95 | The inherited configuration for this application. Normally from |
|
95 | 96 | the [DEFAULT] section of the Paste ini file. |
|
96 | 97 | |
|
97 | 98 | ``app_conf`` |
|
98 | 99 | The application's local configuration. Normally specified in |
|
99 | 100 | the [app:<name>] section of the Paste ini file (where <name> |
|
100 | 101 | defaults to main). |
|
101 | 102 | |
|
102 | 103 | """ |
|
103 | 104 | # Apply compatibility patches |
|
104 | 105 | patches.kombu_1_5_1_python_2_7_11() |
|
105 | 106 | patches.inspect_getargspec() |
|
106 | 107 | |
|
107 | 108 | # Configure the Pylons environment |
|
108 | 109 | config = load_environment(global_conf, app_conf) |
|
109 | 110 | |
|
110 | 111 | # The Pylons WSGI app |
|
111 | 112 | app = PylonsApp(config=config) |
|
112 | 113 | |
|
113 | 114 | # Establish the Registry for this application |
|
114 | 115 | app = RegistryManager(app) |
|
115 | 116 | |
|
116 | 117 | app.config = config |
|
117 | 118 | |
|
118 | 119 | return app |
|
119 | 120 | |
|
120 | 121 | |
|
121 | 122 | def make_pyramid_app(global_config, **settings): |
|
122 | 123 | """ |
|
123 | 124 | Constructs the WSGI application based on Pyramid and wraps the Pylons based |
|
124 | 125 | application. |
|
125 | 126 | |
|
126 | 127 | Specials: |
|
127 | 128 | |
|
128 | 129 | * We migrate from Pylons to Pyramid. While doing this, we keep both |
|
129 | 130 | frameworks functional. This involves moving some WSGI middlewares around |
|
130 | 131 | and providing access to some data internals, so that the old code is |
|
131 | 132 | still functional. |
|
132 | 133 | |
|
133 | 134 | * The application can also be integrated like a plugin via the call to |
|
134 | 135 | `includeme`. This is accompanied with the other utility functions which |
|
135 | 136 | are called. Changing this should be done with great care to not break |
|
136 | 137 | cases when these fragments are assembled from another place. |
|
137 | 138 | |
|
138 | 139 | """ |
|
139 | 140 | # The edition string should be available in pylons too, so we add it here |
|
140 | 141 | # before copying the settings. |
|
141 | 142 | settings.setdefault('rhodecode.edition', 'Community Edition') |
|
142 | 143 | |
|
143 | 144 | # As long as our Pylons application does expect "unprepared" settings, make |
|
144 | 145 | # sure that we keep an unmodified copy. This avoids unintentional change of |
|
145 | 146 | # behavior in the old application. |
|
146 | 147 | settings_pylons = settings.copy() |
|
147 | 148 | |
|
148 | 149 | sanitize_settings_and_apply_defaults(settings) |
|
150 | ||
|
149 | 151 | config = Configurator(settings=settings) |
|
152 | load_pyramid_environment(global_config, settings) | |
|
153 | ||
|
150 | 154 | add_pylons_compat_data(config.registry, global_config, settings_pylons) |
|
151 | 155 | |
|
152 | load_pyramid_environment(global_config, settings) | |
|
153 | ||
|
154 | 156 | includeme_first(config) |
|
155 | 157 | includeme(config) |
|
156 | 158 | |
|
157 | 159 | pyramid_app = config.make_wsgi_app() |
|
158 | 160 | pyramid_app = wrap_app_in_wsgi_middlewares(pyramid_app, config) |
|
159 | 161 | pyramid_app.config = config |
|
160 | 162 | |
|
161 | 163 | # creating the app uses a connection - return it after we are done |
|
162 | 164 | meta.Session.remove() |
|
163 | 165 | |
|
164 | 166 | return pyramid_app |
|
165 | 167 | |
|
166 | 168 | |
|
167 | 169 | def make_not_found_view(config): |
|
168 | 170 | """ |
|
169 | 171 | This creates the view which should be registered as not-found-view to |
|
170 | 172 | pyramid. Basically it contains of the old pylons app, converted to a view. |
|
171 | 173 | Additionally it is wrapped by some other middlewares. |
|
172 | 174 | """ |
|
173 | 175 | settings = config.registry.settings |
|
174 | 176 | vcs_server_enabled = settings['vcs.server.enable'] |
|
175 | 177 | |
|
176 | 178 | # Make pylons app from unprepared settings. |
|
177 | 179 | pylons_app = make_app( |
|
178 | 180 | config.registry._pylons_compat_global_config, |
|
179 | 181 | **config.registry._pylons_compat_settings) |
|
180 | 182 | config.registry._pylons_compat_config = pylons_app.config |
|
181 | 183 | |
|
182 | 184 | # Appenlight monitoring. |
|
183 | 185 | pylons_app, appenlight_client = wrap_in_appenlight_if_enabled( |
|
184 | 186 | pylons_app, settings) |
|
185 | 187 | |
|
186 | 188 | # The pylons app is executed inside of the pyramid 404 exception handler. |
|
187 | 189 | # Exceptions which are raised inside of it are not handled by pyramid |
|
188 | 190 | # again. Therefore we add a middleware that invokes the error handler in |
|
189 | 191 | # case of an exception or error response. This way we return proper error |
|
190 | 192 | # HTML pages in case of an error. |
|
191 | 193 | reraise = (settings.get('debugtoolbar.enabled', False) or |
|
192 | 194 | rhodecode.disable_error_handler) |
|
193 | 195 | pylons_app = PylonsErrorHandlingMiddleware( |
|
194 | 196 | pylons_app, error_handler, reraise) |
|
195 | 197 | |
|
196 | 198 | # The VCSMiddleware shall operate like a fallback if pyramid doesn't find a |
|
197 | 199 | # view to handle the request. Therefore it is wrapped around the pylons |
|
198 | 200 | # app. It has to be outside of the error handling otherwise error responses |
|
199 | 201 | # from the vcsserver are converted to HTML error pages. This confuses the |
|
200 | 202 | # command line tools and the user won't get a meaningful error message. |
|
201 | 203 | if vcs_server_enabled: |
|
202 | 204 | pylons_app = VCSMiddleware( |
|
203 | 205 | pylons_app, settings, appenlight_client, registry=config.registry) |
|
204 | 206 | |
|
205 | 207 | # Convert WSGI app to pyramid view and return it. |
|
206 | 208 | return wsgiapp(pylons_app) |
|
207 | 209 | |
|
208 | 210 | |
|
209 | 211 | def add_pylons_compat_data(registry, global_config, settings): |
|
210 | 212 | """ |
|
211 | 213 | Attach data to the registry to support the Pylons integration. |
|
212 | 214 | """ |
|
213 | 215 | registry._pylons_compat_global_config = global_config |
|
214 | 216 | registry._pylons_compat_settings = settings |
|
215 | 217 | |
|
216 | 218 | |
|
217 | 219 | def error_handler(exception, request): |
|
218 | 220 | import rhodecode |
|
219 | 221 | from rhodecode.lib import helpers |
|
220 | 222 | |
|
221 | 223 | rhodecode_title = rhodecode.CONFIG.get('rhodecode_title') or 'RhodeCode' |
|
222 | 224 | |
|
223 | 225 | base_response = HTTPInternalServerError() |
|
224 | 226 | # prefer original exception for the response since it may have headers set |
|
225 | 227 | if isinstance(exception, HTTPException): |
|
226 | 228 | base_response = exception |
|
227 | 229 | elif isinstance(exception, VCSCommunicationError): |
|
228 | 230 | base_response = VCSServerUnavailable() |
|
229 | 231 | |
|
230 | 232 | def is_http_error(response): |
|
231 | 233 | # error which should have traceback |
|
232 | 234 | return response.status_code > 499 |
|
233 | 235 | |
|
234 | 236 | if is_http_error(base_response): |
|
235 | 237 | log.exception( |
|
236 | 238 | 'error occurred handling this request for path: %s', request.path) |
|
237 | 239 | |
|
238 | 240 | c = AttributeDict() |
|
239 | 241 | c.error_message = base_response.status |
|
240 | 242 | c.error_explanation = base_response.explanation or str(base_response) |
|
241 | 243 | c.visual = AttributeDict() |
|
242 | 244 | |
|
243 | 245 | c.visual.rhodecode_support_url = ( |
|
244 | 246 | request.registry.settings.get('rhodecode_support_url') or |
|
245 | 247 | request.route_url('rhodecode_support') |
|
246 | 248 | ) |
|
247 | 249 | c.redirect_time = 0 |
|
248 | 250 | c.rhodecode_name = rhodecode_title |
|
249 | 251 | if not c.rhodecode_name: |
|
250 | 252 | c.rhodecode_name = 'Rhodecode' |
|
251 | 253 | |
|
252 | 254 | c.causes = [] |
|
253 | 255 | if hasattr(base_response, 'causes'): |
|
254 | 256 | c.causes = base_response.causes |
|
255 | 257 | c.messages = helpers.flash.pop_messages(request=request) |
|
256 | 258 | c.traceback = traceback.format_exc() |
|
257 | 259 | response = render_to_response( |
|
258 | 260 | '/errors/error_document.mako', {'c': c, 'h': helpers}, request=request, |
|
259 | 261 | response=base_response) |
|
260 | 262 | |
|
261 | 263 | return response |
|
262 | 264 | |
|
263 | 265 | |
|
264 | 266 | def includeme(config): |
|
265 | 267 | settings = config.registry.settings |
|
266 | 268 | |
|
267 | 269 | # plugin information |
|
268 | 270 | config.registry.rhodecode_plugins = OrderedDict() |
|
269 | 271 | |
|
270 | 272 | config.add_directive( |
|
271 | 273 | 'register_rhodecode_plugin', register_rhodecode_plugin) |
|
272 | 274 | |
|
273 | 275 | if asbool(settings.get('appenlight', 'false')): |
|
274 | 276 | config.include('appenlight_client.ext.pyramid_tween') |
|
275 | 277 | |
|
276 | 278 | if 'mako.default_filters' not in settings: |
|
277 | 279 | # set custom default filters if we don't have it defined |
|
278 | 280 | settings['mako.imports'] = 'from rhodecode.lib.base import h_filter' |
|
279 | 281 | settings['mako.default_filters'] = 'h_filter' |
|
280 | 282 | |
|
281 | 283 | # Includes which are required. The application would fail without them. |
|
282 | 284 | config.include('pyramid_mako') |
|
283 | 285 | config.include('pyramid_beaker') |
|
284 | 286 | |
|
285 | 287 | config.include('rhodecode.authentication') |
|
286 | 288 | config.include('rhodecode.integrations') |
|
287 | 289 | |
|
288 | 290 | # apps |
|
289 | 291 | config.include('rhodecode.apps._base') |
|
290 | 292 | config.include('rhodecode.apps.ops') |
|
291 | 293 | |
|
292 | 294 | config.include('rhodecode.apps.admin') |
|
293 | 295 | config.include('rhodecode.apps.channelstream') |
|
294 | 296 | config.include('rhodecode.apps.login') |
|
295 | 297 | config.include('rhodecode.apps.home') |
|
296 | 298 | config.include('rhodecode.apps.journal') |
|
297 | 299 | config.include('rhodecode.apps.repository') |
|
298 | 300 | config.include('rhodecode.apps.repo_group') |
|
299 | 301 | config.include('rhodecode.apps.user_group') |
|
300 | 302 | config.include('rhodecode.apps.search') |
|
301 | 303 | config.include('rhodecode.apps.user_profile') |
|
302 | 304 | config.include('rhodecode.apps.my_account') |
|
303 | 305 | config.include('rhodecode.apps.svn_support') |
|
304 | 306 | config.include('rhodecode.apps.ssh_support') |
|
305 | 307 | config.include('rhodecode.apps.gist') |
|
306 | 308 | |
|
307 | 309 | config.include('rhodecode.apps.debug_style') |
|
308 | 310 | config.include('rhodecode.tweens') |
|
309 | 311 | config.include('rhodecode.api') |
|
310 | 312 | |
|
311 | 313 | config.add_route( |
|
312 | 314 | 'rhodecode_support', 'https://rhodecode.com/help/', static=True) |
|
313 | 315 | |
|
314 | 316 | config.add_translation_dirs('rhodecode:i18n/') |
|
315 | 317 | settings['default_locale_name'] = settings.get('lang', 'en') |
|
316 | 318 | |
|
317 | 319 | # Add subscribers. |
|
320 | config.add_subscriber(inject_app_settings, ApplicationCreated) | |
|
318 | 321 | config.add_subscriber(scan_repositories_if_enabled, ApplicationCreated) |
|
319 | 322 | config.add_subscriber(write_metadata_if_needed, ApplicationCreated) |
|
320 | 323 | config.add_subscriber(write_js_routes_if_enabled, ApplicationCreated) |
|
321 | 324 | |
|
322 | 325 | config.add_request_method( |
|
323 | 326 | 'rhodecode.lib.partial_renderer.get_partial_renderer', |
|
324 | 327 | 'get_partial_renderer') |
|
325 | 328 | |
|
326 | 329 | # events |
|
327 | 330 | # TODO(marcink): this should be done when pyramid migration is finished |
|
328 | 331 | # config.add_subscriber( |
|
329 | 332 | # 'rhodecode.integrations.integrations_event_handler', |
|
330 | 333 | # 'rhodecode.events.RhodecodeEvent') |
|
331 | 334 | |
|
332 | 335 | # Set the authorization policy. |
|
333 | 336 | authz_policy = ACLAuthorizationPolicy() |
|
334 | 337 | config.set_authorization_policy(authz_policy) |
|
335 | 338 | |
|
336 | 339 | # Set the default renderer for HTML templates to mako. |
|
337 | 340 | config.add_mako_renderer('.html') |
|
338 | 341 | |
|
339 | 342 | config.add_renderer( |
|
340 | 343 | name='json_ext', |
|
341 | 344 | factory='rhodecode.lib.ext_json_renderer.pyramid_ext_json') |
|
342 | 345 | |
|
343 | 346 | # include RhodeCode plugins |
|
344 | 347 | includes = aslist(settings.get('rhodecode.includes', [])) |
|
345 | 348 | for inc in includes: |
|
346 | 349 | config.include(inc) |
|
347 | 350 | |
|
348 | 351 | # This is the glue which allows us to migrate in chunks. By registering the |
|
349 | 352 | # pylons based application as the "Not Found" view in Pyramid, we will |
|
350 | 353 | # fallback to the old application each time the new one does not yet know |
|
351 | 354 | # how to handle a request. |
|
352 | 355 | config.add_notfound_view(make_not_found_view(config)) |
|
353 | 356 | |
|
354 | 357 | if not settings.get('debugtoolbar.enabled', False): |
|
355 | 358 | # disabled debugtoolbar handle all exceptions via the error_handlers |
|
356 | 359 | config.add_view(error_handler, context=Exception) |
|
357 | 360 | |
|
358 | 361 | config.add_view(error_handler, context=HTTPError) |
|
359 | 362 | |
|
360 | 363 | |
|
361 | 364 | def includeme_first(config): |
|
362 | 365 | # redirect automatic browser favicon.ico requests to correct place |
|
363 | 366 | def favicon_redirect(context, request): |
|
364 | 367 | return HTTPFound( |
|
365 | 368 | request.static_path('rhodecode:public/images/favicon.ico')) |
|
366 | 369 | |
|
367 | 370 | config.add_view(favicon_redirect, route_name='favicon') |
|
368 | 371 | config.add_route('favicon', '/favicon.ico') |
|
369 | 372 | |
|
370 | 373 | def robots_redirect(context, request): |
|
371 | 374 | return HTTPFound( |
|
372 | 375 | request.static_path('rhodecode:public/robots.txt')) |
|
373 | 376 | |
|
374 | 377 | config.add_view(robots_redirect, route_name='robots') |
|
375 | 378 | config.add_route('robots', '/robots.txt') |
|
376 | 379 | |
|
377 | 380 | config.add_static_view( |
|
378 | 381 | '_static/deform', 'deform:static') |
|
379 | 382 | config.add_static_view( |
|
380 | 383 | '_static/rhodecode', path='rhodecode:public', cache_max_age=3600 * 24) |
|
381 | 384 | |
|
382 | 385 | |
|
383 | 386 | def wrap_app_in_wsgi_middlewares(pyramid_app, config): |
|
384 | 387 | """ |
|
385 | 388 | Apply outer WSGI middlewares around the application. |
|
386 | 389 | |
|
387 | 390 | Part of this has been moved up from the Pylons layer, so that the |
|
388 | 391 | data is also available if old Pylons code is hit through an already ported |
|
389 | 392 | view. |
|
390 | 393 | """ |
|
391 | 394 | settings = config.registry.settings |
|
392 | 395 | |
|
393 | 396 | # enable https redirects based on HTTP_X_URL_SCHEME set by proxy |
|
394 | 397 | pyramid_app = HttpsFixup(pyramid_app, settings) |
|
395 | 398 | |
|
396 | 399 | # Add RoutesMiddleware to support the pylons compatibility tween during |
|
397 | 400 | # migration to pyramid. |
|
398 | 401 | |
|
399 | 402 | # TODO(marcink): remove after migration to pyramid |
|
400 | 403 | if hasattr(config.registry, '_pylons_compat_config'): |
|
401 | 404 | routes_map = config.registry._pylons_compat_config['routes.map'] |
|
402 | 405 | pyramid_app = SkippableRoutesMiddleware( |
|
403 | 406 | pyramid_app, routes_map, |
|
404 | 407 | skip_prefixes=(STATIC_FILE_PREFIX, '/_debug_toolbar')) |
|
405 | 408 | |
|
406 | 409 | pyramid_app, _ = wrap_in_appenlight_if_enabled(pyramid_app, settings) |
|
407 | 410 | |
|
408 | 411 | if settings['gzip_responses']: |
|
409 | 412 | pyramid_app = make_gzip_middleware( |
|
410 | 413 | pyramid_app, settings, compress_level=1) |
|
411 | 414 | |
|
412 | 415 | # this should be the outer most middleware in the wsgi stack since |
|
413 | 416 | # middleware like Routes make database calls |
|
414 | 417 | def pyramid_app_with_cleanup(environ, start_response): |
|
415 | 418 | try: |
|
416 | 419 | return pyramid_app(environ, start_response) |
|
417 | 420 | finally: |
|
418 | 421 | # Dispose current database session and rollback uncommitted |
|
419 | 422 | # transactions. |
|
420 | 423 | meta.Session.remove() |
|
421 | 424 | |
|
422 | 425 | # In a single threaded mode server, on non sqlite db we should have |
|
423 | 426 | # '0 Current Checked out connections' at the end of a request, |
|
424 | 427 | # if not, then something, somewhere is leaving a connection open |
|
425 | 428 | pool = meta.Base.metadata.bind.engine.pool |
|
426 | 429 | log.debug('sa pool status: %s', pool.status()) |
|
427 | 430 | |
|
428 | 431 | return pyramid_app_with_cleanup |
|
429 | 432 | |
|
430 | 433 | |
|
431 | 434 | def sanitize_settings_and_apply_defaults(settings): |
|
432 | 435 | """ |
|
433 | 436 | Applies settings defaults and does all type conversion. |
|
434 | 437 | |
|
435 | 438 | We would move all settings parsing and preparation into this place, so that |
|
436 | 439 | we have only one place left which deals with this part. The remaining parts |
|
437 | 440 | of the application would start to rely fully on well prepared settings. |
|
438 | 441 | |
|
439 | 442 | This piece would later be split up per topic to avoid a big fat monster |
|
440 | 443 | function. |
|
441 | 444 | """ |
|
442 | 445 | |
|
443 | 446 | # Pyramid's mako renderer has to search in the templates folder so that the |
|
444 | 447 | # old templates still work. Ported and new templates are expected to use |
|
445 | 448 | # real asset specifications for the includes. |
|
446 | 449 | mako_directories = settings.setdefault('mako.directories', [ |
|
447 | 450 | # Base templates of the original Pylons application |
|
448 | 451 | 'rhodecode:templates', |
|
449 | 452 | ]) |
|
450 | 453 | log.debug( |
|
451 | 454 | "Using the following Mako template directories: %s", |
|
452 | 455 | mako_directories) |
|
453 | 456 | |
|
454 | 457 | # Default includes, possible to change as a user |
|
455 | 458 | pyramid_includes = settings.setdefault('pyramid.includes', [ |
|
456 | 459 | 'rhodecode.lib.middleware.request_wrapper', |
|
457 | 460 | ]) |
|
458 | 461 | log.debug( |
|
459 | 462 | "Using the following pyramid.includes: %s", |
|
460 | 463 | pyramid_includes) |
|
461 | 464 | |
|
462 | 465 | # TODO: johbo: Re-think this, usually the call to config.include |
|
463 | 466 | # should allow to pass in a prefix. |
|
464 | 467 | settings.setdefault('rhodecode.api.url', '/_admin/api') |
|
465 | 468 | |
|
466 | 469 | # Sanitize generic settings. |
|
467 | 470 | _list_setting(settings, 'default_encoding', 'UTF-8') |
|
468 | 471 | _bool_setting(settings, 'is_test', 'false') |
|
469 | 472 | _bool_setting(settings, 'gzip_responses', 'false') |
|
470 | 473 | |
|
471 | 474 | # Call split out functions that sanitize settings for each topic. |
|
472 | 475 | _sanitize_appenlight_settings(settings) |
|
473 | 476 | _sanitize_vcs_settings(settings) |
|
474 | 477 | |
|
478 | # configure instance id | |
|
479 | config_utils.set_instance_id(settings) | |
|
480 | ||
|
475 | 481 | return settings |
|
476 | 482 | |
|
477 | 483 | |
|
478 | 484 | def _sanitize_appenlight_settings(settings): |
|
479 | 485 | _bool_setting(settings, 'appenlight', 'false') |
|
480 | 486 | |
|
481 | 487 | |
|
482 | 488 | def _sanitize_vcs_settings(settings): |
|
483 | 489 | """ |
|
484 | 490 | Applies settings defaults and does type conversion for all VCS related |
|
485 | 491 | settings. |
|
486 | 492 | """ |
|
487 | 493 | _string_setting(settings, 'vcs.svn.compatible_version', '') |
|
488 | 494 | _string_setting(settings, 'git_rev_filter', '--all') |
|
489 | 495 | _string_setting(settings, 'vcs.hooks.protocol', 'http') |
|
490 | 496 | _string_setting(settings, 'vcs.scm_app_implementation', 'http') |
|
491 | 497 | _string_setting(settings, 'vcs.server', '') |
|
492 | 498 | _string_setting(settings, 'vcs.server.log_level', 'debug') |
|
493 | 499 | _string_setting(settings, 'vcs.server.protocol', 'http') |
|
494 | 500 | _bool_setting(settings, 'startup.import_repos', 'false') |
|
495 | 501 | _bool_setting(settings, 'vcs.hooks.direct_calls', 'false') |
|
496 | 502 | _bool_setting(settings, 'vcs.server.enable', 'true') |
|
497 | 503 | _bool_setting(settings, 'vcs.start_server', 'false') |
|
498 | 504 | _list_setting(settings, 'vcs.backends', 'hg, git, svn') |
|
499 | 505 | _int_setting(settings, 'vcs.connection_timeout', 3600) |
|
500 | 506 | |
|
501 | 507 | # Support legacy values of vcs.scm_app_implementation. Legacy |
|
502 | 508 | # configurations may use 'rhodecode.lib.middleware.utils.scm_app_http' |
|
503 | 509 | # which is now mapped to 'http'. |
|
504 | 510 | scm_app_impl = settings['vcs.scm_app_implementation'] |
|
505 | 511 | if scm_app_impl == 'rhodecode.lib.middleware.utils.scm_app_http': |
|
506 | 512 | settings['vcs.scm_app_implementation'] = 'http' |
|
507 | 513 | |
|
508 | 514 | |
|
509 | 515 | def _int_setting(settings, name, default): |
|
510 | 516 | settings[name] = int(settings.get(name, default)) |
|
511 | 517 | |
|
512 | 518 | |
|
513 | 519 | def _bool_setting(settings, name, default): |
|
514 | 520 | input = settings.get(name, default) |
|
515 | 521 | if isinstance(input, unicode): |
|
516 | 522 | input = input.encode('utf8') |
|
517 | 523 | settings[name] = asbool(input) |
|
518 | 524 | |
|
519 | 525 | |
|
520 | 526 | def _list_setting(settings, name, default): |
|
521 | 527 | raw_value = settings.get(name, default) |
|
522 | 528 | |
|
523 | 529 | old_separator = ',' |
|
524 | 530 | if old_separator in raw_value: |
|
525 | 531 | # If we get a comma separated list, pass it to our own function. |
|
526 | 532 | settings[name] = rhodecode_aslist(raw_value, sep=old_separator) |
|
527 | 533 | else: |
|
528 | 534 | # Otherwise we assume it uses pyramids space/newline separation. |
|
529 | 535 | settings[name] = aslist(raw_value) |
|
530 | 536 | |
|
531 | 537 | |
|
532 | 538 | def _string_setting(settings, name, default, lower=True): |
|
533 | 539 | value = settings.get(name, default) |
|
534 | 540 | if lower: |
|
535 | 541 | value = value.lower() |
|
536 | 542 | settings[name] = value |
@@ -1,343 +1,311 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | |
|
3 | 3 | # Copyright (C) 2010-2017 RhodeCode GmbH |
|
4 | 4 | # |
|
5 | 5 | # This program is free software: you can redistribute it and/or modify |
|
6 | 6 | # it under the terms of the GNU Affero General Public License, version 3 |
|
7 | 7 | # (only), as published by the Free Software Foundation. |
|
8 | 8 | # |
|
9 | 9 | # This program is distributed in the hope that it will be useful, |
|
10 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of |
|
11 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|
12 | 12 | # GNU General Public License for more details. |
|
13 | 13 | # |
|
14 | 14 | # You should have received a copy of the GNU Affero General Public License |
|
15 | 15 | # along with this program. If not, see <http://www.gnu.org/licenses/>. |
|
16 | 16 | # |
|
17 | 17 | # This program is dual-licensed. If you wish to learn more about the |
|
18 | 18 | # RhodeCode Enterprise Edition, including its added features, Support services, |
|
19 | 19 | # and proprietary license terms, please see https://rhodecode.com/licenses/ |
|
20 | 20 | |
|
21 | 21 | """ |
|
22 | 22 | Routes configuration |
|
23 | 23 | |
|
24 | 24 | The more specific and detailed routes should be defined first so they |
|
25 | 25 | may take precedent over the more generic routes. For more information |
|
26 | 26 | refer to the routes manual at http://routes.groovie.org/docs/ |
|
27 | 27 | |
|
28 | 28 | IMPORTANT: if you change any routing here, make sure to take a look at lib/base.py |
|
29 | 29 | and _route_name variable which uses some of stored naming here to do redirects. |
|
30 | 30 | """ |
|
31 | 31 | import os |
|
32 | 32 | import re |
|
33 | 33 | from routes import Mapper |
|
34 | 34 | |
|
35 | 35 | # prefix for non repository related links needs to be prefixed with `/` |
|
36 | 36 | ADMIN_PREFIX = '/_admin' |
|
37 | 37 | STATIC_FILE_PREFIX = '/_static' |
|
38 | 38 | |
|
39 | 39 | # Default requirements for URL parts |
|
40 | 40 | URL_NAME_REQUIREMENTS = { |
|
41 | 41 | # group name can have a slash in them, but they must not end with a slash |
|
42 | 42 | 'group_name': r'.*?[^/]', |
|
43 | 43 | 'repo_group_name': r'.*?[^/]', |
|
44 | 44 | # repo names can have a slash in them, but they must not end with a slash |
|
45 | 45 | 'repo_name': r'.*?[^/]', |
|
46 | 46 | # file path eats up everything at the end |
|
47 | 47 | 'f_path': r'.*', |
|
48 | 48 | # reference types |
|
49 | 49 | 'source_ref_type': '(branch|book|tag|rev|\%\(source_ref_type\)s)', |
|
50 | 50 | 'target_ref_type': '(branch|book|tag|rev|\%\(target_ref_type\)s)', |
|
51 | 51 | } |
|
52 | 52 | |
|
53 | 53 | |
|
54 | 54 | class JSRoutesMapper(Mapper): |
|
55 | 55 | """ |
|
56 | 56 | Wrapper for routes.Mapper to make pyroutes compatible url definitions |
|
57 | 57 | """ |
|
58 | 58 | _named_route_regex = re.compile(r'^[a-z-_0-9A-Z]+$') |
|
59 | 59 | _argument_prog = re.compile('\{(.*?)\}|:\((.*)\)') |
|
60 | 60 | def __init__(self, *args, **kw): |
|
61 | 61 | super(JSRoutesMapper, self).__init__(*args, **kw) |
|
62 | 62 | self._jsroutes = [] |
|
63 | 63 | |
|
64 | 64 | def connect(self, *args, **kw): |
|
65 | 65 | """ |
|
66 | 66 | Wrapper for connect to take an extra argument jsroute=True |
|
67 | 67 | |
|
68 | 68 | :param jsroute: boolean, if True will add the route to the pyroutes list |
|
69 | 69 | """ |
|
70 | 70 | if kw.pop('jsroute', False): |
|
71 | 71 | if not self._named_route_regex.match(args[0]): |
|
72 | 72 | raise Exception('only named routes can be added to pyroutes') |
|
73 | 73 | self._jsroutes.append(args[0]) |
|
74 | 74 | |
|
75 | 75 | super(JSRoutesMapper, self).connect(*args, **kw) |
|
76 | 76 | |
|
77 | 77 | def _extract_route_information(self, route): |
|
78 | 78 | """ |
|
79 | 79 | Convert a route into tuple(name, path, args), eg: |
|
80 | 80 | ('show_user', '/profile/%(username)s', ['username']) |
|
81 | 81 | """ |
|
82 | 82 | routepath = route.routepath |
|
83 | 83 | def replace(matchobj): |
|
84 | 84 | if matchobj.group(1): |
|
85 | 85 | return "%%(%s)s" % matchobj.group(1).split(':')[0] |
|
86 | 86 | else: |
|
87 | 87 | return "%%(%s)s" % matchobj.group(2) |
|
88 | 88 | |
|
89 | 89 | routepath = self._argument_prog.sub(replace, routepath) |
|
90 | 90 | return ( |
|
91 | 91 | route.name, |
|
92 | 92 | routepath, |
|
93 | 93 | [(arg[0].split(':')[0] if arg[0] != '' else arg[1]) |
|
94 | 94 | for arg in self._argument_prog.findall(route.routepath)] |
|
95 | 95 | ) |
|
96 | 96 | |
|
97 | 97 | def jsroutes(self): |
|
98 | 98 | """ |
|
99 | 99 | Return a list of pyroutes.js compatible routes |
|
100 | 100 | """ |
|
101 | 101 | for route_name in self._jsroutes: |
|
102 | 102 | yield self._extract_route_information(self._routenames[route_name]) |
|
103 | 103 | |
|
104 | 104 | |
|
105 | 105 | def make_map(config): |
|
106 | 106 | """Create, configure and return the routes Mapper""" |
|
107 | 107 | rmap = JSRoutesMapper( |
|
108 | 108 | directory=config['pylons.paths']['controllers'], |
|
109 | 109 | always_scan=config['debug']) |
|
110 | 110 | rmap.minimization = False |
|
111 | 111 | rmap.explicit = False |
|
112 | 112 | |
|
113 | 113 | from rhodecode.lib.utils2 import str2bool |
|
114 | 114 | from rhodecode.model import repo, repo_group |
|
115 | 115 | |
|
116 | 116 | def check_repo(environ, match_dict): |
|
117 | 117 | """ |
|
118 | 118 | check for valid repository for proper 404 handling |
|
119 | 119 | |
|
120 | 120 | :param environ: |
|
121 | 121 | :param match_dict: |
|
122 | 122 | """ |
|
123 | 123 | repo_name = match_dict.get('repo_name') |
|
124 | 124 | |
|
125 | 125 | if match_dict.get('f_path'): |
|
126 | 126 | # fix for multiple initial slashes that causes errors |
|
127 | 127 | match_dict['f_path'] = match_dict['f_path'].lstrip('/') |
|
128 | 128 | repo_model = repo.RepoModel() |
|
129 | 129 | by_name_match = repo_model.get_by_repo_name(repo_name) |
|
130 | 130 | # if we match quickly from database, short circuit the operation, |
|
131 | 131 | # and validate repo based on the type. |
|
132 | 132 | if by_name_match: |
|
133 | 133 | return True |
|
134 | 134 | |
|
135 | 135 | by_id_match = repo_model.get_repo_by_id(repo_name) |
|
136 | 136 | if by_id_match: |
|
137 | 137 | repo_name = by_id_match.repo_name |
|
138 | 138 | match_dict['repo_name'] = repo_name |
|
139 | 139 | return True |
|
140 | 140 | |
|
141 | 141 | return False |
|
142 | 142 | |
|
143 | 143 | def check_group(environ, match_dict): |
|
144 | 144 | """ |
|
145 | 145 | check for valid repository group path for proper 404 handling |
|
146 | 146 | |
|
147 | 147 | :param environ: |
|
148 | 148 | :param match_dict: |
|
149 | 149 | """ |
|
150 | 150 | repo_group_name = match_dict.get('group_name') |
|
151 | 151 | repo_group_model = repo_group.RepoGroupModel() |
|
152 | 152 | by_name_match = repo_group_model.get_by_group_name(repo_group_name) |
|
153 | 153 | if by_name_match: |
|
154 | 154 | return True |
|
155 | 155 | |
|
156 | 156 | return False |
|
157 | 157 | |
|
158 | 158 | def check_user_group(environ, match_dict): |
|
159 | 159 | """ |
|
160 | 160 | check for valid user group for proper 404 handling |
|
161 | 161 | |
|
162 | 162 | :param environ: |
|
163 | 163 | :param match_dict: |
|
164 | 164 | """ |
|
165 | 165 | return True |
|
166 | 166 | |
|
167 | 167 | def check_int(environ, match_dict): |
|
168 | 168 | return match_dict.get('id').isdigit() |
|
169 | 169 | |
|
170 | 170 | |
|
171 | 171 | #========================================================================== |
|
172 | 172 | # CUSTOM ROUTES HERE |
|
173 | 173 | #========================================================================== |
|
174 | 174 | |
|
175 | 175 | # ADMIN REPOSITORY GROUPS ROUTES |
|
176 | 176 | with rmap.submapper(path_prefix=ADMIN_PREFIX, |
|
177 | 177 | controller='admin/repo_groups') as m: |
|
178 | 178 | m.connect('repo_groups', '/repo_groups', |
|
179 | 179 | action='create', conditions={'method': ['POST']}) |
|
180 | 180 | m.connect('repo_groups', '/repo_groups', |
|
181 | 181 | action='index', conditions={'method': ['GET']}) |
|
182 | 182 | m.connect('new_repo_group', '/repo_groups/new', |
|
183 | 183 | action='new', conditions={'method': ['GET']}) |
|
184 | 184 | m.connect('update_repo_group', '/repo_groups/{group_name}', |
|
185 | 185 | action='update', conditions={'method': ['PUT'], |
|
186 | 186 | 'function': check_group}, |
|
187 | 187 | requirements=URL_NAME_REQUIREMENTS) |
|
188 | 188 | |
|
189 | 189 | # EXTRAS REPO GROUP ROUTES |
|
190 | 190 | m.connect('edit_repo_group', '/repo_groups/{group_name}/edit', |
|
191 | 191 | action='edit', |
|
192 | 192 | conditions={'method': ['GET'], 'function': check_group}, |
|
193 | 193 | requirements=URL_NAME_REQUIREMENTS) |
|
194 | 194 | m.connect('edit_repo_group', '/repo_groups/{group_name}/edit', |
|
195 | 195 | action='edit', |
|
196 | 196 | conditions={'method': ['PUT'], 'function': check_group}, |
|
197 | 197 | requirements=URL_NAME_REQUIREMENTS) |
|
198 | 198 | |
|
199 | 199 | m.connect('edit_repo_group_advanced', '/repo_groups/{group_name}/edit/advanced', |
|
200 | 200 | action='edit_repo_group_advanced', |
|
201 | 201 | conditions={'method': ['GET'], 'function': check_group}, |
|
202 | 202 | requirements=URL_NAME_REQUIREMENTS) |
|
203 | 203 | m.connect('edit_repo_group_advanced', '/repo_groups/{group_name}/edit/advanced', |
|
204 | 204 | action='edit_repo_group_advanced', |
|
205 | 205 | conditions={'method': ['PUT'], 'function': check_group}, |
|
206 | 206 | requirements=URL_NAME_REQUIREMENTS) |
|
207 | 207 | |
|
208 | 208 | m.connect('edit_repo_group_perms', '/repo_groups/{group_name}/edit/permissions', |
|
209 | 209 | action='edit_repo_group_perms', |
|
210 | 210 | conditions={'method': ['GET'], 'function': check_group}, |
|
211 | 211 | requirements=URL_NAME_REQUIREMENTS) |
|
212 | 212 | m.connect('edit_repo_group_perms', '/repo_groups/{group_name}/edit/permissions', |
|
213 | 213 | action='update_perms', |
|
214 | 214 | conditions={'method': ['PUT'], 'function': check_group}, |
|
215 | 215 | requirements=URL_NAME_REQUIREMENTS) |
|
216 | 216 | |
|
217 | 217 | m.connect('delete_repo_group', '/repo_groups/{group_name}', |
|
218 | 218 | action='delete', conditions={'method': ['DELETE'], |
|
219 | 219 | 'function': check_group}, |
|
220 | 220 | requirements=URL_NAME_REQUIREMENTS) |
|
221 | 221 | |
|
222 | # ADMIN USER ROUTES | |
|
223 | with rmap.submapper(path_prefix=ADMIN_PREFIX, | |
|
224 | controller='admin/users') as m: | |
|
225 | m.connect('users', '/users', | |
|
226 | action='create', conditions={'method': ['POST']}) | |
|
227 | m.connect('new_user', '/users/new', | |
|
228 | action='new', conditions={'method': ['GET']}) | |
|
229 | m.connect('update_user', '/users/{user_id}', | |
|
230 | action='update', conditions={'method': ['PUT']}) | |
|
231 | m.connect('delete_user', '/users/{user_id}', | |
|
232 | action='delete', conditions={'method': ['DELETE']}) | |
|
233 | m.connect('edit_user', '/users/{user_id}/edit', | |
|
234 | action='edit', conditions={'method': ['GET']}, jsroute=True) | |
|
235 | m.connect('user', '/users/{user_id}', | |
|
236 | action='show', conditions={'method': ['GET']}) | |
|
237 | m.connect('force_password_reset_user', '/users/{user_id}/password_reset', | |
|
238 | action='reset_password', conditions={'method': ['POST']}) | |
|
239 | m.connect('create_personal_repo_group', '/users/{user_id}/create_repo_group', | |
|
240 | action='create_personal_repo_group', conditions={'method': ['POST']}) | |
|
241 | ||
|
242 | # EXTRAS USER ROUTES | |
|
243 | m.connect('edit_user_advanced', '/users/{user_id}/edit/advanced', | |
|
244 | action='edit_advanced', conditions={'method': ['GET']}) | |
|
245 | m.connect('edit_user_advanced', '/users/{user_id}/edit/advanced', | |
|
246 | action='update_advanced', conditions={'method': ['PUT']}) | |
|
247 | ||
|
248 | m.connect('edit_user_global_perms', '/users/{user_id}/edit/global_permissions', | |
|
249 | action='edit_global_perms', conditions={'method': ['GET']}) | |
|
250 | m.connect('edit_user_global_perms', '/users/{user_id}/edit/global_permissions', | |
|
251 | action='update_global_perms', conditions={'method': ['PUT']}) | |
|
252 | ||
|
253 | 222 | # ADMIN SETTINGS ROUTES |
|
254 | 223 | with rmap.submapper(path_prefix=ADMIN_PREFIX, |
|
255 | 224 | controller='admin/settings') as m: |
|
256 | 225 | |
|
257 | 226 | # default |
|
258 | 227 | m.connect('admin_settings', '/settings', |
|
259 | 228 | action='settings_global_update', |
|
260 | 229 | conditions={'method': ['POST']}) |
|
261 | 230 | m.connect('admin_settings', '/settings', |
|
262 | 231 | action='settings_global', conditions={'method': ['GET']}) |
|
263 | 232 | |
|
264 | 233 | m.connect('admin_settings_vcs', '/settings/vcs', |
|
265 | 234 | action='settings_vcs_update', |
|
266 | 235 | conditions={'method': ['POST']}) |
|
267 | 236 | m.connect('admin_settings_vcs', '/settings/vcs', |
|
268 | 237 | action='settings_vcs', |
|
269 | 238 | conditions={'method': ['GET']}) |
|
270 | 239 | m.connect('admin_settings_vcs', '/settings/vcs', |
|
271 | 240 | action='delete_svn_pattern', |
|
272 | 241 | conditions={'method': ['DELETE']}) |
|
273 | 242 | |
|
274 | 243 | m.connect('admin_settings_mapping', '/settings/mapping', |
|
275 | 244 | action='settings_mapping_update', |
|
276 | 245 | conditions={'method': ['POST']}) |
|
277 | 246 | m.connect('admin_settings_mapping', '/settings/mapping', |
|
278 | 247 | action='settings_mapping', conditions={'method': ['GET']}) |
|
279 | 248 | |
|
280 | 249 | m.connect('admin_settings_global', '/settings/global', |
|
281 | 250 | action='settings_global_update', |
|
282 | 251 | conditions={'method': ['POST']}) |
|
283 | 252 | m.connect('admin_settings_global', '/settings/global', |
|
284 | 253 | action='settings_global', conditions={'method': ['GET']}) |
|
285 | 254 | |
|
286 | 255 | m.connect('admin_settings_visual', '/settings/visual', |
|
287 | 256 | action='settings_visual_update', |
|
288 | 257 | conditions={'method': ['POST']}) |
|
289 | 258 | m.connect('admin_settings_visual', '/settings/visual', |
|
290 | 259 | action='settings_visual', conditions={'method': ['GET']}) |
|
291 | 260 | |
|
292 | 261 | m.connect('admin_settings_issuetracker', |
|
293 | 262 | '/settings/issue-tracker', action='settings_issuetracker', |
|
294 | 263 | conditions={'method': ['GET']}) |
|
295 | 264 | m.connect('admin_settings_issuetracker_save', |
|
296 | 265 | '/settings/issue-tracker/save', |
|
297 | 266 | action='settings_issuetracker_save', |
|
298 | 267 | conditions={'method': ['POST']}) |
|
299 | 268 | m.connect('admin_issuetracker_test', '/settings/issue-tracker/test', |
|
300 | 269 | action='settings_issuetracker_test', |
|
301 | 270 | conditions={'method': ['POST']}) |
|
302 | 271 | m.connect('admin_issuetracker_delete', |
|
303 | 272 | '/settings/issue-tracker/delete', |
|
304 | 273 | action='settings_issuetracker_delete', |
|
305 | 274 | conditions={'method': ['DELETE']}) |
|
306 | 275 | |
|
307 | 276 | m.connect('admin_settings_email', '/settings/email', |
|
308 | 277 | action='settings_email_update', |
|
309 | 278 | conditions={'method': ['POST']}) |
|
310 | 279 | m.connect('admin_settings_email', '/settings/email', |
|
311 | 280 | action='settings_email', conditions={'method': ['GET']}) |
|
312 | 281 | |
|
313 | 282 | m.connect('admin_settings_hooks', '/settings/hooks', |
|
314 | 283 | action='settings_hooks_update', |
|
315 | 284 | conditions={'method': ['POST', 'DELETE']}) |
|
316 | 285 | m.connect('admin_settings_hooks', '/settings/hooks', |
|
317 | 286 | action='settings_hooks', conditions={'method': ['GET']}) |
|
318 | 287 | |
|
319 | 288 | m.connect('admin_settings_search', '/settings/search', |
|
320 | 289 | action='settings_search', conditions={'method': ['GET']}) |
|
321 | 290 | |
|
322 | 291 | m.connect('admin_settings_supervisor', '/settings/supervisor', |
|
323 | 292 | action='settings_supervisor', conditions={'method': ['GET']}) |
|
324 | 293 | m.connect('admin_settings_supervisor_log', '/settings/supervisor/{procid}/log', |
|
325 | 294 | action='settings_supervisor_log', conditions={'method': ['GET']}) |
|
326 | 295 | |
|
327 | 296 | m.connect('admin_settings_labs', '/settings/labs', |
|
328 | 297 | action='settings_labs_update', |
|
329 | 298 | conditions={'method': ['POST']}) |
|
330 | 299 | m.connect('admin_settings_labs', '/settings/labs', |
|
331 | 300 | action='settings_labs', conditions={'method': ['GET']}) |
|
332 | 301 | |
|
333 | 302 | # ADMIN MY ACCOUNT |
|
334 | 303 | with rmap.submapper(path_prefix=ADMIN_PREFIX, |
|
335 | 304 | controller='admin/my_account') as m: |
|
336 | 305 | |
|
337 | 306 | # NOTE(marcink): this needs to be kept for password force flag to be |
|
338 | 307 | # handled in pylons controllers, remove after full migration to pyramid |
|
339 | 308 | m.connect('my_account_password', '/my_account/password', |
|
340 | 309 | action='my_account_password', conditions={'method': ['GET']}) |
|
341 | 310 | |
|
342 | ||
|
343 | 311 | return rmap |
@@ -1,2170 +1,2174 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | |
|
3 | 3 | # Copyright (C) 2010-2017 RhodeCode GmbH |
|
4 | 4 | # |
|
5 | 5 | # This program is free software: you can redistribute it and/or modify |
|
6 | 6 | # it under the terms of the GNU Affero General Public License, version 3 |
|
7 | 7 | # (only), as published by the Free Software Foundation. |
|
8 | 8 | # |
|
9 | 9 | # This program is distributed in the hope that it will be useful, |
|
10 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of |
|
11 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|
12 | 12 | # GNU General Public License for more details. |
|
13 | 13 | # |
|
14 | 14 | # You should have received a copy of the GNU Affero General Public License |
|
15 | 15 | # along with this program. If not, see <http://www.gnu.org/licenses/>. |
|
16 | 16 | # |
|
17 | 17 | # This program is dual-licensed. If you wish to learn more about the |
|
18 | 18 | # RhodeCode Enterprise Edition, including its added features, Support services, |
|
19 | 19 | # and proprietary license terms, please see https://rhodecode.com/licenses/ |
|
20 | 20 | |
|
21 | 21 | """ |
|
22 | 22 | authentication and permission libraries |
|
23 | 23 | """ |
|
24 | 24 | |
|
25 | 25 | import os |
|
26 | 26 | import inspect |
|
27 | 27 | import collections |
|
28 | 28 | import fnmatch |
|
29 | 29 | import hashlib |
|
30 | 30 | import itertools |
|
31 | 31 | import logging |
|
32 | 32 | import random |
|
33 | 33 | import traceback |
|
34 | 34 | from functools import wraps |
|
35 | 35 | |
|
36 | 36 | import ipaddress |
|
37 | 37 | from beaker.cache import cache_region |
|
38 | 38 | from pyramid.httpexceptions import HTTPForbidden, HTTPFound, HTTPNotFound |
|
39 | 39 | from pylons.i18n.translation import _ |
|
40 | 40 | # NOTE(marcink): this has to be removed only after pyramid migration, |
|
41 | 41 | # replace with _ = request.translate |
|
42 | 42 | from sqlalchemy.orm.exc import ObjectDeletedError |
|
43 | 43 | from sqlalchemy.orm import joinedload |
|
44 | 44 | from zope.cachedescriptors.property import Lazy as LazyProperty |
|
45 | 45 | |
|
46 | 46 | import rhodecode |
|
47 | 47 | from rhodecode.model import meta |
|
48 | 48 | from rhodecode.model.meta import Session |
|
49 | 49 | from rhodecode.model.user import UserModel |
|
50 | 50 | from rhodecode.model.db import ( |
|
51 | 51 | User, Repository, Permission, UserToPerm, UserGroupToPerm, UserGroupMember, |
|
52 | 52 | UserIpMap, UserApiKeys, RepoGroup, UserGroup) |
|
53 | 53 | from rhodecode.lib import caches |
|
54 | 54 | from rhodecode.lib.utils2 import safe_unicode, aslist, safe_str, md5 |
|
55 | 55 | from rhodecode.lib.utils import ( |
|
56 | 56 | get_repo_slug, get_repo_group_slug, get_user_group_slug) |
|
57 | 57 | from rhodecode.lib.caching_query import FromCache |
|
58 | 58 | |
|
59 | 59 | |
|
60 | 60 | if rhodecode.is_unix: |
|
61 | 61 | import bcrypt |
|
62 | 62 | |
|
63 | 63 | log = logging.getLogger(__name__) |
|
64 | 64 | |
|
65 | 65 | csrf_token_key = "csrf_token" |
|
66 | 66 | |
|
67 | 67 | |
|
68 | 68 | class PasswordGenerator(object): |
|
69 | 69 | """ |
|
70 | 70 | This is a simple class for generating password from different sets of |
|
71 | 71 | characters |
|
72 | 72 | usage:: |
|
73 | 73 | |
|
74 | 74 | passwd_gen = PasswordGenerator() |
|
75 | 75 | #print 8-letter password containing only big and small letters |
|
76 | 76 | of alphabet |
|
77 | 77 | passwd_gen.gen_password(8, passwd_gen.ALPHABETS_BIG_SMALL) |
|
78 | 78 | """ |
|
79 | 79 | ALPHABETS_NUM = r'''1234567890''' |
|
80 | 80 | ALPHABETS_SMALL = r'''qwertyuiopasdfghjklzxcvbnm''' |
|
81 | 81 | ALPHABETS_BIG = r'''QWERTYUIOPASDFGHJKLZXCVBNM''' |
|
82 | 82 | ALPHABETS_SPECIAL = r'''`-=[]\;',./~!@#$%^&*()_+{}|:"<>?''' |
|
83 | 83 | ALPHABETS_FULL = ALPHABETS_BIG + ALPHABETS_SMALL \ |
|
84 | 84 | + ALPHABETS_NUM + ALPHABETS_SPECIAL |
|
85 | 85 | ALPHABETS_ALPHANUM = ALPHABETS_BIG + ALPHABETS_SMALL + ALPHABETS_NUM |
|
86 | 86 | ALPHABETS_BIG_SMALL = ALPHABETS_BIG + ALPHABETS_SMALL |
|
87 | 87 | ALPHABETS_ALPHANUM_BIG = ALPHABETS_BIG + ALPHABETS_NUM |
|
88 | 88 | ALPHABETS_ALPHANUM_SMALL = ALPHABETS_SMALL + ALPHABETS_NUM |
|
89 | 89 | |
|
90 | 90 | def __init__(self, passwd=''): |
|
91 | 91 | self.passwd = passwd |
|
92 | 92 | |
|
93 | 93 | def gen_password(self, length, type_=None): |
|
94 | 94 | if type_ is None: |
|
95 | 95 | type_ = self.ALPHABETS_FULL |
|
96 | 96 | self.passwd = ''.join([random.choice(type_) for _ in xrange(length)]) |
|
97 | 97 | return self.passwd |
|
98 | 98 | |
|
99 | 99 | |
|
100 | 100 | class _RhodeCodeCryptoBase(object): |
|
101 | 101 | ENC_PREF = None |
|
102 | 102 | |
|
103 | 103 | def hash_create(self, str_): |
|
104 | 104 | """ |
|
105 | 105 | hash the string using |
|
106 | 106 | |
|
107 | 107 | :param str_: password to hash |
|
108 | 108 | """ |
|
109 | 109 | raise NotImplementedError |
|
110 | 110 | |
|
111 | 111 | def hash_check_with_upgrade(self, password, hashed): |
|
112 | 112 | """ |
|
113 | 113 | Returns tuple in which first element is boolean that states that |
|
114 | 114 | given password matches it's hashed version, and the second is new hash |
|
115 | 115 | of the password, in case this password should be migrated to new |
|
116 | 116 | cipher. |
|
117 | 117 | """ |
|
118 | 118 | checked_hash = self.hash_check(password, hashed) |
|
119 | 119 | return checked_hash, None |
|
120 | 120 | |
|
121 | 121 | def hash_check(self, password, hashed): |
|
122 | 122 | """ |
|
123 | 123 | Checks matching password with it's hashed value. |
|
124 | 124 | |
|
125 | 125 | :param password: password |
|
126 | 126 | :param hashed: password in hashed form |
|
127 | 127 | """ |
|
128 | 128 | raise NotImplementedError |
|
129 | 129 | |
|
130 | 130 | def _assert_bytes(self, value): |
|
131 | 131 | """ |
|
132 | 132 | Passing in an `unicode` object can lead to hard to detect issues |
|
133 | 133 | if passwords contain non-ascii characters. Doing a type check |
|
134 | 134 | during runtime, so that such mistakes are detected early on. |
|
135 | 135 | """ |
|
136 | 136 | if not isinstance(value, str): |
|
137 | 137 | raise TypeError( |
|
138 | 138 | "Bytestring required as input, got %r." % (value, )) |
|
139 | 139 | |
|
140 | 140 | |
|
141 | 141 | class _RhodeCodeCryptoBCrypt(_RhodeCodeCryptoBase): |
|
142 | 142 | ENC_PREF = ('$2a$10', '$2b$10') |
|
143 | 143 | |
|
144 | 144 | def hash_create(self, str_): |
|
145 | 145 | self._assert_bytes(str_) |
|
146 | 146 | return bcrypt.hashpw(str_, bcrypt.gensalt(10)) |
|
147 | 147 | |
|
148 | 148 | def hash_check_with_upgrade(self, password, hashed): |
|
149 | 149 | """ |
|
150 | 150 | Returns tuple in which first element is boolean that states that |
|
151 | 151 | given password matches it's hashed version, and the second is new hash |
|
152 | 152 | of the password, in case this password should be migrated to new |
|
153 | 153 | cipher. |
|
154 | 154 | |
|
155 | 155 | This implements special upgrade logic which works like that: |
|
156 | 156 | - check if the given password == bcrypted hash, if yes then we |
|
157 | 157 | properly used password and it was already in bcrypt. Proceed |
|
158 | 158 | without any changes |
|
159 | 159 | - if bcrypt hash check is not working try with sha256. If hash compare |
|
160 | 160 | is ok, it means we using correct but old hashed password. indicate |
|
161 | 161 | hash change and proceed |
|
162 | 162 | """ |
|
163 | 163 | |
|
164 | 164 | new_hash = None |
|
165 | 165 | |
|
166 | 166 | # regular pw check |
|
167 | 167 | password_match_bcrypt = self.hash_check(password, hashed) |
|
168 | 168 | |
|
169 | 169 | # now we want to know if the password was maybe from sha256 |
|
170 | 170 | # basically calling _RhodeCodeCryptoSha256().hash_check() |
|
171 | 171 | if not password_match_bcrypt: |
|
172 | 172 | if _RhodeCodeCryptoSha256().hash_check(password, hashed): |
|
173 | 173 | new_hash = self.hash_create(password) # make new bcrypt hash |
|
174 | 174 | password_match_bcrypt = True |
|
175 | 175 | |
|
176 | 176 | return password_match_bcrypt, new_hash |
|
177 | 177 | |
|
178 | 178 | def hash_check(self, password, hashed): |
|
179 | 179 | """ |
|
180 | 180 | Checks matching password with it's hashed value. |
|
181 | 181 | |
|
182 | 182 | :param password: password |
|
183 | 183 | :param hashed: password in hashed form |
|
184 | 184 | """ |
|
185 | 185 | self._assert_bytes(password) |
|
186 | 186 | try: |
|
187 | 187 | return bcrypt.hashpw(password, hashed) == hashed |
|
188 | 188 | except ValueError as e: |
|
189 | 189 | # we're having a invalid salt here probably, we should not crash |
|
190 | 190 | # just return with False as it would be a wrong password. |
|
191 | 191 | log.debug('Failed to check password hash using bcrypt %s', |
|
192 | 192 | safe_str(e)) |
|
193 | 193 | |
|
194 | 194 | return False |
|
195 | 195 | |
|
196 | 196 | |
|
197 | 197 | class _RhodeCodeCryptoSha256(_RhodeCodeCryptoBase): |
|
198 | 198 | ENC_PREF = '_' |
|
199 | 199 | |
|
200 | 200 | def hash_create(self, str_): |
|
201 | 201 | self._assert_bytes(str_) |
|
202 | 202 | return hashlib.sha256(str_).hexdigest() |
|
203 | 203 | |
|
204 | 204 | def hash_check(self, password, hashed): |
|
205 | 205 | """ |
|
206 | 206 | Checks matching password with it's hashed value. |
|
207 | 207 | |
|
208 | 208 | :param password: password |
|
209 | 209 | :param hashed: password in hashed form |
|
210 | 210 | """ |
|
211 | 211 | self._assert_bytes(password) |
|
212 | 212 | return hashlib.sha256(password).hexdigest() == hashed |
|
213 | 213 | |
|
214 | 214 | |
|
215 | 215 | class _RhodeCodeCryptoMd5(_RhodeCodeCryptoBase): |
|
216 | 216 | ENC_PREF = '_' |
|
217 | 217 | |
|
218 | 218 | def hash_create(self, str_): |
|
219 | 219 | self._assert_bytes(str_) |
|
220 | 220 | return hashlib.md5(str_).hexdigest() |
|
221 | 221 | |
|
222 | 222 | def hash_check(self, password, hashed): |
|
223 | 223 | """ |
|
224 | 224 | Checks matching password with it's hashed value. |
|
225 | 225 | |
|
226 | 226 | :param password: password |
|
227 | 227 | :param hashed: password in hashed form |
|
228 | 228 | """ |
|
229 | 229 | self._assert_bytes(password) |
|
230 | 230 | return hashlib.md5(password).hexdigest() == hashed |
|
231 | 231 | |
|
232 | 232 | |
|
233 | 233 | def crypto_backend(): |
|
234 | 234 | """ |
|
235 | 235 | Return the matching crypto backend. |
|
236 | 236 | |
|
237 | 237 | Selection is based on if we run tests or not, we pick md5 backend to run |
|
238 | 238 | tests faster since BCRYPT is expensive to calculate |
|
239 | 239 | """ |
|
240 | 240 | if rhodecode.is_test: |
|
241 | 241 | RhodeCodeCrypto = _RhodeCodeCryptoMd5() |
|
242 | 242 | else: |
|
243 | 243 | RhodeCodeCrypto = _RhodeCodeCryptoBCrypt() |
|
244 | 244 | |
|
245 | 245 | return RhodeCodeCrypto |
|
246 | 246 | |
|
247 | 247 | |
|
248 | 248 | def get_crypt_password(password): |
|
249 | 249 | """ |
|
250 | 250 | Create the hash of `password` with the active crypto backend. |
|
251 | 251 | |
|
252 | 252 | :param password: The cleartext password. |
|
253 | 253 | :type password: unicode |
|
254 | 254 | """ |
|
255 | 255 | password = safe_str(password) |
|
256 | 256 | return crypto_backend().hash_create(password) |
|
257 | 257 | |
|
258 | 258 | |
|
259 | 259 | def check_password(password, hashed): |
|
260 | 260 | """ |
|
261 | 261 | Check if the value in `password` matches the hash in `hashed`. |
|
262 | 262 | |
|
263 | 263 | :param password: The cleartext password. |
|
264 | 264 | :type password: unicode |
|
265 | 265 | |
|
266 | 266 | :param hashed: The expected hashed version of the password. |
|
267 | 267 | :type hashed: The hash has to be passed in in text representation. |
|
268 | 268 | """ |
|
269 | 269 | password = safe_str(password) |
|
270 | 270 | return crypto_backend().hash_check(password, hashed) |
|
271 | 271 | |
|
272 | 272 | |
|
273 | 273 | def generate_auth_token(data, salt=None): |
|
274 | 274 | """ |
|
275 | 275 | Generates API KEY from given string |
|
276 | 276 | """ |
|
277 | 277 | |
|
278 | 278 | if salt is None: |
|
279 | 279 | salt = os.urandom(16) |
|
280 | 280 | return hashlib.sha1(safe_str(data) + salt).hexdigest() |
|
281 | 281 | |
|
282 | 282 | |
|
283 | 283 | def get_came_from(request): |
|
284 | 284 | """ |
|
285 | 285 | get query_string+path from request sanitized after removing auth_token |
|
286 | 286 | """ |
|
287 | 287 | _req = request |
|
288 | 288 | |
|
289 | 289 | path = _req.path |
|
290 | 290 | if 'auth_token' in _req.GET: |
|
291 | 291 | # sanitize the request and remove auth_token for redirection |
|
292 | 292 | _req.GET.pop('auth_token') |
|
293 | 293 | qs = _req.query_string |
|
294 | 294 | if qs: |
|
295 | 295 | path += '?' + qs |
|
296 | 296 | |
|
297 | 297 | return path |
|
298 | 298 | |
|
299 | 299 | |
|
300 | 300 | class CookieStoreWrapper(object): |
|
301 | 301 | |
|
302 | 302 | def __init__(self, cookie_store): |
|
303 | 303 | self.cookie_store = cookie_store |
|
304 | 304 | |
|
305 | 305 | def __repr__(self): |
|
306 | 306 | return 'CookieStore<%s>' % (self.cookie_store) |
|
307 | 307 | |
|
308 | 308 | def get(self, key, other=None): |
|
309 | 309 | if isinstance(self.cookie_store, dict): |
|
310 | 310 | return self.cookie_store.get(key, other) |
|
311 | 311 | elif isinstance(self.cookie_store, AuthUser): |
|
312 | 312 | return self.cookie_store.__dict__.get(key, other) |
|
313 | 313 | |
|
314 | 314 | |
|
315 | 315 | def _cached_perms_data(user_id, scope, user_is_admin, |
|
316 | 316 | user_inherit_default_permissions, explicit, algo, |
|
317 | 317 | calculate_super_admin): |
|
318 | 318 | |
|
319 | 319 | permissions = PermissionCalculator( |
|
320 | 320 | user_id, scope, user_is_admin, user_inherit_default_permissions, |
|
321 | 321 | explicit, algo, calculate_super_admin) |
|
322 | 322 | return permissions.calculate() |
|
323 | 323 | |
|
324 | 324 | |
|
325 | 325 | class PermOrigin(object): |
|
326 | 326 | SUPER_ADMIN = 'superadmin' |
|
327 | 327 | |
|
328 | 328 | REPO_USER = 'user:%s' |
|
329 | 329 | REPO_USERGROUP = 'usergroup:%s' |
|
330 | 330 | REPO_OWNER = 'repo.owner' |
|
331 | 331 | REPO_DEFAULT = 'repo.default' |
|
332 | 332 | REPO_DEFAULT_NO_INHERIT = 'repo.default.no.inherit' |
|
333 | 333 | REPO_PRIVATE = 'repo.private' |
|
334 | 334 | |
|
335 | 335 | REPOGROUP_USER = 'user:%s' |
|
336 | 336 | REPOGROUP_USERGROUP = 'usergroup:%s' |
|
337 | 337 | REPOGROUP_OWNER = 'group.owner' |
|
338 | 338 | REPOGROUP_DEFAULT = 'group.default' |
|
339 | 339 | REPOGROUP_DEFAULT_NO_INHERIT = 'group.default.no.inherit' |
|
340 | 340 | |
|
341 | 341 | USERGROUP_USER = 'user:%s' |
|
342 | 342 | USERGROUP_USERGROUP = 'usergroup:%s' |
|
343 | 343 | USERGROUP_OWNER = 'usergroup.owner' |
|
344 | 344 | USERGROUP_DEFAULT = 'usergroup.default' |
|
345 | 345 | USERGROUP_DEFAULT_NO_INHERIT = 'usergroup.default.no.inherit' |
|
346 | 346 | |
|
347 | 347 | |
|
348 | 348 | class PermOriginDict(dict): |
|
349 | 349 | """ |
|
350 | 350 | A special dict used for tracking permissions along with their origins. |
|
351 | 351 | |
|
352 | 352 | `__setitem__` has been overridden to expect a tuple(perm, origin) |
|
353 | 353 | `__getitem__` will return only the perm |
|
354 | 354 | `.perm_origin_stack` will return the stack of (perm, origin) set per key |
|
355 | 355 | |
|
356 | 356 | >>> perms = PermOriginDict() |
|
357 | 357 | >>> perms['resource'] = 'read', 'default' |
|
358 | 358 | >>> perms['resource'] |
|
359 | 359 | 'read' |
|
360 | 360 | >>> perms['resource'] = 'write', 'admin' |
|
361 | 361 | >>> perms['resource'] |
|
362 | 362 | 'write' |
|
363 | 363 | >>> perms.perm_origin_stack |
|
364 | 364 | {'resource': [('read', 'default'), ('write', 'admin')]} |
|
365 | 365 | """ |
|
366 | 366 | |
|
367 | 367 | def __init__(self, *args, **kw): |
|
368 | 368 | dict.__init__(self, *args, **kw) |
|
369 | 369 | self.perm_origin_stack = collections.OrderedDict() |
|
370 | 370 | |
|
371 | 371 | def __setitem__(self, key, (perm, origin)): |
|
372 | 372 | self.perm_origin_stack.setdefault(key, []).append((perm, origin)) |
|
373 | 373 | dict.__setitem__(self, key, perm) |
|
374 | 374 | |
|
375 | 375 | |
|
376 | 376 | class PermissionCalculator(object): |
|
377 | 377 | |
|
378 | 378 | def __init__( |
|
379 | 379 | self, user_id, scope, user_is_admin, |
|
380 | 380 | user_inherit_default_permissions, explicit, algo, |
|
381 | 381 | calculate_super_admin=False): |
|
382 | 382 | |
|
383 | 383 | self.user_id = user_id |
|
384 | 384 | self.user_is_admin = user_is_admin |
|
385 | 385 | self.inherit_default_permissions = user_inherit_default_permissions |
|
386 | 386 | self.explicit = explicit |
|
387 | 387 | self.algo = algo |
|
388 | 388 | self.calculate_super_admin = calculate_super_admin |
|
389 | 389 | |
|
390 | 390 | scope = scope or {} |
|
391 | 391 | self.scope_repo_id = scope.get('repo_id') |
|
392 | 392 | self.scope_repo_group_id = scope.get('repo_group_id') |
|
393 | 393 | self.scope_user_group_id = scope.get('user_group_id') |
|
394 | 394 | |
|
395 | 395 | self.default_user_id = User.get_default_user(cache=True).user_id |
|
396 | 396 | |
|
397 | 397 | self.permissions_repositories = PermOriginDict() |
|
398 | 398 | self.permissions_repository_groups = PermOriginDict() |
|
399 | 399 | self.permissions_user_groups = PermOriginDict() |
|
400 | 400 | self.permissions_global = set() |
|
401 | 401 | |
|
402 | 402 | self.default_repo_perms = Permission.get_default_repo_perms( |
|
403 | 403 | self.default_user_id, self.scope_repo_id) |
|
404 | 404 | self.default_repo_groups_perms = Permission.get_default_group_perms( |
|
405 | 405 | self.default_user_id, self.scope_repo_group_id) |
|
406 | 406 | self.default_user_group_perms = \ |
|
407 | 407 | Permission.get_default_user_group_perms( |
|
408 | 408 | self.default_user_id, self.scope_user_group_id) |
|
409 | 409 | |
|
410 | 410 | def calculate(self): |
|
411 | 411 | if self.user_is_admin and not self.calculate_super_admin: |
|
412 | 412 | return self._admin_permissions() |
|
413 | 413 | |
|
414 | 414 | self._calculate_global_default_permissions() |
|
415 | 415 | self._calculate_global_permissions() |
|
416 | 416 | self._calculate_default_permissions() |
|
417 | 417 | self._calculate_repository_permissions() |
|
418 | 418 | self._calculate_repository_group_permissions() |
|
419 | 419 | self._calculate_user_group_permissions() |
|
420 | 420 | return self._permission_structure() |
|
421 | 421 | |
|
422 | 422 | def _admin_permissions(self): |
|
423 | 423 | """ |
|
424 | 424 | admin user have all default rights for repositories |
|
425 | 425 | and groups set to admin |
|
426 | 426 | """ |
|
427 | 427 | self.permissions_global.add('hg.admin') |
|
428 | 428 | self.permissions_global.add('hg.create.write_on_repogroup.true') |
|
429 | 429 | |
|
430 | 430 | # repositories |
|
431 | 431 | for perm in self.default_repo_perms: |
|
432 | 432 | r_k = perm.UserRepoToPerm.repository.repo_name |
|
433 | 433 | p = 'repository.admin' |
|
434 | 434 | self.permissions_repositories[r_k] = p, PermOrigin.SUPER_ADMIN |
|
435 | 435 | |
|
436 | 436 | # repository groups |
|
437 | 437 | for perm in self.default_repo_groups_perms: |
|
438 | 438 | rg_k = perm.UserRepoGroupToPerm.group.group_name |
|
439 | 439 | p = 'group.admin' |
|
440 | 440 | self.permissions_repository_groups[rg_k] = p, PermOrigin.SUPER_ADMIN |
|
441 | 441 | |
|
442 | 442 | # user groups |
|
443 | 443 | for perm in self.default_user_group_perms: |
|
444 | 444 | u_k = perm.UserUserGroupToPerm.user_group.users_group_name |
|
445 | 445 | p = 'usergroup.admin' |
|
446 | 446 | self.permissions_user_groups[u_k] = p, PermOrigin.SUPER_ADMIN |
|
447 | 447 | |
|
448 | 448 | return self._permission_structure() |
|
449 | 449 | |
|
450 | 450 | def _calculate_global_default_permissions(self): |
|
451 | 451 | """ |
|
452 | 452 | global permissions taken from the default user |
|
453 | 453 | """ |
|
454 | 454 | default_global_perms = UserToPerm.query()\ |
|
455 | 455 | .filter(UserToPerm.user_id == self.default_user_id)\ |
|
456 | 456 | .options(joinedload(UserToPerm.permission)) |
|
457 | 457 | |
|
458 | 458 | for perm in default_global_perms: |
|
459 | 459 | self.permissions_global.add(perm.permission.permission_name) |
|
460 | 460 | |
|
461 | 461 | if self.user_is_admin: |
|
462 | 462 | self.permissions_global.add('hg.admin') |
|
463 | 463 | self.permissions_global.add('hg.create.write_on_repogroup.true') |
|
464 | 464 | |
|
465 | 465 | def _calculate_global_permissions(self): |
|
466 | 466 | """ |
|
467 | 467 | Set global system permissions with user permissions or permissions |
|
468 | 468 | taken from the user groups of the current user. |
|
469 | 469 | |
|
470 | 470 | The permissions include repo creating, repo group creating, forking |
|
471 | 471 | etc. |
|
472 | 472 | """ |
|
473 | 473 | |
|
474 | 474 | # now we read the defined permissions and overwrite what we have set |
|
475 | 475 | # before those can be configured from groups or users explicitly. |
|
476 | 476 | |
|
477 | 477 | # TODO: johbo: This seems to be out of sync, find out the reason |
|
478 | 478 | # for the comment below and update it. |
|
479 | 479 | |
|
480 | 480 | # In case we want to extend this list we should be always in sync with |
|
481 | 481 | # User.DEFAULT_USER_PERMISSIONS definitions |
|
482 | 482 | _configurable = frozenset([ |
|
483 | 483 | 'hg.fork.none', 'hg.fork.repository', |
|
484 | 484 | 'hg.create.none', 'hg.create.repository', |
|
485 | 485 | 'hg.usergroup.create.false', 'hg.usergroup.create.true', |
|
486 | 486 | 'hg.repogroup.create.false', 'hg.repogroup.create.true', |
|
487 | 487 | 'hg.create.write_on_repogroup.false', |
|
488 | 488 | 'hg.create.write_on_repogroup.true', |
|
489 | 489 | 'hg.inherit_default_perms.false', 'hg.inherit_default_perms.true' |
|
490 | 490 | ]) |
|
491 | 491 | |
|
492 | 492 | # USER GROUPS comes first user group global permissions |
|
493 | 493 | user_perms_from_users_groups = Session().query(UserGroupToPerm)\ |
|
494 | 494 | .options(joinedload(UserGroupToPerm.permission))\ |
|
495 | 495 | .join((UserGroupMember, UserGroupToPerm.users_group_id == |
|
496 | 496 | UserGroupMember.users_group_id))\ |
|
497 | 497 | .filter(UserGroupMember.user_id == self.user_id)\ |
|
498 | 498 | .order_by(UserGroupToPerm.users_group_id)\ |
|
499 | 499 | .all() |
|
500 | 500 | |
|
501 | 501 | # need to group here by groups since user can be in more than |
|
502 | 502 | # one group, so we get all groups |
|
503 | 503 | _explicit_grouped_perms = [ |
|
504 | 504 | [x, list(y)] for x, y in |
|
505 | 505 | itertools.groupby(user_perms_from_users_groups, |
|
506 | 506 | lambda _x: _x.users_group)] |
|
507 | 507 | |
|
508 | 508 | for gr, perms in _explicit_grouped_perms: |
|
509 | 509 | # since user can be in multiple groups iterate over them and |
|
510 | 510 | # select the lowest permissions first (more explicit) |
|
511 | 511 | # TODO: marcink: do this^^ |
|
512 | 512 | |
|
513 | 513 | # group doesn't inherit default permissions so we actually set them |
|
514 | 514 | if not gr.inherit_default_permissions: |
|
515 | 515 | # NEED TO IGNORE all previously set configurable permissions |
|
516 | 516 | # and replace them with explicitly set from this user |
|
517 | 517 | # group permissions |
|
518 | 518 | self.permissions_global = self.permissions_global.difference( |
|
519 | 519 | _configurable) |
|
520 | 520 | for perm in perms: |
|
521 | 521 | self.permissions_global.add(perm.permission.permission_name) |
|
522 | 522 | |
|
523 | 523 | # user explicit global permissions |
|
524 | 524 | user_perms = Session().query(UserToPerm)\ |
|
525 | 525 | .options(joinedload(UserToPerm.permission))\ |
|
526 | 526 | .filter(UserToPerm.user_id == self.user_id).all() |
|
527 | 527 | |
|
528 | 528 | if not self.inherit_default_permissions: |
|
529 | 529 | # NEED TO IGNORE all configurable permissions and |
|
530 | 530 | # replace them with explicitly set from this user permissions |
|
531 | 531 | self.permissions_global = self.permissions_global.difference( |
|
532 | 532 | _configurable) |
|
533 | 533 | for perm in user_perms: |
|
534 | 534 | self.permissions_global.add(perm.permission.permission_name) |
|
535 | 535 | |
|
536 | 536 | def _calculate_default_permissions(self): |
|
537 | 537 | """ |
|
538 | 538 | Set default user permissions for repositories, repository groups |
|
539 | 539 | taken from the default user. |
|
540 | 540 | |
|
541 | 541 | Calculate inheritance of object permissions based on what we have now |
|
542 | 542 | in GLOBAL permissions. We check if .false is in GLOBAL since this is |
|
543 | 543 | explicitly set. Inherit is the opposite of .false being there. |
|
544 | 544 | |
|
545 | 545 | .. note:: |
|
546 | 546 | |
|
547 | 547 | the syntax is little bit odd but what we need to check here is |
|
548 | 548 | the opposite of .false permission being in the list so even for |
|
549 | 549 | inconsistent state when both .true/.false is there |
|
550 | 550 | .false is more important |
|
551 | 551 | |
|
552 | 552 | """ |
|
553 | 553 | user_inherit_object_permissions = not ('hg.inherit_default_perms.false' |
|
554 | 554 | in self.permissions_global) |
|
555 | 555 | |
|
556 | 556 | # defaults for repositories, taken from `default` user permissions |
|
557 | 557 | # on given repo |
|
558 | 558 | for perm in self.default_repo_perms: |
|
559 | 559 | r_k = perm.UserRepoToPerm.repository.repo_name |
|
560 | 560 | p = perm.Permission.permission_name |
|
561 | 561 | o = PermOrigin.REPO_DEFAULT |
|
562 | 562 | self.permissions_repositories[r_k] = p, o |
|
563 | 563 | |
|
564 | 564 | # if we decide this user isn't inheriting permissions from |
|
565 | 565 | # default user we set him to .none so only explicit |
|
566 | 566 | # permissions work |
|
567 | 567 | if not user_inherit_object_permissions: |
|
568 | 568 | p = 'repository.none' |
|
569 | 569 | o = PermOrigin.REPO_DEFAULT_NO_INHERIT |
|
570 | 570 | self.permissions_repositories[r_k] = p, o |
|
571 | 571 | |
|
572 | 572 | if perm.Repository.private and not ( |
|
573 | 573 | perm.Repository.user_id == self.user_id): |
|
574 | 574 | # disable defaults for private repos, |
|
575 | 575 | p = 'repository.none' |
|
576 | 576 | o = PermOrigin.REPO_PRIVATE |
|
577 | 577 | self.permissions_repositories[r_k] = p, o |
|
578 | 578 | |
|
579 | 579 | elif perm.Repository.user_id == self.user_id: |
|
580 | 580 | # set admin if owner |
|
581 | 581 | p = 'repository.admin' |
|
582 | 582 | o = PermOrigin.REPO_OWNER |
|
583 | 583 | self.permissions_repositories[r_k] = p, o |
|
584 | 584 | |
|
585 | 585 | if self.user_is_admin: |
|
586 | 586 | p = 'repository.admin' |
|
587 | 587 | o = PermOrigin.SUPER_ADMIN |
|
588 | 588 | self.permissions_repositories[r_k] = p, o |
|
589 | 589 | |
|
590 | 590 | # defaults for repository groups taken from `default` user permission |
|
591 | 591 | # on given group |
|
592 | 592 | for perm in self.default_repo_groups_perms: |
|
593 | 593 | rg_k = perm.UserRepoGroupToPerm.group.group_name |
|
594 | 594 | p = perm.Permission.permission_name |
|
595 | 595 | o = PermOrigin.REPOGROUP_DEFAULT |
|
596 | 596 | self.permissions_repository_groups[rg_k] = p, o |
|
597 | 597 | |
|
598 | 598 | # if we decide this user isn't inheriting permissions from default |
|
599 | 599 | # user we set him to .none so only explicit permissions work |
|
600 | 600 | if not user_inherit_object_permissions: |
|
601 | 601 | p = 'group.none' |
|
602 | 602 | o = PermOrigin.REPOGROUP_DEFAULT_NO_INHERIT |
|
603 | 603 | self.permissions_repository_groups[rg_k] = p, o |
|
604 | 604 | |
|
605 | 605 | if perm.RepoGroup.user_id == self.user_id: |
|
606 | 606 | # set admin if owner |
|
607 | 607 | p = 'group.admin' |
|
608 | 608 | o = PermOrigin.REPOGROUP_OWNER |
|
609 | 609 | self.permissions_repository_groups[rg_k] = p, o |
|
610 | 610 | |
|
611 | 611 | if self.user_is_admin: |
|
612 | 612 | p = 'group.admin' |
|
613 | 613 | o = PermOrigin.SUPER_ADMIN |
|
614 | 614 | self.permissions_repository_groups[rg_k] = p, o |
|
615 | 615 | |
|
616 | 616 | # defaults for user groups taken from `default` user permission |
|
617 | 617 | # on given user group |
|
618 | 618 | for perm in self.default_user_group_perms: |
|
619 | 619 | u_k = perm.UserUserGroupToPerm.user_group.users_group_name |
|
620 | 620 | p = perm.Permission.permission_name |
|
621 | 621 | o = PermOrigin.USERGROUP_DEFAULT |
|
622 | 622 | self.permissions_user_groups[u_k] = p, o |
|
623 | 623 | |
|
624 | 624 | # if we decide this user isn't inheriting permissions from default |
|
625 | 625 | # user we set him to .none so only explicit permissions work |
|
626 | 626 | if not user_inherit_object_permissions: |
|
627 | 627 | p = 'usergroup.none' |
|
628 | 628 | o = PermOrigin.USERGROUP_DEFAULT_NO_INHERIT |
|
629 | 629 | self.permissions_user_groups[u_k] = p, o |
|
630 | 630 | |
|
631 | 631 | if perm.UserGroup.user_id == self.user_id: |
|
632 | 632 | # set admin if owner |
|
633 | 633 | p = 'usergroup.admin' |
|
634 | 634 | o = PermOrigin.USERGROUP_OWNER |
|
635 | 635 | self.permissions_user_groups[u_k] = p, o |
|
636 | 636 | |
|
637 | 637 | if self.user_is_admin: |
|
638 | 638 | p = 'usergroup.admin' |
|
639 | 639 | o = PermOrigin.SUPER_ADMIN |
|
640 | 640 | self.permissions_user_groups[u_k] = p, o |
|
641 | 641 | |
|
642 | 642 | def _calculate_repository_permissions(self): |
|
643 | 643 | """ |
|
644 | 644 | Repository permissions for the current user. |
|
645 | 645 | |
|
646 | 646 | Check if the user is part of user groups for this repository and |
|
647 | 647 | fill in the permission from it. `_choose_permission` decides of which |
|
648 | 648 | permission should be selected based on selected method. |
|
649 | 649 | """ |
|
650 | 650 | |
|
651 | 651 | # user group for repositories permissions |
|
652 | 652 | user_repo_perms_from_user_group = Permission\ |
|
653 | 653 | .get_default_repo_perms_from_user_group( |
|
654 | 654 | self.user_id, self.scope_repo_id) |
|
655 | 655 | |
|
656 | 656 | multiple_counter = collections.defaultdict(int) |
|
657 | 657 | for perm in user_repo_perms_from_user_group: |
|
658 | 658 | r_k = perm.UserGroupRepoToPerm.repository.repo_name |
|
659 | 659 | multiple_counter[r_k] += 1 |
|
660 | 660 | p = perm.Permission.permission_name |
|
661 | 661 | o = PermOrigin.REPO_USERGROUP % perm.UserGroupRepoToPerm\ |
|
662 | 662 | .users_group.users_group_name |
|
663 | 663 | |
|
664 | 664 | if multiple_counter[r_k] > 1: |
|
665 | 665 | cur_perm = self.permissions_repositories[r_k] |
|
666 | 666 | p = self._choose_permission(p, cur_perm) |
|
667 | 667 | |
|
668 | 668 | self.permissions_repositories[r_k] = p, o |
|
669 | 669 | |
|
670 | 670 | if perm.Repository.user_id == self.user_id: |
|
671 | 671 | # set admin if owner |
|
672 | 672 | p = 'repository.admin' |
|
673 | 673 | o = PermOrigin.REPO_OWNER |
|
674 | 674 | self.permissions_repositories[r_k] = p, o |
|
675 | 675 | |
|
676 | 676 | if self.user_is_admin: |
|
677 | 677 | p = 'repository.admin' |
|
678 | 678 | o = PermOrigin.SUPER_ADMIN |
|
679 | 679 | self.permissions_repositories[r_k] = p, o |
|
680 | 680 | |
|
681 | 681 | # user explicit permissions for repositories, overrides any specified |
|
682 | 682 | # by the group permission |
|
683 | 683 | user_repo_perms = Permission.get_default_repo_perms( |
|
684 | 684 | self.user_id, self.scope_repo_id) |
|
685 | 685 | for perm in user_repo_perms: |
|
686 | 686 | r_k = perm.UserRepoToPerm.repository.repo_name |
|
687 | 687 | p = perm.Permission.permission_name |
|
688 | 688 | o = PermOrigin.REPO_USER % perm.UserRepoToPerm.user.username |
|
689 | 689 | |
|
690 | 690 | if not self.explicit: |
|
691 | 691 | cur_perm = self.permissions_repositories.get( |
|
692 | 692 | r_k, 'repository.none') |
|
693 | 693 | p = self._choose_permission(p, cur_perm) |
|
694 | 694 | |
|
695 | 695 | self.permissions_repositories[r_k] = p, o |
|
696 | 696 | |
|
697 | 697 | if perm.Repository.user_id == self.user_id: |
|
698 | 698 | # set admin if owner |
|
699 | 699 | p = 'repository.admin' |
|
700 | 700 | o = PermOrigin.REPO_OWNER |
|
701 | 701 | self.permissions_repositories[r_k] = p, o |
|
702 | 702 | |
|
703 | 703 | if self.user_is_admin: |
|
704 | 704 | p = 'repository.admin' |
|
705 | 705 | o = PermOrigin.SUPER_ADMIN |
|
706 | 706 | self.permissions_repositories[r_k] = p, o |
|
707 | 707 | |
|
708 | 708 | def _calculate_repository_group_permissions(self): |
|
709 | 709 | """ |
|
710 | 710 | Repository group permissions for the current user. |
|
711 | 711 | |
|
712 | 712 | Check if the user is part of user groups for repository groups and |
|
713 | 713 | fill in the permissions from it. `_choose_permission` decides of which |
|
714 | 714 | permission should be selected based on selected method. |
|
715 | 715 | """ |
|
716 | 716 | # user group for repo groups permissions |
|
717 | 717 | user_repo_group_perms_from_user_group = Permission\ |
|
718 | 718 | .get_default_group_perms_from_user_group( |
|
719 | 719 | self.user_id, self.scope_repo_group_id) |
|
720 | 720 | |
|
721 | 721 | multiple_counter = collections.defaultdict(int) |
|
722 | 722 | for perm in user_repo_group_perms_from_user_group: |
|
723 | 723 | rg_k = perm.UserGroupRepoGroupToPerm.group.group_name |
|
724 | 724 | multiple_counter[rg_k] += 1 |
|
725 | 725 | o = PermOrigin.REPOGROUP_USERGROUP % perm.UserGroupRepoGroupToPerm\ |
|
726 | 726 | .users_group.users_group_name |
|
727 | 727 | p = perm.Permission.permission_name |
|
728 | 728 | |
|
729 | 729 | if multiple_counter[rg_k] > 1: |
|
730 | 730 | cur_perm = self.permissions_repository_groups[rg_k] |
|
731 | 731 | p = self._choose_permission(p, cur_perm) |
|
732 | 732 | self.permissions_repository_groups[rg_k] = p, o |
|
733 | 733 | |
|
734 | 734 | if perm.RepoGroup.user_id == self.user_id: |
|
735 | 735 | # set admin if owner, even for member of other user group |
|
736 | 736 | p = 'group.admin' |
|
737 | 737 | o = PermOrigin.REPOGROUP_OWNER |
|
738 | 738 | self.permissions_repository_groups[rg_k] = p, o |
|
739 | 739 | |
|
740 | 740 | if self.user_is_admin: |
|
741 | 741 | p = 'group.admin' |
|
742 | 742 | o = PermOrigin.SUPER_ADMIN |
|
743 | 743 | self.permissions_repository_groups[rg_k] = p, o |
|
744 | 744 | |
|
745 | 745 | # user explicit permissions for repository groups |
|
746 | 746 | user_repo_groups_perms = Permission.get_default_group_perms( |
|
747 | 747 | self.user_id, self.scope_repo_group_id) |
|
748 | 748 | for perm in user_repo_groups_perms: |
|
749 | 749 | rg_k = perm.UserRepoGroupToPerm.group.group_name |
|
750 | 750 | o = PermOrigin.REPOGROUP_USER % perm.UserRepoGroupToPerm\ |
|
751 | 751 | .user.username |
|
752 | 752 | p = perm.Permission.permission_name |
|
753 | 753 | |
|
754 | 754 | if not self.explicit: |
|
755 | 755 | cur_perm = self.permissions_repository_groups.get( |
|
756 | 756 | rg_k, 'group.none') |
|
757 | 757 | p = self._choose_permission(p, cur_perm) |
|
758 | 758 | |
|
759 | 759 | self.permissions_repository_groups[rg_k] = p, o |
|
760 | 760 | |
|
761 | 761 | if perm.RepoGroup.user_id == self.user_id: |
|
762 | 762 | # set admin if owner |
|
763 | 763 | p = 'group.admin' |
|
764 | 764 | o = PermOrigin.REPOGROUP_OWNER |
|
765 | 765 | self.permissions_repository_groups[rg_k] = p, o |
|
766 | 766 | |
|
767 | 767 | if self.user_is_admin: |
|
768 | 768 | p = 'group.admin' |
|
769 | 769 | o = PermOrigin.SUPER_ADMIN |
|
770 | 770 | self.permissions_repository_groups[rg_k] = p, o |
|
771 | 771 | |
|
772 | 772 | def _calculate_user_group_permissions(self): |
|
773 | 773 | """ |
|
774 | 774 | User group permissions for the current user. |
|
775 | 775 | """ |
|
776 | 776 | # user group for user group permissions |
|
777 | 777 | user_group_from_user_group = Permission\ |
|
778 | 778 | .get_default_user_group_perms_from_user_group( |
|
779 | 779 | self.user_id, self.scope_user_group_id) |
|
780 | 780 | |
|
781 | 781 | multiple_counter = collections.defaultdict(int) |
|
782 | 782 | for perm in user_group_from_user_group: |
|
783 | 783 | ug_k = perm.UserGroupUserGroupToPerm\ |
|
784 | 784 | .target_user_group.users_group_name |
|
785 | 785 | multiple_counter[ug_k] += 1 |
|
786 | 786 | o = PermOrigin.USERGROUP_USERGROUP % perm.UserGroupUserGroupToPerm\ |
|
787 | 787 | .user_group.users_group_name |
|
788 | 788 | p = perm.Permission.permission_name |
|
789 | 789 | |
|
790 | 790 | if multiple_counter[ug_k] > 1: |
|
791 | 791 | cur_perm = self.permissions_user_groups[ug_k] |
|
792 | 792 | p = self._choose_permission(p, cur_perm) |
|
793 | 793 | |
|
794 | 794 | self.permissions_user_groups[ug_k] = p, o |
|
795 | 795 | |
|
796 | 796 | if perm.UserGroup.user_id == self.user_id: |
|
797 | 797 | # set admin if owner, even for member of other user group |
|
798 | 798 | p = 'usergroup.admin' |
|
799 | 799 | o = PermOrigin.USERGROUP_OWNER |
|
800 | 800 | self.permissions_user_groups[ug_k] = p, o |
|
801 | 801 | |
|
802 | 802 | if self.user_is_admin: |
|
803 | 803 | p = 'usergroup.admin' |
|
804 | 804 | o = PermOrigin.SUPER_ADMIN |
|
805 | 805 | self.permissions_user_groups[ug_k] = p, o |
|
806 | 806 | |
|
807 | 807 | # user explicit permission for user groups |
|
808 | 808 | user_user_groups_perms = Permission.get_default_user_group_perms( |
|
809 | 809 | self.user_id, self.scope_user_group_id) |
|
810 | 810 | for perm in user_user_groups_perms: |
|
811 | 811 | ug_k = perm.UserUserGroupToPerm.user_group.users_group_name |
|
812 | 812 | o = PermOrigin.USERGROUP_USER % perm.UserUserGroupToPerm\ |
|
813 | 813 | .user.username |
|
814 | 814 | p = perm.Permission.permission_name |
|
815 | 815 | |
|
816 | 816 | if not self.explicit: |
|
817 | 817 | cur_perm = self.permissions_user_groups.get( |
|
818 | 818 | ug_k, 'usergroup.none') |
|
819 | 819 | p = self._choose_permission(p, cur_perm) |
|
820 | 820 | |
|
821 | 821 | self.permissions_user_groups[ug_k] = p, o |
|
822 | 822 | |
|
823 | 823 | if perm.UserGroup.user_id == self.user_id: |
|
824 | 824 | # set admin if owner |
|
825 | 825 | p = 'usergroup.admin' |
|
826 | 826 | o = PermOrigin.USERGROUP_OWNER |
|
827 | 827 | self.permissions_user_groups[ug_k] = p, o |
|
828 | 828 | |
|
829 | 829 | if self.user_is_admin: |
|
830 | 830 | p = 'usergroup.admin' |
|
831 | 831 | o = PermOrigin.SUPER_ADMIN |
|
832 | 832 | self.permissions_user_groups[ug_k] = p, o |
|
833 | 833 | |
|
834 | 834 | def _choose_permission(self, new_perm, cur_perm): |
|
835 | 835 | new_perm_val = Permission.PERM_WEIGHTS[new_perm] |
|
836 | 836 | cur_perm_val = Permission.PERM_WEIGHTS[cur_perm] |
|
837 | 837 | if self.algo == 'higherwin': |
|
838 | 838 | if new_perm_val > cur_perm_val: |
|
839 | 839 | return new_perm |
|
840 | 840 | return cur_perm |
|
841 | 841 | elif self.algo == 'lowerwin': |
|
842 | 842 | if new_perm_val < cur_perm_val: |
|
843 | 843 | return new_perm |
|
844 | 844 | return cur_perm |
|
845 | 845 | |
|
846 | 846 | def _permission_structure(self): |
|
847 | 847 | return { |
|
848 | 848 | 'global': self.permissions_global, |
|
849 | 849 | 'repositories': self.permissions_repositories, |
|
850 | 850 | 'repositories_groups': self.permissions_repository_groups, |
|
851 | 851 | 'user_groups': self.permissions_user_groups, |
|
852 | 852 | } |
|
853 | 853 | |
|
854 | 854 | |
|
855 | 855 | def allowed_auth_token_access(view_name, auth_token, whitelist=None): |
|
856 | 856 | """ |
|
857 | 857 | Check if given controller_name is in whitelist of auth token access |
|
858 | 858 | """ |
|
859 | 859 | if not whitelist: |
|
860 | 860 | from rhodecode import CONFIG |
|
861 | 861 | whitelist = aslist( |
|
862 | 862 | CONFIG.get('api_access_controllers_whitelist'), sep=',') |
|
863 | 863 | # backward compat translation |
|
864 | 864 | compat = { |
|
865 | 865 | # old controller, new VIEW |
|
866 | 866 | 'ChangesetController:*': 'RepoCommitsView:*', |
|
867 | 867 | 'ChangesetController:changeset_patch': 'RepoCommitsView:repo_commit_patch', |
|
868 | 868 | 'ChangesetController:changeset_raw': 'RepoCommitsView:repo_commit_raw', |
|
869 | 869 | 'FilesController:raw': 'RepoCommitsView:repo_commit_raw', |
|
870 | 870 | 'FilesController:archivefile': 'RepoFilesView:repo_archivefile', |
|
871 | 871 | 'GistsController:*': 'GistView:*', |
|
872 | 872 | } |
|
873 | 873 | |
|
874 | 874 | log.debug( |
|
875 | 875 | 'Allowed views for AUTH TOKEN access: %s' % (whitelist,)) |
|
876 | 876 | auth_token_access_valid = False |
|
877 | 877 | |
|
878 | 878 | for entry in whitelist: |
|
879 | 879 | token_match = True |
|
880 | 880 | if entry in compat: |
|
881 | 881 | # translate from old Controllers to Pyramid Views |
|
882 | 882 | entry = compat[entry] |
|
883 | 883 | |
|
884 | 884 | if '@' in entry: |
|
885 | 885 | # specific AuthToken |
|
886 | 886 | entry, allowed_token = entry.split('@', 1) |
|
887 | 887 | token_match = auth_token == allowed_token |
|
888 | 888 | |
|
889 | 889 | if fnmatch.fnmatch(view_name, entry) and token_match: |
|
890 | 890 | auth_token_access_valid = True |
|
891 | 891 | break |
|
892 | 892 | |
|
893 | 893 | if auth_token_access_valid: |
|
894 | 894 | log.debug('view: `%s` matches entry in whitelist: %s' |
|
895 | 895 | % (view_name, whitelist)) |
|
896 | 896 | else: |
|
897 | 897 | msg = ('view: `%s` does *NOT* match any entry in whitelist: %s' |
|
898 | 898 | % (view_name, whitelist)) |
|
899 | 899 | if auth_token: |
|
900 | 900 | # if we use auth token key and don't have access it's a warning |
|
901 | 901 | log.warning(msg) |
|
902 | 902 | else: |
|
903 | 903 | log.debug(msg) |
|
904 | 904 | |
|
905 | 905 | return auth_token_access_valid |
|
906 | 906 | |
|
907 | 907 | |
|
908 | 908 | class AuthUser(object): |
|
909 | 909 | """ |
|
910 | 910 | A simple object that handles all attributes of user in RhodeCode |
|
911 | 911 | |
|
912 | 912 | It does lookup based on API key,given user, or user present in session |
|
913 | 913 | Then it fills all required information for such user. It also checks if |
|
914 | 914 | anonymous access is enabled and if so, it returns default user as logged in |
|
915 | 915 | """ |
|
916 | 916 | GLOBAL_PERMS = [x[0] for x in Permission.PERMS] |
|
917 | 917 | |
|
918 | 918 | def __init__(self, user_id=None, api_key=None, username=None, ip_addr=None): |
|
919 | 919 | |
|
920 | 920 | self.user_id = user_id |
|
921 | 921 | self._api_key = api_key |
|
922 | 922 | |
|
923 | 923 | self.api_key = None |
|
924 | 924 | self.feed_token = '' |
|
925 | 925 | self.username = username |
|
926 | 926 | self.ip_addr = ip_addr |
|
927 | 927 | self.name = '' |
|
928 | 928 | self.lastname = '' |
|
929 | 929 | self.first_name = '' |
|
930 | 930 | self.last_name = '' |
|
931 | 931 | self.email = '' |
|
932 | 932 | self.is_authenticated = False |
|
933 | 933 | self.admin = False |
|
934 | 934 | self.inherit_default_permissions = False |
|
935 | 935 | self.password = '' |
|
936 | 936 | |
|
937 | 937 | self.anonymous_user = None # propagated on propagate_data |
|
938 | 938 | self.propagate_data() |
|
939 | 939 | self._instance = None |
|
940 | 940 | self._permissions_scoped_cache = {} # used to bind scoped calculation |
|
941 | 941 | |
|
942 | 942 | @LazyProperty |
|
943 | 943 | def permissions(self): |
|
944 | 944 | return self.get_perms(user=self, cache=False) |
|
945 | 945 | |
|
946 | 946 | @LazyProperty |
|
947 | 947 | def permissions_full_details(self): |
|
948 | 948 | return self.get_perms( |
|
949 | 949 | user=self, cache=False, calculate_super_admin=True) |
|
950 | 950 | |
|
951 | 951 | def permissions_with_scope(self, scope): |
|
952 | 952 | """ |
|
953 | 953 | Call the get_perms function with scoped data. The scope in that function |
|
954 | 954 | narrows the SQL calls to the given ID of objects resulting in fetching |
|
955 | 955 | Just particular permission we want to obtain. If scope is an empty dict |
|
956 | 956 | then it basically narrows the scope to GLOBAL permissions only. |
|
957 | 957 | |
|
958 | 958 | :param scope: dict |
|
959 | 959 | """ |
|
960 | 960 | if 'repo_name' in scope: |
|
961 | 961 | obj = Repository.get_by_repo_name(scope['repo_name']) |
|
962 | 962 | if obj: |
|
963 | 963 | scope['repo_id'] = obj.repo_id |
|
964 | 964 | _scope = { |
|
965 | 965 | 'repo_id': -1, |
|
966 | 966 | 'user_group_id': -1, |
|
967 | 967 | 'repo_group_id': -1, |
|
968 | 968 | } |
|
969 | 969 | _scope.update(scope) |
|
970 | 970 | cache_key = "_".join(map(safe_str, reduce(lambda a, b: a+b, |
|
971 | 971 | _scope.items()))) |
|
972 | 972 | if cache_key not in self._permissions_scoped_cache: |
|
973 | 973 | # store in cache to mimic how the @LazyProperty works, |
|
974 | 974 | # the difference here is that we use the unique key calculated |
|
975 | 975 | # from params and values |
|
976 | 976 | res = self.get_perms(user=self, cache=False, scope=_scope) |
|
977 | 977 | self._permissions_scoped_cache[cache_key] = res |
|
978 | 978 | return self._permissions_scoped_cache[cache_key] |
|
979 | 979 | |
|
980 | 980 | def get_instance(self): |
|
981 | 981 | return User.get(self.user_id) |
|
982 | 982 | |
|
983 | 983 | def update_lastactivity(self): |
|
984 | 984 | if self.user_id: |
|
985 | 985 | User.get(self.user_id).update_lastactivity() |
|
986 | 986 | |
|
987 | 987 | def propagate_data(self): |
|
988 | 988 | """ |
|
989 | 989 | Fills in user data and propagates values to this instance. Maps fetched |
|
990 | 990 | user attributes to this class instance attributes |
|
991 | 991 | """ |
|
992 | 992 | log.debug('AuthUser: starting data propagation for new potential user') |
|
993 | 993 | user_model = UserModel() |
|
994 | 994 | anon_user = self.anonymous_user = User.get_default_user(cache=True) |
|
995 | 995 | is_user_loaded = False |
|
996 | 996 | |
|
997 | 997 | # lookup by userid |
|
998 | 998 | if self.user_id is not None and self.user_id != anon_user.user_id: |
|
999 | 999 | log.debug('Trying Auth User lookup by USER ID: `%s`', self.user_id) |
|
1000 | 1000 | is_user_loaded = user_model.fill_data(self, user_id=self.user_id) |
|
1001 | 1001 | |
|
1002 | 1002 | # try go get user by api key |
|
1003 | 1003 | elif self._api_key and self._api_key != anon_user.api_key: |
|
1004 | 1004 | log.debug('Trying Auth User lookup by API KEY: `%s`', self._api_key) |
|
1005 | 1005 | is_user_loaded = user_model.fill_data(self, api_key=self._api_key) |
|
1006 | 1006 | |
|
1007 | 1007 | # lookup by username |
|
1008 | 1008 | elif self.username: |
|
1009 | 1009 | log.debug('Trying Auth User lookup by USER NAME: `%s`', self.username) |
|
1010 | 1010 | is_user_loaded = user_model.fill_data(self, username=self.username) |
|
1011 | 1011 | else: |
|
1012 | 1012 | log.debug('No data in %s that could been used to log in', self) |
|
1013 | 1013 | |
|
1014 | 1014 | if not is_user_loaded: |
|
1015 | log.debug('Failed to load user. Fallback to default user') | |
|
1015 | log.debug( | |
|
1016 | 'Failed to load user. Fallback to default user %s', anon_user) | |
|
1016 | 1017 | # if we cannot authenticate user try anonymous |
|
1017 | 1018 | if anon_user.active: |
|
1019 | log.debug('default user is active, using it as a session user') | |
|
1018 | 1020 | user_model.fill_data(self, user_id=anon_user.user_id) |
|
1019 | 1021 | # then we set this user is logged in |
|
1020 | 1022 | self.is_authenticated = True |
|
1021 | 1023 | else: |
|
1024 | log.debug('default user is NOT active') | |
|
1022 | 1025 | # in case of disabled anonymous user we reset some of the |
|
1023 | 1026 | # parameters so such user is "corrupted", skipping the fill_data |
|
1024 | 1027 | for attr in ['user_id', 'username', 'admin', 'active']: |
|
1025 | 1028 | setattr(self, attr, None) |
|
1026 | 1029 | self.is_authenticated = False |
|
1027 | 1030 | |
|
1028 | 1031 | if not self.username: |
|
1029 | 1032 | self.username = 'None' |
|
1030 | 1033 | |
|
1031 | 1034 | log.debug('AuthUser: propagated user is now %s', self) |
|
1032 | 1035 | |
|
1033 | 1036 | def get_perms(self, user, scope=None, explicit=True, algo='higherwin', |
|
1034 | 1037 | calculate_super_admin=False, cache=False): |
|
1035 | 1038 | """ |
|
1036 | 1039 | Fills user permission attribute with permissions taken from database |
|
1037 | 1040 | works for permissions given for repositories, and for permissions that |
|
1038 | 1041 | are granted to groups |
|
1039 | 1042 | |
|
1040 | 1043 | :param user: instance of User object from database |
|
1041 | 1044 | :param explicit: In case there are permissions both for user and a group |
|
1042 | 1045 | that user is part of, explicit flag will defiine if user will |
|
1043 | 1046 | explicitly override permissions from group, if it's False it will |
|
1044 | 1047 | make decision based on the algo |
|
1045 | 1048 | :param algo: algorithm to decide what permission should be choose if |
|
1046 | 1049 | it's multiple defined, eg user in two different groups. It also |
|
1047 | 1050 | decides if explicit flag is turned off how to specify the permission |
|
1048 | 1051 | for case when user is in a group + have defined separate permission |
|
1049 | 1052 | """ |
|
1050 | 1053 | user_id = user.user_id |
|
1051 | 1054 | user_is_admin = user.is_admin |
|
1052 | 1055 | |
|
1053 | 1056 | # inheritance of global permissions like create repo/fork repo etc |
|
1054 | 1057 | user_inherit_default_permissions = user.inherit_default_permissions |
|
1055 | 1058 | |
|
1056 | 1059 | log.debug('Computing PERMISSION tree for scope %s' % (scope, )) |
|
1057 | 1060 | compute = caches.conditional_cache( |
|
1058 | 1061 | 'short_term', 'cache_desc', |
|
1059 | 1062 | condition=cache, func=_cached_perms_data) |
|
1060 | 1063 | result = compute(user_id, scope, user_is_admin, |
|
1061 | 1064 | user_inherit_default_permissions, explicit, algo, |
|
1062 | 1065 | calculate_super_admin) |
|
1063 | 1066 | |
|
1064 | 1067 | result_repr = [] |
|
1065 | 1068 | for k in result: |
|
1066 | 1069 | result_repr.append((k, len(result[k]))) |
|
1067 | 1070 | |
|
1068 | 1071 | log.debug('PERMISSION tree computed %s' % (result_repr,)) |
|
1069 | 1072 | return result |
|
1070 | 1073 | |
|
1071 | 1074 | @property |
|
1072 | 1075 | def is_default(self): |
|
1073 | 1076 | return self.username == User.DEFAULT_USER |
|
1074 | 1077 | |
|
1075 | 1078 | @property |
|
1076 | 1079 | def is_admin(self): |
|
1077 | 1080 | return self.admin |
|
1078 | 1081 | |
|
1079 | 1082 | @property |
|
1080 | 1083 | def is_user_object(self): |
|
1081 | 1084 | return self.user_id is not None |
|
1082 | 1085 | |
|
1083 | 1086 | @property |
|
1084 | 1087 | def repositories_admin(self): |
|
1085 | 1088 | """ |
|
1086 | 1089 | Returns list of repositories you're an admin of |
|
1087 | 1090 | """ |
|
1088 | 1091 | return [ |
|
1089 | 1092 | x[0] for x in self.permissions['repositories'].iteritems() |
|
1090 | 1093 | if x[1] == 'repository.admin'] |
|
1091 | 1094 | |
|
1092 | 1095 | @property |
|
1093 | 1096 | def repository_groups_admin(self): |
|
1094 | 1097 | """ |
|
1095 | 1098 | Returns list of repository groups you're an admin of |
|
1096 | 1099 | """ |
|
1097 | 1100 | return [ |
|
1098 | 1101 | x[0] for x in self.permissions['repositories_groups'].iteritems() |
|
1099 | 1102 | if x[1] == 'group.admin'] |
|
1100 | 1103 | |
|
1101 | 1104 | @property |
|
1102 | 1105 | def user_groups_admin(self): |
|
1103 | 1106 | """ |
|
1104 | 1107 | Returns list of user groups you're an admin of |
|
1105 | 1108 | """ |
|
1106 | 1109 | return [ |
|
1107 | 1110 | x[0] for x in self.permissions['user_groups'].iteritems() |
|
1108 | 1111 | if x[1] == 'usergroup.admin'] |
|
1109 | 1112 | |
|
1110 | 1113 | def repo_acl_ids(self, perms=None, name_filter=None, cache=False): |
|
1111 | 1114 | """ |
|
1112 | 1115 | Returns list of repository ids that user have access to based on given |
|
1113 | 1116 | perms. The cache flag should be only used in cases that are used for |
|
1114 | 1117 | display purposes, NOT IN ANY CASE for permission checks. |
|
1115 | 1118 | """ |
|
1116 | 1119 | from rhodecode.model.scm import RepoList |
|
1117 | 1120 | if not perms: |
|
1118 | 1121 | perms = [ |
|
1119 | 1122 | 'repository.read', 'repository.write', 'repository.admin'] |
|
1120 | 1123 | |
|
1121 | 1124 | def _cached_repo_acl(user_id, perm_def, name_filter): |
|
1122 | 1125 | qry = Repository.query() |
|
1123 | 1126 | if name_filter: |
|
1124 | 1127 | ilike_expression = u'%{}%'.format(safe_unicode(name_filter)) |
|
1125 | 1128 | qry = qry.filter( |
|
1126 | 1129 | Repository.repo_name.ilike(ilike_expression)) |
|
1127 | 1130 | |
|
1128 | 1131 | return [x.repo_id for x in |
|
1129 | 1132 | RepoList(qry, perm_set=perm_def)] |
|
1130 | 1133 | |
|
1131 | 1134 | compute = caches.conditional_cache( |
|
1132 | 1135 | 'long_term', 'repo_acl_ids', |
|
1133 | 1136 | condition=cache, func=_cached_repo_acl) |
|
1134 | 1137 | return compute(self.user_id, perms, name_filter) |
|
1135 | 1138 | |
|
1136 | 1139 | def repo_group_acl_ids(self, perms=None, name_filter=None, cache=False): |
|
1137 | 1140 | """ |
|
1138 | 1141 | Returns list of repository group ids that user have access to based on given |
|
1139 | 1142 | perms. The cache flag should be only used in cases that are used for |
|
1140 | 1143 | display purposes, NOT IN ANY CASE for permission checks. |
|
1141 | 1144 | """ |
|
1142 | 1145 | from rhodecode.model.scm import RepoGroupList |
|
1143 | 1146 | if not perms: |
|
1144 | 1147 | perms = [ |
|
1145 | 1148 | 'group.read', 'group.write', 'group.admin'] |
|
1146 | 1149 | |
|
1147 | 1150 | def _cached_repo_group_acl(user_id, perm_def, name_filter): |
|
1148 | 1151 | qry = RepoGroup.query() |
|
1149 | 1152 | if name_filter: |
|
1150 | 1153 | ilike_expression = u'%{}%'.format(safe_unicode(name_filter)) |
|
1151 | 1154 | qry = qry.filter( |
|
1152 | 1155 | RepoGroup.group_name.ilike(ilike_expression)) |
|
1153 | 1156 | |
|
1154 | 1157 | return [x.group_id for x in |
|
1155 | 1158 | RepoGroupList(qry, perm_set=perm_def)] |
|
1156 | 1159 | |
|
1157 | 1160 | compute = caches.conditional_cache( |
|
1158 | 1161 | 'long_term', 'repo_group_acl_ids', |
|
1159 | 1162 | condition=cache, func=_cached_repo_group_acl) |
|
1160 | 1163 | return compute(self.user_id, perms, name_filter) |
|
1161 | 1164 | |
|
1162 | 1165 | def user_group_acl_ids(self, perms=None, name_filter=None, cache=False): |
|
1163 | 1166 | """ |
|
1164 | 1167 | Returns list of user group ids that user have access to based on given |
|
1165 | 1168 | perms. The cache flag should be only used in cases that are used for |
|
1166 | 1169 | display purposes, NOT IN ANY CASE for permission checks. |
|
1167 | 1170 | """ |
|
1168 | 1171 | from rhodecode.model.scm import UserGroupList |
|
1169 | 1172 | if not perms: |
|
1170 | 1173 | perms = [ |
|
1171 | 1174 | 'usergroup.read', 'usergroup.write', 'usergroup.admin'] |
|
1172 | 1175 | |
|
1173 | 1176 | def _cached_user_group_acl(user_id, perm_def, name_filter): |
|
1174 | 1177 | qry = UserGroup.query() |
|
1175 | 1178 | if name_filter: |
|
1176 | 1179 | ilike_expression = u'%{}%'.format(safe_unicode(name_filter)) |
|
1177 | 1180 | qry = qry.filter( |
|
1178 | 1181 | UserGroup.users_group_name.ilike(ilike_expression)) |
|
1179 | 1182 | |
|
1180 | 1183 | return [x.users_group_id for x in |
|
1181 | 1184 | UserGroupList(qry, perm_set=perm_def)] |
|
1182 | 1185 | |
|
1183 | 1186 | compute = caches.conditional_cache( |
|
1184 | 1187 | 'long_term', 'user_group_acl_ids', |
|
1185 | 1188 | condition=cache, func=_cached_user_group_acl) |
|
1186 | 1189 | return compute(self.user_id, perms, name_filter) |
|
1187 | 1190 | |
|
1188 | 1191 | @property |
|
1189 | 1192 | def ip_allowed(self): |
|
1190 | 1193 | """ |
|
1191 | 1194 | Checks if ip_addr used in constructor is allowed from defined list of |
|
1192 | 1195 | allowed ip_addresses for user |
|
1193 | 1196 | |
|
1194 | 1197 | :returns: boolean, True if ip is in allowed ip range |
|
1195 | 1198 | """ |
|
1196 | 1199 | # check IP |
|
1197 | 1200 | inherit = self.inherit_default_permissions |
|
1198 | 1201 | return AuthUser.check_ip_allowed(self.user_id, self.ip_addr, |
|
1199 | 1202 | inherit_from_default=inherit) |
|
1200 | 1203 | @property |
|
1201 | 1204 | def personal_repo_group(self): |
|
1202 | 1205 | return RepoGroup.get_user_personal_repo_group(self.user_id) |
|
1203 | 1206 | |
|
1204 | 1207 | @classmethod |
|
1205 | 1208 | def check_ip_allowed(cls, user_id, ip_addr, inherit_from_default): |
|
1206 | 1209 | allowed_ips = AuthUser.get_allowed_ips( |
|
1207 | 1210 | user_id, cache=True, inherit_from_default=inherit_from_default) |
|
1208 | 1211 | if check_ip_access(source_ip=ip_addr, allowed_ips=allowed_ips): |
|
1209 | 1212 | log.debug('IP:%s is in range of %s' % (ip_addr, allowed_ips)) |
|
1210 | 1213 | return True |
|
1211 | 1214 | else: |
|
1212 | 1215 | log.info('Access for IP:%s forbidden, ' |
|
1213 | 1216 | 'not in %s' % (ip_addr, allowed_ips)) |
|
1214 | 1217 | return False |
|
1215 | 1218 | |
|
1216 | 1219 | def __repr__(self): |
|
1217 | 1220 | return "<AuthUser('id:%s[%s] ip:%s auth:%s')>"\ |
|
1218 | 1221 | % (self.user_id, self.username, self.ip_addr, self.is_authenticated) |
|
1219 | 1222 | |
|
1220 | 1223 | def set_authenticated(self, authenticated=True): |
|
1221 | 1224 | if self.user_id != self.anonymous_user.user_id: |
|
1222 | 1225 | self.is_authenticated = authenticated |
|
1223 | 1226 | |
|
1224 | 1227 | def get_cookie_store(self): |
|
1225 | 1228 | return { |
|
1226 | 1229 | 'username': self.username, |
|
1227 | 1230 | 'password': md5(self.password), |
|
1228 | 1231 | 'user_id': self.user_id, |
|
1229 | 1232 | 'is_authenticated': self.is_authenticated |
|
1230 | 1233 | } |
|
1231 | 1234 | |
|
1232 | 1235 | @classmethod |
|
1233 | 1236 | def from_cookie_store(cls, cookie_store): |
|
1234 | 1237 | """ |
|
1235 | 1238 | Creates AuthUser from a cookie store |
|
1236 | 1239 | |
|
1237 | 1240 | :param cls: |
|
1238 | 1241 | :param cookie_store: |
|
1239 | 1242 | """ |
|
1240 | 1243 | user_id = cookie_store.get('user_id') |
|
1241 | 1244 | username = cookie_store.get('username') |
|
1242 | 1245 | api_key = cookie_store.get('api_key') |
|
1243 | 1246 | return AuthUser(user_id, api_key, username) |
|
1244 | 1247 | |
|
1245 | 1248 | @classmethod |
|
1246 | 1249 | def get_allowed_ips(cls, user_id, cache=False, inherit_from_default=False): |
|
1247 | 1250 | _set = set() |
|
1248 | 1251 | |
|
1249 | 1252 | if inherit_from_default: |
|
1250 | 1253 | default_ips = UserIpMap.query().filter( |
|
1251 | 1254 | UserIpMap.user == User.get_default_user(cache=True)) |
|
1252 | 1255 | if cache: |
|
1253 | 1256 | default_ips = default_ips.options( |
|
1254 | 1257 | FromCache("sql_cache_short", "get_user_ips_default")) |
|
1255 | 1258 | |
|
1256 | 1259 | # populate from default user |
|
1257 | 1260 | for ip in default_ips: |
|
1258 | 1261 | try: |
|
1259 | 1262 | _set.add(ip.ip_addr) |
|
1260 | 1263 | except ObjectDeletedError: |
|
1261 | 1264 | # since we use heavy caching sometimes it happens that |
|
1262 | 1265 | # we get deleted objects here, we just skip them |
|
1263 | 1266 | pass |
|
1264 | 1267 | |
|
1265 | 1268 | user_ips = UserIpMap.query().filter(UserIpMap.user_id == user_id) |
|
1266 | 1269 | if cache: |
|
1267 | 1270 | user_ips = user_ips.options( |
|
1268 | 1271 | FromCache("sql_cache_short", "get_user_ips_%s" % user_id)) |
|
1269 | 1272 | |
|
1270 | 1273 | for ip in user_ips: |
|
1271 | 1274 | try: |
|
1272 | 1275 | _set.add(ip.ip_addr) |
|
1273 | 1276 | except ObjectDeletedError: |
|
1274 | 1277 | # since we use heavy caching sometimes it happens that we get |
|
1275 | 1278 | # deleted objects here, we just skip them |
|
1276 | 1279 | pass |
|
1277 | 1280 | return _set or set(['0.0.0.0/0', '::/0']) |
|
1278 | 1281 | |
|
1279 | 1282 | |
|
1280 |
def set_available_permissions( |
|
|
1283 | def set_available_permissions(settings): | |
|
1281 | 1284 | """ |
|
1282 |
This function will propagate py |
|
|
1285 | This function will propagate pyramid settings with all available defined | |
|
1283 | 1286 | permission given in db. We don't want to check each time from db for new |
|
1284 | 1287 | permissions since adding a new permission also requires application restart |
|
1285 | 1288 | ie. to decorate new views with the newly created permission |
|
1286 | 1289 | |
|
1287 | :param config: current pylons config instance | |
|
1290 | :param settings: current pyramid registry.settings | |
|
1288 | 1291 | |
|
1289 | 1292 | """ |
|
1290 |
log. |
|
|
1293 | log.debug('auth: getting information about all available permissions') | |
|
1291 | 1294 | try: |
|
1292 | 1295 | sa = meta.Session |
|
1293 | 1296 | all_perms = sa.query(Permission).all() |
|
1294 | config['available_permissions'] = [x.permission_name for x in all_perms] | |
|
1297 | settings.setdefault('available_permissions', | |
|
1298 | [x.permission_name for x in all_perms]) | |
|
1299 | log.debug('auth: set available permissions') | |
|
1295 | 1300 | except Exception: |
|
1296 | log.error(traceback.format_exc()) | |
|
1297 | finally: | |
|
1298 | meta.Session.remove() | |
|
1301 | log.exception('Failed to fetch permissions from the database.') | |
|
1302 | raise | |
|
1299 | 1303 | |
|
1300 | 1304 | |
|
1301 | 1305 | def get_csrf_token(session, force_new=False, save_if_missing=True): |
|
1302 | 1306 | """ |
|
1303 | 1307 | Return the current authentication token, creating one if one doesn't |
|
1304 | 1308 | already exist and the save_if_missing flag is present. |
|
1305 | 1309 | |
|
1306 | 1310 | :param session: pass in the pylons session, else we use the global ones |
|
1307 | 1311 | :param force_new: force to re-generate the token and store it in session |
|
1308 | 1312 | :param save_if_missing: save the newly generated token if it's missing in |
|
1309 | 1313 | session |
|
1310 | 1314 | """ |
|
1311 | 1315 | # NOTE(marcink): probably should be replaced with below one from pyramid 1.9 |
|
1312 | 1316 | # from pyramid.csrf import get_csrf_token |
|
1313 | 1317 | |
|
1314 | 1318 | if (csrf_token_key not in session and save_if_missing) or force_new: |
|
1315 | 1319 | token = hashlib.sha1(str(random.getrandbits(128))).hexdigest() |
|
1316 | 1320 | session[csrf_token_key] = token |
|
1317 | 1321 | if hasattr(session, 'save'): |
|
1318 | 1322 | session.save() |
|
1319 | 1323 | return session.get(csrf_token_key) |
|
1320 | 1324 | |
|
1321 | 1325 | |
|
1322 | 1326 | def get_request(perm_class_instance): |
|
1323 | 1327 | from pyramid.threadlocal import get_current_request |
|
1324 | 1328 | pyramid_request = get_current_request() |
|
1325 | 1329 | if not pyramid_request: |
|
1326 | 1330 | # return global request of pylons in case pyramid isn't available |
|
1327 | 1331 | # NOTE(marcink): this should be removed after migration to pyramid |
|
1328 | 1332 | from pylons import request |
|
1329 | 1333 | return request |
|
1330 | 1334 | return pyramid_request |
|
1331 | 1335 | |
|
1332 | 1336 | |
|
1333 | 1337 | # CHECK DECORATORS |
|
1334 | 1338 | class CSRFRequired(object): |
|
1335 | 1339 | """ |
|
1336 | 1340 | Decorator for authenticating a form |
|
1337 | 1341 | |
|
1338 | 1342 | This decorator uses an authorization token stored in the client's |
|
1339 | 1343 | session for prevention of certain Cross-site request forgery (CSRF) |
|
1340 | 1344 | attacks (See |
|
1341 | 1345 | http://en.wikipedia.org/wiki/Cross-site_request_forgery for more |
|
1342 | 1346 | information). |
|
1343 | 1347 | |
|
1344 | 1348 | For use with the ``webhelpers.secure_form`` helper functions. |
|
1345 | 1349 | |
|
1346 | 1350 | """ |
|
1347 | 1351 | def __init__(self, token=csrf_token_key, header='X-CSRF-Token', |
|
1348 | 1352 | except_methods=None): |
|
1349 | 1353 | self.token = token |
|
1350 | 1354 | self.header = header |
|
1351 | 1355 | self.except_methods = except_methods or [] |
|
1352 | 1356 | |
|
1353 | 1357 | def __call__(self, func): |
|
1354 | 1358 | return get_cython_compat_decorator(self.__wrapper, func) |
|
1355 | 1359 | |
|
1356 | 1360 | def _get_csrf(self, _request): |
|
1357 | 1361 | return _request.POST.get(self.token, _request.headers.get(self.header)) |
|
1358 | 1362 | |
|
1359 | 1363 | def check_csrf(self, _request, cur_token): |
|
1360 | 1364 | supplied_token = self._get_csrf(_request) |
|
1361 | 1365 | return supplied_token and supplied_token == cur_token |
|
1362 | 1366 | |
|
1363 | 1367 | def _get_request(self): |
|
1364 | 1368 | return get_request(self) |
|
1365 | 1369 | |
|
1366 | 1370 | def __wrapper(self, func, *fargs, **fkwargs): |
|
1367 | 1371 | request = self._get_request() |
|
1368 | 1372 | |
|
1369 | 1373 | if request.method in self.except_methods: |
|
1370 | 1374 | return func(*fargs, **fkwargs) |
|
1371 | 1375 | |
|
1372 | 1376 | cur_token = get_csrf_token(request.session, save_if_missing=False) |
|
1373 | 1377 | if self.check_csrf(request, cur_token): |
|
1374 | 1378 | if request.POST.get(self.token): |
|
1375 | 1379 | del request.POST[self.token] |
|
1376 | 1380 | return func(*fargs, **fkwargs) |
|
1377 | 1381 | else: |
|
1378 | 1382 | reason = 'token-missing' |
|
1379 | 1383 | supplied_token = self._get_csrf(request) |
|
1380 | 1384 | if supplied_token and cur_token != supplied_token: |
|
1381 | 1385 | reason = 'token-mismatch [%s:%s]' % ( |
|
1382 | 1386 | cur_token or ''[:6], supplied_token or ''[:6]) |
|
1383 | 1387 | |
|
1384 | 1388 | csrf_message = \ |
|
1385 | 1389 | ("Cross-site request forgery detected, request denied. See " |
|
1386 | 1390 | "http://en.wikipedia.org/wiki/Cross-site_request_forgery for " |
|
1387 | 1391 | "more information.") |
|
1388 | 1392 | log.warn('Cross-site request forgery detected, request %r DENIED: %s ' |
|
1389 | 1393 | 'REMOTE_ADDR:%s, HEADERS:%s' % ( |
|
1390 | 1394 | request, reason, request.remote_addr, request.headers)) |
|
1391 | 1395 | |
|
1392 | 1396 | raise HTTPForbidden(explanation=csrf_message) |
|
1393 | 1397 | |
|
1394 | 1398 | |
|
1395 | 1399 | class LoginRequired(object): |
|
1396 | 1400 | """ |
|
1397 | 1401 | Must be logged in to execute this function else |
|
1398 | 1402 | redirect to login page |
|
1399 | 1403 | |
|
1400 | 1404 | :param api_access: if enabled this checks only for valid auth token |
|
1401 | 1405 | and grants access based on valid token |
|
1402 | 1406 | """ |
|
1403 | 1407 | def __init__(self, auth_token_access=None): |
|
1404 | 1408 | self.auth_token_access = auth_token_access |
|
1405 | 1409 | |
|
1406 | 1410 | def __call__(self, func): |
|
1407 | 1411 | return get_cython_compat_decorator(self.__wrapper, func) |
|
1408 | 1412 | |
|
1409 | 1413 | def _get_request(self): |
|
1410 | 1414 | return get_request(self) |
|
1411 | 1415 | |
|
1412 | 1416 | def __wrapper(self, func, *fargs, **fkwargs): |
|
1413 | 1417 | from rhodecode.lib import helpers as h |
|
1414 | 1418 | cls = fargs[0] |
|
1415 | 1419 | user = cls._rhodecode_user |
|
1416 | 1420 | request = self._get_request() |
|
1417 | 1421 | |
|
1418 | 1422 | loc = "%s:%s" % (cls.__class__.__name__, func.__name__) |
|
1419 | 1423 | log.debug('Starting login restriction checks for user: %s' % (user,)) |
|
1420 | 1424 | # check if our IP is allowed |
|
1421 | 1425 | ip_access_valid = True |
|
1422 | 1426 | if not user.ip_allowed: |
|
1423 | 1427 | h.flash(h.literal(_('IP %s not allowed' % (user.ip_addr,))), |
|
1424 | 1428 | category='warning') |
|
1425 | 1429 | ip_access_valid = False |
|
1426 | 1430 | |
|
1427 | 1431 | # check if we used an APIKEY and it's a valid one |
|
1428 | 1432 | # defined white-list of controllers which API access will be enabled |
|
1429 | 1433 | _auth_token = request.GET.get( |
|
1430 | 1434 | 'auth_token', '') or request.GET.get('api_key', '') |
|
1431 | 1435 | auth_token_access_valid = allowed_auth_token_access( |
|
1432 | 1436 | loc, auth_token=_auth_token) |
|
1433 | 1437 | |
|
1434 | 1438 | # explicit controller is enabled or API is in our whitelist |
|
1435 | 1439 | if self.auth_token_access or auth_token_access_valid: |
|
1436 | 1440 | log.debug('Checking AUTH TOKEN access for %s' % (cls,)) |
|
1437 | 1441 | db_user = user.get_instance() |
|
1438 | 1442 | |
|
1439 | 1443 | if db_user: |
|
1440 | 1444 | if self.auth_token_access: |
|
1441 | 1445 | roles = self.auth_token_access |
|
1442 | 1446 | else: |
|
1443 | 1447 | roles = [UserApiKeys.ROLE_HTTP] |
|
1444 | 1448 | token_match = db_user.authenticate_by_token( |
|
1445 | 1449 | _auth_token, roles=roles) |
|
1446 | 1450 | else: |
|
1447 | 1451 | log.debug('Unable to fetch db instance for auth user: %s', user) |
|
1448 | 1452 | token_match = False |
|
1449 | 1453 | |
|
1450 | 1454 | if _auth_token and token_match: |
|
1451 | 1455 | auth_token_access_valid = True |
|
1452 | 1456 | log.debug('AUTH TOKEN ****%s is VALID' % (_auth_token[-4:],)) |
|
1453 | 1457 | else: |
|
1454 | 1458 | auth_token_access_valid = False |
|
1455 | 1459 | if not _auth_token: |
|
1456 | 1460 | log.debug("AUTH TOKEN *NOT* present in request") |
|
1457 | 1461 | else: |
|
1458 | 1462 | log.warning( |
|
1459 | 1463 | "AUTH TOKEN ****%s *NOT* valid" % _auth_token[-4:]) |
|
1460 | 1464 | |
|
1461 | 1465 | log.debug('Checking if %s is authenticated @ %s' % (user.username, loc)) |
|
1462 | 1466 | reason = 'RHODECODE_AUTH' if user.is_authenticated \ |
|
1463 | 1467 | else 'AUTH_TOKEN_AUTH' |
|
1464 | 1468 | |
|
1465 | 1469 | if ip_access_valid and ( |
|
1466 | 1470 | user.is_authenticated or auth_token_access_valid): |
|
1467 | 1471 | log.info( |
|
1468 | 1472 | 'user %s authenticating with:%s IS authenticated on func %s' |
|
1469 | 1473 | % (user, reason, loc)) |
|
1470 | 1474 | |
|
1471 | 1475 | # update user data to check last activity |
|
1472 | 1476 | user.update_lastactivity() |
|
1473 | 1477 | Session().commit() |
|
1474 | 1478 | return func(*fargs, **fkwargs) |
|
1475 | 1479 | else: |
|
1476 | 1480 | log.warning( |
|
1477 | 1481 | 'user %s authenticating with:%s NOT authenticated on ' |
|
1478 | 1482 | 'func: %s: IP_ACCESS:%s AUTH_TOKEN_ACCESS:%s' |
|
1479 | 1483 | % (user, reason, loc, ip_access_valid, |
|
1480 | 1484 | auth_token_access_valid)) |
|
1481 | 1485 | # we preserve the get PARAM |
|
1482 | 1486 | came_from = get_came_from(request) |
|
1483 | 1487 | |
|
1484 | 1488 | log.debug('redirecting to login page with %s' % (came_from,)) |
|
1485 | 1489 | raise HTTPFound( |
|
1486 | 1490 | h.route_path('login', _query={'came_from': came_from})) |
|
1487 | 1491 | |
|
1488 | 1492 | |
|
1489 | 1493 | class NotAnonymous(object): |
|
1490 | 1494 | """ |
|
1491 | 1495 | Must be logged in to execute this function else |
|
1492 | 1496 | redirect to login page |
|
1493 | 1497 | """ |
|
1494 | 1498 | |
|
1495 | 1499 | def __call__(self, func): |
|
1496 | 1500 | return get_cython_compat_decorator(self.__wrapper, func) |
|
1497 | 1501 | |
|
1498 | 1502 | def _get_request(self): |
|
1499 | 1503 | return get_request(self) |
|
1500 | 1504 | |
|
1501 | 1505 | def __wrapper(self, func, *fargs, **fkwargs): |
|
1502 | 1506 | import rhodecode.lib.helpers as h |
|
1503 | 1507 | cls = fargs[0] |
|
1504 | 1508 | self.user = cls._rhodecode_user |
|
1505 | 1509 | request = self._get_request() |
|
1506 | 1510 | |
|
1507 | 1511 | log.debug('Checking if user is not anonymous @%s' % cls) |
|
1508 | 1512 | |
|
1509 | 1513 | anonymous = self.user.username == User.DEFAULT_USER |
|
1510 | 1514 | |
|
1511 | 1515 | if anonymous: |
|
1512 | 1516 | came_from = get_came_from(request) |
|
1513 | 1517 | h.flash(_('You need to be a registered user to ' |
|
1514 | 1518 | 'perform this action'), |
|
1515 | 1519 | category='warning') |
|
1516 | 1520 | raise HTTPFound( |
|
1517 | 1521 | h.route_path('login', _query={'came_from': came_from})) |
|
1518 | 1522 | else: |
|
1519 | 1523 | return func(*fargs, **fkwargs) |
|
1520 | 1524 | |
|
1521 | 1525 | |
|
1522 | 1526 | class PermsDecorator(object): |
|
1523 | 1527 | """ |
|
1524 | 1528 | Base class for controller decorators, we extract the current user from |
|
1525 | 1529 | the class itself, which has it stored in base controllers |
|
1526 | 1530 | """ |
|
1527 | 1531 | |
|
1528 | 1532 | def __init__(self, *required_perms): |
|
1529 | 1533 | self.required_perms = set(required_perms) |
|
1530 | 1534 | |
|
1531 | 1535 | def __call__(self, func): |
|
1532 | 1536 | return get_cython_compat_decorator(self.__wrapper, func) |
|
1533 | 1537 | |
|
1534 | 1538 | def _get_request(self): |
|
1535 | 1539 | return get_request(self) |
|
1536 | 1540 | |
|
1537 | 1541 | def __wrapper(self, func, *fargs, **fkwargs): |
|
1538 | 1542 | import rhodecode.lib.helpers as h |
|
1539 | 1543 | cls = fargs[0] |
|
1540 | 1544 | _user = cls._rhodecode_user |
|
1541 | 1545 | |
|
1542 | 1546 | log.debug('checking %s permissions %s for %s %s', |
|
1543 | 1547 | self.__class__.__name__, self.required_perms, cls, _user) |
|
1544 | 1548 | |
|
1545 | 1549 | if self.check_permissions(_user): |
|
1546 | 1550 | log.debug('Permission granted for %s %s', cls, _user) |
|
1547 | 1551 | return func(*fargs, **fkwargs) |
|
1548 | 1552 | |
|
1549 | 1553 | else: |
|
1550 | 1554 | log.debug('Permission denied for %s %s', cls, _user) |
|
1551 | 1555 | anonymous = _user.username == User.DEFAULT_USER |
|
1552 | 1556 | |
|
1553 | 1557 | if anonymous: |
|
1554 | 1558 | came_from = get_came_from(self._get_request()) |
|
1555 | 1559 | h.flash(_('You need to be signed in to view this page'), |
|
1556 | 1560 | category='warning') |
|
1557 | 1561 | raise HTTPFound( |
|
1558 | 1562 | h.route_path('login', _query={'came_from': came_from})) |
|
1559 | 1563 | |
|
1560 | 1564 | else: |
|
1561 | 1565 | # redirect with 404 to prevent resource discovery |
|
1562 | 1566 | raise HTTPNotFound() |
|
1563 | 1567 | |
|
1564 | 1568 | def check_permissions(self, user): |
|
1565 | 1569 | """Dummy function for overriding""" |
|
1566 | 1570 | raise NotImplementedError( |
|
1567 | 1571 | 'You have to write this function in child class') |
|
1568 | 1572 | |
|
1569 | 1573 | |
|
1570 | 1574 | class HasPermissionAllDecorator(PermsDecorator): |
|
1571 | 1575 | """ |
|
1572 | 1576 | Checks for access permission for all given predicates. All of them |
|
1573 | 1577 | have to be meet in order to fulfill the request |
|
1574 | 1578 | """ |
|
1575 | 1579 | |
|
1576 | 1580 | def check_permissions(self, user): |
|
1577 | 1581 | perms = user.permissions_with_scope({}) |
|
1578 | 1582 | if self.required_perms.issubset(perms['global']): |
|
1579 | 1583 | return True |
|
1580 | 1584 | return False |
|
1581 | 1585 | |
|
1582 | 1586 | |
|
1583 | 1587 | class HasPermissionAnyDecorator(PermsDecorator): |
|
1584 | 1588 | """ |
|
1585 | 1589 | Checks for access permission for any of given predicates. In order to |
|
1586 | 1590 | fulfill the request any of predicates must be meet |
|
1587 | 1591 | """ |
|
1588 | 1592 | |
|
1589 | 1593 | def check_permissions(self, user): |
|
1590 | 1594 | perms = user.permissions_with_scope({}) |
|
1591 | 1595 | if self.required_perms.intersection(perms['global']): |
|
1592 | 1596 | return True |
|
1593 | 1597 | return False |
|
1594 | 1598 | |
|
1595 | 1599 | |
|
1596 | 1600 | class HasRepoPermissionAllDecorator(PermsDecorator): |
|
1597 | 1601 | """ |
|
1598 | 1602 | Checks for access permission for all given predicates for specific |
|
1599 | 1603 | repository. All of them have to be meet in order to fulfill the request |
|
1600 | 1604 | """ |
|
1601 | 1605 | def _get_repo_name(self): |
|
1602 | 1606 | _request = self._get_request() |
|
1603 | 1607 | return get_repo_slug(_request) |
|
1604 | 1608 | |
|
1605 | 1609 | def check_permissions(self, user): |
|
1606 | 1610 | perms = user.permissions |
|
1607 | 1611 | repo_name = self._get_repo_name() |
|
1608 | 1612 | |
|
1609 | 1613 | try: |
|
1610 | 1614 | user_perms = set([perms['repositories'][repo_name]]) |
|
1611 | 1615 | except KeyError: |
|
1612 | 1616 | log.debug('cannot locate repo with name: `%s` in permissions defs', |
|
1613 | 1617 | repo_name) |
|
1614 | 1618 | return False |
|
1615 | 1619 | |
|
1616 | 1620 | log.debug('checking `%s` permissions for repo `%s`', |
|
1617 | 1621 | user_perms, repo_name) |
|
1618 | 1622 | if self.required_perms.issubset(user_perms): |
|
1619 | 1623 | return True |
|
1620 | 1624 | return False |
|
1621 | 1625 | |
|
1622 | 1626 | |
|
1623 | 1627 | class HasRepoPermissionAnyDecorator(PermsDecorator): |
|
1624 | 1628 | """ |
|
1625 | 1629 | Checks for access permission for any of given predicates for specific |
|
1626 | 1630 | repository. In order to fulfill the request any of predicates must be meet |
|
1627 | 1631 | """ |
|
1628 | 1632 | def _get_repo_name(self): |
|
1629 | 1633 | _request = self._get_request() |
|
1630 | 1634 | return get_repo_slug(_request) |
|
1631 | 1635 | |
|
1632 | 1636 | def check_permissions(self, user): |
|
1633 | 1637 | perms = user.permissions |
|
1634 | 1638 | repo_name = self._get_repo_name() |
|
1635 | 1639 | |
|
1636 | 1640 | try: |
|
1637 | 1641 | user_perms = set([perms['repositories'][repo_name]]) |
|
1638 | 1642 | except KeyError: |
|
1639 | 1643 | log.debug( |
|
1640 | 1644 | 'cannot locate repo with name: `%s` in permissions defs', |
|
1641 | 1645 | repo_name) |
|
1642 | 1646 | return False |
|
1643 | 1647 | |
|
1644 | 1648 | log.debug('checking `%s` permissions for repo `%s`', |
|
1645 | 1649 | user_perms, repo_name) |
|
1646 | 1650 | if self.required_perms.intersection(user_perms): |
|
1647 | 1651 | return True |
|
1648 | 1652 | return False |
|
1649 | 1653 | |
|
1650 | 1654 | |
|
1651 | 1655 | class HasRepoGroupPermissionAllDecorator(PermsDecorator): |
|
1652 | 1656 | """ |
|
1653 | 1657 | Checks for access permission for all given predicates for specific |
|
1654 | 1658 | repository group. All of them have to be meet in order to |
|
1655 | 1659 | fulfill the request |
|
1656 | 1660 | """ |
|
1657 | 1661 | def _get_repo_group_name(self): |
|
1658 | 1662 | _request = self._get_request() |
|
1659 | 1663 | return get_repo_group_slug(_request) |
|
1660 | 1664 | |
|
1661 | 1665 | def check_permissions(self, user): |
|
1662 | 1666 | perms = user.permissions |
|
1663 | 1667 | group_name = self._get_repo_group_name() |
|
1664 | 1668 | try: |
|
1665 | 1669 | user_perms = set([perms['repositories_groups'][group_name]]) |
|
1666 | 1670 | except KeyError: |
|
1667 | 1671 | log.debug( |
|
1668 | 1672 | 'cannot locate repo group with name: `%s` in permissions defs', |
|
1669 | 1673 | group_name) |
|
1670 | 1674 | return False |
|
1671 | 1675 | |
|
1672 | 1676 | log.debug('checking `%s` permissions for repo group `%s`', |
|
1673 | 1677 | user_perms, group_name) |
|
1674 | 1678 | if self.required_perms.issubset(user_perms): |
|
1675 | 1679 | return True |
|
1676 | 1680 | return False |
|
1677 | 1681 | |
|
1678 | 1682 | |
|
1679 | 1683 | class HasRepoGroupPermissionAnyDecorator(PermsDecorator): |
|
1680 | 1684 | """ |
|
1681 | 1685 | Checks for access permission for any of given predicates for specific |
|
1682 | 1686 | repository group. In order to fulfill the request any |
|
1683 | 1687 | of predicates must be met |
|
1684 | 1688 | """ |
|
1685 | 1689 | def _get_repo_group_name(self): |
|
1686 | 1690 | _request = self._get_request() |
|
1687 | 1691 | return get_repo_group_slug(_request) |
|
1688 | 1692 | |
|
1689 | 1693 | def check_permissions(self, user): |
|
1690 | 1694 | perms = user.permissions |
|
1691 | 1695 | group_name = self._get_repo_group_name() |
|
1692 | 1696 | |
|
1693 | 1697 | try: |
|
1694 | 1698 | user_perms = set([perms['repositories_groups'][group_name]]) |
|
1695 | 1699 | except KeyError: |
|
1696 | 1700 | log.debug( |
|
1697 | 1701 | 'cannot locate repo group with name: `%s` in permissions defs', |
|
1698 | 1702 | group_name) |
|
1699 | 1703 | return False |
|
1700 | 1704 | |
|
1701 | 1705 | log.debug('checking `%s` permissions for repo group `%s`', |
|
1702 | 1706 | user_perms, group_name) |
|
1703 | 1707 | if self.required_perms.intersection(user_perms): |
|
1704 | 1708 | return True |
|
1705 | 1709 | return False |
|
1706 | 1710 | |
|
1707 | 1711 | |
|
1708 | 1712 | class HasUserGroupPermissionAllDecorator(PermsDecorator): |
|
1709 | 1713 | """ |
|
1710 | 1714 | Checks for access permission for all given predicates for specific |
|
1711 | 1715 | user group. All of them have to be meet in order to fulfill the request |
|
1712 | 1716 | """ |
|
1713 | 1717 | def _get_user_group_name(self): |
|
1714 | 1718 | _request = self._get_request() |
|
1715 | 1719 | return get_user_group_slug(_request) |
|
1716 | 1720 | |
|
1717 | 1721 | def check_permissions(self, user): |
|
1718 | 1722 | perms = user.permissions |
|
1719 | 1723 | group_name = self._get_user_group_name() |
|
1720 | 1724 | try: |
|
1721 | 1725 | user_perms = set([perms['user_groups'][group_name]]) |
|
1722 | 1726 | except KeyError: |
|
1723 | 1727 | return False |
|
1724 | 1728 | |
|
1725 | 1729 | if self.required_perms.issubset(user_perms): |
|
1726 | 1730 | return True |
|
1727 | 1731 | return False |
|
1728 | 1732 | |
|
1729 | 1733 | |
|
1730 | 1734 | class HasUserGroupPermissionAnyDecorator(PermsDecorator): |
|
1731 | 1735 | """ |
|
1732 | 1736 | Checks for access permission for any of given predicates for specific |
|
1733 | 1737 | user group. In order to fulfill the request any of predicates must be meet |
|
1734 | 1738 | """ |
|
1735 | 1739 | def _get_user_group_name(self): |
|
1736 | 1740 | _request = self._get_request() |
|
1737 | 1741 | return get_user_group_slug(_request) |
|
1738 | 1742 | |
|
1739 | 1743 | def check_permissions(self, user): |
|
1740 | 1744 | perms = user.permissions |
|
1741 | 1745 | group_name = self._get_user_group_name() |
|
1742 | 1746 | try: |
|
1743 | 1747 | user_perms = set([perms['user_groups'][group_name]]) |
|
1744 | 1748 | except KeyError: |
|
1745 | 1749 | return False |
|
1746 | 1750 | |
|
1747 | 1751 | if self.required_perms.intersection(user_perms): |
|
1748 | 1752 | return True |
|
1749 | 1753 | return False |
|
1750 | 1754 | |
|
1751 | 1755 | |
|
1752 | 1756 | # CHECK FUNCTIONS |
|
1753 | 1757 | class PermsFunction(object): |
|
1754 | 1758 | """Base function for other check functions""" |
|
1755 | 1759 | |
|
1756 | 1760 | def __init__(self, *perms): |
|
1757 | 1761 | self.required_perms = set(perms) |
|
1758 | 1762 | self.repo_name = None |
|
1759 | 1763 | self.repo_group_name = None |
|
1760 | 1764 | self.user_group_name = None |
|
1761 | 1765 | |
|
1762 | 1766 | def __bool__(self): |
|
1763 | 1767 | frame = inspect.currentframe() |
|
1764 | 1768 | stack_trace = traceback.format_stack(frame) |
|
1765 | 1769 | log.error('Checking bool value on a class instance of perm ' |
|
1766 | 1770 | 'function is not allowed: %s' % ''.join(stack_trace)) |
|
1767 | 1771 | # rather than throwing errors, here we always return False so if by |
|
1768 | 1772 | # accident someone checks truth for just an instance it will always end |
|
1769 | 1773 | # up in returning False |
|
1770 | 1774 | return False |
|
1771 | 1775 | __nonzero__ = __bool__ |
|
1772 | 1776 | |
|
1773 | 1777 | def __call__(self, check_location='', user=None): |
|
1774 | 1778 | if not user: |
|
1775 | 1779 | log.debug('Using user attribute from global request') |
|
1776 | 1780 | # TODO: remove this someday,put as user as attribute here |
|
1777 | 1781 | request = self._get_request() |
|
1778 | 1782 | user = request.user |
|
1779 | 1783 | |
|
1780 | 1784 | # init auth user if not already given |
|
1781 | 1785 | if not isinstance(user, AuthUser): |
|
1782 | 1786 | log.debug('Wrapping user %s into AuthUser', user) |
|
1783 | 1787 | user = AuthUser(user.user_id) |
|
1784 | 1788 | |
|
1785 | 1789 | cls_name = self.__class__.__name__ |
|
1786 | 1790 | check_scope = self._get_check_scope(cls_name) |
|
1787 | 1791 | check_location = check_location or 'unspecified location' |
|
1788 | 1792 | |
|
1789 | 1793 | log.debug('checking cls:%s %s usr:%s %s @ %s', cls_name, |
|
1790 | 1794 | self.required_perms, user, check_scope, check_location) |
|
1791 | 1795 | if not user: |
|
1792 | 1796 | log.warning('Empty user given for permission check') |
|
1793 | 1797 | return False |
|
1794 | 1798 | |
|
1795 | 1799 | if self.check_permissions(user): |
|
1796 | 1800 | log.debug('Permission to repo:`%s` GRANTED for user:`%s` @ %s', |
|
1797 | 1801 | check_scope, user, check_location) |
|
1798 | 1802 | return True |
|
1799 | 1803 | |
|
1800 | 1804 | else: |
|
1801 | 1805 | log.debug('Permission to repo:`%s` DENIED for user:`%s` @ %s', |
|
1802 | 1806 | check_scope, user, check_location) |
|
1803 | 1807 | return False |
|
1804 | 1808 | |
|
1805 | 1809 | def _get_request(self): |
|
1806 | 1810 | return get_request(self) |
|
1807 | 1811 | |
|
1808 | 1812 | def _get_check_scope(self, cls_name): |
|
1809 | 1813 | return { |
|
1810 | 1814 | 'HasPermissionAll': 'GLOBAL', |
|
1811 | 1815 | 'HasPermissionAny': 'GLOBAL', |
|
1812 | 1816 | 'HasRepoPermissionAll': 'repo:%s' % self.repo_name, |
|
1813 | 1817 | 'HasRepoPermissionAny': 'repo:%s' % self.repo_name, |
|
1814 | 1818 | 'HasRepoGroupPermissionAll': 'repo_group:%s' % self.repo_group_name, |
|
1815 | 1819 | 'HasRepoGroupPermissionAny': 'repo_group:%s' % self.repo_group_name, |
|
1816 | 1820 | 'HasUserGroupPermissionAll': 'user_group:%s' % self.user_group_name, |
|
1817 | 1821 | 'HasUserGroupPermissionAny': 'user_group:%s' % self.user_group_name, |
|
1818 | 1822 | }.get(cls_name, '?:%s' % cls_name) |
|
1819 | 1823 | |
|
1820 | 1824 | def check_permissions(self, user): |
|
1821 | 1825 | """Dummy function for overriding""" |
|
1822 | 1826 | raise Exception('You have to write this function in child class') |
|
1823 | 1827 | |
|
1824 | 1828 | |
|
1825 | 1829 | class HasPermissionAll(PermsFunction): |
|
1826 | 1830 | def check_permissions(self, user): |
|
1827 | 1831 | perms = user.permissions_with_scope({}) |
|
1828 | 1832 | if self.required_perms.issubset(perms.get('global')): |
|
1829 | 1833 | return True |
|
1830 | 1834 | return False |
|
1831 | 1835 | |
|
1832 | 1836 | |
|
1833 | 1837 | class HasPermissionAny(PermsFunction): |
|
1834 | 1838 | def check_permissions(self, user): |
|
1835 | 1839 | perms = user.permissions_with_scope({}) |
|
1836 | 1840 | if self.required_perms.intersection(perms.get('global')): |
|
1837 | 1841 | return True |
|
1838 | 1842 | return False |
|
1839 | 1843 | |
|
1840 | 1844 | |
|
1841 | 1845 | class HasRepoPermissionAll(PermsFunction): |
|
1842 | 1846 | def __call__(self, repo_name=None, check_location='', user=None): |
|
1843 | 1847 | self.repo_name = repo_name |
|
1844 | 1848 | return super(HasRepoPermissionAll, self).__call__(check_location, user) |
|
1845 | 1849 | |
|
1846 | 1850 | def _get_repo_name(self): |
|
1847 | 1851 | if not self.repo_name: |
|
1848 | 1852 | _request = self._get_request() |
|
1849 | 1853 | self.repo_name = get_repo_slug(_request) |
|
1850 | 1854 | return self.repo_name |
|
1851 | 1855 | |
|
1852 | 1856 | def check_permissions(self, user): |
|
1853 | 1857 | self.repo_name = self._get_repo_name() |
|
1854 | 1858 | perms = user.permissions |
|
1855 | 1859 | try: |
|
1856 | 1860 | user_perms = set([perms['repositories'][self.repo_name]]) |
|
1857 | 1861 | except KeyError: |
|
1858 | 1862 | return False |
|
1859 | 1863 | if self.required_perms.issubset(user_perms): |
|
1860 | 1864 | return True |
|
1861 | 1865 | return False |
|
1862 | 1866 | |
|
1863 | 1867 | |
|
1864 | 1868 | class HasRepoPermissionAny(PermsFunction): |
|
1865 | 1869 | def __call__(self, repo_name=None, check_location='', user=None): |
|
1866 | 1870 | self.repo_name = repo_name |
|
1867 | 1871 | return super(HasRepoPermissionAny, self).__call__(check_location, user) |
|
1868 | 1872 | |
|
1869 | 1873 | def _get_repo_name(self): |
|
1870 | 1874 | if not self.repo_name: |
|
1871 | 1875 | _request = self._get_request() |
|
1872 | 1876 | self.repo_name = get_repo_slug(_request) |
|
1873 | 1877 | return self.repo_name |
|
1874 | 1878 | |
|
1875 | 1879 | def check_permissions(self, user): |
|
1876 | 1880 | self.repo_name = self._get_repo_name() |
|
1877 | 1881 | perms = user.permissions |
|
1878 | 1882 | try: |
|
1879 | 1883 | user_perms = set([perms['repositories'][self.repo_name]]) |
|
1880 | 1884 | except KeyError: |
|
1881 | 1885 | return False |
|
1882 | 1886 | if self.required_perms.intersection(user_perms): |
|
1883 | 1887 | return True |
|
1884 | 1888 | return False |
|
1885 | 1889 | |
|
1886 | 1890 | |
|
1887 | 1891 | class HasRepoGroupPermissionAny(PermsFunction): |
|
1888 | 1892 | def __call__(self, group_name=None, check_location='', user=None): |
|
1889 | 1893 | self.repo_group_name = group_name |
|
1890 | 1894 | return super(HasRepoGroupPermissionAny, self).__call__( |
|
1891 | 1895 | check_location, user) |
|
1892 | 1896 | |
|
1893 | 1897 | def check_permissions(self, user): |
|
1894 | 1898 | perms = user.permissions |
|
1895 | 1899 | try: |
|
1896 | 1900 | user_perms = set( |
|
1897 | 1901 | [perms['repositories_groups'][self.repo_group_name]]) |
|
1898 | 1902 | except KeyError: |
|
1899 | 1903 | return False |
|
1900 | 1904 | if self.required_perms.intersection(user_perms): |
|
1901 | 1905 | return True |
|
1902 | 1906 | return False |
|
1903 | 1907 | |
|
1904 | 1908 | |
|
1905 | 1909 | class HasRepoGroupPermissionAll(PermsFunction): |
|
1906 | 1910 | def __call__(self, group_name=None, check_location='', user=None): |
|
1907 | 1911 | self.repo_group_name = group_name |
|
1908 | 1912 | return super(HasRepoGroupPermissionAll, self).__call__( |
|
1909 | 1913 | check_location, user) |
|
1910 | 1914 | |
|
1911 | 1915 | def check_permissions(self, user): |
|
1912 | 1916 | perms = user.permissions |
|
1913 | 1917 | try: |
|
1914 | 1918 | user_perms = set( |
|
1915 | 1919 | [perms['repositories_groups'][self.repo_group_name]]) |
|
1916 | 1920 | except KeyError: |
|
1917 | 1921 | return False |
|
1918 | 1922 | if self.required_perms.issubset(user_perms): |
|
1919 | 1923 | return True |
|
1920 | 1924 | return False |
|
1921 | 1925 | |
|
1922 | 1926 | |
|
1923 | 1927 | class HasUserGroupPermissionAny(PermsFunction): |
|
1924 | 1928 | def __call__(self, user_group_name=None, check_location='', user=None): |
|
1925 | 1929 | self.user_group_name = user_group_name |
|
1926 | 1930 | return super(HasUserGroupPermissionAny, self).__call__( |
|
1927 | 1931 | check_location, user) |
|
1928 | 1932 | |
|
1929 | 1933 | def check_permissions(self, user): |
|
1930 | 1934 | perms = user.permissions |
|
1931 | 1935 | try: |
|
1932 | 1936 | user_perms = set([perms['user_groups'][self.user_group_name]]) |
|
1933 | 1937 | except KeyError: |
|
1934 | 1938 | return False |
|
1935 | 1939 | if self.required_perms.intersection(user_perms): |
|
1936 | 1940 | return True |
|
1937 | 1941 | return False |
|
1938 | 1942 | |
|
1939 | 1943 | |
|
1940 | 1944 | class HasUserGroupPermissionAll(PermsFunction): |
|
1941 | 1945 | def __call__(self, user_group_name=None, check_location='', user=None): |
|
1942 | 1946 | self.user_group_name = user_group_name |
|
1943 | 1947 | return super(HasUserGroupPermissionAll, self).__call__( |
|
1944 | 1948 | check_location, user) |
|
1945 | 1949 | |
|
1946 | 1950 | def check_permissions(self, user): |
|
1947 | 1951 | perms = user.permissions |
|
1948 | 1952 | try: |
|
1949 | 1953 | user_perms = set([perms['user_groups'][self.user_group_name]]) |
|
1950 | 1954 | except KeyError: |
|
1951 | 1955 | return False |
|
1952 | 1956 | if self.required_perms.issubset(user_perms): |
|
1953 | 1957 | return True |
|
1954 | 1958 | return False |
|
1955 | 1959 | |
|
1956 | 1960 | |
|
1957 | 1961 | # SPECIAL VERSION TO HANDLE MIDDLEWARE AUTH |
|
1958 | 1962 | class HasPermissionAnyMiddleware(object): |
|
1959 | 1963 | def __init__(self, *perms): |
|
1960 | 1964 | self.required_perms = set(perms) |
|
1961 | 1965 | |
|
1962 | 1966 | def __call__(self, user, repo_name): |
|
1963 | 1967 | # repo_name MUST be unicode, since we handle keys in permission |
|
1964 | 1968 | # dict by unicode |
|
1965 | 1969 | repo_name = safe_unicode(repo_name) |
|
1966 | 1970 | user = AuthUser(user.user_id) |
|
1967 | 1971 | log.debug( |
|
1968 | 1972 | 'Checking VCS protocol permissions %s for user:%s repo:`%s`', |
|
1969 | 1973 | self.required_perms, user, repo_name) |
|
1970 | 1974 | |
|
1971 | 1975 | if self.check_permissions(user, repo_name): |
|
1972 | 1976 | log.debug('Permission to repo:`%s` GRANTED for user:%s @ %s', |
|
1973 | 1977 | repo_name, user, 'PermissionMiddleware') |
|
1974 | 1978 | return True |
|
1975 | 1979 | |
|
1976 | 1980 | else: |
|
1977 | 1981 | log.debug('Permission to repo:`%s` DENIED for user:%s @ %s', |
|
1978 | 1982 | repo_name, user, 'PermissionMiddleware') |
|
1979 | 1983 | return False |
|
1980 | 1984 | |
|
1981 | 1985 | def check_permissions(self, user, repo_name): |
|
1982 | 1986 | perms = user.permissions_with_scope({'repo_name': repo_name}) |
|
1983 | 1987 | |
|
1984 | 1988 | try: |
|
1985 | 1989 | user_perms = set([perms['repositories'][repo_name]]) |
|
1986 | 1990 | except Exception: |
|
1987 | 1991 | log.exception('Error while accessing user permissions') |
|
1988 | 1992 | return False |
|
1989 | 1993 | |
|
1990 | 1994 | if self.required_perms.intersection(user_perms): |
|
1991 | 1995 | return True |
|
1992 | 1996 | return False |
|
1993 | 1997 | |
|
1994 | 1998 | |
|
1995 | 1999 | # SPECIAL VERSION TO HANDLE API AUTH |
|
1996 | 2000 | class _BaseApiPerm(object): |
|
1997 | 2001 | def __init__(self, *perms): |
|
1998 | 2002 | self.required_perms = set(perms) |
|
1999 | 2003 | |
|
2000 | 2004 | def __call__(self, check_location=None, user=None, repo_name=None, |
|
2001 | 2005 | group_name=None, user_group_name=None): |
|
2002 | 2006 | cls_name = self.__class__.__name__ |
|
2003 | 2007 | check_scope = 'global:%s' % (self.required_perms,) |
|
2004 | 2008 | if repo_name: |
|
2005 | 2009 | check_scope += ', repo_name:%s' % (repo_name,) |
|
2006 | 2010 | |
|
2007 | 2011 | if group_name: |
|
2008 | 2012 | check_scope += ', repo_group_name:%s' % (group_name,) |
|
2009 | 2013 | |
|
2010 | 2014 | if user_group_name: |
|
2011 | 2015 | check_scope += ', user_group_name:%s' % (user_group_name,) |
|
2012 | 2016 | |
|
2013 | 2017 | log.debug( |
|
2014 | 2018 | 'checking cls:%s %s %s @ %s' |
|
2015 | 2019 | % (cls_name, self.required_perms, check_scope, check_location)) |
|
2016 | 2020 | if not user: |
|
2017 | 2021 | log.debug('Empty User passed into arguments') |
|
2018 | 2022 | return False |
|
2019 | 2023 | |
|
2020 | 2024 | # process user |
|
2021 | 2025 | if not isinstance(user, AuthUser): |
|
2022 | 2026 | user = AuthUser(user.user_id) |
|
2023 | 2027 | if not check_location: |
|
2024 | 2028 | check_location = 'unspecified' |
|
2025 | 2029 | if self.check_permissions(user.permissions, repo_name, group_name, |
|
2026 | 2030 | user_group_name): |
|
2027 | 2031 | log.debug('Permission to repo:`%s` GRANTED for user:`%s` @ %s', |
|
2028 | 2032 | check_scope, user, check_location) |
|
2029 | 2033 | return True |
|
2030 | 2034 | |
|
2031 | 2035 | else: |
|
2032 | 2036 | log.debug('Permission to repo:`%s` DENIED for user:`%s` @ %s', |
|
2033 | 2037 | check_scope, user, check_location) |
|
2034 | 2038 | return False |
|
2035 | 2039 | |
|
2036 | 2040 | def check_permissions(self, perm_defs, repo_name=None, group_name=None, |
|
2037 | 2041 | user_group_name=None): |
|
2038 | 2042 | """ |
|
2039 | 2043 | implement in child class should return True if permissions are ok, |
|
2040 | 2044 | False otherwise |
|
2041 | 2045 | |
|
2042 | 2046 | :param perm_defs: dict with permission definitions |
|
2043 | 2047 | :param repo_name: repo name |
|
2044 | 2048 | """ |
|
2045 | 2049 | raise NotImplementedError() |
|
2046 | 2050 | |
|
2047 | 2051 | |
|
2048 | 2052 | class HasPermissionAllApi(_BaseApiPerm): |
|
2049 | 2053 | def check_permissions(self, perm_defs, repo_name=None, group_name=None, |
|
2050 | 2054 | user_group_name=None): |
|
2051 | 2055 | if self.required_perms.issubset(perm_defs.get('global')): |
|
2052 | 2056 | return True |
|
2053 | 2057 | return False |
|
2054 | 2058 | |
|
2055 | 2059 | |
|
2056 | 2060 | class HasPermissionAnyApi(_BaseApiPerm): |
|
2057 | 2061 | def check_permissions(self, perm_defs, repo_name=None, group_name=None, |
|
2058 | 2062 | user_group_name=None): |
|
2059 | 2063 | if self.required_perms.intersection(perm_defs.get('global')): |
|
2060 | 2064 | return True |
|
2061 | 2065 | return False |
|
2062 | 2066 | |
|
2063 | 2067 | |
|
2064 | 2068 | class HasRepoPermissionAllApi(_BaseApiPerm): |
|
2065 | 2069 | def check_permissions(self, perm_defs, repo_name=None, group_name=None, |
|
2066 | 2070 | user_group_name=None): |
|
2067 | 2071 | try: |
|
2068 | 2072 | _user_perms = set([perm_defs['repositories'][repo_name]]) |
|
2069 | 2073 | except KeyError: |
|
2070 | 2074 | log.warning(traceback.format_exc()) |
|
2071 | 2075 | return False |
|
2072 | 2076 | if self.required_perms.issubset(_user_perms): |
|
2073 | 2077 | return True |
|
2074 | 2078 | return False |
|
2075 | 2079 | |
|
2076 | 2080 | |
|
2077 | 2081 | class HasRepoPermissionAnyApi(_BaseApiPerm): |
|
2078 | 2082 | def check_permissions(self, perm_defs, repo_name=None, group_name=None, |
|
2079 | 2083 | user_group_name=None): |
|
2080 | 2084 | try: |
|
2081 | 2085 | _user_perms = set([perm_defs['repositories'][repo_name]]) |
|
2082 | 2086 | except KeyError: |
|
2083 | 2087 | log.warning(traceback.format_exc()) |
|
2084 | 2088 | return False |
|
2085 | 2089 | if self.required_perms.intersection(_user_perms): |
|
2086 | 2090 | return True |
|
2087 | 2091 | return False |
|
2088 | 2092 | |
|
2089 | 2093 | |
|
2090 | 2094 | class HasRepoGroupPermissionAnyApi(_BaseApiPerm): |
|
2091 | 2095 | def check_permissions(self, perm_defs, repo_name=None, group_name=None, |
|
2092 | 2096 | user_group_name=None): |
|
2093 | 2097 | try: |
|
2094 | 2098 | _user_perms = set([perm_defs['repositories_groups'][group_name]]) |
|
2095 | 2099 | except KeyError: |
|
2096 | 2100 | log.warning(traceback.format_exc()) |
|
2097 | 2101 | return False |
|
2098 | 2102 | if self.required_perms.intersection(_user_perms): |
|
2099 | 2103 | return True |
|
2100 | 2104 | return False |
|
2101 | 2105 | |
|
2102 | 2106 | |
|
2103 | 2107 | class HasRepoGroupPermissionAllApi(_BaseApiPerm): |
|
2104 | 2108 | def check_permissions(self, perm_defs, repo_name=None, group_name=None, |
|
2105 | 2109 | user_group_name=None): |
|
2106 | 2110 | try: |
|
2107 | 2111 | _user_perms = set([perm_defs['repositories_groups'][group_name]]) |
|
2108 | 2112 | except KeyError: |
|
2109 | 2113 | log.warning(traceback.format_exc()) |
|
2110 | 2114 | return False |
|
2111 | 2115 | if self.required_perms.issubset(_user_perms): |
|
2112 | 2116 | return True |
|
2113 | 2117 | return False |
|
2114 | 2118 | |
|
2115 | 2119 | |
|
2116 | 2120 | class HasUserGroupPermissionAnyApi(_BaseApiPerm): |
|
2117 | 2121 | def check_permissions(self, perm_defs, repo_name=None, group_name=None, |
|
2118 | 2122 | user_group_name=None): |
|
2119 | 2123 | try: |
|
2120 | 2124 | _user_perms = set([perm_defs['user_groups'][user_group_name]]) |
|
2121 | 2125 | except KeyError: |
|
2122 | 2126 | log.warning(traceback.format_exc()) |
|
2123 | 2127 | return False |
|
2124 | 2128 | if self.required_perms.intersection(_user_perms): |
|
2125 | 2129 | return True |
|
2126 | 2130 | return False |
|
2127 | 2131 | |
|
2128 | 2132 | |
|
2129 | 2133 | def check_ip_access(source_ip, allowed_ips=None): |
|
2130 | 2134 | """ |
|
2131 | 2135 | Checks if source_ip is a subnet of any of allowed_ips. |
|
2132 | 2136 | |
|
2133 | 2137 | :param source_ip: |
|
2134 | 2138 | :param allowed_ips: list of allowed ips together with mask |
|
2135 | 2139 | """ |
|
2136 | 2140 | log.debug('checking if ip:%s is subnet of %s' % (source_ip, allowed_ips)) |
|
2137 | 2141 | source_ip_address = ipaddress.ip_address(safe_unicode(source_ip)) |
|
2138 | 2142 | if isinstance(allowed_ips, (tuple, list, set)): |
|
2139 | 2143 | for ip in allowed_ips: |
|
2140 | 2144 | ip = safe_unicode(ip) |
|
2141 | 2145 | try: |
|
2142 | 2146 | network_address = ipaddress.ip_network(ip, strict=False) |
|
2143 | 2147 | if source_ip_address in network_address: |
|
2144 | 2148 | log.debug('IP %s is network %s' % |
|
2145 | 2149 | (source_ip_address, network_address)) |
|
2146 | 2150 | return True |
|
2147 | 2151 | # for any case we cannot determine the IP, don't crash just |
|
2148 | 2152 | # skip it and log as error, we want to say forbidden still when |
|
2149 | 2153 | # sending bad IP |
|
2150 | 2154 | except Exception: |
|
2151 | 2155 | log.error(traceback.format_exc()) |
|
2152 | 2156 | continue |
|
2153 | 2157 | return False |
|
2154 | 2158 | |
|
2155 | 2159 | |
|
2156 | 2160 | def get_cython_compat_decorator(wrapper, func): |
|
2157 | 2161 | """ |
|
2158 | 2162 | Creates a cython compatible decorator. The previously used |
|
2159 | 2163 | decorator.decorator() function seems to be incompatible with cython. |
|
2160 | 2164 | |
|
2161 | 2165 | :param wrapper: __wrapper method of the decorator class |
|
2162 | 2166 | :param func: decorated function |
|
2163 | 2167 | """ |
|
2164 | 2168 | @wraps(func) |
|
2165 | 2169 | def local_wrapper(*args, **kwds): |
|
2166 | 2170 | return wrapper(func, *args, **kwds) |
|
2167 | 2171 | local_wrapper.__wrapped__ = func |
|
2168 | 2172 | return local_wrapper |
|
2169 | 2173 | |
|
2170 | 2174 |
@@ -1,4213 +1,4227 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | |
|
3 | 3 | # Copyright (C) 2010-2017 RhodeCode GmbH |
|
4 | 4 | # |
|
5 | 5 | # This program is free software: you can redistribute it and/or modify |
|
6 | 6 | # it under the terms of the GNU Affero General Public License, version 3 |
|
7 | 7 | # (only), as published by the Free Software Foundation. |
|
8 | 8 | # |
|
9 | 9 | # This program is distributed in the hope that it will be useful, |
|
10 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of |
|
11 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|
12 | 12 | # GNU General Public License for more details. |
|
13 | 13 | # |
|
14 | 14 | # You should have received a copy of the GNU Affero General Public License |
|
15 | 15 | # along with this program. If not, see <http://www.gnu.org/licenses/>. |
|
16 | 16 | # |
|
17 | 17 | # This program is dual-licensed. If you wish to learn more about the |
|
18 | 18 | # RhodeCode Enterprise Edition, including its added features, Support services, |
|
19 | 19 | # and proprietary license terms, please see https://rhodecode.com/licenses/ |
|
20 | 20 | |
|
21 | 21 | """ |
|
22 | 22 | Database Models for RhodeCode Enterprise |
|
23 | 23 | """ |
|
24 | 24 | |
|
25 | 25 | import re |
|
26 | 26 | import os |
|
27 | 27 | import time |
|
28 | 28 | import hashlib |
|
29 | 29 | import logging |
|
30 | 30 | import datetime |
|
31 | 31 | import warnings |
|
32 | 32 | import ipaddress |
|
33 | 33 | import functools |
|
34 | 34 | import traceback |
|
35 | 35 | import collections |
|
36 | 36 | |
|
37 | 37 | |
|
38 | 38 | from sqlalchemy import * |
|
39 | 39 | from sqlalchemy.ext.declarative import declared_attr |
|
40 | 40 | from sqlalchemy.ext.hybrid import hybrid_property |
|
41 | 41 | from sqlalchemy.orm import ( |
|
42 | 42 | relationship, joinedload, class_mapper, validates, aliased) |
|
43 | 43 | from sqlalchemy.sql.expression import true |
|
44 | 44 | from sqlalchemy.sql.functions import coalesce, count # noqa |
|
45 | 45 | from sqlalchemy.exc import IntegrityError # noqa |
|
46 | 46 | from sqlalchemy.dialects.mysql import LONGTEXT |
|
47 | 47 | from beaker.cache import cache_region |
|
48 | 48 | from zope.cachedescriptors.property import Lazy as LazyProperty |
|
49 | 49 | |
|
50 | 50 | from pyramid.threadlocal import get_current_request |
|
51 | 51 | |
|
52 | 52 | from rhodecode.translation import _ |
|
53 | 53 | from rhodecode.lib.vcs import get_vcs_instance |
|
54 | 54 | from rhodecode.lib.vcs.backends.base import EmptyCommit, Reference |
|
55 | 55 | from rhodecode.lib.utils2 import ( |
|
56 | 56 | str2bool, safe_str, get_commit_safe, safe_unicode, md5_safe, |
|
57 | 57 | time_to_datetime, aslist, Optional, safe_int, get_clone_url, AttributeDict, |
|
58 | 58 | glob2re, StrictAttributeDict, cleaned_uri) |
|
59 | 59 | from rhodecode.lib.jsonalchemy import MutationObj, MutationList, JsonType |
|
60 | 60 | from rhodecode.lib.ext_json import json |
|
61 | 61 | from rhodecode.lib.caching_query import FromCache |
|
62 | 62 | from rhodecode.lib.encrypt import AESCipher |
|
63 | 63 | |
|
64 | 64 | from rhodecode.model.meta import Base, Session |
|
65 | 65 | |
|
66 | 66 | URL_SEP = '/' |
|
67 | 67 | log = logging.getLogger(__name__) |
|
68 | 68 | |
|
69 | 69 | # ============================================================================= |
|
70 | 70 | # BASE CLASSES |
|
71 | 71 | # ============================================================================= |
|
72 | 72 | |
|
73 | 73 | # this is propagated from .ini file rhodecode.encrypted_values.secret or |
|
74 | 74 | # beaker.session.secret if first is not set. |
|
75 | 75 | # and initialized at environment.py |
|
76 | 76 | ENCRYPTION_KEY = None |
|
77 | 77 | |
|
78 | 78 | # used to sort permissions by types, '#' used here is not allowed to be in |
|
79 | 79 | # usernames, and it's very early in sorted string.printable table. |
|
80 | 80 | PERMISSION_TYPE_SORT = { |
|
81 | 81 | 'admin': '####', |
|
82 | 82 | 'write': '###', |
|
83 | 83 | 'read': '##', |
|
84 | 84 | 'none': '#', |
|
85 | 85 | } |
|
86 | 86 | |
|
87 | 87 | |
|
88 | 88 | def display_user_sort(obj): |
|
89 | 89 | """ |
|
90 | 90 | Sort function used to sort permissions in .permissions() function of |
|
91 | 91 | Repository, RepoGroup, UserGroup. Also it put the default user in front |
|
92 | 92 | of all other resources |
|
93 | 93 | """ |
|
94 | 94 | |
|
95 | 95 | if obj.username == User.DEFAULT_USER: |
|
96 | 96 | return '#####' |
|
97 | 97 | prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '') |
|
98 | 98 | return prefix + obj.username |
|
99 | 99 | |
|
100 | 100 | |
|
101 | 101 | def display_user_group_sort(obj): |
|
102 | 102 | """ |
|
103 | 103 | Sort function used to sort permissions in .permissions() function of |
|
104 | 104 | Repository, RepoGroup, UserGroup. Also it put the default user in front |
|
105 | 105 | of all other resources |
|
106 | 106 | """ |
|
107 | 107 | |
|
108 | 108 | prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '') |
|
109 | 109 | return prefix + obj.users_group_name |
|
110 | 110 | |
|
111 | 111 | |
|
112 | 112 | def _hash_key(k): |
|
113 | 113 | return md5_safe(k) |
|
114 | 114 | |
|
115 | 115 | |
|
116 | 116 | def in_filter_generator(qry, items, limit=500): |
|
117 | 117 | """ |
|
118 | 118 | Splits IN() into multiple with OR |
|
119 | 119 | e.g.:: |
|
120 | 120 | cnt = Repository.query().filter( |
|
121 | 121 | or_( |
|
122 | 122 | *in_filter_generator(Repository.repo_id, range(100000)) |
|
123 | 123 | )).count() |
|
124 | 124 | """ |
|
125 | 125 | parts = [] |
|
126 | 126 | for chunk in xrange(0, len(items), limit): |
|
127 | 127 | parts.append( |
|
128 | 128 | qry.in_(items[chunk: chunk + limit]) |
|
129 | 129 | ) |
|
130 | 130 | |
|
131 | 131 | return parts |
|
132 | 132 | |
|
133 | 133 | |
|
134 | 134 | class EncryptedTextValue(TypeDecorator): |
|
135 | 135 | """ |
|
136 | 136 | Special column for encrypted long text data, use like:: |
|
137 | 137 | |
|
138 | 138 | value = Column("encrypted_value", EncryptedValue(), nullable=False) |
|
139 | 139 | |
|
140 | 140 | This column is intelligent so if value is in unencrypted form it return |
|
141 | 141 | unencrypted form, but on save it always encrypts |
|
142 | 142 | """ |
|
143 | 143 | impl = Text |
|
144 | 144 | |
|
145 | 145 | def process_bind_param(self, value, dialect): |
|
146 | 146 | if not value: |
|
147 | 147 | return value |
|
148 | 148 | if value.startswith('enc$aes$') or value.startswith('enc$aes_hmac$'): |
|
149 | 149 | # protect against double encrypting if someone manually starts |
|
150 | 150 | # doing |
|
151 | 151 | raise ValueError('value needs to be in unencrypted format, ie. ' |
|
152 | 152 | 'not starting with enc$aes') |
|
153 | 153 | return 'enc$aes_hmac$%s' % AESCipher( |
|
154 | 154 | ENCRYPTION_KEY, hmac=True).encrypt(value) |
|
155 | 155 | |
|
156 | 156 | def process_result_value(self, value, dialect): |
|
157 | 157 | import rhodecode |
|
158 | 158 | |
|
159 | 159 | if not value: |
|
160 | 160 | return value |
|
161 | 161 | |
|
162 | 162 | parts = value.split('$', 3) |
|
163 | 163 | if not len(parts) == 3: |
|
164 | 164 | # probably not encrypted values |
|
165 | 165 | return value |
|
166 | 166 | else: |
|
167 | 167 | if parts[0] != 'enc': |
|
168 | 168 | # parts ok but without our header ? |
|
169 | 169 | return value |
|
170 | 170 | enc_strict_mode = str2bool(rhodecode.CONFIG.get( |
|
171 | 171 | 'rhodecode.encrypted_values.strict') or True) |
|
172 | 172 | # at that stage we know it's our encryption |
|
173 | 173 | if parts[1] == 'aes': |
|
174 | 174 | decrypted_data = AESCipher(ENCRYPTION_KEY).decrypt(parts[2]) |
|
175 | 175 | elif parts[1] == 'aes_hmac': |
|
176 | 176 | decrypted_data = AESCipher( |
|
177 | 177 | ENCRYPTION_KEY, hmac=True, |
|
178 | 178 | strict_verification=enc_strict_mode).decrypt(parts[2]) |
|
179 | 179 | else: |
|
180 | 180 | raise ValueError( |
|
181 | 181 | 'Encryption type part is wrong, must be `aes` ' |
|
182 | 182 | 'or `aes_hmac`, got `%s` instead' % (parts[1])) |
|
183 | 183 | return decrypted_data |
|
184 | 184 | |
|
185 | 185 | |
|
186 | 186 | class BaseModel(object): |
|
187 | 187 | """ |
|
188 | 188 | Base Model for all classes |
|
189 | 189 | """ |
|
190 | 190 | |
|
191 | 191 | @classmethod |
|
192 | 192 | def _get_keys(cls): |
|
193 | 193 | """return column names for this model """ |
|
194 | 194 | return class_mapper(cls).c.keys() |
|
195 | 195 | |
|
196 | 196 | def get_dict(self): |
|
197 | 197 | """ |
|
198 | 198 | return dict with keys and values corresponding |
|
199 | 199 | to this model data """ |
|
200 | 200 | |
|
201 | 201 | d = {} |
|
202 | 202 | for k in self._get_keys(): |
|
203 | 203 | d[k] = getattr(self, k) |
|
204 | 204 | |
|
205 | 205 | # also use __json__() if present to get additional fields |
|
206 | 206 | _json_attr = getattr(self, '__json__', None) |
|
207 | 207 | if _json_attr: |
|
208 | 208 | # update with attributes from __json__ |
|
209 | 209 | if callable(_json_attr): |
|
210 | 210 | _json_attr = _json_attr() |
|
211 | 211 | for k, val in _json_attr.iteritems(): |
|
212 | 212 | d[k] = val |
|
213 | 213 | return d |
|
214 | 214 | |
|
215 | 215 | def get_appstruct(self): |
|
216 | 216 | """return list with keys and values tuples corresponding |
|
217 | 217 | to this model data """ |
|
218 | 218 | |
|
219 | 219 | l = [] |
|
220 | 220 | for k in self._get_keys(): |
|
221 | 221 | l.append((k, getattr(self, k),)) |
|
222 | 222 | return l |
|
223 | 223 | |
|
224 | 224 | def populate_obj(self, populate_dict): |
|
225 | 225 | """populate model with data from given populate_dict""" |
|
226 | 226 | |
|
227 | 227 | for k in self._get_keys(): |
|
228 | 228 | if k in populate_dict: |
|
229 | 229 | setattr(self, k, populate_dict[k]) |
|
230 | 230 | |
|
231 | 231 | @classmethod |
|
232 | 232 | def query(cls): |
|
233 | 233 | return Session().query(cls) |
|
234 | 234 | |
|
235 | 235 | @classmethod |
|
236 | 236 | def get(cls, id_): |
|
237 | 237 | if id_: |
|
238 | 238 | return cls.query().get(id_) |
|
239 | 239 | |
|
240 | 240 | @classmethod |
|
241 | 241 | def get_or_404(cls, id_): |
|
242 | 242 | from pyramid.httpexceptions import HTTPNotFound |
|
243 | 243 | |
|
244 | 244 | try: |
|
245 | 245 | id_ = int(id_) |
|
246 | 246 | except (TypeError, ValueError): |
|
247 | 247 | raise HTTPNotFound() |
|
248 | 248 | |
|
249 | 249 | res = cls.query().get(id_) |
|
250 | 250 | if not res: |
|
251 | 251 | raise HTTPNotFound() |
|
252 | 252 | return res |
|
253 | 253 | |
|
254 | 254 | @classmethod |
|
255 | 255 | def getAll(cls): |
|
256 | 256 | # deprecated and left for backward compatibility |
|
257 | 257 | return cls.get_all() |
|
258 | 258 | |
|
259 | 259 | @classmethod |
|
260 | 260 | def get_all(cls): |
|
261 | 261 | return cls.query().all() |
|
262 | 262 | |
|
263 | 263 | @classmethod |
|
264 | 264 | def delete(cls, id_): |
|
265 | 265 | obj = cls.query().get(id_) |
|
266 | 266 | Session().delete(obj) |
|
267 | 267 | |
|
268 | 268 | @classmethod |
|
269 | 269 | def identity_cache(cls, session, attr_name, value): |
|
270 | 270 | exist_in_session = [] |
|
271 | 271 | for (item_cls, pkey), instance in session.identity_map.items(): |
|
272 | 272 | if cls == item_cls and getattr(instance, attr_name) == value: |
|
273 | 273 | exist_in_session.append(instance) |
|
274 | 274 | if exist_in_session: |
|
275 | 275 | if len(exist_in_session) == 1: |
|
276 | 276 | return exist_in_session[0] |
|
277 | 277 | log.exception( |
|
278 | 278 | 'multiple objects with attr %s and ' |
|
279 | 279 | 'value %s found with same name: %r', |
|
280 | 280 | attr_name, value, exist_in_session) |
|
281 | 281 | |
|
282 | 282 | def __repr__(self): |
|
283 | 283 | if hasattr(self, '__unicode__'): |
|
284 | 284 | # python repr needs to return str |
|
285 | 285 | try: |
|
286 | 286 | return safe_str(self.__unicode__()) |
|
287 | 287 | except UnicodeDecodeError: |
|
288 | 288 | pass |
|
289 | 289 | return '<DB:%s>' % (self.__class__.__name__) |
|
290 | 290 | |
|
291 | 291 | |
|
292 | 292 | class RhodeCodeSetting(Base, BaseModel): |
|
293 | 293 | __tablename__ = 'rhodecode_settings' |
|
294 | 294 | __table_args__ = ( |
|
295 | 295 | UniqueConstraint('app_settings_name'), |
|
296 | 296 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
297 | 297 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} |
|
298 | 298 | ) |
|
299 | 299 | |
|
300 | 300 | SETTINGS_TYPES = { |
|
301 | 301 | 'str': safe_str, |
|
302 | 302 | 'int': safe_int, |
|
303 | 303 | 'unicode': safe_unicode, |
|
304 | 304 | 'bool': str2bool, |
|
305 | 305 | 'list': functools.partial(aslist, sep=',') |
|
306 | 306 | } |
|
307 | 307 | DEFAULT_UPDATE_URL = 'https://rhodecode.com/api/v1/info/versions' |
|
308 | 308 | GLOBAL_CONF_KEY = 'app_settings' |
|
309 | 309 | |
|
310 | 310 | app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) |
|
311 | 311 | app_settings_name = Column("app_settings_name", String(255), nullable=True, unique=None, default=None) |
|
312 | 312 | _app_settings_value = Column("app_settings_value", String(4096), nullable=True, unique=None, default=None) |
|
313 | 313 | _app_settings_type = Column("app_settings_type", String(255), nullable=True, unique=None, default=None) |
|
314 | 314 | |
|
315 | 315 | def __init__(self, key='', val='', type='unicode'): |
|
316 | 316 | self.app_settings_name = key |
|
317 | 317 | self.app_settings_type = type |
|
318 | 318 | self.app_settings_value = val |
|
319 | 319 | |
|
320 | 320 | @validates('_app_settings_value') |
|
321 | 321 | def validate_settings_value(self, key, val): |
|
322 | 322 | assert type(val) == unicode |
|
323 | 323 | return val |
|
324 | 324 | |
|
325 | 325 | @hybrid_property |
|
326 | 326 | def app_settings_value(self): |
|
327 | 327 | v = self._app_settings_value |
|
328 | 328 | _type = self.app_settings_type |
|
329 | 329 | if _type: |
|
330 | 330 | _type = self.app_settings_type.split('.')[0] |
|
331 | 331 | # decode the encrypted value |
|
332 | 332 | if 'encrypted' in self.app_settings_type: |
|
333 | 333 | cipher = EncryptedTextValue() |
|
334 | 334 | v = safe_unicode(cipher.process_result_value(v, None)) |
|
335 | 335 | |
|
336 | 336 | converter = self.SETTINGS_TYPES.get(_type) or \ |
|
337 | 337 | self.SETTINGS_TYPES['unicode'] |
|
338 | 338 | return converter(v) |
|
339 | 339 | |
|
340 | 340 | @app_settings_value.setter |
|
341 | 341 | def app_settings_value(self, val): |
|
342 | 342 | """ |
|
343 | 343 | Setter that will always make sure we use unicode in app_settings_value |
|
344 | 344 | |
|
345 | 345 | :param val: |
|
346 | 346 | """ |
|
347 | 347 | val = safe_unicode(val) |
|
348 | 348 | # encode the encrypted value |
|
349 | 349 | if 'encrypted' in self.app_settings_type: |
|
350 | 350 | cipher = EncryptedTextValue() |
|
351 | 351 | val = safe_unicode(cipher.process_bind_param(val, None)) |
|
352 | 352 | self._app_settings_value = val |
|
353 | 353 | |
|
354 | 354 | @hybrid_property |
|
355 | 355 | def app_settings_type(self): |
|
356 | 356 | return self._app_settings_type |
|
357 | 357 | |
|
358 | 358 | @app_settings_type.setter |
|
359 | 359 | def app_settings_type(self, val): |
|
360 | 360 | if val.split('.')[0] not in self.SETTINGS_TYPES: |
|
361 | 361 | raise Exception('type must be one of %s got %s' |
|
362 | 362 | % (self.SETTINGS_TYPES.keys(), val)) |
|
363 | 363 | self._app_settings_type = val |
|
364 | 364 | |
|
365 | 365 | def __unicode__(self): |
|
366 | 366 | return u"<%s('%s:%s[%s]')>" % ( |
|
367 | 367 | self.__class__.__name__, |
|
368 | 368 | self.app_settings_name, self.app_settings_value, |
|
369 | 369 | self.app_settings_type |
|
370 | 370 | ) |
|
371 | 371 | |
|
372 | 372 | |
|
373 | 373 | class RhodeCodeUi(Base, BaseModel): |
|
374 | 374 | __tablename__ = 'rhodecode_ui' |
|
375 | 375 | __table_args__ = ( |
|
376 | 376 | UniqueConstraint('ui_key'), |
|
377 | 377 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
378 | 378 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} |
|
379 | 379 | ) |
|
380 | 380 | |
|
381 | 381 | HOOK_REPO_SIZE = 'changegroup.repo_size' |
|
382 | 382 | # HG |
|
383 | 383 | HOOK_PRE_PULL = 'preoutgoing.pre_pull' |
|
384 | 384 | HOOK_PULL = 'outgoing.pull_logger' |
|
385 | 385 | HOOK_PRE_PUSH = 'prechangegroup.pre_push' |
|
386 | 386 | HOOK_PRETX_PUSH = 'pretxnchangegroup.pre_push' |
|
387 | 387 | HOOK_PUSH = 'changegroup.push_logger' |
|
388 | 388 | HOOK_PUSH_KEY = 'pushkey.key_push' |
|
389 | 389 | |
|
390 | 390 | # TODO: johbo: Unify way how hooks are configured for git and hg, |
|
391 | 391 | # git part is currently hardcoded. |
|
392 | 392 | |
|
393 | 393 | # SVN PATTERNS |
|
394 | 394 | SVN_BRANCH_ID = 'vcs_svn_branch' |
|
395 | 395 | SVN_TAG_ID = 'vcs_svn_tag' |
|
396 | 396 | |
|
397 | 397 | ui_id = Column( |
|
398 | 398 | "ui_id", Integer(), nullable=False, unique=True, default=None, |
|
399 | 399 | primary_key=True) |
|
400 | 400 | ui_section = Column( |
|
401 | 401 | "ui_section", String(255), nullable=True, unique=None, default=None) |
|
402 | 402 | ui_key = Column( |
|
403 | 403 | "ui_key", String(255), nullable=True, unique=None, default=None) |
|
404 | 404 | ui_value = Column( |
|
405 | 405 | "ui_value", String(255), nullable=True, unique=None, default=None) |
|
406 | 406 | ui_active = Column( |
|
407 | 407 | "ui_active", Boolean(), nullable=True, unique=None, default=True) |
|
408 | 408 | |
|
409 | 409 | def __repr__(self): |
|
410 | 410 | return '<%s[%s]%s=>%s]>' % (self.__class__.__name__, self.ui_section, |
|
411 | 411 | self.ui_key, self.ui_value) |
|
412 | 412 | |
|
413 | 413 | |
|
414 | 414 | class RepoRhodeCodeSetting(Base, BaseModel): |
|
415 | 415 | __tablename__ = 'repo_rhodecode_settings' |
|
416 | 416 | __table_args__ = ( |
|
417 | 417 | UniqueConstraint( |
|
418 | 418 | 'app_settings_name', 'repository_id', |
|
419 | 419 | name='uq_repo_rhodecode_setting_name_repo_id'), |
|
420 | 420 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
421 | 421 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} |
|
422 | 422 | ) |
|
423 | 423 | |
|
424 | 424 | repository_id = Column( |
|
425 | 425 | "repository_id", Integer(), ForeignKey('repositories.repo_id'), |
|
426 | 426 | nullable=False) |
|
427 | 427 | app_settings_id = Column( |
|
428 | 428 | "app_settings_id", Integer(), nullable=False, unique=True, |
|
429 | 429 | default=None, primary_key=True) |
|
430 | 430 | app_settings_name = Column( |
|
431 | 431 | "app_settings_name", String(255), nullable=True, unique=None, |
|
432 | 432 | default=None) |
|
433 | 433 | _app_settings_value = Column( |
|
434 | 434 | "app_settings_value", String(4096), nullable=True, unique=None, |
|
435 | 435 | default=None) |
|
436 | 436 | _app_settings_type = Column( |
|
437 | 437 | "app_settings_type", String(255), nullable=True, unique=None, |
|
438 | 438 | default=None) |
|
439 | 439 | |
|
440 | 440 | repository = relationship('Repository') |
|
441 | 441 | |
|
442 | 442 | def __init__(self, repository_id, key='', val='', type='unicode'): |
|
443 | 443 | self.repository_id = repository_id |
|
444 | 444 | self.app_settings_name = key |
|
445 | 445 | self.app_settings_type = type |
|
446 | 446 | self.app_settings_value = val |
|
447 | 447 | |
|
448 | 448 | @validates('_app_settings_value') |
|
449 | 449 | def validate_settings_value(self, key, val): |
|
450 | 450 | assert type(val) == unicode |
|
451 | 451 | return val |
|
452 | 452 | |
|
453 | 453 | @hybrid_property |
|
454 | 454 | def app_settings_value(self): |
|
455 | 455 | v = self._app_settings_value |
|
456 | 456 | type_ = self.app_settings_type |
|
457 | 457 | SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES |
|
458 | 458 | converter = SETTINGS_TYPES.get(type_) or SETTINGS_TYPES['unicode'] |
|
459 | 459 | return converter(v) |
|
460 | 460 | |
|
461 | 461 | @app_settings_value.setter |
|
462 | 462 | def app_settings_value(self, val): |
|
463 | 463 | """ |
|
464 | 464 | Setter that will always make sure we use unicode in app_settings_value |
|
465 | 465 | |
|
466 | 466 | :param val: |
|
467 | 467 | """ |
|
468 | 468 | self._app_settings_value = safe_unicode(val) |
|
469 | 469 | |
|
470 | 470 | @hybrid_property |
|
471 | 471 | def app_settings_type(self): |
|
472 | 472 | return self._app_settings_type |
|
473 | 473 | |
|
474 | 474 | @app_settings_type.setter |
|
475 | 475 | def app_settings_type(self, val): |
|
476 | 476 | SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES |
|
477 | 477 | if val not in SETTINGS_TYPES: |
|
478 | 478 | raise Exception('type must be one of %s got %s' |
|
479 | 479 | % (SETTINGS_TYPES.keys(), val)) |
|
480 | 480 | self._app_settings_type = val |
|
481 | 481 | |
|
482 | 482 | def __unicode__(self): |
|
483 | 483 | return u"<%s('%s:%s:%s[%s]')>" % ( |
|
484 | 484 | self.__class__.__name__, self.repository.repo_name, |
|
485 | 485 | self.app_settings_name, self.app_settings_value, |
|
486 | 486 | self.app_settings_type |
|
487 | 487 | ) |
|
488 | 488 | |
|
489 | 489 | |
|
490 | 490 | class RepoRhodeCodeUi(Base, BaseModel): |
|
491 | 491 | __tablename__ = 'repo_rhodecode_ui' |
|
492 | 492 | __table_args__ = ( |
|
493 | 493 | UniqueConstraint( |
|
494 | 494 | 'repository_id', 'ui_section', 'ui_key', |
|
495 | 495 | name='uq_repo_rhodecode_ui_repository_id_section_key'), |
|
496 | 496 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
497 | 497 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} |
|
498 | 498 | ) |
|
499 | 499 | |
|
500 | 500 | repository_id = Column( |
|
501 | 501 | "repository_id", Integer(), ForeignKey('repositories.repo_id'), |
|
502 | 502 | nullable=False) |
|
503 | 503 | ui_id = Column( |
|
504 | 504 | "ui_id", Integer(), nullable=False, unique=True, default=None, |
|
505 | 505 | primary_key=True) |
|
506 | 506 | ui_section = Column( |
|
507 | 507 | "ui_section", String(255), nullable=True, unique=None, default=None) |
|
508 | 508 | ui_key = Column( |
|
509 | 509 | "ui_key", String(255), nullable=True, unique=None, default=None) |
|
510 | 510 | ui_value = Column( |
|
511 | 511 | "ui_value", String(255), nullable=True, unique=None, default=None) |
|
512 | 512 | ui_active = Column( |
|
513 | 513 | "ui_active", Boolean(), nullable=True, unique=None, default=True) |
|
514 | 514 | |
|
515 | 515 | repository = relationship('Repository') |
|
516 | 516 | |
|
517 | 517 | def __repr__(self): |
|
518 | 518 | return '<%s[%s:%s]%s=>%s]>' % ( |
|
519 | 519 | self.__class__.__name__, self.repository.repo_name, |
|
520 | 520 | self.ui_section, self.ui_key, self.ui_value) |
|
521 | 521 | |
|
522 | 522 | |
|
523 | 523 | class User(Base, BaseModel): |
|
524 | 524 | __tablename__ = 'users' |
|
525 | 525 | __table_args__ = ( |
|
526 | 526 | UniqueConstraint('username'), UniqueConstraint('email'), |
|
527 | 527 | Index('u_username_idx', 'username'), |
|
528 | 528 | Index('u_email_idx', 'email'), |
|
529 | 529 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
530 | 530 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} |
|
531 | 531 | ) |
|
532 | 532 | DEFAULT_USER = 'default' |
|
533 | 533 | DEFAULT_USER_EMAIL = 'anonymous@rhodecode.org' |
|
534 | 534 | DEFAULT_GRAVATAR_URL = 'https://secure.gravatar.com/avatar/{md5email}?d=identicon&s={size}' |
|
535 | 535 | |
|
536 | 536 | user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) |
|
537 | 537 | username = Column("username", String(255), nullable=True, unique=None, default=None) |
|
538 | 538 | password = Column("password", String(255), nullable=True, unique=None, default=None) |
|
539 | 539 | active = Column("active", Boolean(), nullable=True, unique=None, default=True) |
|
540 | 540 | admin = Column("admin", Boolean(), nullable=True, unique=None, default=False) |
|
541 | 541 | name = Column("firstname", String(255), nullable=True, unique=None, default=None) |
|
542 | 542 | lastname = Column("lastname", String(255), nullable=True, unique=None, default=None) |
|
543 | 543 | _email = Column("email", String(255), nullable=True, unique=None, default=None) |
|
544 | 544 | last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None) |
|
545 | 545 | last_activity = Column('last_activity', DateTime(timezone=False), nullable=True, unique=None, default=None) |
|
546 | 546 | |
|
547 | 547 | extern_type = Column("extern_type", String(255), nullable=True, unique=None, default=None) |
|
548 | 548 | extern_name = Column("extern_name", String(255), nullable=True, unique=None, default=None) |
|
549 | 549 | _api_key = Column("api_key", String(255), nullable=True, unique=None, default=None) |
|
550 | 550 | inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True) |
|
551 | 551 | created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now) |
|
552 | 552 | _user_data = Column("user_data", LargeBinary(), nullable=True) # JSON data |
|
553 | 553 | |
|
554 | 554 | user_log = relationship('UserLog') |
|
555 | 555 | user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all') |
|
556 | 556 | |
|
557 | 557 | repositories = relationship('Repository') |
|
558 | 558 | repository_groups = relationship('RepoGroup') |
|
559 | 559 | user_groups = relationship('UserGroup') |
|
560 | 560 | |
|
561 | 561 | user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all') |
|
562 | 562 | followings = relationship('UserFollowing', primaryjoin='UserFollowing.user_id==User.user_id', cascade='all') |
|
563 | 563 | |
|
564 | 564 | repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all') |
|
565 | 565 | repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all') |
|
566 | 566 | user_group_to_perm = relationship('UserUserGroupToPerm', primaryjoin='UserUserGroupToPerm.user_id==User.user_id', cascade='all') |
|
567 | 567 | |
|
568 | 568 | group_member = relationship('UserGroupMember', cascade='all') |
|
569 | 569 | |
|
570 | 570 | notifications = relationship('UserNotification', cascade='all') |
|
571 | 571 | # notifications assigned to this user |
|
572 | 572 | user_created_notifications = relationship('Notification', cascade='all') |
|
573 | 573 | # comments created by this user |
|
574 | 574 | user_comments = relationship('ChangesetComment', cascade='all') |
|
575 | 575 | # user profile extra info |
|
576 | 576 | user_emails = relationship('UserEmailMap', cascade='all') |
|
577 | 577 | user_ip_map = relationship('UserIpMap', cascade='all') |
|
578 | 578 | user_auth_tokens = relationship('UserApiKeys', cascade='all') |
|
579 | 579 | user_ssh_keys = relationship('UserSshKeys', cascade='all') |
|
580 | 580 | |
|
581 | 581 | # gists |
|
582 | 582 | user_gists = relationship('Gist', cascade='all') |
|
583 | 583 | # user pull requests |
|
584 | 584 | user_pull_requests = relationship('PullRequest', cascade='all') |
|
585 | 585 | # external identities |
|
586 | 586 | extenal_identities = relationship( |
|
587 | 587 | 'ExternalIdentity', |
|
588 | 588 | primaryjoin="User.user_id==ExternalIdentity.local_user_id", |
|
589 | 589 | cascade='all') |
|
590 | 590 | # review rules |
|
591 | 591 | user_review_rules = relationship('RepoReviewRuleUser', cascade='all') |
|
592 | 592 | |
|
593 | 593 | def __unicode__(self): |
|
594 | 594 | return u"<%s('id:%s:%s')>" % (self.__class__.__name__, |
|
595 | 595 | self.user_id, self.username) |
|
596 | 596 | |
|
597 | 597 | @hybrid_property |
|
598 | 598 | def email(self): |
|
599 | 599 | return self._email |
|
600 | 600 | |
|
601 | 601 | @email.setter |
|
602 | 602 | def email(self, val): |
|
603 | 603 | self._email = val.lower() if val else None |
|
604 | 604 | |
|
605 | 605 | @hybrid_property |
|
606 | 606 | def first_name(self): |
|
607 | 607 | from rhodecode.lib import helpers as h |
|
608 | 608 | if self.name: |
|
609 | 609 | return h.escape(self.name) |
|
610 | 610 | return self.name |
|
611 | 611 | |
|
612 | 612 | @hybrid_property |
|
613 | 613 | def last_name(self): |
|
614 | 614 | from rhodecode.lib import helpers as h |
|
615 | 615 | if self.lastname: |
|
616 | 616 | return h.escape(self.lastname) |
|
617 | 617 | return self.lastname |
|
618 | 618 | |
|
619 | 619 | @hybrid_property |
|
620 | 620 | def api_key(self): |
|
621 | 621 | """ |
|
622 | 622 | Fetch if exist an auth-token with role ALL connected to this user |
|
623 | 623 | """ |
|
624 | 624 | user_auth_token = UserApiKeys.query()\ |
|
625 | 625 | .filter(UserApiKeys.user_id == self.user_id)\ |
|
626 | 626 | .filter(or_(UserApiKeys.expires == -1, |
|
627 | 627 | UserApiKeys.expires >= time.time()))\ |
|
628 | 628 | .filter(UserApiKeys.role == UserApiKeys.ROLE_ALL).first() |
|
629 | 629 | if user_auth_token: |
|
630 | 630 | user_auth_token = user_auth_token.api_key |
|
631 | 631 | |
|
632 | 632 | return user_auth_token |
|
633 | 633 | |
|
634 | 634 | @api_key.setter |
|
635 | 635 | def api_key(self, val): |
|
636 | 636 | # don't allow to set API key this is deprecated for now |
|
637 | 637 | self._api_key = None |
|
638 | 638 | |
|
639 | 639 | @property |
|
640 | 640 | def reviewer_pull_requests(self): |
|
641 | 641 | return PullRequestReviewers.query() \ |
|
642 | 642 | .options(joinedload(PullRequestReviewers.pull_request)) \ |
|
643 | 643 | .filter(PullRequestReviewers.user_id == self.user_id) \ |
|
644 | 644 | .all() |
|
645 | 645 | |
|
646 | 646 | @property |
|
647 | 647 | def firstname(self): |
|
648 | 648 | # alias for future |
|
649 | 649 | return self.name |
|
650 | 650 | |
|
651 | 651 | @property |
|
652 | 652 | def emails(self): |
|
653 | 653 | other = UserEmailMap.query()\ |
|
654 | 654 | .filter(UserEmailMap.user == self) \ |
|
655 | 655 | .order_by(UserEmailMap.email_id.asc()) \ |
|
656 | 656 | .all() |
|
657 | 657 | return [self.email] + [x.email for x in other] |
|
658 | 658 | |
|
659 | 659 | @property |
|
660 | 660 | def auth_tokens(self): |
|
661 | 661 | auth_tokens = self.get_auth_tokens() |
|
662 | 662 | return [x.api_key for x in auth_tokens] |
|
663 | 663 | |
|
664 | 664 | def get_auth_tokens(self): |
|
665 | 665 | return UserApiKeys.query()\ |
|
666 | 666 | .filter(UserApiKeys.user == self)\ |
|
667 | 667 | .order_by(UserApiKeys.user_api_key_id.asc())\ |
|
668 | 668 | .all() |
|
669 | 669 | |
|
670 | 670 | @property |
|
671 | 671 | def feed_token(self): |
|
672 | 672 | return self.get_feed_token() |
|
673 | 673 | |
|
674 | 674 | def get_feed_token(self): |
|
675 | 675 | feed_tokens = UserApiKeys.query()\ |
|
676 | 676 | .filter(UserApiKeys.user == self)\ |
|
677 | 677 | .filter(UserApiKeys.role == UserApiKeys.ROLE_FEED)\ |
|
678 | 678 | .all() |
|
679 | 679 | if feed_tokens: |
|
680 | 680 | return feed_tokens[0].api_key |
|
681 | 681 | return 'NO_FEED_TOKEN_AVAILABLE' |
|
682 | 682 | |
|
683 | 683 | @classmethod |
|
684 | def get(cls, user_id, cache=False): | |
|
685 | if not user_id: | |
|
686 | return | |
|
687 | ||
|
688 | user = cls.query() | |
|
689 | if cache: | |
|
690 | user = user.options( | |
|
691 | FromCache("sql_cache_short", "get_users_%s" % user_id)) | |
|
692 | return user.get(user_id) | |
|
693 | ||
|
694 | @classmethod | |
|
684 | 695 | def extra_valid_auth_tokens(cls, user, role=None): |
|
685 | 696 | tokens = UserApiKeys.query().filter(UserApiKeys.user == user)\ |
|
686 | 697 | .filter(or_(UserApiKeys.expires == -1, |
|
687 | 698 | UserApiKeys.expires >= time.time())) |
|
688 | 699 | if role: |
|
689 | 700 | tokens = tokens.filter(or_(UserApiKeys.role == role, |
|
690 | 701 | UserApiKeys.role == UserApiKeys.ROLE_ALL)) |
|
691 | 702 | return tokens.all() |
|
692 | 703 | |
|
693 | 704 | def authenticate_by_token(self, auth_token, roles=None, scope_repo_id=None): |
|
694 | 705 | from rhodecode.lib import auth |
|
695 | 706 | |
|
696 | 707 | log.debug('Trying to authenticate user: %s via auth-token, ' |
|
697 | 708 | 'and roles: %s', self, roles) |
|
698 | 709 | |
|
699 | 710 | if not auth_token: |
|
700 | 711 | return False |
|
701 | 712 | |
|
702 | 713 | crypto_backend = auth.crypto_backend() |
|
703 | 714 | |
|
704 | 715 | roles = (roles or []) + [UserApiKeys.ROLE_ALL] |
|
705 | 716 | tokens_q = UserApiKeys.query()\ |
|
706 | 717 | .filter(UserApiKeys.user_id == self.user_id)\ |
|
707 | 718 | .filter(or_(UserApiKeys.expires == -1, |
|
708 | 719 | UserApiKeys.expires >= time.time())) |
|
709 | 720 | |
|
710 | 721 | tokens_q = tokens_q.filter(UserApiKeys.role.in_(roles)) |
|
711 | 722 | |
|
712 | 723 | plain_tokens = [] |
|
713 | 724 | hash_tokens = [] |
|
714 | 725 | |
|
715 | 726 | for token in tokens_q.all(): |
|
716 | 727 | # verify scope first |
|
717 | 728 | if token.repo_id: |
|
718 | 729 | # token has a scope, we need to verify it |
|
719 | 730 | if scope_repo_id != token.repo_id: |
|
720 | 731 | log.debug( |
|
721 | 732 | 'Scope mismatch: token has a set repo scope: %s, ' |
|
722 | 733 | 'and calling scope is:%s, skipping further checks', |
|
723 | 734 | token.repo, scope_repo_id) |
|
724 | 735 | # token has a scope, and it doesn't match, skip token |
|
725 | 736 | continue |
|
726 | 737 | |
|
727 | 738 | if token.api_key.startswith(crypto_backend.ENC_PREF): |
|
728 | 739 | hash_tokens.append(token.api_key) |
|
729 | 740 | else: |
|
730 | 741 | plain_tokens.append(token.api_key) |
|
731 | 742 | |
|
732 | 743 | is_plain_match = auth_token in plain_tokens |
|
733 | 744 | if is_plain_match: |
|
734 | 745 | return True |
|
735 | 746 | |
|
736 | 747 | for hashed in hash_tokens: |
|
737 | 748 | # TODO(marcink): this is expensive to calculate, but most secure |
|
738 | 749 | match = crypto_backend.hash_check(auth_token, hashed) |
|
739 | 750 | if match: |
|
740 | 751 | return True |
|
741 | 752 | |
|
742 | 753 | return False |
|
743 | 754 | |
|
744 | 755 | @property |
|
745 | 756 | def ip_addresses(self): |
|
746 | 757 | ret = UserIpMap.query().filter(UserIpMap.user == self).all() |
|
747 | 758 | return [x.ip_addr for x in ret] |
|
748 | 759 | |
|
749 | 760 | @property |
|
750 | 761 | def username_and_name(self): |
|
751 | 762 | return '%s (%s %s)' % (self.username, self.first_name, self.last_name) |
|
752 | 763 | |
|
753 | 764 | @property |
|
754 | 765 | def username_or_name_or_email(self): |
|
755 | 766 | full_name = self.full_name if self.full_name is not ' ' else None |
|
756 | 767 | return self.username or full_name or self.email |
|
757 | 768 | |
|
758 | 769 | @property |
|
759 | 770 | def full_name(self): |
|
760 | 771 | return '%s %s' % (self.first_name, self.last_name) |
|
761 | 772 | |
|
762 | 773 | @property |
|
763 | 774 | def full_name_or_username(self): |
|
764 | 775 | return ('%s %s' % (self.first_name, self.last_name) |
|
765 | 776 | if (self.first_name and self.last_name) else self.username) |
|
766 | 777 | |
|
767 | 778 | @property |
|
768 | 779 | def full_contact(self): |
|
769 | 780 | return '%s %s <%s>' % (self.first_name, self.last_name, self.email) |
|
770 | 781 | |
|
771 | 782 | @property |
|
772 | 783 | def short_contact(self): |
|
773 | 784 | return '%s %s' % (self.first_name, self.last_name) |
|
774 | 785 | |
|
775 | 786 | @property |
|
776 | 787 | def is_admin(self): |
|
777 | 788 | return self.admin |
|
778 | 789 | |
|
779 | 790 | def AuthUser(self, **kwargs): |
|
780 | 791 | """ |
|
781 | 792 | Returns instance of AuthUser for this user |
|
782 | 793 | """ |
|
783 | 794 | from rhodecode.lib.auth import AuthUser |
|
784 | 795 | return AuthUser(user_id=self.user_id, username=self.username, **kwargs) |
|
785 | 796 | |
|
786 | 797 | @hybrid_property |
|
787 | 798 | def user_data(self): |
|
788 | 799 | if not self._user_data: |
|
789 | 800 | return {} |
|
790 | 801 | |
|
791 | 802 | try: |
|
792 | 803 | return json.loads(self._user_data) |
|
793 | 804 | except TypeError: |
|
794 | 805 | return {} |
|
795 | 806 | |
|
796 | 807 | @user_data.setter |
|
797 | 808 | def user_data(self, val): |
|
798 | 809 | if not isinstance(val, dict): |
|
799 | 810 | raise Exception('user_data must be dict, got %s' % type(val)) |
|
800 | 811 | try: |
|
801 | 812 | self._user_data = json.dumps(val) |
|
802 | 813 | except Exception: |
|
803 | 814 | log.error(traceback.format_exc()) |
|
804 | 815 | |
|
805 | 816 | @classmethod |
|
806 | 817 | def get_by_username(cls, username, case_insensitive=False, |
|
807 | 818 | cache=False, identity_cache=False): |
|
808 | 819 | session = Session() |
|
809 | 820 | |
|
810 | 821 | if case_insensitive: |
|
811 | 822 | q = cls.query().filter( |
|
812 | 823 | func.lower(cls.username) == func.lower(username)) |
|
813 | 824 | else: |
|
814 | 825 | q = cls.query().filter(cls.username == username) |
|
815 | 826 | |
|
816 | 827 | if cache: |
|
817 | 828 | if identity_cache: |
|
818 | 829 | val = cls.identity_cache(session, 'username', username) |
|
819 | 830 | if val: |
|
820 | 831 | return val |
|
821 | 832 | else: |
|
822 | 833 | cache_key = "get_user_by_name_%s" % _hash_key(username) |
|
823 | 834 | q = q.options( |
|
824 | 835 | FromCache("sql_cache_short", cache_key)) |
|
825 | 836 | |
|
826 | 837 | return q.scalar() |
|
827 | 838 | |
|
828 | 839 | @classmethod |
|
829 | 840 | def get_by_auth_token(cls, auth_token, cache=False): |
|
830 | 841 | q = UserApiKeys.query()\ |
|
831 | 842 | .filter(UserApiKeys.api_key == auth_token)\ |
|
832 | 843 | .filter(or_(UserApiKeys.expires == -1, |
|
833 | 844 | UserApiKeys.expires >= time.time())) |
|
834 | 845 | if cache: |
|
835 | 846 | q = q.options( |
|
836 | 847 | FromCache("sql_cache_short", "get_auth_token_%s" % auth_token)) |
|
837 | 848 | |
|
838 | 849 | match = q.first() |
|
839 | 850 | if match: |
|
840 | 851 | return match.user |
|
841 | 852 | |
|
842 | 853 | @classmethod |
|
843 | 854 | def get_by_email(cls, email, case_insensitive=False, cache=False): |
|
844 | 855 | |
|
845 | 856 | if case_insensitive: |
|
846 | 857 | q = cls.query().filter(func.lower(cls.email) == func.lower(email)) |
|
847 | 858 | |
|
848 | 859 | else: |
|
849 | 860 | q = cls.query().filter(cls.email == email) |
|
850 | 861 | |
|
851 | 862 | email_key = _hash_key(email) |
|
852 | 863 | if cache: |
|
853 | 864 | q = q.options( |
|
854 | 865 | FromCache("sql_cache_short", "get_email_key_%s" % email_key)) |
|
855 | 866 | |
|
856 | 867 | ret = q.scalar() |
|
857 | 868 | if ret is None: |
|
858 | 869 | q = UserEmailMap.query() |
|
859 | 870 | # try fetching in alternate email map |
|
860 | 871 | if case_insensitive: |
|
861 | 872 | q = q.filter(func.lower(UserEmailMap.email) == func.lower(email)) |
|
862 | 873 | else: |
|
863 | 874 | q = q.filter(UserEmailMap.email == email) |
|
864 | 875 | q = q.options(joinedload(UserEmailMap.user)) |
|
865 | 876 | if cache: |
|
866 | 877 | q = q.options( |
|
867 | 878 | FromCache("sql_cache_short", "get_email_map_key_%s" % email_key)) |
|
868 | 879 | ret = getattr(q.scalar(), 'user', None) |
|
869 | 880 | |
|
870 | 881 | return ret |
|
871 | 882 | |
|
872 | 883 | @classmethod |
|
873 | 884 | def get_from_cs_author(cls, author): |
|
874 | 885 | """ |
|
875 | 886 | Tries to get User objects out of commit author string |
|
876 | 887 | |
|
877 | 888 | :param author: |
|
878 | 889 | """ |
|
879 | 890 | from rhodecode.lib.helpers import email, author_name |
|
880 | 891 | # Valid email in the attribute passed, see if they're in the system |
|
881 | 892 | _email = email(author) |
|
882 | 893 | if _email: |
|
883 | 894 | user = cls.get_by_email(_email, case_insensitive=True) |
|
884 | 895 | if user: |
|
885 | 896 | return user |
|
886 | 897 | # Maybe we can match by username? |
|
887 | 898 | _author = author_name(author) |
|
888 | 899 | user = cls.get_by_username(_author, case_insensitive=True) |
|
889 | 900 | if user: |
|
890 | 901 | return user |
|
891 | 902 | |
|
892 | 903 | def update_userdata(self, **kwargs): |
|
893 | 904 | usr = self |
|
894 | 905 | old = usr.user_data |
|
895 | 906 | old.update(**kwargs) |
|
896 | 907 | usr.user_data = old |
|
897 | 908 | Session().add(usr) |
|
898 | 909 | log.debug('updated userdata with ', kwargs) |
|
899 | 910 | |
|
900 | 911 | def update_lastlogin(self): |
|
901 | 912 | """Update user lastlogin""" |
|
902 | 913 | self.last_login = datetime.datetime.now() |
|
903 | 914 | Session().add(self) |
|
904 | 915 | log.debug('updated user %s lastlogin', self.username) |
|
905 | 916 | |
|
906 | 917 | def update_lastactivity(self): |
|
907 | 918 | """Update user lastactivity""" |
|
908 | 919 | self.last_activity = datetime.datetime.now() |
|
909 | 920 | Session().add(self) |
|
910 | 921 | log.debug('updated user %s lastactivity', self.username) |
|
911 | 922 | |
|
912 | 923 | def update_password(self, new_password): |
|
913 | 924 | from rhodecode.lib.auth import get_crypt_password |
|
914 | 925 | |
|
915 | 926 | self.password = get_crypt_password(new_password) |
|
916 | 927 | Session().add(self) |
|
917 | 928 | |
|
918 | 929 | @classmethod |
|
919 | 930 | def get_first_super_admin(cls): |
|
920 | 931 | user = User.query().filter(User.admin == true()).first() |
|
921 | 932 | if user is None: |
|
922 | 933 | raise Exception('FATAL: Missing administrative account!') |
|
923 | 934 | return user |
|
924 | 935 | |
|
925 | 936 | @classmethod |
|
926 | 937 | def get_all_super_admins(cls): |
|
927 | 938 | """ |
|
928 | 939 | Returns all admin accounts sorted by username |
|
929 | 940 | """ |
|
930 | 941 | return User.query().filter(User.admin == true())\ |
|
931 | 942 | .order_by(User.username.asc()).all() |
|
932 | 943 | |
|
933 | 944 | @classmethod |
|
934 | 945 | def get_default_user(cls, cache=False, refresh=False): |
|
935 | 946 | user = User.get_by_username(User.DEFAULT_USER, cache=cache) |
|
936 | 947 | if user is None: |
|
937 | 948 | raise Exception('FATAL: Missing default account!') |
|
938 | 949 | if refresh: |
|
939 | 950 | # The default user might be based on outdated state which |
|
940 | 951 | # has been loaded from the cache. |
|
941 | 952 | # A call to refresh() ensures that the |
|
942 | 953 | # latest state from the database is used. |
|
943 | 954 | Session().refresh(user) |
|
944 | 955 | return user |
|
945 | 956 | |
|
946 | 957 | def _get_default_perms(self, user, suffix=''): |
|
947 | 958 | from rhodecode.model.permission import PermissionModel |
|
948 | 959 | return PermissionModel().get_default_perms(user.user_perms, suffix) |
|
949 | 960 | |
|
950 | 961 | def get_default_perms(self, suffix=''): |
|
951 | 962 | return self._get_default_perms(self, suffix) |
|
952 | 963 | |
|
953 | 964 | def get_api_data(self, include_secrets=False, details='full'): |
|
954 | 965 | """ |
|
955 | 966 | Common function for generating user related data for API |
|
956 | 967 | |
|
957 | 968 | :param include_secrets: By default secrets in the API data will be replaced |
|
958 | 969 | by a placeholder value to prevent exposing this data by accident. In case |
|
959 | 970 | this data shall be exposed, set this flag to ``True``. |
|
960 | 971 | |
|
961 | 972 | :param details: details can be 'basic|full' basic gives only a subset of |
|
962 | 973 | the available user information that includes user_id, name and emails. |
|
963 | 974 | """ |
|
964 | 975 | user = self |
|
965 | 976 | user_data = self.user_data |
|
966 | 977 | data = { |
|
967 | 978 | 'user_id': user.user_id, |
|
968 | 979 | 'username': user.username, |
|
969 | 980 | 'firstname': user.name, |
|
970 | 981 | 'lastname': user.lastname, |
|
971 | 982 | 'email': user.email, |
|
972 | 983 | 'emails': user.emails, |
|
973 | 984 | } |
|
974 | 985 | if details == 'basic': |
|
975 | 986 | return data |
|
976 | 987 | |
|
977 | 988 | auth_token_length = 40 |
|
978 | 989 | auth_token_replacement = '*' * auth_token_length |
|
979 | 990 | |
|
980 | 991 | extras = { |
|
981 | 992 | 'auth_tokens': [auth_token_replacement], |
|
982 | 993 | 'active': user.active, |
|
983 | 994 | 'admin': user.admin, |
|
984 | 995 | 'extern_type': user.extern_type, |
|
985 | 996 | 'extern_name': user.extern_name, |
|
986 | 997 | 'last_login': user.last_login, |
|
987 | 998 | 'last_activity': user.last_activity, |
|
988 | 999 | 'ip_addresses': user.ip_addresses, |
|
989 | 1000 | 'language': user_data.get('language') |
|
990 | 1001 | } |
|
991 | 1002 | data.update(extras) |
|
992 | 1003 | |
|
993 | 1004 | if include_secrets: |
|
994 | 1005 | data['auth_tokens'] = user.auth_tokens |
|
995 | 1006 | return data |
|
996 | 1007 | |
|
997 | 1008 | def __json__(self): |
|
998 | 1009 | data = { |
|
999 | 1010 | 'full_name': self.full_name, |
|
1000 | 1011 | 'full_name_or_username': self.full_name_or_username, |
|
1001 | 1012 | 'short_contact': self.short_contact, |
|
1002 | 1013 | 'full_contact': self.full_contact, |
|
1003 | 1014 | } |
|
1004 | 1015 | data.update(self.get_api_data()) |
|
1005 | 1016 | return data |
|
1006 | 1017 | |
|
1007 | 1018 | |
|
1008 | 1019 | class UserApiKeys(Base, BaseModel): |
|
1009 | 1020 | __tablename__ = 'user_api_keys' |
|
1010 | 1021 | __table_args__ = ( |
|
1011 | 1022 | Index('uak_api_key_idx', 'api_key', unique=True), |
|
1012 | 1023 | Index('uak_api_key_expires_idx', 'api_key', 'expires'), |
|
1013 | 1024 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
1014 | 1025 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} |
|
1015 | 1026 | ) |
|
1016 | 1027 | __mapper_args__ = {} |
|
1017 | 1028 | |
|
1018 | 1029 | # ApiKey role |
|
1019 | 1030 | ROLE_ALL = 'token_role_all' |
|
1020 | 1031 | ROLE_HTTP = 'token_role_http' |
|
1021 | 1032 | ROLE_VCS = 'token_role_vcs' |
|
1022 | 1033 | ROLE_API = 'token_role_api' |
|
1023 | 1034 | ROLE_FEED = 'token_role_feed' |
|
1024 | 1035 | ROLE_PASSWORD_RESET = 'token_password_reset' |
|
1025 | 1036 | |
|
1026 | 1037 | ROLES = [ROLE_ALL, ROLE_HTTP, ROLE_VCS, ROLE_API, ROLE_FEED] |
|
1027 | 1038 | |
|
1028 | 1039 | user_api_key_id = Column("user_api_key_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) |
|
1029 | 1040 | user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None) |
|
1030 | 1041 | api_key = Column("api_key", String(255), nullable=False, unique=True) |
|
1031 | 1042 | description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql')) |
|
1032 | 1043 | expires = Column('expires', Float(53), nullable=False) |
|
1033 | 1044 | role = Column('role', String(255), nullable=True) |
|
1034 | 1045 | created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now) |
|
1035 | 1046 | |
|
1036 | 1047 | # scope columns |
|
1037 | 1048 | repo_id = Column( |
|
1038 | 1049 | 'repo_id', Integer(), ForeignKey('repositories.repo_id'), |
|
1039 | 1050 | nullable=True, unique=None, default=None) |
|
1040 | 1051 | repo = relationship('Repository', lazy='joined') |
|
1041 | 1052 | |
|
1042 | 1053 | repo_group_id = Column( |
|
1043 | 1054 | 'repo_group_id', Integer(), ForeignKey('groups.group_id'), |
|
1044 | 1055 | nullable=True, unique=None, default=None) |
|
1045 | 1056 | repo_group = relationship('RepoGroup', lazy='joined') |
|
1046 | 1057 | |
|
1047 | 1058 | user = relationship('User', lazy='joined') |
|
1048 | 1059 | |
|
1049 | 1060 | def __unicode__(self): |
|
1050 | 1061 | return u"<%s('%s')>" % (self.__class__.__name__, self.role) |
|
1051 | 1062 | |
|
1052 | 1063 | def __json__(self): |
|
1053 | 1064 | data = { |
|
1054 | 1065 | 'auth_token': self.api_key, |
|
1055 | 1066 | 'role': self.role, |
|
1056 | 1067 | 'scope': self.scope_humanized, |
|
1057 | 1068 | 'expired': self.expired |
|
1058 | 1069 | } |
|
1059 | 1070 | return data |
|
1060 | 1071 | |
|
1061 | 1072 | def get_api_data(self, include_secrets=False): |
|
1062 | 1073 | data = self.__json__() |
|
1063 | 1074 | if include_secrets: |
|
1064 | 1075 | return data |
|
1065 | 1076 | else: |
|
1066 | 1077 | data['auth_token'] = self.token_obfuscated |
|
1067 | 1078 | return data |
|
1068 | 1079 | |
|
1069 | 1080 | @hybrid_property |
|
1070 | 1081 | def description_safe(self): |
|
1071 | 1082 | from rhodecode.lib import helpers as h |
|
1072 | 1083 | return h.escape(self.description) |
|
1073 | 1084 | |
|
1074 | 1085 | @property |
|
1075 | 1086 | def expired(self): |
|
1076 | 1087 | if self.expires == -1: |
|
1077 | 1088 | return False |
|
1078 | 1089 | return time.time() > self.expires |
|
1079 | 1090 | |
|
1080 | 1091 | @classmethod |
|
1081 | 1092 | def _get_role_name(cls, role): |
|
1082 | 1093 | return { |
|
1083 | 1094 | cls.ROLE_ALL: _('all'), |
|
1084 | 1095 | cls.ROLE_HTTP: _('http/web interface'), |
|
1085 | 1096 | cls.ROLE_VCS: _('vcs (git/hg/svn protocol)'), |
|
1086 | 1097 | cls.ROLE_API: _('api calls'), |
|
1087 | 1098 | cls.ROLE_FEED: _('feed access'), |
|
1088 | 1099 | }.get(role, role) |
|
1089 | 1100 | |
|
1090 | 1101 | @property |
|
1091 | 1102 | def role_humanized(self): |
|
1092 | 1103 | return self._get_role_name(self.role) |
|
1093 | 1104 | |
|
1094 | 1105 | def _get_scope(self): |
|
1095 | 1106 | if self.repo: |
|
1096 | 1107 | return repr(self.repo) |
|
1097 | 1108 | if self.repo_group: |
|
1098 | 1109 | return repr(self.repo_group) + ' (recursive)' |
|
1099 | 1110 | return 'global' |
|
1100 | 1111 | |
|
1101 | 1112 | @property |
|
1102 | 1113 | def scope_humanized(self): |
|
1103 | 1114 | return self._get_scope() |
|
1104 | 1115 | |
|
1105 | 1116 | @property |
|
1106 | 1117 | def token_obfuscated(self): |
|
1107 | 1118 | if self.api_key: |
|
1108 | 1119 | return self.api_key[:4] + "****" |
|
1109 | 1120 | |
|
1110 | 1121 | |
|
1111 | 1122 | class UserEmailMap(Base, BaseModel): |
|
1112 | 1123 | __tablename__ = 'user_email_map' |
|
1113 | 1124 | __table_args__ = ( |
|
1114 | 1125 | Index('uem_email_idx', 'email'), |
|
1115 | 1126 | UniqueConstraint('email'), |
|
1116 | 1127 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
1117 | 1128 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} |
|
1118 | 1129 | ) |
|
1119 | 1130 | __mapper_args__ = {} |
|
1120 | 1131 | |
|
1121 | 1132 | email_id = Column("email_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) |
|
1122 | 1133 | user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None) |
|
1123 | 1134 | _email = Column("email", String(255), nullable=True, unique=False, default=None) |
|
1124 | 1135 | user = relationship('User', lazy='joined') |
|
1125 | 1136 | |
|
1126 | 1137 | @validates('_email') |
|
1127 | 1138 | def validate_email(self, key, email): |
|
1128 | 1139 | # check if this email is not main one |
|
1129 | 1140 | main_email = Session().query(User).filter(User.email == email).scalar() |
|
1130 | 1141 | if main_email is not None: |
|
1131 | 1142 | raise AttributeError('email %s is present is user table' % email) |
|
1132 | 1143 | return email |
|
1133 | 1144 | |
|
1134 | 1145 | @hybrid_property |
|
1135 | 1146 | def email(self): |
|
1136 | 1147 | return self._email |
|
1137 | 1148 | |
|
1138 | 1149 | @email.setter |
|
1139 | 1150 | def email(self, val): |
|
1140 | 1151 | self._email = val.lower() if val else None |
|
1141 | 1152 | |
|
1142 | 1153 | |
|
1143 | 1154 | class UserIpMap(Base, BaseModel): |
|
1144 | 1155 | __tablename__ = 'user_ip_map' |
|
1145 | 1156 | __table_args__ = ( |
|
1146 | 1157 | UniqueConstraint('user_id', 'ip_addr'), |
|
1147 | 1158 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
1148 | 1159 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} |
|
1149 | 1160 | ) |
|
1150 | 1161 | __mapper_args__ = {} |
|
1151 | 1162 | |
|
1152 | 1163 | ip_id = Column("ip_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) |
|
1153 | 1164 | user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None) |
|
1154 | 1165 | ip_addr = Column("ip_addr", String(255), nullable=True, unique=False, default=None) |
|
1155 | 1166 | active = Column("active", Boolean(), nullable=True, unique=None, default=True) |
|
1156 | 1167 | description = Column("description", String(10000), nullable=True, unique=None, default=None) |
|
1157 | 1168 | user = relationship('User', lazy='joined') |
|
1158 | 1169 | |
|
1159 | 1170 | @hybrid_property |
|
1160 | 1171 | def description_safe(self): |
|
1161 | 1172 | from rhodecode.lib import helpers as h |
|
1162 | 1173 | return h.escape(self.description) |
|
1163 | 1174 | |
|
1164 | 1175 | @classmethod |
|
1165 | 1176 | def _get_ip_range(cls, ip_addr): |
|
1166 | 1177 | net = ipaddress.ip_network(safe_unicode(ip_addr), strict=False) |
|
1167 | 1178 | return [str(net.network_address), str(net.broadcast_address)] |
|
1168 | 1179 | |
|
1169 | 1180 | def __json__(self): |
|
1170 | 1181 | return { |
|
1171 | 1182 | 'ip_addr': self.ip_addr, |
|
1172 | 1183 | 'ip_range': self._get_ip_range(self.ip_addr), |
|
1173 | 1184 | } |
|
1174 | 1185 | |
|
1175 | 1186 | def __unicode__(self): |
|
1176 | 1187 | return u"<%s('user_id:%s=>%s')>" % (self.__class__.__name__, |
|
1177 | 1188 | self.user_id, self.ip_addr) |
|
1178 | 1189 | |
|
1179 | 1190 | |
|
1180 | 1191 | class UserSshKeys(Base, BaseModel): |
|
1181 | 1192 | __tablename__ = 'user_ssh_keys' |
|
1182 | 1193 | __table_args__ = ( |
|
1183 | 1194 | Index('usk_ssh_key_fingerprint_idx', 'ssh_key_fingerprint'), |
|
1184 | 1195 | |
|
1185 | 1196 | UniqueConstraint('ssh_key_fingerprint'), |
|
1186 | 1197 | |
|
1187 | 1198 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
1188 | 1199 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} |
|
1189 | 1200 | ) |
|
1190 | 1201 | __mapper_args__ = {} |
|
1191 | 1202 | |
|
1192 | 1203 | ssh_key_id = Column('ssh_key_id', Integer(), nullable=False, unique=True, default=None, primary_key=True) |
|
1193 | 1204 | ssh_key_data = Column('ssh_key_data', String(10240), nullable=False, unique=None, default=None) |
|
1194 | 1205 | ssh_key_fingerprint = Column('ssh_key_fingerprint', String(1024), nullable=False, unique=None, default=None) |
|
1195 | 1206 | |
|
1196 | 1207 | description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql')) |
|
1197 | 1208 | |
|
1198 | 1209 | created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now) |
|
1199 | 1210 | accessed_on = Column('accessed_on', DateTime(timezone=False), nullable=True, default=None) |
|
1200 | 1211 | user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None) |
|
1201 | 1212 | |
|
1202 | 1213 | user = relationship('User', lazy='joined') |
|
1203 | 1214 | |
|
1204 | 1215 | def __json__(self): |
|
1205 | 1216 | data = { |
|
1206 | 1217 | 'ssh_fingerprint': self.ssh_key_fingerprint, |
|
1207 | 1218 | 'description': self.description, |
|
1208 | 1219 | 'created_on': self.created_on |
|
1209 | 1220 | } |
|
1210 | 1221 | return data |
|
1211 | 1222 | |
|
1212 | 1223 | def get_api_data(self): |
|
1213 | 1224 | data = self.__json__() |
|
1214 | 1225 | return data |
|
1215 | 1226 | |
|
1216 | 1227 | |
|
1217 | 1228 | class UserLog(Base, BaseModel): |
|
1218 | 1229 | __tablename__ = 'user_logs' |
|
1219 | 1230 | __table_args__ = ( |
|
1220 | 1231 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
1221 | 1232 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}, |
|
1222 | 1233 | ) |
|
1223 | 1234 | VERSION_1 = 'v1' |
|
1224 | 1235 | VERSION_2 = 'v2' |
|
1225 | 1236 | VERSIONS = [VERSION_1, VERSION_2] |
|
1226 | 1237 | |
|
1227 | 1238 | user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) |
|
1228 | 1239 | user_id = Column("user_id", Integer(), ForeignKey('users.user_id',ondelete='SET NULL'), nullable=True, unique=None, default=None) |
|
1229 | 1240 | username = Column("username", String(255), nullable=True, unique=None, default=None) |
|
1230 | 1241 | repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id', ondelete='SET NULL'), nullable=True, unique=None, default=None) |
|
1231 | 1242 | repository_name = Column("repository_name", String(255), nullable=True, unique=None, default=None) |
|
1232 | 1243 | user_ip = Column("user_ip", String(255), nullable=True, unique=None, default=None) |
|
1233 | 1244 | action = Column("action", Text().with_variant(Text(1200000), 'mysql'), nullable=True, unique=None, default=None) |
|
1234 | 1245 | action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None) |
|
1235 | 1246 | |
|
1236 | 1247 | version = Column("version", String(255), nullable=True, default=VERSION_1) |
|
1237 | 1248 | user_data = Column('user_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT())))) |
|
1238 | 1249 | action_data = Column('action_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT())))) |
|
1239 | 1250 | |
|
1240 | 1251 | def __unicode__(self): |
|
1241 | 1252 | return u"<%s('id:%s:%s')>" % ( |
|
1242 | 1253 | self.__class__.__name__, self.repository_name, self.action) |
|
1243 | 1254 | |
|
1244 | 1255 | def __json__(self): |
|
1245 | 1256 | return { |
|
1246 | 1257 | 'user_id': self.user_id, |
|
1247 | 1258 | 'username': self.username, |
|
1248 | 1259 | 'repository_id': self.repository_id, |
|
1249 | 1260 | 'repository_name': self.repository_name, |
|
1250 | 1261 | 'user_ip': self.user_ip, |
|
1251 | 1262 | 'action_date': self.action_date, |
|
1252 | 1263 | 'action': self.action, |
|
1253 | 1264 | } |
|
1254 | 1265 | |
|
1255 | 1266 | @hybrid_property |
|
1256 | 1267 | def entry_id(self): |
|
1257 | 1268 | return self.user_log_id |
|
1258 | 1269 | |
|
1259 | 1270 | @property |
|
1260 | 1271 | def action_as_day(self): |
|
1261 | 1272 | return datetime.date(*self.action_date.timetuple()[:3]) |
|
1262 | 1273 | |
|
1263 | 1274 | user = relationship('User') |
|
1264 | 1275 | repository = relationship('Repository', cascade='') |
|
1265 | 1276 | |
|
1266 | 1277 | |
|
1267 | 1278 | class UserGroup(Base, BaseModel): |
|
1268 | 1279 | __tablename__ = 'users_groups' |
|
1269 | 1280 | __table_args__ = ( |
|
1270 | 1281 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
1271 | 1282 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}, |
|
1272 | 1283 | ) |
|
1273 | 1284 | |
|
1274 | 1285 | users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) |
|
1275 | 1286 | users_group_name = Column("users_group_name", String(255), nullable=False, unique=True, default=None) |
|
1276 | 1287 | user_group_description = Column("user_group_description", String(10000), nullable=True, unique=None, default=None) |
|
1277 | 1288 | users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None) |
|
1278 | 1289 | inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True) |
|
1279 | 1290 | user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None) |
|
1280 | 1291 | created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now) |
|
1281 | 1292 | _group_data = Column("group_data", LargeBinary(), nullable=True) # JSON data |
|
1282 | 1293 | |
|
1283 | 1294 | members = relationship('UserGroupMember', cascade="all, delete, delete-orphan", lazy="joined") |
|
1284 | 1295 | users_group_to_perm = relationship('UserGroupToPerm', cascade='all') |
|
1285 | 1296 | users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all') |
|
1286 | 1297 | users_group_repo_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all') |
|
1287 | 1298 | user_user_group_to_perm = relationship('UserUserGroupToPerm', cascade='all') |
|
1288 | 1299 | user_group_user_group_to_perm = relationship('UserGroupUserGroupToPerm ', primaryjoin="UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id", cascade='all') |
|
1289 | 1300 | |
|
1290 | 1301 | user_group_review_rules = relationship('RepoReviewRuleUserGroup', cascade='all') |
|
1291 | 1302 | user = relationship('User', primaryjoin="User.user_id==UserGroup.user_id") |
|
1292 | 1303 | |
|
1293 | 1304 | @classmethod |
|
1294 | 1305 | def _load_group_data(cls, column): |
|
1295 | 1306 | if not column: |
|
1296 | 1307 | return {} |
|
1297 | 1308 | |
|
1298 | 1309 | try: |
|
1299 | 1310 | return json.loads(column) or {} |
|
1300 | 1311 | except TypeError: |
|
1301 | 1312 | return {} |
|
1302 | 1313 | |
|
1303 | 1314 | @hybrid_property |
|
1304 | 1315 | def description_safe(self): |
|
1305 | 1316 | from rhodecode.lib import helpers as h |
|
1306 | 1317 | return h.escape(self.description) |
|
1307 | 1318 | |
|
1308 | 1319 | @hybrid_property |
|
1309 | 1320 | def group_data(self): |
|
1310 | 1321 | return self._load_group_data(self._group_data) |
|
1311 | 1322 | |
|
1312 | 1323 | @group_data.expression |
|
1313 | 1324 | def group_data(self, **kwargs): |
|
1314 | 1325 | return self._group_data |
|
1315 | 1326 | |
|
1316 | 1327 | @group_data.setter |
|
1317 | 1328 | def group_data(self, val): |
|
1318 | 1329 | try: |
|
1319 | 1330 | self._group_data = json.dumps(val) |
|
1320 | 1331 | except Exception: |
|
1321 | 1332 | log.error(traceback.format_exc()) |
|
1322 | 1333 | |
|
1323 | 1334 | def __unicode__(self): |
|
1324 | 1335 | return u"<%s('id:%s:%s')>" % (self.__class__.__name__, |
|
1325 | 1336 | self.users_group_id, |
|
1326 | 1337 | self.users_group_name) |
|
1327 | 1338 | |
|
1328 | 1339 | @classmethod |
|
1329 | 1340 | def get_by_group_name(cls, group_name, cache=False, |
|
1330 | 1341 | case_insensitive=False): |
|
1331 | 1342 | if case_insensitive: |
|
1332 | 1343 | q = cls.query().filter(func.lower(cls.users_group_name) == |
|
1333 | 1344 | func.lower(group_name)) |
|
1334 | 1345 | |
|
1335 | 1346 | else: |
|
1336 | 1347 | q = cls.query().filter(cls.users_group_name == group_name) |
|
1337 | 1348 | if cache: |
|
1338 | 1349 | q = q.options( |
|
1339 | 1350 | FromCache("sql_cache_short", "get_group_%s" % _hash_key(group_name))) |
|
1340 | 1351 | return q.scalar() |
|
1341 | 1352 | |
|
1342 | 1353 | @classmethod |
|
1343 | 1354 | def get(cls, user_group_id, cache=False): |
|
1355 | if not user_group_id: | |
|
1356 | return | |
|
1357 | ||
|
1344 | 1358 | user_group = cls.query() |
|
1345 | 1359 | if cache: |
|
1346 | 1360 | user_group = user_group.options( |
|
1347 | 1361 | FromCache("sql_cache_short", "get_users_group_%s" % user_group_id)) |
|
1348 | 1362 | return user_group.get(user_group_id) |
|
1349 | 1363 | |
|
1350 | 1364 | def permissions(self, with_admins=True, with_owner=True): |
|
1351 | 1365 | q = UserUserGroupToPerm.query().filter(UserUserGroupToPerm.user_group == self) |
|
1352 | 1366 | q = q.options(joinedload(UserUserGroupToPerm.user_group), |
|
1353 | 1367 | joinedload(UserUserGroupToPerm.user), |
|
1354 | 1368 | joinedload(UserUserGroupToPerm.permission),) |
|
1355 | 1369 | |
|
1356 | 1370 | # get owners and admins and permissions. We do a trick of re-writing |
|
1357 | 1371 | # objects from sqlalchemy to named-tuples due to sqlalchemy session |
|
1358 | 1372 | # has a global reference and changing one object propagates to all |
|
1359 | 1373 | # others. This means if admin is also an owner admin_row that change |
|
1360 | 1374 | # would propagate to both objects |
|
1361 | 1375 | perm_rows = [] |
|
1362 | 1376 | for _usr in q.all(): |
|
1363 | 1377 | usr = AttributeDict(_usr.user.get_dict()) |
|
1364 | 1378 | usr.permission = _usr.permission.permission_name |
|
1365 | 1379 | perm_rows.append(usr) |
|
1366 | 1380 | |
|
1367 | 1381 | # filter the perm rows by 'default' first and then sort them by |
|
1368 | 1382 | # admin,write,read,none permissions sorted again alphabetically in |
|
1369 | 1383 | # each group |
|
1370 | 1384 | perm_rows = sorted(perm_rows, key=display_user_sort) |
|
1371 | 1385 | |
|
1372 | 1386 | _admin_perm = 'usergroup.admin' |
|
1373 | 1387 | owner_row = [] |
|
1374 | 1388 | if with_owner: |
|
1375 | 1389 | usr = AttributeDict(self.user.get_dict()) |
|
1376 | 1390 | usr.owner_row = True |
|
1377 | 1391 | usr.permission = _admin_perm |
|
1378 | 1392 | owner_row.append(usr) |
|
1379 | 1393 | |
|
1380 | 1394 | super_admin_rows = [] |
|
1381 | 1395 | if with_admins: |
|
1382 | 1396 | for usr in User.get_all_super_admins(): |
|
1383 | 1397 | # if this admin is also owner, don't double the record |
|
1384 | 1398 | if usr.user_id == owner_row[0].user_id: |
|
1385 | 1399 | owner_row[0].admin_row = True |
|
1386 | 1400 | else: |
|
1387 | 1401 | usr = AttributeDict(usr.get_dict()) |
|
1388 | 1402 | usr.admin_row = True |
|
1389 | 1403 | usr.permission = _admin_perm |
|
1390 | 1404 | super_admin_rows.append(usr) |
|
1391 | 1405 | |
|
1392 | 1406 | return super_admin_rows + owner_row + perm_rows |
|
1393 | 1407 | |
|
1394 | 1408 | def permission_user_groups(self): |
|
1395 | 1409 | q = UserGroupUserGroupToPerm.query().filter(UserGroupUserGroupToPerm.target_user_group == self) |
|
1396 | 1410 | q = q.options(joinedload(UserGroupUserGroupToPerm.user_group), |
|
1397 | 1411 | joinedload(UserGroupUserGroupToPerm.target_user_group), |
|
1398 | 1412 | joinedload(UserGroupUserGroupToPerm.permission),) |
|
1399 | 1413 | |
|
1400 | 1414 | perm_rows = [] |
|
1401 | 1415 | for _user_group in q.all(): |
|
1402 | 1416 | usr = AttributeDict(_user_group.user_group.get_dict()) |
|
1403 | 1417 | usr.permission = _user_group.permission.permission_name |
|
1404 | 1418 | perm_rows.append(usr) |
|
1405 | 1419 | |
|
1406 | 1420 | perm_rows = sorted(perm_rows, key=display_user_group_sort) |
|
1407 | 1421 | return perm_rows |
|
1408 | 1422 | |
|
1409 | 1423 | def _get_default_perms(self, user_group, suffix=''): |
|
1410 | 1424 | from rhodecode.model.permission import PermissionModel |
|
1411 | 1425 | return PermissionModel().get_default_perms(user_group.users_group_to_perm, suffix) |
|
1412 | 1426 | |
|
1413 | 1427 | def get_default_perms(self, suffix=''): |
|
1414 | 1428 | return self._get_default_perms(self, suffix) |
|
1415 | 1429 | |
|
1416 | 1430 | def get_api_data(self, with_group_members=True, include_secrets=False): |
|
1417 | 1431 | """ |
|
1418 | 1432 | :param include_secrets: See :meth:`User.get_api_data`, this parameter is |
|
1419 | 1433 | basically forwarded. |
|
1420 | 1434 | |
|
1421 | 1435 | """ |
|
1422 | 1436 | user_group = self |
|
1423 | 1437 | data = { |
|
1424 | 1438 | 'users_group_id': user_group.users_group_id, |
|
1425 | 1439 | 'group_name': user_group.users_group_name, |
|
1426 | 1440 | 'group_description': user_group.user_group_description, |
|
1427 | 1441 | 'active': user_group.users_group_active, |
|
1428 | 1442 | 'owner': user_group.user.username, |
|
1429 | 1443 | 'owner_email': user_group.user.email, |
|
1430 | 1444 | } |
|
1431 | 1445 | |
|
1432 | 1446 | if with_group_members: |
|
1433 | 1447 | users = [] |
|
1434 | 1448 | for user in user_group.members: |
|
1435 | 1449 | user = user.user |
|
1436 | 1450 | users.append(user.get_api_data(include_secrets=include_secrets)) |
|
1437 | 1451 | data['users'] = users |
|
1438 | 1452 | |
|
1439 | 1453 | return data |
|
1440 | 1454 | |
|
1441 | 1455 | |
|
1442 | 1456 | class UserGroupMember(Base, BaseModel): |
|
1443 | 1457 | __tablename__ = 'users_groups_members' |
|
1444 | 1458 | __table_args__ = ( |
|
1445 | 1459 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
1446 | 1460 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}, |
|
1447 | 1461 | ) |
|
1448 | 1462 | |
|
1449 | 1463 | users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) |
|
1450 | 1464 | users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None) |
|
1451 | 1465 | user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None) |
|
1452 | 1466 | |
|
1453 | 1467 | user = relationship('User', lazy='joined') |
|
1454 | 1468 | users_group = relationship('UserGroup') |
|
1455 | 1469 | |
|
1456 | 1470 | def __init__(self, gr_id='', u_id=''): |
|
1457 | 1471 | self.users_group_id = gr_id |
|
1458 | 1472 | self.user_id = u_id |
|
1459 | 1473 | |
|
1460 | 1474 | |
|
1461 | 1475 | class RepositoryField(Base, BaseModel): |
|
1462 | 1476 | __tablename__ = 'repositories_fields' |
|
1463 | 1477 | __table_args__ = ( |
|
1464 | 1478 | UniqueConstraint('repository_id', 'field_key'), # no-multi field |
|
1465 | 1479 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
1466 | 1480 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}, |
|
1467 | 1481 | ) |
|
1468 | 1482 | PREFIX = 'ex_' # prefix used in form to not conflict with already existing fields |
|
1469 | 1483 | |
|
1470 | 1484 | repo_field_id = Column("repo_field_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) |
|
1471 | 1485 | repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None) |
|
1472 | 1486 | field_key = Column("field_key", String(250)) |
|
1473 | 1487 | field_label = Column("field_label", String(1024), nullable=False) |
|
1474 | 1488 | field_value = Column("field_value", String(10000), nullable=False) |
|
1475 | 1489 | field_desc = Column("field_desc", String(1024), nullable=False) |
|
1476 | 1490 | field_type = Column("field_type", String(255), nullable=False, unique=None) |
|
1477 | 1491 | created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now) |
|
1478 | 1492 | |
|
1479 | 1493 | repository = relationship('Repository') |
|
1480 | 1494 | |
|
1481 | 1495 | @property |
|
1482 | 1496 | def field_key_prefixed(self): |
|
1483 | 1497 | return 'ex_%s' % self.field_key |
|
1484 | 1498 | |
|
1485 | 1499 | @classmethod |
|
1486 | 1500 | def un_prefix_key(cls, key): |
|
1487 | 1501 | if key.startswith(cls.PREFIX): |
|
1488 | 1502 | return key[len(cls.PREFIX):] |
|
1489 | 1503 | return key |
|
1490 | 1504 | |
|
1491 | 1505 | @classmethod |
|
1492 | 1506 | def get_by_key_name(cls, key, repo): |
|
1493 | 1507 | row = cls.query()\ |
|
1494 | 1508 | .filter(cls.repository == repo)\ |
|
1495 | 1509 | .filter(cls.field_key == key).scalar() |
|
1496 | 1510 | return row |
|
1497 | 1511 | |
|
1498 | 1512 | |
|
1499 | 1513 | class Repository(Base, BaseModel): |
|
1500 | 1514 | __tablename__ = 'repositories' |
|
1501 | 1515 | __table_args__ = ( |
|
1502 | 1516 | Index('r_repo_name_idx', 'repo_name', mysql_length=255), |
|
1503 | 1517 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
1504 | 1518 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}, |
|
1505 | 1519 | ) |
|
1506 | 1520 | DEFAULT_CLONE_URI = '{scheme}://{user}@{netloc}/{repo}' |
|
1507 | 1521 | DEFAULT_CLONE_URI_ID = '{scheme}://{user}@{netloc}/_{repoid}' |
|
1508 | 1522 | |
|
1509 | 1523 | STATE_CREATED = 'repo_state_created' |
|
1510 | 1524 | STATE_PENDING = 'repo_state_pending' |
|
1511 | 1525 | STATE_ERROR = 'repo_state_error' |
|
1512 | 1526 | |
|
1513 | 1527 | LOCK_AUTOMATIC = 'lock_auto' |
|
1514 | 1528 | LOCK_API = 'lock_api' |
|
1515 | 1529 | LOCK_WEB = 'lock_web' |
|
1516 | 1530 | LOCK_PULL = 'lock_pull' |
|
1517 | 1531 | |
|
1518 | 1532 | NAME_SEP = URL_SEP |
|
1519 | 1533 | |
|
1520 | 1534 | repo_id = Column( |
|
1521 | 1535 | "repo_id", Integer(), nullable=False, unique=True, default=None, |
|
1522 | 1536 | primary_key=True) |
|
1523 | 1537 | _repo_name = Column( |
|
1524 | 1538 | "repo_name", Text(), nullable=False, default=None) |
|
1525 | 1539 | _repo_name_hash = Column( |
|
1526 | 1540 | "repo_name_hash", String(255), nullable=False, unique=True) |
|
1527 | 1541 | repo_state = Column("repo_state", String(255), nullable=True) |
|
1528 | 1542 | |
|
1529 | 1543 | clone_uri = Column( |
|
1530 | 1544 | "clone_uri", EncryptedTextValue(), nullable=True, unique=False, |
|
1531 | 1545 | default=None) |
|
1532 | 1546 | repo_type = Column( |
|
1533 | 1547 | "repo_type", String(255), nullable=False, unique=False, default=None) |
|
1534 | 1548 | user_id = Column( |
|
1535 | 1549 | "user_id", Integer(), ForeignKey('users.user_id'), nullable=False, |
|
1536 | 1550 | unique=False, default=None) |
|
1537 | 1551 | private = Column( |
|
1538 | 1552 | "private", Boolean(), nullable=True, unique=None, default=None) |
|
1539 | 1553 | enable_statistics = Column( |
|
1540 | 1554 | "statistics", Boolean(), nullable=True, unique=None, default=True) |
|
1541 | 1555 | enable_downloads = Column( |
|
1542 | 1556 | "downloads", Boolean(), nullable=True, unique=None, default=True) |
|
1543 | 1557 | description = Column( |
|
1544 | 1558 | "description", String(10000), nullable=True, unique=None, default=None) |
|
1545 | 1559 | created_on = Column( |
|
1546 | 1560 | 'created_on', DateTime(timezone=False), nullable=True, unique=None, |
|
1547 | 1561 | default=datetime.datetime.now) |
|
1548 | 1562 | updated_on = Column( |
|
1549 | 1563 | 'updated_on', DateTime(timezone=False), nullable=True, unique=None, |
|
1550 | 1564 | default=datetime.datetime.now) |
|
1551 | 1565 | _landing_revision = Column( |
|
1552 | 1566 | "landing_revision", String(255), nullable=False, unique=False, |
|
1553 | 1567 | default=None) |
|
1554 | 1568 | enable_locking = Column( |
|
1555 | 1569 | "enable_locking", Boolean(), nullable=False, unique=None, |
|
1556 | 1570 | default=False) |
|
1557 | 1571 | _locked = Column( |
|
1558 | 1572 | "locked", String(255), nullable=True, unique=False, default=None) |
|
1559 | 1573 | _changeset_cache = Column( |
|
1560 | 1574 | "changeset_cache", LargeBinary(), nullable=True) # JSON data |
|
1561 | 1575 | |
|
1562 | 1576 | fork_id = Column( |
|
1563 | 1577 | "fork_id", Integer(), ForeignKey('repositories.repo_id'), |
|
1564 | 1578 | nullable=True, unique=False, default=None) |
|
1565 | 1579 | group_id = Column( |
|
1566 | 1580 | "group_id", Integer(), ForeignKey('groups.group_id'), nullable=True, |
|
1567 | 1581 | unique=False, default=None) |
|
1568 | 1582 | |
|
1569 | 1583 | user = relationship('User', lazy='joined') |
|
1570 | 1584 | fork = relationship('Repository', remote_side=repo_id, lazy='joined') |
|
1571 | 1585 | group = relationship('RepoGroup', lazy='joined') |
|
1572 | 1586 | repo_to_perm = relationship( |
|
1573 | 1587 | 'UserRepoToPerm', cascade='all', |
|
1574 | 1588 | order_by='UserRepoToPerm.repo_to_perm_id') |
|
1575 | 1589 | users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all') |
|
1576 | 1590 | stats = relationship('Statistics', cascade='all', uselist=False) |
|
1577 | 1591 | |
|
1578 | 1592 | followers = relationship( |
|
1579 | 1593 | 'UserFollowing', |
|
1580 | 1594 | primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id', |
|
1581 | 1595 | cascade='all') |
|
1582 | 1596 | extra_fields = relationship( |
|
1583 | 1597 | 'RepositoryField', cascade="all, delete, delete-orphan") |
|
1584 | 1598 | logs = relationship('UserLog') |
|
1585 | 1599 | comments = relationship( |
|
1586 | 1600 | 'ChangesetComment', cascade="all, delete, delete-orphan") |
|
1587 | 1601 | pull_requests_source = relationship( |
|
1588 | 1602 | 'PullRequest', |
|
1589 | 1603 | primaryjoin='PullRequest.source_repo_id==Repository.repo_id', |
|
1590 | 1604 | cascade="all, delete, delete-orphan") |
|
1591 | 1605 | pull_requests_target = relationship( |
|
1592 | 1606 | 'PullRequest', |
|
1593 | 1607 | primaryjoin='PullRequest.target_repo_id==Repository.repo_id', |
|
1594 | 1608 | cascade="all, delete, delete-orphan") |
|
1595 | 1609 | ui = relationship('RepoRhodeCodeUi', cascade="all") |
|
1596 | 1610 | settings = relationship('RepoRhodeCodeSetting', cascade="all") |
|
1597 | 1611 | integrations = relationship('Integration', |
|
1598 | 1612 | cascade="all, delete, delete-orphan") |
|
1599 | 1613 | |
|
1600 | 1614 | def __unicode__(self): |
|
1601 | 1615 | return u"<%s('%s:%s')>" % (self.__class__.__name__, self.repo_id, |
|
1602 | 1616 | safe_unicode(self.repo_name)) |
|
1603 | 1617 | |
|
1604 | 1618 | @hybrid_property |
|
1605 | 1619 | def description_safe(self): |
|
1606 | 1620 | from rhodecode.lib import helpers as h |
|
1607 | 1621 | return h.escape(self.description) |
|
1608 | 1622 | |
|
1609 | 1623 | @hybrid_property |
|
1610 | 1624 | def landing_rev(self): |
|
1611 | 1625 | # always should return [rev_type, rev] |
|
1612 | 1626 | if self._landing_revision: |
|
1613 | 1627 | _rev_info = self._landing_revision.split(':') |
|
1614 | 1628 | if len(_rev_info) < 2: |
|
1615 | 1629 | _rev_info.insert(0, 'rev') |
|
1616 | 1630 | return [_rev_info[0], _rev_info[1]] |
|
1617 | 1631 | return [None, None] |
|
1618 | 1632 | |
|
1619 | 1633 | @landing_rev.setter |
|
1620 | 1634 | def landing_rev(self, val): |
|
1621 | 1635 | if ':' not in val: |
|
1622 | 1636 | raise ValueError('value must be delimited with `:` and consist ' |
|
1623 | 1637 | 'of <rev_type>:<rev>, got %s instead' % val) |
|
1624 | 1638 | self._landing_revision = val |
|
1625 | 1639 | |
|
1626 | 1640 | @hybrid_property |
|
1627 | 1641 | def locked(self): |
|
1628 | 1642 | if self._locked: |
|
1629 | 1643 | user_id, timelocked, reason = self._locked.split(':') |
|
1630 | 1644 | lock_values = int(user_id), timelocked, reason |
|
1631 | 1645 | else: |
|
1632 | 1646 | lock_values = [None, None, None] |
|
1633 | 1647 | return lock_values |
|
1634 | 1648 | |
|
1635 | 1649 | @locked.setter |
|
1636 | 1650 | def locked(self, val): |
|
1637 | 1651 | if val and isinstance(val, (list, tuple)): |
|
1638 | 1652 | self._locked = ':'.join(map(str, val)) |
|
1639 | 1653 | else: |
|
1640 | 1654 | self._locked = None |
|
1641 | 1655 | |
|
1642 | 1656 | @hybrid_property |
|
1643 | 1657 | def changeset_cache(self): |
|
1644 | 1658 | from rhodecode.lib.vcs.backends.base import EmptyCommit |
|
1645 | 1659 | dummy = EmptyCommit().__json__() |
|
1646 | 1660 | if not self._changeset_cache: |
|
1647 | 1661 | return dummy |
|
1648 | 1662 | try: |
|
1649 | 1663 | return json.loads(self._changeset_cache) |
|
1650 | 1664 | except TypeError: |
|
1651 | 1665 | return dummy |
|
1652 | 1666 | except Exception: |
|
1653 | 1667 | log.error(traceback.format_exc()) |
|
1654 | 1668 | return dummy |
|
1655 | 1669 | |
|
1656 | 1670 | @changeset_cache.setter |
|
1657 | 1671 | def changeset_cache(self, val): |
|
1658 | 1672 | try: |
|
1659 | 1673 | self._changeset_cache = json.dumps(val) |
|
1660 | 1674 | except Exception: |
|
1661 | 1675 | log.error(traceback.format_exc()) |
|
1662 | 1676 | |
|
1663 | 1677 | @hybrid_property |
|
1664 | 1678 | def repo_name(self): |
|
1665 | 1679 | return self._repo_name |
|
1666 | 1680 | |
|
1667 | 1681 | @repo_name.setter |
|
1668 | 1682 | def repo_name(self, value): |
|
1669 | 1683 | self._repo_name = value |
|
1670 | 1684 | self._repo_name_hash = hashlib.sha1(safe_str(value)).hexdigest() |
|
1671 | 1685 | |
|
1672 | 1686 | @classmethod |
|
1673 | 1687 | def normalize_repo_name(cls, repo_name): |
|
1674 | 1688 | """ |
|
1675 | 1689 | Normalizes os specific repo_name to the format internally stored inside |
|
1676 | 1690 | database using URL_SEP |
|
1677 | 1691 | |
|
1678 | 1692 | :param cls: |
|
1679 | 1693 | :param repo_name: |
|
1680 | 1694 | """ |
|
1681 | 1695 | return cls.NAME_SEP.join(repo_name.split(os.sep)) |
|
1682 | 1696 | |
|
1683 | 1697 | @classmethod |
|
1684 | 1698 | def get_by_repo_name(cls, repo_name, cache=False, identity_cache=False): |
|
1685 | 1699 | session = Session() |
|
1686 | 1700 | q = session.query(cls).filter(cls.repo_name == repo_name) |
|
1687 | 1701 | |
|
1688 | 1702 | if cache: |
|
1689 | 1703 | if identity_cache: |
|
1690 | 1704 | val = cls.identity_cache(session, 'repo_name', repo_name) |
|
1691 | 1705 | if val: |
|
1692 | 1706 | return val |
|
1693 | 1707 | else: |
|
1694 | 1708 | cache_key = "get_repo_by_name_%s" % _hash_key(repo_name) |
|
1695 | 1709 | q = q.options( |
|
1696 | 1710 | FromCache("sql_cache_short", cache_key)) |
|
1697 | 1711 | |
|
1698 | 1712 | return q.scalar() |
|
1699 | 1713 | |
|
1700 | 1714 | @classmethod |
|
1701 | 1715 | def get_by_full_path(cls, repo_full_path): |
|
1702 | 1716 | repo_name = repo_full_path.split(cls.base_path(), 1)[-1] |
|
1703 | 1717 | repo_name = cls.normalize_repo_name(repo_name) |
|
1704 | 1718 | return cls.get_by_repo_name(repo_name.strip(URL_SEP)) |
|
1705 | 1719 | |
|
1706 | 1720 | @classmethod |
|
1707 | 1721 | def get_repo_forks(cls, repo_id): |
|
1708 | 1722 | return cls.query().filter(Repository.fork_id == repo_id) |
|
1709 | 1723 | |
|
1710 | 1724 | @classmethod |
|
1711 | 1725 | def base_path(cls): |
|
1712 | 1726 | """ |
|
1713 | 1727 | Returns base path when all repos are stored |
|
1714 | 1728 | |
|
1715 | 1729 | :param cls: |
|
1716 | 1730 | """ |
|
1717 | 1731 | q = Session().query(RhodeCodeUi)\ |
|
1718 | 1732 | .filter(RhodeCodeUi.ui_key == cls.NAME_SEP) |
|
1719 | 1733 | q = q.options(FromCache("sql_cache_short", "repository_repo_path")) |
|
1720 | 1734 | return q.one().ui_value |
|
1721 | 1735 | |
|
1722 | 1736 | @classmethod |
|
1723 | 1737 | def is_valid(cls, repo_name): |
|
1724 | 1738 | """ |
|
1725 | 1739 | returns True if given repo name is a valid filesystem repository |
|
1726 | 1740 | |
|
1727 | 1741 | :param cls: |
|
1728 | 1742 | :param repo_name: |
|
1729 | 1743 | """ |
|
1730 | 1744 | from rhodecode.lib.utils import is_valid_repo |
|
1731 | 1745 | |
|
1732 | 1746 | return is_valid_repo(repo_name, cls.base_path()) |
|
1733 | 1747 | |
|
1734 | 1748 | @classmethod |
|
1735 | 1749 | def get_all_repos(cls, user_id=Optional(None), group_id=Optional(None), |
|
1736 | 1750 | case_insensitive=True): |
|
1737 | 1751 | q = Repository.query() |
|
1738 | 1752 | |
|
1739 | 1753 | if not isinstance(user_id, Optional): |
|
1740 | 1754 | q = q.filter(Repository.user_id == user_id) |
|
1741 | 1755 | |
|
1742 | 1756 | if not isinstance(group_id, Optional): |
|
1743 | 1757 | q = q.filter(Repository.group_id == group_id) |
|
1744 | 1758 | |
|
1745 | 1759 | if case_insensitive: |
|
1746 | 1760 | q = q.order_by(func.lower(Repository.repo_name)) |
|
1747 | 1761 | else: |
|
1748 | 1762 | q = q.order_by(Repository.repo_name) |
|
1749 | 1763 | return q.all() |
|
1750 | 1764 | |
|
1751 | 1765 | @property |
|
1752 | 1766 | def forks(self): |
|
1753 | 1767 | """ |
|
1754 | 1768 | Return forks of this repo |
|
1755 | 1769 | """ |
|
1756 | 1770 | return Repository.get_repo_forks(self.repo_id) |
|
1757 | 1771 | |
|
1758 | 1772 | @property |
|
1759 | 1773 | def parent(self): |
|
1760 | 1774 | """ |
|
1761 | 1775 | Returns fork parent |
|
1762 | 1776 | """ |
|
1763 | 1777 | return self.fork |
|
1764 | 1778 | |
|
1765 | 1779 | @property |
|
1766 | 1780 | def just_name(self): |
|
1767 | 1781 | return self.repo_name.split(self.NAME_SEP)[-1] |
|
1768 | 1782 | |
|
1769 | 1783 | @property |
|
1770 | 1784 | def groups_with_parents(self): |
|
1771 | 1785 | groups = [] |
|
1772 | 1786 | if self.group is None: |
|
1773 | 1787 | return groups |
|
1774 | 1788 | |
|
1775 | 1789 | cur_gr = self.group |
|
1776 | 1790 | groups.insert(0, cur_gr) |
|
1777 | 1791 | while 1: |
|
1778 | 1792 | gr = getattr(cur_gr, 'parent_group', None) |
|
1779 | 1793 | cur_gr = cur_gr.parent_group |
|
1780 | 1794 | if gr is None: |
|
1781 | 1795 | break |
|
1782 | 1796 | groups.insert(0, gr) |
|
1783 | 1797 | |
|
1784 | 1798 | return groups |
|
1785 | 1799 | |
|
1786 | 1800 | @property |
|
1787 | 1801 | def groups_and_repo(self): |
|
1788 | 1802 | return self.groups_with_parents, self |
|
1789 | 1803 | |
|
1790 | 1804 | @LazyProperty |
|
1791 | 1805 | def repo_path(self): |
|
1792 | 1806 | """ |
|
1793 | 1807 | Returns base full path for that repository means where it actually |
|
1794 | 1808 | exists on a filesystem |
|
1795 | 1809 | """ |
|
1796 | 1810 | q = Session().query(RhodeCodeUi).filter( |
|
1797 | 1811 | RhodeCodeUi.ui_key == self.NAME_SEP) |
|
1798 | 1812 | q = q.options(FromCache("sql_cache_short", "repository_repo_path")) |
|
1799 | 1813 | return q.one().ui_value |
|
1800 | 1814 | |
|
1801 | 1815 | @property |
|
1802 | 1816 | def repo_full_path(self): |
|
1803 | 1817 | p = [self.repo_path] |
|
1804 | 1818 | # we need to split the name by / since this is how we store the |
|
1805 | 1819 | # names in the database, but that eventually needs to be converted |
|
1806 | 1820 | # into a valid system path |
|
1807 | 1821 | p += self.repo_name.split(self.NAME_SEP) |
|
1808 | 1822 | return os.path.join(*map(safe_unicode, p)) |
|
1809 | 1823 | |
|
1810 | 1824 | @property |
|
1811 | 1825 | def cache_keys(self): |
|
1812 | 1826 | """ |
|
1813 | 1827 | Returns associated cache keys for that repo |
|
1814 | 1828 | """ |
|
1815 | 1829 | return CacheKey.query()\ |
|
1816 | 1830 | .filter(CacheKey.cache_args == self.repo_name)\ |
|
1817 | 1831 | .order_by(CacheKey.cache_key)\ |
|
1818 | 1832 | .all() |
|
1819 | 1833 | |
|
1820 | 1834 | def get_new_name(self, repo_name): |
|
1821 | 1835 | """ |
|
1822 | 1836 | returns new full repository name based on assigned group and new new |
|
1823 | 1837 | |
|
1824 | 1838 | :param group_name: |
|
1825 | 1839 | """ |
|
1826 | 1840 | path_prefix = self.group.full_path_splitted if self.group else [] |
|
1827 | 1841 | return self.NAME_SEP.join(path_prefix + [repo_name]) |
|
1828 | 1842 | |
|
1829 | 1843 | @property |
|
1830 | 1844 | def _config(self): |
|
1831 | 1845 | """ |
|
1832 | 1846 | Returns db based config object. |
|
1833 | 1847 | """ |
|
1834 | 1848 | from rhodecode.lib.utils import make_db_config |
|
1835 | 1849 | return make_db_config(clear_session=False, repo=self) |
|
1836 | 1850 | |
|
1837 | 1851 | def permissions(self, with_admins=True, with_owner=True): |
|
1838 | 1852 | q = UserRepoToPerm.query().filter(UserRepoToPerm.repository == self) |
|
1839 | 1853 | q = q.options(joinedload(UserRepoToPerm.repository), |
|
1840 | 1854 | joinedload(UserRepoToPerm.user), |
|
1841 | 1855 | joinedload(UserRepoToPerm.permission),) |
|
1842 | 1856 | |
|
1843 | 1857 | # get owners and admins and permissions. We do a trick of re-writing |
|
1844 | 1858 | # objects from sqlalchemy to named-tuples due to sqlalchemy session |
|
1845 | 1859 | # has a global reference and changing one object propagates to all |
|
1846 | 1860 | # others. This means if admin is also an owner admin_row that change |
|
1847 | 1861 | # would propagate to both objects |
|
1848 | 1862 | perm_rows = [] |
|
1849 | 1863 | for _usr in q.all(): |
|
1850 | 1864 | usr = AttributeDict(_usr.user.get_dict()) |
|
1851 | 1865 | usr.permission = _usr.permission.permission_name |
|
1852 | 1866 | perm_rows.append(usr) |
|
1853 | 1867 | |
|
1854 | 1868 | # filter the perm rows by 'default' first and then sort them by |
|
1855 | 1869 | # admin,write,read,none permissions sorted again alphabetically in |
|
1856 | 1870 | # each group |
|
1857 | 1871 | perm_rows = sorted(perm_rows, key=display_user_sort) |
|
1858 | 1872 | |
|
1859 | 1873 | _admin_perm = 'repository.admin' |
|
1860 | 1874 | owner_row = [] |
|
1861 | 1875 | if with_owner: |
|
1862 | 1876 | usr = AttributeDict(self.user.get_dict()) |
|
1863 | 1877 | usr.owner_row = True |
|
1864 | 1878 | usr.permission = _admin_perm |
|
1865 | 1879 | owner_row.append(usr) |
|
1866 | 1880 | |
|
1867 | 1881 | super_admin_rows = [] |
|
1868 | 1882 | if with_admins: |
|
1869 | 1883 | for usr in User.get_all_super_admins(): |
|
1870 | 1884 | # if this admin is also owner, don't double the record |
|
1871 | 1885 | if usr.user_id == owner_row[0].user_id: |
|
1872 | 1886 | owner_row[0].admin_row = True |
|
1873 | 1887 | else: |
|
1874 | 1888 | usr = AttributeDict(usr.get_dict()) |
|
1875 | 1889 | usr.admin_row = True |
|
1876 | 1890 | usr.permission = _admin_perm |
|
1877 | 1891 | super_admin_rows.append(usr) |
|
1878 | 1892 | |
|
1879 | 1893 | return super_admin_rows + owner_row + perm_rows |
|
1880 | 1894 | |
|
1881 | 1895 | def permission_user_groups(self): |
|
1882 | 1896 | q = UserGroupRepoToPerm.query().filter( |
|
1883 | 1897 | UserGroupRepoToPerm.repository == self) |
|
1884 | 1898 | q = q.options(joinedload(UserGroupRepoToPerm.repository), |
|
1885 | 1899 | joinedload(UserGroupRepoToPerm.users_group), |
|
1886 | 1900 | joinedload(UserGroupRepoToPerm.permission),) |
|
1887 | 1901 | |
|
1888 | 1902 | perm_rows = [] |
|
1889 | 1903 | for _user_group in q.all(): |
|
1890 | 1904 | usr = AttributeDict(_user_group.users_group.get_dict()) |
|
1891 | 1905 | usr.permission = _user_group.permission.permission_name |
|
1892 | 1906 | perm_rows.append(usr) |
|
1893 | 1907 | |
|
1894 | 1908 | perm_rows = sorted(perm_rows, key=display_user_group_sort) |
|
1895 | 1909 | return perm_rows |
|
1896 | 1910 | |
|
1897 | 1911 | def get_api_data(self, include_secrets=False): |
|
1898 | 1912 | """ |
|
1899 | 1913 | Common function for generating repo api data |
|
1900 | 1914 | |
|
1901 | 1915 | :param include_secrets: See :meth:`User.get_api_data`. |
|
1902 | 1916 | |
|
1903 | 1917 | """ |
|
1904 | 1918 | # TODO: mikhail: Here there is an anti-pattern, we probably need to |
|
1905 | 1919 | # move this methods on models level. |
|
1906 | 1920 | from rhodecode.model.settings import SettingsModel |
|
1907 | 1921 | from rhodecode.model.repo import RepoModel |
|
1908 | 1922 | |
|
1909 | 1923 | repo = self |
|
1910 | 1924 | _user_id, _time, _reason = self.locked |
|
1911 | 1925 | |
|
1912 | 1926 | data = { |
|
1913 | 1927 | 'repo_id': repo.repo_id, |
|
1914 | 1928 | 'repo_name': repo.repo_name, |
|
1915 | 1929 | 'repo_type': repo.repo_type, |
|
1916 | 1930 | 'clone_uri': repo.clone_uri or '', |
|
1917 | 1931 | 'url': RepoModel().get_url(self), |
|
1918 | 1932 | 'private': repo.private, |
|
1919 | 1933 | 'created_on': repo.created_on, |
|
1920 | 1934 | 'description': repo.description_safe, |
|
1921 | 1935 | 'landing_rev': repo.landing_rev, |
|
1922 | 1936 | 'owner': repo.user.username, |
|
1923 | 1937 | 'fork_of': repo.fork.repo_name if repo.fork else None, |
|
1924 | 1938 | 'fork_of_id': repo.fork.repo_id if repo.fork else None, |
|
1925 | 1939 | 'enable_statistics': repo.enable_statistics, |
|
1926 | 1940 | 'enable_locking': repo.enable_locking, |
|
1927 | 1941 | 'enable_downloads': repo.enable_downloads, |
|
1928 | 1942 | 'last_changeset': repo.changeset_cache, |
|
1929 | 1943 | 'locked_by': User.get(_user_id).get_api_data( |
|
1930 | 1944 | include_secrets=include_secrets) if _user_id else None, |
|
1931 | 1945 | 'locked_date': time_to_datetime(_time) if _time else None, |
|
1932 | 1946 | 'lock_reason': _reason if _reason else None, |
|
1933 | 1947 | } |
|
1934 | 1948 | |
|
1935 | 1949 | # TODO: mikhail: should be per-repo settings here |
|
1936 | 1950 | rc_config = SettingsModel().get_all_settings() |
|
1937 | 1951 | repository_fields = str2bool( |
|
1938 | 1952 | rc_config.get('rhodecode_repository_fields')) |
|
1939 | 1953 | if repository_fields: |
|
1940 | 1954 | for f in self.extra_fields: |
|
1941 | 1955 | data[f.field_key_prefixed] = f.field_value |
|
1942 | 1956 | |
|
1943 | 1957 | return data |
|
1944 | 1958 | |
|
1945 | 1959 | @classmethod |
|
1946 | 1960 | def lock(cls, repo, user_id, lock_time=None, lock_reason=None): |
|
1947 | 1961 | if not lock_time: |
|
1948 | 1962 | lock_time = time.time() |
|
1949 | 1963 | if not lock_reason: |
|
1950 | 1964 | lock_reason = cls.LOCK_AUTOMATIC |
|
1951 | 1965 | repo.locked = [user_id, lock_time, lock_reason] |
|
1952 | 1966 | Session().add(repo) |
|
1953 | 1967 | Session().commit() |
|
1954 | 1968 | |
|
1955 | 1969 | @classmethod |
|
1956 | 1970 | def unlock(cls, repo): |
|
1957 | 1971 | repo.locked = None |
|
1958 | 1972 | Session().add(repo) |
|
1959 | 1973 | Session().commit() |
|
1960 | 1974 | |
|
1961 | 1975 | @classmethod |
|
1962 | 1976 | def getlock(cls, repo): |
|
1963 | 1977 | return repo.locked |
|
1964 | 1978 | |
|
1965 | 1979 | def is_user_lock(self, user_id): |
|
1966 | 1980 | if self.lock[0]: |
|
1967 | 1981 | lock_user_id = safe_int(self.lock[0]) |
|
1968 | 1982 | user_id = safe_int(user_id) |
|
1969 | 1983 | # both are ints, and they are equal |
|
1970 | 1984 | return all([lock_user_id, user_id]) and lock_user_id == user_id |
|
1971 | 1985 | |
|
1972 | 1986 | return False |
|
1973 | 1987 | |
|
1974 | 1988 | def get_locking_state(self, action, user_id, only_when_enabled=True): |
|
1975 | 1989 | """ |
|
1976 | 1990 | Checks locking on this repository, if locking is enabled and lock is |
|
1977 | 1991 | present returns a tuple of make_lock, locked, locked_by. |
|
1978 | 1992 | make_lock can have 3 states None (do nothing) True, make lock |
|
1979 | 1993 | False release lock, This value is later propagated to hooks, which |
|
1980 | 1994 | do the locking. Think about this as signals passed to hooks what to do. |
|
1981 | 1995 | |
|
1982 | 1996 | """ |
|
1983 | 1997 | # TODO: johbo: This is part of the business logic and should be moved |
|
1984 | 1998 | # into the RepositoryModel. |
|
1985 | 1999 | |
|
1986 | 2000 | if action not in ('push', 'pull'): |
|
1987 | 2001 | raise ValueError("Invalid action value: %s" % repr(action)) |
|
1988 | 2002 | |
|
1989 | 2003 | # defines if locked error should be thrown to user |
|
1990 | 2004 | currently_locked = False |
|
1991 | 2005 | # defines if new lock should be made, tri-state |
|
1992 | 2006 | make_lock = None |
|
1993 | 2007 | repo = self |
|
1994 | 2008 | user = User.get(user_id) |
|
1995 | 2009 | |
|
1996 | 2010 | lock_info = repo.locked |
|
1997 | 2011 | |
|
1998 | 2012 | if repo and (repo.enable_locking or not only_when_enabled): |
|
1999 | 2013 | if action == 'push': |
|
2000 | 2014 | # check if it's already locked !, if it is compare users |
|
2001 | 2015 | locked_by_user_id = lock_info[0] |
|
2002 | 2016 | if user.user_id == locked_by_user_id: |
|
2003 | 2017 | log.debug( |
|
2004 | 2018 | 'Got `push` action from user %s, now unlocking', user) |
|
2005 | 2019 | # unlock if we have push from user who locked |
|
2006 | 2020 | make_lock = False |
|
2007 | 2021 | else: |
|
2008 | 2022 | # we're not the same user who locked, ban with |
|
2009 | 2023 | # code defined in settings (default is 423 HTTP Locked) ! |
|
2010 | 2024 | log.debug('Repo %s is currently locked by %s', repo, user) |
|
2011 | 2025 | currently_locked = True |
|
2012 | 2026 | elif action == 'pull': |
|
2013 | 2027 | # [0] user [1] date |
|
2014 | 2028 | if lock_info[0] and lock_info[1]: |
|
2015 | 2029 | log.debug('Repo %s is currently locked by %s', repo, user) |
|
2016 | 2030 | currently_locked = True |
|
2017 | 2031 | else: |
|
2018 | 2032 | log.debug('Setting lock on repo %s by %s', repo, user) |
|
2019 | 2033 | make_lock = True |
|
2020 | 2034 | |
|
2021 | 2035 | else: |
|
2022 | 2036 | log.debug('Repository %s do not have locking enabled', repo) |
|
2023 | 2037 | |
|
2024 | 2038 | log.debug('FINAL locking values make_lock:%s,locked:%s,locked_by:%s', |
|
2025 | 2039 | make_lock, currently_locked, lock_info) |
|
2026 | 2040 | |
|
2027 | 2041 | from rhodecode.lib.auth import HasRepoPermissionAny |
|
2028 | 2042 | perm_check = HasRepoPermissionAny('repository.write', 'repository.admin') |
|
2029 | 2043 | if make_lock and not perm_check(repo_name=repo.repo_name, user=user): |
|
2030 | 2044 | # if we don't have at least write permission we cannot make a lock |
|
2031 | 2045 | log.debug('lock state reset back to FALSE due to lack ' |
|
2032 | 2046 | 'of at least read permission') |
|
2033 | 2047 | make_lock = False |
|
2034 | 2048 | |
|
2035 | 2049 | return make_lock, currently_locked, lock_info |
|
2036 | 2050 | |
|
2037 | 2051 | @property |
|
2038 | 2052 | def last_db_change(self): |
|
2039 | 2053 | return self.updated_on |
|
2040 | 2054 | |
|
2041 | 2055 | @property |
|
2042 | 2056 | def clone_uri_hidden(self): |
|
2043 | 2057 | clone_uri = self.clone_uri |
|
2044 | 2058 | if clone_uri: |
|
2045 | 2059 | import urlobject |
|
2046 | 2060 | url_obj = urlobject.URLObject(cleaned_uri(clone_uri)) |
|
2047 | 2061 | if url_obj.password: |
|
2048 | 2062 | clone_uri = url_obj.with_password('*****') |
|
2049 | 2063 | return clone_uri |
|
2050 | 2064 | |
|
2051 | 2065 | def clone_url(self, **override): |
|
2052 | 2066 | from rhodecode.model.settings import SettingsModel |
|
2053 | 2067 | |
|
2054 | 2068 | uri_tmpl = None |
|
2055 | 2069 | if 'with_id' in override: |
|
2056 | 2070 | uri_tmpl = self.DEFAULT_CLONE_URI_ID |
|
2057 | 2071 | del override['with_id'] |
|
2058 | 2072 | |
|
2059 | 2073 | if 'uri_tmpl' in override: |
|
2060 | 2074 | uri_tmpl = override['uri_tmpl'] |
|
2061 | 2075 | del override['uri_tmpl'] |
|
2062 | 2076 | |
|
2063 | 2077 | # we didn't override our tmpl from **overrides |
|
2064 | 2078 | if not uri_tmpl: |
|
2065 | 2079 | rc_config = SettingsModel().get_all_settings(cache=True) |
|
2066 | 2080 | uri_tmpl = rc_config.get( |
|
2067 | 2081 | 'rhodecode_clone_uri_tmpl') or self.DEFAULT_CLONE_URI |
|
2068 | 2082 | |
|
2069 | 2083 | request = get_current_request() |
|
2070 | 2084 | return get_clone_url(request=request, |
|
2071 | 2085 | uri_tmpl=uri_tmpl, |
|
2072 | 2086 | repo_name=self.repo_name, |
|
2073 | 2087 | repo_id=self.repo_id, **override) |
|
2074 | 2088 | |
|
2075 | 2089 | def set_state(self, state): |
|
2076 | 2090 | self.repo_state = state |
|
2077 | 2091 | Session().add(self) |
|
2078 | 2092 | #========================================================================== |
|
2079 | 2093 | # SCM PROPERTIES |
|
2080 | 2094 | #========================================================================== |
|
2081 | 2095 | |
|
2082 | 2096 | def get_commit(self, commit_id=None, commit_idx=None, pre_load=None): |
|
2083 | 2097 | return get_commit_safe( |
|
2084 | 2098 | self.scm_instance(), commit_id, commit_idx, pre_load=pre_load) |
|
2085 | 2099 | |
|
2086 | 2100 | def get_changeset(self, rev=None, pre_load=None): |
|
2087 | 2101 | warnings.warn("Use get_commit", DeprecationWarning) |
|
2088 | 2102 | commit_id = None |
|
2089 | 2103 | commit_idx = None |
|
2090 | 2104 | if isinstance(rev, basestring): |
|
2091 | 2105 | commit_id = rev |
|
2092 | 2106 | else: |
|
2093 | 2107 | commit_idx = rev |
|
2094 | 2108 | return self.get_commit(commit_id=commit_id, commit_idx=commit_idx, |
|
2095 | 2109 | pre_load=pre_load) |
|
2096 | 2110 | |
|
2097 | 2111 | def get_landing_commit(self): |
|
2098 | 2112 | """ |
|
2099 | 2113 | Returns landing commit, or if that doesn't exist returns the tip |
|
2100 | 2114 | """ |
|
2101 | 2115 | _rev_type, _rev = self.landing_rev |
|
2102 | 2116 | commit = self.get_commit(_rev) |
|
2103 | 2117 | if isinstance(commit, EmptyCommit): |
|
2104 | 2118 | return self.get_commit() |
|
2105 | 2119 | return commit |
|
2106 | 2120 | |
|
2107 | 2121 | def update_commit_cache(self, cs_cache=None, config=None): |
|
2108 | 2122 | """ |
|
2109 | 2123 | Update cache of last changeset for repository, keys should be:: |
|
2110 | 2124 | |
|
2111 | 2125 | short_id |
|
2112 | 2126 | raw_id |
|
2113 | 2127 | revision |
|
2114 | 2128 | parents |
|
2115 | 2129 | message |
|
2116 | 2130 | date |
|
2117 | 2131 | author |
|
2118 | 2132 | |
|
2119 | 2133 | :param cs_cache: |
|
2120 | 2134 | """ |
|
2121 | 2135 | from rhodecode.lib.vcs.backends.base import BaseChangeset |
|
2122 | 2136 | if cs_cache is None: |
|
2123 | 2137 | # use no-cache version here |
|
2124 | 2138 | scm_repo = self.scm_instance(cache=False, config=config) |
|
2125 | 2139 | if scm_repo: |
|
2126 | 2140 | cs_cache = scm_repo.get_commit( |
|
2127 | 2141 | pre_load=["author", "date", "message", "parents"]) |
|
2128 | 2142 | else: |
|
2129 | 2143 | cs_cache = EmptyCommit() |
|
2130 | 2144 | |
|
2131 | 2145 | if isinstance(cs_cache, BaseChangeset): |
|
2132 | 2146 | cs_cache = cs_cache.__json__() |
|
2133 | 2147 | |
|
2134 | 2148 | def is_outdated(new_cs_cache): |
|
2135 | 2149 | if (new_cs_cache['raw_id'] != self.changeset_cache['raw_id'] or |
|
2136 | 2150 | new_cs_cache['revision'] != self.changeset_cache['revision']): |
|
2137 | 2151 | return True |
|
2138 | 2152 | return False |
|
2139 | 2153 | |
|
2140 | 2154 | # check if we have maybe already latest cached revision |
|
2141 | 2155 | if is_outdated(cs_cache) or not self.changeset_cache: |
|
2142 | 2156 | _default = datetime.datetime.fromtimestamp(0) |
|
2143 | 2157 | last_change = cs_cache.get('date') or _default |
|
2144 | 2158 | log.debug('updated repo %s with new cs cache %s', |
|
2145 | 2159 | self.repo_name, cs_cache) |
|
2146 | 2160 | self.updated_on = last_change |
|
2147 | 2161 | self.changeset_cache = cs_cache |
|
2148 | 2162 | Session().add(self) |
|
2149 | 2163 | Session().commit() |
|
2150 | 2164 | else: |
|
2151 | 2165 | log.debug('Skipping update_commit_cache for repo:`%s` ' |
|
2152 | 2166 | 'commit already with latest changes', self.repo_name) |
|
2153 | 2167 | |
|
2154 | 2168 | @property |
|
2155 | 2169 | def tip(self): |
|
2156 | 2170 | return self.get_commit('tip') |
|
2157 | 2171 | |
|
2158 | 2172 | @property |
|
2159 | 2173 | def author(self): |
|
2160 | 2174 | return self.tip.author |
|
2161 | 2175 | |
|
2162 | 2176 | @property |
|
2163 | 2177 | def last_change(self): |
|
2164 | 2178 | return self.scm_instance().last_change |
|
2165 | 2179 | |
|
2166 | 2180 | def get_comments(self, revisions=None): |
|
2167 | 2181 | """ |
|
2168 | 2182 | Returns comments for this repository grouped by revisions |
|
2169 | 2183 | |
|
2170 | 2184 | :param revisions: filter query by revisions only |
|
2171 | 2185 | """ |
|
2172 | 2186 | cmts = ChangesetComment.query()\ |
|
2173 | 2187 | .filter(ChangesetComment.repo == self) |
|
2174 | 2188 | if revisions: |
|
2175 | 2189 | cmts = cmts.filter(ChangesetComment.revision.in_(revisions)) |
|
2176 | 2190 | grouped = collections.defaultdict(list) |
|
2177 | 2191 | for cmt in cmts.all(): |
|
2178 | 2192 | grouped[cmt.revision].append(cmt) |
|
2179 | 2193 | return grouped |
|
2180 | 2194 | |
|
2181 | 2195 | def statuses(self, revisions=None): |
|
2182 | 2196 | """ |
|
2183 | 2197 | Returns statuses for this repository |
|
2184 | 2198 | |
|
2185 | 2199 | :param revisions: list of revisions to get statuses for |
|
2186 | 2200 | """ |
|
2187 | 2201 | statuses = ChangesetStatus.query()\ |
|
2188 | 2202 | .filter(ChangesetStatus.repo == self)\ |
|
2189 | 2203 | .filter(ChangesetStatus.version == 0) |
|
2190 | 2204 | |
|
2191 | 2205 | if revisions: |
|
2192 | 2206 | # Try doing the filtering in chunks to avoid hitting limits |
|
2193 | 2207 | size = 500 |
|
2194 | 2208 | status_results = [] |
|
2195 | 2209 | for chunk in xrange(0, len(revisions), size): |
|
2196 | 2210 | status_results += statuses.filter( |
|
2197 | 2211 | ChangesetStatus.revision.in_( |
|
2198 | 2212 | revisions[chunk: chunk+size]) |
|
2199 | 2213 | ).all() |
|
2200 | 2214 | else: |
|
2201 | 2215 | status_results = statuses.all() |
|
2202 | 2216 | |
|
2203 | 2217 | grouped = {} |
|
2204 | 2218 | |
|
2205 | 2219 | # maybe we have open new pullrequest without a status? |
|
2206 | 2220 | stat = ChangesetStatus.STATUS_UNDER_REVIEW |
|
2207 | 2221 | status_lbl = ChangesetStatus.get_status_lbl(stat) |
|
2208 | 2222 | for pr in PullRequest.query().filter(PullRequest.source_repo == self).all(): |
|
2209 | 2223 | for rev in pr.revisions: |
|
2210 | 2224 | pr_id = pr.pull_request_id |
|
2211 | 2225 | pr_repo = pr.target_repo.repo_name |
|
2212 | 2226 | grouped[rev] = [stat, status_lbl, pr_id, pr_repo] |
|
2213 | 2227 | |
|
2214 | 2228 | for stat in status_results: |
|
2215 | 2229 | pr_id = pr_repo = None |
|
2216 | 2230 | if stat.pull_request: |
|
2217 | 2231 | pr_id = stat.pull_request.pull_request_id |
|
2218 | 2232 | pr_repo = stat.pull_request.target_repo.repo_name |
|
2219 | 2233 | grouped[stat.revision] = [str(stat.status), stat.status_lbl, |
|
2220 | 2234 | pr_id, pr_repo] |
|
2221 | 2235 | return grouped |
|
2222 | 2236 | |
|
2223 | 2237 | # ========================================================================== |
|
2224 | 2238 | # SCM CACHE INSTANCE |
|
2225 | 2239 | # ========================================================================== |
|
2226 | 2240 | |
|
2227 | 2241 | def scm_instance(self, **kwargs): |
|
2228 | 2242 | import rhodecode |
|
2229 | 2243 | |
|
2230 | 2244 | # Passing a config will not hit the cache currently only used |
|
2231 | 2245 | # for repo2dbmapper |
|
2232 | 2246 | config = kwargs.pop('config', None) |
|
2233 | 2247 | cache = kwargs.pop('cache', None) |
|
2234 | 2248 | full_cache = str2bool(rhodecode.CONFIG.get('vcs_full_cache')) |
|
2235 | 2249 | # if cache is NOT defined use default global, else we have a full |
|
2236 | 2250 | # control over cache behaviour |
|
2237 | 2251 | if cache is None and full_cache and not config: |
|
2238 | 2252 | return self._get_instance_cached() |
|
2239 | 2253 | return self._get_instance(cache=bool(cache), config=config) |
|
2240 | 2254 | |
|
2241 | 2255 | def _get_instance_cached(self): |
|
2242 | 2256 | @cache_region('long_term') |
|
2243 | 2257 | def _get_repo(cache_key): |
|
2244 | 2258 | return self._get_instance() |
|
2245 | 2259 | |
|
2246 | 2260 | invalidator_context = CacheKey.repo_context_cache( |
|
2247 | 2261 | _get_repo, self.repo_name, None, thread_scoped=True) |
|
2248 | 2262 | |
|
2249 | 2263 | with invalidator_context as context: |
|
2250 | 2264 | context.invalidate() |
|
2251 | 2265 | repo = context.compute() |
|
2252 | 2266 | |
|
2253 | 2267 | return repo |
|
2254 | 2268 | |
|
2255 | 2269 | def _get_instance(self, cache=True, config=None): |
|
2256 | 2270 | config = config or self._config |
|
2257 | 2271 | custom_wire = { |
|
2258 | 2272 | 'cache': cache # controls the vcs.remote cache |
|
2259 | 2273 | } |
|
2260 | 2274 | repo = get_vcs_instance( |
|
2261 | 2275 | repo_path=safe_str(self.repo_full_path), |
|
2262 | 2276 | config=config, |
|
2263 | 2277 | with_wire=custom_wire, |
|
2264 | 2278 | create=False, |
|
2265 | 2279 | _vcs_alias=self.repo_type) |
|
2266 | 2280 | |
|
2267 | 2281 | return repo |
|
2268 | 2282 | |
|
2269 | 2283 | def __json__(self): |
|
2270 | 2284 | return {'landing_rev': self.landing_rev} |
|
2271 | 2285 | |
|
2272 | 2286 | def get_dict(self): |
|
2273 | 2287 | |
|
2274 | 2288 | # Since we transformed `repo_name` to a hybrid property, we need to |
|
2275 | 2289 | # keep compatibility with the code which uses `repo_name` field. |
|
2276 | 2290 | |
|
2277 | 2291 | result = super(Repository, self).get_dict() |
|
2278 | 2292 | result['repo_name'] = result.pop('_repo_name', None) |
|
2279 | 2293 | return result |
|
2280 | 2294 | |
|
2281 | 2295 | |
|
2282 | 2296 | class RepoGroup(Base, BaseModel): |
|
2283 | 2297 | __tablename__ = 'groups' |
|
2284 | 2298 | __table_args__ = ( |
|
2285 | 2299 | UniqueConstraint('group_name', 'group_parent_id'), |
|
2286 | 2300 | CheckConstraint('group_id != group_parent_id'), |
|
2287 | 2301 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
2288 | 2302 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}, |
|
2289 | 2303 | ) |
|
2290 | 2304 | __mapper_args__ = {'order_by': 'group_name'} |
|
2291 | 2305 | |
|
2292 | 2306 | CHOICES_SEPARATOR = '/' # used to generate select2 choices for nested groups |
|
2293 | 2307 | |
|
2294 | 2308 | group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) |
|
2295 | 2309 | group_name = Column("group_name", String(255), nullable=False, unique=True, default=None) |
|
2296 | 2310 | group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None) |
|
2297 | 2311 | group_description = Column("group_description", String(10000), nullable=True, unique=None, default=None) |
|
2298 | 2312 | enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False) |
|
2299 | 2313 | user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None) |
|
2300 | 2314 | created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now) |
|
2301 | 2315 | updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now) |
|
2302 | 2316 | personal = Column('personal', Boolean(), nullable=True, unique=None, default=None) |
|
2303 | 2317 | |
|
2304 | 2318 | repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id') |
|
2305 | 2319 | users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all') |
|
2306 | 2320 | parent_group = relationship('RepoGroup', remote_side=group_id) |
|
2307 | 2321 | user = relationship('User') |
|
2308 | 2322 | integrations = relationship('Integration', |
|
2309 | 2323 | cascade="all, delete, delete-orphan") |
|
2310 | 2324 | |
|
2311 | 2325 | def __init__(self, group_name='', parent_group=None): |
|
2312 | 2326 | self.group_name = group_name |
|
2313 | 2327 | self.parent_group = parent_group |
|
2314 | 2328 | |
|
2315 | 2329 | def __unicode__(self): |
|
2316 | 2330 | return u"<%s('id:%s:%s')>" % ( |
|
2317 | 2331 | self.__class__.__name__, self.group_id, self.group_name) |
|
2318 | 2332 | |
|
2319 | 2333 | @hybrid_property |
|
2320 | 2334 | def description_safe(self): |
|
2321 | 2335 | from rhodecode.lib import helpers as h |
|
2322 | 2336 | return h.escape(self.group_description) |
|
2323 | 2337 | |
|
2324 | 2338 | @classmethod |
|
2325 | 2339 | def _generate_choice(cls, repo_group): |
|
2326 | 2340 | from webhelpers.html import literal as _literal |
|
2327 | 2341 | _name = lambda k: _literal(cls.CHOICES_SEPARATOR.join(k)) |
|
2328 | 2342 | return repo_group.group_id, _name(repo_group.full_path_splitted) |
|
2329 | 2343 | |
|
2330 | 2344 | @classmethod |
|
2331 | 2345 | def groups_choices(cls, groups=None, show_empty_group=True): |
|
2332 | 2346 | if not groups: |
|
2333 | 2347 | groups = cls.query().all() |
|
2334 | 2348 | |
|
2335 | 2349 | repo_groups = [] |
|
2336 | 2350 | if show_empty_group: |
|
2337 | 2351 | repo_groups = [(-1, u'-- %s --' % _('No parent'))] |
|
2338 | 2352 | |
|
2339 | 2353 | repo_groups.extend([cls._generate_choice(x) for x in groups]) |
|
2340 | 2354 | |
|
2341 | 2355 | repo_groups = sorted( |
|
2342 | 2356 | repo_groups, key=lambda t: t[1].split(cls.CHOICES_SEPARATOR)[0]) |
|
2343 | 2357 | return repo_groups |
|
2344 | 2358 | |
|
2345 | 2359 | @classmethod |
|
2346 | 2360 | def url_sep(cls): |
|
2347 | 2361 | return URL_SEP |
|
2348 | 2362 | |
|
2349 | 2363 | @classmethod |
|
2350 | 2364 | def get_by_group_name(cls, group_name, cache=False, case_insensitive=False): |
|
2351 | 2365 | if case_insensitive: |
|
2352 | 2366 | gr = cls.query().filter(func.lower(cls.group_name) |
|
2353 | 2367 | == func.lower(group_name)) |
|
2354 | 2368 | else: |
|
2355 | 2369 | gr = cls.query().filter(cls.group_name == group_name) |
|
2356 | 2370 | if cache: |
|
2357 | 2371 | name_key = _hash_key(group_name) |
|
2358 | 2372 | gr = gr.options( |
|
2359 | 2373 | FromCache("sql_cache_short", "get_group_%s" % name_key)) |
|
2360 | 2374 | return gr.scalar() |
|
2361 | 2375 | |
|
2362 | 2376 | @classmethod |
|
2363 | 2377 | def get_user_personal_repo_group(cls, user_id): |
|
2364 | 2378 | user = User.get(user_id) |
|
2365 | 2379 | if user.username == User.DEFAULT_USER: |
|
2366 | 2380 | return None |
|
2367 | 2381 | |
|
2368 | 2382 | return cls.query()\ |
|
2369 | 2383 | .filter(cls.personal == true()) \ |
|
2370 | 2384 | .filter(cls.user == user).scalar() |
|
2371 | 2385 | |
|
2372 | 2386 | @classmethod |
|
2373 | 2387 | def get_all_repo_groups(cls, user_id=Optional(None), group_id=Optional(None), |
|
2374 | 2388 | case_insensitive=True): |
|
2375 | 2389 | q = RepoGroup.query() |
|
2376 | 2390 | |
|
2377 | 2391 | if not isinstance(user_id, Optional): |
|
2378 | 2392 | q = q.filter(RepoGroup.user_id == user_id) |
|
2379 | 2393 | |
|
2380 | 2394 | if not isinstance(group_id, Optional): |
|
2381 | 2395 | q = q.filter(RepoGroup.group_parent_id == group_id) |
|
2382 | 2396 | |
|
2383 | 2397 | if case_insensitive: |
|
2384 | 2398 | q = q.order_by(func.lower(RepoGroup.group_name)) |
|
2385 | 2399 | else: |
|
2386 | 2400 | q = q.order_by(RepoGroup.group_name) |
|
2387 | 2401 | return q.all() |
|
2388 | 2402 | |
|
2389 | 2403 | @property |
|
2390 | 2404 | def parents(self): |
|
2391 | 2405 | parents_recursion_limit = 10 |
|
2392 | 2406 | groups = [] |
|
2393 | 2407 | if self.parent_group is None: |
|
2394 | 2408 | return groups |
|
2395 | 2409 | cur_gr = self.parent_group |
|
2396 | 2410 | groups.insert(0, cur_gr) |
|
2397 | 2411 | cnt = 0 |
|
2398 | 2412 | while 1: |
|
2399 | 2413 | cnt += 1 |
|
2400 | 2414 | gr = getattr(cur_gr, 'parent_group', None) |
|
2401 | 2415 | cur_gr = cur_gr.parent_group |
|
2402 | 2416 | if gr is None: |
|
2403 | 2417 | break |
|
2404 | 2418 | if cnt == parents_recursion_limit: |
|
2405 | 2419 | # this will prevent accidental infinit loops |
|
2406 | 2420 | log.error(('more than %s parents found for group %s, stopping ' |
|
2407 | 2421 | 'recursive parent fetching' % (parents_recursion_limit, self))) |
|
2408 | 2422 | break |
|
2409 | 2423 | |
|
2410 | 2424 | groups.insert(0, gr) |
|
2411 | 2425 | return groups |
|
2412 | 2426 | |
|
2413 | 2427 | @property |
|
2414 | 2428 | def last_db_change(self): |
|
2415 | 2429 | return self.updated_on |
|
2416 | 2430 | |
|
2417 | 2431 | @property |
|
2418 | 2432 | def children(self): |
|
2419 | 2433 | return RepoGroup.query().filter(RepoGroup.parent_group == self) |
|
2420 | 2434 | |
|
2421 | 2435 | @property |
|
2422 | 2436 | def name(self): |
|
2423 | 2437 | return self.group_name.split(RepoGroup.url_sep())[-1] |
|
2424 | 2438 | |
|
2425 | 2439 | @property |
|
2426 | 2440 | def full_path(self): |
|
2427 | 2441 | return self.group_name |
|
2428 | 2442 | |
|
2429 | 2443 | @property |
|
2430 | 2444 | def full_path_splitted(self): |
|
2431 | 2445 | return self.group_name.split(RepoGroup.url_sep()) |
|
2432 | 2446 | |
|
2433 | 2447 | @property |
|
2434 | 2448 | def repositories(self): |
|
2435 | 2449 | return Repository.query()\ |
|
2436 | 2450 | .filter(Repository.group == self)\ |
|
2437 | 2451 | .order_by(Repository.repo_name) |
|
2438 | 2452 | |
|
2439 | 2453 | @property |
|
2440 | 2454 | def repositories_recursive_count(self): |
|
2441 | 2455 | cnt = self.repositories.count() |
|
2442 | 2456 | |
|
2443 | 2457 | def children_count(group): |
|
2444 | 2458 | cnt = 0 |
|
2445 | 2459 | for child in group.children: |
|
2446 | 2460 | cnt += child.repositories.count() |
|
2447 | 2461 | cnt += children_count(child) |
|
2448 | 2462 | return cnt |
|
2449 | 2463 | |
|
2450 | 2464 | return cnt + children_count(self) |
|
2451 | 2465 | |
|
2452 | 2466 | def _recursive_objects(self, include_repos=True): |
|
2453 | 2467 | all_ = [] |
|
2454 | 2468 | |
|
2455 | 2469 | def _get_members(root_gr): |
|
2456 | 2470 | if include_repos: |
|
2457 | 2471 | for r in root_gr.repositories: |
|
2458 | 2472 | all_.append(r) |
|
2459 | 2473 | childs = root_gr.children.all() |
|
2460 | 2474 | if childs: |
|
2461 | 2475 | for gr in childs: |
|
2462 | 2476 | all_.append(gr) |
|
2463 | 2477 | _get_members(gr) |
|
2464 | 2478 | |
|
2465 | 2479 | _get_members(self) |
|
2466 | 2480 | return [self] + all_ |
|
2467 | 2481 | |
|
2468 | 2482 | def recursive_groups_and_repos(self): |
|
2469 | 2483 | """ |
|
2470 | 2484 | Recursive return all groups, with repositories in those groups |
|
2471 | 2485 | """ |
|
2472 | 2486 | return self._recursive_objects() |
|
2473 | 2487 | |
|
2474 | 2488 | def recursive_groups(self): |
|
2475 | 2489 | """ |
|
2476 | 2490 | Returns all children groups for this group including children of children |
|
2477 | 2491 | """ |
|
2478 | 2492 | return self._recursive_objects(include_repos=False) |
|
2479 | 2493 | |
|
2480 | 2494 | def get_new_name(self, group_name): |
|
2481 | 2495 | """ |
|
2482 | 2496 | returns new full group name based on parent and new name |
|
2483 | 2497 | |
|
2484 | 2498 | :param group_name: |
|
2485 | 2499 | """ |
|
2486 | 2500 | path_prefix = (self.parent_group.full_path_splitted if |
|
2487 | 2501 | self.parent_group else []) |
|
2488 | 2502 | return RepoGroup.url_sep().join(path_prefix + [group_name]) |
|
2489 | 2503 | |
|
2490 | 2504 | def permissions(self, with_admins=True, with_owner=True): |
|
2491 | 2505 | q = UserRepoGroupToPerm.query().filter(UserRepoGroupToPerm.group == self) |
|
2492 | 2506 | q = q.options(joinedload(UserRepoGroupToPerm.group), |
|
2493 | 2507 | joinedload(UserRepoGroupToPerm.user), |
|
2494 | 2508 | joinedload(UserRepoGroupToPerm.permission),) |
|
2495 | 2509 | |
|
2496 | 2510 | # get owners and admins and permissions. We do a trick of re-writing |
|
2497 | 2511 | # objects from sqlalchemy to named-tuples due to sqlalchemy session |
|
2498 | 2512 | # has a global reference and changing one object propagates to all |
|
2499 | 2513 | # others. This means if admin is also an owner admin_row that change |
|
2500 | 2514 | # would propagate to both objects |
|
2501 | 2515 | perm_rows = [] |
|
2502 | 2516 | for _usr in q.all(): |
|
2503 | 2517 | usr = AttributeDict(_usr.user.get_dict()) |
|
2504 | 2518 | usr.permission = _usr.permission.permission_name |
|
2505 | 2519 | perm_rows.append(usr) |
|
2506 | 2520 | |
|
2507 | 2521 | # filter the perm rows by 'default' first and then sort them by |
|
2508 | 2522 | # admin,write,read,none permissions sorted again alphabetically in |
|
2509 | 2523 | # each group |
|
2510 | 2524 | perm_rows = sorted(perm_rows, key=display_user_sort) |
|
2511 | 2525 | |
|
2512 | 2526 | _admin_perm = 'group.admin' |
|
2513 | 2527 | owner_row = [] |
|
2514 | 2528 | if with_owner: |
|
2515 | 2529 | usr = AttributeDict(self.user.get_dict()) |
|
2516 | 2530 | usr.owner_row = True |
|
2517 | 2531 | usr.permission = _admin_perm |
|
2518 | 2532 | owner_row.append(usr) |
|
2519 | 2533 | |
|
2520 | 2534 | super_admin_rows = [] |
|
2521 | 2535 | if with_admins: |
|
2522 | 2536 | for usr in User.get_all_super_admins(): |
|
2523 | 2537 | # if this admin is also owner, don't double the record |
|
2524 | 2538 | if usr.user_id == owner_row[0].user_id: |
|
2525 | 2539 | owner_row[0].admin_row = True |
|
2526 | 2540 | else: |
|
2527 | 2541 | usr = AttributeDict(usr.get_dict()) |
|
2528 | 2542 | usr.admin_row = True |
|
2529 | 2543 | usr.permission = _admin_perm |
|
2530 | 2544 | super_admin_rows.append(usr) |
|
2531 | 2545 | |
|
2532 | 2546 | return super_admin_rows + owner_row + perm_rows |
|
2533 | 2547 | |
|
2534 | 2548 | def permission_user_groups(self): |
|
2535 | 2549 | q = UserGroupRepoGroupToPerm.query().filter(UserGroupRepoGroupToPerm.group == self) |
|
2536 | 2550 | q = q.options(joinedload(UserGroupRepoGroupToPerm.group), |
|
2537 | 2551 | joinedload(UserGroupRepoGroupToPerm.users_group), |
|
2538 | 2552 | joinedload(UserGroupRepoGroupToPerm.permission),) |
|
2539 | 2553 | |
|
2540 | 2554 | perm_rows = [] |
|
2541 | 2555 | for _user_group in q.all(): |
|
2542 | 2556 | usr = AttributeDict(_user_group.users_group.get_dict()) |
|
2543 | 2557 | usr.permission = _user_group.permission.permission_name |
|
2544 | 2558 | perm_rows.append(usr) |
|
2545 | 2559 | |
|
2546 | 2560 | perm_rows = sorted(perm_rows, key=display_user_group_sort) |
|
2547 | 2561 | return perm_rows |
|
2548 | 2562 | |
|
2549 | 2563 | def get_api_data(self): |
|
2550 | 2564 | """ |
|
2551 | 2565 | Common function for generating api data |
|
2552 | 2566 | |
|
2553 | 2567 | """ |
|
2554 | 2568 | group = self |
|
2555 | 2569 | data = { |
|
2556 | 2570 | 'group_id': group.group_id, |
|
2557 | 2571 | 'group_name': group.group_name, |
|
2558 | 2572 | 'group_description': group.description_safe, |
|
2559 | 2573 | 'parent_group': group.parent_group.group_name if group.parent_group else None, |
|
2560 | 2574 | 'repositories': [x.repo_name for x in group.repositories], |
|
2561 | 2575 | 'owner': group.user.username, |
|
2562 | 2576 | } |
|
2563 | 2577 | return data |
|
2564 | 2578 | |
|
2565 | 2579 | |
|
2566 | 2580 | class Permission(Base, BaseModel): |
|
2567 | 2581 | __tablename__ = 'permissions' |
|
2568 | 2582 | __table_args__ = ( |
|
2569 | 2583 | Index('p_perm_name_idx', 'permission_name'), |
|
2570 | 2584 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
2571 | 2585 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}, |
|
2572 | 2586 | ) |
|
2573 | 2587 | PERMS = [ |
|
2574 | 2588 | ('hg.admin', _('RhodeCode Super Administrator')), |
|
2575 | 2589 | |
|
2576 | 2590 | ('repository.none', _('Repository no access')), |
|
2577 | 2591 | ('repository.read', _('Repository read access')), |
|
2578 | 2592 | ('repository.write', _('Repository write access')), |
|
2579 | 2593 | ('repository.admin', _('Repository admin access')), |
|
2580 | 2594 | |
|
2581 | 2595 | ('group.none', _('Repository group no access')), |
|
2582 | 2596 | ('group.read', _('Repository group read access')), |
|
2583 | 2597 | ('group.write', _('Repository group write access')), |
|
2584 | 2598 | ('group.admin', _('Repository group admin access')), |
|
2585 | 2599 | |
|
2586 | 2600 | ('usergroup.none', _('User group no access')), |
|
2587 | 2601 | ('usergroup.read', _('User group read access')), |
|
2588 | 2602 | ('usergroup.write', _('User group write access')), |
|
2589 | 2603 | ('usergroup.admin', _('User group admin access')), |
|
2590 | 2604 | |
|
2591 | 2605 | ('hg.repogroup.create.false', _('Repository Group creation disabled')), |
|
2592 | 2606 | ('hg.repogroup.create.true', _('Repository Group creation enabled')), |
|
2593 | 2607 | |
|
2594 | 2608 | ('hg.usergroup.create.false', _('User Group creation disabled')), |
|
2595 | 2609 | ('hg.usergroup.create.true', _('User Group creation enabled')), |
|
2596 | 2610 | |
|
2597 | 2611 | ('hg.create.none', _('Repository creation disabled')), |
|
2598 | 2612 | ('hg.create.repository', _('Repository creation enabled')), |
|
2599 | 2613 | ('hg.create.write_on_repogroup.true', _('Repository creation enabled with write permission to a repository group')), |
|
2600 | 2614 | ('hg.create.write_on_repogroup.false', _('Repository creation disabled with write permission to a repository group')), |
|
2601 | 2615 | |
|
2602 | 2616 | ('hg.fork.none', _('Repository forking disabled')), |
|
2603 | 2617 | ('hg.fork.repository', _('Repository forking enabled')), |
|
2604 | 2618 | |
|
2605 | 2619 | ('hg.register.none', _('Registration disabled')), |
|
2606 | 2620 | ('hg.register.manual_activate', _('User Registration with manual account activation')), |
|
2607 | 2621 | ('hg.register.auto_activate', _('User Registration with automatic account activation')), |
|
2608 | 2622 | |
|
2609 | 2623 | ('hg.password_reset.enabled', _('Password reset enabled')), |
|
2610 | 2624 | ('hg.password_reset.hidden', _('Password reset hidden')), |
|
2611 | 2625 | ('hg.password_reset.disabled', _('Password reset disabled')), |
|
2612 | 2626 | |
|
2613 | 2627 | ('hg.extern_activate.manual', _('Manual activation of external account')), |
|
2614 | 2628 | ('hg.extern_activate.auto', _('Automatic activation of external account')), |
|
2615 | 2629 | |
|
2616 | 2630 | ('hg.inherit_default_perms.false', _('Inherit object permissions from default user disabled')), |
|
2617 | 2631 | ('hg.inherit_default_perms.true', _('Inherit object permissions from default user enabled')), |
|
2618 | 2632 | ] |
|
2619 | 2633 | |
|
2620 | 2634 | # definition of system default permissions for DEFAULT user |
|
2621 | 2635 | DEFAULT_USER_PERMISSIONS = [ |
|
2622 | 2636 | 'repository.read', |
|
2623 | 2637 | 'group.read', |
|
2624 | 2638 | 'usergroup.read', |
|
2625 | 2639 | 'hg.create.repository', |
|
2626 | 2640 | 'hg.repogroup.create.false', |
|
2627 | 2641 | 'hg.usergroup.create.false', |
|
2628 | 2642 | 'hg.create.write_on_repogroup.true', |
|
2629 | 2643 | 'hg.fork.repository', |
|
2630 | 2644 | 'hg.register.manual_activate', |
|
2631 | 2645 | 'hg.password_reset.enabled', |
|
2632 | 2646 | 'hg.extern_activate.auto', |
|
2633 | 2647 | 'hg.inherit_default_perms.true', |
|
2634 | 2648 | ] |
|
2635 | 2649 | |
|
2636 | 2650 | # defines which permissions are more important higher the more important |
|
2637 | 2651 | # Weight defines which permissions are more important. |
|
2638 | 2652 | # The higher number the more important. |
|
2639 | 2653 | PERM_WEIGHTS = { |
|
2640 | 2654 | 'repository.none': 0, |
|
2641 | 2655 | 'repository.read': 1, |
|
2642 | 2656 | 'repository.write': 3, |
|
2643 | 2657 | 'repository.admin': 4, |
|
2644 | 2658 | |
|
2645 | 2659 | 'group.none': 0, |
|
2646 | 2660 | 'group.read': 1, |
|
2647 | 2661 | 'group.write': 3, |
|
2648 | 2662 | 'group.admin': 4, |
|
2649 | 2663 | |
|
2650 | 2664 | 'usergroup.none': 0, |
|
2651 | 2665 | 'usergroup.read': 1, |
|
2652 | 2666 | 'usergroup.write': 3, |
|
2653 | 2667 | 'usergroup.admin': 4, |
|
2654 | 2668 | |
|
2655 | 2669 | 'hg.repogroup.create.false': 0, |
|
2656 | 2670 | 'hg.repogroup.create.true': 1, |
|
2657 | 2671 | |
|
2658 | 2672 | 'hg.usergroup.create.false': 0, |
|
2659 | 2673 | 'hg.usergroup.create.true': 1, |
|
2660 | 2674 | |
|
2661 | 2675 | 'hg.fork.none': 0, |
|
2662 | 2676 | 'hg.fork.repository': 1, |
|
2663 | 2677 | 'hg.create.none': 0, |
|
2664 | 2678 | 'hg.create.repository': 1 |
|
2665 | 2679 | } |
|
2666 | 2680 | |
|
2667 | 2681 | permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) |
|
2668 | 2682 | permission_name = Column("permission_name", String(255), nullable=True, unique=None, default=None) |
|
2669 | 2683 | permission_longname = Column("permission_longname", String(255), nullable=True, unique=None, default=None) |
|
2670 | 2684 | |
|
2671 | 2685 | def __unicode__(self): |
|
2672 | 2686 | return u"<%s('%s:%s')>" % ( |
|
2673 | 2687 | self.__class__.__name__, self.permission_id, self.permission_name |
|
2674 | 2688 | ) |
|
2675 | 2689 | |
|
2676 | 2690 | @classmethod |
|
2677 | 2691 | def get_by_key(cls, key): |
|
2678 | 2692 | return cls.query().filter(cls.permission_name == key).scalar() |
|
2679 | 2693 | |
|
2680 | 2694 | @classmethod |
|
2681 | 2695 | def get_default_repo_perms(cls, user_id, repo_id=None): |
|
2682 | 2696 | q = Session().query(UserRepoToPerm, Repository, Permission)\ |
|
2683 | 2697 | .join((Permission, UserRepoToPerm.permission_id == Permission.permission_id))\ |
|
2684 | 2698 | .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\ |
|
2685 | 2699 | .filter(UserRepoToPerm.user_id == user_id) |
|
2686 | 2700 | if repo_id: |
|
2687 | 2701 | q = q.filter(UserRepoToPerm.repository_id == repo_id) |
|
2688 | 2702 | return q.all() |
|
2689 | 2703 | |
|
2690 | 2704 | @classmethod |
|
2691 | 2705 | def get_default_repo_perms_from_user_group(cls, user_id, repo_id=None): |
|
2692 | 2706 | q = Session().query(UserGroupRepoToPerm, Repository, Permission)\ |
|
2693 | 2707 | .join( |
|
2694 | 2708 | Permission, |
|
2695 | 2709 | UserGroupRepoToPerm.permission_id == Permission.permission_id)\ |
|
2696 | 2710 | .join( |
|
2697 | 2711 | Repository, |
|
2698 | 2712 | UserGroupRepoToPerm.repository_id == Repository.repo_id)\ |
|
2699 | 2713 | .join( |
|
2700 | 2714 | UserGroup, |
|
2701 | 2715 | UserGroupRepoToPerm.users_group_id == |
|
2702 | 2716 | UserGroup.users_group_id)\ |
|
2703 | 2717 | .join( |
|
2704 | 2718 | UserGroupMember, |
|
2705 | 2719 | UserGroupRepoToPerm.users_group_id == |
|
2706 | 2720 | UserGroupMember.users_group_id)\ |
|
2707 | 2721 | .filter( |
|
2708 | 2722 | UserGroupMember.user_id == user_id, |
|
2709 | 2723 | UserGroup.users_group_active == true()) |
|
2710 | 2724 | if repo_id: |
|
2711 | 2725 | q = q.filter(UserGroupRepoToPerm.repository_id == repo_id) |
|
2712 | 2726 | return q.all() |
|
2713 | 2727 | |
|
2714 | 2728 | @classmethod |
|
2715 | 2729 | def get_default_group_perms(cls, user_id, repo_group_id=None): |
|
2716 | 2730 | q = Session().query(UserRepoGroupToPerm, RepoGroup, Permission)\ |
|
2717 | 2731 | .join((Permission, UserRepoGroupToPerm.permission_id == Permission.permission_id))\ |
|
2718 | 2732 | .join((RepoGroup, UserRepoGroupToPerm.group_id == RepoGroup.group_id))\ |
|
2719 | 2733 | .filter(UserRepoGroupToPerm.user_id == user_id) |
|
2720 | 2734 | if repo_group_id: |
|
2721 | 2735 | q = q.filter(UserRepoGroupToPerm.group_id == repo_group_id) |
|
2722 | 2736 | return q.all() |
|
2723 | 2737 | |
|
2724 | 2738 | @classmethod |
|
2725 | 2739 | def get_default_group_perms_from_user_group( |
|
2726 | 2740 | cls, user_id, repo_group_id=None): |
|
2727 | 2741 | q = Session().query(UserGroupRepoGroupToPerm, RepoGroup, Permission)\ |
|
2728 | 2742 | .join( |
|
2729 | 2743 | Permission, |
|
2730 | 2744 | UserGroupRepoGroupToPerm.permission_id == |
|
2731 | 2745 | Permission.permission_id)\ |
|
2732 | 2746 | .join( |
|
2733 | 2747 | RepoGroup, |
|
2734 | 2748 | UserGroupRepoGroupToPerm.group_id == RepoGroup.group_id)\ |
|
2735 | 2749 | .join( |
|
2736 | 2750 | UserGroup, |
|
2737 | 2751 | UserGroupRepoGroupToPerm.users_group_id == |
|
2738 | 2752 | UserGroup.users_group_id)\ |
|
2739 | 2753 | .join( |
|
2740 | 2754 | UserGroupMember, |
|
2741 | 2755 | UserGroupRepoGroupToPerm.users_group_id == |
|
2742 | 2756 | UserGroupMember.users_group_id)\ |
|
2743 | 2757 | .filter( |
|
2744 | 2758 | UserGroupMember.user_id == user_id, |
|
2745 | 2759 | UserGroup.users_group_active == true()) |
|
2746 | 2760 | if repo_group_id: |
|
2747 | 2761 | q = q.filter(UserGroupRepoGroupToPerm.group_id == repo_group_id) |
|
2748 | 2762 | return q.all() |
|
2749 | 2763 | |
|
2750 | 2764 | @classmethod |
|
2751 | 2765 | def get_default_user_group_perms(cls, user_id, user_group_id=None): |
|
2752 | 2766 | q = Session().query(UserUserGroupToPerm, UserGroup, Permission)\ |
|
2753 | 2767 | .join((Permission, UserUserGroupToPerm.permission_id == Permission.permission_id))\ |
|
2754 | 2768 | .join((UserGroup, UserUserGroupToPerm.user_group_id == UserGroup.users_group_id))\ |
|
2755 | 2769 | .filter(UserUserGroupToPerm.user_id == user_id) |
|
2756 | 2770 | if user_group_id: |
|
2757 | 2771 | q = q.filter(UserUserGroupToPerm.user_group_id == user_group_id) |
|
2758 | 2772 | return q.all() |
|
2759 | 2773 | |
|
2760 | 2774 | @classmethod |
|
2761 | 2775 | def get_default_user_group_perms_from_user_group( |
|
2762 | 2776 | cls, user_id, user_group_id=None): |
|
2763 | 2777 | TargetUserGroup = aliased(UserGroup, name='target_user_group') |
|
2764 | 2778 | q = Session().query(UserGroupUserGroupToPerm, UserGroup, Permission)\ |
|
2765 | 2779 | .join( |
|
2766 | 2780 | Permission, |
|
2767 | 2781 | UserGroupUserGroupToPerm.permission_id == |
|
2768 | 2782 | Permission.permission_id)\ |
|
2769 | 2783 | .join( |
|
2770 | 2784 | TargetUserGroup, |
|
2771 | 2785 | UserGroupUserGroupToPerm.target_user_group_id == |
|
2772 | 2786 | TargetUserGroup.users_group_id)\ |
|
2773 | 2787 | .join( |
|
2774 | 2788 | UserGroup, |
|
2775 | 2789 | UserGroupUserGroupToPerm.user_group_id == |
|
2776 | 2790 | UserGroup.users_group_id)\ |
|
2777 | 2791 | .join( |
|
2778 | 2792 | UserGroupMember, |
|
2779 | 2793 | UserGroupUserGroupToPerm.user_group_id == |
|
2780 | 2794 | UserGroupMember.users_group_id)\ |
|
2781 | 2795 | .filter( |
|
2782 | 2796 | UserGroupMember.user_id == user_id, |
|
2783 | 2797 | UserGroup.users_group_active == true()) |
|
2784 | 2798 | if user_group_id: |
|
2785 | 2799 | q = q.filter( |
|
2786 | 2800 | UserGroupUserGroupToPerm.user_group_id == user_group_id) |
|
2787 | 2801 | |
|
2788 | 2802 | return q.all() |
|
2789 | 2803 | |
|
2790 | 2804 | |
|
2791 | 2805 | class UserRepoToPerm(Base, BaseModel): |
|
2792 | 2806 | __tablename__ = 'repo_to_perm' |
|
2793 | 2807 | __table_args__ = ( |
|
2794 | 2808 | UniqueConstraint('user_id', 'repository_id', 'permission_id'), |
|
2795 | 2809 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
2796 | 2810 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} |
|
2797 | 2811 | ) |
|
2798 | 2812 | repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) |
|
2799 | 2813 | user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None) |
|
2800 | 2814 | permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None) |
|
2801 | 2815 | repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None) |
|
2802 | 2816 | |
|
2803 | 2817 | user = relationship('User') |
|
2804 | 2818 | repository = relationship('Repository') |
|
2805 | 2819 | permission = relationship('Permission') |
|
2806 | 2820 | |
|
2807 | 2821 | @classmethod |
|
2808 | 2822 | def create(cls, user, repository, permission): |
|
2809 | 2823 | n = cls() |
|
2810 | 2824 | n.user = user |
|
2811 | 2825 | n.repository = repository |
|
2812 | 2826 | n.permission = permission |
|
2813 | 2827 | Session().add(n) |
|
2814 | 2828 | return n |
|
2815 | 2829 | |
|
2816 | 2830 | def __unicode__(self): |
|
2817 | 2831 | return u'<%s => %s >' % (self.user, self.repository) |
|
2818 | 2832 | |
|
2819 | 2833 | |
|
2820 | 2834 | class UserUserGroupToPerm(Base, BaseModel): |
|
2821 | 2835 | __tablename__ = 'user_user_group_to_perm' |
|
2822 | 2836 | __table_args__ = ( |
|
2823 | 2837 | UniqueConstraint('user_id', 'user_group_id', 'permission_id'), |
|
2824 | 2838 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
2825 | 2839 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} |
|
2826 | 2840 | ) |
|
2827 | 2841 | user_user_group_to_perm_id = Column("user_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) |
|
2828 | 2842 | user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None) |
|
2829 | 2843 | permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None) |
|
2830 | 2844 | user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None) |
|
2831 | 2845 | |
|
2832 | 2846 | user = relationship('User') |
|
2833 | 2847 | user_group = relationship('UserGroup') |
|
2834 | 2848 | permission = relationship('Permission') |
|
2835 | 2849 | |
|
2836 | 2850 | @classmethod |
|
2837 | 2851 | def create(cls, user, user_group, permission): |
|
2838 | 2852 | n = cls() |
|
2839 | 2853 | n.user = user |
|
2840 | 2854 | n.user_group = user_group |
|
2841 | 2855 | n.permission = permission |
|
2842 | 2856 | Session().add(n) |
|
2843 | 2857 | return n |
|
2844 | 2858 | |
|
2845 | 2859 | def __unicode__(self): |
|
2846 | 2860 | return u'<%s => %s >' % (self.user, self.user_group) |
|
2847 | 2861 | |
|
2848 | 2862 | |
|
2849 | 2863 | class UserToPerm(Base, BaseModel): |
|
2850 | 2864 | __tablename__ = 'user_to_perm' |
|
2851 | 2865 | __table_args__ = ( |
|
2852 | 2866 | UniqueConstraint('user_id', 'permission_id'), |
|
2853 | 2867 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
2854 | 2868 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} |
|
2855 | 2869 | ) |
|
2856 | 2870 | user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) |
|
2857 | 2871 | user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None) |
|
2858 | 2872 | permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None) |
|
2859 | 2873 | |
|
2860 | 2874 | user = relationship('User') |
|
2861 | 2875 | permission = relationship('Permission', lazy='joined') |
|
2862 | 2876 | |
|
2863 | 2877 | def __unicode__(self): |
|
2864 | 2878 | return u'<%s => %s >' % (self.user, self.permission) |
|
2865 | 2879 | |
|
2866 | 2880 | |
|
2867 | 2881 | class UserGroupRepoToPerm(Base, BaseModel): |
|
2868 | 2882 | __tablename__ = 'users_group_repo_to_perm' |
|
2869 | 2883 | __table_args__ = ( |
|
2870 | 2884 | UniqueConstraint('repository_id', 'users_group_id', 'permission_id'), |
|
2871 | 2885 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
2872 | 2886 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} |
|
2873 | 2887 | ) |
|
2874 | 2888 | users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) |
|
2875 | 2889 | users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None) |
|
2876 | 2890 | permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None) |
|
2877 | 2891 | repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None) |
|
2878 | 2892 | |
|
2879 | 2893 | users_group = relationship('UserGroup') |
|
2880 | 2894 | permission = relationship('Permission') |
|
2881 | 2895 | repository = relationship('Repository') |
|
2882 | 2896 | |
|
2883 | 2897 | @classmethod |
|
2884 | 2898 | def create(cls, users_group, repository, permission): |
|
2885 | 2899 | n = cls() |
|
2886 | 2900 | n.users_group = users_group |
|
2887 | 2901 | n.repository = repository |
|
2888 | 2902 | n.permission = permission |
|
2889 | 2903 | Session().add(n) |
|
2890 | 2904 | return n |
|
2891 | 2905 | |
|
2892 | 2906 | def __unicode__(self): |
|
2893 | 2907 | return u'<UserGroupRepoToPerm:%s => %s >' % (self.users_group, self.repository) |
|
2894 | 2908 | |
|
2895 | 2909 | |
|
2896 | 2910 | class UserGroupUserGroupToPerm(Base, BaseModel): |
|
2897 | 2911 | __tablename__ = 'user_group_user_group_to_perm' |
|
2898 | 2912 | __table_args__ = ( |
|
2899 | 2913 | UniqueConstraint('target_user_group_id', 'user_group_id', 'permission_id'), |
|
2900 | 2914 | CheckConstraint('target_user_group_id != user_group_id'), |
|
2901 | 2915 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
2902 | 2916 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} |
|
2903 | 2917 | ) |
|
2904 | 2918 | user_group_user_group_to_perm_id = Column("user_group_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) |
|
2905 | 2919 | target_user_group_id = Column("target_user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None) |
|
2906 | 2920 | permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None) |
|
2907 | 2921 | user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None) |
|
2908 | 2922 | |
|
2909 | 2923 | target_user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id') |
|
2910 | 2924 | user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.user_group_id==UserGroup.users_group_id') |
|
2911 | 2925 | permission = relationship('Permission') |
|
2912 | 2926 | |
|
2913 | 2927 | @classmethod |
|
2914 | 2928 | def create(cls, target_user_group, user_group, permission): |
|
2915 | 2929 | n = cls() |
|
2916 | 2930 | n.target_user_group = target_user_group |
|
2917 | 2931 | n.user_group = user_group |
|
2918 | 2932 | n.permission = permission |
|
2919 | 2933 | Session().add(n) |
|
2920 | 2934 | return n |
|
2921 | 2935 | |
|
2922 | 2936 | def __unicode__(self): |
|
2923 | 2937 | return u'<UserGroupUserGroup:%s => %s >' % (self.target_user_group, self.user_group) |
|
2924 | 2938 | |
|
2925 | 2939 | |
|
2926 | 2940 | class UserGroupToPerm(Base, BaseModel): |
|
2927 | 2941 | __tablename__ = 'users_group_to_perm' |
|
2928 | 2942 | __table_args__ = ( |
|
2929 | 2943 | UniqueConstraint('users_group_id', 'permission_id',), |
|
2930 | 2944 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
2931 | 2945 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} |
|
2932 | 2946 | ) |
|
2933 | 2947 | users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) |
|
2934 | 2948 | users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None) |
|
2935 | 2949 | permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None) |
|
2936 | 2950 | |
|
2937 | 2951 | users_group = relationship('UserGroup') |
|
2938 | 2952 | permission = relationship('Permission') |
|
2939 | 2953 | |
|
2940 | 2954 | |
|
2941 | 2955 | class UserRepoGroupToPerm(Base, BaseModel): |
|
2942 | 2956 | __tablename__ = 'user_repo_group_to_perm' |
|
2943 | 2957 | __table_args__ = ( |
|
2944 | 2958 | UniqueConstraint('user_id', 'group_id', 'permission_id'), |
|
2945 | 2959 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
2946 | 2960 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} |
|
2947 | 2961 | ) |
|
2948 | 2962 | |
|
2949 | 2963 | group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) |
|
2950 | 2964 | user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None) |
|
2951 | 2965 | group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None) |
|
2952 | 2966 | permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None) |
|
2953 | 2967 | |
|
2954 | 2968 | user = relationship('User') |
|
2955 | 2969 | group = relationship('RepoGroup') |
|
2956 | 2970 | permission = relationship('Permission') |
|
2957 | 2971 | |
|
2958 | 2972 | @classmethod |
|
2959 | 2973 | def create(cls, user, repository_group, permission): |
|
2960 | 2974 | n = cls() |
|
2961 | 2975 | n.user = user |
|
2962 | 2976 | n.group = repository_group |
|
2963 | 2977 | n.permission = permission |
|
2964 | 2978 | Session().add(n) |
|
2965 | 2979 | return n |
|
2966 | 2980 | |
|
2967 | 2981 | |
|
2968 | 2982 | class UserGroupRepoGroupToPerm(Base, BaseModel): |
|
2969 | 2983 | __tablename__ = 'users_group_repo_group_to_perm' |
|
2970 | 2984 | __table_args__ = ( |
|
2971 | 2985 | UniqueConstraint('users_group_id', 'group_id'), |
|
2972 | 2986 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
2973 | 2987 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} |
|
2974 | 2988 | ) |
|
2975 | 2989 | |
|
2976 | 2990 | users_group_repo_group_to_perm_id = Column("users_group_repo_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) |
|
2977 | 2991 | users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None) |
|
2978 | 2992 | group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None) |
|
2979 | 2993 | permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None) |
|
2980 | 2994 | |
|
2981 | 2995 | users_group = relationship('UserGroup') |
|
2982 | 2996 | permission = relationship('Permission') |
|
2983 | 2997 | group = relationship('RepoGroup') |
|
2984 | 2998 | |
|
2985 | 2999 | @classmethod |
|
2986 | 3000 | def create(cls, user_group, repository_group, permission): |
|
2987 | 3001 | n = cls() |
|
2988 | 3002 | n.users_group = user_group |
|
2989 | 3003 | n.group = repository_group |
|
2990 | 3004 | n.permission = permission |
|
2991 | 3005 | Session().add(n) |
|
2992 | 3006 | return n |
|
2993 | 3007 | |
|
2994 | 3008 | def __unicode__(self): |
|
2995 | 3009 | return u'<UserGroupRepoGroupToPerm:%s => %s >' % (self.users_group, self.group) |
|
2996 | 3010 | |
|
2997 | 3011 | |
|
2998 | 3012 | class Statistics(Base, BaseModel): |
|
2999 | 3013 | __tablename__ = 'statistics' |
|
3000 | 3014 | __table_args__ = ( |
|
3001 | 3015 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
3002 | 3016 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} |
|
3003 | 3017 | ) |
|
3004 | 3018 | stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) |
|
3005 | 3019 | repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None) |
|
3006 | 3020 | stat_on_revision = Column("stat_on_revision", Integer(), nullable=False) |
|
3007 | 3021 | commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data |
|
3008 | 3022 | commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data |
|
3009 | 3023 | languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data |
|
3010 | 3024 | |
|
3011 | 3025 | repository = relationship('Repository', single_parent=True) |
|
3012 | 3026 | |
|
3013 | 3027 | |
|
3014 | 3028 | class UserFollowing(Base, BaseModel): |
|
3015 | 3029 | __tablename__ = 'user_followings' |
|
3016 | 3030 | __table_args__ = ( |
|
3017 | 3031 | UniqueConstraint('user_id', 'follows_repository_id'), |
|
3018 | 3032 | UniqueConstraint('user_id', 'follows_user_id'), |
|
3019 | 3033 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
3020 | 3034 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} |
|
3021 | 3035 | ) |
|
3022 | 3036 | |
|
3023 | 3037 | user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) |
|
3024 | 3038 | user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None) |
|
3025 | 3039 | follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None) |
|
3026 | 3040 | follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None) |
|
3027 | 3041 | follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now) |
|
3028 | 3042 | |
|
3029 | 3043 | user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id') |
|
3030 | 3044 | |
|
3031 | 3045 | follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id') |
|
3032 | 3046 | follows_repository = relationship('Repository', order_by='Repository.repo_name') |
|
3033 | 3047 | |
|
3034 | 3048 | @classmethod |
|
3035 | 3049 | def get_repo_followers(cls, repo_id): |
|
3036 | 3050 | return cls.query().filter(cls.follows_repo_id == repo_id) |
|
3037 | 3051 | |
|
3038 | 3052 | |
|
3039 | 3053 | class CacheKey(Base, BaseModel): |
|
3040 | 3054 | __tablename__ = 'cache_invalidation' |
|
3041 | 3055 | __table_args__ = ( |
|
3042 | 3056 | UniqueConstraint('cache_key'), |
|
3043 | 3057 | Index('key_idx', 'cache_key'), |
|
3044 | 3058 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
3045 | 3059 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}, |
|
3046 | 3060 | ) |
|
3047 | 3061 | CACHE_TYPE_ATOM = 'ATOM' |
|
3048 | 3062 | CACHE_TYPE_RSS = 'RSS' |
|
3049 | 3063 | CACHE_TYPE_README = 'README' |
|
3050 | 3064 | |
|
3051 | 3065 | cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) |
|
3052 | 3066 | cache_key = Column("cache_key", String(255), nullable=True, unique=None, default=None) |
|
3053 | 3067 | cache_args = Column("cache_args", String(255), nullable=True, unique=None, default=None) |
|
3054 | 3068 | cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False) |
|
3055 | 3069 | |
|
3056 | 3070 | def __init__(self, cache_key, cache_args=''): |
|
3057 | 3071 | self.cache_key = cache_key |
|
3058 | 3072 | self.cache_args = cache_args |
|
3059 | 3073 | self.cache_active = False |
|
3060 | 3074 | |
|
3061 | 3075 | def __unicode__(self): |
|
3062 | 3076 | return u"<%s('%s:%s[%s]')>" % ( |
|
3063 | 3077 | self.__class__.__name__, |
|
3064 | 3078 | self.cache_id, self.cache_key, self.cache_active) |
|
3065 | 3079 | |
|
3066 | 3080 | def _cache_key_partition(self): |
|
3067 | 3081 | prefix, repo_name, suffix = self.cache_key.partition(self.cache_args) |
|
3068 | 3082 | return prefix, repo_name, suffix |
|
3069 | 3083 | |
|
3070 | 3084 | def get_prefix(self): |
|
3071 | 3085 | """ |
|
3072 | 3086 | Try to extract prefix from existing cache key. The key could consist |
|
3073 | 3087 | of prefix, repo_name, suffix |
|
3074 | 3088 | """ |
|
3075 | 3089 | # this returns prefix, repo_name, suffix |
|
3076 | 3090 | return self._cache_key_partition()[0] |
|
3077 | 3091 | |
|
3078 | 3092 | def get_suffix(self): |
|
3079 | 3093 | """ |
|
3080 | 3094 | get suffix that might have been used in _get_cache_key to |
|
3081 | 3095 | generate self.cache_key. Only used for informational purposes |
|
3082 | 3096 | in repo_edit.mako. |
|
3083 | 3097 | """ |
|
3084 | 3098 | # prefix, repo_name, suffix |
|
3085 | 3099 | return self._cache_key_partition()[2] |
|
3086 | 3100 | |
|
3087 | 3101 | @classmethod |
|
3088 | 3102 | def delete_all_cache(cls): |
|
3089 | 3103 | """ |
|
3090 | 3104 | Delete all cache keys from database. |
|
3091 | 3105 | Should only be run when all instances are down and all entries |
|
3092 | 3106 | thus stale. |
|
3093 | 3107 | """ |
|
3094 | 3108 | cls.query().delete() |
|
3095 | 3109 | Session().commit() |
|
3096 | 3110 | |
|
3097 | 3111 | @classmethod |
|
3098 | 3112 | def get_cache_key(cls, repo_name, cache_type): |
|
3099 | 3113 | """ |
|
3100 | 3114 | |
|
3101 | 3115 | Generate a cache key for this process of RhodeCode instance. |
|
3102 | 3116 | Prefix most likely will be process id or maybe explicitly set |
|
3103 | 3117 | instance_id from .ini file. |
|
3104 | 3118 | """ |
|
3105 | 3119 | import rhodecode |
|
3106 | 3120 | prefix = safe_unicode(rhodecode.CONFIG.get('instance_id') or '') |
|
3107 | 3121 | |
|
3108 | 3122 | repo_as_unicode = safe_unicode(repo_name) |
|
3109 | 3123 | key = u'{}_{}'.format(repo_as_unicode, cache_type) \ |
|
3110 | 3124 | if cache_type else repo_as_unicode |
|
3111 | 3125 | |
|
3112 | 3126 | return u'{}{}'.format(prefix, key) |
|
3113 | 3127 | |
|
3114 | 3128 | @classmethod |
|
3115 | 3129 | def set_invalidate(cls, repo_name, delete=False): |
|
3116 | 3130 | """ |
|
3117 | 3131 | Mark all caches of a repo as invalid in the database. |
|
3118 | 3132 | """ |
|
3119 | 3133 | |
|
3120 | 3134 | try: |
|
3121 | 3135 | qry = Session().query(cls).filter(cls.cache_args == repo_name) |
|
3122 | 3136 | if delete: |
|
3123 | 3137 | log.debug('cache objects deleted for repo %s', |
|
3124 | 3138 | safe_str(repo_name)) |
|
3125 | 3139 | qry.delete() |
|
3126 | 3140 | else: |
|
3127 | 3141 | log.debug('cache objects marked as invalid for repo %s', |
|
3128 | 3142 | safe_str(repo_name)) |
|
3129 | 3143 | qry.update({"cache_active": False}) |
|
3130 | 3144 | |
|
3131 | 3145 | Session().commit() |
|
3132 | 3146 | except Exception: |
|
3133 | 3147 | log.exception( |
|
3134 | 3148 | 'Cache key invalidation failed for repository %s', |
|
3135 | 3149 | safe_str(repo_name)) |
|
3136 | 3150 | Session().rollback() |
|
3137 | 3151 | |
|
3138 | 3152 | @classmethod |
|
3139 | 3153 | def get_active_cache(cls, cache_key): |
|
3140 | 3154 | inv_obj = cls.query().filter(cls.cache_key == cache_key).scalar() |
|
3141 | 3155 | if inv_obj: |
|
3142 | 3156 | return inv_obj |
|
3143 | 3157 | return None |
|
3144 | 3158 | |
|
3145 | 3159 | @classmethod |
|
3146 | 3160 | def repo_context_cache(cls, compute_func, repo_name, cache_type, |
|
3147 | 3161 | thread_scoped=False): |
|
3148 | 3162 | """ |
|
3149 | 3163 | @cache_region('long_term') |
|
3150 | 3164 | def _heavy_calculation(cache_key): |
|
3151 | 3165 | return 'result' |
|
3152 | 3166 | |
|
3153 | 3167 | cache_context = CacheKey.repo_context_cache( |
|
3154 | 3168 | _heavy_calculation, repo_name, cache_type) |
|
3155 | 3169 | |
|
3156 | 3170 | with cache_context as context: |
|
3157 | 3171 | context.invalidate() |
|
3158 | 3172 | computed = context.compute() |
|
3159 | 3173 | |
|
3160 | 3174 | assert computed == 'result' |
|
3161 | 3175 | """ |
|
3162 | 3176 | from rhodecode.lib import caches |
|
3163 | 3177 | return caches.InvalidationContext( |
|
3164 | 3178 | compute_func, repo_name, cache_type, thread_scoped=thread_scoped) |
|
3165 | 3179 | |
|
3166 | 3180 | |
|
3167 | 3181 | class ChangesetComment(Base, BaseModel): |
|
3168 | 3182 | __tablename__ = 'changeset_comments' |
|
3169 | 3183 | __table_args__ = ( |
|
3170 | 3184 | Index('cc_revision_idx', 'revision'), |
|
3171 | 3185 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
3172 | 3186 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}, |
|
3173 | 3187 | ) |
|
3174 | 3188 | |
|
3175 | 3189 | COMMENT_OUTDATED = u'comment_outdated' |
|
3176 | 3190 | COMMENT_TYPE_NOTE = u'note' |
|
3177 | 3191 | COMMENT_TYPE_TODO = u'todo' |
|
3178 | 3192 | COMMENT_TYPES = [COMMENT_TYPE_NOTE, COMMENT_TYPE_TODO] |
|
3179 | 3193 | |
|
3180 | 3194 | comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True) |
|
3181 | 3195 | repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False) |
|
3182 | 3196 | revision = Column('revision', String(40), nullable=True) |
|
3183 | 3197 | pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True) |
|
3184 | 3198 | pull_request_version_id = Column("pull_request_version_id", Integer(), ForeignKey('pull_request_versions.pull_request_version_id'), nullable=True) |
|
3185 | 3199 | line_no = Column('line_no', Unicode(10), nullable=True) |
|
3186 | 3200 | hl_lines = Column('hl_lines', Unicode(512), nullable=True) |
|
3187 | 3201 | f_path = Column('f_path', Unicode(1000), nullable=True) |
|
3188 | 3202 | user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False) |
|
3189 | 3203 | text = Column('text', UnicodeText().with_variant(UnicodeText(25000), 'mysql'), nullable=False) |
|
3190 | 3204 | created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now) |
|
3191 | 3205 | modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now) |
|
3192 | 3206 | renderer = Column('renderer', Unicode(64), nullable=True) |
|
3193 | 3207 | display_state = Column('display_state', Unicode(128), nullable=True) |
|
3194 | 3208 | |
|
3195 | 3209 | comment_type = Column('comment_type', Unicode(128), nullable=True, default=COMMENT_TYPE_NOTE) |
|
3196 | 3210 | resolved_comment_id = Column('resolved_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'), nullable=True) |
|
3197 | 3211 | resolved_comment = relationship('ChangesetComment', remote_side=comment_id, backref='resolved_by') |
|
3198 | 3212 | author = relationship('User', lazy='joined') |
|
3199 | 3213 | repo = relationship('Repository') |
|
3200 | 3214 | status_change = relationship('ChangesetStatus', cascade="all, delete, delete-orphan", lazy='joined') |
|
3201 | 3215 | pull_request = relationship('PullRequest', lazy='joined') |
|
3202 | 3216 | pull_request_version = relationship('PullRequestVersion') |
|
3203 | 3217 | |
|
3204 | 3218 | @classmethod |
|
3205 | 3219 | def get_users(cls, revision=None, pull_request_id=None): |
|
3206 | 3220 | """ |
|
3207 | 3221 | Returns user associated with this ChangesetComment. ie those |
|
3208 | 3222 | who actually commented |
|
3209 | 3223 | |
|
3210 | 3224 | :param cls: |
|
3211 | 3225 | :param revision: |
|
3212 | 3226 | """ |
|
3213 | 3227 | q = Session().query(User)\ |
|
3214 | 3228 | .join(ChangesetComment.author) |
|
3215 | 3229 | if revision: |
|
3216 | 3230 | q = q.filter(cls.revision == revision) |
|
3217 | 3231 | elif pull_request_id: |
|
3218 | 3232 | q = q.filter(cls.pull_request_id == pull_request_id) |
|
3219 | 3233 | return q.all() |
|
3220 | 3234 | |
|
3221 | 3235 | @classmethod |
|
3222 | 3236 | def get_index_from_version(cls, pr_version, versions): |
|
3223 | 3237 | num_versions = [x.pull_request_version_id for x in versions] |
|
3224 | 3238 | try: |
|
3225 | 3239 | return num_versions.index(pr_version) +1 |
|
3226 | 3240 | except (IndexError, ValueError): |
|
3227 | 3241 | return |
|
3228 | 3242 | |
|
3229 | 3243 | @property |
|
3230 | 3244 | def outdated(self): |
|
3231 | 3245 | return self.display_state == self.COMMENT_OUTDATED |
|
3232 | 3246 | |
|
3233 | 3247 | def outdated_at_version(self, version): |
|
3234 | 3248 | """ |
|
3235 | 3249 | Checks if comment is outdated for given pull request version |
|
3236 | 3250 | """ |
|
3237 | 3251 | return self.outdated and self.pull_request_version_id != version |
|
3238 | 3252 | |
|
3239 | 3253 | def older_than_version(self, version): |
|
3240 | 3254 | """ |
|
3241 | 3255 | Checks if comment is made from previous version than given |
|
3242 | 3256 | """ |
|
3243 | 3257 | if version is None: |
|
3244 | 3258 | return self.pull_request_version_id is not None |
|
3245 | 3259 | |
|
3246 | 3260 | return self.pull_request_version_id < version |
|
3247 | 3261 | |
|
3248 | 3262 | @property |
|
3249 | 3263 | def resolved(self): |
|
3250 | 3264 | return self.resolved_by[0] if self.resolved_by else None |
|
3251 | 3265 | |
|
3252 | 3266 | @property |
|
3253 | 3267 | def is_todo(self): |
|
3254 | 3268 | return self.comment_type == self.COMMENT_TYPE_TODO |
|
3255 | 3269 | |
|
3256 | 3270 | @property |
|
3257 | 3271 | def is_inline(self): |
|
3258 | 3272 | return self.line_no and self.f_path |
|
3259 | 3273 | |
|
3260 | 3274 | def get_index_version(self, versions): |
|
3261 | 3275 | return self.get_index_from_version( |
|
3262 | 3276 | self.pull_request_version_id, versions) |
|
3263 | 3277 | |
|
3264 | 3278 | def __repr__(self): |
|
3265 | 3279 | if self.comment_id: |
|
3266 | 3280 | return '<DB:Comment #%s>' % self.comment_id |
|
3267 | 3281 | else: |
|
3268 | 3282 | return '<DB:Comment at %#x>' % id(self) |
|
3269 | 3283 | |
|
3270 | 3284 | def get_api_data(self): |
|
3271 | 3285 | comment = self |
|
3272 | 3286 | data = { |
|
3273 | 3287 | 'comment_id': comment.comment_id, |
|
3274 | 3288 | 'comment_type': comment.comment_type, |
|
3275 | 3289 | 'comment_text': comment.text, |
|
3276 | 3290 | 'comment_status': comment.status_change, |
|
3277 | 3291 | 'comment_f_path': comment.f_path, |
|
3278 | 3292 | 'comment_lineno': comment.line_no, |
|
3279 | 3293 | 'comment_author': comment.author, |
|
3280 | 3294 | 'comment_created_on': comment.created_on |
|
3281 | 3295 | } |
|
3282 | 3296 | return data |
|
3283 | 3297 | |
|
3284 | 3298 | def __json__(self): |
|
3285 | 3299 | data = dict() |
|
3286 | 3300 | data.update(self.get_api_data()) |
|
3287 | 3301 | return data |
|
3288 | 3302 | |
|
3289 | 3303 | |
|
3290 | 3304 | class ChangesetStatus(Base, BaseModel): |
|
3291 | 3305 | __tablename__ = 'changeset_statuses' |
|
3292 | 3306 | __table_args__ = ( |
|
3293 | 3307 | Index('cs_revision_idx', 'revision'), |
|
3294 | 3308 | Index('cs_version_idx', 'version'), |
|
3295 | 3309 | UniqueConstraint('repo_id', 'revision', 'version'), |
|
3296 | 3310 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
3297 | 3311 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} |
|
3298 | 3312 | ) |
|
3299 | 3313 | STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed' |
|
3300 | 3314 | STATUS_APPROVED = 'approved' |
|
3301 | 3315 | STATUS_REJECTED = 'rejected' |
|
3302 | 3316 | STATUS_UNDER_REVIEW = 'under_review' |
|
3303 | 3317 | |
|
3304 | 3318 | STATUSES = [ |
|
3305 | 3319 | (STATUS_NOT_REVIEWED, _("Not Reviewed")), # (no icon) and default |
|
3306 | 3320 | (STATUS_APPROVED, _("Approved")), |
|
3307 | 3321 | (STATUS_REJECTED, _("Rejected")), |
|
3308 | 3322 | (STATUS_UNDER_REVIEW, _("Under Review")), |
|
3309 | 3323 | ] |
|
3310 | 3324 | |
|
3311 | 3325 | changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True) |
|
3312 | 3326 | repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False) |
|
3313 | 3327 | user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None) |
|
3314 | 3328 | revision = Column('revision', String(40), nullable=False) |
|
3315 | 3329 | status = Column('status', String(128), nullable=False, default=DEFAULT) |
|
3316 | 3330 | changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id')) |
|
3317 | 3331 | modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now) |
|
3318 | 3332 | version = Column('version', Integer(), nullable=False, default=0) |
|
3319 | 3333 | pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True) |
|
3320 | 3334 | |
|
3321 | 3335 | author = relationship('User', lazy='joined') |
|
3322 | 3336 | repo = relationship('Repository') |
|
3323 | 3337 | comment = relationship('ChangesetComment', lazy='joined') |
|
3324 | 3338 | pull_request = relationship('PullRequest', lazy='joined') |
|
3325 | 3339 | |
|
3326 | 3340 | def __unicode__(self): |
|
3327 | 3341 | return u"<%s('%s[v%s]:%s')>" % ( |
|
3328 | 3342 | self.__class__.__name__, |
|
3329 | 3343 | self.status, self.version, self.author |
|
3330 | 3344 | ) |
|
3331 | 3345 | |
|
3332 | 3346 | @classmethod |
|
3333 | 3347 | def get_status_lbl(cls, value): |
|
3334 | 3348 | return dict(cls.STATUSES).get(value) |
|
3335 | 3349 | |
|
3336 | 3350 | @property |
|
3337 | 3351 | def status_lbl(self): |
|
3338 | 3352 | return ChangesetStatus.get_status_lbl(self.status) |
|
3339 | 3353 | |
|
3340 | 3354 | def get_api_data(self): |
|
3341 | 3355 | status = self |
|
3342 | 3356 | data = { |
|
3343 | 3357 | 'status_id': status.changeset_status_id, |
|
3344 | 3358 | 'status': status.status, |
|
3345 | 3359 | } |
|
3346 | 3360 | return data |
|
3347 | 3361 | |
|
3348 | 3362 | def __json__(self): |
|
3349 | 3363 | data = dict() |
|
3350 | 3364 | data.update(self.get_api_data()) |
|
3351 | 3365 | return data |
|
3352 | 3366 | |
|
3353 | 3367 | |
|
3354 | 3368 | class _PullRequestBase(BaseModel): |
|
3355 | 3369 | """ |
|
3356 | 3370 | Common attributes of pull request and version entries. |
|
3357 | 3371 | """ |
|
3358 | 3372 | |
|
3359 | 3373 | # .status values |
|
3360 | 3374 | STATUS_NEW = u'new' |
|
3361 | 3375 | STATUS_OPEN = u'open' |
|
3362 | 3376 | STATUS_CLOSED = u'closed' |
|
3363 | 3377 | |
|
3364 | 3378 | title = Column('title', Unicode(255), nullable=True) |
|
3365 | 3379 | description = Column( |
|
3366 | 3380 | 'description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'), |
|
3367 | 3381 | nullable=True) |
|
3368 | 3382 | # new/open/closed status of pull request (not approve/reject/etc) |
|
3369 | 3383 | status = Column('status', Unicode(255), nullable=False, default=STATUS_NEW) |
|
3370 | 3384 | created_on = Column( |
|
3371 | 3385 | 'created_on', DateTime(timezone=False), nullable=False, |
|
3372 | 3386 | default=datetime.datetime.now) |
|
3373 | 3387 | updated_on = Column( |
|
3374 | 3388 | 'updated_on', DateTime(timezone=False), nullable=False, |
|
3375 | 3389 | default=datetime.datetime.now) |
|
3376 | 3390 | |
|
3377 | 3391 | @declared_attr |
|
3378 | 3392 | def user_id(cls): |
|
3379 | 3393 | return Column( |
|
3380 | 3394 | "user_id", Integer(), ForeignKey('users.user_id'), nullable=False, |
|
3381 | 3395 | unique=None) |
|
3382 | 3396 | |
|
3383 | 3397 | # 500 revisions max |
|
3384 | 3398 | _revisions = Column( |
|
3385 | 3399 | 'revisions', UnicodeText().with_variant(UnicodeText(20500), 'mysql')) |
|
3386 | 3400 | |
|
3387 | 3401 | @declared_attr |
|
3388 | 3402 | def source_repo_id(cls): |
|
3389 | 3403 | # TODO: dan: rename column to source_repo_id |
|
3390 | 3404 | return Column( |
|
3391 | 3405 | 'org_repo_id', Integer(), ForeignKey('repositories.repo_id'), |
|
3392 | 3406 | nullable=False) |
|
3393 | 3407 | |
|
3394 | 3408 | source_ref = Column('org_ref', Unicode(255), nullable=False) |
|
3395 | 3409 | |
|
3396 | 3410 | @declared_attr |
|
3397 | 3411 | def target_repo_id(cls): |
|
3398 | 3412 | # TODO: dan: rename column to target_repo_id |
|
3399 | 3413 | return Column( |
|
3400 | 3414 | 'other_repo_id', Integer(), ForeignKey('repositories.repo_id'), |
|
3401 | 3415 | nullable=False) |
|
3402 | 3416 | |
|
3403 | 3417 | target_ref = Column('other_ref', Unicode(255), nullable=False) |
|
3404 | 3418 | _shadow_merge_ref = Column('shadow_merge_ref', Unicode(255), nullable=True) |
|
3405 | 3419 | |
|
3406 | 3420 | # TODO: dan: rename column to last_merge_source_rev |
|
3407 | 3421 | _last_merge_source_rev = Column( |
|
3408 | 3422 | 'last_merge_org_rev', String(40), nullable=True) |
|
3409 | 3423 | # TODO: dan: rename column to last_merge_target_rev |
|
3410 | 3424 | _last_merge_target_rev = Column( |
|
3411 | 3425 | 'last_merge_other_rev', String(40), nullable=True) |
|
3412 | 3426 | _last_merge_status = Column('merge_status', Integer(), nullable=True) |
|
3413 | 3427 | merge_rev = Column('merge_rev', String(40), nullable=True) |
|
3414 | 3428 | |
|
3415 | 3429 | reviewer_data = Column( |
|
3416 | 3430 | 'reviewer_data_json', MutationObj.as_mutable( |
|
3417 | 3431 | JsonType(dialect_map=dict(mysql=UnicodeText(16384))))) |
|
3418 | 3432 | |
|
3419 | 3433 | @property |
|
3420 | 3434 | def reviewer_data_json(self): |
|
3421 | 3435 | return json.dumps(self.reviewer_data) |
|
3422 | 3436 | |
|
3423 | 3437 | @hybrid_property |
|
3424 | 3438 | def description_safe(self): |
|
3425 | 3439 | from rhodecode.lib import helpers as h |
|
3426 | 3440 | return h.escape(self.description) |
|
3427 | 3441 | |
|
3428 | 3442 | @hybrid_property |
|
3429 | 3443 | def revisions(self): |
|
3430 | 3444 | return self._revisions.split(':') if self._revisions else [] |
|
3431 | 3445 | |
|
3432 | 3446 | @revisions.setter |
|
3433 | 3447 | def revisions(self, val): |
|
3434 | 3448 | self._revisions = ':'.join(val) |
|
3435 | 3449 | |
|
3436 | 3450 | @hybrid_property |
|
3437 | 3451 | def last_merge_status(self): |
|
3438 | 3452 | return safe_int(self._last_merge_status) |
|
3439 | 3453 | |
|
3440 | 3454 | @last_merge_status.setter |
|
3441 | 3455 | def last_merge_status(self, val): |
|
3442 | 3456 | self._last_merge_status = val |
|
3443 | 3457 | |
|
3444 | 3458 | @declared_attr |
|
3445 | 3459 | def author(cls): |
|
3446 | 3460 | return relationship('User', lazy='joined') |
|
3447 | 3461 | |
|
3448 | 3462 | @declared_attr |
|
3449 | 3463 | def source_repo(cls): |
|
3450 | 3464 | return relationship( |
|
3451 | 3465 | 'Repository', |
|
3452 | 3466 | primaryjoin='%s.source_repo_id==Repository.repo_id' % cls.__name__) |
|
3453 | 3467 | |
|
3454 | 3468 | @property |
|
3455 | 3469 | def source_ref_parts(self): |
|
3456 | 3470 | return self.unicode_to_reference(self.source_ref) |
|
3457 | 3471 | |
|
3458 | 3472 | @declared_attr |
|
3459 | 3473 | def target_repo(cls): |
|
3460 | 3474 | return relationship( |
|
3461 | 3475 | 'Repository', |
|
3462 | 3476 | primaryjoin='%s.target_repo_id==Repository.repo_id' % cls.__name__) |
|
3463 | 3477 | |
|
3464 | 3478 | @property |
|
3465 | 3479 | def target_ref_parts(self): |
|
3466 | 3480 | return self.unicode_to_reference(self.target_ref) |
|
3467 | 3481 | |
|
3468 | 3482 | @property |
|
3469 | 3483 | def shadow_merge_ref(self): |
|
3470 | 3484 | return self.unicode_to_reference(self._shadow_merge_ref) |
|
3471 | 3485 | |
|
3472 | 3486 | @shadow_merge_ref.setter |
|
3473 | 3487 | def shadow_merge_ref(self, ref): |
|
3474 | 3488 | self._shadow_merge_ref = self.reference_to_unicode(ref) |
|
3475 | 3489 | |
|
3476 | 3490 | def unicode_to_reference(self, raw): |
|
3477 | 3491 | """ |
|
3478 | 3492 | Convert a unicode (or string) to a reference object. |
|
3479 | 3493 | If unicode evaluates to False it returns None. |
|
3480 | 3494 | """ |
|
3481 | 3495 | if raw: |
|
3482 | 3496 | refs = raw.split(':') |
|
3483 | 3497 | return Reference(*refs) |
|
3484 | 3498 | else: |
|
3485 | 3499 | return None |
|
3486 | 3500 | |
|
3487 | 3501 | def reference_to_unicode(self, ref): |
|
3488 | 3502 | """ |
|
3489 | 3503 | Convert a reference object to unicode. |
|
3490 | 3504 | If reference is None it returns None. |
|
3491 | 3505 | """ |
|
3492 | 3506 | if ref: |
|
3493 | 3507 | return u':'.join(ref) |
|
3494 | 3508 | else: |
|
3495 | 3509 | return None |
|
3496 | 3510 | |
|
3497 | 3511 | def get_api_data(self, with_merge_state=True): |
|
3498 | 3512 | from rhodecode.model.pull_request import PullRequestModel |
|
3499 | 3513 | |
|
3500 | 3514 | pull_request = self |
|
3501 | 3515 | if with_merge_state: |
|
3502 | 3516 | merge_status = PullRequestModel().merge_status(pull_request) |
|
3503 | 3517 | merge_state = { |
|
3504 | 3518 | 'status': merge_status[0], |
|
3505 | 3519 | 'message': safe_unicode(merge_status[1]), |
|
3506 | 3520 | } |
|
3507 | 3521 | else: |
|
3508 | 3522 | merge_state = {'status': 'not_available', |
|
3509 | 3523 | 'message': 'not_available'} |
|
3510 | 3524 | |
|
3511 | 3525 | merge_data = { |
|
3512 | 3526 | 'clone_url': PullRequestModel().get_shadow_clone_url(pull_request), |
|
3513 | 3527 | 'reference': ( |
|
3514 | 3528 | pull_request.shadow_merge_ref._asdict() |
|
3515 | 3529 | if pull_request.shadow_merge_ref else None), |
|
3516 | 3530 | } |
|
3517 | 3531 | |
|
3518 | 3532 | data = { |
|
3519 | 3533 | 'pull_request_id': pull_request.pull_request_id, |
|
3520 | 3534 | 'url': PullRequestModel().get_url(pull_request), |
|
3521 | 3535 | 'title': pull_request.title, |
|
3522 | 3536 | 'description': pull_request.description, |
|
3523 | 3537 | 'status': pull_request.status, |
|
3524 | 3538 | 'created_on': pull_request.created_on, |
|
3525 | 3539 | 'updated_on': pull_request.updated_on, |
|
3526 | 3540 | 'commit_ids': pull_request.revisions, |
|
3527 | 3541 | 'review_status': pull_request.calculated_review_status(), |
|
3528 | 3542 | 'mergeable': merge_state, |
|
3529 | 3543 | 'source': { |
|
3530 | 3544 | 'clone_url': pull_request.source_repo.clone_url(), |
|
3531 | 3545 | 'repository': pull_request.source_repo.repo_name, |
|
3532 | 3546 | 'reference': { |
|
3533 | 3547 | 'name': pull_request.source_ref_parts.name, |
|
3534 | 3548 | 'type': pull_request.source_ref_parts.type, |
|
3535 | 3549 | 'commit_id': pull_request.source_ref_parts.commit_id, |
|
3536 | 3550 | }, |
|
3537 | 3551 | }, |
|
3538 | 3552 | 'target': { |
|
3539 | 3553 | 'clone_url': pull_request.target_repo.clone_url(), |
|
3540 | 3554 | 'repository': pull_request.target_repo.repo_name, |
|
3541 | 3555 | 'reference': { |
|
3542 | 3556 | 'name': pull_request.target_ref_parts.name, |
|
3543 | 3557 | 'type': pull_request.target_ref_parts.type, |
|
3544 | 3558 | 'commit_id': pull_request.target_ref_parts.commit_id, |
|
3545 | 3559 | }, |
|
3546 | 3560 | }, |
|
3547 | 3561 | 'merge': merge_data, |
|
3548 | 3562 | 'author': pull_request.author.get_api_data(include_secrets=False, |
|
3549 | 3563 | details='basic'), |
|
3550 | 3564 | 'reviewers': [ |
|
3551 | 3565 | { |
|
3552 | 3566 | 'user': reviewer.get_api_data(include_secrets=False, |
|
3553 | 3567 | details='basic'), |
|
3554 | 3568 | 'reasons': reasons, |
|
3555 | 3569 | 'review_status': st[0][1].status if st else 'not_reviewed', |
|
3556 | 3570 | } |
|
3557 | 3571 | for reviewer, reasons, mandatory, st in |
|
3558 | 3572 | pull_request.reviewers_statuses() |
|
3559 | 3573 | ] |
|
3560 | 3574 | } |
|
3561 | 3575 | |
|
3562 | 3576 | return data |
|
3563 | 3577 | |
|
3564 | 3578 | |
|
3565 | 3579 | class PullRequest(Base, _PullRequestBase): |
|
3566 | 3580 | __tablename__ = 'pull_requests' |
|
3567 | 3581 | __table_args__ = ( |
|
3568 | 3582 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
3569 | 3583 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}, |
|
3570 | 3584 | ) |
|
3571 | 3585 | |
|
3572 | 3586 | pull_request_id = Column( |
|
3573 | 3587 | 'pull_request_id', Integer(), nullable=False, primary_key=True) |
|
3574 | 3588 | |
|
3575 | 3589 | def __repr__(self): |
|
3576 | 3590 | if self.pull_request_id: |
|
3577 | 3591 | return '<DB:PullRequest #%s>' % self.pull_request_id |
|
3578 | 3592 | else: |
|
3579 | 3593 | return '<DB:PullRequest at %#x>' % id(self) |
|
3580 | 3594 | |
|
3581 | 3595 | reviewers = relationship('PullRequestReviewers', |
|
3582 | 3596 | cascade="all, delete, delete-orphan") |
|
3583 | 3597 | statuses = relationship('ChangesetStatus', |
|
3584 | 3598 | cascade="all, delete, delete-orphan") |
|
3585 | 3599 | comments = relationship('ChangesetComment', |
|
3586 | 3600 | cascade="all, delete, delete-orphan") |
|
3587 | 3601 | versions = relationship('PullRequestVersion', |
|
3588 | 3602 | cascade="all, delete, delete-orphan", |
|
3589 | 3603 | lazy='dynamic') |
|
3590 | 3604 | |
|
3591 | 3605 | @classmethod |
|
3592 | 3606 | def get_pr_display_object(cls, pull_request_obj, org_pull_request_obj, |
|
3593 | 3607 | internal_methods=None): |
|
3594 | 3608 | |
|
3595 | 3609 | class PullRequestDisplay(object): |
|
3596 | 3610 | """ |
|
3597 | 3611 | Special object wrapper for showing PullRequest data via Versions |
|
3598 | 3612 | It mimics PR object as close as possible. This is read only object |
|
3599 | 3613 | just for display |
|
3600 | 3614 | """ |
|
3601 | 3615 | |
|
3602 | 3616 | def __init__(self, attrs, internal=None): |
|
3603 | 3617 | self.attrs = attrs |
|
3604 | 3618 | # internal have priority over the given ones via attrs |
|
3605 | 3619 | self.internal = internal or ['versions'] |
|
3606 | 3620 | |
|
3607 | 3621 | def __getattr__(self, item): |
|
3608 | 3622 | if item in self.internal: |
|
3609 | 3623 | return getattr(self, item) |
|
3610 | 3624 | try: |
|
3611 | 3625 | return self.attrs[item] |
|
3612 | 3626 | except KeyError: |
|
3613 | 3627 | raise AttributeError( |
|
3614 | 3628 | '%s object has no attribute %s' % (self, item)) |
|
3615 | 3629 | |
|
3616 | 3630 | def __repr__(self): |
|
3617 | 3631 | return '<DB:PullRequestDisplay #%s>' % self.attrs.get('pull_request_id') |
|
3618 | 3632 | |
|
3619 | 3633 | def versions(self): |
|
3620 | 3634 | return pull_request_obj.versions.order_by( |
|
3621 | 3635 | PullRequestVersion.pull_request_version_id).all() |
|
3622 | 3636 | |
|
3623 | 3637 | def is_closed(self): |
|
3624 | 3638 | return pull_request_obj.is_closed() |
|
3625 | 3639 | |
|
3626 | 3640 | @property |
|
3627 | 3641 | def pull_request_version_id(self): |
|
3628 | 3642 | return getattr(pull_request_obj, 'pull_request_version_id', None) |
|
3629 | 3643 | |
|
3630 | 3644 | attrs = StrictAttributeDict(pull_request_obj.get_api_data()) |
|
3631 | 3645 | |
|
3632 | 3646 | attrs.author = StrictAttributeDict( |
|
3633 | 3647 | pull_request_obj.author.get_api_data()) |
|
3634 | 3648 | if pull_request_obj.target_repo: |
|
3635 | 3649 | attrs.target_repo = StrictAttributeDict( |
|
3636 | 3650 | pull_request_obj.target_repo.get_api_data()) |
|
3637 | 3651 | attrs.target_repo.clone_url = pull_request_obj.target_repo.clone_url |
|
3638 | 3652 | |
|
3639 | 3653 | if pull_request_obj.source_repo: |
|
3640 | 3654 | attrs.source_repo = StrictAttributeDict( |
|
3641 | 3655 | pull_request_obj.source_repo.get_api_data()) |
|
3642 | 3656 | attrs.source_repo.clone_url = pull_request_obj.source_repo.clone_url |
|
3643 | 3657 | |
|
3644 | 3658 | attrs.source_ref_parts = pull_request_obj.source_ref_parts |
|
3645 | 3659 | attrs.target_ref_parts = pull_request_obj.target_ref_parts |
|
3646 | 3660 | attrs.revisions = pull_request_obj.revisions |
|
3647 | 3661 | |
|
3648 | 3662 | attrs.shadow_merge_ref = org_pull_request_obj.shadow_merge_ref |
|
3649 | 3663 | attrs.reviewer_data = org_pull_request_obj.reviewer_data |
|
3650 | 3664 | attrs.reviewer_data_json = org_pull_request_obj.reviewer_data_json |
|
3651 | 3665 | |
|
3652 | 3666 | return PullRequestDisplay(attrs, internal=internal_methods) |
|
3653 | 3667 | |
|
3654 | 3668 | def is_closed(self): |
|
3655 | 3669 | return self.status == self.STATUS_CLOSED |
|
3656 | 3670 | |
|
3657 | 3671 | def __json__(self): |
|
3658 | 3672 | return { |
|
3659 | 3673 | 'revisions': self.revisions, |
|
3660 | 3674 | } |
|
3661 | 3675 | |
|
3662 | 3676 | def calculated_review_status(self): |
|
3663 | 3677 | from rhodecode.model.changeset_status import ChangesetStatusModel |
|
3664 | 3678 | return ChangesetStatusModel().calculated_review_status(self) |
|
3665 | 3679 | |
|
3666 | 3680 | def reviewers_statuses(self): |
|
3667 | 3681 | from rhodecode.model.changeset_status import ChangesetStatusModel |
|
3668 | 3682 | return ChangesetStatusModel().reviewers_statuses(self) |
|
3669 | 3683 | |
|
3670 | 3684 | @property |
|
3671 | 3685 | def workspace_id(self): |
|
3672 | 3686 | from rhodecode.model.pull_request import PullRequestModel |
|
3673 | 3687 | return PullRequestModel()._workspace_id(self) |
|
3674 | 3688 | |
|
3675 | 3689 | def get_shadow_repo(self): |
|
3676 | 3690 | workspace_id = self.workspace_id |
|
3677 | 3691 | vcs_obj = self.target_repo.scm_instance() |
|
3678 | 3692 | shadow_repository_path = vcs_obj._get_shadow_repository_path( |
|
3679 | 3693 | workspace_id) |
|
3680 | 3694 | return vcs_obj._get_shadow_instance(shadow_repository_path) |
|
3681 | 3695 | |
|
3682 | 3696 | |
|
3683 | 3697 | class PullRequestVersion(Base, _PullRequestBase): |
|
3684 | 3698 | __tablename__ = 'pull_request_versions' |
|
3685 | 3699 | __table_args__ = ( |
|
3686 | 3700 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
3687 | 3701 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}, |
|
3688 | 3702 | ) |
|
3689 | 3703 | |
|
3690 | 3704 | pull_request_version_id = Column( |
|
3691 | 3705 | 'pull_request_version_id', Integer(), nullable=False, primary_key=True) |
|
3692 | 3706 | pull_request_id = Column( |
|
3693 | 3707 | 'pull_request_id', Integer(), |
|
3694 | 3708 | ForeignKey('pull_requests.pull_request_id'), nullable=False) |
|
3695 | 3709 | pull_request = relationship('PullRequest') |
|
3696 | 3710 | |
|
3697 | 3711 | def __repr__(self): |
|
3698 | 3712 | if self.pull_request_version_id: |
|
3699 | 3713 | return '<DB:PullRequestVersion #%s>' % self.pull_request_version_id |
|
3700 | 3714 | else: |
|
3701 | 3715 | return '<DB:PullRequestVersion at %#x>' % id(self) |
|
3702 | 3716 | |
|
3703 | 3717 | @property |
|
3704 | 3718 | def reviewers(self): |
|
3705 | 3719 | return self.pull_request.reviewers |
|
3706 | 3720 | |
|
3707 | 3721 | @property |
|
3708 | 3722 | def versions(self): |
|
3709 | 3723 | return self.pull_request.versions |
|
3710 | 3724 | |
|
3711 | 3725 | def is_closed(self): |
|
3712 | 3726 | # calculate from original |
|
3713 | 3727 | return self.pull_request.status == self.STATUS_CLOSED |
|
3714 | 3728 | |
|
3715 | 3729 | def calculated_review_status(self): |
|
3716 | 3730 | return self.pull_request.calculated_review_status() |
|
3717 | 3731 | |
|
3718 | 3732 | def reviewers_statuses(self): |
|
3719 | 3733 | return self.pull_request.reviewers_statuses() |
|
3720 | 3734 | |
|
3721 | 3735 | |
|
3722 | 3736 | class PullRequestReviewers(Base, BaseModel): |
|
3723 | 3737 | __tablename__ = 'pull_request_reviewers' |
|
3724 | 3738 | __table_args__ = ( |
|
3725 | 3739 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
3726 | 3740 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}, |
|
3727 | 3741 | ) |
|
3728 | 3742 | |
|
3729 | 3743 | @hybrid_property |
|
3730 | 3744 | def reasons(self): |
|
3731 | 3745 | if not self._reasons: |
|
3732 | 3746 | return [] |
|
3733 | 3747 | return self._reasons |
|
3734 | 3748 | |
|
3735 | 3749 | @reasons.setter |
|
3736 | 3750 | def reasons(self, val): |
|
3737 | 3751 | val = val or [] |
|
3738 | 3752 | if any(not isinstance(x, basestring) for x in val): |
|
3739 | 3753 | raise Exception('invalid reasons type, must be list of strings') |
|
3740 | 3754 | self._reasons = val |
|
3741 | 3755 | |
|
3742 | 3756 | pull_requests_reviewers_id = Column( |
|
3743 | 3757 | 'pull_requests_reviewers_id', Integer(), nullable=False, |
|
3744 | 3758 | primary_key=True) |
|
3745 | 3759 | pull_request_id = Column( |
|
3746 | 3760 | "pull_request_id", Integer(), |
|
3747 | 3761 | ForeignKey('pull_requests.pull_request_id'), nullable=False) |
|
3748 | 3762 | user_id = Column( |
|
3749 | 3763 | "user_id", Integer(), ForeignKey('users.user_id'), nullable=True) |
|
3750 | 3764 | _reasons = Column( |
|
3751 | 3765 | 'reason', MutationList.as_mutable( |
|
3752 | 3766 | JsonType('list', dialect_map=dict(mysql=UnicodeText(16384))))) |
|
3753 | 3767 | mandatory = Column("mandatory", Boolean(), nullable=False, default=False) |
|
3754 | 3768 | user = relationship('User') |
|
3755 | 3769 | pull_request = relationship('PullRequest') |
|
3756 | 3770 | |
|
3757 | 3771 | |
|
3758 | 3772 | class Notification(Base, BaseModel): |
|
3759 | 3773 | __tablename__ = 'notifications' |
|
3760 | 3774 | __table_args__ = ( |
|
3761 | 3775 | Index('notification_type_idx', 'type'), |
|
3762 | 3776 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
3763 | 3777 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}, |
|
3764 | 3778 | ) |
|
3765 | 3779 | |
|
3766 | 3780 | TYPE_CHANGESET_COMMENT = u'cs_comment' |
|
3767 | 3781 | TYPE_MESSAGE = u'message' |
|
3768 | 3782 | TYPE_MENTION = u'mention' |
|
3769 | 3783 | TYPE_REGISTRATION = u'registration' |
|
3770 | 3784 | TYPE_PULL_REQUEST = u'pull_request' |
|
3771 | 3785 | TYPE_PULL_REQUEST_COMMENT = u'pull_request_comment' |
|
3772 | 3786 | |
|
3773 | 3787 | notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True) |
|
3774 | 3788 | subject = Column('subject', Unicode(512), nullable=True) |
|
3775 | 3789 | body = Column('body', UnicodeText().with_variant(UnicodeText(50000), 'mysql'), nullable=True) |
|
3776 | 3790 | created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True) |
|
3777 | 3791 | created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now) |
|
3778 | 3792 | type_ = Column('type', Unicode(255)) |
|
3779 | 3793 | |
|
3780 | 3794 | created_by_user = relationship('User') |
|
3781 | 3795 | notifications_to_users = relationship('UserNotification', lazy='joined', |
|
3782 | 3796 | cascade="all, delete, delete-orphan") |
|
3783 | 3797 | |
|
3784 | 3798 | @property |
|
3785 | 3799 | def recipients(self): |
|
3786 | 3800 | return [x.user for x in UserNotification.query()\ |
|
3787 | 3801 | .filter(UserNotification.notification == self)\ |
|
3788 | 3802 | .order_by(UserNotification.user_id.asc()).all()] |
|
3789 | 3803 | |
|
3790 | 3804 | @classmethod |
|
3791 | 3805 | def create(cls, created_by, subject, body, recipients, type_=None): |
|
3792 | 3806 | if type_ is None: |
|
3793 | 3807 | type_ = Notification.TYPE_MESSAGE |
|
3794 | 3808 | |
|
3795 | 3809 | notification = cls() |
|
3796 | 3810 | notification.created_by_user = created_by |
|
3797 | 3811 | notification.subject = subject |
|
3798 | 3812 | notification.body = body |
|
3799 | 3813 | notification.type_ = type_ |
|
3800 | 3814 | notification.created_on = datetime.datetime.now() |
|
3801 | 3815 | |
|
3802 | 3816 | for u in recipients: |
|
3803 | 3817 | assoc = UserNotification() |
|
3804 | 3818 | assoc.notification = notification |
|
3805 | 3819 | |
|
3806 | 3820 | # if created_by is inside recipients mark his notification |
|
3807 | 3821 | # as read |
|
3808 | 3822 | if u.user_id == created_by.user_id: |
|
3809 | 3823 | assoc.read = True |
|
3810 | 3824 | |
|
3811 | 3825 | u.notifications.append(assoc) |
|
3812 | 3826 | Session().add(notification) |
|
3813 | 3827 | |
|
3814 | 3828 | return notification |
|
3815 | 3829 | |
|
3816 | 3830 | |
|
3817 | 3831 | class UserNotification(Base, BaseModel): |
|
3818 | 3832 | __tablename__ = 'user_to_notification' |
|
3819 | 3833 | __table_args__ = ( |
|
3820 | 3834 | UniqueConstraint('user_id', 'notification_id'), |
|
3821 | 3835 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
3822 | 3836 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} |
|
3823 | 3837 | ) |
|
3824 | 3838 | user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True) |
|
3825 | 3839 | notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True) |
|
3826 | 3840 | read = Column('read', Boolean, default=False) |
|
3827 | 3841 | sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None) |
|
3828 | 3842 | |
|
3829 | 3843 | user = relationship('User', lazy="joined") |
|
3830 | 3844 | notification = relationship('Notification', lazy="joined", |
|
3831 | 3845 | order_by=lambda: Notification.created_on.desc(),) |
|
3832 | 3846 | |
|
3833 | 3847 | def mark_as_read(self): |
|
3834 | 3848 | self.read = True |
|
3835 | 3849 | Session().add(self) |
|
3836 | 3850 | |
|
3837 | 3851 | |
|
3838 | 3852 | class Gist(Base, BaseModel): |
|
3839 | 3853 | __tablename__ = 'gists' |
|
3840 | 3854 | __table_args__ = ( |
|
3841 | 3855 | Index('g_gist_access_id_idx', 'gist_access_id'), |
|
3842 | 3856 | Index('g_created_on_idx', 'created_on'), |
|
3843 | 3857 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
3844 | 3858 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} |
|
3845 | 3859 | ) |
|
3846 | 3860 | GIST_PUBLIC = u'public' |
|
3847 | 3861 | GIST_PRIVATE = u'private' |
|
3848 | 3862 | DEFAULT_FILENAME = u'gistfile1.txt' |
|
3849 | 3863 | |
|
3850 | 3864 | ACL_LEVEL_PUBLIC = u'acl_public' |
|
3851 | 3865 | ACL_LEVEL_PRIVATE = u'acl_private' |
|
3852 | 3866 | |
|
3853 | 3867 | gist_id = Column('gist_id', Integer(), primary_key=True) |
|
3854 | 3868 | gist_access_id = Column('gist_access_id', Unicode(250)) |
|
3855 | 3869 | gist_description = Column('gist_description', UnicodeText().with_variant(UnicodeText(1024), 'mysql')) |
|
3856 | 3870 | gist_owner = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True) |
|
3857 | 3871 | gist_expires = Column('gist_expires', Float(53), nullable=False) |
|
3858 | 3872 | gist_type = Column('gist_type', Unicode(128), nullable=False) |
|
3859 | 3873 | created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now) |
|
3860 | 3874 | modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now) |
|
3861 | 3875 | acl_level = Column('acl_level', Unicode(128), nullable=True) |
|
3862 | 3876 | |
|
3863 | 3877 | owner = relationship('User') |
|
3864 | 3878 | |
|
3865 | 3879 | def __repr__(self): |
|
3866 | 3880 | return '<Gist:[%s]%s>' % (self.gist_type, self.gist_access_id) |
|
3867 | 3881 | |
|
3868 | 3882 | @hybrid_property |
|
3869 | 3883 | def description_safe(self): |
|
3870 | 3884 | from rhodecode.lib import helpers as h |
|
3871 | 3885 | return h.escape(self.gist_description) |
|
3872 | 3886 | |
|
3873 | 3887 | @classmethod |
|
3874 | 3888 | def get_or_404(cls, id_): |
|
3875 | 3889 | from pyramid.httpexceptions import HTTPNotFound |
|
3876 | 3890 | |
|
3877 | 3891 | res = cls.query().filter(cls.gist_access_id == id_).scalar() |
|
3878 | 3892 | if not res: |
|
3879 | 3893 | raise HTTPNotFound() |
|
3880 | 3894 | return res |
|
3881 | 3895 | |
|
3882 | 3896 | @classmethod |
|
3883 | 3897 | def get_by_access_id(cls, gist_access_id): |
|
3884 | 3898 | return cls.query().filter(cls.gist_access_id == gist_access_id).scalar() |
|
3885 | 3899 | |
|
3886 | 3900 | def gist_url(self): |
|
3887 | 3901 | from rhodecode.model.gist import GistModel |
|
3888 | 3902 | return GistModel().get_url(self) |
|
3889 | 3903 | |
|
3890 | 3904 | @classmethod |
|
3891 | 3905 | def base_path(cls): |
|
3892 | 3906 | """ |
|
3893 | 3907 | Returns base path when all gists are stored |
|
3894 | 3908 | |
|
3895 | 3909 | :param cls: |
|
3896 | 3910 | """ |
|
3897 | 3911 | from rhodecode.model.gist import GIST_STORE_LOC |
|
3898 | 3912 | q = Session().query(RhodeCodeUi)\ |
|
3899 | 3913 | .filter(RhodeCodeUi.ui_key == URL_SEP) |
|
3900 | 3914 | q = q.options(FromCache("sql_cache_short", "repository_repo_path")) |
|
3901 | 3915 | return os.path.join(q.one().ui_value, GIST_STORE_LOC) |
|
3902 | 3916 | |
|
3903 | 3917 | def get_api_data(self): |
|
3904 | 3918 | """ |
|
3905 | 3919 | Common function for generating gist related data for API |
|
3906 | 3920 | """ |
|
3907 | 3921 | gist = self |
|
3908 | 3922 | data = { |
|
3909 | 3923 | 'gist_id': gist.gist_id, |
|
3910 | 3924 | 'type': gist.gist_type, |
|
3911 | 3925 | 'access_id': gist.gist_access_id, |
|
3912 | 3926 | 'description': gist.gist_description, |
|
3913 | 3927 | 'url': gist.gist_url(), |
|
3914 | 3928 | 'expires': gist.gist_expires, |
|
3915 | 3929 | 'created_on': gist.created_on, |
|
3916 | 3930 | 'modified_at': gist.modified_at, |
|
3917 | 3931 | 'content': None, |
|
3918 | 3932 | 'acl_level': gist.acl_level, |
|
3919 | 3933 | } |
|
3920 | 3934 | return data |
|
3921 | 3935 | |
|
3922 | 3936 | def __json__(self): |
|
3923 | 3937 | data = dict( |
|
3924 | 3938 | ) |
|
3925 | 3939 | data.update(self.get_api_data()) |
|
3926 | 3940 | return data |
|
3927 | 3941 | # SCM functions |
|
3928 | 3942 | |
|
3929 | 3943 | def scm_instance(self, **kwargs): |
|
3930 | 3944 | full_repo_path = os.path.join(self.base_path(), self.gist_access_id) |
|
3931 | 3945 | return get_vcs_instance( |
|
3932 | 3946 | repo_path=safe_str(full_repo_path), create=False) |
|
3933 | 3947 | |
|
3934 | 3948 | |
|
3935 | 3949 | class ExternalIdentity(Base, BaseModel): |
|
3936 | 3950 | __tablename__ = 'external_identities' |
|
3937 | 3951 | __table_args__ = ( |
|
3938 | 3952 | Index('local_user_id_idx', 'local_user_id'), |
|
3939 | 3953 | Index('external_id_idx', 'external_id'), |
|
3940 | 3954 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
3941 | 3955 | 'mysql_charset': 'utf8'}) |
|
3942 | 3956 | |
|
3943 | 3957 | external_id = Column('external_id', Unicode(255), default=u'', |
|
3944 | 3958 | primary_key=True) |
|
3945 | 3959 | external_username = Column('external_username', Unicode(1024), default=u'') |
|
3946 | 3960 | local_user_id = Column('local_user_id', Integer(), |
|
3947 | 3961 | ForeignKey('users.user_id'), primary_key=True) |
|
3948 | 3962 | provider_name = Column('provider_name', Unicode(255), default=u'', |
|
3949 | 3963 | primary_key=True) |
|
3950 | 3964 | access_token = Column('access_token', String(1024), default=u'') |
|
3951 | 3965 | alt_token = Column('alt_token', String(1024), default=u'') |
|
3952 | 3966 | token_secret = Column('token_secret', String(1024), default=u'') |
|
3953 | 3967 | |
|
3954 | 3968 | @classmethod |
|
3955 | 3969 | def by_external_id_and_provider(cls, external_id, provider_name, |
|
3956 | 3970 | local_user_id=None): |
|
3957 | 3971 | """ |
|
3958 | 3972 | Returns ExternalIdentity instance based on search params |
|
3959 | 3973 | |
|
3960 | 3974 | :param external_id: |
|
3961 | 3975 | :param provider_name: |
|
3962 | 3976 | :return: ExternalIdentity |
|
3963 | 3977 | """ |
|
3964 | 3978 | query = cls.query() |
|
3965 | 3979 | query = query.filter(cls.external_id == external_id) |
|
3966 | 3980 | query = query.filter(cls.provider_name == provider_name) |
|
3967 | 3981 | if local_user_id: |
|
3968 | 3982 | query = query.filter(cls.local_user_id == local_user_id) |
|
3969 | 3983 | return query.first() |
|
3970 | 3984 | |
|
3971 | 3985 | @classmethod |
|
3972 | 3986 | def user_by_external_id_and_provider(cls, external_id, provider_name): |
|
3973 | 3987 | """ |
|
3974 | 3988 | Returns User instance based on search params |
|
3975 | 3989 | |
|
3976 | 3990 | :param external_id: |
|
3977 | 3991 | :param provider_name: |
|
3978 | 3992 | :return: User |
|
3979 | 3993 | """ |
|
3980 | 3994 | query = User.query() |
|
3981 | 3995 | query = query.filter(cls.external_id == external_id) |
|
3982 | 3996 | query = query.filter(cls.provider_name == provider_name) |
|
3983 | 3997 | query = query.filter(User.user_id == cls.local_user_id) |
|
3984 | 3998 | return query.first() |
|
3985 | 3999 | |
|
3986 | 4000 | @classmethod |
|
3987 | 4001 | def by_local_user_id(cls, local_user_id): |
|
3988 | 4002 | """ |
|
3989 | 4003 | Returns all tokens for user |
|
3990 | 4004 | |
|
3991 | 4005 | :param local_user_id: |
|
3992 | 4006 | :return: ExternalIdentity |
|
3993 | 4007 | """ |
|
3994 | 4008 | query = cls.query() |
|
3995 | 4009 | query = query.filter(cls.local_user_id == local_user_id) |
|
3996 | 4010 | return query |
|
3997 | 4011 | |
|
3998 | 4012 | |
|
3999 | 4013 | class Integration(Base, BaseModel): |
|
4000 | 4014 | __tablename__ = 'integrations' |
|
4001 | 4015 | __table_args__ = ( |
|
4002 | 4016 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
4003 | 4017 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} |
|
4004 | 4018 | ) |
|
4005 | 4019 | |
|
4006 | 4020 | integration_id = Column('integration_id', Integer(), primary_key=True) |
|
4007 | 4021 | integration_type = Column('integration_type', String(255)) |
|
4008 | 4022 | enabled = Column('enabled', Boolean(), nullable=False) |
|
4009 | 4023 | name = Column('name', String(255), nullable=False) |
|
4010 | 4024 | child_repos_only = Column('child_repos_only', Boolean(), nullable=False, |
|
4011 | 4025 | default=False) |
|
4012 | 4026 | |
|
4013 | 4027 | settings = Column( |
|
4014 | 4028 | 'settings_json', MutationObj.as_mutable( |
|
4015 | 4029 | JsonType(dialect_map=dict(mysql=UnicodeText(16384))))) |
|
4016 | 4030 | repo_id = Column( |
|
4017 | 4031 | 'repo_id', Integer(), ForeignKey('repositories.repo_id'), |
|
4018 | 4032 | nullable=True, unique=None, default=None) |
|
4019 | 4033 | repo = relationship('Repository', lazy='joined') |
|
4020 | 4034 | |
|
4021 | 4035 | repo_group_id = Column( |
|
4022 | 4036 | 'repo_group_id', Integer(), ForeignKey('groups.group_id'), |
|
4023 | 4037 | nullable=True, unique=None, default=None) |
|
4024 | 4038 | repo_group = relationship('RepoGroup', lazy='joined') |
|
4025 | 4039 | |
|
4026 | 4040 | @property |
|
4027 | 4041 | def scope(self): |
|
4028 | 4042 | if self.repo: |
|
4029 | 4043 | return repr(self.repo) |
|
4030 | 4044 | if self.repo_group: |
|
4031 | 4045 | if self.child_repos_only: |
|
4032 | 4046 | return repr(self.repo_group) + ' (child repos only)' |
|
4033 | 4047 | else: |
|
4034 | 4048 | return repr(self.repo_group) + ' (recursive)' |
|
4035 | 4049 | if self.child_repos_only: |
|
4036 | 4050 | return 'root_repos' |
|
4037 | 4051 | return 'global' |
|
4038 | 4052 | |
|
4039 | 4053 | def __repr__(self): |
|
4040 | 4054 | return '<Integration(%r, %r)>' % (self.integration_type, self.scope) |
|
4041 | 4055 | |
|
4042 | 4056 | |
|
4043 | 4057 | class RepoReviewRuleUser(Base, BaseModel): |
|
4044 | 4058 | __tablename__ = 'repo_review_rules_users' |
|
4045 | 4059 | __table_args__ = ( |
|
4046 | 4060 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
4047 | 4061 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,} |
|
4048 | 4062 | ) |
|
4049 | 4063 | repo_review_rule_user_id = Column('repo_review_rule_user_id', Integer(), primary_key=True) |
|
4050 | 4064 | repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id')) |
|
4051 | 4065 | user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False) |
|
4052 | 4066 | mandatory = Column("mandatory", Boolean(), nullable=False, default=False) |
|
4053 | 4067 | user = relationship('User') |
|
4054 | 4068 | |
|
4055 | 4069 | def rule_data(self): |
|
4056 | 4070 | return { |
|
4057 | 4071 | 'mandatory': self.mandatory |
|
4058 | 4072 | } |
|
4059 | 4073 | |
|
4060 | 4074 | |
|
4061 | 4075 | class RepoReviewRuleUserGroup(Base, BaseModel): |
|
4062 | 4076 | __tablename__ = 'repo_review_rules_users_groups' |
|
4063 | 4077 | __table_args__ = ( |
|
4064 | 4078 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
4065 | 4079 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,} |
|
4066 | 4080 | ) |
|
4067 | 4081 | repo_review_rule_users_group_id = Column('repo_review_rule_users_group_id', Integer(), primary_key=True) |
|
4068 | 4082 | repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id')) |
|
4069 | 4083 | users_group_id = Column("users_group_id", Integer(),ForeignKey('users_groups.users_group_id'), nullable=False) |
|
4070 | 4084 | mandatory = Column("mandatory", Boolean(), nullable=False, default=False) |
|
4071 | 4085 | users_group = relationship('UserGroup') |
|
4072 | 4086 | |
|
4073 | 4087 | def rule_data(self): |
|
4074 | 4088 | return { |
|
4075 | 4089 | 'mandatory': self.mandatory |
|
4076 | 4090 | } |
|
4077 | 4091 | |
|
4078 | 4092 | |
|
4079 | 4093 | class RepoReviewRule(Base, BaseModel): |
|
4080 | 4094 | __tablename__ = 'repo_review_rules' |
|
4081 | 4095 | __table_args__ = ( |
|
4082 | 4096 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
4083 | 4097 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,} |
|
4084 | 4098 | ) |
|
4085 | 4099 | |
|
4086 | 4100 | repo_review_rule_id = Column( |
|
4087 | 4101 | 'repo_review_rule_id', Integer(), primary_key=True) |
|
4088 | 4102 | repo_id = Column( |
|
4089 | 4103 | "repo_id", Integer(), ForeignKey('repositories.repo_id')) |
|
4090 | 4104 | repo = relationship('Repository', backref='review_rules') |
|
4091 | 4105 | |
|
4092 | 4106 | _branch_pattern = Column("branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob |
|
4093 | 4107 | _file_pattern = Column("file_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob |
|
4094 | 4108 | |
|
4095 | 4109 | use_authors_for_review = Column("use_authors_for_review", Boolean(), nullable=False, default=False) |
|
4096 | 4110 | forbid_author_to_review = Column("forbid_author_to_review", Boolean(), nullable=False, default=False) |
|
4097 | 4111 | forbid_commit_author_to_review = Column("forbid_commit_author_to_review", Boolean(), nullable=False, default=False) |
|
4098 | 4112 | forbid_adding_reviewers = Column("forbid_adding_reviewers", Boolean(), nullable=False, default=False) |
|
4099 | 4113 | |
|
4100 | 4114 | rule_users = relationship('RepoReviewRuleUser') |
|
4101 | 4115 | rule_user_groups = relationship('RepoReviewRuleUserGroup') |
|
4102 | 4116 | |
|
4103 | 4117 | @hybrid_property |
|
4104 | 4118 | def branch_pattern(self): |
|
4105 | 4119 | return self._branch_pattern or '*' |
|
4106 | 4120 | |
|
4107 | 4121 | def _validate_glob(self, value): |
|
4108 | 4122 | re.compile('^' + glob2re(value) + '$') |
|
4109 | 4123 | |
|
4110 | 4124 | @branch_pattern.setter |
|
4111 | 4125 | def branch_pattern(self, value): |
|
4112 | 4126 | self._validate_glob(value) |
|
4113 | 4127 | self._branch_pattern = value or '*' |
|
4114 | 4128 | |
|
4115 | 4129 | @hybrid_property |
|
4116 | 4130 | def file_pattern(self): |
|
4117 | 4131 | return self._file_pattern or '*' |
|
4118 | 4132 | |
|
4119 | 4133 | @file_pattern.setter |
|
4120 | 4134 | def file_pattern(self, value): |
|
4121 | 4135 | self._validate_glob(value) |
|
4122 | 4136 | self._file_pattern = value or '*' |
|
4123 | 4137 | |
|
4124 | 4138 | def matches(self, branch, files_changed): |
|
4125 | 4139 | """ |
|
4126 | 4140 | Check if this review rule matches a branch/files in a pull request |
|
4127 | 4141 | |
|
4128 | 4142 | :param branch: branch name for the commit |
|
4129 | 4143 | :param files_changed: list of file paths changed in the pull request |
|
4130 | 4144 | """ |
|
4131 | 4145 | |
|
4132 | 4146 | branch = branch or '' |
|
4133 | 4147 | files_changed = files_changed or [] |
|
4134 | 4148 | |
|
4135 | 4149 | branch_matches = True |
|
4136 | 4150 | if branch: |
|
4137 | 4151 | branch_regex = re.compile('^' + glob2re(self.branch_pattern) + '$') |
|
4138 | 4152 | branch_matches = bool(branch_regex.search(branch)) |
|
4139 | 4153 | |
|
4140 | 4154 | files_matches = True |
|
4141 | 4155 | if self.file_pattern != '*': |
|
4142 | 4156 | files_matches = False |
|
4143 | 4157 | file_regex = re.compile(glob2re(self.file_pattern)) |
|
4144 | 4158 | for filename in files_changed: |
|
4145 | 4159 | if file_regex.search(filename): |
|
4146 | 4160 | files_matches = True |
|
4147 | 4161 | break |
|
4148 | 4162 | |
|
4149 | 4163 | return branch_matches and files_matches |
|
4150 | 4164 | |
|
4151 | 4165 | @property |
|
4152 | 4166 | def review_users(self): |
|
4153 | 4167 | """ Returns the users which this rule applies to """ |
|
4154 | 4168 | |
|
4155 | 4169 | users = collections.OrderedDict() |
|
4156 | 4170 | |
|
4157 | 4171 | for rule_user in self.rule_users: |
|
4158 | 4172 | if rule_user.user.active: |
|
4159 | 4173 | if rule_user.user not in users: |
|
4160 | 4174 | users[rule_user.user.username] = { |
|
4161 | 4175 | 'user': rule_user.user, |
|
4162 | 4176 | 'source': 'user', |
|
4163 | 4177 | 'source_data': {}, |
|
4164 | 4178 | 'data': rule_user.rule_data() |
|
4165 | 4179 | } |
|
4166 | 4180 | |
|
4167 | 4181 | for rule_user_group in self.rule_user_groups: |
|
4168 | 4182 | source_data = { |
|
4169 | 4183 | 'name': rule_user_group.users_group.users_group_name, |
|
4170 | 4184 | 'members': len(rule_user_group.users_group.members) |
|
4171 | 4185 | } |
|
4172 | 4186 | for member in rule_user_group.users_group.members: |
|
4173 | 4187 | if member.user.active: |
|
4174 | 4188 | users[member.user.username] = { |
|
4175 | 4189 | 'user': member.user, |
|
4176 | 4190 | 'source': 'user_group', |
|
4177 | 4191 | 'source_data': source_data, |
|
4178 | 4192 | 'data': rule_user_group.rule_data() |
|
4179 | 4193 | } |
|
4180 | 4194 | |
|
4181 | 4195 | return users |
|
4182 | 4196 | |
|
4183 | 4197 | def __repr__(self): |
|
4184 | 4198 | return '<RepoReviewerRule(id=%r, repo=%r)>' % ( |
|
4185 | 4199 | self.repo_review_rule_id, self.repo) |
|
4186 | 4200 | |
|
4187 | 4201 | |
|
4188 | 4202 | class DbMigrateVersion(Base, BaseModel): |
|
4189 | 4203 | __tablename__ = 'db_migrate_version' |
|
4190 | 4204 | __table_args__ = ( |
|
4191 | 4205 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
4192 | 4206 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}, |
|
4193 | 4207 | ) |
|
4194 | 4208 | repository_id = Column('repository_id', String(250), primary_key=True) |
|
4195 | 4209 | repository_path = Column('repository_path', Text) |
|
4196 | 4210 | version = Column('version', Integer) |
|
4197 | 4211 | |
|
4198 | 4212 | |
|
4199 | 4213 | class DbSession(Base, BaseModel): |
|
4200 | 4214 | __tablename__ = 'db_session' |
|
4201 | 4215 | __table_args__ = ( |
|
4202 | 4216 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
4203 | 4217 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}, |
|
4204 | 4218 | ) |
|
4205 | 4219 | |
|
4206 | 4220 | def __repr__(self): |
|
4207 | 4221 | return '<DB:DbSession({})>'.format(self.id) |
|
4208 | 4222 | |
|
4209 | 4223 | id = Column('id', Integer()) |
|
4210 | 4224 | namespace = Column('namespace', String(255), primary_key=True) |
|
4211 | 4225 | accessed = Column('accessed', DateTime, nullable=False) |
|
4212 | 4226 | created = Column('created', DateTime, nullable=False) |
|
4213 | 4227 | data = Column('data', PickleType, nullable=False) |
@@ -1,635 +1,641 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | |
|
3 | 3 | # Copyright (C) 2011-2017 RhodeCode GmbH |
|
4 | 4 | # |
|
5 | 5 | # This program is free software: you can redistribute it and/or modify |
|
6 | 6 | # it under the terms of the GNU Affero General Public License, version 3 |
|
7 | 7 | # (only), as published by the Free Software Foundation. |
|
8 | 8 | # |
|
9 | 9 | # This program is distributed in the hope that it will be useful, |
|
10 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of |
|
11 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|
12 | 12 | # GNU General Public License for more details. |
|
13 | 13 | # |
|
14 | 14 | # You should have received a copy of the GNU Affero General Public License |
|
15 | 15 | # along with this program. If not, see <http://www.gnu.org/licenses/>. |
|
16 | 16 | # |
|
17 | 17 | # This program is dual-licensed. If you wish to learn more about the |
|
18 | 18 | # RhodeCode Enterprise Edition, including its added features, Support services, |
|
19 | 19 | # and proprietary license terms, please see https://rhodecode.com/licenses/ |
|
20 | 20 | |
|
21 | 21 | import logging |
|
22 | 22 | import traceback |
|
23 | 23 | |
|
24 | 24 | from rhodecode.lib.utils2 import safe_str, safe_unicode |
|
25 | 25 | from rhodecode.lib.exceptions import ( |
|
26 | 26 | UserGroupAssignedException, RepoGroupAssignmentError) |
|
27 | 27 | from rhodecode.lib.utils2 import ( |
|
28 | 28 | get_current_rhodecode_user, action_logger_generic) |
|
29 | 29 | from rhodecode.model import BaseModel |
|
30 | 30 | from rhodecode.model.scm import UserGroupList |
|
31 | 31 | from rhodecode.model.db import ( |
|
32 | 32 | true, func, User, UserGroupMember, UserGroup, |
|
33 | 33 | UserGroupRepoToPerm, Permission, UserGroupToPerm, UserUserGroupToPerm, |
|
34 | 34 | UserGroupUserGroupToPerm, UserGroupRepoGroupToPerm) |
|
35 | 35 | |
|
36 | 36 | |
|
37 | 37 | log = logging.getLogger(__name__) |
|
38 | 38 | |
|
39 | 39 | |
|
40 | 40 | class UserGroupModel(BaseModel): |
|
41 | 41 | |
|
42 | 42 | cls = UserGroup |
|
43 | 43 | |
|
44 | 44 | def _get_user_group(self, user_group): |
|
45 | 45 | return self._get_instance(UserGroup, user_group, |
|
46 | 46 | callback=UserGroup.get_by_group_name) |
|
47 | 47 | |
|
48 | 48 | def _create_default_perms(self, user_group): |
|
49 | 49 | # create default permission |
|
50 | 50 | default_perm = 'usergroup.read' |
|
51 | 51 | def_user = User.get_default_user() |
|
52 | 52 | for p in def_user.user_perms: |
|
53 | 53 | if p.permission.permission_name.startswith('usergroup.'): |
|
54 | 54 | default_perm = p.permission.permission_name |
|
55 | 55 | break |
|
56 | 56 | |
|
57 | 57 | user_group_to_perm = UserUserGroupToPerm() |
|
58 | 58 | user_group_to_perm.permission = Permission.get_by_key(default_perm) |
|
59 | 59 | |
|
60 | 60 | user_group_to_perm.user_group = user_group |
|
61 | 61 | user_group_to_perm.user_id = def_user.user_id |
|
62 | 62 | return user_group_to_perm |
|
63 | 63 | |
|
64 | 64 | def update_permissions( |
|
65 | 65 | self, user_group, perm_additions=None, perm_updates=None, |
|
66 | 66 | perm_deletions=None, check_perms=True, cur_user=None): |
|
67 | 67 | |
|
68 | 68 | from rhodecode.lib.auth import HasUserGroupPermissionAny |
|
69 | 69 | if not perm_additions: |
|
70 | 70 | perm_additions = [] |
|
71 | 71 | if not perm_updates: |
|
72 | 72 | perm_updates = [] |
|
73 | 73 | if not perm_deletions: |
|
74 | 74 | perm_deletions = [] |
|
75 | 75 | |
|
76 | 76 | req_perms = ('usergroup.read', 'usergroup.write', 'usergroup.admin') |
|
77 | 77 | |
|
78 | 78 | changes = { |
|
79 | 79 | 'added': [], |
|
80 | 80 | 'updated': [], |
|
81 | 81 | 'deleted': [] |
|
82 | 82 | } |
|
83 | 83 | # update permissions |
|
84 | 84 | for member_id, perm, member_type in perm_updates: |
|
85 | 85 | member_id = int(member_id) |
|
86 | 86 | if member_type == 'user': |
|
87 | 87 | member_name = User.get(member_id).username |
|
88 | 88 | # this updates existing one |
|
89 | 89 | self.grant_user_permission( |
|
90 | 90 | user_group=user_group, user=member_id, perm=perm |
|
91 | 91 | ) |
|
92 | 92 | else: |
|
93 | 93 | # check if we have permissions to alter this usergroup |
|
94 | 94 | member_name = UserGroup.get(member_id).users_group_name |
|
95 | 95 | if not check_perms or HasUserGroupPermissionAny( |
|
96 | 96 | *req_perms)(member_name, user=cur_user): |
|
97 | 97 | self.grant_user_group_permission( |
|
98 | 98 | target_user_group=user_group, user_group=member_id, perm=perm) |
|
99 | 99 | |
|
100 | 100 | changes['updated'].append({'type': member_type, 'id': member_id, |
|
101 | 101 | 'name': member_name, 'new_perm': perm}) |
|
102 | 102 | |
|
103 | 103 | # set new permissions |
|
104 | 104 | for member_id, perm, member_type in perm_additions: |
|
105 | 105 | member_id = int(member_id) |
|
106 | 106 | if member_type == 'user': |
|
107 | 107 | member_name = User.get(member_id).username |
|
108 | 108 | self.grant_user_permission( |
|
109 | 109 | user_group=user_group, user=member_id, perm=perm) |
|
110 | 110 | else: |
|
111 | 111 | # check if we have permissions to alter this usergroup |
|
112 | 112 | member_name = UserGroup.get(member_id).users_group_name |
|
113 | 113 | if not check_perms or HasUserGroupPermissionAny( |
|
114 | 114 | *req_perms)(member_name, user=cur_user): |
|
115 | 115 | self.grant_user_group_permission( |
|
116 | 116 | target_user_group=user_group, user_group=member_id, perm=perm) |
|
117 | 117 | |
|
118 | 118 | changes['added'].append({'type': member_type, 'id': member_id, |
|
119 | 119 | 'name': member_name, 'new_perm': perm}) |
|
120 | 120 | |
|
121 | 121 | # delete permissions |
|
122 | 122 | for member_id, perm, member_type in perm_deletions: |
|
123 | 123 | member_id = int(member_id) |
|
124 | 124 | if member_type == 'user': |
|
125 | 125 | member_name = User.get(member_id).username |
|
126 | 126 | self.revoke_user_permission(user_group=user_group, user=member_id) |
|
127 | 127 | else: |
|
128 | 128 | # check if we have permissions to alter this usergroup |
|
129 | 129 | member_name = UserGroup.get(member_id).users_group_name |
|
130 | 130 | if not check_perms or HasUserGroupPermissionAny( |
|
131 | 131 | *req_perms)(member_name, user=cur_user): |
|
132 | 132 | self.revoke_user_group_permission( |
|
133 | 133 | target_user_group=user_group, user_group=member_id) |
|
134 | 134 | |
|
135 | 135 | changes['deleted'].append({'type': member_type, 'id': member_id, |
|
136 | 136 | 'name': member_name, 'new_perm': perm}) |
|
137 | 137 | return changes |
|
138 | 138 | |
|
139 | 139 | def get(self, user_group_id, cache=False): |
|
140 | 140 | return UserGroup.get(user_group_id) |
|
141 | 141 | |
|
142 | 142 | def get_group(self, user_group): |
|
143 | 143 | return self._get_user_group(user_group) |
|
144 | 144 | |
|
145 | 145 | def get_by_name(self, name, cache=False, case_insensitive=False): |
|
146 | 146 | return UserGroup.get_by_group_name(name, cache, case_insensitive) |
|
147 | 147 | |
|
148 | 148 | def create(self, name, description, owner, active=True, group_data=None): |
|
149 | 149 | try: |
|
150 | 150 | new_user_group = UserGroup() |
|
151 | 151 | new_user_group.user = self._get_user(owner) |
|
152 | 152 | new_user_group.users_group_name = name |
|
153 | 153 | new_user_group.user_group_description = description |
|
154 | 154 | new_user_group.users_group_active = active |
|
155 | 155 | if group_data: |
|
156 | 156 | new_user_group.group_data = group_data |
|
157 | 157 | self.sa.add(new_user_group) |
|
158 | 158 | perm_obj = self._create_default_perms(new_user_group) |
|
159 | 159 | self.sa.add(perm_obj) |
|
160 | 160 | |
|
161 | 161 | self.grant_user_permission(user_group=new_user_group, |
|
162 | 162 | user=owner, perm='usergroup.admin') |
|
163 | 163 | |
|
164 | 164 | return new_user_group |
|
165 | 165 | except Exception: |
|
166 | 166 | log.error(traceback.format_exc()) |
|
167 | 167 | raise |
|
168 | 168 | |
|
169 | 169 | def _get_memberships_for_user_ids(self, user_group, user_id_list): |
|
170 | 170 | members = [] |
|
171 | 171 | for user_id in user_id_list: |
|
172 | 172 | member = self._get_membership(user_group.users_group_id, user_id) |
|
173 | 173 | members.append(member) |
|
174 | 174 | return members |
|
175 | 175 | |
|
176 | 176 | def _get_added_and_removed_user_ids(self, user_group, user_id_list): |
|
177 | 177 | current_members = user_group.members or [] |
|
178 | 178 | current_members_ids = [m.user.user_id for m in current_members] |
|
179 | 179 | |
|
180 | 180 | added_members = [ |
|
181 | 181 | user_id for user_id in user_id_list |
|
182 | 182 | if user_id not in current_members_ids] |
|
183 | 183 | if user_id_list == []: |
|
184 | 184 | # all members were deleted |
|
185 | 185 | deleted_members = current_members_ids |
|
186 | 186 | else: |
|
187 | 187 | deleted_members = [ |
|
188 | 188 | user_id for user_id in current_members_ids |
|
189 | 189 | if user_id not in user_id_list] |
|
190 | 190 | |
|
191 | 191 | return added_members, deleted_members |
|
192 | 192 | |
|
193 | 193 | def _set_users_as_members(self, user_group, user_ids): |
|
194 | 194 | user_group.members = [] |
|
195 | 195 | self.sa.flush() |
|
196 | 196 | members = self._get_memberships_for_user_ids( |
|
197 | 197 | user_group, user_ids) |
|
198 | 198 | user_group.members = members |
|
199 | 199 | self.sa.add(user_group) |
|
200 | 200 | |
|
201 | 201 | def _update_members_from_user_ids(self, user_group, user_ids): |
|
202 | 202 | added, removed = self._get_added_and_removed_user_ids( |
|
203 | 203 | user_group, user_ids) |
|
204 | 204 | self._set_users_as_members(user_group, user_ids) |
|
205 | 205 | self._log_user_changes('added to', user_group, added) |
|
206 | 206 | self._log_user_changes('removed from', user_group, removed) |
|
207 | 207 | return added, removed |
|
208 | 208 | |
|
209 | 209 | def _clean_members_data(self, members_data): |
|
210 | 210 | if not members_data: |
|
211 | 211 | members_data = [] |
|
212 | 212 | |
|
213 | 213 | members = [] |
|
214 | 214 | for user in members_data: |
|
215 | 215 | uid = int(user['member_user_id']) |
|
216 | 216 | if uid not in members and user['type'] in ['new', 'existing']: |
|
217 | 217 | members.append(uid) |
|
218 | 218 | return members |
|
219 | 219 | |
|
220 | 220 | def update(self, user_group, form_data): |
|
221 | 221 | user_group = self._get_user_group(user_group) |
|
222 | 222 | if 'users_group_name' in form_data: |
|
223 | 223 | user_group.users_group_name = form_data['users_group_name'] |
|
224 | 224 | if 'users_group_active' in form_data: |
|
225 | 225 | user_group.users_group_active = form_data['users_group_active'] |
|
226 | 226 | if 'user_group_description' in form_data: |
|
227 | 227 | user_group.user_group_description = form_data[ |
|
228 | 228 | 'user_group_description'] |
|
229 | 229 | |
|
230 | 230 | # handle owner change |
|
231 | 231 | if 'user' in form_data: |
|
232 | 232 | owner = form_data['user'] |
|
233 | 233 | if isinstance(owner, basestring): |
|
234 | 234 | owner = User.get_by_username(form_data['user']) |
|
235 | 235 | |
|
236 | 236 | if not isinstance(owner, User): |
|
237 | 237 | raise ValueError( |
|
238 | 238 | 'invalid owner for user group: %s' % form_data['user']) |
|
239 | 239 | |
|
240 | 240 | user_group.user = owner |
|
241 | 241 | |
|
242 | 242 | added_user_ids = [] |
|
243 | 243 | removed_user_ids = [] |
|
244 | 244 | if 'users_group_members' in form_data: |
|
245 | 245 | members_id_list = self._clean_members_data( |
|
246 | 246 | form_data['users_group_members']) |
|
247 | 247 | added_user_ids, removed_user_ids = \ |
|
248 | 248 | self._update_members_from_user_ids(user_group, members_id_list) |
|
249 | 249 | |
|
250 | 250 | self.sa.add(user_group) |
|
251 | 251 | return user_group, added_user_ids, removed_user_ids |
|
252 | 252 | |
|
253 | 253 | def delete(self, user_group, force=False): |
|
254 | 254 | """ |
|
255 | 255 | Deletes repository group, unless force flag is used |
|
256 | 256 | raises exception if there are members in that group, else deletes |
|
257 | 257 | group and users |
|
258 | 258 | |
|
259 | 259 | :param user_group: |
|
260 | 260 | :param force: |
|
261 | 261 | """ |
|
262 | 262 | user_group = self._get_user_group(user_group) |
|
263 | 263 | if not user_group: |
|
264 | 264 | return |
|
265 | 265 | |
|
266 | 266 | try: |
|
267 | 267 | # check if this group is not assigned to repo |
|
268 | 268 | assigned_to_repo = [x.repository for x in UserGroupRepoToPerm.query()\ |
|
269 | 269 | .filter(UserGroupRepoToPerm.users_group == user_group).all()] |
|
270 | 270 | # check if this group is not assigned to repo |
|
271 | 271 | assigned_to_repo_group = [x.group for x in UserGroupRepoGroupToPerm.query()\ |
|
272 | 272 | .filter(UserGroupRepoGroupToPerm.users_group == user_group).all()] |
|
273 | 273 | |
|
274 | 274 | if (assigned_to_repo or assigned_to_repo_group) and not force: |
|
275 | 275 | assigned = ','.join(map(safe_str, |
|
276 | 276 | assigned_to_repo+assigned_to_repo_group)) |
|
277 | 277 | |
|
278 | 278 | raise UserGroupAssignedException( |
|
279 | 279 | 'UserGroup assigned to %s' % (assigned,)) |
|
280 | 280 | self.sa.delete(user_group) |
|
281 | 281 | except Exception: |
|
282 | 282 | log.error(traceback.format_exc()) |
|
283 | 283 | raise |
|
284 | 284 | |
|
285 | 285 | def _log_user_changes(self, action, user_group, user_or_users): |
|
286 | 286 | users = user_or_users |
|
287 | 287 | if not isinstance(users, (list, tuple)): |
|
288 | 288 | users = [users] |
|
289 | 289 | |
|
290 | 290 | group_name = user_group.users_group_name |
|
291 | 291 | |
|
292 | 292 | for user_or_user_id in users: |
|
293 | 293 | user = self._get_user(user_or_user_id) |
|
294 | 294 | log_text = 'User {user} {action} {group}'.format( |
|
295 | 295 | action=action, user=user.username, group=group_name) |
|
296 | 296 | action_logger_generic(log_text) |
|
297 | 297 | |
|
298 | 298 | def _find_user_in_group(self, user, user_group): |
|
299 | 299 | user_group_member = None |
|
300 | 300 | for m in user_group.members: |
|
301 | 301 | if m.user_id == user.user_id: |
|
302 | 302 | # Found this user's membership row |
|
303 | 303 | user_group_member = m |
|
304 | 304 | break |
|
305 | 305 | |
|
306 | 306 | return user_group_member |
|
307 | 307 | |
|
308 | 308 | def _get_membership(self, user_group_id, user_id): |
|
309 | 309 | user_group_member = UserGroupMember(user_group_id, user_id) |
|
310 | 310 | return user_group_member |
|
311 | 311 | |
|
312 | 312 | def add_user_to_group(self, user_group, user): |
|
313 | 313 | user_group = self._get_user_group(user_group) |
|
314 | 314 | user = self._get_user(user) |
|
315 | 315 | user_member = self._find_user_in_group(user, user_group) |
|
316 | 316 | if user_member: |
|
317 | 317 | # user already in the group, skip |
|
318 | 318 | return True |
|
319 | 319 | |
|
320 | 320 | member = self._get_membership( |
|
321 | 321 | user_group.users_group_id, user.user_id) |
|
322 | 322 | user_group.members.append(member) |
|
323 | 323 | |
|
324 | 324 | try: |
|
325 | 325 | self.sa.add(member) |
|
326 | 326 | except Exception: |
|
327 | 327 | # what could go wrong here? |
|
328 | 328 | log.error(traceback.format_exc()) |
|
329 | 329 | raise |
|
330 | 330 | |
|
331 | 331 | self._log_user_changes('added to', user_group, user) |
|
332 | 332 | return member |
|
333 | 333 | |
|
334 | 334 | def remove_user_from_group(self, user_group, user): |
|
335 | 335 | user_group = self._get_user_group(user_group) |
|
336 | 336 | user = self._get_user(user) |
|
337 | 337 | user_group_member = self._find_user_in_group(user, user_group) |
|
338 | 338 | |
|
339 | 339 | if not user_group_member: |
|
340 | 340 | # User isn't in that group |
|
341 | 341 | return False |
|
342 | 342 | |
|
343 | 343 | try: |
|
344 | 344 | self.sa.delete(user_group_member) |
|
345 | 345 | except Exception: |
|
346 | 346 | log.error(traceback.format_exc()) |
|
347 | 347 | raise |
|
348 | 348 | |
|
349 | 349 | self._log_user_changes('removed from', user_group, user) |
|
350 | 350 | return True |
|
351 | 351 | |
|
352 | 352 | def has_perm(self, user_group, perm): |
|
353 | 353 | user_group = self._get_user_group(user_group) |
|
354 | 354 | perm = self._get_perm(perm) |
|
355 | 355 | |
|
356 | 356 | return UserGroupToPerm.query()\ |
|
357 | 357 | .filter(UserGroupToPerm.users_group == user_group)\ |
|
358 | 358 | .filter(UserGroupToPerm.permission == perm).scalar() is not None |
|
359 | 359 | |
|
360 | 360 | def grant_perm(self, user_group, perm): |
|
361 | 361 | user_group = self._get_user_group(user_group) |
|
362 | 362 | perm = self._get_perm(perm) |
|
363 | 363 | |
|
364 | 364 | # if this permission is already granted skip it |
|
365 | 365 | _perm = UserGroupToPerm.query()\ |
|
366 | 366 | .filter(UserGroupToPerm.users_group == user_group)\ |
|
367 | 367 | .filter(UserGroupToPerm.permission == perm)\ |
|
368 | 368 | .scalar() |
|
369 | 369 | if _perm: |
|
370 | 370 | return |
|
371 | 371 | |
|
372 | 372 | new = UserGroupToPerm() |
|
373 | 373 | new.users_group = user_group |
|
374 | 374 | new.permission = perm |
|
375 | 375 | self.sa.add(new) |
|
376 | 376 | return new |
|
377 | 377 | |
|
378 | 378 | def revoke_perm(self, user_group, perm): |
|
379 | 379 | user_group = self._get_user_group(user_group) |
|
380 | 380 | perm = self._get_perm(perm) |
|
381 | 381 | |
|
382 | 382 | obj = UserGroupToPerm.query()\ |
|
383 | 383 | .filter(UserGroupToPerm.users_group == user_group)\ |
|
384 | 384 | .filter(UserGroupToPerm.permission == perm).scalar() |
|
385 | 385 | if obj: |
|
386 | 386 | self.sa.delete(obj) |
|
387 | 387 | |
|
388 | 388 | def grant_user_permission(self, user_group, user, perm): |
|
389 | 389 | """ |
|
390 | 390 | Grant permission for user on given user group, or update |
|
391 | 391 | existing one if found |
|
392 | 392 | |
|
393 | 393 | :param user_group: Instance of UserGroup, users_group_id, |
|
394 | 394 | or users_group_name |
|
395 | 395 | :param user: Instance of User, user_id or username |
|
396 | 396 | :param perm: Instance of Permission, or permission_name |
|
397 | 397 | """ |
|
398 | 398 | |
|
399 | 399 | user_group = self._get_user_group(user_group) |
|
400 | 400 | user = self._get_user(user) |
|
401 | 401 | permission = self._get_perm(perm) |
|
402 | 402 | |
|
403 | 403 | # check if we have that permission already |
|
404 | 404 | obj = self.sa.query(UserUserGroupToPerm)\ |
|
405 | 405 | .filter(UserUserGroupToPerm.user == user)\ |
|
406 | 406 | .filter(UserUserGroupToPerm.user_group == user_group)\ |
|
407 | 407 | .scalar() |
|
408 | 408 | if obj is None: |
|
409 | 409 | # create new ! |
|
410 | 410 | obj = UserUserGroupToPerm() |
|
411 | 411 | obj.user_group = user_group |
|
412 | 412 | obj.user = user |
|
413 | 413 | obj.permission = permission |
|
414 | 414 | self.sa.add(obj) |
|
415 | 415 | log.debug('Granted perm %s to %s on %s', perm, user, user_group) |
|
416 | 416 | action_logger_generic( |
|
417 | 417 | 'granted permission: {} to user: {} on usergroup: {}'.format( |
|
418 | 418 | perm, user, user_group), namespace='security.usergroup') |
|
419 | 419 | |
|
420 | 420 | return obj |
|
421 | 421 | |
|
422 | 422 | def revoke_user_permission(self, user_group, user): |
|
423 | 423 | """ |
|
424 | 424 | Revoke permission for user on given user group |
|
425 | 425 | |
|
426 | 426 | :param user_group: Instance of UserGroup, users_group_id, |
|
427 | 427 | or users_group name |
|
428 | 428 | :param user: Instance of User, user_id or username |
|
429 | 429 | """ |
|
430 | 430 | |
|
431 | 431 | user_group = self._get_user_group(user_group) |
|
432 | 432 | user = self._get_user(user) |
|
433 | 433 | |
|
434 | 434 | obj = self.sa.query(UserUserGroupToPerm)\ |
|
435 | 435 | .filter(UserUserGroupToPerm.user == user)\ |
|
436 | 436 | .filter(UserUserGroupToPerm.user_group == user_group)\ |
|
437 | 437 | .scalar() |
|
438 | 438 | if obj: |
|
439 | 439 | self.sa.delete(obj) |
|
440 | 440 | log.debug('Revoked perm on %s on %s', user_group, user) |
|
441 | 441 | action_logger_generic( |
|
442 | 442 | 'revoked permission from user: {} on usergroup: {}'.format( |
|
443 | 443 | user, user_group), namespace='security.usergroup') |
|
444 | 444 | |
|
445 | 445 | def grant_user_group_permission(self, target_user_group, user_group, perm): |
|
446 | 446 | """ |
|
447 | 447 | Grant user group permission for given target_user_group |
|
448 | 448 | |
|
449 | 449 | :param target_user_group: |
|
450 | 450 | :param user_group: |
|
451 | 451 | :param perm: |
|
452 | 452 | """ |
|
453 | 453 | target_user_group = self._get_user_group(target_user_group) |
|
454 | 454 | user_group = self._get_user_group(user_group) |
|
455 | 455 | permission = self._get_perm(perm) |
|
456 | 456 | # forbid assigning same user group to itself |
|
457 | 457 | if target_user_group == user_group: |
|
458 | 458 | raise RepoGroupAssignmentError('target repo:%s cannot be ' |
|
459 | 459 | 'assigned to itself' % target_user_group) |
|
460 | 460 | |
|
461 | 461 | # check if we have that permission already |
|
462 | 462 | obj = self.sa.query(UserGroupUserGroupToPerm)\ |
|
463 | 463 | .filter(UserGroupUserGroupToPerm.target_user_group == target_user_group)\ |
|
464 | 464 | .filter(UserGroupUserGroupToPerm.user_group == user_group)\ |
|
465 | 465 | .scalar() |
|
466 | 466 | if obj is None: |
|
467 | 467 | # create new ! |
|
468 | 468 | obj = UserGroupUserGroupToPerm() |
|
469 | 469 | obj.user_group = user_group |
|
470 | 470 | obj.target_user_group = target_user_group |
|
471 | 471 | obj.permission = permission |
|
472 | 472 | self.sa.add(obj) |
|
473 | 473 | log.debug( |
|
474 | 474 | 'Granted perm %s to %s on %s', perm, target_user_group, user_group) |
|
475 | 475 | action_logger_generic( |
|
476 | 476 | 'granted permission: {} to usergroup: {} on usergroup: {}'.format( |
|
477 | 477 | perm, user_group, target_user_group), |
|
478 | 478 | namespace='security.usergroup') |
|
479 | 479 | |
|
480 | 480 | return obj |
|
481 | 481 | |
|
482 | 482 | def revoke_user_group_permission(self, target_user_group, user_group): |
|
483 | 483 | """ |
|
484 | 484 | Revoke user group permission for given target_user_group |
|
485 | 485 | |
|
486 | 486 | :param target_user_group: |
|
487 | 487 | :param user_group: |
|
488 | 488 | """ |
|
489 | 489 | target_user_group = self._get_user_group(target_user_group) |
|
490 | 490 | user_group = self._get_user_group(user_group) |
|
491 | 491 | |
|
492 | 492 | obj = self.sa.query(UserGroupUserGroupToPerm)\ |
|
493 | 493 | .filter(UserGroupUserGroupToPerm.target_user_group == target_user_group)\ |
|
494 | 494 | .filter(UserGroupUserGroupToPerm.user_group == user_group)\ |
|
495 | 495 | .scalar() |
|
496 | 496 | if obj: |
|
497 | 497 | self.sa.delete(obj) |
|
498 | 498 | log.debug( |
|
499 | 499 | 'Revoked perm on %s on %s', target_user_group, user_group) |
|
500 | 500 | action_logger_generic( |
|
501 | 501 | 'revoked permission from usergroup: {} on usergroup: {}'.format( |
|
502 | 502 | user_group, target_user_group), |
|
503 | 503 | namespace='security.repogroup') |
|
504 | 504 | |
|
505 | 505 | def enforce_groups(self, user, groups, extern_type=None): |
|
506 | 506 | user = self._get_user(user) |
|
507 | 507 | log.debug('Enforcing groups %s on user %s', groups, user) |
|
508 | 508 | current_groups = user.group_member |
|
509 | 509 | # find the external created groups |
|
510 | 510 | externals = [x.users_group for x in current_groups |
|
511 | 511 | if 'extern_type' in x.users_group.group_data] |
|
512 | 512 | |
|
513 | 513 | # calculate from what groups user should be removed |
|
514 | 514 | # externals that are not in groups |
|
515 | 515 | for gr in externals: |
|
516 | 516 | if gr.users_group_name not in groups: |
|
517 | 517 | log.debug('Removing user %s from user group %s', user, gr) |
|
518 | 518 | self.remove_user_from_group(gr, user) |
|
519 | 519 | |
|
520 | 520 | # now we calculate in which groups user should be == groups params |
|
521 | 521 | owner = User.get_first_super_admin().username |
|
522 | 522 | for gr in set(groups): |
|
523 | 523 | existing_group = UserGroup.get_by_group_name(gr) |
|
524 | 524 | if not existing_group: |
|
525 | 525 | desc = 'Automatically created from plugin:%s' % extern_type |
|
526 | 526 | # we use first admin account to set the owner of the group |
|
527 | 527 | existing_group = UserGroupModel().create( |
|
528 | 528 | gr, desc, owner, group_data={'extern_type': extern_type}) |
|
529 | 529 | |
|
530 | 530 | # we can only add users to special groups created via plugins |
|
531 | 531 | managed = 'extern_type' in existing_group.group_data |
|
532 | 532 | if managed: |
|
533 | 533 | log.debug('Adding user %s to user group %s', user, gr) |
|
534 | 534 | UserGroupModel().add_user_to_group(existing_group, user) |
|
535 | 535 | else: |
|
536 | 536 | log.debug('Skipping addition to group %s since it is ' |
|
537 | 537 | 'not set to be automatically synchronized' % gr) |
|
538 | 538 | |
|
539 | 539 | def change_groups(self, user, groups): |
|
540 | 540 | """ |
|
541 | 541 | This method changes user group assignment |
|
542 | 542 | :param user: User |
|
543 | 543 | :param groups: array of UserGroupModel |
|
544 | 544 | """ |
|
545 | 545 | user = self._get_user(user) |
|
546 | 546 | log.debug('Changing user(%s) assignment to groups(%s)', user, groups) |
|
547 | 547 | current_groups = user.group_member |
|
548 | 548 | current_groups = [x.users_group for x in current_groups] |
|
549 | 549 | |
|
550 | 550 | # calculate from what groups user should be removed/add |
|
551 | 551 | groups = set(groups) |
|
552 | 552 | current_groups = set(current_groups) |
|
553 | 553 | |
|
554 | 554 | groups_to_remove = current_groups - groups |
|
555 | 555 | groups_to_add = groups - current_groups |
|
556 | 556 | |
|
557 | removed_from_groups = [] | |
|
558 | added_to_groups = [] | |
|
557 | 559 | for gr in groups_to_remove: |
|
558 | 560 | log.debug('Removing user %s from user group %s', |
|
559 | 561 | user.username, gr.users_group_name) |
|
562 | removed_from_groups.append(gr.users_group_id) | |
|
560 | 563 | self.remove_user_from_group(gr.users_group_name, user.username) |
|
561 | 564 | for gr in groups_to_add: |
|
562 | 565 | log.debug('Adding user %s to user group %s', |
|
563 | 566 | user.username, gr.users_group_name) |
|
567 | added_to_groups.append(gr.users_group_id) | |
|
564 | 568 | UserGroupModel().add_user_to_group( |
|
565 | 569 | gr.users_group_name, user.username) |
|
566 | 570 | |
|
571 | return added_to_groups, removed_from_groups | |
|
572 | ||
|
567 | 573 | def _serialize_user_group(self, user_group): |
|
568 | 574 | import rhodecode.lib.helpers as h |
|
569 | 575 | return { |
|
570 | 576 | 'id': user_group.users_group_id, |
|
571 | 577 | # TODO: marcink figure out a way to generate the url for the |
|
572 | 578 | # icon |
|
573 | 579 | 'icon_link': '', |
|
574 | 580 | 'value_display': 'Group: %s (%d members)' % ( |
|
575 | 581 | user_group.users_group_name, len(user_group.members),), |
|
576 | 582 | 'value': user_group.users_group_name, |
|
577 | 583 | 'description': user_group.user_group_description, |
|
578 | 584 | 'owner': user_group.user.username, |
|
579 | 585 | |
|
580 | 586 | 'owner_icon': h.gravatar_url(user_group.user.email, 30), |
|
581 | 587 | 'value_display_owner': h.person(user_group.user.email), |
|
582 | 588 | |
|
583 | 589 | 'value_type': 'user_group', |
|
584 | 590 | 'active': user_group.users_group_active, |
|
585 | 591 | } |
|
586 | 592 | |
|
587 | 593 | def get_user_groups(self, name_contains=None, limit=20, only_active=True, |
|
588 | 594 | expand_groups=False): |
|
589 | 595 | query = self.sa.query(UserGroup) |
|
590 | 596 | if only_active: |
|
591 | 597 | query = query.filter(UserGroup.users_group_active == true()) |
|
592 | 598 | |
|
593 | 599 | if name_contains: |
|
594 | 600 | ilike_expression = u'%{}%'.format(safe_unicode(name_contains)) |
|
595 | 601 | query = query.filter( |
|
596 | 602 | UserGroup.users_group_name.ilike(ilike_expression))\ |
|
597 | 603 | .order_by(func.length(UserGroup.users_group_name))\ |
|
598 | 604 | .order_by(UserGroup.users_group_name) |
|
599 | 605 | |
|
600 | 606 | query = query.limit(limit) |
|
601 | 607 | user_groups = query.all() |
|
602 | 608 | perm_set = ['usergroup.read', 'usergroup.write', 'usergroup.admin'] |
|
603 | 609 | user_groups = UserGroupList(user_groups, perm_set=perm_set) |
|
604 | 610 | |
|
605 | 611 | # store same serialize method to extract data from User |
|
606 | 612 | from rhodecode.model.user import UserModel |
|
607 | 613 | serialize_user = UserModel()._serialize_user |
|
608 | 614 | |
|
609 | 615 | _groups = [] |
|
610 | 616 | for group in user_groups: |
|
611 | 617 | entry = self._serialize_user_group(group) |
|
612 | 618 | if expand_groups: |
|
613 | 619 | expanded_members = [] |
|
614 | 620 | for member in group.members: |
|
615 | 621 | expanded_members.append(serialize_user(member.user)) |
|
616 | 622 | entry['members'] = expanded_members |
|
617 | 623 | _groups.append(entry) |
|
618 | 624 | return _groups |
|
619 | 625 | |
|
620 | 626 | @staticmethod |
|
621 | 627 | def get_user_groups_as_dict(user_group): |
|
622 | 628 | import rhodecode.lib.helpers as h |
|
623 | 629 | |
|
624 | 630 | data = { |
|
625 | 631 | 'users_group_id': user_group.users_group_id, |
|
626 | 632 | 'group_name': user_group.users_group_name, |
|
627 | 633 | 'group_description': user_group.user_group_description, |
|
628 | 634 | 'active': user_group.users_group_active, |
|
629 | 635 | "owner": user_group.user.username, |
|
630 | 636 | 'owner_icon': h.gravatar_url(user_group.user.email, 30), |
|
631 | 637 | "owner_data": { |
|
632 | 638 | 'owner': user_group.user.username, |
|
633 | 639 | 'owner_icon': h.gravatar_url(user_group.user.email, 30)} |
|
634 | 640 | } |
|
635 | 641 | return data |
@@ -1,274 +1,283 b'' | |||
|
1 | 1 | |
|
2 | 2 | /****************************************************************************** |
|
3 | 3 | * * |
|
4 | 4 | * DO NOT CHANGE THIS FILE MANUALLY * |
|
5 | 5 | * * |
|
6 | 6 | * * |
|
7 | 7 | * This file is automatically generated when the app starts up with * |
|
8 | 8 | * generate_js_files = true * |
|
9 | 9 | * * |
|
10 | 10 | * To add a route here pass jsroute=True to the route definition in the app * |
|
11 | 11 | * * |
|
12 | 12 | ******************************************************************************/ |
|
13 | 13 | function registerRCRoutes() { |
|
14 | 14 | // routes registration |
|
15 | pyroutes.register('edit_user', '/_admin/users/%(user_id)s/edit', ['user_id']); | |
|
16 | 15 | pyroutes.register('favicon', '/favicon.ico', []); |
|
17 | 16 | pyroutes.register('robots', '/robots.txt', []); |
|
18 | 17 | pyroutes.register('auth_home', '/_admin/auth*traverse', []); |
|
19 | 18 | pyroutes.register('global_integrations_new', '/_admin/integrations/new', []); |
|
20 | 19 | pyroutes.register('global_integrations_home', '/_admin/integrations', []); |
|
21 | 20 | pyroutes.register('global_integrations_list', '/_admin/integrations/%(integration)s', ['integration']); |
|
22 | 21 | pyroutes.register('global_integrations_create', '/_admin/integrations/%(integration)s/new', ['integration']); |
|
23 | 22 | pyroutes.register('global_integrations_edit', '/_admin/integrations/%(integration)s/%(integration_id)s', ['integration', 'integration_id']); |
|
24 | 23 | pyroutes.register('repo_group_integrations_home', '/%(repo_group_name)s/settings/integrations', ['repo_group_name']); |
|
25 | 24 | pyroutes.register('repo_group_integrations_new', '/%(repo_group_name)s/settings/integrations/new', ['repo_group_name']); |
|
26 | 25 | pyroutes.register('repo_group_integrations_list', '/%(repo_group_name)s/settings/integrations/%(integration)s', ['repo_group_name', 'integration']); |
|
27 | 26 | pyroutes.register('repo_group_integrations_create', '/%(repo_group_name)s/settings/integrations/%(integration)s/new', ['repo_group_name', 'integration']); |
|
28 | 27 | pyroutes.register('repo_group_integrations_edit', '/%(repo_group_name)s/settings/integrations/%(integration)s/%(integration_id)s', ['repo_group_name', 'integration', 'integration_id']); |
|
29 | 28 | pyroutes.register('repo_integrations_home', '/%(repo_name)s/settings/integrations', ['repo_name']); |
|
30 | 29 | pyroutes.register('repo_integrations_new', '/%(repo_name)s/settings/integrations/new', ['repo_name']); |
|
31 | 30 | pyroutes.register('repo_integrations_list', '/%(repo_name)s/settings/integrations/%(integration)s', ['repo_name', 'integration']); |
|
32 | 31 | pyroutes.register('repo_integrations_create', '/%(repo_name)s/settings/integrations/%(integration)s/new', ['repo_name', 'integration']); |
|
33 | 32 | pyroutes.register('repo_integrations_edit', '/%(repo_name)s/settings/integrations/%(integration)s/%(integration_id)s', ['repo_name', 'integration', 'integration_id']); |
|
34 | 33 | pyroutes.register('ops_ping', '/_admin/ops/ping', []); |
|
35 | 34 | pyroutes.register('ops_error_test', '/_admin/ops/error', []); |
|
36 | 35 | pyroutes.register('ops_redirect_test', '/_admin/ops/redirect', []); |
|
37 | 36 | pyroutes.register('ops_ping_legacy', '/_admin/ping', []); |
|
38 | 37 | pyroutes.register('ops_error_test_legacy', '/_admin/error_test', []); |
|
39 | 38 | pyroutes.register('admin_home', '/_admin', []); |
|
40 | 39 | pyroutes.register('admin_audit_logs', '/_admin/audit_logs', []); |
|
41 | 40 | pyroutes.register('admin_audit_log_entry', '/_admin/audit_logs/%(audit_log_id)s', ['audit_log_id']); |
|
42 | 41 | pyroutes.register('pull_requests_global_0', '/_admin/pull_requests/%(pull_request_id)s', ['pull_request_id']); |
|
43 | 42 | pyroutes.register('pull_requests_global_1', '/_admin/pull-requests/%(pull_request_id)s', ['pull_request_id']); |
|
44 | 43 | pyroutes.register('pull_requests_global', '/_admin/pull-request/%(pull_request_id)s', ['pull_request_id']); |
|
45 | 44 | pyroutes.register('admin_settings_open_source', '/_admin/settings/open_source', []); |
|
46 | 45 | pyroutes.register('admin_settings_vcs_svn_generate_cfg', '/_admin/settings/vcs/svn_generate_cfg', []); |
|
47 | 46 | pyroutes.register('admin_settings_system', '/_admin/settings/system', []); |
|
48 | 47 | pyroutes.register('admin_settings_system_update', '/_admin/settings/system/updates', []); |
|
49 | 48 | pyroutes.register('admin_settings_sessions', '/_admin/settings/sessions', []); |
|
50 | 49 | pyroutes.register('admin_settings_sessions_cleanup', '/_admin/settings/sessions/cleanup', []); |
|
51 | 50 | pyroutes.register('admin_settings_process_management', '/_admin/settings/process_management', []); |
|
52 | 51 | pyroutes.register('admin_settings_process_management_signal', '/_admin/settings/process_management/signal', []); |
|
53 | 52 | pyroutes.register('admin_defaults_repositories', '/_admin/defaults/repositories', []); |
|
54 | 53 | pyroutes.register('admin_defaults_repositories_update', '/_admin/defaults/repositories/update', []); |
|
55 | 54 | pyroutes.register('admin_permissions_application', '/_admin/permissions/application', []); |
|
56 | 55 | pyroutes.register('admin_permissions_application_update', '/_admin/permissions/application/update', []); |
|
57 | 56 | pyroutes.register('admin_permissions_global', '/_admin/permissions/global', []); |
|
58 | 57 | pyroutes.register('admin_permissions_global_update', '/_admin/permissions/global/update', []); |
|
59 | 58 | pyroutes.register('admin_permissions_object', '/_admin/permissions/object', []); |
|
60 | 59 | pyroutes.register('admin_permissions_object_update', '/_admin/permissions/object/update', []); |
|
61 | 60 | pyroutes.register('admin_permissions_ips', '/_admin/permissions/ips', []); |
|
62 | 61 | pyroutes.register('admin_permissions_overview', '/_admin/permissions/overview', []); |
|
63 | 62 | pyroutes.register('admin_permissions_auth_token_access', '/_admin/permissions/auth_token_access', []); |
|
64 | 63 | pyroutes.register('admin_permissions_ssh_keys', '/_admin/permissions/ssh_keys', []); |
|
65 | 64 | pyroutes.register('admin_permissions_ssh_keys_data', '/_admin/permissions/ssh_keys/data', []); |
|
66 | 65 | pyroutes.register('admin_permissions_ssh_keys_update', '/_admin/permissions/ssh_keys/update', []); |
|
67 | 66 | pyroutes.register('users', '/_admin/users', []); |
|
68 | 67 | pyroutes.register('users_data', '/_admin/users_data', []); |
|
68 | pyroutes.register('users_create', '/_admin/users/create', []); | |
|
69 | pyroutes.register('users_new', '/_admin/users/new', []); | |
|
70 | pyroutes.register('user_edit', '/_admin/users/%(user_id)s/edit', ['user_id']); | |
|
71 | pyroutes.register('user_edit_advanced', '/_admin/users/%(user_id)s/edit/advanced', ['user_id']); | |
|
72 | pyroutes.register('user_edit_global_perms', '/_admin/users/%(user_id)s/edit/global_permissions', ['user_id']); | |
|
73 | pyroutes.register('user_edit_global_perms_update', '/_admin/users/%(user_id)s/edit/global_permissions/update', ['user_id']); | |
|
74 | pyroutes.register('user_update', '/_admin/users/%(user_id)s/update', ['user_id']); | |
|
75 | pyroutes.register('user_delete', '/_admin/users/%(user_id)s/delete', ['user_id']); | |
|
76 | pyroutes.register('user_force_password_reset', '/_admin/users/%(user_id)s/password_reset', ['user_id']); | |
|
77 | pyroutes.register('user_create_personal_repo_group', '/_admin/users/%(user_id)s/create_repo_group', ['user_id']); | |
|
69 | 78 | pyroutes.register('edit_user_auth_tokens', '/_admin/users/%(user_id)s/edit/auth_tokens', ['user_id']); |
|
70 | 79 | pyroutes.register('edit_user_auth_tokens_add', '/_admin/users/%(user_id)s/edit/auth_tokens/new', ['user_id']); |
|
71 | 80 | pyroutes.register('edit_user_auth_tokens_delete', '/_admin/users/%(user_id)s/edit/auth_tokens/delete', ['user_id']); |
|
72 | 81 | pyroutes.register('edit_user_ssh_keys', '/_admin/users/%(user_id)s/edit/ssh_keys', ['user_id']); |
|
73 | 82 | pyroutes.register('edit_user_ssh_keys_generate_keypair', '/_admin/users/%(user_id)s/edit/ssh_keys/generate', ['user_id']); |
|
74 | 83 | pyroutes.register('edit_user_ssh_keys_add', '/_admin/users/%(user_id)s/edit/ssh_keys/new', ['user_id']); |
|
75 | 84 | pyroutes.register('edit_user_ssh_keys_delete', '/_admin/users/%(user_id)s/edit/ssh_keys/delete', ['user_id']); |
|
76 | 85 | pyroutes.register('edit_user_emails', '/_admin/users/%(user_id)s/edit/emails', ['user_id']); |
|
77 | 86 | pyroutes.register('edit_user_emails_add', '/_admin/users/%(user_id)s/edit/emails/new', ['user_id']); |
|
78 | 87 | pyroutes.register('edit_user_emails_delete', '/_admin/users/%(user_id)s/edit/emails/delete', ['user_id']); |
|
79 | 88 | pyroutes.register('edit_user_ips', '/_admin/users/%(user_id)s/edit/ips', ['user_id']); |
|
80 | 89 | pyroutes.register('edit_user_ips_add', '/_admin/users/%(user_id)s/edit/ips/new', ['user_id']); |
|
81 | 90 | pyroutes.register('edit_user_ips_delete', '/_admin/users/%(user_id)s/edit/ips/delete', ['user_id']); |
|
82 | 91 | pyroutes.register('edit_user_perms_summary', '/_admin/users/%(user_id)s/edit/permissions_summary', ['user_id']); |
|
83 | 92 | pyroutes.register('edit_user_perms_summary_json', '/_admin/users/%(user_id)s/edit/permissions_summary/json', ['user_id']); |
|
84 | 93 | pyroutes.register('edit_user_groups_management', '/_admin/users/%(user_id)s/edit/groups_management', ['user_id']); |
|
85 | 94 | pyroutes.register('edit_user_groups_management_updates', '/_admin/users/%(user_id)s/edit/edit_user_groups_management/updates', ['user_id']); |
|
86 | 95 | pyroutes.register('edit_user_audit_logs', '/_admin/users/%(user_id)s/edit/audit', ['user_id']); |
|
87 | 96 | pyroutes.register('user_groups', '/_admin/user_groups', []); |
|
88 | 97 | pyroutes.register('user_groups_data', '/_admin/user_groups_data', []); |
|
89 | 98 | pyroutes.register('user_groups_new', '/_admin/user_groups/new', []); |
|
90 | 99 | pyroutes.register('user_groups_create', '/_admin/user_groups/create', []); |
|
91 | 100 | pyroutes.register('repos', '/_admin/repos', []); |
|
92 | 101 | pyroutes.register('repo_new', '/_admin/repos/new', []); |
|
93 | 102 | pyroutes.register('repo_create', '/_admin/repos/create', []); |
|
94 | 103 | pyroutes.register('channelstream_connect', '/_admin/channelstream/connect', []); |
|
95 | 104 | pyroutes.register('channelstream_subscribe', '/_admin/channelstream/subscribe', []); |
|
96 | 105 | pyroutes.register('channelstream_proxy', '/_channelstream', []); |
|
97 | 106 | pyroutes.register('login', '/_admin/login', []); |
|
98 | 107 | pyroutes.register('logout', '/_admin/logout', []); |
|
99 | 108 | pyroutes.register('register', '/_admin/register', []); |
|
100 | 109 | pyroutes.register('reset_password', '/_admin/password_reset', []); |
|
101 | 110 | pyroutes.register('reset_password_confirmation', '/_admin/password_reset_confirmation', []); |
|
102 | 111 | pyroutes.register('home', '/', []); |
|
103 | 112 | pyroutes.register('user_autocomplete_data', '/_users', []); |
|
104 | 113 | pyroutes.register('user_group_autocomplete_data', '/_user_groups', []); |
|
105 | 114 | pyroutes.register('repo_list_data', '/_repos', []); |
|
106 | 115 | pyroutes.register('goto_switcher_data', '/_goto_data', []); |
|
107 | 116 | pyroutes.register('journal', '/_admin/journal', []); |
|
108 | 117 | pyroutes.register('journal_rss', '/_admin/journal/rss', []); |
|
109 | 118 | pyroutes.register('journal_atom', '/_admin/journal/atom', []); |
|
110 | 119 | pyroutes.register('journal_public', '/_admin/public_journal', []); |
|
111 | 120 | pyroutes.register('journal_public_atom', '/_admin/public_journal/atom', []); |
|
112 | 121 | pyroutes.register('journal_public_atom_old', '/_admin/public_journal_atom', []); |
|
113 | 122 | pyroutes.register('journal_public_rss', '/_admin/public_journal/rss', []); |
|
114 | 123 | pyroutes.register('journal_public_rss_old', '/_admin/public_journal_rss', []); |
|
115 | 124 | pyroutes.register('toggle_following', '/_admin/toggle_following', []); |
|
116 | 125 | pyroutes.register('repo_creating', '/%(repo_name)s/repo_creating', ['repo_name']); |
|
117 | 126 | pyroutes.register('repo_creating_check', '/%(repo_name)s/repo_creating_check', ['repo_name']); |
|
118 | 127 | pyroutes.register('repo_summary_explicit', '/%(repo_name)s/summary', ['repo_name']); |
|
119 | 128 | pyroutes.register('repo_summary_commits', '/%(repo_name)s/summary-commits', ['repo_name']); |
|
120 | 129 | pyroutes.register('repo_commit', '/%(repo_name)s/changeset/%(commit_id)s', ['repo_name', 'commit_id']); |
|
121 | 130 | pyroutes.register('repo_commit_children', '/%(repo_name)s/changeset_children/%(commit_id)s', ['repo_name', 'commit_id']); |
|
122 | 131 | pyroutes.register('repo_commit_parents', '/%(repo_name)s/changeset_parents/%(commit_id)s', ['repo_name', 'commit_id']); |
|
123 | 132 | pyroutes.register('repo_commit_raw', '/%(repo_name)s/changeset-diff/%(commit_id)s', ['repo_name', 'commit_id']); |
|
124 | 133 | pyroutes.register('repo_commit_patch', '/%(repo_name)s/changeset-patch/%(commit_id)s', ['repo_name', 'commit_id']); |
|
125 | 134 | pyroutes.register('repo_commit_download', '/%(repo_name)s/changeset-download/%(commit_id)s', ['repo_name', 'commit_id']); |
|
126 | 135 | pyroutes.register('repo_commit_data', '/%(repo_name)s/changeset-data/%(commit_id)s', ['repo_name', 'commit_id']); |
|
127 | 136 | pyroutes.register('repo_commit_comment_create', '/%(repo_name)s/changeset/%(commit_id)s/comment/create', ['repo_name', 'commit_id']); |
|
128 | 137 | pyroutes.register('repo_commit_comment_preview', '/%(repo_name)s/changeset/%(commit_id)s/comment/preview', ['repo_name', 'commit_id']); |
|
129 | 138 | pyroutes.register('repo_commit_comment_delete', '/%(repo_name)s/changeset/%(commit_id)s/comment/%(comment_id)s/delete', ['repo_name', 'commit_id', 'comment_id']); |
|
130 | 139 | pyroutes.register('repo_commit_raw_deprecated', '/%(repo_name)s/raw-changeset/%(commit_id)s', ['repo_name', 'commit_id']); |
|
131 | 140 | pyroutes.register('repo_archivefile', '/%(repo_name)s/archive/%(fname)s', ['repo_name', 'fname']); |
|
132 | 141 | pyroutes.register('repo_files_diff', '/%(repo_name)s/diff/%(f_path)s', ['repo_name', 'f_path']); |
|
133 | 142 | pyroutes.register('repo_files_diff_2way_redirect', '/%(repo_name)s/diff-2way/%(f_path)s', ['repo_name', 'f_path']); |
|
134 | 143 | pyroutes.register('repo_files', '/%(repo_name)s/files/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']); |
|
135 | 144 | pyroutes.register('repo_files:default_path', '/%(repo_name)s/files/%(commit_id)s/', ['repo_name', 'commit_id']); |
|
136 | 145 | pyroutes.register('repo_files:default_commit', '/%(repo_name)s/files', ['repo_name']); |
|
137 | 146 | pyroutes.register('repo_files:rendered', '/%(repo_name)s/render/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']); |
|
138 | 147 | pyroutes.register('repo_files:annotated', '/%(repo_name)s/annotate/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']); |
|
139 | 148 | pyroutes.register('repo_files:annotated_previous', '/%(repo_name)s/annotate-previous/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']); |
|
140 | 149 | pyroutes.register('repo_nodetree_full', '/%(repo_name)s/nodetree_full/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']); |
|
141 | 150 | pyroutes.register('repo_nodetree_full:default_path', '/%(repo_name)s/nodetree_full/%(commit_id)s/', ['repo_name', 'commit_id']); |
|
142 | 151 | pyroutes.register('repo_files_nodelist', '/%(repo_name)s/nodelist/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']); |
|
143 | 152 | pyroutes.register('repo_file_raw', '/%(repo_name)s/raw/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']); |
|
144 | 153 | pyroutes.register('repo_file_download', '/%(repo_name)s/download/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']); |
|
145 | 154 | pyroutes.register('repo_file_download:legacy', '/%(repo_name)s/rawfile/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']); |
|
146 | 155 | pyroutes.register('repo_file_history', '/%(repo_name)s/history/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']); |
|
147 | 156 | pyroutes.register('repo_file_authors', '/%(repo_name)s/authors/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']); |
|
148 | 157 | pyroutes.register('repo_files_remove_file', '/%(repo_name)s/remove_file/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']); |
|
149 | 158 | pyroutes.register('repo_files_delete_file', '/%(repo_name)s/delete_file/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']); |
|
150 | 159 | pyroutes.register('repo_files_edit_file', '/%(repo_name)s/edit_file/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']); |
|
151 | 160 | pyroutes.register('repo_files_update_file', '/%(repo_name)s/update_file/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']); |
|
152 | 161 | pyroutes.register('repo_files_add_file', '/%(repo_name)s/add_file/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']); |
|
153 | 162 | pyroutes.register('repo_files_create_file', '/%(repo_name)s/create_file/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']); |
|
154 | 163 | pyroutes.register('repo_refs_data', '/%(repo_name)s/refs-data', ['repo_name']); |
|
155 | 164 | pyroutes.register('repo_refs_changelog_data', '/%(repo_name)s/refs-data-changelog', ['repo_name']); |
|
156 | 165 | pyroutes.register('repo_stats', '/%(repo_name)s/repo_stats/%(commit_id)s', ['repo_name', 'commit_id']); |
|
157 | 166 | pyroutes.register('repo_changelog', '/%(repo_name)s/changelog', ['repo_name']); |
|
158 | 167 | pyroutes.register('repo_changelog_file', '/%(repo_name)s/changelog/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']); |
|
159 | 168 | pyroutes.register('repo_changelog_elements', '/%(repo_name)s/changelog_elements', ['repo_name']); |
|
160 | 169 | pyroutes.register('repo_compare_select', '/%(repo_name)s/compare', ['repo_name']); |
|
161 | 170 | pyroutes.register('repo_compare', '/%(repo_name)s/compare/%(source_ref_type)s@%(source_ref)s...%(target_ref_type)s@%(target_ref)s', ['repo_name', 'source_ref_type', 'source_ref', 'target_ref_type', 'target_ref']); |
|
162 | 171 | pyroutes.register('tags_home', '/%(repo_name)s/tags', ['repo_name']); |
|
163 | 172 | pyroutes.register('branches_home', '/%(repo_name)s/branches', ['repo_name']); |
|
164 | 173 | pyroutes.register('bookmarks_home', '/%(repo_name)s/bookmarks', ['repo_name']); |
|
165 | 174 | pyroutes.register('repo_fork_new', '/%(repo_name)s/fork', ['repo_name']); |
|
166 | 175 | pyroutes.register('repo_fork_create', '/%(repo_name)s/fork/create', ['repo_name']); |
|
167 | 176 | pyroutes.register('repo_forks_show_all', '/%(repo_name)s/forks', ['repo_name']); |
|
168 | 177 | pyroutes.register('repo_forks_data', '/%(repo_name)s/forks/data', ['repo_name']); |
|
169 | 178 | pyroutes.register('pullrequest_show', '/%(repo_name)s/pull-request/%(pull_request_id)s', ['repo_name', 'pull_request_id']); |
|
170 | 179 | pyroutes.register('pullrequest_show_all', '/%(repo_name)s/pull-request', ['repo_name']); |
|
171 | 180 | pyroutes.register('pullrequest_show_all_data', '/%(repo_name)s/pull-request-data', ['repo_name']); |
|
172 | 181 | pyroutes.register('pullrequest_repo_refs', '/%(repo_name)s/pull-request/refs/%(target_repo_name)s', ['repo_name', 'target_repo_name']); |
|
173 | 182 | pyroutes.register('pullrequest_repo_destinations', '/%(repo_name)s/pull-request/repo-destinations', ['repo_name']); |
|
174 | 183 | pyroutes.register('pullrequest_new', '/%(repo_name)s/pull-request/new', ['repo_name']); |
|
175 | 184 | pyroutes.register('pullrequest_create', '/%(repo_name)s/pull-request/create', ['repo_name']); |
|
176 | 185 | pyroutes.register('pullrequest_update', '/%(repo_name)s/pull-request/%(pull_request_id)s/update', ['repo_name', 'pull_request_id']); |
|
177 | 186 | pyroutes.register('pullrequest_merge', '/%(repo_name)s/pull-request/%(pull_request_id)s/merge', ['repo_name', 'pull_request_id']); |
|
178 | 187 | pyroutes.register('pullrequest_delete', '/%(repo_name)s/pull-request/%(pull_request_id)s/delete', ['repo_name', 'pull_request_id']); |
|
179 | 188 | pyroutes.register('pullrequest_comment_create', '/%(repo_name)s/pull-request/%(pull_request_id)s/comment', ['repo_name', 'pull_request_id']); |
|
180 | 189 | pyroutes.register('pullrequest_comment_delete', '/%(repo_name)s/pull-request/%(pull_request_id)s/comment/%(comment_id)s/delete', ['repo_name', 'pull_request_id', 'comment_id']); |
|
181 | 190 | pyroutes.register('edit_repo', '/%(repo_name)s/settings', ['repo_name']); |
|
182 | 191 | pyroutes.register('edit_repo_advanced', '/%(repo_name)s/settings/advanced', ['repo_name']); |
|
183 | 192 | pyroutes.register('edit_repo_advanced_delete', '/%(repo_name)s/settings/advanced/delete', ['repo_name']); |
|
184 | 193 | pyroutes.register('edit_repo_advanced_locking', '/%(repo_name)s/settings/advanced/locking', ['repo_name']); |
|
185 | 194 | pyroutes.register('edit_repo_advanced_journal', '/%(repo_name)s/settings/advanced/journal', ['repo_name']); |
|
186 | 195 | pyroutes.register('edit_repo_advanced_fork', '/%(repo_name)s/settings/advanced/fork', ['repo_name']); |
|
187 | 196 | pyroutes.register('edit_repo_caches', '/%(repo_name)s/settings/caches', ['repo_name']); |
|
188 | 197 | pyroutes.register('edit_repo_perms', '/%(repo_name)s/settings/permissions', ['repo_name']); |
|
189 | 198 | pyroutes.register('edit_repo_maintenance', '/%(repo_name)s/settings/maintenance', ['repo_name']); |
|
190 | 199 | pyroutes.register('edit_repo_maintenance_execute', '/%(repo_name)s/settings/maintenance/execute', ['repo_name']); |
|
191 | 200 | pyroutes.register('edit_repo_fields', '/%(repo_name)s/settings/fields', ['repo_name']); |
|
192 | 201 | pyroutes.register('edit_repo_fields_create', '/%(repo_name)s/settings/fields/create', ['repo_name']); |
|
193 | 202 | pyroutes.register('edit_repo_fields_delete', '/%(repo_name)s/settings/fields/%(field_id)s/delete', ['repo_name', 'field_id']); |
|
194 | 203 | pyroutes.register('repo_edit_toggle_locking', '/%(repo_name)s/settings/toggle_locking', ['repo_name']); |
|
195 | 204 | pyroutes.register('edit_repo_remote', '/%(repo_name)s/settings/remote', ['repo_name']); |
|
196 | 205 | pyroutes.register('edit_repo_remote_pull', '/%(repo_name)s/settings/remote/pull', ['repo_name']); |
|
197 | 206 | pyroutes.register('edit_repo_statistics', '/%(repo_name)s/settings/statistics', ['repo_name']); |
|
198 | 207 | pyroutes.register('edit_repo_statistics_reset', '/%(repo_name)s/settings/statistics/update', ['repo_name']); |
|
199 | 208 | pyroutes.register('edit_repo_issuetracker', '/%(repo_name)s/settings/issue_trackers', ['repo_name']); |
|
200 | 209 | pyroutes.register('edit_repo_issuetracker_test', '/%(repo_name)s/settings/issue_trackers/test', ['repo_name']); |
|
201 | 210 | pyroutes.register('edit_repo_issuetracker_delete', '/%(repo_name)s/settings/issue_trackers/delete', ['repo_name']); |
|
202 | 211 | pyroutes.register('edit_repo_issuetracker_update', '/%(repo_name)s/settings/issue_trackers/update', ['repo_name']); |
|
203 | 212 | pyroutes.register('edit_repo_vcs', '/%(repo_name)s/settings/vcs', ['repo_name']); |
|
204 | 213 | pyroutes.register('edit_repo_vcs_update', '/%(repo_name)s/settings/vcs/update', ['repo_name']); |
|
205 | 214 | pyroutes.register('edit_repo_vcs_svn_pattern_delete', '/%(repo_name)s/settings/vcs/svn_pattern/delete', ['repo_name']); |
|
206 | 215 | pyroutes.register('repo_reviewers', '/%(repo_name)s/settings/review/rules', ['repo_name']); |
|
207 | 216 | pyroutes.register('repo_default_reviewers_data', '/%(repo_name)s/settings/review/default-reviewers', ['repo_name']); |
|
208 | 217 | pyroutes.register('edit_repo_strip', '/%(repo_name)s/settings/strip', ['repo_name']); |
|
209 | 218 | pyroutes.register('strip_check', '/%(repo_name)s/settings/strip_check', ['repo_name']); |
|
210 | 219 | pyroutes.register('strip_execute', '/%(repo_name)s/settings/strip_execute', ['repo_name']); |
|
211 | 220 | pyroutes.register('rss_feed_home', '/%(repo_name)s/feed/rss', ['repo_name']); |
|
212 | 221 | pyroutes.register('atom_feed_home', '/%(repo_name)s/feed/atom', ['repo_name']); |
|
213 | 222 | pyroutes.register('repo_summary', '/%(repo_name)s', ['repo_name']); |
|
214 | 223 | pyroutes.register('repo_summary_slash', '/%(repo_name)s/', ['repo_name']); |
|
215 | 224 | pyroutes.register('repo_group_home', '/%(repo_group_name)s', ['repo_group_name']); |
|
216 | 225 | pyroutes.register('repo_group_home_slash', '/%(repo_group_name)s/', ['repo_group_name']); |
|
217 | 226 | pyroutes.register('user_group_members_data', '/_admin/user_groups/%(user_group_id)s/members', ['user_group_id']); |
|
218 | 227 | pyroutes.register('edit_user_group_perms_summary', '/_admin/user_groups/%(user_group_id)s/edit/permissions_summary', ['user_group_id']); |
|
219 | 228 | pyroutes.register('edit_user_group_perms_summary_json', '/_admin/user_groups/%(user_group_id)s/edit/permissions_summary/json', ['user_group_id']); |
|
220 | 229 | pyroutes.register('edit_user_group', '/_admin/user_groups/%(user_group_id)s/edit', ['user_group_id']); |
|
221 | 230 | pyroutes.register('user_groups_update', '/_admin/user_groups/%(user_group_id)s/update', ['user_group_id']); |
|
222 | 231 | pyroutes.register('edit_user_group_global_perms', '/_admin/user_groups/%(user_group_id)s/edit/global_permissions', ['user_group_id']); |
|
223 | 232 | pyroutes.register('edit_user_group_global_perms_update', '/_admin/user_groups/%(user_group_id)s/edit/global_permissions/update', ['user_group_id']); |
|
224 | 233 | pyroutes.register('edit_user_group_perms', '/_admin/user_groups/%(user_group_id)s/edit/permissions', ['user_group_id']); |
|
225 | 234 | pyroutes.register('edit_user_group_perms_update', '/_admin/user_groups/%(user_group_id)s/edit/permissions/update', ['user_group_id']); |
|
226 | 235 | pyroutes.register('edit_user_group_advanced', '/_admin/user_groups/%(user_group_id)s/edit/advanced', ['user_group_id']); |
|
227 | 236 | pyroutes.register('edit_user_group_advanced_sync', '/_admin/user_groups/%(user_group_id)s/edit/advanced/sync', ['user_group_id']); |
|
228 | 237 | pyroutes.register('user_groups_delete', '/_admin/user_groups/%(user_group_id)s/delete', ['user_group_id']); |
|
229 | 238 | pyroutes.register('search', '/_admin/search', []); |
|
230 | 239 | pyroutes.register('search_repo', '/%(repo_name)s/search', ['repo_name']); |
|
231 | 240 | pyroutes.register('user_profile', '/_profiles/%(username)s', ['username']); |
|
232 | 241 | pyroutes.register('my_account_profile', '/_admin/my_account/profile', []); |
|
233 | 242 | pyroutes.register('my_account_edit', '/_admin/my_account/edit', []); |
|
234 | 243 | pyroutes.register('my_account_update', '/_admin/my_account/update', []); |
|
235 | 244 | pyroutes.register('my_account_password', '/_admin/my_account/password', []); |
|
236 | 245 | pyroutes.register('my_account_password_update', '/_admin/my_account/password/update', []); |
|
237 | 246 | pyroutes.register('my_account_auth_tokens', '/_admin/my_account/auth_tokens', []); |
|
238 | 247 | pyroutes.register('my_account_auth_tokens_add', '/_admin/my_account/auth_tokens/new', []); |
|
239 | 248 | pyroutes.register('my_account_auth_tokens_delete', '/_admin/my_account/auth_tokens/delete', []); |
|
240 | 249 | pyroutes.register('my_account_ssh_keys', '/_admin/my_account/ssh_keys', []); |
|
241 | 250 | pyroutes.register('my_account_ssh_keys_generate', '/_admin/my_account/ssh_keys/generate', []); |
|
242 | 251 | pyroutes.register('my_account_ssh_keys_add', '/_admin/my_account/ssh_keys/new', []); |
|
243 | 252 | pyroutes.register('my_account_ssh_keys_delete', '/_admin/my_account/ssh_keys/delete', []); |
|
244 | 253 | pyroutes.register('my_account_emails', '/_admin/my_account/emails', []); |
|
245 | 254 | pyroutes.register('my_account_emails_add', '/_admin/my_account/emails/new', []); |
|
246 | 255 | pyroutes.register('my_account_emails_delete', '/_admin/my_account/emails/delete', []); |
|
247 | 256 | pyroutes.register('my_account_repos', '/_admin/my_account/repos', []); |
|
248 | 257 | pyroutes.register('my_account_watched', '/_admin/my_account/watched', []); |
|
249 | 258 | pyroutes.register('my_account_perms', '/_admin/my_account/perms', []); |
|
250 | 259 | pyroutes.register('my_account_notifications', '/_admin/my_account/notifications', []); |
|
251 | 260 | pyroutes.register('my_account_notifications_toggle_visibility', '/_admin/my_account/toggle_visibility', []); |
|
252 | 261 | pyroutes.register('my_account_pullrequests', '/_admin/my_account/pull_requests', []); |
|
253 | 262 | pyroutes.register('my_account_pullrequests_data', '/_admin/my_account/pull_requests/data', []); |
|
254 | 263 | pyroutes.register('notifications_show_all', '/_admin/notifications', []); |
|
255 | 264 | pyroutes.register('notifications_mark_all_read', '/_admin/notifications/mark_all_read', []); |
|
256 | 265 | pyroutes.register('notifications_show', '/_admin/notifications/%(notification_id)s', ['notification_id']); |
|
257 | 266 | pyroutes.register('notifications_update', '/_admin/notifications/%(notification_id)s/update', ['notification_id']); |
|
258 | 267 | pyroutes.register('notifications_delete', '/_admin/notifications/%(notification_id)s/delete', ['notification_id']); |
|
259 | 268 | pyroutes.register('my_account_notifications_test_channelstream', '/_admin/my_account/test_channelstream', []); |
|
260 | 269 | pyroutes.register('gists_show', '/_admin/gists', []); |
|
261 | 270 | pyroutes.register('gists_new', '/_admin/gists/new', []); |
|
262 | 271 | pyroutes.register('gists_create', '/_admin/gists/create', []); |
|
263 | 272 | pyroutes.register('gist_show', '/_admin/gists/%(gist_id)s', ['gist_id']); |
|
264 | 273 | pyroutes.register('gist_delete', '/_admin/gists/%(gist_id)s/delete', ['gist_id']); |
|
265 | 274 | pyroutes.register('gist_edit', '/_admin/gists/%(gist_id)s/edit', ['gist_id']); |
|
266 | 275 | pyroutes.register('gist_edit_check_revision', '/_admin/gists/%(gist_id)s/edit/check_revision', ['gist_id']); |
|
267 | 276 | pyroutes.register('gist_update', '/_admin/gists/%(gist_id)s/update', ['gist_id']); |
|
268 | 277 | pyroutes.register('gist_show_rev', '/_admin/gists/%(gist_id)s/%(revision)s', ['gist_id', 'revision']); |
|
269 | 278 | pyroutes.register('gist_show_formatted', '/_admin/gists/%(gist_id)s/%(revision)s/%(format)s', ['gist_id', 'revision', 'format']); |
|
270 | 279 | pyroutes.register('gist_show_formatted_path', '/_admin/gists/%(gist_id)s/%(revision)s/%(format)s/%(f_path)s', ['gist_id', 'revision', 'format', 'f_path']); |
|
271 | 280 | pyroutes.register('debug_style_home', '/_admin/debug_style', []); |
|
272 | 281 | pyroutes.register('debug_style_template', '/_admin/debug_style/t/%(t_path)s', ['t_path']); |
|
273 | 282 | pyroutes.register('apiv2', '/_admin/api', []); |
|
274 | 283 | } |
@@ -1,332 +1,339 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | |
|
3 | 3 | # Copyright (C) 2010-2017 RhodeCode GmbH |
|
4 | 4 | # |
|
5 | 5 | # This program is free software: you can redistribute it and/or modify |
|
6 | 6 | # it under the terms of the GNU Affero General Public License, version 3 |
|
7 | 7 | # (only), as published by the Free Software Foundation. |
|
8 | 8 | # |
|
9 | 9 | # This program is distributed in the hope that it will be useful, |
|
10 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of |
|
11 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|
12 | 12 | # GNU General Public License for more details. |
|
13 | 13 | # |
|
14 | 14 | # You should have received a copy of the GNU Affero General Public License |
|
15 | 15 | # along with this program. If not, see <http://www.gnu.org/licenses/>. |
|
16 | 16 | # |
|
17 | 17 | # This program is dual-licensed. If you wish to learn more about the |
|
18 | 18 | # RhodeCode Enterprise Edition, including its added features, Support services, |
|
19 | 19 | # and proprietary license terms, please see https://rhodecode.com/licenses/ |
|
20 | 20 | import io |
|
21 | 21 | import re |
|
22 | 22 | import datetime |
|
23 | 23 | import logging |
|
24 | 24 | import pylons |
|
25 | 25 | import Queue |
|
26 | 26 | import subprocess32 |
|
27 | 27 | import os |
|
28 | 28 | |
|
29 | 29 | from pyramid.i18n import get_localizer |
|
30 | 30 | from pyramid.threadlocal import get_current_request |
|
31 | 31 | from pyramid.interfaces import IRoutesMapper |
|
32 | 32 | from pyramid.settings import asbool |
|
33 | 33 | from pyramid.path import AssetResolver |
|
34 | 34 | from threading import Thread |
|
35 | 35 | |
|
36 | 36 | from rhodecode.translation import _ as tsf |
|
37 | 37 | from rhodecode.config.jsroutes import generate_jsroutes_content |
|
38 | from rhodecode.lib import auth | |
|
38 | 39 | |
|
39 | 40 | import rhodecode |
|
40 | 41 | |
|
41 | 42 | from pylons.i18n.translation import _get_translator |
|
42 | 43 | from pylons.util import ContextObj |
|
43 | 44 | from routes.util import URLGenerator |
|
44 | 45 | |
|
45 | 46 | from rhodecode.lib.base import attach_context_attributes, get_auth_user |
|
46 | 47 | |
|
47 | 48 | log = logging.getLogger(__name__) |
|
48 | 49 | |
|
49 | 50 | |
|
50 | 51 | def add_renderer_globals(event): |
|
51 | 52 | from rhodecode.lib import helpers |
|
52 | 53 | |
|
53 | 54 | # NOTE(marcink): |
|
54 | 55 | # Put pylons stuff into the context. This will be removed as soon as |
|
55 | 56 | # migration to pyramid is finished. |
|
56 | 57 | event['c'] = pylons.tmpl_context |
|
57 | 58 | |
|
58 | 59 | # TODO: When executed in pyramid view context the request is not available |
|
59 | 60 | # in the event. Find a better solution to get the request. |
|
60 | 61 | request = event['request'] or get_current_request() |
|
61 | 62 | |
|
62 | 63 | # Add Pyramid translation as '_' to context |
|
63 | 64 | event['_'] = request.translate |
|
64 | 65 | event['_ungettext'] = request.plularize |
|
65 | 66 | event['h'] = helpers |
|
66 | 67 | |
|
67 | 68 | |
|
68 | 69 | def add_localizer(event): |
|
69 | 70 | request = event.request |
|
70 | 71 | localizer = get_localizer(request) |
|
71 | 72 | |
|
72 | 73 | def auto_translate(*args, **kwargs): |
|
73 | 74 | return localizer.translate(tsf(*args, **kwargs)) |
|
74 | 75 | |
|
75 | 76 | request.localizer = localizer |
|
76 | 77 | request.translate = auto_translate |
|
77 | 78 | request.plularize = localizer.pluralize |
|
78 | 79 | |
|
79 | 80 | |
|
80 | 81 | def set_user_lang(event): |
|
81 | 82 | request = event.request |
|
82 | 83 | cur_user = getattr(request, 'user', None) |
|
83 | 84 | |
|
84 | 85 | if cur_user: |
|
85 | 86 | user_lang = cur_user.get_instance().user_data.get('language') |
|
86 | 87 | if user_lang: |
|
87 | 88 | log.debug('lang: setting current user:%s language to: %s', cur_user, user_lang) |
|
88 | 89 | event.request._LOCALE_ = user_lang |
|
89 | 90 | |
|
90 | 91 | |
|
91 | 92 | def add_request_user_context(event): |
|
92 | 93 | """ |
|
93 | 94 | Adds auth user into request context |
|
94 | 95 | """ |
|
95 | 96 | request = event.request |
|
96 | 97 | |
|
97 | 98 | if hasattr(request, 'vcs_call'): |
|
98 | 99 | # skip vcs calls |
|
99 | 100 | return |
|
100 | 101 | |
|
101 | 102 | if hasattr(request, 'rpc_method'): |
|
102 | 103 | # skip api calls |
|
103 | 104 | return |
|
104 | 105 | |
|
105 | 106 | auth_user = get_auth_user(request) |
|
106 | 107 | request.user = auth_user |
|
107 | 108 | request.environ['rc_auth_user'] = auth_user |
|
108 | 109 | |
|
109 | 110 | |
|
110 | 111 | def add_pylons_context(event): |
|
111 | 112 | request = event.request |
|
112 | 113 | |
|
113 | 114 | config = rhodecode.CONFIG |
|
114 | 115 | environ = request.environ |
|
115 | 116 | session = request.session |
|
116 | 117 | |
|
117 | 118 | if hasattr(request, 'vcs_call'): |
|
118 | 119 | # skip vcs calls |
|
119 | 120 | return |
|
120 | 121 | |
|
121 | 122 | # Setup pylons globals. |
|
122 | 123 | pylons.config._push_object(config) |
|
123 | 124 | pylons.request._push_object(request) |
|
124 | 125 | pylons.session._push_object(session) |
|
125 | 126 | pylons.translator._push_object(_get_translator(config.get('lang'))) |
|
126 | 127 | |
|
127 | 128 | pylons.url._push_object(URLGenerator(config['routes.map'], environ)) |
|
128 | 129 | session_key = ( |
|
129 | 130 | config['pylons.environ_config'].get('session', 'beaker.session')) |
|
130 | 131 | environ[session_key] = session |
|
131 | 132 | |
|
132 | 133 | if hasattr(request, 'rpc_method'): |
|
133 | 134 | # skip api calls |
|
134 | 135 | return |
|
135 | 136 | |
|
136 | 137 | # Setup the pylons context object ('c') |
|
137 | 138 | context = ContextObj() |
|
138 | 139 | context.rhodecode_user = request.user |
|
139 | 140 | attach_context_attributes(context, request, request.user.user_id) |
|
140 | 141 | pylons.tmpl_context._push_object(context) |
|
141 | 142 | |
|
142 | 143 | |
|
144 | def inject_app_settings(event): | |
|
145 | settings = event.app.registry.settings | |
|
146 | # inject info about available permissions | |
|
147 | auth.set_available_permissions(settings) | |
|
148 | ||
|
149 | ||
|
143 | 150 | def scan_repositories_if_enabled(event): |
|
144 | 151 | """ |
|
145 | 152 | This is subscribed to the `pyramid.events.ApplicationCreated` event. It |
|
146 | 153 | does a repository scan if enabled in the settings. |
|
147 | 154 | """ |
|
148 | 155 | settings = event.app.registry.settings |
|
149 | 156 | vcs_server_enabled = settings['vcs.server.enable'] |
|
150 | 157 | import_on_startup = settings['startup.import_repos'] |
|
151 | 158 | if vcs_server_enabled and import_on_startup: |
|
152 | 159 | from rhodecode.model.scm import ScmModel |
|
153 | 160 | from rhodecode.lib.utils import repo2db_mapper, get_rhodecode_base_path |
|
154 | 161 | repositories = ScmModel().repo_scan(get_rhodecode_base_path()) |
|
155 | 162 | repo2db_mapper(repositories, remove_obsolete=False) |
|
156 | 163 | |
|
157 | 164 | |
|
158 | 165 | def write_metadata_if_needed(event): |
|
159 | 166 | """ |
|
160 | 167 | Writes upgrade metadata |
|
161 | 168 | """ |
|
162 | 169 | import rhodecode |
|
163 | 170 | from rhodecode.lib import system_info |
|
164 | 171 | from rhodecode.lib import ext_json |
|
165 | 172 | |
|
166 | 173 | def write(): |
|
167 | 174 | fname = '.rcmetadata.json' |
|
168 | 175 | ini_loc = os.path.dirname(rhodecode.CONFIG.get('__file__')) |
|
169 | 176 | metadata_destination = os.path.join(ini_loc, fname) |
|
170 | 177 | |
|
171 | 178 | configuration = system_info.SysInfo( |
|
172 | 179 | system_info.rhodecode_config)()['value'] |
|
173 | 180 | license_token = configuration['config']['license_token'] |
|
174 | 181 | dbinfo = system_info.SysInfo(system_info.database_info)()['value'] |
|
175 | 182 | del dbinfo['url'] |
|
176 | 183 | metadata = dict( |
|
177 | 184 | desc='upgrade metadata info', |
|
178 | 185 | license_token=license_token, |
|
179 | 186 | created_on=datetime.datetime.utcnow().isoformat(), |
|
180 | 187 | usage=system_info.SysInfo(system_info.usage_info)()['value'], |
|
181 | 188 | platform=system_info.SysInfo(system_info.platform_type)()['value'], |
|
182 | 189 | database=dbinfo, |
|
183 | 190 | cpu=system_info.SysInfo(system_info.cpu)()['value'], |
|
184 | 191 | memory=system_info.SysInfo(system_info.memory)()['value'], |
|
185 | 192 | ) |
|
186 | 193 | |
|
187 | 194 | with open(metadata_destination, 'wb') as f: |
|
188 | 195 | f.write(ext_json.json.dumps(metadata)) |
|
189 | 196 | |
|
190 | 197 | settings = event.app.registry.settings |
|
191 | 198 | if settings.get('metadata.skip'): |
|
192 | 199 | return |
|
193 | 200 | |
|
194 | 201 | try: |
|
195 | 202 | write() |
|
196 | 203 | except Exception: |
|
197 | 204 | pass |
|
198 | 205 | |
|
199 | 206 | |
|
200 | 207 | def write_js_routes_if_enabled(event): |
|
201 | 208 | registry = event.app.registry |
|
202 | 209 | |
|
203 | 210 | mapper = registry.queryUtility(IRoutesMapper) |
|
204 | 211 | _argument_prog = re.compile('\{(.*?)\}|:\((.*)\)') |
|
205 | 212 | |
|
206 | 213 | def _extract_route_information(route): |
|
207 | 214 | """ |
|
208 | 215 | Convert a route into tuple(name, path, args), eg: |
|
209 | 216 | ('show_user', '/profile/%(username)s', ['username']) |
|
210 | 217 | """ |
|
211 | 218 | |
|
212 | 219 | routepath = route.pattern |
|
213 | 220 | pattern = route.pattern |
|
214 | 221 | |
|
215 | 222 | def replace(matchobj): |
|
216 | 223 | if matchobj.group(1): |
|
217 | 224 | return "%%(%s)s" % matchobj.group(1).split(':')[0] |
|
218 | 225 | else: |
|
219 | 226 | return "%%(%s)s" % matchobj.group(2) |
|
220 | 227 | |
|
221 | 228 | routepath = _argument_prog.sub(replace, routepath) |
|
222 | 229 | |
|
223 | 230 | if not routepath.startswith('/'): |
|
224 | 231 | routepath = '/'+routepath |
|
225 | 232 | |
|
226 | 233 | return ( |
|
227 | 234 | route.name, |
|
228 | 235 | routepath, |
|
229 | 236 | [(arg[0].split(':')[0] if arg[0] != '' else arg[1]) |
|
230 | 237 | for arg in _argument_prog.findall(pattern)] |
|
231 | 238 | ) |
|
232 | 239 | |
|
233 | 240 | def get_routes(): |
|
234 | 241 | # pylons routes |
|
235 | 242 | # TODO(marcink): remove when pyramid migration is finished |
|
236 | 243 | if 'routes.map' in rhodecode.CONFIG: |
|
237 | 244 | for route in rhodecode.CONFIG['routes.map'].jsroutes(): |
|
238 | 245 | yield route |
|
239 | 246 | |
|
240 | 247 | # pyramid routes |
|
241 | 248 | for route in mapper.get_routes(): |
|
242 | 249 | if not route.name.startswith('__'): |
|
243 | 250 | yield _extract_route_information(route) |
|
244 | 251 | |
|
245 | 252 | if asbool(registry.settings.get('generate_js_files', 'false')): |
|
246 | 253 | static_path = AssetResolver().resolve('rhodecode:public').abspath() |
|
247 | 254 | jsroutes = get_routes() |
|
248 | 255 | jsroutes_file_content = generate_jsroutes_content(jsroutes) |
|
249 | 256 | jsroutes_file_path = os.path.join( |
|
250 | 257 | static_path, 'js', 'rhodecode', 'routes.js') |
|
251 | 258 | |
|
252 | 259 | with io.open(jsroutes_file_path, 'w', encoding='utf-8') as f: |
|
253 | 260 | f.write(jsroutes_file_content) |
|
254 | 261 | |
|
255 | 262 | |
|
256 | 263 | class Subscriber(object): |
|
257 | 264 | """ |
|
258 | 265 | Base class for subscribers to the pyramid event system. |
|
259 | 266 | """ |
|
260 | 267 | def __call__(self, event): |
|
261 | 268 | self.run(event) |
|
262 | 269 | |
|
263 | 270 | def run(self, event): |
|
264 | 271 | raise NotImplementedError('Subclass has to implement this.') |
|
265 | 272 | |
|
266 | 273 | |
|
267 | 274 | class AsyncSubscriber(Subscriber): |
|
268 | 275 | """ |
|
269 | 276 | Subscriber that handles the execution of events in a separate task to not |
|
270 | 277 | block the execution of the code which triggers the event. It puts the |
|
271 | 278 | received events into a queue from which the worker process takes them in |
|
272 | 279 | order. |
|
273 | 280 | """ |
|
274 | 281 | def __init__(self): |
|
275 | 282 | self._stop = False |
|
276 | 283 | self._eventq = Queue.Queue() |
|
277 | 284 | self._worker = self.create_worker() |
|
278 | 285 | self._worker.start() |
|
279 | 286 | |
|
280 | 287 | def __call__(self, event): |
|
281 | 288 | self._eventq.put(event) |
|
282 | 289 | |
|
283 | 290 | def create_worker(self): |
|
284 | 291 | worker = Thread(target=self.do_work) |
|
285 | 292 | worker.daemon = True |
|
286 | 293 | return worker |
|
287 | 294 | |
|
288 | 295 | def stop_worker(self): |
|
289 | 296 | self._stop = False |
|
290 | 297 | self._eventq.put(None) |
|
291 | 298 | self._worker.join() |
|
292 | 299 | |
|
293 | 300 | def do_work(self): |
|
294 | 301 | while not self._stop: |
|
295 | 302 | event = self._eventq.get() |
|
296 | 303 | if event is not None: |
|
297 | 304 | self.run(event) |
|
298 | 305 | |
|
299 | 306 | |
|
300 | 307 | class AsyncSubprocessSubscriber(AsyncSubscriber): |
|
301 | 308 | """ |
|
302 | 309 | Subscriber that uses the subprocess32 module to execute a command if an |
|
303 | 310 | event is received. Events are handled asynchronously. |
|
304 | 311 | """ |
|
305 | 312 | |
|
306 | 313 | def __init__(self, cmd, timeout=None): |
|
307 | 314 | super(AsyncSubprocessSubscriber, self).__init__() |
|
308 | 315 | self._cmd = cmd |
|
309 | 316 | self._timeout = timeout |
|
310 | 317 | |
|
311 | 318 | def run(self, event): |
|
312 | 319 | cmd = self._cmd |
|
313 | 320 | timeout = self._timeout |
|
314 | 321 | log.debug('Executing command %s.', cmd) |
|
315 | 322 | |
|
316 | 323 | try: |
|
317 | 324 | output = subprocess32.check_output( |
|
318 | 325 | cmd, timeout=timeout, stderr=subprocess32.STDOUT) |
|
319 | 326 | log.debug('Command finished %s', cmd) |
|
320 | 327 | if output: |
|
321 | 328 | log.debug('Command output: %s', output) |
|
322 | 329 | except subprocess32.TimeoutExpired as e: |
|
323 | 330 | log.exception('Timeout while executing command.') |
|
324 | 331 | if e.output: |
|
325 | 332 | log.error('Command output: %s', e.output) |
|
326 | 333 | except subprocess32.CalledProcessError as e: |
|
327 | 334 | log.exception('Error while executing command.') |
|
328 | 335 | if e.output: |
|
329 | 336 | log.error('Command output: %s', e.output) |
|
330 | 337 | except: |
|
331 | 338 | log.exception( |
|
332 | 339 | 'Exception while executing command %s.', cmd) |
@@ -1,180 +1,179 b'' | |||
|
1 | 1 | <div class="panel panel-default"> |
|
2 | 2 | <div class="panel-heading"> |
|
3 | 3 | <h3 class="panel-title">${_('Authentication Tokens')}</h3> |
|
4 | 4 | </div> |
|
5 | 5 | <div class="panel-body"> |
|
6 | 6 | <div class="apikeys_wrap"> |
|
7 | 7 | <p> |
|
8 | 8 | ${_('Each token can have a role. Token with a role can be used only in given context, ' |
|
9 | 9 | 'e.g. VCS tokens can be used together with the authtoken auth plugin for git/hg/svn operations only.')} |
|
10 | 10 | </p> |
|
11 | 11 | <table class="rctable auth_tokens"> |
|
12 | 12 | <tr> |
|
13 | 13 | <th>${_('Token')}</th> |
|
14 | 14 | <th>${_('Scope')}</th> |
|
15 | 15 | <th>${_('Description')}</th> |
|
16 | 16 | <th>${_('Role')}</th> |
|
17 | 17 | <th>${_('Expiration')}</th> |
|
18 | 18 | <th>${_('Action')}</th> |
|
19 | 19 | </tr> |
|
20 | 20 | %if c.user_auth_tokens: |
|
21 | 21 | %for auth_token in c.user_auth_tokens: |
|
22 | 22 | <tr class="${'expired' if auth_token.expired else ''}"> |
|
23 | 23 | <td class="truncate-wrap td-authtoken"> |
|
24 | 24 | <div class="user_auth_tokens truncate autoexpand"> |
|
25 | 25 | <code>${auth_token.api_key}</code> |
|
26 | 26 | </div> |
|
27 | 27 | </td> |
|
28 | 28 | <td class="td">${auth_token.scope_humanized}</td> |
|
29 | 29 | <td class="td-wrap">${auth_token.description}</td> |
|
30 | 30 | <td class="td-tags"> |
|
31 | 31 | <span class="tag disabled">${auth_token.role_humanized}</span> |
|
32 | 32 | </td> |
|
33 | 33 | <td class="td-exp"> |
|
34 | 34 | %if auth_token.expires == -1: |
|
35 | 35 | ${_('never')} |
|
36 | 36 | %else: |
|
37 | 37 | %if auth_token.expired: |
|
38 | 38 | <span style="text-decoration: line-through">${h.age_component(h.time_to_utcdatetime(auth_token.expires))}</span> |
|
39 | 39 | %else: |
|
40 | 40 | ${h.age_component(h.time_to_utcdatetime(auth_token.expires))} |
|
41 | 41 | %endif |
|
42 | 42 | %endif |
|
43 | 43 | </td> |
|
44 | 44 | <td class="td-action"> |
|
45 | 45 | ${h.secure_form(h.route_path('my_account_auth_tokens_delete'), request=request)} |
|
46 | 46 | ${h.hidden('del_auth_token', auth_token.user_api_key_id)} |
|
47 | 47 | <button class="btn btn-link btn-danger" type="submit" |
|
48 | 48 | onclick="return confirm('${_('Confirm to remove this auth token: %s') % auth_token.token_obfuscated}');"> |
|
49 | 49 | ${_('Delete')} |
|
50 | 50 | </button> |
|
51 | 51 | ${h.end_form()} |
|
52 | 52 | </td> |
|
53 | 53 | </tr> |
|
54 | 54 | %endfor |
|
55 | 55 | %else: |
|
56 | 56 | <tr><td><div class="ip">${_('No additional auth tokens specified')}</div></td></tr> |
|
57 | 57 | %endif |
|
58 | 58 | </table> |
|
59 | 59 | </div> |
|
60 | 60 | |
|
61 | 61 | <div class="user_auth_tokens"> |
|
62 | 62 | ${h.secure_form(h.route_path('my_account_auth_tokens_add'), request=request)} |
|
63 | 63 | <div class="form form-vertical"> |
|
64 | 64 | <!-- fields --> |
|
65 | 65 | <div class="fields"> |
|
66 | 66 | <div class="field"> |
|
67 | 67 | <div class="label"> |
|
68 | 68 | <label for="new_email">${_('New authentication token')}:</label> |
|
69 | 69 | </div> |
|
70 | 70 | <div class="input"> |
|
71 | 71 | ${h.text('description', class_='medium', placeholder=_('Description'))} |
|
72 | 72 | ${h.hidden('lifetime')} |
|
73 | 73 | ${h.select('role', '', c.role_options)} |
|
74 | 74 | |
|
75 | 75 | % if c.allow_scoped_tokens: |
|
76 | 76 | ${h.hidden('scope_repo_id')} |
|
77 | 77 | % else: |
|
78 | 78 | ${h.select('scope_repo_id_disabled', '', ['Scopes available in EE edition'], disabled='disabled')} |
|
79 | 79 | % endif |
|
80 | 80 | </div> |
|
81 | 81 | <p class="help-block"> |
|
82 | 82 | ${_('Repository scope works only with tokens with VCS type.')} |
|
83 | 83 | </p> |
|
84 | 84 | </div> |
|
85 | 85 | <div class="buttons"> |
|
86 | 86 | ${h.submit('save',_('Add'),class_="btn")} |
|
87 | 87 | ${h.reset('reset',_('Reset'),class_="btn")} |
|
88 | 88 | </div> |
|
89 | 89 | </div> |
|
90 | 90 | </div> |
|
91 | 91 | ${h.end_form()} |
|
92 | 92 | </div> |
|
93 | 93 | </div> |
|
94 | 94 | </div> |
|
95 | 95 | <script> |
|
96 | 96 | $(document).ready(function(){ |
|
97 | 97 | |
|
98 | 98 | var select2Options = { |
|
99 | 99 | 'containerCssClass': "drop-menu", |
|
100 | 100 | 'dropdownCssClass': "drop-menu-dropdown", |
|
101 | 101 | 'dropdownAutoWidth': true |
|
102 | 102 | }; |
|
103 | 103 | $("#role").select2(select2Options); |
|
104 | 104 | |
|
105 | ||
|
106 | 105 | var preloadData = { |
|
107 | 106 | results: [ |
|
108 | 107 | % for entry in c.lifetime_values: |
|
109 | 108 | {id:${entry[0]}, text:"${entry[1]}"}${'' if loop.last else ','} |
|
110 | 109 | % endfor |
|
111 | 110 | ] |
|
112 | 111 | }; |
|
113 | 112 | |
|
114 | 113 | $("#lifetime").select2({ |
|
115 | 114 | containerCssClass: "drop-menu", |
|
116 | 115 | dropdownCssClass: "drop-menu-dropdown", |
|
117 | 116 | dropdownAutoWidth: true, |
|
118 | 117 | data: preloadData, |
|
119 | 118 | placeholder: "${_('Select or enter expiration date')}", |
|
120 | 119 | query: function(query) { |
|
121 | 120 | feedLifetimeOptions(query, preloadData); |
|
122 | 121 | } |
|
123 | 122 | }); |
|
124 | 123 | |
|
125 | 124 | |
|
126 | 125 | var repoFilter = function(data) { |
|
127 | 126 | var results = []; |
|
128 | 127 | |
|
129 | 128 | if (!data.results[0]) { |
|
130 | 129 | return data |
|
131 | 130 | } |
|
132 | 131 | |
|
133 | 132 | $.each(data.results[0].children, function() { |
|
134 | 133 | // replace name to ID for submision |
|
135 | 134 | this.id = this.obj.repo_id; |
|
136 | 135 | results.push(this); |
|
137 | 136 | }); |
|
138 | 137 | |
|
139 | 138 | data.results[0].children = results; |
|
140 | 139 | return data; |
|
141 | 140 | }; |
|
142 | 141 | |
|
143 | 142 | $("#scope_repo_id_disabled").select2(select2Options); |
|
144 | 143 | |
|
145 | 144 | $("#scope_repo_id").select2({ |
|
146 | 145 | cachedDataSource: {}, |
|
147 | 146 | minimumInputLength: 2, |
|
148 | 147 | placeholder: "${_('repository scope')}", |
|
149 | 148 | dropdownAutoWidth: true, |
|
150 | 149 | containerCssClass: "drop-menu", |
|
151 | 150 | dropdownCssClass: "drop-menu-dropdown", |
|
152 | 151 | formatResult: formatResult, |
|
153 | 152 | query: $.debounce(250, function(query){ |
|
154 | 153 | self = this; |
|
155 | 154 | var cacheKey = query.term; |
|
156 | 155 | var cachedData = self.cachedDataSource[cacheKey]; |
|
157 | 156 | |
|
158 | 157 | if (cachedData) { |
|
159 | 158 | query.callback({results: cachedData.results}); |
|
160 | 159 | } else { |
|
161 | 160 | $.ajax({ |
|
162 | 161 | url: pyroutes.url('repo_list_data'), |
|
163 | 162 | data: {'query': query.term}, |
|
164 | 163 | dataType: 'json', |
|
165 | 164 | type: 'GET', |
|
166 | 165 | success: function(data) { |
|
167 | 166 | data = repoFilter(data); |
|
168 | 167 | self.cachedDataSource[cacheKey] = data; |
|
169 | 168 | query.callback({results: data.results}); |
|
170 | 169 | }, |
|
171 | 170 | error: function(data, textStatus, errorThrown) { |
|
172 | 171 | alert("Error while fetching entries.\nError code {0} ({1}).".format(data.status, data.statusText)); |
|
173 | 172 | } |
|
174 | 173 | }) |
|
175 | 174 | } |
|
176 | 175 | }) |
|
177 | 176 | }); |
|
178 | 177 | |
|
179 | 178 | }); |
|
180 | 179 | </script> |
@@ -1,186 +1,186 b'' | |||
|
1 | 1 | ## -*- coding: utf-8 -*- |
|
2 | 2 | <%namespace name="base" file="/base/base.mako"/> |
|
3 | 3 | |
|
4 | 4 | <div class="panel panel-default"> |
|
5 | 5 | <div class="panel-heading"> |
|
6 | 6 | <h3 class="panel-title">${_('User Group: %s') % c.user_group.users_group_name}</h3> |
|
7 | 7 | </div> |
|
8 | 8 | <div class="panel-body"> |
|
9 | 9 | ${h.secure_form(h.route_path('user_groups_update', user_group_id=c.user_group.users_group_id), id='edit_user_group', request=request)} |
|
10 | 10 | <div class="form"> |
|
11 | 11 | <!-- fields --> |
|
12 | 12 | <div class="fields"> |
|
13 | 13 | <div class="field"> |
|
14 | 14 | <div class="label"> |
|
15 | 15 | <label for="users_group_name">${_('Group name')}:</label> |
|
16 | 16 | </div> |
|
17 | 17 | <div class="input"> |
|
18 | 18 | ${h.text('users_group_name',class_='medium')} |
|
19 | 19 | </div> |
|
20 | 20 | </div> |
|
21 | 21 | |
|
22 | 22 | <div class="field badged-field"> |
|
23 | 23 | <div class="label"> |
|
24 | 24 | <label for="user">${_('Owner')}:</label> |
|
25 | 25 | </div> |
|
26 | 26 | <div class="input"> |
|
27 | 27 | <div class="badge-input-container"> |
|
28 | 28 | <div class="user-badge"> |
|
29 | 29 | ${base.gravatar_with_user(c.user_group.user.email, show_disabled=not c.user_group.user.active)} |
|
30 | 30 | </div> |
|
31 | 31 | <div class="badge-input-wrap"> |
|
32 | 32 | ${h.text('user', class_="medium", autocomplete="off")} |
|
33 | 33 | </div> |
|
34 | 34 | </div> |
|
35 | 35 | <form:error name="user"/> |
|
36 | 36 | <p class="help-block">${_('Change owner of this user group.')}</p> |
|
37 | 37 | </div> |
|
38 | 38 | </div> |
|
39 | 39 | |
|
40 | 40 | <div class="field"> |
|
41 | 41 | <div class="label label-textarea"> |
|
42 | 42 | <label for="user_group_description">${_('Description')}:</label> |
|
43 | 43 | </div> |
|
44 | 44 | <div class="textarea textarea-small editor"> |
|
45 | 45 | ${h.textarea('user_group_description',cols=23,rows=5,class_="medium")} |
|
46 | 46 | <span class="help-block">${_('Short, optional description for this user group.')}</span> |
|
47 | 47 | </div> |
|
48 | 48 | </div> |
|
49 | 49 | <div class="field"> |
|
50 | 50 | <div class="label label-checkbox"> |
|
51 | 51 | <label for="users_group_active">${_('Active')}:</label> |
|
52 | 52 | </div> |
|
53 | 53 | <div class="checkboxes"> |
|
54 | 54 | ${h.checkbox('users_group_active',value=True)} |
|
55 | 55 | </div> |
|
56 | 56 | </div> |
|
57 | 57 | |
|
58 | 58 | <div class="field"> |
|
59 | 59 | <div class="label label-checkbox"> |
|
60 | 60 | <label for="users_group_active">${_('Add members')}:</label> |
|
61 | 61 | </div> |
|
62 | 62 | <div class="input"> |
|
63 | 63 | ${h.text('user_group_add_members', placeholder="user/usergroup", class_="medium")} |
|
64 | 64 | </div> |
|
65 | 65 | </div> |
|
66 | 66 | |
|
67 | 67 | <input type="hidden" name="__start__" value="user_group_members:sequence"/> |
|
68 | 68 | <table id="group_members_placeholder" class="rctable group_members"> |
|
69 | 69 | <tr> |
|
70 | 70 | <th>${_('Username')}</th> |
|
71 | 71 | <th>${_('Action')}</th> |
|
72 | 72 | </tr> |
|
73 | 73 | |
|
74 | 74 | % if c.group_members_obj: |
|
75 | 75 | % for user in c.group_members_obj: |
|
76 | 76 | <tr> |
|
77 | 77 | <td id="member_user_${user.user_id}" class="td-author"> |
|
78 | 78 | <div class="group_member"> |
|
79 | 79 | ${base.gravatar(user.email, 16)} |
|
80 |
<span class="username user">${h.link_to(h.person(user), h. |
|
|
80 | <span class="username user">${h.link_to(h.person(user), h.route_path('user_edit',user_id=user.user_id))}</span> | |
|
81 | 81 | <input type="hidden" name="__start__" value="member:mapping"> |
|
82 | 82 | <input type="hidden" name="member_user_id" value="${user.user_id}"> |
|
83 | 83 | <input type="hidden" name="type" value="existing" id="member_${user.user_id}"> |
|
84 | 84 | <input type="hidden" name="__end__" value="member:mapping"> |
|
85 | 85 | </div> |
|
86 | 86 | </td> |
|
87 | 87 | <td class=""> |
|
88 | 88 | <div class="usergroup_member_remove action_button" onclick="removeUserGroupMember(${user.user_id}, true)" style="visibility: visible;"> |
|
89 | 89 | <i class="icon-remove-sign"></i> |
|
90 | 90 | </div> |
|
91 | 91 | </td> |
|
92 | 92 | </tr> |
|
93 | 93 | % endfor |
|
94 | 94 | |
|
95 | 95 | % else: |
|
96 | 96 | <tr><td colspan="2">${_('No members yet')}</td></tr> |
|
97 | 97 | % endif |
|
98 | 98 | </table> |
|
99 | 99 | <input type="hidden" name="__end__" value="user_group_members:sequence"/> |
|
100 | 100 | |
|
101 | 101 | <div class="buttons"> |
|
102 | 102 | ${h.submit('Save',_('Save'),class_="btn")} |
|
103 | 103 | </div> |
|
104 | 104 | </div> |
|
105 | 105 | </div> |
|
106 | 106 | ${h.end_form()} |
|
107 | 107 | </div> |
|
108 | 108 | </div> |
|
109 | 109 | <script> |
|
110 | 110 | $(document).ready(function(){ |
|
111 | 111 | $("#group_parent_id").select2({ |
|
112 | 112 | 'containerCssClass': "drop-menu", |
|
113 | 113 | 'dropdownCssClass': "drop-menu-dropdown", |
|
114 | 114 | 'dropdownAutoWidth': true |
|
115 | 115 | }); |
|
116 | 116 | |
|
117 | 117 | removeUserGroupMember = function(userId){ |
|
118 | 118 | $('#member_'+userId).val('remove'); |
|
119 | 119 | $('#member_user_'+userId).addClass('to-delete'); |
|
120 | 120 | }; |
|
121 | 121 | |
|
122 | 122 | $('#user_group_add_members').autocomplete({ |
|
123 | 123 | serviceUrl: pyroutes.url('user_autocomplete_data'), |
|
124 | 124 | minChars:2, |
|
125 | 125 | maxHeight:400, |
|
126 | 126 | width:300, |
|
127 | 127 | deferRequestBy: 300, //miliseconds |
|
128 | 128 | showNoSuggestionNotice: true, |
|
129 | 129 | params: { user_groups:true }, |
|
130 | 130 | formatResult: autocompleteFormatResult, |
|
131 | 131 | lookupFilter: autocompleteFilterResult, |
|
132 | 132 | onSelect: function(element, suggestion){ |
|
133 | 133 | |
|
134 | 134 | function addMember(user, fromUserGroup) { |
|
135 | 135 | var gravatar = user.icon_link; |
|
136 | 136 | var username = user.value_display; |
|
137 |
var userLink = pyroutes.url(' |
|
|
137 | var userLink = pyroutes.url('user_edit', {"user_id": user.id}); | |
|
138 | 138 | var uid = user.id; |
|
139 | 139 | |
|
140 | 140 | if (fromUserGroup) { |
|
141 | 141 | username = username +" "+ _gettext('(from usergroup {0})'.format(fromUserGroup)) |
|
142 | 142 | } |
|
143 | 143 | |
|
144 | 144 | var elem = $( |
|
145 | 145 | ('<tr>'+ |
|
146 | 146 | '<td id="member_user_{6}" class="td-author td-author-new-entry">'+ |
|
147 | 147 | '<div class="group_member">'+ |
|
148 | 148 | '<img class="gravatar" src="{0}" height="16" width="16">'+ |
|
149 | 149 | '<span class="username user"><a href="{1}">{2}</a></span>'+ |
|
150 | 150 | '<input type="hidden" name="__start__" value="member:mapping">'+ |
|
151 | 151 | '<input type="hidden" name="member_user_id" value="{3}">'+ |
|
152 | 152 | '<input type="hidden" name="type" value="new" id="member_{4}">'+ |
|
153 | 153 | '<input type="hidden" name="__end__" value="member:mapping">'+ |
|
154 | 154 | '</div>'+ |
|
155 | 155 | '</td>'+ |
|
156 | 156 | '<td class="td-author-new-entry">'+ |
|
157 | 157 | '<div class="usergroup_member_remove action_button" onclick="removeUserGroupMember({5}, true)" style="visibility: visible;">'+ |
|
158 | 158 | '<i class="icon-remove-sign"></i>'+ |
|
159 | 159 | '</div>'+ |
|
160 | 160 | '</td>'+ |
|
161 | 161 | '</tr>').format(gravatar, userLink, username, |
|
162 | 162 | uid, uid, uid, uid) |
|
163 | 163 | ); |
|
164 | 164 | $('#group_members_placeholder').append(elem) |
|
165 | 165 | } |
|
166 | 166 | |
|
167 | 167 | if (suggestion.value_type == 'user_group') { |
|
168 | 168 | $.getJSON( |
|
169 | 169 | pyroutes.url('user_group_members_data', |
|
170 | 170 | {'user_group_id': suggestion.id}), |
|
171 | 171 | function(data) { |
|
172 | 172 | $.each(data.members, function(idx, user) { |
|
173 | 173 | addMember(user, suggestion.value) |
|
174 | 174 | }); |
|
175 | 175 | } |
|
176 | 176 | ); |
|
177 | 177 | } else if (suggestion.value_type == 'user') { |
|
178 | 178 | addMember(suggestion, null); |
|
179 | 179 | } |
|
180 | 180 | } |
|
181 | 181 | }); |
|
182 | 182 | |
|
183 | 183 | |
|
184 | 184 | UsersAutoComplete('user', '${c.rhodecode_user.user_id}'); |
|
185 | 185 | }) |
|
186 | 186 | </script> |
@@ -1,147 +1,147 b'' | |||
|
1 | 1 | ## -*- coding: utf-8 -*- |
|
2 | 2 | <%inherit file="/base/base.mako"/> |
|
3 | 3 | |
|
4 | 4 | <%def name="title()"> |
|
5 | 5 | ${_('Add user')} |
|
6 | 6 | %if c.rhodecode_name: |
|
7 | 7 | · ${h.branding(c.rhodecode_name)} |
|
8 | 8 | %endif |
|
9 | 9 | </%def> |
|
10 | 10 | <%def name="breadcrumbs_links()"> |
|
11 | 11 | ${h.link_to(_('Admin'),h.route_path('admin_home'))} |
|
12 | 12 | » |
|
13 | 13 | ${h.link_to(_('Users'),h.route_path('users'))} |
|
14 | 14 | » |
|
15 | 15 | ${_('Add User')} |
|
16 | 16 | </%def> |
|
17 | 17 | |
|
18 | 18 | <%def name="menu_bar_nav()"> |
|
19 | 19 | ${self.menu_items(active='admin')} |
|
20 | 20 | </%def> |
|
21 | 21 | |
|
22 | 22 | <%def name="main()"> |
|
23 | 23 | <div class="box"> |
|
24 | 24 | <!-- box / title --> |
|
25 | 25 | <div class="title"> |
|
26 | 26 | ${self.breadcrumbs()} |
|
27 | 27 | </div> |
|
28 | 28 | <!-- end box / title --> |
|
29 |
${h.secure_form(h. |
|
|
29 | ${h.secure_form(h.route_path('users_create'), request=request)} | |
|
30 | 30 | <div class="form"> |
|
31 | 31 | <!-- fields --> |
|
32 | 32 | <div class="fields"> |
|
33 | 33 | <div class="field"> |
|
34 | 34 | <div class="label"> |
|
35 | 35 | <label for="username">${_('Username')}:</label> |
|
36 | 36 | </div> |
|
37 | 37 | <div class="input"> |
|
38 | 38 | ${h.text('username', class_='medium')} |
|
39 | 39 | </div> |
|
40 | 40 | </div> |
|
41 | 41 | |
|
42 | 42 | <div class="field"> |
|
43 | 43 | <div class="label"> |
|
44 | 44 | <label for="password">${_('Password')}:</label> |
|
45 | 45 | </div> |
|
46 | 46 | <div class="input"> |
|
47 | 47 | ${h.password('password', class_='medium')} |
|
48 | 48 | </div> |
|
49 | 49 | </div> |
|
50 | 50 | |
|
51 | 51 | <div class="field"> |
|
52 | 52 | <div class="label"> |
|
53 | 53 | <label for="password_confirmation">${_('Password confirmation')}:</label> |
|
54 | 54 | </div> |
|
55 | 55 | <div class="input"> |
|
56 | 56 | ${h.password('password_confirmation',autocomplete="off", class_='medium')} |
|
57 | 57 | <div class="info-block"> |
|
58 | 58 | <a id="generate_password" href="#"> |
|
59 | 59 | <i class="icon-lock"></i> ${_('Generate password')} |
|
60 | 60 | </a> |
|
61 | 61 | <span id="generate_password_preview"></span> |
|
62 | 62 | </div> |
|
63 | 63 | </div> |
|
64 | 64 | </div> |
|
65 | 65 | |
|
66 | 66 | <div class="field"> |
|
67 | 67 | <div class="label"> |
|
68 | 68 | <label for="firstname">${_('First Name')}:</label> |
|
69 | 69 | </div> |
|
70 | 70 | <div class="input"> |
|
71 | 71 | ${h.text('firstname', class_='medium')} |
|
72 | 72 | </div> |
|
73 | 73 | </div> |
|
74 | 74 | |
|
75 | 75 | <div class="field"> |
|
76 | 76 | <div class="label"> |
|
77 | 77 | <label for="lastname">${_('Last Name')}:</label> |
|
78 | 78 | </div> |
|
79 | 79 | <div class="input"> |
|
80 | 80 | ${h.text('lastname', class_='medium')} |
|
81 | 81 | </div> |
|
82 | 82 | </div> |
|
83 | 83 | |
|
84 | 84 | <div class="field"> |
|
85 | 85 | <div class="label"> |
|
86 | 86 | <label for="email">${_('Email')}:</label> |
|
87 | 87 | </div> |
|
88 | 88 | <div class="input"> |
|
89 | 89 | ${h.text('email', class_='medium')} |
|
90 | 90 | ${h.hidden('extern_name', c.default_extern_type)} |
|
91 | 91 | ${h.hidden('extern_type', c.default_extern_type)} |
|
92 | 92 | </div> |
|
93 | 93 | </div> |
|
94 | 94 | |
|
95 | 95 | <div class="field"> |
|
96 | 96 | <div class="label label-checkbox"> |
|
97 | 97 | <label for="active">${_('Active')}:</label> |
|
98 | 98 | </div> |
|
99 | 99 | <div class="checkboxes"> |
|
100 | 100 | ${h.checkbox('active',value=True,checked='checked')} |
|
101 | 101 | </div> |
|
102 | 102 | </div> |
|
103 | 103 | |
|
104 | 104 | <div class="field"> |
|
105 | 105 | <div class="label label-checkbox"> |
|
106 | 106 | <label for="password_change">${_('Password change')}:</label> |
|
107 | 107 | </div> |
|
108 | 108 | <div class="checkboxes"> |
|
109 | 109 | ${h.checkbox('password_change',value=True)} |
|
110 | 110 | <span class="help-block">${_('Force user to change his password on the next login')}</span> |
|
111 | 111 | </div> |
|
112 | 112 | </div> |
|
113 | 113 | |
|
114 | 114 | <div class="field"> |
|
115 | 115 | <div class="label label-checkbox"> |
|
116 | 116 | <label for="create_repo_group">${_('Add personal repository group')}:</label> |
|
117 | 117 | </div> |
|
118 | 118 | <div class="checkboxes"> |
|
119 | 119 | ${h.checkbox('create_repo_group',value=True, checked=c.default_create_repo_group)} |
|
120 | 120 | <span class="help-block"> |
|
121 | 121 | ${_('New group will be created at: `/%(path)s`') % {'path': c.personal_repo_group_name}}<br/> |
|
122 | 122 | ${_('User will be automatically set as this group owner.')} |
|
123 | 123 | </span> |
|
124 | 124 | </div> |
|
125 | 125 | </div> |
|
126 | 126 | |
|
127 | 127 | <div class="buttons"> |
|
128 | 128 | ${h.submit('save',_('Save'),class_="btn")} |
|
129 | 129 | </div> |
|
130 | 130 | </div> |
|
131 | 131 | </div> |
|
132 | 132 | ${h.end_form()} |
|
133 | 133 | </div> |
|
134 | 134 | <script> |
|
135 | 135 | $(document).ready(function(){ |
|
136 | 136 | $('#username').focus(); |
|
137 | 137 | |
|
138 | 138 | $('#generate_password').on('click', function(e){ |
|
139 | 139 | var tmpl = "(${_('generated password:')} {0})"; |
|
140 | 140 | var new_passwd = generatePassword(12); |
|
141 | 141 | $('#generate_password_preview').html(tmpl.format(new_passwd)); |
|
142 | 142 | $('#password').val(new_passwd); |
|
143 | 143 | $('#password_confirmation').val(new_passwd); |
|
144 | 144 | }) |
|
145 | 145 | }) |
|
146 | 146 | </script> |
|
147 | 147 | </%def> |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: file was removed |
|
1 | NO CONTENT: file was removed | |
The requested commit or file is too big and content was truncated. Show full diff |
General Comments 0
You need to be logged in to leave comments.
Login now