##// END OF EJS Templates
branch permissions: added logic to define in UI branch permissions....
marcink -
r2975:2d612d18 default
parent child Browse files
Show More

The requested changes are too big and content was truncated. Show full diff

@@ -0,0 +1,45 b''
1 # -*- coding: utf-8 -*-
2
3 # Copyright (C) 2011-2018 RhodeCode GmbH
4 #
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
21 import logging
22
23 from pyramid.view import view_config
24
25 from rhodecode.apps._base import RepoAppView
26 from rhodecode.lib.auth import LoginRequired, HasRepoPermissionAnyDecorator
27
28 log = logging.getLogger(__name__)
29
30
31 class RepoSettingsBranchPermissionsView(RepoAppView):
32
33 def load_default_context(self):
34 c = self._get_local_tmpl_context()
35 return c
36
37 @LoginRequired()
38 @HasRepoPermissionAnyDecorator('repository.admin')
39 @view_config(
40 route_name='edit_repo_perms_branch', request_method='GET',
41 renderer='rhodecode:templates/admin/repos/repo_edit.mako')
42 def branch_permissions(self):
43 c = self.load_default_context()
44 c.active = 'permissions_branch'
45 return self._get_template_context(c)
1 NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
@@ -0,0 +1,46 b''
1 import logging
2
3 from sqlalchemy import *
4 from sqlalchemy.engine import reflection
5 from sqlalchemy.dialects.mysql import LONGTEXT
6
7 from alembic.migration import MigrationContext
8 from alembic.operations import Operations
9
10 from rhodecode.lib.dbmigrate.utils import create_default_permissions, \
11 create_default_object_permission
12 from rhodecode.model import meta
13 from rhodecode.lib.dbmigrate.versions import _reset_base, notify
14
15 log = logging.getLogger(__name__)
16
17
18 def upgrade(migrate_engine):
19 """
20 Upgrade operations go here.
21 Don't create your own engine; bind migrate_engine to your metadata
22 """
23 _reset_base(migrate_engine)
24 from rhodecode.lib.dbmigrate.schema import db_4_13_0_0 as db
25
26 # issue fixups
27 fixups(db, meta.Session)
28
29
30 def downgrade(migrate_engine):
31 meta = MetaData()
32 meta.bind = migrate_engine
33
34
35 def fixups(models, _SESSION):
36 # create default permissions
37 create_default_permissions(_SESSION, models)
38 log.info('created default global permissions definitions')
39 _SESSION().commit()
40
41 # # fix default object permissions
42 # create_default_object_permission(_SESSION, models)
43
44 log.info('created default permission')
45 _SESSION().commit()
46
@@ -0,0 +1,39 b''
1 import logging
2
3 from sqlalchemy import *
4 from sqlalchemy.engine import reflection
5 from sqlalchemy.dialects.mysql import LONGTEXT
6
7 from alembic.migration import MigrationContext
8 from alembic.operations import Operations
9
10 from rhodecode.model import meta
11 from rhodecode.lib.dbmigrate.versions import _reset_base, notify
12
13 log = logging.getLogger(__name__)
14
15
16 def upgrade(migrate_engine):
17 """
18 Upgrade operations go here.
19 Don't create your own engine; bind migrate_engine to your metadata
20 """
21 _reset_base(migrate_engine)
22 from rhodecode.lib.dbmigrate.schema import db_4_13_0_0 as db
23
24 db.UserToRepoBranchPermission.__table__.create()
25 db.UserGroupToRepoBranchPermission.__table__.create()
26
27 # issue fixups
28 fixups(db, meta.Session)
29
30
31 def downgrade(migrate_engine):
32 meta = MetaData()
33 meta.bind = migrate_engine
34
35
36 def fixups(models, _SESSION):
37 pass
38
39
@@ -0,0 +1,43 b''
1 import logging
2
3 from sqlalchemy import *
4
5 from rhodecode.lib.dbmigrate.utils import (
6 create_default_object_permission, create_default_permissions)
7
8 from rhodecode.model import meta
9 from rhodecode.lib.dbmigrate.versions import _reset_base, notify
10
11 log = logging.getLogger(__name__)
12
13
14 def upgrade(migrate_engine):
15 """
16 Upgrade operations go here.
17 Don't create your own engine; bind migrate_engine to your metadata
18 """
19 _reset_base(migrate_engine)
20 from rhodecode.lib.dbmigrate.schema import db_4_13_0_0 as db
21
22 # issue fixups
23 fixups(db, meta.Session)
24
25
26 def downgrade(migrate_engine):
27 meta = MetaData()
28 meta.bind = migrate_engine
29
30
31 def fixups(models, _SESSION):
32 # create default permissions
33 create_default_permissions(_SESSION, models)
34 log.info('created default global permissions definitions')
35 _SESSION().commit()
36
37 # fix default object permissions
38 create_default_object_permission(_SESSION, models)
39
40 log.info('created default permission')
41 _SESSION().commit()
42
43
1 NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
@@ -1,63 +1,63 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2010-2018 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
23 23 RhodeCode, a web based repository management software
24 24 versioning implementation: http://www.python.org/dev/peps/pep-0386/
25 25 """
26 26
27 27 import os
28 28 import sys
29 29 import platform
30 30
31 31 VERSION = tuple(open(os.path.join(
32 32 os.path.dirname(__file__), 'VERSION')).read().split('.'))
33 33
34 34 BACKENDS = {
35 35 'hg': 'Mercurial repository',
36 36 'git': 'Git repository',
37 37 'svn': 'Subversion repository',
38 38 }
39 39
40 40 CELERY_ENABLED = False
41 41 CELERY_EAGER = False
42 42
43 43 # link to config for pyramid
44 44 CONFIG = {}
45 45
46 46 # Populated with the settings dictionary from application init in
47 47 # rhodecode.conf.environment.load_pyramid_environment
48 48 PYRAMID_SETTINGS = {}
49 49
50 50 # Linked module for extensions
51 51 EXTENSIONS = {}
52 52
53 53 __version__ = ('.'.join((str(each) for each in VERSION[:3])))
54 __dbversion__ = 87 # defines current db version for migrations
54 __dbversion__ = 90 # defines current db version for migrations
55 55 __platform__ = platform.system()
56 56 __license__ = 'AGPLv3, and Commercial License'
57 57 __author__ = 'RhodeCode GmbH'
58 58 __url__ = 'https://code.rhodecode.com'
59 59
60 60 is_windows = __platform__ in ['Windows']
61 61 is_unix = not is_windows
62 62 is_test = False
63 63 disable_error_handler = False
@@ -1,439 +1,444 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2016-2018 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._base import ADMIN_PREFIX
23 23
24 24
25 25 def admin_routes(config):
26 26 """
27 27 Admin prefixed routes
28 28 """
29 29
30 30 config.add_route(
31 31 name='admin_audit_logs',
32 32 pattern='/audit_logs')
33 33
34 34 config.add_route(
35 35 name='admin_audit_log_entry',
36 36 pattern='/audit_logs/{audit_log_id}')
37 37
38 38 config.add_route(
39 39 name='pull_requests_global_0', # backward compat
40 40 pattern='/pull_requests/{pull_request_id:\d+}')
41 41 config.add_route(
42 42 name='pull_requests_global_1', # backward compat
43 43 pattern='/pull-requests/{pull_request_id:\d+}')
44 44 config.add_route(
45 45 name='pull_requests_global',
46 46 pattern='/pull-request/{pull_request_id:\d+}')
47 47
48 48 config.add_route(
49 49 name='admin_settings_open_source',
50 50 pattern='/settings/open_source')
51 51 config.add_route(
52 52 name='admin_settings_vcs_svn_generate_cfg',
53 53 pattern='/settings/vcs/svn_generate_cfg')
54 54
55 55 config.add_route(
56 56 name='admin_settings_system',
57 57 pattern='/settings/system')
58 58 config.add_route(
59 59 name='admin_settings_system_update',
60 60 pattern='/settings/system/updates')
61 61
62 62 config.add_route(
63 63 name='admin_settings_exception_tracker',
64 64 pattern='/settings/exceptions')
65 65 config.add_route(
66 66 name='admin_settings_exception_tracker_delete_all',
67 67 pattern='/settings/exceptions/delete')
68 68 config.add_route(
69 69 name='admin_settings_exception_tracker_show',
70 70 pattern='/settings/exceptions/{exception_id}')
71 71 config.add_route(
72 72 name='admin_settings_exception_tracker_delete',
73 73 pattern='/settings/exceptions/{exception_id}/delete')
74 74
75 75 config.add_route(
76 76 name='admin_settings_sessions',
77 77 pattern='/settings/sessions')
78 78 config.add_route(
79 79 name='admin_settings_sessions_cleanup',
80 80 pattern='/settings/sessions/cleanup')
81 81
82 82 config.add_route(
83 83 name='admin_settings_process_management',
84 84 pattern='/settings/process_management')
85 85 config.add_route(
86 86 name='admin_settings_process_management_data',
87 87 pattern='/settings/process_management/data')
88 88 config.add_route(
89 89 name='admin_settings_process_management_signal',
90 90 pattern='/settings/process_management/signal')
91 91 config.add_route(
92 92 name='admin_settings_process_management_master_signal',
93 93 pattern='/settings/process_management/master_signal')
94 94
95 95 # default settings
96 96 config.add_route(
97 97 name='admin_defaults_repositories',
98 98 pattern='/defaults/repositories')
99 99 config.add_route(
100 100 name='admin_defaults_repositories_update',
101 101 pattern='/defaults/repositories/update')
102 102
103 103 # admin settings
104 104
105 105 config.add_route(
106 106 name='admin_settings',
107 107 pattern='/settings')
108 108 config.add_route(
109 109 name='admin_settings_update',
110 110 pattern='/settings/update')
111 111
112 112 config.add_route(
113 113 name='admin_settings_global',
114 114 pattern='/settings/global')
115 115 config.add_route(
116 116 name='admin_settings_global_update',
117 117 pattern='/settings/global/update')
118 118
119 119 config.add_route(
120 120 name='admin_settings_vcs',
121 121 pattern='/settings/vcs')
122 122 config.add_route(
123 123 name='admin_settings_vcs_update',
124 124 pattern='/settings/vcs/update')
125 125 config.add_route(
126 126 name='admin_settings_vcs_svn_pattern_delete',
127 127 pattern='/settings/vcs/svn_pattern_delete')
128 128
129 129 config.add_route(
130 130 name='admin_settings_mapping',
131 131 pattern='/settings/mapping')
132 132 config.add_route(
133 133 name='admin_settings_mapping_update',
134 134 pattern='/settings/mapping/update')
135 135
136 136 config.add_route(
137 137 name='admin_settings_visual',
138 138 pattern='/settings/visual')
139 139 config.add_route(
140 140 name='admin_settings_visual_update',
141 141 pattern='/settings/visual/update')
142 142
143 143
144 144 config.add_route(
145 145 name='admin_settings_issuetracker',
146 146 pattern='/settings/issue-tracker')
147 147 config.add_route(
148 148 name='admin_settings_issuetracker_update',
149 149 pattern='/settings/issue-tracker/update')
150 150 config.add_route(
151 151 name='admin_settings_issuetracker_test',
152 152 pattern='/settings/issue-tracker/test')
153 153 config.add_route(
154 154 name='admin_settings_issuetracker_delete',
155 155 pattern='/settings/issue-tracker/delete')
156 156
157 157 config.add_route(
158 158 name='admin_settings_email',
159 159 pattern='/settings/email')
160 160 config.add_route(
161 161 name='admin_settings_email_update',
162 162 pattern='/settings/email/update')
163 163
164 164 config.add_route(
165 165 name='admin_settings_hooks',
166 166 pattern='/settings/hooks')
167 167 config.add_route(
168 168 name='admin_settings_hooks_update',
169 169 pattern='/settings/hooks/update')
170 170 config.add_route(
171 171 name='admin_settings_hooks_delete',
172 172 pattern='/settings/hooks/delete')
173 173
174 174 config.add_route(
175 175 name='admin_settings_search',
176 176 pattern='/settings/search')
177 177
178 178 config.add_route(
179 179 name='admin_settings_labs',
180 180 pattern='/settings/labs')
181 181 config.add_route(
182 182 name='admin_settings_labs_update',
183 183 pattern='/settings/labs/update')
184 184
185 185 # Automation EE feature
186 186 config.add_route(
187 187 'admin_settings_automation',
188 188 pattern=ADMIN_PREFIX + '/settings/automation')
189 189
190 190 # global permissions
191 191
192 192 config.add_route(
193 193 name='admin_permissions_application',
194 194 pattern='/permissions/application')
195 195 config.add_route(
196 196 name='admin_permissions_application_update',
197 197 pattern='/permissions/application/update')
198 198
199 199 config.add_route(
200 200 name='admin_permissions_global',
201 201 pattern='/permissions/global')
202 202 config.add_route(
203 203 name='admin_permissions_global_update',
204 204 pattern='/permissions/global/update')
205 205
206 206 config.add_route(
207 207 name='admin_permissions_object',
208 208 pattern='/permissions/object')
209 209 config.add_route(
210 210 name='admin_permissions_object_update',
211 211 pattern='/permissions/object/update')
212 212
213 # Branch perms EE feature
214 config.add_route(
215 name='admin_permissions_branch',
216 pattern='/permissions/branch')
217
213 218 config.add_route(
214 219 name='admin_permissions_ips',
215 220 pattern='/permissions/ips')
216 221
217 222 config.add_route(
218 223 name='admin_permissions_overview',
219 224 pattern='/permissions/overview')
220 225
221 226 config.add_route(
222 227 name='admin_permissions_auth_token_access',
223 228 pattern='/permissions/auth_token_access')
224 229
225 230 config.add_route(
226 231 name='admin_permissions_ssh_keys',
227 232 pattern='/permissions/ssh_keys')
228 233 config.add_route(
229 234 name='admin_permissions_ssh_keys_data',
230 235 pattern='/permissions/ssh_keys/data')
231 236 config.add_route(
232 237 name='admin_permissions_ssh_keys_update',
233 238 pattern='/permissions/ssh_keys/update')
234 239
235 240 # users admin
236 241 config.add_route(
237 242 name='users',
238 243 pattern='/users')
239 244
240 245 config.add_route(
241 246 name='users_data',
242 247 pattern='/users_data')
243 248
244 249 config.add_route(
245 250 name='users_create',
246 251 pattern='/users/create')
247 252
248 253 config.add_route(
249 254 name='users_new',
250 255 pattern='/users/new')
251 256
252 257 # user management
253 258 config.add_route(
254 259 name='user_edit',
255 260 pattern='/users/{user_id:\d+}/edit',
256 261 user_route=True)
257 262 config.add_route(
258 263 name='user_edit_advanced',
259 264 pattern='/users/{user_id:\d+}/edit/advanced',
260 265 user_route=True)
261 266 config.add_route(
262 267 name='user_edit_global_perms',
263 268 pattern='/users/{user_id:\d+}/edit/global_permissions',
264 269 user_route=True)
265 270 config.add_route(
266 271 name='user_edit_global_perms_update',
267 272 pattern='/users/{user_id:\d+}/edit/global_permissions/update',
268 273 user_route=True)
269 274 config.add_route(
270 275 name='user_update',
271 276 pattern='/users/{user_id:\d+}/update',
272 277 user_route=True)
273 278 config.add_route(
274 279 name='user_delete',
275 280 pattern='/users/{user_id:\d+}/delete',
276 281 user_route=True)
277 282 config.add_route(
278 283 name='user_force_password_reset',
279 284 pattern='/users/{user_id:\d+}/password_reset',
280 285 user_route=True)
281 286 config.add_route(
282 287 name='user_create_personal_repo_group',
283 288 pattern='/users/{user_id:\d+}/create_repo_group',
284 289 user_route=True)
285 290
286 291 # user auth tokens
287 292 config.add_route(
288 293 name='edit_user_auth_tokens',
289 294 pattern='/users/{user_id:\d+}/edit/auth_tokens',
290 295 user_route=True)
291 296 config.add_route(
292 297 name='edit_user_auth_tokens_add',
293 298 pattern='/users/{user_id:\d+}/edit/auth_tokens/new',
294 299 user_route=True)
295 300 config.add_route(
296 301 name='edit_user_auth_tokens_delete',
297 302 pattern='/users/{user_id:\d+}/edit/auth_tokens/delete',
298 303 user_route=True)
299 304
300 305 # user ssh keys
301 306 config.add_route(
302 307 name='edit_user_ssh_keys',
303 308 pattern='/users/{user_id:\d+}/edit/ssh_keys',
304 309 user_route=True)
305 310 config.add_route(
306 311 name='edit_user_ssh_keys_generate_keypair',
307 312 pattern='/users/{user_id:\d+}/edit/ssh_keys/generate',
308 313 user_route=True)
309 314 config.add_route(
310 315 name='edit_user_ssh_keys_add',
311 316 pattern='/users/{user_id:\d+}/edit/ssh_keys/new',
312 317 user_route=True)
313 318 config.add_route(
314 319 name='edit_user_ssh_keys_delete',
315 320 pattern='/users/{user_id:\d+}/edit/ssh_keys/delete',
316 321 user_route=True)
317 322
318 323 # user emails
319 324 config.add_route(
320 325 name='edit_user_emails',
321 326 pattern='/users/{user_id:\d+}/edit/emails',
322 327 user_route=True)
323 328 config.add_route(
324 329 name='edit_user_emails_add',
325 330 pattern='/users/{user_id:\d+}/edit/emails/new',
326 331 user_route=True)
327 332 config.add_route(
328 333 name='edit_user_emails_delete',
329 334 pattern='/users/{user_id:\d+}/edit/emails/delete',
330 335 user_route=True)
331 336
332 337 # user IPs
333 338 config.add_route(
334 339 name='edit_user_ips',
335 340 pattern='/users/{user_id:\d+}/edit/ips',
336 341 user_route=True)
337 342 config.add_route(
338 343 name='edit_user_ips_add',
339 344 pattern='/users/{user_id:\d+}/edit/ips/new',
340 345 user_route_with_default=True) # enabled for default user too
341 346 config.add_route(
342 347 name='edit_user_ips_delete',
343 348 pattern='/users/{user_id:\d+}/edit/ips/delete',
344 349 user_route_with_default=True) # enabled for default user too
345 350
346 351 # user perms
347 352 config.add_route(
348 353 name='edit_user_perms_summary',
349 354 pattern='/users/{user_id:\d+}/edit/permissions_summary',
350 355 user_route=True)
351 356 config.add_route(
352 357 name='edit_user_perms_summary_json',
353 358 pattern='/users/{user_id:\d+}/edit/permissions_summary/json',
354 359 user_route=True)
355 360
356 361 # user user groups management
357 362 config.add_route(
358 363 name='edit_user_groups_management',
359 364 pattern='/users/{user_id:\d+}/edit/groups_management',
360 365 user_route=True)
361 366
362 367 config.add_route(
363 368 name='edit_user_groups_management_updates',
364 369 pattern='/users/{user_id:\d+}/edit/edit_user_groups_management/updates',
365 370 user_route=True)
366 371
367 372 # user audit logs
368 373 config.add_route(
369 374 name='edit_user_audit_logs',
370 375 pattern='/users/{user_id:\d+}/edit/audit', user_route=True)
371 376
372 377 # user caches
373 378 config.add_route(
374 379 name='edit_user_caches',
375 380 pattern='/users/{user_id:\d+}/edit/caches',
376 381 user_route=True)
377 382 config.add_route(
378 383 name='edit_user_caches_update',
379 384 pattern='/users/{user_id:\d+}/edit/caches/update',
380 385 user_route=True)
381 386
382 387 # user-groups admin
383 388 config.add_route(
384 389 name='user_groups',
385 390 pattern='/user_groups')
386 391
387 392 config.add_route(
388 393 name='user_groups_data',
389 394 pattern='/user_groups_data')
390 395
391 396 config.add_route(
392 397 name='user_groups_new',
393 398 pattern='/user_groups/new')
394 399
395 400 config.add_route(
396 401 name='user_groups_create',
397 402 pattern='/user_groups/create')
398 403
399 404 # repos admin
400 405 config.add_route(
401 406 name='repos',
402 407 pattern='/repos')
403 408
404 409 config.add_route(
405 410 name='repo_new',
406 411 pattern='/repos/new')
407 412
408 413 config.add_route(
409 414 name='repo_create',
410 415 pattern='/repos/create')
411 416
412 417 # repo groups admin
413 418 config.add_route(
414 419 name='repo_groups',
415 420 pattern='/repo_groups')
416 421
417 422 config.add_route(
418 423 name='repo_group_new',
419 424 pattern='/repo_group/new')
420 425
421 426 config.add_route(
422 427 name='repo_group_create',
423 428 pattern='/repo_group/create')
424 429
425 430
426 431 def includeme(config):
427 432 from rhodecode.apps.admin.navigation import includeme as nav_includeme
428 433
429 434 # Create admin navigation registry and add it to the pyramid registry.
430 435 nav_includeme(config)
431 436
432 437 # main admin routes
433 438 config.add_route(name='admin_home', pattern=ADMIN_PREFIX)
434 439 config.include(admin_routes, route_prefix=ADMIN_PREFIX)
435 440
436 441 config.include('.subscribers')
437 442
438 443 # Scan module for configuration decorators.
439 444 config.scan('.views', ignore='.tests')
@@ -1,484 +1,509 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2016-2018 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 re
22 22 import logging
23 23 import formencode
24 24 import formencode.htmlfill
25 25 import datetime
26 26 from pyramid.interfaces import IRoutesMapper
27 27
28 28 from pyramid.view import view_config
29 29 from pyramid.httpexceptions import HTTPFound
30 30 from pyramid.renderers import render
31 31 from pyramid.response import Response
32 32
33 33 from rhodecode.apps._base import BaseAppView, DataGridAppView
34 34 from rhodecode.apps.ssh_support import SshKeyFileChangeEvent
35 35 from rhodecode.events import trigger
36 36
37 37 from rhodecode.lib import helpers as h
38 38 from rhodecode.lib.auth import (
39 39 LoginRequired, HasPermissionAllDecorator, CSRFRequired)
40 40 from rhodecode.lib.utils2 import aslist, safe_unicode
41 41 from rhodecode.model.db import (
42 42 or_, coalesce, User, UserIpMap, UserSshKeys)
43 43 from rhodecode.model.forms import (
44 44 ApplicationPermissionsForm, ObjectPermissionsForm, UserPermissionsForm)
45 45 from rhodecode.model.meta import Session
46 46 from rhodecode.model.permission import PermissionModel
47 47 from rhodecode.model.settings import SettingsModel
48 48
49 49
50 50 log = logging.getLogger(__name__)
51 51
52 52
53 53 class AdminPermissionsView(BaseAppView, DataGridAppView):
54 54 def load_default_context(self):
55 55 c = self._get_local_tmpl_context()
56 56 PermissionModel().set_global_permission_choices(
57 57 c, gettext_translator=self.request.translate)
58 58 return c
59 59
60 60 @LoginRequired()
61 61 @HasPermissionAllDecorator('hg.admin')
62 62 @view_config(
63 63 route_name='admin_permissions_application', request_method='GET',
64 64 renderer='rhodecode:templates/admin/permissions/permissions.mako')
65 65 def permissions_application(self):
66 66 c = self.load_default_context()
67 67 c.active = 'application'
68 68
69 69 c.user = User.get_default_user(refresh=True)
70 70
71 71 app_settings = SettingsModel().get_all_settings()
72 72 defaults = {
73 73 'anonymous': c.user.active,
74 74 'default_register_message': app_settings.get(
75 75 'rhodecode_register_message')
76 76 }
77 77 defaults.update(c.user.get_default_perms())
78 78
79 79 data = render('rhodecode:templates/admin/permissions/permissions.mako',
80 80 self._get_template_context(c), self.request)
81 81 html = formencode.htmlfill.render(
82 82 data,
83 83 defaults=defaults,
84 84 encoding="UTF-8",
85 85 force_defaults=False
86 86 )
87 87 return Response(html)
88 88
89 89 @LoginRequired()
90 90 @HasPermissionAllDecorator('hg.admin')
91 91 @CSRFRequired()
92 92 @view_config(
93 93 route_name='admin_permissions_application_update', request_method='POST',
94 94 renderer='rhodecode:templates/admin/permissions/permissions.mako')
95 95 def permissions_application_update(self):
96 96 _ = self.request.translate
97 97 c = self.load_default_context()
98 98 c.active = 'application'
99 99
100 100 _form = ApplicationPermissionsForm(
101 101 self.request.translate,
102 102 [x[0] for x in c.register_choices],
103 103 [x[0] for x in c.password_reset_choices],
104 104 [x[0] for x in c.extern_activate_choices])()
105 105
106 106 try:
107 107 form_result = _form.to_python(dict(self.request.POST))
108 108 form_result.update({'perm_user_name': User.DEFAULT_USER})
109 109 PermissionModel().update_application_permissions(form_result)
110 110
111 111 settings = [
112 112 ('register_message', 'default_register_message'),
113 113 ]
114 114 for setting, form_key in settings:
115 115 sett = SettingsModel().create_or_update_setting(
116 116 setting, form_result[form_key])
117 117 Session().add(sett)
118 118
119 119 Session().commit()
120 120 h.flash(_('Application permissions updated successfully'),
121 121 category='success')
122 122
123 123 except formencode.Invalid as errors:
124 124 defaults = errors.value
125 125
126 126 data = render(
127 127 'rhodecode:templates/admin/permissions/permissions.mako',
128 128 self._get_template_context(c), self.request)
129 129 html = formencode.htmlfill.render(
130 130 data,
131 131 defaults=defaults,
132 132 errors=errors.error_dict or {},
133 133 prefix_error=False,
134 134 encoding="UTF-8",
135 135 force_defaults=False
136 136 )
137 137 return Response(html)
138 138
139 139 except Exception:
140 140 log.exception("Exception during update of permissions")
141 141 h.flash(_('Error occurred during update of permissions'),
142 142 category='error')
143 143
144 144 raise HTTPFound(h.route_path('admin_permissions_application'))
145 145
146 146 @LoginRequired()
147 147 @HasPermissionAllDecorator('hg.admin')
148 148 @view_config(
149 149 route_name='admin_permissions_object', request_method='GET',
150 150 renderer='rhodecode:templates/admin/permissions/permissions.mako')
151 151 def permissions_objects(self):
152 152 c = self.load_default_context()
153 153 c.active = 'objects'
154 154
155 155 c.user = User.get_default_user(refresh=True)
156 156 defaults = {}
157 157 defaults.update(c.user.get_default_perms())
158 158
159 159 data = render(
160 160 'rhodecode:templates/admin/permissions/permissions.mako',
161 161 self._get_template_context(c), self.request)
162 162 html = formencode.htmlfill.render(
163 163 data,
164 164 defaults=defaults,
165 165 encoding="UTF-8",
166 166 force_defaults=False
167 167 )
168 168 return Response(html)
169 169
170 170 @LoginRequired()
171 171 @HasPermissionAllDecorator('hg.admin')
172 172 @CSRFRequired()
173 173 @view_config(
174 174 route_name='admin_permissions_object_update', request_method='POST',
175 175 renderer='rhodecode:templates/admin/permissions/permissions.mako')
176 176 def permissions_objects_update(self):
177 177 _ = self.request.translate
178 178 c = self.load_default_context()
179 179 c.active = 'objects'
180 180
181 181 _form = ObjectPermissionsForm(
182 182 self.request.translate,
183 183 [x[0] for x in c.repo_perms_choices],
184 184 [x[0] for x in c.group_perms_choices],
185 [x[0] for x in c.user_group_perms_choices])()
185 [x[0] for x in c.user_group_perms_choices],
186 )()
186 187
187 188 try:
188 189 form_result = _form.to_python(dict(self.request.POST))
189 190 form_result.update({'perm_user_name': User.DEFAULT_USER})
190 191 PermissionModel().update_object_permissions(form_result)
191 192
192 193 Session().commit()
193 194 h.flash(_('Object permissions updated successfully'),
194 195 category='success')
195 196
196 197 except formencode.Invalid as errors:
197 198 defaults = errors.value
198 199
199 200 data = render(
200 201 'rhodecode:templates/admin/permissions/permissions.mako',
201 202 self._get_template_context(c), self.request)
202 203 html = formencode.htmlfill.render(
203 204 data,
204 205 defaults=defaults,
205 206 errors=errors.error_dict or {},
206 207 prefix_error=False,
207 208 encoding="UTF-8",
208 209 force_defaults=False
209 210 )
210 211 return Response(html)
211 212 except Exception:
212 213 log.exception("Exception during update of permissions")
213 214 h.flash(_('Error occurred during update of permissions'),
214 215 category='error')
215 216
216 217 raise HTTPFound(h.route_path('admin_permissions_object'))
217 218
218 219 @LoginRequired()
219 220 @HasPermissionAllDecorator('hg.admin')
220 221 @view_config(
222 route_name='admin_permissions_branch', request_method='GET',
223 renderer='rhodecode:templates/admin/permissions/permissions.mako')
224 def permissions_branch(self):
225 c = self.load_default_context()
226 c.active = 'branch'
227
228 c.user = User.get_default_user(refresh=True)
229 defaults = {}
230 defaults.update(c.user.get_default_perms())
231
232 data = render(
233 'rhodecode:templates/admin/permissions/permissions.mako',
234 self._get_template_context(c), self.request)
235 html = formencode.htmlfill.render(
236 data,
237 defaults=defaults,
238 encoding="UTF-8",
239 force_defaults=False
240 )
241 return Response(html)
242
243 @LoginRequired()
244 @HasPermissionAllDecorator('hg.admin')
245 @view_config(
221 246 route_name='admin_permissions_global', request_method='GET',
222 247 renderer='rhodecode:templates/admin/permissions/permissions.mako')
223 248 def permissions_global(self):
224 249 c = self.load_default_context()
225 250 c.active = 'global'
226 251
227 252 c.user = User.get_default_user(refresh=True)
228 253 defaults = {}
229 254 defaults.update(c.user.get_default_perms())
230 255
231 256 data = render(
232 257 'rhodecode:templates/admin/permissions/permissions.mako',
233 258 self._get_template_context(c), self.request)
234 259 html = formencode.htmlfill.render(
235 260 data,
236 261 defaults=defaults,
237 262 encoding="UTF-8",
238 263 force_defaults=False
239 264 )
240 265 return Response(html)
241 266
242 267 @LoginRequired()
243 268 @HasPermissionAllDecorator('hg.admin')
244 269 @CSRFRequired()
245 270 @view_config(
246 271 route_name='admin_permissions_global_update', request_method='POST',
247 272 renderer='rhodecode:templates/admin/permissions/permissions.mako')
248 273 def permissions_global_update(self):
249 274 _ = self.request.translate
250 275 c = self.load_default_context()
251 276 c.active = 'global'
252 277
253 278 _form = UserPermissionsForm(
254 279 self.request.translate,
255 280 [x[0] for x in c.repo_create_choices],
256 281 [x[0] for x in c.repo_create_on_write_choices],
257 282 [x[0] for x in c.repo_group_create_choices],
258 283 [x[0] for x in c.user_group_create_choices],
259 284 [x[0] for x in c.fork_choices],
260 285 [x[0] for x in c.inherit_default_permission_choices])()
261 286
262 287 try:
263 288 form_result = _form.to_python(dict(self.request.POST))
264 289 form_result.update({'perm_user_name': User.DEFAULT_USER})
265 290 PermissionModel().update_user_permissions(form_result)
266 291
267 292 Session().commit()
268 293 h.flash(_('Global permissions updated successfully'),
269 294 category='success')
270 295
271 296 except formencode.Invalid as errors:
272 297 defaults = errors.value
273 298
274 299 data = render(
275 300 'rhodecode:templates/admin/permissions/permissions.mako',
276 301 self._get_template_context(c), self.request)
277 302 html = formencode.htmlfill.render(
278 303 data,
279 304 defaults=defaults,
280 305 errors=errors.error_dict or {},
281 306 prefix_error=False,
282 307 encoding="UTF-8",
283 308 force_defaults=False
284 309 )
285 310 return Response(html)
286 311 except Exception:
287 312 log.exception("Exception during update of permissions")
288 313 h.flash(_('Error occurred during update of permissions'),
289 314 category='error')
290 315
291 316 raise HTTPFound(h.route_path('admin_permissions_global'))
292 317
293 318 @LoginRequired()
294 319 @HasPermissionAllDecorator('hg.admin')
295 320 @view_config(
296 321 route_name='admin_permissions_ips', request_method='GET',
297 322 renderer='rhodecode:templates/admin/permissions/permissions.mako')
298 323 def permissions_ips(self):
299 324 c = self.load_default_context()
300 325 c.active = 'ips'
301 326
302 327 c.user = User.get_default_user(refresh=True)
303 328 c.user_ip_map = (
304 329 UserIpMap.query().filter(UserIpMap.user == c.user).all())
305 330
306 331 return self._get_template_context(c)
307 332
308 333 @LoginRequired()
309 334 @HasPermissionAllDecorator('hg.admin')
310 335 @view_config(
311 336 route_name='admin_permissions_overview', request_method='GET',
312 337 renderer='rhodecode:templates/admin/permissions/permissions.mako')
313 338 def permissions_overview(self):
314 339 c = self.load_default_context()
315 340 c.active = 'perms'
316 341
317 342 c.user = User.get_default_user(refresh=True)
318 343 c.perm_user = c.user.AuthUser()
319 344 return self._get_template_context(c)
320 345
321 346 @LoginRequired()
322 347 @HasPermissionAllDecorator('hg.admin')
323 348 @view_config(
324 349 route_name='admin_permissions_auth_token_access', request_method='GET',
325 350 renderer='rhodecode:templates/admin/permissions/permissions.mako')
326 351 def auth_token_access(self):
327 352 from rhodecode import CONFIG
328 353
329 354 c = self.load_default_context()
330 355 c.active = 'auth_token_access'
331 356
332 357 c.user = User.get_default_user(refresh=True)
333 358 c.perm_user = c.user.AuthUser()
334 359
335 360 mapper = self.request.registry.queryUtility(IRoutesMapper)
336 361 c.view_data = []
337 362
338 363 _argument_prog = re.compile('\{(.*?)\}|:\((.*)\)')
339 364 introspector = self.request.registry.introspector
340 365
341 366 view_intr = {}
342 367 for view_data in introspector.get_category('views'):
343 368 intr = view_data['introspectable']
344 369
345 370 if 'route_name' in intr and intr['attr']:
346 371 view_intr[intr['route_name']] = '{}:{}'.format(
347 372 str(intr['derived_callable'].func_name), intr['attr']
348 373 )
349 374
350 375 c.whitelist_key = 'api_access_controllers_whitelist'
351 376 c.whitelist_file = CONFIG.get('__file__')
352 377 whitelist_views = aslist(
353 378 CONFIG.get(c.whitelist_key), sep=',')
354 379
355 380 for route_info in mapper.get_routes():
356 381 if not route_info.name.startswith('__'):
357 382 routepath = route_info.pattern
358 383
359 384 def replace(matchobj):
360 385 if matchobj.group(1):
361 386 return "{%s}" % matchobj.group(1).split(':')[0]
362 387 else:
363 388 return "{%s}" % matchobj.group(2)
364 389
365 390 routepath = _argument_prog.sub(replace, routepath)
366 391
367 392 if not routepath.startswith('/'):
368 393 routepath = '/' + routepath
369 394
370 395 view_fqn = view_intr.get(route_info.name, 'NOT AVAILABLE')
371 396 active = view_fqn in whitelist_views
372 397 c.view_data.append((route_info.name, view_fqn, routepath, active))
373 398
374 399 c.whitelist_views = whitelist_views
375 400 return self._get_template_context(c)
376 401
377 402 def ssh_enabled(self):
378 403 return self.request.registry.settings.get(
379 404 'ssh.generate_authorized_keyfile')
380 405
381 406 @LoginRequired()
382 407 @HasPermissionAllDecorator('hg.admin')
383 408 @view_config(
384 409 route_name='admin_permissions_ssh_keys', request_method='GET',
385 410 renderer='rhodecode:templates/admin/permissions/permissions.mako')
386 411 def ssh_keys(self):
387 412 c = self.load_default_context()
388 413 c.active = 'ssh_keys'
389 414 c.ssh_enabled = self.ssh_enabled()
390 415 return self._get_template_context(c)
391 416
392 417 @LoginRequired()
393 418 @HasPermissionAllDecorator('hg.admin')
394 419 @view_config(
395 420 route_name='admin_permissions_ssh_keys_data', request_method='GET',
396 421 renderer='json_ext', xhr=True)
397 422 def ssh_keys_data(self):
398 423 _ = self.request.translate
399 424 self.load_default_context()
400 425 column_map = {
401 426 'fingerprint': 'ssh_key_fingerprint',
402 427 'username': User.username
403 428 }
404 429 draw, start, limit = self._extract_chunk(self.request)
405 430 search_q, order_by, order_dir = self._extract_ordering(
406 431 self.request, column_map=column_map)
407 432
408 433 ssh_keys_data_total_count = UserSshKeys.query()\
409 434 .count()
410 435
411 436 # json generate
412 437 base_q = UserSshKeys.query().join(UserSshKeys.user)
413 438
414 439 if search_q:
415 440 like_expression = u'%{}%'.format(safe_unicode(search_q))
416 441 base_q = base_q.filter(or_(
417 442 User.username.ilike(like_expression),
418 443 UserSshKeys.ssh_key_fingerprint.ilike(like_expression),
419 444 ))
420 445
421 446 users_data_total_filtered_count = base_q.count()
422 447
423 448 sort_col = self._get_order_col(order_by, UserSshKeys)
424 449 if sort_col:
425 450 if order_dir == 'asc':
426 451 # handle null values properly to order by NULL last
427 452 if order_by in ['created_on']:
428 453 sort_col = coalesce(sort_col, datetime.date.max)
429 454 sort_col = sort_col.asc()
430 455 else:
431 456 # handle null values properly to order by NULL last
432 457 if order_by in ['created_on']:
433 458 sort_col = coalesce(sort_col, datetime.date.min)
434 459 sort_col = sort_col.desc()
435 460
436 461 base_q = base_q.order_by(sort_col)
437 462 base_q = base_q.offset(start).limit(limit)
438 463
439 464 ssh_keys = base_q.all()
440 465
441 466 ssh_keys_data = []
442 467 for ssh_key in ssh_keys:
443 468 ssh_keys_data.append({
444 469 "username": h.gravatar_with_user(self.request, ssh_key.user.username),
445 470 "fingerprint": ssh_key.ssh_key_fingerprint,
446 471 "description": ssh_key.description,
447 472 "created_on": h.format_date(ssh_key.created_on),
448 473 "accessed_on": h.format_date(ssh_key.accessed_on),
449 474 "action": h.link_to(
450 475 _('Edit'), h.route_path('edit_user_ssh_keys',
451 476 user_id=ssh_key.user.user_id))
452 477 })
453 478
454 479 data = ({
455 480 'draw': draw,
456 481 'data': ssh_keys_data,
457 482 'recordsTotal': ssh_keys_data_total_count,
458 483 'recordsFiltered': users_data_total_filtered_count,
459 484 })
460 485
461 486 return data
462 487
463 488 @LoginRequired()
464 489 @HasPermissionAllDecorator('hg.admin')
465 490 @CSRFRequired()
466 491 @view_config(
467 492 route_name='admin_permissions_ssh_keys_update', request_method='POST',
468 493 renderer='rhodecode:templates/admin/permissions/permissions.mako')
469 494 def ssh_keys_update(self):
470 495 _ = self.request.translate
471 496 self.load_default_context()
472 497
473 498 ssh_enabled = self.ssh_enabled()
474 499 key_file = self.request.registry.settings.get(
475 500 'ssh.authorized_keys_file_path')
476 501 if ssh_enabled:
477 502 trigger(SshKeyFileChangeEvent(), self.request.registry)
478 503 h.flash(_('Updated SSH keys file: {}').format(key_file),
479 504 category='success')
480 505 else:
481 506 h.flash(_('SSH key support is disabled in .ini file'),
482 507 category='warning')
483 508
484 509 raise HTTPFound(h.route_path('admin_permissions_ssh_keys'))
@@ -1,467 +1,476 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2016-2018 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 from rhodecode.apps._base import add_route_with_slash
21 21
22 22
23 23 def includeme(config):
24 24
25 25 # repo creating checks, special cases that aren't repo routes
26 26 config.add_route(
27 27 name='repo_creating',
28 28 pattern='/{repo_name:.*?[^/]}/repo_creating')
29 29
30 30 config.add_route(
31 31 name='repo_creating_check',
32 32 pattern='/{repo_name:.*?[^/]}/repo_creating_check')
33 33
34 34 # Summary
35 35 # NOTE(marcink): one additional route is defined in very bottom, catch
36 36 # all pattern
37 37 config.add_route(
38 38 name='repo_summary_explicit',
39 39 pattern='/{repo_name:.*?[^/]}/summary', repo_route=True)
40 40 config.add_route(
41 41 name='repo_summary_commits',
42 42 pattern='/{repo_name:.*?[^/]}/summary-commits', repo_route=True)
43 43
44 44 # Commits
45 45 config.add_route(
46 46 name='repo_commit',
47 47 pattern='/{repo_name:.*?[^/]}/changeset/{commit_id}', repo_route=True)
48 48
49 49 config.add_route(
50 50 name='repo_commit_children',
51 51 pattern='/{repo_name:.*?[^/]}/changeset_children/{commit_id}', repo_route=True)
52 52
53 53 config.add_route(
54 54 name='repo_commit_parents',
55 55 pattern='/{repo_name:.*?[^/]}/changeset_parents/{commit_id}', repo_route=True)
56 56
57 57 config.add_route(
58 58 name='repo_commit_raw',
59 59 pattern='/{repo_name:.*?[^/]}/changeset-diff/{commit_id}', repo_route=True)
60 60
61 61 config.add_route(
62 62 name='repo_commit_patch',
63 63 pattern='/{repo_name:.*?[^/]}/changeset-patch/{commit_id}', repo_route=True)
64 64
65 65 config.add_route(
66 66 name='repo_commit_download',
67 67 pattern='/{repo_name:.*?[^/]}/changeset-download/{commit_id}', repo_route=True)
68 68
69 69 config.add_route(
70 70 name='repo_commit_data',
71 71 pattern='/{repo_name:.*?[^/]}/changeset-data/{commit_id}', repo_route=True)
72 72
73 73 config.add_route(
74 74 name='repo_commit_comment_create',
75 75 pattern='/{repo_name:.*?[^/]}/changeset/{commit_id}/comment/create', repo_route=True)
76 76
77 77 config.add_route(
78 78 name='repo_commit_comment_preview',
79 79 pattern='/{repo_name:.*?[^/]}/changeset/{commit_id}/comment/preview', repo_route=True)
80 80
81 81 config.add_route(
82 82 name='repo_commit_comment_delete',
83 83 pattern='/{repo_name:.*?[^/]}/changeset/{commit_id}/comment/{comment_id}/delete', repo_route=True)
84 84
85 85 # still working url for backward compat.
86 86 config.add_route(
87 87 name='repo_commit_raw_deprecated',
88 88 pattern='/{repo_name:.*?[^/]}/raw-changeset/{commit_id}', repo_route=True)
89 89
90 90 # Files
91 91 config.add_route(
92 92 name='repo_archivefile',
93 93 pattern='/{repo_name:.*?[^/]}/archive/{fname}', repo_route=True)
94 94
95 95 config.add_route(
96 96 name='repo_files_diff',
97 97 pattern='/{repo_name:.*?[^/]}/diff/{f_path:.*}', repo_route=True)
98 98 config.add_route( # legacy route to make old links work
99 99 name='repo_files_diff_2way_redirect',
100 100 pattern='/{repo_name:.*?[^/]}/diff-2way/{f_path:.*}', repo_route=True)
101 101
102 102 config.add_route(
103 103 name='repo_files',
104 104 pattern='/{repo_name:.*?[^/]}/files/{commit_id}/{f_path:.*}', repo_route=True)
105 105 config.add_route(
106 106 name='repo_files:default_path',
107 107 pattern='/{repo_name:.*?[^/]}/files/{commit_id}/', repo_route=True)
108 108 config.add_route(
109 109 name='repo_files:default_commit',
110 110 pattern='/{repo_name:.*?[^/]}/files', repo_route=True)
111 111
112 112 config.add_route(
113 113 name='repo_files:rendered',
114 114 pattern='/{repo_name:.*?[^/]}/render/{commit_id}/{f_path:.*}', repo_route=True)
115 115
116 116 config.add_route(
117 117 name='repo_files:annotated',
118 118 pattern='/{repo_name:.*?[^/]}/annotate/{commit_id}/{f_path:.*}', repo_route=True)
119 119 config.add_route(
120 120 name='repo_files:annotated_previous',
121 121 pattern='/{repo_name:.*?[^/]}/annotate-previous/{commit_id}/{f_path:.*}', repo_route=True)
122 122
123 123 config.add_route(
124 124 name='repo_nodetree_full',
125 125 pattern='/{repo_name:.*?[^/]}/nodetree_full/{commit_id}/{f_path:.*}', repo_route=True)
126 126 config.add_route(
127 127 name='repo_nodetree_full:default_path',
128 128 pattern='/{repo_name:.*?[^/]}/nodetree_full/{commit_id}/', repo_route=True)
129 129
130 130 config.add_route(
131 131 name='repo_files_nodelist',
132 132 pattern='/{repo_name:.*?[^/]}/nodelist/{commit_id}/{f_path:.*}', repo_route=True)
133 133
134 134 config.add_route(
135 135 name='repo_file_raw',
136 136 pattern='/{repo_name:.*?[^/]}/raw/{commit_id}/{f_path:.*}', repo_route=True)
137 137
138 138 config.add_route(
139 139 name='repo_file_download',
140 140 pattern='/{repo_name:.*?[^/]}/download/{commit_id}/{f_path:.*}', repo_route=True)
141 141 config.add_route( # backward compat to keep old links working
142 142 name='repo_file_download:legacy',
143 143 pattern='/{repo_name:.*?[^/]}/rawfile/{commit_id}/{f_path:.*}',
144 144 repo_route=True)
145 145
146 146 config.add_route(
147 147 name='repo_file_history',
148 148 pattern='/{repo_name:.*?[^/]}/history/{commit_id}/{f_path:.*}', repo_route=True)
149 149
150 150 config.add_route(
151 151 name='repo_file_authors',
152 152 pattern='/{repo_name:.*?[^/]}/authors/{commit_id}/{f_path:.*}', repo_route=True)
153 153
154 154 config.add_route(
155 155 name='repo_files_remove_file',
156 156 pattern='/{repo_name:.*?[^/]}/remove_file/{commit_id}/{f_path:.*}',
157 157 repo_route=True)
158 158 config.add_route(
159 159 name='repo_files_delete_file',
160 160 pattern='/{repo_name:.*?[^/]}/delete_file/{commit_id}/{f_path:.*}',
161 161 repo_route=True)
162 162 config.add_route(
163 163 name='repo_files_edit_file',
164 164 pattern='/{repo_name:.*?[^/]}/edit_file/{commit_id}/{f_path:.*}',
165 165 repo_route=True)
166 166 config.add_route(
167 167 name='repo_files_update_file',
168 168 pattern='/{repo_name:.*?[^/]}/update_file/{commit_id}/{f_path:.*}',
169 169 repo_route=True)
170 170 config.add_route(
171 171 name='repo_files_add_file',
172 172 pattern='/{repo_name:.*?[^/]}/add_file/{commit_id}/{f_path:.*}',
173 173 repo_route=True)
174 174 config.add_route(
175 175 name='repo_files_create_file',
176 176 pattern='/{repo_name:.*?[^/]}/create_file/{commit_id}/{f_path:.*}',
177 177 repo_route=True)
178 178
179 179 # Refs data
180 180 config.add_route(
181 181 name='repo_refs_data',
182 182 pattern='/{repo_name:.*?[^/]}/refs-data', repo_route=True)
183 183
184 184 config.add_route(
185 185 name='repo_refs_changelog_data',
186 186 pattern='/{repo_name:.*?[^/]}/refs-data-changelog', repo_route=True)
187 187
188 188 config.add_route(
189 189 name='repo_stats',
190 190 pattern='/{repo_name:.*?[^/]}/repo_stats/{commit_id}', repo_route=True)
191 191
192 192 # Changelog
193 193 config.add_route(
194 194 name='repo_changelog',
195 195 pattern='/{repo_name:.*?[^/]}/changelog', repo_route=True)
196 196 config.add_route(
197 197 name='repo_changelog_file',
198 198 pattern='/{repo_name:.*?[^/]}/changelog/{commit_id}/{f_path:.*}', repo_route=True)
199 199 config.add_route(
200 200 name='repo_changelog_elements',
201 201 pattern='/{repo_name:.*?[^/]}/changelog_elements', repo_route=True)
202 202 config.add_route(
203 203 name='repo_changelog_elements_file',
204 204 pattern='/{repo_name:.*?[^/]}/changelog_elements/{commit_id}/{f_path:.*}', repo_route=True)
205 205
206 206 # Compare
207 207 config.add_route(
208 208 name='repo_compare_select',
209 209 pattern='/{repo_name:.*?[^/]}/compare', repo_route=True)
210 210
211 211 config.add_route(
212 212 name='repo_compare',
213 213 pattern='/{repo_name:.*?[^/]}/compare/{source_ref_type}@{source_ref:.*?}...{target_ref_type}@{target_ref:.*?}', repo_route=True)
214 214
215 215 # Tags
216 216 config.add_route(
217 217 name='tags_home',
218 218 pattern='/{repo_name:.*?[^/]}/tags', repo_route=True)
219 219
220 220 # Branches
221 221 config.add_route(
222 222 name='branches_home',
223 223 pattern='/{repo_name:.*?[^/]}/branches', repo_route=True)
224 224
225 225 # Bookmarks
226 226 config.add_route(
227 227 name='bookmarks_home',
228 228 pattern='/{repo_name:.*?[^/]}/bookmarks', repo_route=True)
229 229
230 230 # Forks
231 231 config.add_route(
232 232 name='repo_fork_new',
233 233 pattern='/{repo_name:.*?[^/]}/fork', repo_route=True,
234 234 repo_accepted_types=['hg', 'git'])
235 235
236 236 config.add_route(
237 237 name='repo_fork_create',
238 238 pattern='/{repo_name:.*?[^/]}/fork/create', repo_route=True,
239 239 repo_accepted_types=['hg', 'git'])
240 240
241 241 config.add_route(
242 242 name='repo_forks_show_all',
243 243 pattern='/{repo_name:.*?[^/]}/forks', repo_route=True,
244 244 repo_accepted_types=['hg', 'git'])
245 245 config.add_route(
246 246 name='repo_forks_data',
247 247 pattern='/{repo_name:.*?[^/]}/forks/data', repo_route=True,
248 248 repo_accepted_types=['hg', 'git'])
249 249
250 250 # Pull Requests
251 251 config.add_route(
252 252 name='pullrequest_show',
253 253 pattern='/{repo_name:.*?[^/]}/pull-request/{pull_request_id:\d+}',
254 254 repo_route=True)
255 255
256 256 config.add_route(
257 257 name='pullrequest_show_all',
258 258 pattern='/{repo_name:.*?[^/]}/pull-request',
259 259 repo_route=True, repo_accepted_types=['hg', 'git'])
260 260
261 261 config.add_route(
262 262 name='pullrequest_show_all_data',
263 263 pattern='/{repo_name:.*?[^/]}/pull-request-data',
264 264 repo_route=True, repo_accepted_types=['hg', 'git'])
265 265
266 266 config.add_route(
267 267 name='pullrequest_repo_refs',
268 268 pattern='/{repo_name:.*?[^/]}/pull-request/refs/{target_repo_name:.*?[^/]}',
269 269 repo_route=True)
270 270
271 271 config.add_route(
272 272 name='pullrequest_repo_destinations',
273 273 pattern='/{repo_name:.*?[^/]}/pull-request/repo-destinations',
274 274 repo_route=True)
275 275
276 276 config.add_route(
277 277 name='pullrequest_new',
278 278 pattern='/{repo_name:.*?[^/]}/pull-request/new',
279 279 repo_route=True, repo_accepted_types=['hg', 'git'])
280 280
281 281 config.add_route(
282 282 name='pullrequest_create',
283 283 pattern='/{repo_name:.*?[^/]}/pull-request/create',
284 284 repo_route=True, repo_accepted_types=['hg', 'git'])
285 285
286 286 config.add_route(
287 287 name='pullrequest_update',
288 288 pattern='/{repo_name:.*?[^/]}/pull-request/{pull_request_id:\d+}/update',
289 289 repo_route=True)
290 290
291 291 config.add_route(
292 292 name='pullrequest_merge',
293 293 pattern='/{repo_name:.*?[^/]}/pull-request/{pull_request_id:\d+}/merge',
294 294 repo_route=True)
295 295
296 296 config.add_route(
297 297 name='pullrequest_delete',
298 298 pattern='/{repo_name:.*?[^/]}/pull-request/{pull_request_id:\d+}/delete',
299 299 repo_route=True)
300 300
301 301 config.add_route(
302 302 name='pullrequest_comment_create',
303 303 pattern='/{repo_name:.*?[^/]}/pull-request/{pull_request_id:\d+}/comment',
304 304 repo_route=True)
305 305
306 306 config.add_route(
307 307 name='pullrequest_comment_delete',
308 308 pattern='/{repo_name:.*?[^/]}/pull-request/{pull_request_id:\d+}/comment/{comment_id}/delete',
309 309 repo_route=True, repo_accepted_types=['hg', 'git'])
310 310
311 311 # Settings
312 312 config.add_route(
313 313 name='edit_repo',
314 314 pattern='/{repo_name:.*?[^/]}/settings', repo_route=True)
315 315 # update is POST on edit_repo
316 316
317 317 # Settings advanced
318 318 config.add_route(
319 319 name='edit_repo_advanced',
320 320 pattern='/{repo_name:.*?[^/]}/settings/advanced', repo_route=True)
321 321 config.add_route(
322 322 name='edit_repo_advanced_delete',
323 323 pattern='/{repo_name:.*?[^/]}/settings/advanced/delete', repo_route=True)
324 324 config.add_route(
325 325 name='edit_repo_advanced_locking',
326 326 pattern='/{repo_name:.*?[^/]}/settings/advanced/locking', repo_route=True)
327 327 config.add_route(
328 328 name='edit_repo_advanced_journal',
329 329 pattern='/{repo_name:.*?[^/]}/settings/advanced/journal', repo_route=True)
330 330 config.add_route(
331 331 name='edit_repo_advanced_fork',
332 332 pattern='/{repo_name:.*?[^/]}/settings/advanced/fork', repo_route=True)
333 333
334 334 config.add_route(
335 335 name='edit_repo_advanced_hooks',
336 336 pattern='/{repo_name:.*?[^/]}/settings/advanced/hooks', repo_route=True)
337 337
338 338 # Caches
339 339 config.add_route(
340 340 name='edit_repo_caches',
341 341 pattern='/{repo_name:.*?[^/]}/settings/caches', repo_route=True)
342 342
343 343 # Permissions
344 344 config.add_route(
345 345 name='edit_repo_perms',
346 346 pattern='/{repo_name:.*?[^/]}/settings/permissions', repo_route=True)
347 347
348 # Permissions Branch (EE feature)
349 config.add_route(
350 name='edit_repo_perms_branch',
351 pattern='/{repo_name:.*?[^/]}/settings/branch_permissions', repo_route=True)
352 config.add_route(
353 name='edit_repo_perms_branch_delete',
354 pattern='/{repo_name:.*?[^/]}/settings/branch_permissions/{rule_id}/delete',
355 repo_route=True)
356
348 357 # Maintenance
349 358 config.add_route(
350 359 name='edit_repo_maintenance',
351 360 pattern='/{repo_name:.*?[^/]}/settings/maintenance', repo_route=True)
352 361
353 362 config.add_route(
354 363 name='edit_repo_maintenance_execute',
355 364 pattern='/{repo_name:.*?[^/]}/settings/maintenance/execute', repo_route=True)
356 365
357 366 # Fields
358 367 config.add_route(
359 368 name='edit_repo_fields',
360 369 pattern='/{repo_name:.*?[^/]}/settings/fields', repo_route=True)
361 370 config.add_route(
362 371 name='edit_repo_fields_create',
363 372 pattern='/{repo_name:.*?[^/]}/settings/fields/create', repo_route=True)
364 373 config.add_route(
365 374 name='edit_repo_fields_delete',
366 375 pattern='/{repo_name:.*?[^/]}/settings/fields/{field_id}/delete', repo_route=True)
367 376
368 377 # Locking
369 378 config.add_route(
370 379 name='repo_edit_toggle_locking',
371 380 pattern='/{repo_name:.*?[^/]}/settings/toggle_locking', repo_route=True)
372 381
373 382 # Remote
374 383 config.add_route(
375 384 name='edit_repo_remote',
376 385 pattern='/{repo_name:.*?[^/]}/settings/remote', repo_route=True)
377 386 config.add_route(
378 387 name='edit_repo_remote_pull',
379 388 pattern='/{repo_name:.*?[^/]}/settings/remote/pull', repo_route=True)
380 389 config.add_route(
381 390 name='edit_repo_remote_push',
382 391 pattern='/{repo_name:.*?[^/]}/settings/remote/push', repo_route=True)
383 392
384 393 # Statistics
385 394 config.add_route(
386 395 name='edit_repo_statistics',
387 396 pattern='/{repo_name:.*?[^/]}/settings/statistics', repo_route=True)
388 397 config.add_route(
389 398 name='edit_repo_statistics_reset',
390 399 pattern='/{repo_name:.*?[^/]}/settings/statistics/update', repo_route=True)
391 400
392 401 # Issue trackers
393 402 config.add_route(
394 403 name='edit_repo_issuetracker',
395 404 pattern='/{repo_name:.*?[^/]}/settings/issue_trackers', repo_route=True)
396 405 config.add_route(
397 406 name='edit_repo_issuetracker_test',
398 407 pattern='/{repo_name:.*?[^/]}/settings/issue_trackers/test', repo_route=True)
399 408 config.add_route(
400 409 name='edit_repo_issuetracker_delete',
401 410 pattern='/{repo_name:.*?[^/]}/settings/issue_trackers/delete', repo_route=True)
402 411 config.add_route(
403 412 name='edit_repo_issuetracker_update',
404 413 pattern='/{repo_name:.*?[^/]}/settings/issue_trackers/update', repo_route=True)
405 414
406 415 # VCS Settings
407 416 config.add_route(
408 417 name='edit_repo_vcs',
409 418 pattern='/{repo_name:.*?[^/]}/settings/vcs', repo_route=True)
410 419 config.add_route(
411 420 name='edit_repo_vcs_update',
412 421 pattern='/{repo_name:.*?[^/]}/settings/vcs/update', repo_route=True)
413 422
414 423 # svn pattern
415 424 config.add_route(
416 425 name='edit_repo_vcs_svn_pattern_delete',
417 426 pattern='/{repo_name:.*?[^/]}/settings/vcs/svn_pattern/delete', repo_route=True)
418 427
419 428 # Repo Review Rules (EE feature)
420 429 config.add_route(
421 430 name='repo_reviewers',
422 431 pattern='/{repo_name:.*?[^/]}/settings/review/rules', repo_route=True)
423 432
424 433 config.add_route(
425 434 name='repo_default_reviewers_data',
426 435 pattern='/{repo_name:.*?[^/]}/settings/review/default-reviewers', repo_route=True)
427 436
428 437 # Repo Automation (EE feature)
429 438 config.add_route(
430 439 name='repo_automation',
431 440 pattern='/{repo_name:.*?[^/]}/settings/automation', repo_route=True)
432 441
433 442 # Strip
434 443 config.add_route(
435 444 name='edit_repo_strip',
436 445 pattern='/{repo_name:.*?[^/]}/settings/strip', repo_route=True)
437 446
438 447 config.add_route(
439 448 name='strip_check',
440 449 pattern='/{repo_name:.*?[^/]}/settings/strip_check', repo_route=True)
441 450
442 451 config.add_route(
443 452 name='strip_execute',
444 453 pattern='/{repo_name:.*?[^/]}/settings/strip_execute', repo_route=True)
445 454
446 455 # Audit logs
447 456 config.add_route(
448 457 name='edit_repo_audit_logs',
449 458 pattern='/{repo_name:.*?[^/]}/settings/audit_logs', repo_route=True)
450 459
451 460 # ATOM/RSS Feed
452 461 config.add_route(
453 462 name='rss_feed_home',
454 463 pattern='/{repo_name:.*?[^/]}/feed/rss', repo_route=True)
455 464
456 465 config.add_route(
457 466 name='atom_feed_home',
458 467 pattern='/{repo_name:.*?[^/]}/feed/atom', repo_route=True)
459 468
460 469 # NOTE(marcink): needs to be at the end for catch-all
461 470 add_route_with_slash(
462 471 config,
463 472 name='repo_summary',
464 473 pattern='/{repo_name:.*?[^/]}', repo_route=True)
465 474
466 475 # Scan module for configuration decorators.
467 476 config.scan('.views', ignore='.tests')
@@ -1,2195 +1,2295 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2010-2018 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 time
27 27 import inspect
28 28 import collections
29 29 import fnmatch
30 30 import hashlib
31 31 import itertools
32 32 import logging
33 33 import random
34 34 import traceback
35 35 from functools import wraps
36 36
37 37 import ipaddress
38 38
39 39 from pyramid.httpexceptions import HTTPForbidden, HTTPFound, HTTPNotFound
40 40 from sqlalchemy.orm.exc import ObjectDeletedError
41 41 from sqlalchemy.orm import joinedload
42 42 from zope.cachedescriptors.property import Lazy as LazyProperty
43 43
44 44 import rhodecode
45 45 from rhodecode.model import meta
46 46 from rhodecode.model.meta import Session
47 47 from rhodecode.model.user import UserModel
48 48 from rhodecode.model.db import (
49 49 User, Repository, Permission, UserToPerm, UserGroupToPerm, UserGroupMember,
50 50 UserIpMap, UserApiKeys, RepoGroup, UserGroup)
51 51 from rhodecode.lib import rc_cache
52 52 from rhodecode.lib.utils2 import safe_unicode, aslist, safe_str, md5, safe_int, sha1
53 53 from rhodecode.lib.utils import (
54 54 get_repo_slug, get_repo_group_slug, get_user_group_slug)
55 55 from rhodecode.lib.caching_query import FromCache
56 56
57 57
58 58 if rhodecode.is_unix:
59 59 import bcrypt
60 60
61 61 log = logging.getLogger(__name__)
62 62
63 63 csrf_token_key = "csrf_token"
64 64
65 65
66 66 class PasswordGenerator(object):
67 67 """
68 68 This is a simple class for generating password from different sets of
69 69 characters
70 70 usage::
71 71
72 72 passwd_gen = PasswordGenerator()
73 73 #print 8-letter password containing only big and small letters
74 74 of alphabet
75 75 passwd_gen.gen_password(8, passwd_gen.ALPHABETS_BIG_SMALL)
76 76 """
77 77 ALPHABETS_NUM = r'''1234567890'''
78 78 ALPHABETS_SMALL = r'''qwertyuiopasdfghjklzxcvbnm'''
79 79 ALPHABETS_BIG = r'''QWERTYUIOPASDFGHJKLZXCVBNM'''
80 80 ALPHABETS_SPECIAL = r'''`-=[]\;',./~!@#$%^&*()_+{}|:"<>?'''
81 81 ALPHABETS_FULL = ALPHABETS_BIG + ALPHABETS_SMALL \
82 82 + ALPHABETS_NUM + ALPHABETS_SPECIAL
83 83 ALPHABETS_ALPHANUM = ALPHABETS_BIG + ALPHABETS_SMALL + ALPHABETS_NUM
84 84 ALPHABETS_BIG_SMALL = ALPHABETS_BIG + ALPHABETS_SMALL
85 85 ALPHABETS_ALPHANUM_BIG = ALPHABETS_BIG + ALPHABETS_NUM
86 86 ALPHABETS_ALPHANUM_SMALL = ALPHABETS_SMALL + ALPHABETS_NUM
87 87
88 88 def __init__(self, passwd=''):
89 89 self.passwd = passwd
90 90
91 91 def gen_password(self, length, type_=None):
92 92 if type_ is None:
93 93 type_ = self.ALPHABETS_FULL
94 94 self.passwd = ''.join([random.choice(type_) for _ in range(length)])
95 95 return self.passwd
96 96
97 97
98 98 class _RhodeCodeCryptoBase(object):
99 99 ENC_PREF = None
100 100
101 101 def hash_create(self, str_):
102 102 """
103 103 hash the string using
104 104
105 105 :param str_: password to hash
106 106 """
107 107 raise NotImplementedError
108 108
109 109 def hash_check_with_upgrade(self, password, hashed):
110 110 """
111 111 Returns tuple in which first element is boolean that states that
112 112 given password matches it's hashed version, and the second is new hash
113 113 of the password, in case this password should be migrated to new
114 114 cipher.
115 115 """
116 116 checked_hash = self.hash_check(password, hashed)
117 117 return checked_hash, None
118 118
119 119 def hash_check(self, password, hashed):
120 120 """
121 121 Checks matching password with it's hashed value.
122 122
123 123 :param password: password
124 124 :param hashed: password in hashed form
125 125 """
126 126 raise NotImplementedError
127 127
128 128 def _assert_bytes(self, value):
129 129 """
130 130 Passing in an `unicode` object can lead to hard to detect issues
131 131 if passwords contain non-ascii characters. Doing a type check
132 132 during runtime, so that such mistakes are detected early on.
133 133 """
134 134 if not isinstance(value, str):
135 135 raise TypeError(
136 136 "Bytestring required as input, got %r." % (value, ))
137 137
138 138
139 139 class _RhodeCodeCryptoBCrypt(_RhodeCodeCryptoBase):
140 140 ENC_PREF = ('$2a$10', '$2b$10')
141 141
142 142 def hash_create(self, str_):
143 143 self._assert_bytes(str_)
144 144 return bcrypt.hashpw(str_, bcrypt.gensalt(10))
145 145
146 146 def hash_check_with_upgrade(self, password, hashed):
147 147 """
148 148 Returns tuple in which first element is boolean that states that
149 149 given password matches it's hashed version, and the second is new hash
150 150 of the password, in case this password should be migrated to new
151 151 cipher.
152 152
153 153 This implements special upgrade logic which works like that:
154 154 - check if the given password == bcrypted hash, if yes then we
155 155 properly used password and it was already in bcrypt. Proceed
156 156 without any changes
157 157 - if bcrypt hash check is not working try with sha256. If hash compare
158 158 is ok, it means we using correct but old hashed password. indicate
159 159 hash change and proceed
160 160 """
161 161
162 162 new_hash = None
163 163
164 164 # regular pw check
165 165 password_match_bcrypt = self.hash_check(password, hashed)
166 166
167 167 # now we want to know if the password was maybe from sha256
168 168 # basically calling _RhodeCodeCryptoSha256().hash_check()
169 169 if not password_match_bcrypt:
170 170 if _RhodeCodeCryptoSha256().hash_check(password, hashed):
171 171 new_hash = self.hash_create(password) # make new bcrypt hash
172 172 password_match_bcrypt = True
173 173
174 174 return password_match_bcrypt, new_hash
175 175
176 176 def hash_check(self, password, hashed):
177 177 """
178 178 Checks matching password with it's hashed value.
179 179
180 180 :param password: password
181 181 :param hashed: password in hashed form
182 182 """
183 183 self._assert_bytes(password)
184 184 try:
185 185 return bcrypt.hashpw(password, hashed) == hashed
186 186 except ValueError as e:
187 187 # we're having a invalid salt here probably, we should not crash
188 188 # just return with False as it would be a wrong password.
189 189 log.debug('Failed to check password hash using bcrypt %s',
190 190 safe_str(e))
191 191
192 192 return False
193 193
194 194
195 195 class _RhodeCodeCryptoSha256(_RhodeCodeCryptoBase):
196 196 ENC_PREF = '_'
197 197
198 198 def hash_create(self, str_):
199 199 self._assert_bytes(str_)
200 200 return hashlib.sha256(str_).hexdigest()
201 201
202 202 def hash_check(self, password, hashed):
203 203 """
204 204 Checks matching password with it's hashed value.
205 205
206 206 :param password: password
207 207 :param hashed: password in hashed form
208 208 """
209 209 self._assert_bytes(password)
210 210 return hashlib.sha256(password).hexdigest() == hashed
211 211
212 212
213 213 class _RhodeCodeCryptoTest(_RhodeCodeCryptoBase):
214 214 ENC_PREF = '_'
215 215
216 216 def hash_create(self, str_):
217 217 self._assert_bytes(str_)
218 218 return sha1(str_)
219 219
220 220 def hash_check(self, password, hashed):
221 221 """
222 222 Checks matching password with it's hashed value.
223 223
224 224 :param password: password
225 225 :param hashed: password in hashed form
226 226 """
227 227 self._assert_bytes(password)
228 228 return sha1(password) == hashed
229 229
230 230
231 231 def crypto_backend():
232 232 """
233 233 Return the matching crypto backend.
234 234
235 235 Selection is based on if we run tests or not, we pick sha1-test backend to run
236 236 tests faster since BCRYPT is expensive to calculate
237 237 """
238 238 if rhodecode.is_test:
239 239 RhodeCodeCrypto = _RhodeCodeCryptoTest()
240 240 else:
241 241 RhodeCodeCrypto = _RhodeCodeCryptoBCrypt()
242 242
243 243 return RhodeCodeCrypto
244 244
245 245
246 246 def get_crypt_password(password):
247 247 """
248 248 Create the hash of `password` with the active crypto backend.
249 249
250 250 :param password: The cleartext password.
251 251 :type password: unicode
252 252 """
253 253 password = safe_str(password)
254 254 return crypto_backend().hash_create(password)
255 255
256 256
257 257 def check_password(password, hashed):
258 258 """
259 259 Check if the value in `password` matches the hash in `hashed`.
260 260
261 261 :param password: The cleartext password.
262 262 :type password: unicode
263 263
264 264 :param hashed: The expected hashed version of the password.
265 265 :type hashed: The hash has to be passed in in text representation.
266 266 """
267 267 password = safe_str(password)
268 268 return crypto_backend().hash_check(password, hashed)
269 269
270 270
271 271 def generate_auth_token(data, salt=None):
272 272 """
273 273 Generates API KEY from given string
274 274 """
275 275
276 276 if salt is None:
277 277 salt = os.urandom(16)
278 278 return hashlib.sha1(safe_str(data) + salt).hexdigest()
279 279
280 280
281 281 def get_came_from(request):
282 282 """
283 283 get query_string+path from request sanitized after removing auth_token
284 284 """
285 285 _req = request
286 286
287 287 path = _req.path
288 288 if 'auth_token' in _req.GET:
289 289 # sanitize the request and remove auth_token for redirection
290 290 _req.GET.pop('auth_token')
291 291 qs = _req.query_string
292 292 if qs:
293 293 path += '?' + qs
294 294
295 295 return path
296 296
297 297
298 298 class CookieStoreWrapper(object):
299 299
300 300 def __init__(self, cookie_store):
301 301 self.cookie_store = cookie_store
302 302
303 303 def __repr__(self):
304 304 return 'CookieStore<%s>' % (self.cookie_store)
305 305
306 306 def get(self, key, other=None):
307 307 if isinstance(self.cookie_store, dict):
308 308 return self.cookie_store.get(key, other)
309 309 elif isinstance(self.cookie_store, AuthUser):
310 310 return self.cookie_store.__dict__.get(key, other)
311 311
312 312
313 313 def _cached_perms_data(user_id, scope, user_is_admin,
314 314 user_inherit_default_permissions, explicit, algo,
315 315 calculate_super_admin):
316 316
317 317 permissions = PermissionCalculator(
318 318 user_id, scope, user_is_admin, user_inherit_default_permissions,
319 319 explicit, algo, calculate_super_admin)
320 320 return permissions.calculate()
321 321
322 322
323 323 class PermOrigin(object):
324 324 SUPER_ADMIN = 'superadmin'
325 325
326 326 REPO_USER = 'user:%s'
327 327 REPO_USERGROUP = 'usergroup:%s'
328 328 REPO_OWNER = 'repo.owner'
329 329 REPO_DEFAULT = 'repo.default'
330 330 REPO_DEFAULT_NO_INHERIT = 'repo.default.no.inherit'
331 331 REPO_PRIVATE = 'repo.private'
332 332
333 333 REPOGROUP_USER = 'user:%s'
334 334 REPOGROUP_USERGROUP = 'usergroup:%s'
335 335 REPOGROUP_OWNER = 'group.owner'
336 336 REPOGROUP_DEFAULT = 'group.default'
337 337 REPOGROUP_DEFAULT_NO_INHERIT = 'group.default.no.inherit'
338 338
339 339 USERGROUP_USER = 'user:%s'
340 340 USERGROUP_USERGROUP = 'usergroup:%s'
341 341 USERGROUP_OWNER = 'usergroup.owner'
342 342 USERGROUP_DEFAULT = 'usergroup.default'
343 343 USERGROUP_DEFAULT_NO_INHERIT = 'usergroup.default.no.inherit'
344 344
345 345
346 346 class PermOriginDict(dict):
347 347 """
348 348 A special dict used for tracking permissions along with their origins.
349 349
350 350 `__setitem__` has been overridden to expect a tuple(perm, origin)
351 351 `__getitem__` will return only the perm
352 352 `.perm_origin_stack` will return the stack of (perm, origin) set per key
353 353
354 354 >>> perms = PermOriginDict()
355 355 >>> perms['resource'] = 'read', 'default'
356 356 >>> perms['resource']
357 357 'read'
358 358 >>> perms['resource'] = 'write', 'admin'
359 359 >>> perms['resource']
360 360 'write'
361 361 >>> perms.perm_origin_stack
362 362 {'resource': [('read', 'default'), ('write', 'admin')]}
363 363 """
364 364
365 365 def __init__(self, *args, **kw):
366 366 dict.__init__(self, *args, **kw)
367 367 self.perm_origin_stack = collections.OrderedDict()
368 368
369 369 def __setitem__(self, key, (perm, origin)):
370 self.perm_origin_stack.setdefault(key, []).append((perm, origin))
370 self.perm_origin_stack.setdefault(key, []).append(
371 (perm, origin))
371 372 dict.__setitem__(self, key, perm)
372 373
373 374
375 class BranchPermOriginDict(PermOriginDict):
376 """
377 Dedicated branch permissions dict, with tracking of patterns and origins.
378
379 >>> perms = BranchPermOriginDict()
380 >>> perms['resource'] = '*pattern', 'read', 'default'
381 >>> perms['resource']
382 {'*pattern': 'read'}
383 >>> perms['resource'] = '*pattern', 'write', 'admin'
384 >>> perms['resource']
385 {'*pattern': 'write'}
386 >>> perms.perm_origin_stack
387 {'resource': {'*pattern': [('read', 'default'), ('write', 'admin')]}}
388 """
389 def __setitem__(self, key, (pattern, perm, origin)):
390
391 self.perm_origin_stack.setdefault(key, {}) \
392 .setdefault(pattern, []).append((perm, origin))
393
394 if key in self:
395 self[key].__setitem__(pattern, perm)
396 else:
397 patterns = collections.OrderedDict()
398 patterns[pattern] = perm
399 dict.__setitem__(self, key, patterns)
400
401
374 402 class PermissionCalculator(object):
375 403
376 404 def __init__(
377 405 self, user_id, scope, user_is_admin,
378 406 user_inherit_default_permissions, explicit, algo,
379 407 calculate_super_admin=False):
380 408
381 409 self.user_id = user_id
382 410 self.user_is_admin = user_is_admin
383 411 self.inherit_default_permissions = user_inherit_default_permissions
384 412 self.explicit = explicit
385 413 self.algo = algo
386 414 self.calculate_super_admin = calculate_super_admin
387 415
388 416 scope = scope or {}
389 417 self.scope_repo_id = scope.get('repo_id')
390 418 self.scope_repo_group_id = scope.get('repo_group_id')
391 419 self.scope_user_group_id = scope.get('user_group_id')
392 420
393 421 self.default_user_id = User.get_default_user(cache=True).user_id
394 422
395 423 self.permissions_repositories = PermOriginDict()
396 424 self.permissions_repository_groups = PermOriginDict()
397 425 self.permissions_user_groups = PermOriginDict()
426 self.permissions_repository_branches = BranchPermOriginDict()
398 427 self.permissions_global = set()
399 428
400 429 self.default_repo_perms = Permission.get_default_repo_perms(
401 430 self.default_user_id, self.scope_repo_id)
402 431 self.default_repo_groups_perms = Permission.get_default_group_perms(
403 432 self.default_user_id, self.scope_repo_group_id)
404 433 self.default_user_group_perms = \
405 434 Permission.get_default_user_group_perms(
406 435 self.default_user_id, self.scope_user_group_id)
407 436
437 # default branch perms
438 self.default_branch_repo_perms = \
439 Permission.get_default_repo_branch_perms(
440 self.default_user_id, self.scope_repo_id)
441
408 442 def calculate(self):
409 443 if self.user_is_admin and not self.calculate_super_admin:
410 444 return self._admin_permissions()
411 445
412 446 self._calculate_global_default_permissions()
413 447 self._calculate_global_permissions()
414 448 self._calculate_default_permissions()
415 449 self._calculate_repository_permissions()
450 self._calculate_repository_branch_permissions()
416 451 self._calculate_repository_group_permissions()
417 452 self._calculate_user_group_permissions()
418 453 return self._permission_structure()
419 454
420 455 def _admin_permissions(self):
421 456 """
422 457 admin user have all default rights for repositories
423 458 and groups set to admin
424 459 """
425 460 self.permissions_global.add('hg.admin')
426 461 self.permissions_global.add('hg.create.write_on_repogroup.true')
427 462
428 463 # repositories
429 464 for perm in self.default_repo_perms:
430 465 r_k = perm.UserRepoToPerm.repository.repo_name
431 466 p = 'repository.admin'
432 467 self.permissions_repositories[r_k] = p, PermOrigin.SUPER_ADMIN
433 468
434 469 # repository groups
435 470 for perm in self.default_repo_groups_perms:
436 471 rg_k = perm.UserRepoGroupToPerm.group.group_name
437 472 p = 'group.admin'
438 473 self.permissions_repository_groups[rg_k] = p, PermOrigin.SUPER_ADMIN
439 474
440 475 # user groups
441 476 for perm in self.default_user_group_perms:
442 477 u_k = perm.UserUserGroupToPerm.user_group.users_group_name
443 478 p = 'usergroup.admin'
444 479 self.permissions_user_groups[u_k] = p, PermOrigin.SUPER_ADMIN
445 480
481 # branch permissions
482 # TODO(marcink): validate this, especially
483 # how this should work using multiple patterns specified ??
484 # looks ok, but still needs double check !!
485 for perm in self.default_branch_repo_perms:
486 r_k = perm.UserRepoToPerm.repository.repo_name
487 p = 'branch.push_force'
488 self.permissions_repository_branches[r_k] = '*', p, PermOrigin.SUPER_ADMIN
489
446 490 return self._permission_structure()
447 491
448 492 def _calculate_global_default_permissions(self):
449 493 """
450 494 global permissions taken from the default user
451 495 """
452 496 default_global_perms = UserToPerm.query()\
453 497 .filter(UserToPerm.user_id == self.default_user_id)\
454 498 .options(joinedload(UserToPerm.permission))
455 499
456 500 for perm in default_global_perms:
457 501 self.permissions_global.add(perm.permission.permission_name)
458 502
459 503 if self.user_is_admin:
460 504 self.permissions_global.add('hg.admin')
461 505 self.permissions_global.add('hg.create.write_on_repogroup.true')
462 506
463 507 def _calculate_global_permissions(self):
464 508 """
465 509 Set global system permissions with user permissions or permissions
466 510 taken from the user groups of the current user.
467 511
468 512 The permissions include repo creating, repo group creating, forking
469 513 etc.
470 514 """
471 515
472 516 # now we read the defined permissions and overwrite what we have set
473 517 # before those can be configured from groups or users explicitly.
474 518
475 # TODO: johbo: This seems to be out of sync, find out the reason
476 # for the comment below and update it.
477
478 # In case we want to extend this list we should be always in sync with
479 # User.DEFAULT_USER_PERMISSIONS definitions
519 # In case we want to extend this list we should make sure
520 # this is in sync with User.DEFAULT_USER_PERMISSIONS definitions
480 521 _configurable = frozenset([
481 522 'hg.fork.none', 'hg.fork.repository',
482 523 'hg.create.none', 'hg.create.repository',
483 524 'hg.usergroup.create.false', 'hg.usergroup.create.true',
484 525 'hg.repogroup.create.false', 'hg.repogroup.create.true',
485 'hg.create.write_on_repogroup.false',
486 'hg.create.write_on_repogroup.true',
526 'hg.create.write_on_repogroup.false', 'hg.create.write_on_repogroup.true',
487 527 'hg.inherit_default_perms.false', 'hg.inherit_default_perms.true'
488 528 ])
489 529
490 530 # USER GROUPS comes first user group global permissions
491 531 user_perms_from_users_groups = Session().query(UserGroupToPerm)\
492 532 .options(joinedload(UserGroupToPerm.permission))\
493 533 .join((UserGroupMember, UserGroupToPerm.users_group_id ==
494 534 UserGroupMember.users_group_id))\
495 535 .filter(UserGroupMember.user_id == self.user_id)\
496 536 .order_by(UserGroupToPerm.users_group_id)\
497 537 .all()
498 538
499 539 # need to group here by groups since user can be in more than
500 540 # one group, so we get all groups
501 541 _explicit_grouped_perms = [
502 542 [x, list(y)] for x, y in
503 543 itertools.groupby(user_perms_from_users_groups,
504 544 lambda _x: _x.users_group)]
505 545
506 546 for gr, perms in _explicit_grouped_perms:
507 547 # since user can be in multiple groups iterate over them and
508 548 # select the lowest permissions first (more explicit)
509 # TODO: marcink: do this^^
549 # TODO(marcink): do this^^
510 550
511 551 # group doesn't inherit default permissions so we actually set them
512 552 if not gr.inherit_default_permissions:
513 553 # NEED TO IGNORE all previously set configurable permissions
514 554 # and replace them with explicitly set from this user
515 555 # group permissions
516 556 self.permissions_global = self.permissions_global.difference(
517 557 _configurable)
518 558 for perm in perms:
519 559 self.permissions_global.add(perm.permission.permission_name)
520 560
521 561 # user explicit global permissions
522 562 user_perms = Session().query(UserToPerm)\
523 563 .options(joinedload(UserToPerm.permission))\
524 564 .filter(UserToPerm.user_id == self.user_id).all()
525 565
526 566 if not self.inherit_default_permissions:
527 567 # NEED TO IGNORE all configurable permissions and
528 568 # replace them with explicitly set from this user permissions
529 569 self.permissions_global = self.permissions_global.difference(
530 570 _configurable)
531 571 for perm in user_perms:
532 572 self.permissions_global.add(perm.permission.permission_name)
533 573
534 574 def _calculate_default_permissions(self):
535 575 """
536 Set default user permissions for repositories, repository groups
537 taken from the default user.
576 Set default user permissions for repositories, repository branches,
577 repository groups, user groups taken from the default user.
538 578
539 579 Calculate inheritance of object permissions based on what we have now
540 580 in GLOBAL permissions. We check if .false is in GLOBAL since this is
541 581 explicitly set. Inherit is the opposite of .false being there.
542 582
543 583 .. note::
544 584
545 585 the syntax is little bit odd but what we need to check here is
546 586 the opposite of .false permission being in the list so even for
547 587 inconsistent state when both .true/.false is there
548 588 .false is more important
549 589
550 590 """
551 591 user_inherit_object_permissions = not ('hg.inherit_default_perms.false'
552 592 in self.permissions_global)
553 593
554 # defaults for repositories, taken from `default` user permissions
555 # on given repo
594 # default permissions for repositories, taken from `default` user permissions
556 595 for perm in self.default_repo_perms:
557 596 r_k = perm.UserRepoToPerm.repository.repo_name
558 597 p = perm.Permission.permission_name
559 598 o = PermOrigin.REPO_DEFAULT
560 599 self.permissions_repositories[r_k] = p, o
561 600
562 601 # if we decide this user isn't inheriting permissions from
563 602 # default user we set him to .none so only explicit
564 603 # permissions work
565 604 if not user_inherit_object_permissions:
566 605 p = 'repository.none'
567 606 o = PermOrigin.REPO_DEFAULT_NO_INHERIT
568 607 self.permissions_repositories[r_k] = p, o
569 608
570 609 if perm.Repository.private and not (
571 610 perm.Repository.user_id == self.user_id):
572 611 # disable defaults for private repos,
573 612 p = 'repository.none'
574 613 o = PermOrigin.REPO_PRIVATE
575 614 self.permissions_repositories[r_k] = p, o
576 615
577 616 elif perm.Repository.user_id == self.user_id:
578 617 # set admin if owner
579 618 p = 'repository.admin'
580 619 o = PermOrigin.REPO_OWNER
581 620 self.permissions_repositories[r_k] = p, o
582 621
583 622 if self.user_is_admin:
584 623 p = 'repository.admin'
585 624 o = PermOrigin.SUPER_ADMIN
586 625 self.permissions_repositories[r_k] = p, o
587 626
588 # defaults for repository groups taken from `default` user permission
589 # on given group
627 # default permissions branch for repositories, taken from `default` user permissions
628 for perm in self.default_branch_repo_perms:
629
630 r_k = perm.UserRepoToPerm.repository.repo_name
631 p = perm.Permission.permission_name
632 pattern = perm.UserToRepoBranchPermission.branch_pattern
633 o = PermOrigin.REPO_USER % perm.UserRepoToPerm.user.username
634
635 if not self.explicit:
636 # TODO(marcink): fix this for multiple entries
637 cur_perm = self.permissions_repository_branches.get(r_k) or 'branch.none'
638 p = self._choose_permission(p, cur_perm)
639
640 # NOTE(marcink): register all pattern/perm instances in this
641 # special dict that aggregates entries
642 self.permissions_repository_branches[r_k] = pattern, p, o
643
644 # default permissions for repository groups taken from `default` user permission
590 645 for perm in self.default_repo_groups_perms:
591 646 rg_k = perm.UserRepoGroupToPerm.group.group_name
592 647 p = perm.Permission.permission_name
593 648 o = PermOrigin.REPOGROUP_DEFAULT
594 649 self.permissions_repository_groups[rg_k] = p, o
595 650
596 651 # if we decide this user isn't inheriting permissions from default
597 652 # user we set him to .none so only explicit permissions work
598 653 if not user_inherit_object_permissions:
599 654 p = 'group.none'
600 655 o = PermOrigin.REPOGROUP_DEFAULT_NO_INHERIT
601 656 self.permissions_repository_groups[rg_k] = p, o
602 657
603 658 if perm.RepoGroup.user_id == self.user_id:
604 659 # set admin if owner
605 660 p = 'group.admin'
606 661 o = PermOrigin.REPOGROUP_OWNER
607 662 self.permissions_repository_groups[rg_k] = p, o
608 663
609 664 if self.user_is_admin:
610 665 p = 'group.admin'
611 666 o = PermOrigin.SUPER_ADMIN
612 667 self.permissions_repository_groups[rg_k] = p, o
613 668
614 # defaults for user groups taken from `default` user permission
615 # on given user group
669 # default permissions for user groups taken from `default` user permission
616 670 for perm in self.default_user_group_perms:
617 671 u_k = perm.UserUserGroupToPerm.user_group.users_group_name
618 672 p = perm.Permission.permission_name
619 673 o = PermOrigin.USERGROUP_DEFAULT
620 674 self.permissions_user_groups[u_k] = p, o
621 675
622 676 # if we decide this user isn't inheriting permissions from default
623 677 # user we set him to .none so only explicit permissions work
624 678 if not user_inherit_object_permissions:
625 679 p = 'usergroup.none'
626 680 o = PermOrigin.USERGROUP_DEFAULT_NO_INHERIT
627 681 self.permissions_user_groups[u_k] = p, o
628 682
629 683 if perm.UserGroup.user_id == self.user_id:
630 684 # set admin if owner
631 685 p = 'usergroup.admin'
632 686 o = PermOrigin.USERGROUP_OWNER
633 687 self.permissions_user_groups[u_k] = p, o
634 688
635 689 if self.user_is_admin:
636 690 p = 'usergroup.admin'
637 691 o = PermOrigin.SUPER_ADMIN
638 692 self.permissions_user_groups[u_k] = p, o
639 693
640 694 def _calculate_repository_permissions(self):
641 695 """
642 696 Repository permissions for the current user.
643 697
644 698 Check if the user is part of user groups for this repository and
645 699 fill in the permission from it. `_choose_permission` decides of which
646 700 permission should be selected based on selected method.
647 701 """
648 702
649 703 # user group for repositories permissions
650 704 user_repo_perms_from_user_group = Permission\
651 705 .get_default_repo_perms_from_user_group(
652 706 self.user_id, self.scope_repo_id)
653 707
654 708 multiple_counter = collections.defaultdict(int)
655 709 for perm in user_repo_perms_from_user_group:
656 710 r_k = perm.UserGroupRepoToPerm.repository.repo_name
657 711 multiple_counter[r_k] += 1
658 712 p = perm.Permission.permission_name
659 713 o = PermOrigin.REPO_USERGROUP % perm.UserGroupRepoToPerm\
660 714 .users_group.users_group_name
661 715
662 716 if multiple_counter[r_k] > 1:
663 717 cur_perm = self.permissions_repositories[r_k]
664 718 p = self._choose_permission(p, cur_perm)
665 719
666 720 self.permissions_repositories[r_k] = p, o
667 721
668 722 if perm.Repository.user_id == self.user_id:
669 723 # set admin if owner
670 724 p = 'repository.admin'
671 725 o = PermOrigin.REPO_OWNER
672 726 self.permissions_repositories[r_k] = p, o
673 727
674 728 if self.user_is_admin:
675 729 p = 'repository.admin'
676 730 o = PermOrigin.SUPER_ADMIN
677 731 self.permissions_repositories[r_k] = p, o
678 732
679 733 # user explicit permissions for repositories, overrides any specified
680 734 # by the group permission
681 735 user_repo_perms = Permission.get_default_repo_perms(
682 736 self.user_id, self.scope_repo_id)
683 737 for perm in user_repo_perms:
684 738 r_k = perm.UserRepoToPerm.repository.repo_name
685 739 p = perm.Permission.permission_name
686 740 o = PermOrigin.REPO_USER % perm.UserRepoToPerm.user.username
687 741
688 742 if not self.explicit:
689 743 cur_perm = self.permissions_repositories.get(
690 744 r_k, 'repository.none')
691 745 p = self._choose_permission(p, cur_perm)
692 746
693 747 self.permissions_repositories[r_k] = p, o
694 748
695 749 if perm.Repository.user_id == self.user_id:
696 750 # set admin if owner
697 751 p = 'repository.admin'
698 752 o = PermOrigin.REPO_OWNER
699 753 self.permissions_repositories[r_k] = p, o
700 754
701 755 if self.user_is_admin:
702 756 p = 'repository.admin'
703 757 o = PermOrigin.SUPER_ADMIN
704 758 self.permissions_repositories[r_k] = p, o
705 759
760 def _calculate_repository_branch_permissions(self):
761 # user group for repositories permissions
762 user_repo_branch_perms_from_user_group = Permission\
763 .get_default_repo_branch_perms_from_user_group(
764 self.user_id, self.scope_repo_id)
765
766 multiple_counter = collections.defaultdict(int)
767 for perm in user_repo_branch_perms_from_user_group:
768 r_k = perm.UserGroupRepoToPerm.repository.repo_name
769 p = perm.Permission.permission_name
770 pattern = perm.UserGroupToRepoBranchPermission.branch_pattern
771 o = PermOrigin.REPO_USERGROUP % perm.UserGroupRepoToPerm\
772 .users_group.users_group_name
773
774 multiple_counter[r_k] += 1
775 if multiple_counter[r_k] > 1:
776 # TODO(marcink): fix this for multi branch support, and multiple entries
777 cur_perm = self.permissions_repository_branches[r_k]
778 p = self._choose_permission(p, cur_perm)
779
780 self.permissions_repository_branches[r_k] = pattern, p, o
781
782 # user explicit branch permissions for repositories, overrides
783 # any specified by the group permission
784 user_repo_branch_perms = Permission.get_default_repo_branch_perms(
785 self.user_id, self.scope_repo_id)
786 for perm in user_repo_branch_perms:
787
788 r_k = perm.UserRepoToPerm.repository.repo_name
789 p = perm.Permission.permission_name
790 pattern = perm.UserToRepoBranchPermission.branch_pattern
791 o = PermOrigin.REPO_USER % perm.UserRepoToPerm.user.username
792
793 if not self.explicit:
794 # TODO(marcink): fix this for multiple entries
795 cur_perm = self.permissions_repository_branches.get(r_k) or 'branch.none'
796 p = self._choose_permission(p, cur_perm)
797
798 # NOTE(marcink): register all pattern/perm instances in this
799 # special dict that aggregates entries
800 self.permissions_repository_branches[r_k] = pattern, p, o
801
802
706 803 def _calculate_repository_group_permissions(self):
707 804 """
708 805 Repository group permissions for the current user.
709 806
710 807 Check if the user is part of user groups for repository groups and
711 808 fill in the permissions from it. `_choose_permission` decides of which
712 809 permission should be selected based on selected method.
713 810 """
714 811 # user group for repo groups permissions
715 812 user_repo_group_perms_from_user_group = Permission\
716 813 .get_default_group_perms_from_user_group(
717 814 self.user_id, self.scope_repo_group_id)
718 815
719 816 multiple_counter = collections.defaultdict(int)
720 817 for perm in user_repo_group_perms_from_user_group:
721 818 rg_k = perm.UserGroupRepoGroupToPerm.group.group_name
722 819 multiple_counter[rg_k] += 1
723 820 o = PermOrigin.REPOGROUP_USERGROUP % perm.UserGroupRepoGroupToPerm\
724 821 .users_group.users_group_name
725 822 p = perm.Permission.permission_name
726 823
727 824 if multiple_counter[rg_k] > 1:
728 825 cur_perm = self.permissions_repository_groups[rg_k]
729 826 p = self._choose_permission(p, cur_perm)
730 827 self.permissions_repository_groups[rg_k] = p, o
731 828
732 829 if perm.RepoGroup.user_id == self.user_id:
733 830 # set admin if owner, even for member of other user group
734 831 p = 'group.admin'
735 832 o = PermOrigin.REPOGROUP_OWNER
736 833 self.permissions_repository_groups[rg_k] = p, o
737 834
738 835 if self.user_is_admin:
739 836 p = 'group.admin'
740 837 o = PermOrigin.SUPER_ADMIN
741 838 self.permissions_repository_groups[rg_k] = p, o
742 839
743 840 # user explicit permissions for repository groups
744 841 user_repo_groups_perms = Permission.get_default_group_perms(
745 842 self.user_id, self.scope_repo_group_id)
746 843 for perm in user_repo_groups_perms:
747 844 rg_k = perm.UserRepoGroupToPerm.group.group_name
748 845 o = PermOrigin.REPOGROUP_USER % perm.UserRepoGroupToPerm\
749 846 .user.username
750 847 p = perm.Permission.permission_name
751 848
752 849 if not self.explicit:
753 850 cur_perm = self.permissions_repository_groups.get(
754 851 rg_k, 'group.none')
755 852 p = self._choose_permission(p, cur_perm)
756 853
757 854 self.permissions_repository_groups[rg_k] = p, o
758 855
759 856 if perm.RepoGroup.user_id == self.user_id:
760 857 # set admin if owner
761 858 p = 'group.admin'
762 859 o = PermOrigin.REPOGROUP_OWNER
763 860 self.permissions_repository_groups[rg_k] = p, o
764 861
765 862 if self.user_is_admin:
766 863 p = 'group.admin'
767 864 o = PermOrigin.SUPER_ADMIN
768 865 self.permissions_repository_groups[rg_k] = p, o
769 866
770 867 def _calculate_user_group_permissions(self):
771 868 """
772 869 User group permissions for the current user.
773 870 """
774 871 # user group for user group permissions
775 872 user_group_from_user_group = Permission\
776 873 .get_default_user_group_perms_from_user_group(
777 874 self.user_id, self.scope_user_group_id)
778 875
779 876 multiple_counter = collections.defaultdict(int)
780 877 for perm in user_group_from_user_group:
781 878 ug_k = perm.UserGroupUserGroupToPerm\
782 879 .target_user_group.users_group_name
783 880 multiple_counter[ug_k] += 1
784 881 o = PermOrigin.USERGROUP_USERGROUP % perm.UserGroupUserGroupToPerm\
785 882 .user_group.users_group_name
786 883 p = perm.Permission.permission_name
787 884
788 885 if multiple_counter[ug_k] > 1:
789 886 cur_perm = self.permissions_user_groups[ug_k]
790 887 p = self._choose_permission(p, cur_perm)
791 888
792 889 self.permissions_user_groups[ug_k] = p, o
793 890
794 891 if perm.UserGroup.user_id == self.user_id:
795 892 # set admin if owner, even for member of other user group
796 893 p = 'usergroup.admin'
797 894 o = PermOrigin.USERGROUP_OWNER
798 895 self.permissions_user_groups[ug_k] = p, o
799 896
800 897 if self.user_is_admin:
801 898 p = 'usergroup.admin'
802 899 o = PermOrigin.SUPER_ADMIN
803 900 self.permissions_user_groups[ug_k] = p, o
804 901
805 902 # user explicit permission for user groups
806 903 user_user_groups_perms = Permission.get_default_user_group_perms(
807 904 self.user_id, self.scope_user_group_id)
808 905 for perm in user_user_groups_perms:
809 906 ug_k = perm.UserUserGroupToPerm.user_group.users_group_name
810 907 o = PermOrigin.USERGROUP_USER % perm.UserUserGroupToPerm\
811 908 .user.username
812 909 p = perm.Permission.permission_name
813 910
814 911 if not self.explicit:
815 912 cur_perm = self.permissions_user_groups.get(
816 913 ug_k, 'usergroup.none')
817 914 p = self._choose_permission(p, cur_perm)
818 915
819 916 self.permissions_user_groups[ug_k] = p, o
820 917
821 918 if perm.UserGroup.user_id == self.user_id:
822 919 # set admin if owner
823 920 p = 'usergroup.admin'
824 921 o = PermOrigin.USERGROUP_OWNER
825 922 self.permissions_user_groups[ug_k] = p, o
826 923
827 924 if self.user_is_admin:
828 925 p = 'usergroup.admin'
829 926 o = PermOrigin.SUPER_ADMIN
830 927 self.permissions_user_groups[ug_k] = p, o
831 928
832 929 def _choose_permission(self, new_perm, cur_perm):
833 930 new_perm_val = Permission.PERM_WEIGHTS[new_perm]
834 931 cur_perm_val = Permission.PERM_WEIGHTS[cur_perm]
835 932 if self.algo == 'higherwin':
836 933 if new_perm_val > cur_perm_val:
837 934 return new_perm
838 935 return cur_perm
839 936 elif self.algo == 'lowerwin':
840 937 if new_perm_val < cur_perm_val:
841 938 return new_perm
842 939 return cur_perm
843 940
844 941 def _permission_structure(self):
845 942 return {
846 943 'global': self.permissions_global,
847 944 'repositories': self.permissions_repositories,
945 'repository_branches': self.permissions_repository_branches,
848 946 'repositories_groups': self.permissions_repository_groups,
849 947 'user_groups': self.permissions_user_groups,
850 948 }
851 949
852 950
853 951 def allowed_auth_token_access(view_name, auth_token, whitelist=None):
854 952 """
855 953 Check if given controller_name is in whitelist of auth token access
856 954 """
857 955 if not whitelist:
858 956 from rhodecode import CONFIG
859 957 whitelist = aslist(
860 958 CONFIG.get('api_access_controllers_whitelist'), sep=',')
861 959 # backward compat translation
862 960 compat = {
863 961 # old controller, new VIEW
864 962 'ChangesetController:*': 'RepoCommitsView:*',
865 963 'ChangesetController:changeset_patch': 'RepoCommitsView:repo_commit_patch',
866 964 'ChangesetController:changeset_raw': 'RepoCommitsView:repo_commit_raw',
867 965 'FilesController:raw': 'RepoCommitsView:repo_commit_raw',
868 966 'FilesController:archivefile': 'RepoFilesView:repo_archivefile',
869 967 'GistsController:*': 'GistView:*',
870 968 }
871 969
872 970 log.debug(
873 971 'Allowed views for AUTH TOKEN access: %s' % (whitelist,))
874 972 auth_token_access_valid = False
875 973
876 974 for entry in whitelist:
877 975 token_match = True
878 976 if entry in compat:
879 977 # translate from old Controllers to Pyramid Views
880 978 entry = compat[entry]
881 979
882 980 if '@' in entry:
883 981 # specific AuthToken
884 982 entry, allowed_token = entry.split('@', 1)
885 983 token_match = auth_token == allowed_token
886 984
887 985 if fnmatch.fnmatch(view_name, entry) and token_match:
888 986 auth_token_access_valid = True
889 987 break
890 988
891 989 if auth_token_access_valid:
892 990 log.debug('view: `%s` matches entry in whitelist: %s'
893 991 % (view_name, whitelist))
894 992 else:
895 993 msg = ('view: `%s` does *NOT* match any entry in whitelist: %s'
896 994 % (view_name, whitelist))
897 995 if auth_token:
898 996 # if we use auth token key and don't have access it's a warning
899 997 log.warning(msg)
900 998 else:
901 999 log.debug(msg)
902 1000
903 1001 return auth_token_access_valid
904 1002
905 1003
906 1004 class AuthUser(object):
907 1005 """
908 1006 A simple object that handles all attributes of user in RhodeCode
909 1007
910 1008 It does lookup based on API key,given user, or user present in session
911 1009 Then it fills all required information for such user. It also checks if
912 1010 anonymous access is enabled and if so, it returns default user as logged in
913 1011 """
914 1012 GLOBAL_PERMS = [x[0] for x in Permission.PERMS]
915 1013
916 1014 def __init__(self, user_id=None, api_key=None, username=None, ip_addr=None):
917 1015
918 1016 self.user_id = user_id
919 1017 self._api_key = api_key
920 1018
921 1019 self.api_key = None
922 1020 self.username = username
923 1021 self.ip_addr = ip_addr
924 1022 self.name = ''
925 1023 self.lastname = ''
926 1024 self.first_name = ''
927 1025 self.last_name = ''
928 1026 self.email = ''
929 1027 self.is_authenticated = False
930 1028 self.admin = False
931 1029 self.inherit_default_permissions = False
932 1030 self.password = ''
933 1031
934 1032 self.anonymous_user = None # propagated on propagate_data
935 1033 self.propagate_data()
936 1034 self._instance = None
937 1035 self._permissions_scoped_cache = {} # used to bind scoped calculation
938 1036
939 1037 @LazyProperty
940 1038 def permissions(self):
941 1039 return self.get_perms(user=self, cache=False)
942 1040
943 1041 @LazyProperty
944 1042 def permissions_safe(self):
945 1043 """
946 1044 Filtered permissions excluding not allowed repositories
947 1045 """
948 1046 perms = self.get_perms(user=self, cache=False)
949 1047
950 1048 perms['repositories'] = {
951 1049 k: v for k, v in perms['repositories'].items()
952 1050 if v != 'repository.none'}
953 1051 perms['repositories_groups'] = {
954 1052 k: v for k, v in perms['repositories_groups'].items()
955 1053 if v != 'group.none'}
956 1054 perms['user_groups'] = {
957 1055 k: v for k, v in perms['user_groups'].items()
958 1056 if v != 'usergroup.none'}
1057 perms['repository_branches'] = {
1058 k: v for k, v in perms['repository_branches'].iteritems()
1059 if v != 'branch.none'}
959 1060 return perms
960 1061
961 1062 @LazyProperty
962 1063 def permissions_full_details(self):
963 1064 return self.get_perms(
964 1065 user=self, cache=False, calculate_super_admin=True)
965 1066
966 1067 def permissions_with_scope(self, scope):
967 1068 """
968 1069 Call the get_perms function with scoped data. The scope in that function
969 1070 narrows the SQL calls to the given ID of objects resulting in fetching
970 1071 Just particular permission we want to obtain. If scope is an empty dict
971 1072 then it basically narrows the scope to GLOBAL permissions only.
972 1073
973 1074 :param scope: dict
974 1075 """
975 1076 if 'repo_name' in scope:
976 1077 obj = Repository.get_by_repo_name(scope['repo_name'])
977 1078 if obj:
978 1079 scope['repo_id'] = obj.repo_id
979 1080 _scope = collections.OrderedDict()
980 1081 _scope['repo_id'] = -1
981 1082 _scope['user_group_id'] = -1
982 1083 _scope['repo_group_id'] = -1
983 1084
984 1085 for k in sorted(scope.keys()):
985 1086 _scope[k] = scope[k]
986 1087
987 1088 # store in cache to mimic how the @LazyProperty works,
988 1089 # the difference here is that we use the unique key calculated
989 1090 # from params and values
990 1091 return self.get_perms(user=self, cache=False, scope=_scope)
991 1092
992 1093 def get_instance(self):
993 1094 return User.get(self.user_id)
994 1095
995 1096 def propagate_data(self):
996 1097 """
997 1098 Fills in user data and propagates values to this instance. Maps fetched
998 1099 user attributes to this class instance attributes
999 1100 """
1000 1101 log.debug('AuthUser: starting data propagation for new potential user')
1001 1102 user_model = UserModel()
1002 1103 anon_user = self.anonymous_user = User.get_default_user(cache=True)
1003 1104 is_user_loaded = False
1004 1105
1005 1106 # lookup by userid
1006 1107 if self.user_id is not None and self.user_id != anon_user.user_id:
1007 1108 log.debug('Trying Auth User lookup by USER ID: `%s`', self.user_id)
1008 1109 is_user_loaded = user_model.fill_data(self, user_id=self.user_id)
1009 1110
1010 1111 # try go get user by api key
1011 1112 elif self._api_key and self._api_key != anon_user.api_key:
1012 1113 log.debug('Trying Auth User lookup by API KEY: `%s`', self._api_key)
1013 1114 is_user_loaded = user_model.fill_data(self, api_key=self._api_key)
1014 1115
1015 1116 # lookup by username
1016 1117 elif self.username:
1017 1118 log.debug('Trying Auth User lookup by USER NAME: `%s`', self.username)
1018 1119 is_user_loaded = user_model.fill_data(self, username=self.username)
1019 1120 else:
1020 1121 log.debug('No data in %s that could been used to log in', self)
1021 1122
1022 1123 if not is_user_loaded:
1023 1124 log.debug(
1024 1125 'Failed to load user. Fallback to default user %s', anon_user)
1025 1126 # if we cannot authenticate user try anonymous
1026 1127 if anon_user.active:
1027 1128 log.debug('default user is active, using it as a session user')
1028 1129 user_model.fill_data(self, user_id=anon_user.user_id)
1029 1130 # then we set this user is logged in
1030 1131 self.is_authenticated = True
1031 1132 else:
1032 1133 log.debug('default user is NOT active')
1033 1134 # in case of disabled anonymous user we reset some of the
1034 1135 # parameters so such user is "corrupted", skipping the fill_data
1035 1136 for attr in ['user_id', 'username', 'admin', 'active']:
1036 1137 setattr(self, attr, None)
1037 1138 self.is_authenticated = False
1038 1139
1039 1140 if not self.username:
1040 1141 self.username = 'None'
1041 1142
1042 1143 log.debug('AuthUser: propagated user is now %s', self)
1043 1144
1044 1145 def get_perms(self, user, scope=None, explicit=True, algo='higherwin',
1045 1146 calculate_super_admin=False, cache=False):
1046 1147 """
1047 1148 Fills user permission attribute with permissions taken from database
1048 1149 works for permissions given for repositories, and for permissions that
1049 1150 are granted to groups
1050 1151
1051 1152 :param user: instance of User object from database
1052 1153 :param explicit: In case there are permissions both for user and a group
1053 1154 that user is part of, explicit flag will defiine if user will
1054 1155 explicitly override permissions from group, if it's False it will
1055 1156 make decision based on the algo
1056 1157 :param algo: algorithm to decide what permission should be choose if
1057 1158 it's multiple defined, eg user in two different groups. It also
1058 1159 decides if explicit flag is turned off how to specify the permission
1059 1160 for case when user is in a group + have defined separate permission
1060 1161 """
1061 1162 user_id = user.user_id
1062 1163 user_is_admin = user.is_admin
1063 1164
1064 1165 # inheritance of global permissions like create repo/fork repo etc
1065 1166 user_inherit_default_permissions = user.inherit_default_permissions
1066 1167
1067 1168 cache_seconds = safe_int(
1068 1169 rhodecode.CONFIG.get('rc_cache.cache_perms.expiration_time'))
1069 1170
1070 1171 cache_on = cache or cache_seconds > 0
1071 1172 log.debug(
1072 1173 'Computing PERMISSION tree for user %s scope `%s` '
1073 1174 'with caching: %s[TTL: %ss]' % (user, scope, cache_on, cache_seconds or 0))
1074 1175
1075 1176 cache_namespace_uid = 'cache_user_auth.{}'.format(user_id)
1076 1177 region = rc_cache.get_or_create_region('cache_perms', cache_namespace_uid)
1077 1178
1078 1179 @region.conditional_cache_on_arguments(namespace=cache_namespace_uid,
1079 1180 condition=cache_on)
1080 1181 def compute_perm_tree(cache_name,
1081 1182 user_id, scope, user_is_admin,user_inherit_default_permissions,
1082 1183 explicit, algo, calculate_super_admin):
1083 1184 return _cached_perms_data(
1084 1185 user_id, scope, user_is_admin, user_inherit_default_permissions,
1085 1186 explicit, algo, calculate_super_admin)
1086 1187
1087 1188 start = time.time()
1088 1189 result = compute_perm_tree('permissions', user_id, scope, user_is_admin,
1089 1190 user_inherit_default_permissions, explicit, algo,
1090 1191 calculate_super_admin)
1091 1192
1092 1193 result_repr = []
1093 1194 for k in result:
1094 1195 result_repr.append((k, len(result[k])))
1095 1196 total = time.time() - start
1096 1197 log.debug('PERMISSION tree for user %s computed in %.3fs: %s' % (
1097 1198 user, total, result_repr))
1098 1199
1099 1200 return result
1100 1201
1101 1202 @property
1102 1203 def is_default(self):
1103 1204 return self.username == User.DEFAULT_USER
1104 1205
1105 1206 @property
1106 1207 def is_admin(self):
1107 1208 return self.admin
1108 1209
1109 1210 @property
1110 1211 def is_user_object(self):
1111 1212 return self.user_id is not None
1112 1213
1113 1214 @property
1114 1215 def repositories_admin(self):
1115 1216 """
1116 1217 Returns list of repositories you're an admin of
1117 1218 """
1118 1219 return [
1119 1220 x[0] for x in self.permissions['repositories'].items()
1120 1221 if x[1] == 'repository.admin']
1121 1222
1122 1223 @property
1123 1224 def repository_groups_admin(self):
1124 1225 """
1125 1226 Returns list of repository groups you're an admin of
1126 1227 """
1127 1228 return [
1128 1229 x[0] for x in self.permissions['repositories_groups'].items()
1129 1230 if x[1] == 'group.admin']
1130 1231
1131 1232 @property
1132 1233 def user_groups_admin(self):
1133 1234 """
1134 1235 Returns list of user groups you're an admin of
1135 1236 """
1136 1237 return [
1137 1238 x[0] for x in self.permissions['user_groups'].items()
1138 1239 if x[1] == 'usergroup.admin']
1139 1240
1140 1241 def repo_acl_ids(self, perms=None, name_filter=None, cache=False):
1141 1242 """
1142 1243 Returns list of repository ids that user have access to based on given
1143 1244 perms. The cache flag should be only used in cases that are used for
1144 1245 display purposes, NOT IN ANY CASE for permission checks.
1145 1246 """
1146 1247 from rhodecode.model.scm import RepoList
1147 1248 if not perms:
1148 1249 perms = [
1149 1250 'repository.read', 'repository.write', 'repository.admin']
1150 1251
1151 1252 def _cached_repo_acl(user_id, perm_def, _name_filter):
1152 1253 qry = Repository.query()
1153 1254 if _name_filter:
1154 1255 ilike_expression = u'%{}%'.format(safe_unicode(_name_filter))
1155 1256 qry = qry.filter(
1156 1257 Repository.repo_name.ilike(ilike_expression))
1157 1258
1158 1259 return [x.repo_id for x in
1159 1260 RepoList(qry, perm_set=perm_def)]
1160 1261
1161 1262 return _cached_repo_acl(self.user_id, perms, name_filter)
1162 1263
1163 1264 def repo_group_acl_ids(self, perms=None, name_filter=None, cache=False):
1164 1265 """
1165 1266 Returns list of repository group ids that user have access to based on given
1166 1267 perms. The cache flag should be only used in cases that are used for
1167 1268 display purposes, NOT IN ANY CASE for permission checks.
1168 1269 """
1169 1270 from rhodecode.model.scm import RepoGroupList
1170 1271 if not perms:
1171 1272 perms = [
1172 1273 'group.read', 'group.write', 'group.admin']
1173 1274
1174 1275 def _cached_repo_group_acl(user_id, perm_def, _name_filter):
1175 1276 qry = RepoGroup.query()
1176 1277 if _name_filter:
1177 1278 ilike_expression = u'%{}%'.format(safe_unicode(_name_filter))
1178 1279 qry = qry.filter(
1179 1280 RepoGroup.group_name.ilike(ilike_expression))
1180 1281
1181 1282 return [x.group_id for x in
1182 1283 RepoGroupList(qry, perm_set=perm_def)]
1183 1284
1184 1285 return _cached_repo_group_acl(self.user_id, perms, name_filter)
1185 1286
1186 1287 def user_group_acl_ids(self, perms=None, name_filter=None, cache=False):
1187 1288 """
1188 1289 Returns list of user group ids that user have access to based on given
1189 1290 perms. The cache flag should be only used in cases that are used for
1190 1291 display purposes, NOT IN ANY CASE for permission checks.
1191 1292 """
1192 1293 from rhodecode.model.scm import UserGroupList
1193 1294 if not perms:
1194 1295 perms = [
1195 1296 'usergroup.read', 'usergroup.write', 'usergroup.admin']
1196 1297
1197 1298 def _cached_user_group_acl(user_id, perm_def, name_filter):
1198 1299 qry = UserGroup.query()
1199 1300 if name_filter:
1200 1301 ilike_expression = u'%{}%'.format(safe_unicode(name_filter))
1201 1302 qry = qry.filter(
1202 1303 UserGroup.users_group_name.ilike(ilike_expression))
1203 1304
1204 1305 return [x.users_group_id for x in
1205 1306 UserGroupList(qry, perm_set=perm_def)]
1206 1307
1207 1308 return _cached_user_group_acl(self.user_id, perms, name_filter)
1208 1309
1209 1310 @property
1210 1311 def ip_allowed(self):
1211 1312 """
1212 1313 Checks if ip_addr used in constructor is allowed from defined list of
1213 1314 allowed ip_addresses for user
1214 1315
1215 1316 :returns: boolean, True if ip is in allowed ip range
1216 1317 """
1217 1318 # check IP
1218 1319 inherit = self.inherit_default_permissions
1219 1320 return AuthUser.check_ip_allowed(self.user_id, self.ip_addr,
1220 1321 inherit_from_default=inherit)
1221 1322 @property
1222 1323 def personal_repo_group(self):
1223 1324 return RepoGroup.get_user_personal_repo_group(self.user_id)
1224 1325
1225 1326 @LazyProperty
1226 1327 def feed_token(self):
1227 1328 return self.get_instance().feed_token
1228 1329
1229 1330 @classmethod
1230 1331 def check_ip_allowed(cls, user_id, ip_addr, inherit_from_default):
1231 1332 allowed_ips = AuthUser.get_allowed_ips(
1232 1333 user_id, cache=True, inherit_from_default=inherit_from_default)
1233 1334 if check_ip_access(source_ip=ip_addr, allowed_ips=allowed_ips):
1234 1335 log.debug('IP:%s for user %s is in range of %s' % (
1235 1336 ip_addr, user_id, allowed_ips))
1236 1337 return True
1237 1338 else:
1238 1339 log.info('Access for IP:%s forbidden for user %s, '
1239 1340 'not in %s' % (ip_addr, user_id, allowed_ips))
1240 1341 return False
1241 1342
1242 1343 def __repr__(self):
1243 1344 return "<AuthUser('id:%s[%s] ip:%s auth:%s')>"\
1244 1345 % (self.user_id, self.username, self.ip_addr, self.is_authenticated)
1245 1346
1246 1347 def set_authenticated(self, authenticated=True):
1247 1348 if self.user_id != self.anonymous_user.user_id:
1248 1349 self.is_authenticated = authenticated
1249 1350
1250 1351 def get_cookie_store(self):
1251 1352 return {
1252 1353 'username': self.username,
1253 1354 'password': md5(self.password or ''),
1254 1355 'user_id': self.user_id,
1255 1356 'is_authenticated': self.is_authenticated
1256 1357 }
1257 1358
1258 1359 @classmethod
1259 1360 def from_cookie_store(cls, cookie_store):
1260 1361 """
1261 1362 Creates AuthUser from a cookie store
1262 1363
1263 1364 :param cls:
1264 1365 :param cookie_store:
1265 1366 """
1266 1367 user_id = cookie_store.get('user_id')
1267 1368 username = cookie_store.get('username')
1268 1369 api_key = cookie_store.get('api_key')
1269 1370 return AuthUser(user_id, api_key, username)
1270 1371
1271 1372 @classmethod
1272 1373 def get_allowed_ips(cls, user_id, cache=False, inherit_from_default=False):
1273 1374 _set = set()
1274 1375
1275 1376 if inherit_from_default:
1276 1377 def_user_id = User.get_default_user(cache=True).user_id
1277 1378 default_ips = UserIpMap.query().filter(UserIpMap.user_id == def_user_id)
1278 1379 if cache:
1279 1380 default_ips = default_ips.options(
1280 1381 FromCache("sql_cache_short", "get_user_ips_default"))
1281 1382
1282 1383 # populate from default user
1283 1384 for ip in default_ips:
1284 1385 try:
1285 1386 _set.add(ip.ip_addr)
1286 1387 except ObjectDeletedError:
1287 1388 # since we use heavy caching sometimes it happens that
1288 1389 # we get deleted objects here, we just skip them
1289 1390 pass
1290 1391
1291 1392 # NOTE:(marcink) we don't want to load any rules for empty
1292 1393 # user_id which is the case of access of non logged users when anonymous
1293 1394 # access is disabled
1294 1395 user_ips = []
1295 1396 if user_id:
1296 1397 user_ips = UserIpMap.query().filter(UserIpMap.user_id == user_id)
1297 1398 if cache:
1298 1399 user_ips = user_ips.options(
1299 1400 FromCache("sql_cache_short", "get_user_ips_%s" % user_id))
1300 1401
1301 1402 for ip in user_ips:
1302 1403 try:
1303 1404 _set.add(ip.ip_addr)
1304 1405 except ObjectDeletedError:
1305 1406 # since we use heavy caching sometimes it happens that we get
1306 1407 # deleted objects here, we just skip them
1307 1408 pass
1308 1409 return _set or {ip for ip in ['0.0.0.0/0', '::/0']}
1309 1410
1310 1411
1311 1412 def set_available_permissions(settings):
1312 1413 """
1313 1414 This function will propagate pyramid settings with all available defined
1314 1415 permission given in db. We don't want to check each time from db for new
1315 1416 permissions since adding a new permission also requires application restart
1316 1417 ie. to decorate new views with the newly created permission
1317 1418
1318 1419 :param settings: current pyramid registry.settings
1319 1420
1320 1421 """
1321 1422 log.debug('auth: getting information about all available permissions')
1322 1423 try:
1323 1424 sa = meta.Session
1324 1425 all_perms = sa.query(Permission).all()
1325 1426 settings.setdefault('available_permissions',
1326 1427 [x.permission_name for x in all_perms])
1327 1428 log.debug('auth: set available permissions')
1328 1429 except Exception:
1329 1430 log.exception('Failed to fetch permissions from the database.')
1330 1431 raise
1331 1432
1332 1433
1333 1434 def get_csrf_token(session, force_new=False, save_if_missing=True):
1334 1435 """
1335 1436 Return the current authentication token, creating one if one doesn't
1336 1437 already exist and the save_if_missing flag is present.
1337 1438
1338 1439 :param session: pass in the pyramid session, else we use the global ones
1339 1440 :param force_new: force to re-generate the token and store it in session
1340 1441 :param save_if_missing: save the newly generated token if it's missing in
1341 1442 session
1342 1443 """
1343 1444 # NOTE(marcink): probably should be replaced with below one from pyramid 1.9
1344 1445 # from pyramid.csrf import get_csrf_token
1345 1446
1346 1447 if (csrf_token_key not in session and save_if_missing) or force_new:
1347 1448 token = hashlib.sha1(str(random.getrandbits(128))).hexdigest()
1348 1449 session[csrf_token_key] = token
1349 1450 if hasattr(session, 'save'):
1350 1451 session.save()
1351 1452 return session.get(csrf_token_key)
1352 1453
1353 1454
1354 1455 def get_request(perm_class_instance):
1355 1456 from pyramid.threadlocal import get_current_request
1356 1457 pyramid_request = get_current_request()
1357 1458 return pyramid_request
1358 1459
1359 1460
1360 1461 # CHECK DECORATORS
1361 1462 class CSRFRequired(object):
1362 1463 """
1363 1464 Decorator for authenticating a form
1364 1465
1365 1466 This decorator uses an authorization token stored in the client's
1366 1467 session for prevention of certain Cross-site request forgery (CSRF)
1367 1468 attacks (See
1368 1469 http://en.wikipedia.org/wiki/Cross-site_request_forgery for more
1369 1470 information).
1370 1471
1371 1472 For use with the ``webhelpers.secure_form`` helper functions.
1372 1473
1373 1474 """
1374 1475 def __init__(self, token=csrf_token_key, header='X-CSRF-Token',
1375 1476 except_methods=None):
1376 1477 self.token = token
1377 1478 self.header = header
1378 1479 self.except_methods = except_methods or []
1379 1480
1380 1481 def __call__(self, func):
1381 1482 return get_cython_compat_decorator(self.__wrapper, func)
1382 1483
1383 1484 def _get_csrf(self, _request):
1384 1485 return _request.POST.get(self.token, _request.headers.get(self.header))
1385 1486
1386 1487 def check_csrf(self, _request, cur_token):
1387 1488 supplied_token = self._get_csrf(_request)
1388 1489 return supplied_token and supplied_token == cur_token
1389 1490
1390 1491 def _get_request(self):
1391 1492 return get_request(self)
1392 1493
1393 1494 def __wrapper(self, func, *fargs, **fkwargs):
1394 1495 request = self._get_request()
1395 1496
1396 1497 if request.method in self.except_methods:
1397 1498 return func(*fargs, **fkwargs)
1398 1499
1399 1500 cur_token = get_csrf_token(request.session, save_if_missing=False)
1400 1501 if self.check_csrf(request, cur_token):
1401 1502 if request.POST.get(self.token):
1402 1503 del request.POST[self.token]
1403 1504 return func(*fargs, **fkwargs)
1404 1505 else:
1405 1506 reason = 'token-missing'
1406 1507 supplied_token = self._get_csrf(request)
1407 1508 if supplied_token and cur_token != supplied_token:
1408 1509 reason = 'token-mismatch [%s:%s]' % (
1409 1510 cur_token or ''[:6], supplied_token or ''[:6])
1410 1511
1411 1512 csrf_message = \
1412 1513 ("Cross-site request forgery detected, request denied. See "
1413 1514 "http://en.wikipedia.org/wiki/Cross-site_request_forgery for "
1414 1515 "more information.")
1415 1516 log.warn('Cross-site request forgery detected, request %r DENIED: %s '
1416 1517 'REMOTE_ADDR:%s, HEADERS:%s' % (
1417 1518 request, reason, request.remote_addr, request.headers))
1418 1519
1419 1520 raise HTTPForbidden(explanation=csrf_message)
1420 1521
1421 1522
1422 1523 class LoginRequired(object):
1423 1524 """
1424 1525 Must be logged in to execute this function else
1425 1526 redirect to login page
1426 1527
1427 1528 :param api_access: if enabled this checks only for valid auth token
1428 1529 and grants access based on valid token
1429 1530 """
1430 1531 def __init__(self, auth_token_access=None):
1431 1532 self.auth_token_access = auth_token_access
1432 1533
1433 1534 def __call__(self, func):
1434 1535 return get_cython_compat_decorator(self.__wrapper, func)
1435 1536
1436 1537 def _get_request(self):
1437 1538 return get_request(self)
1438 1539
1439 1540 def __wrapper(self, func, *fargs, **fkwargs):
1440 1541 from rhodecode.lib import helpers as h
1441 1542 cls = fargs[0]
1442 1543 user = cls._rhodecode_user
1443 1544 request = self._get_request()
1444 1545 _ = request.translate
1445 1546
1446 1547 loc = "%s:%s" % (cls.__class__.__name__, func.__name__)
1447 1548 log.debug('Starting login restriction checks for user: %s' % (user,))
1448 1549 # check if our IP is allowed
1449 1550 ip_access_valid = True
1450 1551 if not user.ip_allowed:
1451 1552 h.flash(h.literal(_('IP %s not allowed' % (user.ip_addr,))),
1452 1553 category='warning')
1453 1554 ip_access_valid = False
1454 1555
1455 1556 # check if we used an APIKEY and it's a valid one
1456 1557 # defined white-list of controllers which API access will be enabled
1457 1558 _auth_token = request.GET.get(
1458 1559 'auth_token', '') or request.GET.get('api_key', '')
1459 1560 auth_token_access_valid = allowed_auth_token_access(
1460 1561 loc, auth_token=_auth_token)
1461 1562
1462 1563 # explicit controller is enabled or API is in our whitelist
1463 1564 if self.auth_token_access or auth_token_access_valid:
1464 1565 log.debug('Checking AUTH TOKEN access for %s' % (cls,))
1465 1566 db_user = user.get_instance()
1466 1567
1467 1568 if db_user:
1468 1569 if self.auth_token_access:
1469 1570 roles = self.auth_token_access
1470 1571 else:
1471 1572 roles = [UserApiKeys.ROLE_HTTP]
1472 1573 token_match = db_user.authenticate_by_token(
1473 1574 _auth_token, roles=roles)
1474 1575 else:
1475 1576 log.debug('Unable to fetch db instance for auth user: %s', user)
1476 1577 token_match = False
1477 1578
1478 1579 if _auth_token and token_match:
1479 1580 auth_token_access_valid = True
1480 1581 log.debug('AUTH TOKEN ****%s is VALID' % (_auth_token[-4:],))
1481 1582 else:
1482 1583 auth_token_access_valid = False
1483 1584 if not _auth_token:
1484 1585 log.debug("AUTH TOKEN *NOT* present in request")
1485 1586 else:
1486 1587 log.warning(
1487 1588 "AUTH TOKEN ****%s *NOT* valid" % _auth_token[-4:])
1488 1589
1489 1590 log.debug('Checking if %s is authenticated @ %s' % (user.username, loc))
1490 1591 reason = 'RHODECODE_AUTH' if user.is_authenticated \
1491 1592 else 'AUTH_TOKEN_AUTH'
1492 1593
1493 1594 if ip_access_valid and (
1494 1595 user.is_authenticated or auth_token_access_valid):
1495 1596 log.info(
1496 1597 'user %s authenticating with:%s IS authenticated on func %s'
1497 1598 % (user, reason, loc))
1498 1599
1499 1600 return func(*fargs, **fkwargs)
1500 1601 else:
1501 1602 log.warning(
1502 1603 'user %s authenticating with:%s NOT authenticated on '
1503 1604 'func: %s: IP_ACCESS:%s AUTH_TOKEN_ACCESS:%s'
1504 1605 % (user, reason, loc, ip_access_valid,
1505 1606 auth_token_access_valid))
1506 1607 # we preserve the get PARAM
1507 1608 came_from = get_came_from(request)
1508 1609
1509 1610 log.debug('redirecting to login page with %s' % (came_from,))
1510 1611 raise HTTPFound(
1511 1612 h.route_path('login', _query={'came_from': came_from}))
1512 1613
1513 1614
1514 1615 class NotAnonymous(object):
1515 1616 """
1516 1617 Must be logged in to execute this function else
1517 1618 redirect to login page
1518 1619 """
1519 1620
1520 1621 def __call__(self, func):
1521 1622 return get_cython_compat_decorator(self.__wrapper, func)
1522 1623
1523 1624 def _get_request(self):
1524 1625 return get_request(self)
1525 1626
1526 1627 def __wrapper(self, func, *fargs, **fkwargs):
1527 1628 import rhodecode.lib.helpers as h
1528 1629 cls = fargs[0]
1529 1630 self.user = cls._rhodecode_user
1530 1631 request = self._get_request()
1531 1632 _ = request.translate
1532 1633 log.debug('Checking if user is not anonymous @%s' % cls)
1533 1634
1534 1635 anonymous = self.user.username == User.DEFAULT_USER
1535 1636
1536 1637 if anonymous:
1537 1638 came_from = get_came_from(request)
1538 1639 h.flash(_('You need to be a registered user to '
1539 1640 'perform this action'),
1540 1641 category='warning')
1541 1642 raise HTTPFound(
1542 1643 h.route_path('login', _query={'came_from': came_from}))
1543 1644 else:
1544 1645 return func(*fargs, **fkwargs)
1545 1646
1546 1647
1547 1648 class PermsDecorator(object):
1548 1649 """
1549 1650 Base class for controller decorators, we extract the current user from
1550 1651 the class itself, which has it stored in base controllers
1551 1652 """
1552 1653
1553 1654 def __init__(self, *required_perms):
1554 1655 self.required_perms = set(required_perms)
1555 1656
1556 1657 def __call__(self, func):
1557 1658 return get_cython_compat_decorator(self.__wrapper, func)
1558 1659
1559 1660 def _get_request(self):
1560 1661 return get_request(self)
1561 1662
1562 1663 def __wrapper(self, func, *fargs, **fkwargs):
1563 1664 import rhodecode.lib.helpers as h
1564 1665 cls = fargs[0]
1565 1666 _user = cls._rhodecode_user
1566 1667 request = self._get_request()
1567 1668 _ = request.translate
1568 1669
1569 1670 log.debug('checking %s permissions %s for %s %s',
1570 1671 self.__class__.__name__, self.required_perms, cls, _user)
1571 1672
1572 1673 if self.check_permissions(_user):
1573 1674 log.debug('Permission granted for %s %s', cls, _user)
1574 1675 return func(*fargs, **fkwargs)
1575 1676
1576 1677 else:
1577 1678 log.debug('Permission denied for %s %s', cls, _user)
1578 1679 anonymous = _user.username == User.DEFAULT_USER
1579 1680
1580 1681 if anonymous:
1581 1682 came_from = get_came_from(self._get_request())
1582 1683 h.flash(_('You need to be signed in to view this page'),
1583 1684 category='warning')
1584 1685 raise HTTPFound(
1585 1686 h.route_path('login', _query={'came_from': came_from}))
1586 1687
1587 1688 else:
1588 1689 # redirect with 404 to prevent resource discovery
1589 1690 raise HTTPNotFound()
1590 1691
1591 1692 def check_permissions(self, user):
1592 1693 """Dummy function for overriding"""
1593 1694 raise NotImplementedError(
1594 1695 'You have to write this function in child class')
1595 1696
1596 1697
1597 1698 class HasPermissionAllDecorator(PermsDecorator):
1598 1699 """
1599 1700 Checks for access permission for all given predicates. All of them
1600 1701 have to be meet in order to fulfill the request
1601 1702 """
1602 1703
1603 1704 def check_permissions(self, user):
1604 1705 perms = user.permissions_with_scope({})
1605 1706 if self.required_perms.issubset(perms['global']):
1606 1707 return True
1607 1708 return False
1608 1709
1609 1710
1610 1711 class HasPermissionAnyDecorator(PermsDecorator):
1611 1712 """
1612 1713 Checks for access permission for any of given predicates. In order to
1613 1714 fulfill the request any of predicates must be meet
1614 1715 """
1615 1716
1616 1717 def check_permissions(self, user):
1617 1718 perms = user.permissions_with_scope({})
1618 1719 if self.required_perms.intersection(perms['global']):
1619 1720 return True
1620 1721 return False
1621 1722
1622 1723
1623 1724 class HasRepoPermissionAllDecorator(PermsDecorator):
1624 1725 """
1625 1726 Checks for access permission for all given predicates for specific
1626 1727 repository. All of them have to be meet in order to fulfill the request
1627 1728 """
1628 1729 def _get_repo_name(self):
1629 1730 _request = self._get_request()
1630 1731 return get_repo_slug(_request)
1631 1732
1632 1733 def check_permissions(self, user):
1633 1734 perms = user.permissions
1634 1735 repo_name = self._get_repo_name()
1635 1736
1636 1737 try:
1637 1738 user_perms = {perms['repositories'][repo_name]}
1638 1739 except KeyError:
1639 1740 log.debug('cannot locate repo with name: `%s` in permissions defs',
1640 1741 repo_name)
1641 1742 return False
1642 1743
1643 1744 log.debug('checking `%s` permissions for repo `%s`',
1644 1745 user_perms, repo_name)
1645 1746 if self.required_perms.issubset(user_perms):
1646 1747 return True
1647 1748 return False
1648 1749
1649 1750
1650 1751 class HasRepoPermissionAnyDecorator(PermsDecorator):
1651 1752 """
1652 1753 Checks for access permission for any of given predicates for specific
1653 1754 repository. In order to fulfill the request any of predicates must be meet
1654 1755 """
1655 1756 def _get_repo_name(self):
1656 1757 _request = self._get_request()
1657 1758 return get_repo_slug(_request)
1658 1759
1659 1760 def check_permissions(self, user):
1660 1761 perms = user.permissions
1661 1762 repo_name = self._get_repo_name()
1662 1763
1663 1764 try:
1664 1765 user_perms = {perms['repositories'][repo_name]}
1665 1766 except KeyError:
1666 1767 log.debug(
1667 1768 'cannot locate repo with name: `%s` in permissions defs',
1668 1769 repo_name)
1669 1770 return False
1670 1771
1671 1772 log.debug('checking `%s` permissions for repo `%s`',
1672 1773 user_perms, repo_name)
1673 1774 if self.required_perms.intersection(user_perms):
1674 1775 return True
1675 1776 return False
1676 1777
1677 1778
1678 1779 class HasRepoGroupPermissionAllDecorator(PermsDecorator):
1679 1780 """
1680 1781 Checks for access permission for all given predicates for specific
1681 1782 repository group. All of them have to be meet in order to
1682 1783 fulfill the request
1683 1784 """
1684 1785 def _get_repo_group_name(self):
1685 1786 _request = self._get_request()
1686 1787 return get_repo_group_slug(_request)
1687 1788
1688 1789 def check_permissions(self, user):
1689 1790 perms = user.permissions
1690 1791 group_name = self._get_repo_group_name()
1691 1792 try:
1692 1793 user_perms = {perms['repositories_groups'][group_name]}
1693 1794 except KeyError:
1694 1795 log.debug(
1695 1796 'cannot locate repo group with name: `%s` in permissions defs',
1696 1797 group_name)
1697 1798 return False
1698 1799
1699 1800 log.debug('checking `%s` permissions for repo group `%s`',
1700 1801 user_perms, group_name)
1701 1802 if self.required_perms.issubset(user_perms):
1702 1803 return True
1703 1804 return False
1704 1805
1705 1806
1706 1807 class HasRepoGroupPermissionAnyDecorator(PermsDecorator):
1707 1808 """
1708 1809 Checks for access permission for any of given predicates for specific
1709 1810 repository group. In order to fulfill the request any
1710 1811 of predicates must be met
1711 1812 """
1712 1813 def _get_repo_group_name(self):
1713 1814 _request = self._get_request()
1714 1815 return get_repo_group_slug(_request)
1715 1816
1716 1817 def check_permissions(self, user):
1717 1818 perms = user.permissions
1718 1819 group_name = self._get_repo_group_name()
1719 1820
1720 1821 try:
1721 1822 user_perms = {perms['repositories_groups'][group_name]}
1722 1823 except KeyError:
1723 1824 log.debug(
1724 1825 'cannot locate repo group with name: `%s` in permissions defs',
1725 1826 group_name)
1726 1827 return False
1727 1828
1728 1829 log.debug('checking `%s` permissions for repo group `%s`',
1729 1830 user_perms, group_name)
1730 1831 if self.required_perms.intersection(user_perms):
1731 1832 return True
1732 1833 return False
1733 1834
1734 1835
1735 1836 class HasUserGroupPermissionAllDecorator(PermsDecorator):
1736 1837 """
1737 1838 Checks for access permission for all given predicates for specific
1738 1839 user group. All of them have to be meet in order to fulfill the request
1739 1840 """
1740 1841 def _get_user_group_name(self):
1741 1842 _request = self._get_request()
1742 1843 return get_user_group_slug(_request)
1743 1844
1744 1845 def check_permissions(self, user):
1745 1846 perms = user.permissions
1746 1847 group_name = self._get_user_group_name()
1747 1848 try:
1748 1849 user_perms = {perms['user_groups'][group_name]}
1749 1850 except KeyError:
1750 1851 return False
1751 1852
1752 1853 if self.required_perms.issubset(user_perms):
1753 1854 return True
1754 1855 return False
1755 1856
1756 1857
1757 1858 class HasUserGroupPermissionAnyDecorator(PermsDecorator):
1758 1859 """
1759 1860 Checks for access permission for any of given predicates for specific
1760 1861 user group. In order to fulfill the request any of predicates must be meet
1761 1862 """
1762 1863 def _get_user_group_name(self):
1763 1864 _request = self._get_request()
1764 1865 return get_user_group_slug(_request)
1765 1866
1766 1867 def check_permissions(self, user):
1767 1868 perms = user.permissions
1768 1869 group_name = self._get_user_group_name()
1769 1870 try:
1770 1871 user_perms = {perms['user_groups'][group_name]}
1771 1872 except KeyError:
1772 1873 return False
1773 1874
1774 1875 if self.required_perms.intersection(user_perms):
1775 1876 return True
1776 1877 return False
1777 1878
1778 1879
1779 1880 # CHECK FUNCTIONS
1780 1881 class PermsFunction(object):
1781 1882 """Base function for other check functions"""
1782 1883
1783 1884 def __init__(self, *perms):
1784 1885 self.required_perms = set(perms)
1785 1886 self.repo_name = None
1786 1887 self.repo_group_name = None
1787 1888 self.user_group_name = None
1788 1889
1789 1890 def __bool__(self):
1790 1891 frame = inspect.currentframe()
1791 1892 stack_trace = traceback.format_stack(frame)
1792 1893 log.error('Checking bool value on a class instance of perm '
1793 1894 'function is not allowed: %s' % ''.join(stack_trace))
1794 1895 # rather than throwing errors, here we always return False so if by
1795 1896 # accident someone checks truth for just an instance it will always end
1796 1897 # up in returning False
1797 1898 return False
1798 1899 __nonzero__ = __bool__
1799 1900
1800 1901 def __call__(self, check_location='', user=None):
1801 1902 if not user:
1802 1903 log.debug('Using user attribute from global request')
1803 # TODO: remove this someday,put as user as attribute here
1804 1904 request = self._get_request()
1805 1905 user = request.user
1806 1906
1807 1907 # init auth user if not already given
1808 1908 if not isinstance(user, AuthUser):
1809 1909 log.debug('Wrapping user %s into AuthUser', user)
1810 1910 user = AuthUser(user.user_id)
1811 1911
1812 1912 cls_name = self.__class__.__name__
1813 1913 check_scope = self._get_check_scope(cls_name)
1814 1914 check_location = check_location or 'unspecified location'
1815 1915
1816 1916 log.debug('checking cls:%s %s usr:%s %s @ %s', cls_name,
1817 1917 self.required_perms, user, check_scope, check_location)
1818 1918 if not user:
1819 1919 log.warning('Empty user given for permission check')
1820 1920 return False
1821 1921
1822 1922 if self.check_permissions(user):
1823 1923 log.debug('Permission to repo:`%s` GRANTED for user:`%s` @ %s',
1824 1924 check_scope, user, check_location)
1825 1925 return True
1826 1926
1827 1927 else:
1828 1928 log.debug('Permission to repo:`%s` DENIED for user:`%s` @ %s',
1829 1929 check_scope, user, check_location)
1830 1930 return False
1831 1931
1832 1932 def _get_request(self):
1833 1933 return get_request(self)
1834 1934
1835 1935 def _get_check_scope(self, cls_name):
1836 1936 return {
1837 1937 'HasPermissionAll': 'GLOBAL',
1838 1938 'HasPermissionAny': 'GLOBAL',
1839 1939 'HasRepoPermissionAll': 'repo:%s' % self.repo_name,
1840 1940 'HasRepoPermissionAny': 'repo:%s' % self.repo_name,
1841 1941 'HasRepoGroupPermissionAll': 'repo_group:%s' % self.repo_group_name,
1842 1942 'HasRepoGroupPermissionAny': 'repo_group:%s' % self.repo_group_name,
1843 1943 'HasUserGroupPermissionAll': 'user_group:%s' % self.user_group_name,
1844 1944 'HasUserGroupPermissionAny': 'user_group:%s' % self.user_group_name,
1845 1945 }.get(cls_name, '?:%s' % cls_name)
1846 1946
1847 1947 def check_permissions(self, user):
1848 1948 """Dummy function for overriding"""
1849 1949 raise Exception('You have to write this function in child class')
1850 1950
1851 1951
1852 1952 class HasPermissionAll(PermsFunction):
1853 1953 def check_permissions(self, user):
1854 1954 perms = user.permissions_with_scope({})
1855 1955 if self.required_perms.issubset(perms.get('global')):
1856 1956 return True
1857 1957 return False
1858 1958
1859 1959
1860 1960 class HasPermissionAny(PermsFunction):
1861 1961 def check_permissions(self, user):
1862 1962 perms = user.permissions_with_scope({})
1863 1963 if self.required_perms.intersection(perms.get('global')):
1864 1964 return True
1865 1965 return False
1866 1966
1867 1967
1868 1968 class HasRepoPermissionAll(PermsFunction):
1869 1969 def __call__(self, repo_name=None, check_location='', user=None):
1870 1970 self.repo_name = repo_name
1871 1971 return super(HasRepoPermissionAll, self).__call__(check_location, user)
1872 1972
1873 1973 def _get_repo_name(self):
1874 1974 if not self.repo_name:
1875 1975 _request = self._get_request()
1876 1976 self.repo_name = get_repo_slug(_request)
1877 1977 return self.repo_name
1878 1978
1879 1979 def check_permissions(self, user):
1880 1980 self.repo_name = self._get_repo_name()
1881 1981 perms = user.permissions
1882 1982 try:
1883 1983 user_perms = {perms['repositories'][self.repo_name]}
1884 1984 except KeyError:
1885 1985 return False
1886 1986 if self.required_perms.issubset(user_perms):
1887 1987 return True
1888 1988 return False
1889 1989
1890 1990
1891 1991 class HasRepoPermissionAny(PermsFunction):
1892 1992 def __call__(self, repo_name=None, check_location='', user=None):
1893 1993 self.repo_name = repo_name
1894 1994 return super(HasRepoPermissionAny, self).__call__(check_location, user)
1895 1995
1896 1996 def _get_repo_name(self):
1897 1997 if not self.repo_name:
1898 1998 _request = self._get_request()
1899 1999 self.repo_name = get_repo_slug(_request)
1900 2000 return self.repo_name
1901 2001
1902 2002 def check_permissions(self, user):
1903 2003 self.repo_name = self._get_repo_name()
1904 2004 perms = user.permissions
1905 2005 try:
1906 2006 user_perms = {perms['repositories'][self.repo_name]}
1907 2007 except KeyError:
1908 2008 return False
1909 2009 if self.required_perms.intersection(user_perms):
1910 2010 return True
1911 2011 return False
1912 2012
1913 2013
1914 2014 class HasRepoGroupPermissionAny(PermsFunction):
1915 2015 def __call__(self, group_name=None, check_location='', user=None):
1916 2016 self.repo_group_name = group_name
1917 2017 return super(HasRepoGroupPermissionAny, self).__call__(
1918 2018 check_location, user)
1919 2019
1920 2020 def check_permissions(self, user):
1921 2021 perms = user.permissions
1922 2022 try:
1923 2023 user_perms = {perms['repositories_groups'][self.repo_group_name]}
1924 2024 except KeyError:
1925 2025 return False
1926 2026 if self.required_perms.intersection(user_perms):
1927 2027 return True
1928 2028 return False
1929 2029
1930 2030
1931 2031 class HasRepoGroupPermissionAll(PermsFunction):
1932 2032 def __call__(self, group_name=None, check_location='', user=None):
1933 2033 self.repo_group_name = group_name
1934 2034 return super(HasRepoGroupPermissionAll, self).__call__(
1935 2035 check_location, user)
1936 2036
1937 2037 def check_permissions(self, user):
1938 2038 perms = user.permissions
1939 2039 try:
1940 2040 user_perms = {perms['repositories_groups'][self.repo_group_name]}
1941 2041 except KeyError:
1942 2042 return False
1943 2043 if self.required_perms.issubset(user_perms):
1944 2044 return True
1945 2045 return False
1946 2046
1947 2047
1948 2048 class HasUserGroupPermissionAny(PermsFunction):
1949 2049 def __call__(self, user_group_name=None, check_location='', user=None):
1950 2050 self.user_group_name = user_group_name
1951 2051 return super(HasUserGroupPermissionAny, self).__call__(
1952 2052 check_location, user)
1953 2053
1954 2054 def check_permissions(self, user):
1955 2055 perms = user.permissions
1956 2056 try:
1957 2057 user_perms = {perms['user_groups'][self.user_group_name]}
1958 2058 except KeyError:
1959 2059 return False
1960 2060 if self.required_perms.intersection(user_perms):
1961 2061 return True
1962 2062 return False
1963 2063
1964 2064
1965 2065 class HasUserGroupPermissionAll(PermsFunction):
1966 2066 def __call__(self, user_group_name=None, check_location='', user=None):
1967 2067 self.user_group_name = user_group_name
1968 2068 return super(HasUserGroupPermissionAll, self).__call__(
1969 2069 check_location, user)
1970 2070
1971 2071 def check_permissions(self, user):
1972 2072 perms = user.permissions
1973 2073 try:
1974 2074 user_perms = {perms['user_groups'][self.user_group_name]}
1975 2075 except KeyError:
1976 2076 return False
1977 2077 if self.required_perms.issubset(user_perms):
1978 2078 return True
1979 2079 return False
1980 2080
1981 2081
1982 2082 # SPECIAL VERSION TO HANDLE MIDDLEWARE AUTH
1983 2083 class HasPermissionAnyMiddleware(object):
1984 2084 def __init__(self, *perms):
1985 2085 self.required_perms = set(perms)
1986 2086
1987 2087 def __call__(self, user, repo_name):
1988 2088 # repo_name MUST be unicode, since we handle keys in permission
1989 2089 # dict by unicode
1990 2090 repo_name = safe_unicode(repo_name)
1991 2091 user = AuthUser(user.user_id)
1992 2092 log.debug(
1993 2093 'Checking VCS protocol permissions %s for user:%s repo:`%s`',
1994 2094 self.required_perms, user, repo_name)
1995 2095
1996 2096 if self.check_permissions(user, repo_name):
1997 2097 log.debug('Permission to repo:`%s` GRANTED for user:%s @ %s',
1998 2098 repo_name, user, 'PermissionMiddleware')
1999 2099 return True
2000 2100
2001 2101 else:
2002 2102 log.debug('Permission to repo:`%s` DENIED for user:%s @ %s',
2003 2103 repo_name, user, 'PermissionMiddleware')
2004 2104 return False
2005 2105
2006 2106 def check_permissions(self, user, repo_name):
2007 2107 perms = user.permissions_with_scope({'repo_name': repo_name})
2008 2108
2009 2109 try:
2010 2110 user_perms = {perms['repositories'][repo_name]}
2011 2111 except Exception:
2012 2112 log.exception('Error while accessing user permissions')
2013 2113 return False
2014 2114
2015 2115 if self.required_perms.intersection(user_perms):
2016 2116 return True
2017 2117 return False
2018 2118
2019 2119
2020 2120 # SPECIAL VERSION TO HANDLE API AUTH
2021 2121 class _BaseApiPerm(object):
2022 2122 def __init__(self, *perms):
2023 2123 self.required_perms = set(perms)
2024 2124
2025 2125 def __call__(self, check_location=None, user=None, repo_name=None,
2026 2126 group_name=None, user_group_name=None):
2027 2127 cls_name = self.__class__.__name__
2028 2128 check_scope = 'global:%s' % (self.required_perms,)
2029 2129 if repo_name:
2030 2130 check_scope += ', repo_name:%s' % (repo_name,)
2031 2131
2032 2132 if group_name:
2033 2133 check_scope += ', repo_group_name:%s' % (group_name,)
2034 2134
2035 2135 if user_group_name:
2036 2136 check_scope += ', user_group_name:%s' % (user_group_name,)
2037 2137
2038 2138 log.debug(
2039 2139 'checking cls:%s %s %s @ %s'
2040 2140 % (cls_name, self.required_perms, check_scope, check_location))
2041 2141 if not user:
2042 2142 log.debug('Empty User passed into arguments')
2043 2143 return False
2044 2144
2045 2145 # process user
2046 2146 if not isinstance(user, AuthUser):
2047 2147 user = AuthUser(user.user_id)
2048 2148 if not check_location:
2049 2149 check_location = 'unspecified'
2050 2150 if self.check_permissions(user.permissions, repo_name, group_name,
2051 2151 user_group_name):
2052 2152 log.debug('Permission to repo:`%s` GRANTED for user:`%s` @ %s',
2053 2153 check_scope, user, check_location)
2054 2154 return True
2055 2155
2056 2156 else:
2057 2157 log.debug('Permission to repo:`%s` DENIED for user:`%s` @ %s',
2058 2158 check_scope, user, check_location)
2059 2159 return False
2060 2160
2061 2161 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2062 2162 user_group_name=None):
2063 2163 """
2064 2164 implement in child class should return True if permissions are ok,
2065 2165 False otherwise
2066 2166
2067 2167 :param perm_defs: dict with permission definitions
2068 2168 :param repo_name: repo name
2069 2169 """
2070 2170 raise NotImplementedError()
2071 2171
2072 2172
2073 2173 class HasPermissionAllApi(_BaseApiPerm):
2074 2174 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2075 2175 user_group_name=None):
2076 2176 if self.required_perms.issubset(perm_defs.get('global')):
2077 2177 return True
2078 2178 return False
2079 2179
2080 2180
2081 2181 class HasPermissionAnyApi(_BaseApiPerm):
2082 2182 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2083 2183 user_group_name=None):
2084 2184 if self.required_perms.intersection(perm_defs.get('global')):
2085 2185 return True
2086 2186 return False
2087 2187
2088 2188
2089 2189 class HasRepoPermissionAllApi(_BaseApiPerm):
2090 2190 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2091 2191 user_group_name=None):
2092 2192 try:
2093 2193 _user_perms = {perm_defs['repositories'][repo_name]}
2094 2194 except KeyError:
2095 2195 log.warning(traceback.format_exc())
2096 2196 return False
2097 2197 if self.required_perms.issubset(_user_perms):
2098 2198 return True
2099 2199 return False
2100 2200
2101 2201
2102 2202 class HasRepoPermissionAnyApi(_BaseApiPerm):
2103 2203 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2104 2204 user_group_name=None):
2105 2205 try:
2106 2206 _user_perms = {perm_defs['repositories'][repo_name]}
2107 2207 except KeyError:
2108 2208 log.warning(traceback.format_exc())
2109 2209 return False
2110 2210 if self.required_perms.intersection(_user_perms):
2111 2211 return True
2112 2212 return False
2113 2213
2114 2214
2115 2215 class HasRepoGroupPermissionAnyApi(_BaseApiPerm):
2116 2216 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2117 2217 user_group_name=None):
2118 2218 try:
2119 2219 _user_perms = {perm_defs['repositories_groups'][group_name]}
2120 2220 except KeyError:
2121 2221 log.warning(traceback.format_exc())
2122 2222 return False
2123 2223 if self.required_perms.intersection(_user_perms):
2124 2224 return True
2125 2225 return False
2126 2226
2127 2227
2128 2228 class HasRepoGroupPermissionAllApi(_BaseApiPerm):
2129 2229 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2130 2230 user_group_name=None):
2131 2231 try:
2132 2232 _user_perms = {perm_defs['repositories_groups'][group_name]}
2133 2233 except KeyError:
2134 2234 log.warning(traceback.format_exc())
2135 2235 return False
2136 2236 if self.required_perms.issubset(_user_perms):
2137 2237 return True
2138 2238 return False
2139 2239
2140 2240
2141 2241 class HasUserGroupPermissionAnyApi(_BaseApiPerm):
2142 2242 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2143 2243 user_group_name=None):
2144 2244 try:
2145 2245 _user_perms = {perm_defs['user_groups'][user_group_name]}
2146 2246 except KeyError:
2147 2247 log.warning(traceback.format_exc())
2148 2248 return False
2149 2249 if self.required_perms.intersection(_user_perms):
2150 2250 return True
2151 2251 return False
2152 2252
2153 2253
2154 2254 def check_ip_access(source_ip, allowed_ips=None):
2155 2255 """
2156 2256 Checks if source_ip is a subnet of any of allowed_ips.
2157 2257
2158 2258 :param source_ip:
2159 2259 :param allowed_ips: list of allowed ips together with mask
2160 2260 """
2161 2261 log.debug('checking if ip:%s is subnet of %s' % (source_ip, allowed_ips))
2162 2262 source_ip_address = ipaddress.ip_address(safe_unicode(source_ip))
2163 2263 if isinstance(allowed_ips, (tuple, list, set)):
2164 2264 for ip in allowed_ips:
2165 2265 ip = safe_unicode(ip)
2166 2266 try:
2167 2267 network_address = ipaddress.ip_network(ip, strict=False)
2168 2268 if source_ip_address in network_address:
2169 2269 log.debug('IP %s is network %s' %
2170 2270 (source_ip_address, network_address))
2171 2271 return True
2172 2272 # for any case we cannot determine the IP, don't crash just
2173 2273 # skip it and log as error, we want to say forbidden still when
2174 2274 # sending bad IP
2175 2275 except Exception:
2176 2276 log.error(traceback.format_exc())
2177 2277 continue
2178 2278 return False
2179 2279
2180 2280
2181 2281 def get_cython_compat_decorator(wrapper, func):
2182 2282 """
2183 2283 Creates a cython compatible decorator. The previously used
2184 2284 decorator.decorator() function seems to be incompatible with cython.
2185 2285
2186 2286 :param wrapper: __wrapper method of the decorator class
2187 2287 :param func: decorated function
2188 2288 """
2189 2289 @wraps(func)
2190 2290 def local_wrapper(*args, **kwds):
2191 2291 return wrapper(func, *args, **kwds)
2192 2292 local_wrapper.__wrapped__ = func
2193 2293 return local_wrapper
2194 2294
2195 2295
@@ -1,1004 +1,1011 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2011-2018 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 """
23 23 Some simple helper functions
24 24 """
25 25
26 26 import collections
27 27 import datetime
28 28 import dateutil.relativedelta
29 29 import hashlib
30 30 import logging
31 31 import re
32 32 import sys
33 33 import time
34 34 import urllib
35 35 import urlobject
36 36 import uuid
37 37 import getpass
38 38
39 39 import pygments.lexers
40 40 import sqlalchemy
41 41 import sqlalchemy.engine.url
42 42 import sqlalchemy.exc
43 43 import sqlalchemy.sql
44 44 import webob
45 45 import pyramid.threadlocal
46 46
47 47 import rhodecode
48 48 from rhodecode.translation import _, _pluralize
49 49
50 50
51 51 def md5(s):
52 52 return hashlib.md5(s).hexdigest()
53 53
54 54
55 55 def md5_safe(s):
56 56 return md5(safe_str(s))
57 57
58 58
59 59 def sha1(s):
60 60 return hashlib.sha1(s).hexdigest()
61 61
62 62
63 63 def sha1_safe(s):
64 64 return sha1(safe_str(s))
65 65
66 66
67 67 def __get_lem(extra_mapping=None):
68 68 """
69 69 Get language extension map based on what's inside pygments lexers
70 70 """
71 71 d = collections.defaultdict(lambda: [])
72 72
73 73 def __clean(s):
74 74 s = s.lstrip('*')
75 75 s = s.lstrip('.')
76 76
77 77 if s.find('[') != -1:
78 78 exts = []
79 79 start, stop = s.find('['), s.find(']')
80 80
81 81 for suffix in s[start + 1:stop]:
82 82 exts.append(s[:s.find('[')] + suffix)
83 83 return [e.lower() for e in exts]
84 84 else:
85 85 return [s.lower()]
86 86
87 87 for lx, t in sorted(pygments.lexers.LEXERS.items()):
88 88 m = map(__clean, t[-2])
89 89 if m:
90 90 m = reduce(lambda x, y: x + y, m)
91 91 for ext in m:
92 92 desc = lx.replace('Lexer', '')
93 93 d[ext].append(desc)
94 94
95 95 data = dict(d)
96 96
97 97 extra_mapping = extra_mapping or {}
98 98 if extra_mapping:
99 99 for k, v in extra_mapping.items():
100 100 if k not in data:
101 101 # register new mapping2lexer
102 102 data[k] = [v]
103 103
104 104 return data
105 105
106 106
107 107 def str2bool(_str):
108 108 """
109 109 returns True/False value from given string, it tries to translate the
110 110 string into boolean
111 111
112 112 :param _str: string value to translate into boolean
113 113 :rtype: boolean
114 114 :returns: boolean from given string
115 115 """
116 116 if _str is None:
117 117 return False
118 118 if _str in (True, False):
119 119 return _str
120 120 _str = str(_str).strip().lower()
121 121 return _str in ('t', 'true', 'y', 'yes', 'on', '1')
122 122
123 123
124 124 def aslist(obj, sep=None, strip=True):
125 125 """
126 126 Returns given string separated by sep as list
127 127
128 128 :param obj:
129 129 :param sep:
130 130 :param strip:
131 131 """
132 132 if isinstance(obj, (basestring,)):
133 133 lst = obj.split(sep)
134 134 if strip:
135 135 lst = [v.strip() for v in lst]
136 136 return lst
137 137 elif isinstance(obj, (list, tuple)):
138 138 return obj
139 139 elif obj is None:
140 140 return []
141 141 else:
142 142 return [obj]
143 143
144 144
145 145 def convert_line_endings(line, mode):
146 146 """
147 147 Converts a given line "line end" accordingly to given mode
148 148
149 149 Available modes are::
150 150 0 - Unix
151 151 1 - Mac
152 152 2 - DOS
153 153
154 154 :param line: given line to convert
155 155 :param mode: mode to convert to
156 156 :rtype: str
157 157 :return: converted line according to mode
158 158 """
159 159 if mode == 0:
160 160 line = line.replace('\r\n', '\n')
161 161 line = line.replace('\r', '\n')
162 162 elif mode == 1:
163 163 line = line.replace('\r\n', '\r')
164 164 line = line.replace('\n', '\r')
165 165 elif mode == 2:
166 166 line = re.sub('\r(?!\n)|(?<!\r)\n', '\r\n', line)
167 167 return line
168 168
169 169
170 170 def detect_mode(line, default):
171 171 """
172 172 Detects line break for given line, if line break couldn't be found
173 173 given default value is returned
174 174
175 175 :param line: str line
176 176 :param default: default
177 177 :rtype: int
178 178 :return: value of line end on of 0 - Unix, 1 - Mac, 2 - DOS
179 179 """
180 180 if line.endswith('\r\n'):
181 181 return 2
182 182 elif line.endswith('\n'):
183 183 return 0
184 184 elif line.endswith('\r'):
185 185 return 1
186 186 else:
187 187 return default
188 188
189 189
190 190 def safe_int(val, default=None):
191 191 """
192 192 Returns int() of val if val is not convertable to int use default
193 193 instead
194 194
195 195 :param val:
196 196 :param default:
197 197 """
198 198
199 199 try:
200 200 val = int(val)
201 201 except (ValueError, TypeError):
202 202 val = default
203 203
204 204 return val
205 205
206 206
207 207 def safe_unicode(str_, from_encoding=None):
208 208 """
209 209 safe unicode function. Does few trick to turn str_ into unicode
210 210
211 211 In case of UnicodeDecode error, we try to return it with encoding detected
212 212 by chardet library if it fails fallback to unicode with errors replaced
213 213
214 214 :param str_: string to decode
215 215 :rtype: unicode
216 216 :returns: unicode object
217 217 """
218 218 if isinstance(str_, unicode):
219 219 return str_
220 220
221 221 if not from_encoding:
222 222 DEFAULT_ENCODINGS = aslist(rhodecode.CONFIG.get('default_encoding',
223 223 'utf8'), sep=',')
224 224 from_encoding = DEFAULT_ENCODINGS
225 225
226 226 if not isinstance(from_encoding, (list, tuple)):
227 227 from_encoding = [from_encoding]
228 228
229 229 try:
230 230 return unicode(str_)
231 231 except UnicodeDecodeError:
232 232 pass
233 233
234 234 for enc in from_encoding:
235 235 try:
236 236 return unicode(str_, enc)
237 237 except UnicodeDecodeError:
238 238 pass
239 239
240 240 try:
241 241 import chardet
242 242 encoding = chardet.detect(str_)['encoding']
243 243 if encoding is None:
244 244 raise Exception()
245 245 return str_.decode(encoding)
246 246 except (ImportError, UnicodeDecodeError, Exception):
247 247 return unicode(str_, from_encoding[0], 'replace')
248 248
249 249
250 250 def safe_str(unicode_, to_encoding=None):
251 251 """
252 252 safe str function. Does few trick to turn unicode_ into string
253 253
254 254 In case of UnicodeEncodeError, we try to return it with encoding detected
255 255 by chardet library if it fails fallback to string with errors replaced
256 256
257 257 :param unicode_: unicode to encode
258 258 :rtype: str
259 259 :returns: str object
260 260 """
261 261
262 262 # if it's not basestr cast to str
263 263 if not isinstance(unicode_, basestring):
264 264 return str(unicode_)
265 265
266 266 if isinstance(unicode_, str):
267 267 return unicode_
268 268
269 269 if not to_encoding:
270 270 DEFAULT_ENCODINGS = aslist(rhodecode.CONFIG.get('default_encoding',
271 271 'utf8'), sep=',')
272 272 to_encoding = DEFAULT_ENCODINGS
273 273
274 274 if not isinstance(to_encoding, (list, tuple)):
275 275 to_encoding = [to_encoding]
276 276
277 277 for enc in to_encoding:
278 278 try:
279 279 return unicode_.encode(enc)
280 280 except UnicodeEncodeError:
281 281 pass
282 282
283 283 try:
284 284 import chardet
285 285 encoding = chardet.detect(unicode_)['encoding']
286 286 if encoding is None:
287 287 raise UnicodeEncodeError()
288 288
289 289 return unicode_.encode(encoding)
290 290 except (ImportError, UnicodeEncodeError):
291 291 return unicode_.encode(to_encoding[0], 'replace')
292 292
293 293
294 294 def remove_suffix(s, suffix):
295 295 if s.endswith(suffix):
296 296 s = s[:-1 * len(suffix)]
297 297 return s
298 298
299 299
300 300 def remove_prefix(s, prefix):
301 301 if s.startswith(prefix):
302 302 s = s[len(prefix):]
303 303 return s
304 304
305 305
306 306 def find_calling_context(ignore_modules=None):
307 307 """
308 308 Look through the calling stack and return the frame which called
309 309 this function and is part of core module ( ie. rhodecode.* )
310 310
311 311 :param ignore_modules: list of modules to ignore eg. ['rhodecode.lib']
312 312 """
313 313
314 314 ignore_modules = ignore_modules or []
315 315
316 316 f = sys._getframe(2)
317 317 while f.f_back is not None:
318 318 name = f.f_globals.get('__name__')
319 319 if name and name.startswith(__name__.split('.')[0]):
320 320 if name not in ignore_modules:
321 321 return f
322 322 f = f.f_back
323 323 return None
324 324
325 325
326 326 def ping_connection(connection, branch):
327 327 if branch:
328 328 # "branch" refers to a sub-connection of a connection,
329 329 # we don't want to bother pinging on these.
330 330 return
331 331
332 332 # turn off "close with result". This flag is only used with
333 333 # "connectionless" execution, otherwise will be False in any case
334 334 save_should_close_with_result = connection.should_close_with_result
335 335 connection.should_close_with_result = False
336 336
337 337 try:
338 338 # run a SELECT 1. use a core select() so that
339 339 # the SELECT of a scalar value without a table is
340 340 # appropriately formatted for the backend
341 341 connection.scalar(sqlalchemy.sql.select([1]))
342 342 except sqlalchemy.exc.DBAPIError as err:
343 343 # catch SQLAlchemy's DBAPIError, which is a wrapper
344 344 # for the DBAPI's exception. It includes a .connection_invalidated
345 345 # attribute which specifies if this connection is a "disconnect"
346 346 # condition, which is based on inspection of the original exception
347 347 # by the dialect in use.
348 348 if err.connection_invalidated:
349 349 # run the same SELECT again - the connection will re-validate
350 350 # itself and establish a new connection. The disconnect detection
351 351 # here also causes the whole connection pool to be invalidated
352 352 # so that all stale connections are discarded.
353 353 connection.scalar(sqlalchemy.sql.select([1]))
354 354 else:
355 355 raise
356 356 finally:
357 357 # restore "close with result"
358 358 connection.should_close_with_result = save_should_close_with_result
359 359
360 360
361 361 def engine_from_config(configuration, prefix='sqlalchemy.', **kwargs):
362 362 """Custom engine_from_config functions."""
363 363 log = logging.getLogger('sqlalchemy.engine')
364 364 _ping_connection = configuration.pop('sqlalchemy.db1.ping_connection', None)
365 365
366 366 engine = sqlalchemy.engine_from_config(configuration, prefix, **kwargs)
367 367
368 368 def color_sql(sql):
369 369 color_seq = '\033[1;33m' # This is yellow: code 33
370 370 normal = '\x1b[0m'
371 371 return ''.join([color_seq, sql, normal])
372 372
373 373 if configuration['debug'] or _ping_connection:
374 374 sqlalchemy.event.listen(engine, "engine_connect", ping_connection)
375 375
376 376 if configuration['debug']:
377 377 # attach events only for debug configuration
378 378
379 379 def before_cursor_execute(conn, cursor, statement,
380 380 parameters, context, executemany):
381 381 setattr(conn, 'query_start_time', time.time())
382 382 log.info(color_sql(">>>>> STARTING QUERY >>>>>"))
383 383 calling_context = find_calling_context(ignore_modules=[
384 384 'rhodecode.lib.caching_query',
385 385 'rhodecode.model.settings',
386 386 ])
387 387 if calling_context:
388 388 log.info(color_sql('call context %s:%s' % (
389 389 calling_context.f_code.co_filename,
390 390 calling_context.f_lineno,
391 391 )))
392 392
393 393 def after_cursor_execute(conn, cursor, statement,
394 394 parameters, context, executemany):
395 395 delattr(conn, 'query_start_time')
396 396
397 397 sqlalchemy.event.listen(engine, "before_cursor_execute",
398 398 before_cursor_execute)
399 399 sqlalchemy.event.listen(engine, "after_cursor_execute",
400 400 after_cursor_execute)
401 401
402 402 return engine
403 403
404 404
405 405 def get_encryption_key(config):
406 406 secret = config.get('rhodecode.encrypted_values.secret')
407 407 default = config['beaker.session.secret']
408 408 return secret or default
409 409
410 410
411 411 def age(prevdate, now=None, show_short_version=False, show_suffix=True,
412 412 short_format=False):
413 413 """
414 414 Turns a datetime into an age string.
415 415 If show_short_version is True, this generates a shorter string with
416 416 an approximate age; ex. '1 day ago', rather than '1 day and 23 hours ago'.
417 417
418 418 * IMPORTANT*
419 419 Code of this function is written in special way so it's easier to
420 420 backport it to javascript. If you mean to update it, please also update
421 421 `jquery.timeago-extension.js` file
422 422
423 423 :param prevdate: datetime object
424 424 :param now: get current time, if not define we use
425 425 `datetime.datetime.now()`
426 426 :param show_short_version: if it should approximate the date and
427 427 return a shorter string
428 428 :param show_suffix:
429 429 :param short_format: show short format, eg 2D instead of 2 days
430 430 :rtype: unicode
431 431 :returns: unicode words describing age
432 432 """
433 433
434 434 def _get_relative_delta(now, prevdate):
435 435 base = dateutil.relativedelta.relativedelta(now, prevdate)
436 436 return {
437 437 'year': base.years,
438 438 'month': base.months,
439 439 'day': base.days,
440 440 'hour': base.hours,
441 441 'minute': base.minutes,
442 442 'second': base.seconds,
443 443 }
444 444
445 445 def _is_leap_year(year):
446 446 return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
447 447
448 448 def get_month(prevdate):
449 449 return prevdate.month
450 450
451 451 def get_year(prevdate):
452 452 return prevdate.year
453 453
454 454 now = now or datetime.datetime.now()
455 455 order = ['year', 'month', 'day', 'hour', 'minute', 'second']
456 456 deltas = {}
457 457 future = False
458 458
459 459 if prevdate > now:
460 460 now_old = now
461 461 now = prevdate
462 462 prevdate = now_old
463 463 future = True
464 464 if future:
465 465 prevdate = prevdate.replace(microsecond=0)
466 466 # Get date parts deltas
467 467 for part in order:
468 468 rel_delta = _get_relative_delta(now, prevdate)
469 469 deltas[part] = rel_delta[part]
470 470
471 471 # Fix negative offsets (there is 1 second between 10:59:59 and 11:00:00,
472 472 # not 1 hour, -59 minutes and -59 seconds)
473 473 offsets = [[5, 60], [4, 60], [3, 24]]
474 474 for element in offsets: # seconds, minutes, hours
475 475 num = element[0]
476 476 length = element[1]
477 477
478 478 part = order[num]
479 479 carry_part = order[num - 1]
480 480
481 481 if deltas[part] < 0:
482 482 deltas[part] += length
483 483 deltas[carry_part] -= 1
484 484
485 485 # Same thing for days except that the increment depends on the (variable)
486 486 # number of days in the month
487 487 month_lengths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
488 488 if deltas['day'] < 0:
489 489 if get_month(prevdate) == 2 and _is_leap_year(get_year(prevdate)):
490 490 deltas['day'] += 29
491 491 else:
492 492 deltas['day'] += month_lengths[get_month(prevdate) - 1]
493 493
494 494 deltas['month'] -= 1
495 495
496 496 if deltas['month'] < 0:
497 497 deltas['month'] += 12
498 498 deltas['year'] -= 1
499 499
500 500 # Format the result
501 501 if short_format:
502 502 fmt_funcs = {
503 503 'year': lambda d: u'%dy' % d,
504 504 'month': lambda d: u'%dm' % d,
505 505 'day': lambda d: u'%dd' % d,
506 506 'hour': lambda d: u'%dh' % d,
507 507 'minute': lambda d: u'%dmin' % d,
508 508 'second': lambda d: u'%dsec' % d,
509 509 }
510 510 else:
511 511 fmt_funcs = {
512 512 'year': lambda d: _pluralize(u'${num} year', u'${num} years', d, mapping={'num': d}).interpolate(),
513 513 'month': lambda d: _pluralize(u'${num} month', u'${num} months', d, mapping={'num': d}).interpolate(),
514 514 'day': lambda d: _pluralize(u'${num} day', u'${num} days', d, mapping={'num': d}).interpolate(),
515 515 'hour': lambda d: _pluralize(u'${num} hour', u'${num} hours', d, mapping={'num': d}).interpolate(),
516 516 'minute': lambda d: _pluralize(u'${num} minute', u'${num} minutes', d, mapping={'num': d}).interpolate(),
517 517 'second': lambda d: _pluralize(u'${num} second', u'${num} seconds', d, mapping={'num': d}).interpolate(),
518 518 }
519 519
520 520 i = 0
521 521 for part in order:
522 522 value = deltas[part]
523 523 if value != 0:
524 524
525 525 if i < 5:
526 526 sub_part = order[i + 1]
527 527 sub_value = deltas[sub_part]
528 528 else:
529 529 sub_value = 0
530 530
531 531 if sub_value == 0 or show_short_version:
532 532 _val = fmt_funcs[part](value)
533 533 if future:
534 534 if show_suffix:
535 535 return _(u'in ${ago}', mapping={'ago': _val})
536 536 else:
537 537 return _(_val)
538 538
539 539 else:
540 540 if show_suffix:
541 541 return _(u'${ago} ago', mapping={'ago': _val})
542 542 else:
543 543 return _(_val)
544 544
545 545 val = fmt_funcs[part](value)
546 546 val_detail = fmt_funcs[sub_part](sub_value)
547 547 mapping = {'val': val, 'detail': val_detail}
548 548
549 549 if short_format:
550 550 datetime_tmpl = _(u'${val}, ${detail}', mapping=mapping)
551 551 if show_suffix:
552 552 datetime_tmpl = _(u'${val}, ${detail} ago', mapping=mapping)
553 553 if future:
554 554 datetime_tmpl = _(u'in ${val}, ${detail}', mapping=mapping)
555 555 else:
556 556 datetime_tmpl = _(u'${val} and ${detail}', mapping=mapping)
557 557 if show_suffix:
558 558 datetime_tmpl = _(u'${val} and ${detail} ago', mapping=mapping)
559 559 if future:
560 560 datetime_tmpl = _(u'in ${val} and ${detail}', mapping=mapping)
561 561
562 562 return datetime_tmpl
563 563 i += 1
564 564 return _(u'just now')
565 565
566 566
567 567 def cleaned_uri(uri):
568 568 """
569 569 Quotes '[' and ']' from uri if there is only one of them.
570 570 according to RFC3986 we cannot use such chars in uri
571 571 :param uri:
572 572 :return: uri without this chars
573 573 """
574 574 return urllib.quote(uri, safe='@$:/')
575 575
576 576
577 577 def uri_filter(uri):
578 578 """
579 579 Removes user:password from given url string
580 580
581 581 :param uri:
582 582 :rtype: unicode
583 583 :returns: filtered list of strings
584 584 """
585 585 if not uri:
586 586 return ''
587 587
588 588 proto = ''
589 589
590 590 for pat in ('https://', 'http://'):
591 591 if uri.startswith(pat):
592 592 uri = uri[len(pat):]
593 593 proto = pat
594 594 break
595 595
596 596 # remove passwords and username
597 597 uri = uri[uri.find('@') + 1:]
598 598
599 599 # get the port
600 600 cred_pos = uri.find(':')
601 601 if cred_pos == -1:
602 602 host, port = uri, None
603 603 else:
604 604 host, port = uri[:cred_pos], uri[cred_pos + 1:]
605 605
606 606 return filter(None, [proto, host, port])
607 607
608 608
609 609 def credentials_filter(uri):
610 610 """
611 611 Returns a url with removed credentials
612 612
613 613 :param uri:
614 614 """
615 615
616 616 uri = uri_filter(uri)
617 617 # check if we have port
618 618 if len(uri) > 2 and uri[2]:
619 619 uri[2] = ':' + uri[2]
620 620
621 621 return ''.join(uri)
622 622
623 623
624 624 def get_clone_url(request, uri_tmpl, repo_name, repo_id, **override):
625 625 qualifed_home_url = request.route_url('home')
626 626 parsed_url = urlobject.URLObject(qualifed_home_url)
627 627 decoded_path = safe_unicode(urllib.unquote(parsed_url.path.rstrip('/')))
628 628
629 629 args = {
630 630 'scheme': parsed_url.scheme,
631 631 'user': '',
632 632 'sys_user': getpass.getuser(),
633 633 # path if we use proxy-prefix
634 634 'netloc': parsed_url.netloc+decoded_path,
635 635 'hostname': parsed_url.hostname,
636 636 'prefix': decoded_path,
637 637 'repo': repo_name,
638 638 'repoid': str(repo_id)
639 639 }
640 640 args.update(override)
641 641 args['user'] = urllib.quote(safe_str(args['user']))
642 642
643 643 for k, v in args.items():
644 644 uri_tmpl = uri_tmpl.replace('{%s}' % k, v)
645 645
646 646 # remove leading @ sign if it's present. Case of empty user
647 647 url_obj = urlobject.URLObject(uri_tmpl)
648 648 url = url_obj.with_netloc(url_obj.netloc.lstrip('@'))
649 649
650 650 return safe_unicode(url)
651 651
652 652
653 653 def get_commit_safe(repo, commit_id=None, commit_idx=None, pre_load=None):
654 654 """
655 655 Safe version of get_commit if this commit doesn't exists for a
656 656 repository it returns a Dummy one instead
657 657
658 658 :param repo: repository instance
659 659 :param commit_id: commit id as str
660 660 :param pre_load: optional list of commit attributes to load
661 661 """
662 662 # TODO(skreft): remove these circular imports
663 663 from rhodecode.lib.vcs.backends.base import BaseRepository, EmptyCommit
664 664 from rhodecode.lib.vcs.exceptions import RepositoryError
665 665 if not isinstance(repo, BaseRepository):
666 666 raise Exception('You must pass an Repository '
667 667 'object as first argument got %s', type(repo))
668 668
669 669 try:
670 670 commit = repo.get_commit(
671 671 commit_id=commit_id, commit_idx=commit_idx, pre_load=pre_load)
672 672 except (RepositoryError, LookupError):
673 673 commit = EmptyCommit()
674 674 return commit
675 675
676 676
677 677 def datetime_to_time(dt):
678 678 if dt:
679 679 return time.mktime(dt.timetuple())
680 680
681 681
682 682 def time_to_datetime(tm):
683 683 if tm:
684 684 if isinstance(tm, basestring):
685 685 try:
686 686 tm = float(tm)
687 687 except ValueError:
688 688 return
689 689 return datetime.datetime.fromtimestamp(tm)
690 690
691 691
692 692 def time_to_utcdatetime(tm):
693 693 if tm:
694 694 if isinstance(tm, basestring):
695 695 try:
696 696 tm = float(tm)
697 697 except ValueError:
698 698 return
699 699 return datetime.datetime.utcfromtimestamp(tm)
700 700
701 701
702 702 MENTIONS_REGEX = re.compile(
703 703 # ^@ or @ without any special chars in front
704 704 r'(?:^@|[^a-zA-Z0-9\-\_\.]@)'
705 705 # main body starts with letter, then can be . - _
706 706 r'([a-zA-Z0-9]{1}[a-zA-Z0-9\-\_\.]+)',
707 707 re.VERBOSE | re.MULTILINE)
708 708
709 709
710 710 def extract_mentioned_users(s):
711 711 """
712 712 Returns unique usernames from given string s that have @mention
713 713
714 714 :param s: string to get mentions
715 715 """
716 716 usrs = set()
717 717 for username in MENTIONS_REGEX.findall(s):
718 718 usrs.add(username)
719 719
720 720 return sorted(list(usrs), key=lambda k: k.lower())
721 721
722 722
723 723 class AttributeDictBase(dict):
724 724 def __getstate__(self):
725 725 odict = self.__dict__ # get attribute dictionary
726 726 return odict
727 727
728 728 def __setstate__(self, dict):
729 729 self.__dict__ = dict
730 730
731 731 __setattr__ = dict.__setitem__
732 732 __delattr__ = dict.__delitem__
733 733
734 734
735 735 class StrictAttributeDict(AttributeDictBase):
736 736 """
737 737 Strict Version of Attribute dict which raises an Attribute error when
738 738 requested attribute is not set
739 739 """
740 740 def __getattr__(self, attr):
741 741 try:
742 742 return self[attr]
743 743 except KeyError:
744 744 raise AttributeError('%s object has no attribute %s' % (
745 745 self.__class__, attr))
746 746
747 747
748 748 class AttributeDict(AttributeDictBase):
749 749 def __getattr__(self, attr):
750 750 return self.get(attr, None)
751 751
752 752
753 753
754 class OrderedDefaultDict(collections.OrderedDict, collections.defaultdict):
755 def __init__(self, default_factory=None, *args, **kwargs):
756 # in python3 you can omit the args to super
757 super(OrderedDefaultDict, self).__init__(*args, **kwargs)
758 self.default_factory = default_factory
759
760
754 761 def fix_PATH(os_=None):
755 762 """
756 763 Get current active python path, and append it to PATH variable to fix
757 764 issues of subprocess calls and different python versions
758 765 """
759 766 if os_ is None:
760 767 import os
761 768 else:
762 769 os = os_
763 770
764 771 cur_path = os.path.split(sys.executable)[0]
765 772 if not os.environ['PATH'].startswith(cur_path):
766 773 os.environ['PATH'] = '%s:%s' % (cur_path, os.environ['PATH'])
767 774
768 775
769 776 def obfuscate_url_pw(engine):
770 777 _url = engine or ''
771 778 try:
772 779 _url = sqlalchemy.engine.url.make_url(engine)
773 780 if _url.password:
774 781 _url.password = 'XXXXX'
775 782 except Exception:
776 783 pass
777 784 return unicode(_url)
778 785
779 786
780 787 def get_server_url(environ):
781 788 req = webob.Request(environ)
782 789 return req.host_url + req.script_name
783 790
784 791
785 792 def unique_id(hexlen=32):
786 793 alphabet = "23456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjklmnpqrstuvwxyz"
787 794 return suuid(truncate_to=hexlen, alphabet=alphabet)
788 795
789 796
790 797 def suuid(url=None, truncate_to=22, alphabet=None):
791 798 """
792 799 Generate and return a short URL safe UUID.
793 800
794 801 If the url parameter is provided, set the namespace to the provided
795 802 URL and generate a UUID.
796 803
797 804 :param url to get the uuid for
798 805 :truncate_to: truncate the basic 22 UUID to shorter version
799 806
800 807 The IDs won't be universally unique any longer, but the probability of
801 808 a collision will still be very low.
802 809 """
803 810 # Define our alphabet.
804 811 _ALPHABET = alphabet or "23456789ABCDEFGHJKLMNPQRSTUVWXYZ"
805 812
806 813 # If no URL is given, generate a random UUID.
807 814 if url is None:
808 815 unique_id = uuid.uuid4().int
809 816 else:
810 817 unique_id = uuid.uuid3(uuid.NAMESPACE_URL, url).int
811 818
812 819 alphabet_length = len(_ALPHABET)
813 820 output = []
814 821 while unique_id > 0:
815 822 digit = unique_id % alphabet_length
816 823 output.append(_ALPHABET[digit])
817 824 unique_id = int(unique_id / alphabet_length)
818 825 return "".join(output)[:truncate_to]
819 826
820 827
821 828 def get_current_rhodecode_user(request=None):
822 829 """
823 830 Gets rhodecode user from request
824 831 """
825 832 pyramid_request = request or pyramid.threadlocal.get_current_request()
826 833
827 834 # web case
828 835 if pyramid_request and hasattr(pyramid_request, 'user'):
829 836 return pyramid_request.user
830 837
831 838 # api case
832 839 if pyramid_request and hasattr(pyramid_request, 'rpc_user'):
833 840 return pyramid_request.rpc_user
834 841
835 842 return None
836 843
837 844
838 845 def action_logger_generic(action, namespace=''):
839 846 """
840 847 A generic logger for actions useful to the system overview, tries to find
841 848 an acting user for the context of the call otherwise reports unknown user
842 849
843 850 :param action: logging message eg 'comment 5 deleted'
844 851 :param type: string
845 852
846 853 :param namespace: namespace of the logging message eg. 'repo.comments'
847 854 :param type: string
848 855
849 856 """
850 857
851 858 logger_name = 'rhodecode.actions'
852 859
853 860 if namespace:
854 861 logger_name += '.' + namespace
855 862
856 863 log = logging.getLogger(logger_name)
857 864
858 865 # get a user if we can
859 866 user = get_current_rhodecode_user()
860 867
861 868 logfunc = log.info
862 869
863 870 if not user:
864 871 user = '<unknown user>'
865 872 logfunc = log.warning
866 873
867 874 logfunc('Logging action by {}: {}'.format(user, action))
868 875
869 876
870 877 def escape_split(text, sep=',', maxsplit=-1):
871 878 r"""
872 879 Allows for escaping of the separator: e.g. arg='foo\, bar'
873 880
874 881 It should be noted that the way bash et. al. do command line parsing, those
875 882 single quotes are required.
876 883 """
877 884 escaped_sep = r'\%s' % sep
878 885
879 886 if escaped_sep not in text:
880 887 return text.split(sep, maxsplit)
881 888
882 889 before, _mid, after = text.partition(escaped_sep)
883 890 startlist = before.split(sep, maxsplit) # a regular split is fine here
884 891 unfinished = startlist[-1]
885 892 startlist = startlist[:-1]
886 893
887 894 # recurse because there may be more escaped separators
888 895 endlist = escape_split(after, sep, maxsplit)
889 896
890 897 # finish building the escaped value. we use endlist[0] becaue the first
891 898 # part of the string sent in recursion is the rest of the escaped value.
892 899 unfinished += sep + endlist[0]
893 900
894 901 return startlist + [unfinished] + endlist[1:] # put together all the parts
895 902
896 903
897 904 class OptionalAttr(object):
898 905 """
899 906 Special Optional Option that defines other attribute. Example::
900 907
901 908 def test(apiuser, userid=Optional(OAttr('apiuser')):
902 909 user = Optional.extract(userid)
903 910 # calls
904 911
905 912 """
906 913
907 914 def __init__(self, attr_name):
908 915 self.attr_name = attr_name
909 916
910 917 def __repr__(self):
911 918 return '<OptionalAttr:%s>' % self.attr_name
912 919
913 920 def __call__(self):
914 921 return self
915 922
916 923
917 924 # alias
918 925 OAttr = OptionalAttr
919 926
920 927
921 928 class Optional(object):
922 929 """
923 930 Defines an optional parameter::
924 931
925 932 param = param.getval() if isinstance(param, Optional) else param
926 933 param = param() if isinstance(param, Optional) else param
927 934
928 935 is equivalent of::
929 936
930 937 param = Optional.extract(param)
931 938
932 939 """
933 940
934 941 def __init__(self, type_):
935 942 self.type_ = type_
936 943
937 944 def __repr__(self):
938 945 return '<Optional:%s>' % self.type_.__repr__()
939 946
940 947 def __call__(self):
941 948 return self.getval()
942 949
943 950 def getval(self):
944 951 """
945 952 returns value from this Optional instance
946 953 """
947 954 if isinstance(self.type_, OAttr):
948 955 # use params name
949 956 return self.type_.attr_name
950 957 return self.type_
951 958
952 959 @classmethod
953 960 def extract(cls, val):
954 961 """
955 962 Extracts value from Optional() instance
956 963
957 964 :param val:
958 965 :return: original value if it's not Optional instance else
959 966 value of instance
960 967 """
961 968 if isinstance(val, cls):
962 969 return val.getval()
963 970 return val
964 971
965 972
966 973 def glob2re(pat):
967 974 """
968 975 Translate a shell PATTERN to a regular expression.
969 976
970 977 There is no way to quote meta-characters.
971 978 """
972 979
973 980 i, n = 0, len(pat)
974 981 res = ''
975 982 while i < n:
976 983 c = pat[i]
977 984 i = i+1
978 985 if c == '*':
979 986 #res = res + '.*'
980 987 res = res + '[^/]*'
981 988 elif c == '?':
982 989 #res = res + '.'
983 990 res = res + '[^/]'
984 991 elif c == '[':
985 992 j = i
986 993 if j < n and pat[j] == '!':
987 994 j = j+1
988 995 if j < n and pat[j] == ']':
989 996 j = j+1
990 997 while j < n and pat[j] != ']':
991 998 j = j+1
992 999 if j >= n:
993 1000 res = res + '\\['
994 1001 else:
995 1002 stuff = pat[i:j].replace('\\','\\\\')
996 1003 i = j+1
997 1004 if stuff[0] == '!':
998 1005 stuff = '^' + stuff[1:]
999 1006 elif stuff[0] == '^':
1000 1007 stuff = '\\' + stuff
1001 1008 res = '%s[%s]' % (res, stuff)
1002 1009 else:
1003 1010 res = res + re.escape(c)
1004 1011 return res + '\Z(?ms)'
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: 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: 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
General Comments 0
You need to be logged in to leave comments. Login now