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