##// END OF EJS Templates
forks: moved pylons code into pyramid.
marcink -
r1988:f7d6f6e1 default
parent child Browse files
Show More
@@ -0,0 +1,315 b''
1 # -*- coding: utf-8 -*-
2
3 # Copyright (C) 2010-2017 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 pytest
22
23 from rhodecode.tests import TestController, assert_session_flash, HG_FORK, GIT_FORK
24
25 from rhodecode.tests.fixture import Fixture
26 from rhodecode.lib import helpers as h
27
28 from rhodecode.model.db import Repository
29 from rhodecode.model.repo import RepoModel
30 from rhodecode.model.user import UserModel
31 from rhodecode.model.meta import Session
32
33 fixture = Fixture()
34
35
36 def route_path(name, params=None, **kwargs):
37 import urllib
38
39 base_url = {
40 'repo_summary': '/{repo_name}',
41 'repo_creating_check': '/{repo_name}/repo_creating_check',
42 'repo_fork_new': '/{repo_name}/fork',
43 'repo_fork_create': '/{repo_name}/fork/create',
44 'repo_forks_show_all': '/{repo_name}/forks',
45 'repo_forks_data': '/{repo_name}/forks/data',
46 }[name].format(**kwargs)
47
48 if params:
49 base_url = '{}?{}'.format(base_url, urllib.urlencode(params))
50 return base_url
51
52
53 FORK_NAME = {
54 'hg': HG_FORK,
55 'git': GIT_FORK
56 }
57
58
59 @pytest.mark.skip_backends('svn')
60 class TestRepoForkViewTests(TestController):
61
62 def test_show_forks(self, backend, xhr_header):
63 self.log_user()
64 response = self.app.get(
65 route_path('repo_forks_data', repo_name=backend.repo_name),
66 extra_environ=xhr_header)
67
68 assert response.json == {u'data': [], u'draw': None,
69 u'recordsFiltered': 0, u'recordsTotal': 0}
70
71 def test_no_permissions_to_fork_page(self, backend, user_util):
72 user = user_util.create_user(password='qweqwe')
73 user_id = user.user_id
74 self.log_user(user.username, 'qweqwe')
75
76 user_model = UserModel()
77 user_model.revoke_perm(user_id, 'hg.fork.repository')
78 user_model.grant_perm(user_id, 'hg.fork.none')
79 u = UserModel().get(user_id)
80 u.inherit_default_permissions = False
81 Session().commit()
82 # try create a fork
83 self.app.get(
84 route_path('repo_fork_new', repo_name=backend.repo_name),
85 status=404)
86
87 def test_no_permissions_to_fork_submit(self, backend, csrf_token, user_util):
88 user = user_util.create_user(password='qweqwe')
89 user_id = user.user_id
90 self.log_user(user.username, 'qweqwe')
91
92 user_model = UserModel()
93 user_model.revoke_perm(user_id, 'hg.fork.repository')
94 user_model.grant_perm(user_id, 'hg.fork.none')
95 u = UserModel().get(user_id)
96 u.inherit_default_permissions = False
97 Session().commit()
98 # try create a fork
99 self.app.post(
100 route_path('repo_fork_create', repo_name=backend.repo_name),
101 {'csrf_token': csrf_token},
102 status=404)
103
104 def test_fork_missing_data(self, autologin_user, backend, csrf_token):
105 # try create a fork
106 response = self.app.post(
107 route_path('repo_fork_create', repo_name=backend.repo_name),
108 {'csrf_token': csrf_token},
109 status=200)
110 # test if html fill works fine
111 response.mustcontain('Missing value')
112
113 def test_create_fork_page(self, autologin_user, backend):
114 self.app.get(
115 route_path('repo_fork_new', repo_name=backend.repo_name),
116 status=200)
117
118 def test_create_and_show_fork(
119 self, autologin_user, backend, csrf_token, xhr_header):
120
121 # create a fork
122 fork_name = FORK_NAME[backend.alias]
123 description = 'fork of vcs test'
124 repo_name = backend.repo_name
125 source_repo = Repository.get_by_repo_name(repo_name)
126 creation_args = {
127 'repo_name': fork_name,
128 'repo_group': '',
129 'fork_parent_id': source_repo.repo_id,
130 'repo_type': backend.alias,
131 'description': description,
132 'private': 'False',
133 'landing_rev': 'rev:tip',
134 'csrf_token': csrf_token,
135 }
136
137 self.app.post(
138 route_path('repo_fork_create', repo_name=repo_name), creation_args)
139
140 response = self.app.get(
141 route_path('repo_forks_data', repo_name=repo_name),
142 extra_environ=xhr_header)
143
144 assert response.json['data'][0]['fork_name'] == \
145 """<a href="/%s">%s</a>""" % (fork_name, fork_name)
146
147 # remove this fork
148 fixture.destroy_repo(fork_name)
149
150 def test_fork_create(self, autologin_user, backend, csrf_token):
151 fork_name = FORK_NAME[backend.alias]
152 description = 'fork of vcs test'
153 repo_name = backend.repo_name
154 source_repo = Repository.get_by_repo_name(repo_name)
155 creation_args = {
156 'repo_name': fork_name,
157 'repo_group': '',
158 'fork_parent_id': source_repo.repo_id,
159 'repo_type': backend.alias,
160 'description': description,
161 'private': 'False',
162 'landing_rev': 'rev:tip',
163 'csrf_token': csrf_token,
164 }
165 self.app.post(
166 route_path('repo_fork_create', repo_name=repo_name), creation_args)
167 repo = Repository.get_by_repo_name(FORK_NAME[backend.alias])
168 assert repo.fork.repo_name == backend.repo_name
169
170 # run the check page that triggers the flash message
171 response = self.app.get(
172 route_path('repo_creating_check', repo_name=fork_name))
173 # test if we have a message that fork is ok
174 assert_session_flash(response,
175 'Forked repository %s as <a href="/%s">%s</a>'
176 % (repo_name, fork_name, fork_name))
177
178 # test if the fork was created in the database
179 fork_repo = Session().query(Repository)\
180 .filter(Repository.repo_name == fork_name).one()
181
182 assert fork_repo.repo_name == fork_name
183 assert fork_repo.fork.repo_name == repo_name
184
185 # test if the repository is visible in the list ?
186 response = self.app.get(
187 h.route_path('repo_summary', repo_name=fork_name))
188 response.mustcontain(fork_name)
189 response.mustcontain(backend.alias)
190 response.mustcontain('Fork of')
191 response.mustcontain('<a href="/%s">%s</a>' % (repo_name, repo_name))
192
193 def test_fork_create_into_group(self, autologin_user, backend, csrf_token):
194 group = fixture.create_repo_group('vc')
195 group_id = group.group_id
196 fork_name = FORK_NAME[backend.alias]
197 fork_name_full = 'vc/%s' % fork_name
198 description = 'fork of vcs test'
199 repo_name = backend.repo_name
200 source_repo = Repository.get_by_repo_name(repo_name)
201 creation_args = {
202 'repo_name': fork_name,
203 'repo_group': group_id,
204 'fork_parent_id': source_repo.repo_id,
205 'repo_type': backend.alias,
206 'description': description,
207 'private': 'False',
208 'landing_rev': 'rev:tip',
209 'csrf_token': csrf_token,
210 }
211 self.app.post(
212 route_path('repo_fork_create', repo_name=repo_name), creation_args)
213 repo = Repository.get_by_repo_name(fork_name_full)
214 assert repo.fork.repo_name == backend.repo_name
215
216 # run the check page that triggers the flash message
217 response = self.app.get(
218 route_path('repo_creating_check', repo_name=fork_name_full))
219 # test if we have a message that fork is ok
220 assert_session_flash(response,
221 'Forked repository %s as <a href="/%s">%s</a>'
222 % (repo_name, fork_name_full, fork_name_full))
223
224 # test if the fork was created in the database
225 fork_repo = Session().query(Repository)\
226 .filter(Repository.repo_name == fork_name_full).one()
227
228 assert fork_repo.repo_name == fork_name_full
229 assert fork_repo.fork.repo_name == repo_name
230
231 # test if the repository is visible in the list ?
232 response = self.app.get(
233 h.route_path('repo_summary', repo_name=fork_name_full))
234 response.mustcontain(fork_name_full)
235 response.mustcontain(backend.alias)
236
237 response.mustcontain('Fork of')
238 response.mustcontain('<a href="/%s">%s</a>' % (repo_name, repo_name))
239
240 fixture.destroy_repo(fork_name_full)
241 fixture.destroy_repo_group(group_id)
242
243 def test_fork_read_permission(self, backend, xhr_header, user_util):
244 user = user_util.create_user(password='qweqwe')
245 user_id = user.user_id
246 self.log_user(user.username, 'qweqwe')
247
248 # create a fake fork
249 fork = user_util.create_repo(repo_type=backend.alias)
250 source = user_util.create_repo(repo_type=backend.alias)
251 repo_name = source.repo_name
252
253 fork.fork_id = source.repo_id
254 fork_name = fork.repo_name
255 Session().commit()
256
257 forks = Repository.query()\
258 .filter(Repository.repo_type == backend.alias)\
259 .filter(Repository.fork_id == source.repo_id).all()
260 assert 1 == len(forks)
261
262 # set read permissions for this
263 RepoModel().grant_user_permission(
264 repo=forks[0], user=user_id, perm='repository.read')
265 Session().commit()
266
267 response = self.app.get(
268 route_path('repo_forks_data', repo_name=repo_name),
269 extra_environ=xhr_header)
270
271 assert response.json['data'][0]['fork_name'] == \
272 """<a href="/%s">%s</a>""" % (fork_name, fork_name)
273
274 def test_fork_none_permission(self, backend, xhr_header, user_util):
275 user = user_util.create_user(password='qweqwe')
276 user_id = user.user_id
277 self.log_user(user.username, 'qweqwe')
278
279 # create a fake fork
280 fork = user_util.create_repo(repo_type=backend.alias)
281 source = user_util.create_repo(repo_type=backend.alias)
282 repo_name = source.repo_name
283
284 fork.fork_id = source.repo_id
285
286 Session().commit()
287
288 forks = Repository.query()\
289 .filter(Repository.repo_type == backend.alias)\
290 .filter(Repository.fork_id == source.repo_id).all()
291 assert 1 == len(forks)
292
293 # set none
294 RepoModel().grant_user_permission(
295 repo=forks[0], user=user_id, perm='repository.none')
296 Session().commit()
297
298 # fork shouldn't be there
299 response = self.app.get(
300 route_path('repo_forks_data', repo_name=repo_name),
301 extra_environ=xhr_header)
302
303 assert response.json == {u'data': [], u'draw': None,
304 u'recordsFiltered': 0, u'recordsTotal': 0}
305
306
307 class TestSVNFork(TestController):
308 @pytest.mark.parametrize('route_name', [
309 'repo_fork_create', 'repo_fork_new'
310 ])
311 def test_fork_redirects(self, autologin_user, backend_svn, route_name):
312
313 self.app.get(route_path(
314 route_name, repo_name=backend_svn.repo_name),
315 status=404)
@@ -0,0 +1,256 b''
1 # -*- coding: utf-8 -*-
2
3 # Copyright (C) 2011-2017 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 import datetime
23 import formencode
24 from pyramid.httpexceptions import HTTPNotFound, HTTPBadRequest, HTTPFound
25 from pyramid.view import view_config
26 from pyramid.renderers import render
27 from pyramid.response import Response
28
29 from rhodecode.apps._base import RepoAppView, DataGridAppView
30
31 from rhodecode.lib.auth import (
32 LoginRequired, HasRepoPermissionAnyDecorator, NotAnonymous,
33 HasRepoPermissionAny, HasPermissionAnyDecorator, CSRFRequired)
34 import rhodecode.lib.helpers as h
35 from rhodecode.model.db import (
36 coalesce, or_, Repository, RepoGroup, UserFollowing, User)
37 from rhodecode.model.repo import RepoModel
38 from rhodecode.model.forms import RepoForkForm
39 from rhodecode.model.scm import ScmModel, RepoGroupList
40 from rhodecode.lib.utils2 import safe_int, safe_unicode
41
42 log = logging.getLogger(__name__)
43
44
45 class RepoForksView(RepoAppView, DataGridAppView):
46
47 def load_default_context(self):
48 c = self._get_local_tmpl_context(include_app_defaults=True)
49
50 # TODO(marcink): remove repo_info and use c.rhodecode_db_repo instead
51 c.repo_info = self.db_repo
52 c.rhodecode_repo = self.rhodecode_vcs_repo
53
54 acl_groups = RepoGroupList(
55 RepoGroup.query().all(),
56 perm_set=['group.write', 'group.admin'])
57 c.repo_groups = RepoGroup.groups_choices(groups=acl_groups)
58 c.repo_groups_choices = map(lambda k: safe_unicode(k[0]), c.repo_groups)
59 choices, c.landing_revs = ScmModel().get_repo_landing_revs()
60 c.landing_revs_choices = choices
61 c.personal_repo_group = c.rhodecode_user.personal_repo_group
62
63 self._register_global_c(c)
64 return c
65
66 @LoginRequired()
67 @HasRepoPermissionAnyDecorator(
68 'repository.read', 'repository.write', 'repository.admin')
69 @view_config(
70 route_name='repo_forks_show_all', request_method='GET',
71 renderer='rhodecode:templates/forks/forks.mako')
72 def repo_forks_show_all(self):
73 c = self.load_default_context()
74 return self._get_template_context(c)
75
76 @LoginRequired()
77 @HasRepoPermissionAnyDecorator(
78 'repository.read', 'repository.write', 'repository.admin')
79 @view_config(
80 route_name='repo_forks_data', request_method='GET',
81 renderer='json_ext', xhr=True)
82 def repo_forks_data(self):
83 _ = self.request.translate
84 column_map = {
85 'fork_name': 'repo_name',
86 'fork_date': 'created_on',
87 'last_activity': 'updated_on'
88 }
89 draw, start, limit = self._extract_chunk(self.request)
90 search_q, order_by, order_dir = self._extract_ordering(
91 self.request, column_map=column_map)
92
93 acl_check = HasRepoPermissionAny(
94 'repository.read', 'repository.write', 'repository.admin')
95 repo_id = self.db_repo.repo_id
96 allowed_ids = []
97 for f in Repository.query().filter(Repository.fork_id == repo_id):
98 if acl_check(f.repo_name, 'get forks check'):
99 allowed_ids.append(f.repo_id)
100
101 forks_data_total_count = Repository.query()\
102 .filter(Repository.fork_id == repo_id)\
103 .filter(Repository.repo_id.in_(allowed_ids))\
104 .count()
105
106 # json generate
107 base_q = Repository.query()\
108 .filter(Repository.fork_id == repo_id)\
109 .filter(Repository.repo_id.in_(allowed_ids))\
110
111 if search_q:
112 like_expression = u'%{}%'.format(safe_unicode(search_q))
113 base_q = base_q.filter(or_(
114 Repository.repo_name.ilike(like_expression),
115 Repository.description.ilike(like_expression),
116 ))
117
118 forks_data_total_filtered_count = base_q.count()
119
120 sort_col = getattr(Repository, order_by, None)
121 if sort_col:
122 if order_dir == 'asc':
123 # handle null values properly to order by NULL last
124 if order_by in ['last_activity']:
125 sort_col = coalesce(sort_col, datetime.date.max)
126 sort_col = sort_col.asc()
127 else:
128 # handle null values properly to order by NULL last
129 if order_by in ['last_activity']:
130 sort_col = coalesce(sort_col, datetime.date.min)
131 sort_col = sort_col.desc()
132
133 base_q = base_q.order_by(sort_col)
134 base_q = base_q.offset(start).limit(limit)
135
136 fork_list = base_q.all()
137
138 def fork_actions(fork):
139 url_link = h.route_path(
140 'repo_compare',
141 repo_name=fork.repo_name,
142 source_ref_type=self.db_repo.landing_rev[0],
143 source_ref=self.db_repo.landing_rev[1],
144 target_ref_type=self.db_repo.landing_rev[0],
145 target_ref=self.db_repo.landing_rev[1],
146 _query=dict(merge=1, target_repo=f.repo_name))
147 return h.link_to(_('Compare fork'), url_link, class_='btn-link')
148
149 def fork_name(fork):
150 return h.link_to(fork.repo_name,
151 h.route_path('repo_summary', repo_name=fork.repo_name))
152
153 forks_data = []
154 for fork in fork_list:
155 forks_data.append({
156 "username": h.gravatar_with_user(self.request, fork.user.username),
157 "fork_name": fork_name(fork),
158 "description": fork.description,
159 "fork_date": h.age_component(fork.created_on, time_is_local=True),
160 "last_activity": h.format_date(fork.updated_on),
161 "action": fork_actions(fork),
162 })
163
164 data = ({
165 'draw': draw,
166 'data': forks_data,
167 'recordsTotal': forks_data_total_count,
168 'recordsFiltered': forks_data_total_filtered_count,
169 })
170
171 return data
172
173 @LoginRequired()
174 @NotAnonymous()
175 @HasPermissionAnyDecorator('hg.admin', 'hg.fork.repository')
176 @HasRepoPermissionAnyDecorator(
177 'repository.read', 'repository.write', 'repository.admin')
178 @view_config(
179 route_name='repo_fork_new', request_method='GET',
180 renderer='rhodecode:templates/forks/forks.mako')
181 def repo_fork_new(self):
182 c = self.load_default_context()
183
184 defaults = RepoModel()._get_defaults(self.db_repo_name)
185 # alter the description to indicate a fork
186 defaults['description'] = (
187 'fork of repository: %s \n%s' % (
188 defaults['repo_name'], defaults['description']))
189 # add suffix to fork
190 defaults['repo_name'] = '%s-fork' % defaults['repo_name']
191
192 data = render('rhodecode:templates/forks/fork.mako',
193 self._get_template_context(c), self.request)
194 html = formencode.htmlfill.render(
195 data,
196 defaults=defaults,
197 encoding="UTF-8",
198 force_defaults=False
199 )
200 return Response(html)
201
202 @LoginRequired()
203 @NotAnonymous()
204 @HasPermissionAnyDecorator('hg.admin', 'hg.fork.repository')
205 @HasRepoPermissionAnyDecorator(
206 'repository.read', 'repository.write', 'repository.admin')
207 @CSRFRequired()
208 @view_config(
209 route_name='repo_fork_create', request_method='POST',
210 renderer='rhodecode:templates/forks/fork.mako')
211 def repo_fork_create(self):
212 _ = self.request.translate
213 c = self.load_default_context()
214
215 _form = RepoForkForm(old_data={'repo_type': self.db_repo.repo_type},
216 repo_groups=c.repo_groups_choices,
217 landing_revs=c.landing_revs_choices)()
218 form_result = {}
219 task_id = None
220 try:
221 form_result = _form.to_python(dict(self.request.POST))
222 # create fork is done sometimes async on celery, db transaction
223 # management is handled there.
224 task = RepoModel().create_fork(
225 form_result, c.rhodecode_user.user_id)
226 from celery.result import BaseAsyncResult
227 if isinstance(task, BaseAsyncResult):
228 task_id = task.task_id
229 except formencode.Invalid as errors:
230 c.repo_info = self.db_repo
231
232 data = render('rhodecode:templates/forks/fork.mako',
233 self._get_template_context(c), self.request)
234 html = formencode.htmlfill.render(
235 data,
236 defaults=errors.value,
237 errors=errors.error_dict or {},
238 prefix_error=False,
239 encoding="UTF-8",
240 force_defaults=False
241 )
242 return Response(html)
243 except Exception:
244 log.exception(
245 u'Exception while trying to fork the repository %s',
246 self.db_repo_name)
247 msg = (
248 _('An error occurred during repository forking %s') % (
249 self.db_repo_name, ))
250 h.flash(msg, category='error')
251
252 repo_name = form_result.get('repo_name_full', self.db_repo_name)
253 raise HTTPFound(
254 h.route_path('repo_creating',
255 repo_name=repo_name,
256 _query=dict(task_id=task_id)))
@@ -1,366 +1,387 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2016-2017 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20 from rhodecode.apps._base import add_route_with_slash
21 21
22 22
23 23 def includeme(config):
24 24
25 25 # repo creating checks, special cases that aren't repo routes
26 26 config.add_route(
27 27 name='repo_creating',
28 28 pattern='/{repo_name:.*?[^/]}/repo_creating')
29 29
30 30 config.add_route(
31 31 name='repo_creating_check',
32 32 pattern='/{repo_name:.*?[^/]}/repo_creating_check')
33 33
34 34 # Summary
35 35 # NOTE(marcink): one additional route is defined in very bottom, catch
36 36 # all pattern
37 37 config.add_route(
38 38 name='repo_summary_explicit',
39 39 pattern='/{repo_name:.*?[^/]}/summary', repo_route=True)
40 40 config.add_route(
41 41 name='repo_summary_commits',
42 42 pattern='/{repo_name:.*?[^/]}/summary-commits', repo_route=True)
43 43
44 44 # Commits
45 45 config.add_route(
46 46 name='repo_commit',
47 47 pattern='/{repo_name:.*?[^/]}/changeset/{commit_id}', repo_route=True)
48 48
49 49 config.add_route(
50 50 name='repo_commit_children',
51 51 pattern='/{repo_name:.*?[^/]}/changeset_children/{commit_id}', repo_route=True)
52 52
53 53 config.add_route(
54 54 name='repo_commit_parents',
55 55 pattern='/{repo_name:.*?[^/]}/changeset_parents/{commit_id}', repo_route=True)
56 56
57 57 config.add_route(
58 58 name='repo_commit_raw',
59 59 pattern='/{repo_name:.*?[^/]}/changeset-diff/{commit_id}', repo_route=True)
60 60
61 61 config.add_route(
62 62 name='repo_commit_patch',
63 63 pattern='/{repo_name:.*?[^/]}/changeset-patch/{commit_id}', repo_route=True)
64 64
65 65 config.add_route(
66 66 name='repo_commit_download',
67 67 pattern='/{repo_name:.*?[^/]}/changeset-download/{commit_id}', repo_route=True)
68 68
69 69 config.add_route(
70 70 name='repo_commit_data',
71 71 pattern='/{repo_name:.*?[^/]}/changeset-data/{commit_id}', repo_route=True)
72 72
73 73 config.add_route(
74 74 name='repo_commit_comment_create',
75 75 pattern='/{repo_name:.*?[^/]}/changeset/{commit_id}/comment/create', repo_route=True)
76 76
77 77 config.add_route(
78 78 name='repo_commit_comment_preview',
79 79 pattern='/{repo_name:.*?[^/]}/changeset/{commit_id}/comment/preview', repo_route=True)
80 80
81 81 config.add_route(
82 82 name='repo_commit_comment_delete',
83 83 pattern='/{repo_name:.*?[^/]}/changeset/{commit_id}/comment/{comment_id}/delete', repo_route=True)
84 84
85 85 # still working url for backward compat.
86 86 config.add_route(
87 87 name='repo_commit_raw_deprecated',
88 88 pattern='/{repo_name:.*?[^/]}/raw-changeset/{commit_id}', repo_route=True)
89 89
90 90 # Files
91 91 config.add_route(
92 92 name='repo_archivefile',
93 93 pattern='/{repo_name:.*?[^/]}/archive/{fname}', repo_route=True)
94 94
95 95 config.add_route(
96 96 name='repo_files_diff',
97 97 pattern='/{repo_name:.*?[^/]}/diff/{f_path:.*}', repo_route=True)
98 98 config.add_route( # legacy route to make old links work
99 99 name='repo_files_diff_2way_redirect',
100 100 pattern='/{repo_name:.*?[^/]}/diff-2way/{f_path:.*}', repo_route=True)
101 101
102 102 config.add_route(
103 103 name='repo_files',
104 104 pattern='/{repo_name:.*?[^/]}/files/{commit_id}/{f_path:.*}', repo_route=True)
105 105 config.add_route(
106 106 name='repo_files:default_path',
107 107 pattern='/{repo_name:.*?[^/]}/files/{commit_id}/', repo_route=True)
108 108 config.add_route(
109 109 name='repo_files:default_commit',
110 110 pattern='/{repo_name:.*?[^/]}/files', repo_route=True)
111 111
112 112 config.add_route(
113 113 name='repo_files:rendered',
114 114 pattern='/{repo_name:.*?[^/]}/render/{commit_id}/{f_path:.*}', repo_route=True)
115 115
116 116 config.add_route(
117 117 name='repo_files:annotated',
118 118 pattern='/{repo_name:.*?[^/]}/annotate/{commit_id}/{f_path:.*}', repo_route=True)
119 119 config.add_route(
120 120 name='repo_files:annotated_previous',
121 121 pattern='/{repo_name:.*?[^/]}/annotate-previous/{commit_id}/{f_path:.*}', repo_route=True)
122 122
123 123 config.add_route(
124 124 name='repo_nodetree_full',
125 125 pattern='/{repo_name:.*?[^/]}/nodetree_full/{commit_id}/{f_path:.*}', repo_route=True)
126 126 config.add_route(
127 127 name='repo_nodetree_full:default_path',
128 128 pattern='/{repo_name:.*?[^/]}/nodetree_full/{commit_id}/', repo_route=True)
129 129
130 130 config.add_route(
131 131 name='repo_files_nodelist',
132 132 pattern='/{repo_name:.*?[^/]}/nodelist/{commit_id}/{f_path:.*}', repo_route=True)
133 133
134 134 config.add_route(
135 135 name='repo_file_raw',
136 136 pattern='/{repo_name:.*?[^/]}/raw/{commit_id}/{f_path:.*}', repo_route=True)
137 137
138 138 config.add_route(
139 139 name='repo_file_download',
140 140 pattern='/{repo_name:.*?[^/]}/download/{commit_id}/{f_path:.*}', repo_route=True)
141 141 config.add_route( # backward compat to keep old links working
142 142 name='repo_file_download:legacy',
143 143 pattern='/{repo_name:.*?[^/]}/rawfile/{commit_id}/{f_path:.*}',
144 144 repo_route=True)
145 145
146 146 config.add_route(
147 147 name='repo_file_history',
148 148 pattern='/{repo_name:.*?[^/]}/history/{commit_id}/{f_path:.*}', repo_route=True)
149 149
150 150 config.add_route(
151 151 name='repo_file_authors',
152 152 pattern='/{repo_name:.*?[^/]}/authors/{commit_id}/{f_path:.*}', repo_route=True)
153 153
154 154 config.add_route(
155 155 name='repo_files_remove_file',
156 156 pattern='/{repo_name:.*?[^/]}/remove_file/{commit_id}/{f_path:.*}',
157 157 repo_route=True)
158 158 config.add_route(
159 159 name='repo_files_delete_file',
160 160 pattern='/{repo_name:.*?[^/]}/delete_file/{commit_id}/{f_path:.*}',
161 161 repo_route=True)
162 162 config.add_route(
163 163 name='repo_files_edit_file',
164 164 pattern='/{repo_name:.*?[^/]}/edit_file/{commit_id}/{f_path:.*}',
165 165 repo_route=True)
166 166 config.add_route(
167 167 name='repo_files_update_file',
168 168 pattern='/{repo_name:.*?[^/]}/update_file/{commit_id}/{f_path:.*}',
169 169 repo_route=True)
170 170 config.add_route(
171 171 name='repo_files_add_file',
172 172 pattern='/{repo_name:.*?[^/]}/add_file/{commit_id}/{f_path:.*}',
173 173 repo_route=True)
174 174 config.add_route(
175 175 name='repo_files_create_file',
176 176 pattern='/{repo_name:.*?[^/]}/create_file/{commit_id}/{f_path:.*}',
177 177 repo_route=True)
178 178
179 179 # Refs data
180 180 config.add_route(
181 181 name='repo_refs_data',
182 182 pattern='/{repo_name:.*?[^/]}/refs-data', repo_route=True)
183 183
184 184 config.add_route(
185 185 name='repo_refs_changelog_data',
186 186 pattern='/{repo_name:.*?[^/]}/refs-data-changelog', repo_route=True)
187 187
188 188 config.add_route(
189 189 name='repo_stats',
190 190 pattern='/{repo_name:.*?[^/]}/repo_stats/{commit_id}', repo_route=True)
191 191
192 192 # Changelog
193 193 config.add_route(
194 194 name='repo_changelog',
195 195 pattern='/{repo_name:.*?[^/]}/changelog', repo_route=True)
196 196 config.add_route(
197 197 name='repo_changelog_file',
198 198 pattern='/{repo_name:.*?[^/]}/changelog/{commit_id}/{f_path:.*}', repo_route=True)
199 199 config.add_route(
200 200 name='repo_changelog_elements',
201 201 pattern='/{repo_name:.*?[^/]}/changelog_elements', repo_route=True)
202 202
203 203 # Compare
204 204 config.add_route(
205 205 name='repo_compare_select',
206 206 pattern='/{repo_name:.*?[^/]}/compare', repo_route=True)
207 207
208 208 config.add_route(
209 209 name='repo_compare',
210 210 pattern='/{repo_name:.*?[^/]}/compare/{source_ref_type}@{source_ref:.*?}...{target_ref_type}@{target_ref:.*?}', repo_route=True)
211 211
212 212 # Tags
213 213 config.add_route(
214 214 name='tags_home',
215 215 pattern='/{repo_name:.*?[^/]}/tags', repo_route=True)
216 216
217 217 # Branches
218 218 config.add_route(
219 219 name='branches_home',
220 220 pattern='/{repo_name:.*?[^/]}/branches', repo_route=True)
221 221
222 # Bookmarks
222 223 config.add_route(
223 224 name='bookmarks_home',
224 225 pattern='/{repo_name:.*?[^/]}/bookmarks', repo_route=True)
225 226
227 # Forks
228 config.add_route(
229 name='repo_fork_new',
230 pattern='/{repo_name:.*?[^/]}/fork', repo_route=True,
231 repo_accepted_types=['hg', 'git'])
232
233 config.add_route(
234 name='repo_fork_create',
235 pattern='/{repo_name:.*?[^/]}/fork/create', repo_route=True,
236 repo_accepted_types=['hg', 'git'])
237
238 config.add_route(
239 name='repo_forks_show_all',
240 pattern='/{repo_name:.*?[^/]}/forks', repo_route=True,
241 repo_accepted_types=['hg', 'git'])
242 config.add_route(
243 name='repo_forks_data',
244 pattern='/{repo_name:.*?[^/]}/forks/data', repo_route=True,
245 repo_accepted_types=['hg', 'git'])
246
226 247 # Pull Requests
227 248 config.add_route(
228 249 name='pullrequest_show',
229 250 pattern='/{repo_name:.*?[^/]}/pull-request/{pull_request_id:\d+}',
230 251 repo_route=True)
231 252
232 253 config.add_route(
233 254 name='pullrequest_show_all',
234 255 pattern='/{repo_name:.*?[^/]}/pull-request',
235 256 repo_route=True, repo_accepted_types=['hg', 'git'])
236 257
237 258 config.add_route(
238 259 name='pullrequest_show_all_data',
239 260 pattern='/{repo_name:.*?[^/]}/pull-request-data',
240 261 repo_route=True, repo_accepted_types=['hg', 'git'])
241 262
242 263 config.add_route(
243 264 name='pullrequest_repo_refs',
244 265 pattern='/{repo_name:.*?[^/]}/pull-request/refs/{target_repo_name:.*?[^/]}',
245 266 repo_route=True)
246 267
247 268 config.add_route(
248 269 name='pullrequest_repo_destinations',
249 270 pattern='/{repo_name:.*?[^/]}/pull-request/repo-destinations',
250 271 repo_route=True)
251 272
252 273 config.add_route(
253 274 name='pullrequest_new',
254 275 pattern='/{repo_name:.*?[^/]}/pull-request/new',
255 276 repo_route=True, repo_accepted_types=['hg', 'git'])
256 277
257 278 config.add_route(
258 279 name='pullrequest_create',
259 280 pattern='/{repo_name:.*?[^/]}/pull-request/create',
260 281 repo_route=True, repo_accepted_types=['hg', 'git'])
261 282
262 283 config.add_route(
263 284 name='pullrequest_update',
264 285 pattern='/{repo_name:.*?[^/]}/pull-request/{pull_request_id:\d+}/update',
265 286 repo_route=True)
266 287
267 288 config.add_route(
268 289 name='pullrequest_merge',
269 290 pattern='/{repo_name:.*?[^/]}/pull-request/{pull_request_id:\d+}/merge',
270 291 repo_route=True)
271 292
272 293 config.add_route(
273 294 name='pullrequest_delete',
274 295 pattern='/{repo_name:.*?[^/]}/pull-request/{pull_request_id:\d+}/delete',
275 296 repo_route=True)
276 297
277 298 config.add_route(
278 299 name='pullrequest_comment_create',
279 300 pattern='/{repo_name:.*?[^/]}/pull-request/{pull_request_id:\d+}/comment',
280 301 repo_route=True)
281 302
282 303 config.add_route(
283 304 name='pullrequest_comment_delete',
284 305 pattern='/{repo_name:.*?[^/]}/pull-request/{pull_request_id:\d+}/comment/{comment_id}/delete',
285 306 repo_route=True, repo_accepted_types=['hg', 'git'])
286 307
287 308 # Settings
288 309 config.add_route(
289 310 name='edit_repo',
290 311 pattern='/{repo_name:.*?[^/]}/settings', repo_route=True)
291 312
292 313 # Settings advanced
293 314 config.add_route(
294 315 name='edit_repo_advanced',
295 316 pattern='/{repo_name:.*?[^/]}/settings/advanced', repo_route=True)
296 317 config.add_route(
297 318 name='edit_repo_advanced_delete',
298 319 pattern='/{repo_name:.*?[^/]}/settings/advanced/delete', repo_route=True)
299 320 config.add_route(
300 321 name='edit_repo_advanced_locking',
301 322 pattern='/{repo_name:.*?[^/]}/settings/advanced/locking', repo_route=True)
302 323 config.add_route(
303 324 name='edit_repo_advanced_journal',
304 325 pattern='/{repo_name:.*?[^/]}/settings/advanced/journal', repo_route=True)
305 326 config.add_route(
306 327 name='edit_repo_advanced_fork',
307 328 pattern='/{repo_name:.*?[^/]}/settings/advanced/fork', repo_route=True)
308 329
309 330 # Caches
310 331 config.add_route(
311 332 name='edit_repo_caches',
312 333 pattern='/{repo_name:.*?[^/]}/settings/caches', repo_route=True)
313 334
314 335 # Permissions
315 336 config.add_route(
316 337 name='edit_repo_perms',
317 338 pattern='/{repo_name:.*?[^/]}/settings/permissions', repo_route=True)
318 339
319 340 # Repo Review Rules
320 341 config.add_route(
321 342 name='repo_reviewers',
322 343 pattern='/{repo_name:.*?[^/]}/settings/review/rules', repo_route=True)
323 344
324 345 config.add_route(
325 346 name='repo_default_reviewers_data',
326 347 pattern='/{repo_name:.*?[^/]}/settings/review/default-reviewers', repo_route=True)
327 348
328 349 # Maintenance
329 350 config.add_route(
330 351 name='repo_maintenance',
331 352 pattern='/{repo_name:.*?[^/]}/settings/maintenance', repo_route=True)
332 353
333 354 config.add_route(
334 355 name='repo_maintenance_execute',
335 356 pattern='/{repo_name:.*?[^/]}/settings/maintenance/execute', repo_route=True)
336 357
337 358 # Strip
338 359 config.add_route(
339 360 name='strip',
340 361 pattern='/{repo_name:.*?[^/]}/settings/strip', repo_route=True)
341 362
342 363 config.add_route(
343 364 name='strip_check',
344 365 pattern='/{repo_name:.*?[^/]}/settings/strip_check', repo_route=True)
345 366
346 367 config.add_route(
347 368 name='strip_execute',
348 369 pattern='/{repo_name:.*?[^/]}/settings/strip_execute', repo_route=True)
349 370
350 371 # ATOM/RSS Feed
351 372 config.add_route(
352 373 name='rss_feed_home',
353 374 pattern='/{repo_name:.*?[^/]}/feed/rss', repo_route=True)
354 375
355 376 config.add_route(
356 377 name='atom_feed_home',
357 378 pattern='/{repo_name:.*?[^/]}/feed/atom', repo_route=True)
358 379
359 380 # NOTE(marcink): needs to be at the end for catch-all
360 381 add_route_with_slash(
361 382 config,
362 383 name='repo_summary',
363 384 pattern='/{repo_name:.*?[^/]}', repo_route=True)
364 385
365 386 # Scan module for configuration decorators.
366 387 config.scan()
@@ -1,508 +1,492 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2010-2017 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 21 """
22 22 Routes configuration
23 23
24 24 The more specific and detailed routes should be defined first so they
25 25 may take precedent over the more generic routes. For more information
26 26 refer to the routes manual at http://routes.groovie.org/docs/
27 27
28 28 IMPORTANT: if you change any routing here, make sure to take a look at lib/base.py
29 29 and _route_name variable which uses some of stored naming here to do redirects.
30 30 """
31 31 import os
32 32 import re
33 33 from routes import Mapper
34 34
35 35 # prefix for non repository related links needs to be prefixed with `/`
36 36 ADMIN_PREFIX = '/_admin'
37 37 STATIC_FILE_PREFIX = '/_static'
38 38
39 39 # Default requirements for URL parts
40 40 URL_NAME_REQUIREMENTS = {
41 41 # group name can have a slash in them, but they must not end with a slash
42 42 'group_name': r'.*?[^/]',
43 43 'repo_group_name': r'.*?[^/]',
44 44 # repo names can have a slash in them, but they must not end with a slash
45 45 'repo_name': r'.*?[^/]',
46 46 # file path eats up everything at the end
47 47 'f_path': r'.*',
48 48 # reference types
49 49 'source_ref_type': '(branch|book|tag|rev|\%\(source_ref_type\)s)',
50 50 'target_ref_type': '(branch|book|tag|rev|\%\(target_ref_type\)s)',
51 51 }
52 52
53 53
54 54 class JSRoutesMapper(Mapper):
55 55 """
56 56 Wrapper for routes.Mapper to make pyroutes compatible url definitions
57 57 """
58 58 _named_route_regex = re.compile(r'^[a-z-_0-9A-Z]+$')
59 59 _argument_prog = re.compile('\{(.*?)\}|:\((.*)\)')
60 60 def __init__(self, *args, **kw):
61 61 super(JSRoutesMapper, self).__init__(*args, **kw)
62 62 self._jsroutes = []
63 63
64 64 def connect(self, *args, **kw):
65 65 """
66 66 Wrapper for connect to take an extra argument jsroute=True
67 67
68 68 :param jsroute: boolean, if True will add the route to the pyroutes list
69 69 """
70 70 if kw.pop('jsroute', False):
71 71 if not self._named_route_regex.match(args[0]):
72 72 raise Exception('only named routes can be added to pyroutes')
73 73 self._jsroutes.append(args[0])
74 74
75 75 super(JSRoutesMapper, self).connect(*args, **kw)
76 76
77 77 def _extract_route_information(self, route):
78 78 """
79 79 Convert a route into tuple(name, path, args), eg:
80 80 ('show_user', '/profile/%(username)s', ['username'])
81 81 """
82 82 routepath = route.routepath
83 83 def replace(matchobj):
84 84 if matchobj.group(1):
85 85 return "%%(%s)s" % matchobj.group(1).split(':')[0]
86 86 else:
87 87 return "%%(%s)s" % matchobj.group(2)
88 88
89 89 routepath = self._argument_prog.sub(replace, routepath)
90 90 return (
91 91 route.name,
92 92 routepath,
93 93 [(arg[0].split(':')[0] if arg[0] != '' else arg[1])
94 94 for arg in self._argument_prog.findall(route.routepath)]
95 95 )
96 96
97 97 def jsroutes(self):
98 98 """
99 99 Return a list of pyroutes.js compatible routes
100 100 """
101 101 for route_name in self._jsroutes:
102 102 yield self._extract_route_information(self._routenames[route_name])
103 103
104 104
105 105 def make_map(config):
106 106 """Create, configure and return the routes Mapper"""
107 107 rmap = JSRoutesMapper(
108 108 directory=config['pylons.paths']['controllers'],
109 109 always_scan=config['debug'])
110 110 rmap.minimization = False
111 111 rmap.explicit = False
112 112
113 113 from rhodecode.lib.utils2 import str2bool
114 114 from rhodecode.model import repo, repo_group
115 115
116 116 def check_repo(environ, match_dict):
117 117 """
118 118 check for valid repository for proper 404 handling
119 119
120 120 :param environ:
121 121 :param match_dict:
122 122 """
123 123 repo_name = match_dict.get('repo_name')
124 124
125 125 if match_dict.get('f_path'):
126 126 # fix for multiple initial slashes that causes errors
127 127 match_dict['f_path'] = match_dict['f_path'].lstrip('/')
128 128 repo_model = repo.RepoModel()
129 129 by_name_match = repo_model.get_by_repo_name(repo_name)
130 130 # if we match quickly from database, short circuit the operation,
131 131 # and validate repo based on the type.
132 132 if by_name_match:
133 133 return True
134 134
135 135 by_id_match = repo_model.get_repo_by_id(repo_name)
136 136 if by_id_match:
137 137 repo_name = by_id_match.repo_name
138 138 match_dict['repo_name'] = repo_name
139 139 return True
140 140
141 141 return False
142 142
143 143 def check_group(environ, match_dict):
144 144 """
145 145 check for valid repository group path for proper 404 handling
146 146
147 147 :param environ:
148 148 :param match_dict:
149 149 """
150 150 repo_group_name = match_dict.get('group_name')
151 151 repo_group_model = repo_group.RepoGroupModel()
152 152 by_name_match = repo_group_model.get_by_group_name(repo_group_name)
153 153 if by_name_match:
154 154 return True
155 155
156 156 return False
157 157
158 158 def check_user_group(environ, match_dict):
159 159 """
160 160 check for valid user group for proper 404 handling
161 161
162 162 :param environ:
163 163 :param match_dict:
164 164 """
165 165 return True
166 166
167 167 def check_int(environ, match_dict):
168 168 return match_dict.get('id').isdigit()
169 169
170 170
171 171 #==========================================================================
172 172 # CUSTOM ROUTES HERE
173 173 #==========================================================================
174 174
175 175 # ping and pylons error test
176 176 rmap.connect('ping', '%s/ping' % (ADMIN_PREFIX,), controller='home', action='ping')
177 177 rmap.connect('error_test', '%s/error_test' % (ADMIN_PREFIX,), controller='home', action='error_test')
178 178
179 179 # ADMIN REPOSITORY ROUTES
180 180 with rmap.submapper(path_prefix=ADMIN_PREFIX,
181 181 controller='admin/repos') as m:
182 182 m.connect('repos', '/repos',
183 183 action='create', conditions={'method': ['POST']})
184 184 m.connect('repos', '/repos',
185 185 action='index', conditions={'method': ['GET']})
186 186 m.connect('new_repo', '/create_repository', jsroute=True,
187 187 action='create_repository', conditions={'method': ['GET']})
188 188 m.connect('delete_repo', '/repos/{repo_name}',
189 189 action='delete', conditions={'method': ['DELETE']},
190 190 requirements=URL_NAME_REQUIREMENTS)
191 191 m.connect('repo', '/repos/{repo_name}',
192 192 action='show', conditions={'method': ['GET'],
193 193 'function': check_repo},
194 194 requirements=URL_NAME_REQUIREMENTS)
195 195
196 196 # ADMIN REPOSITORY GROUPS ROUTES
197 197 with rmap.submapper(path_prefix=ADMIN_PREFIX,
198 198 controller='admin/repo_groups') as m:
199 199 m.connect('repo_groups', '/repo_groups',
200 200 action='create', conditions={'method': ['POST']})
201 201 m.connect('repo_groups', '/repo_groups',
202 202 action='index', conditions={'method': ['GET']})
203 203 m.connect('new_repo_group', '/repo_groups/new',
204 204 action='new', conditions={'method': ['GET']})
205 205 m.connect('update_repo_group', '/repo_groups/{group_name}',
206 206 action='update', conditions={'method': ['PUT'],
207 207 'function': check_group},
208 208 requirements=URL_NAME_REQUIREMENTS)
209 209
210 210 # EXTRAS REPO GROUP ROUTES
211 211 m.connect('edit_repo_group', '/repo_groups/{group_name}/edit',
212 212 action='edit',
213 213 conditions={'method': ['GET'], 'function': check_group},
214 214 requirements=URL_NAME_REQUIREMENTS)
215 215 m.connect('edit_repo_group', '/repo_groups/{group_name}/edit',
216 216 action='edit',
217 217 conditions={'method': ['PUT'], 'function': check_group},
218 218 requirements=URL_NAME_REQUIREMENTS)
219 219
220 220 m.connect('edit_repo_group_advanced', '/repo_groups/{group_name}/edit/advanced',
221 221 action='edit_repo_group_advanced',
222 222 conditions={'method': ['GET'], 'function': check_group},
223 223 requirements=URL_NAME_REQUIREMENTS)
224 224 m.connect('edit_repo_group_advanced', '/repo_groups/{group_name}/edit/advanced',
225 225 action='edit_repo_group_advanced',
226 226 conditions={'method': ['PUT'], 'function': check_group},
227 227 requirements=URL_NAME_REQUIREMENTS)
228 228
229 229 m.connect('edit_repo_group_perms', '/repo_groups/{group_name}/edit/permissions',
230 230 action='edit_repo_group_perms',
231 231 conditions={'method': ['GET'], 'function': check_group},
232 232 requirements=URL_NAME_REQUIREMENTS)
233 233 m.connect('edit_repo_group_perms', '/repo_groups/{group_name}/edit/permissions',
234 234 action='update_perms',
235 235 conditions={'method': ['PUT'], 'function': check_group},
236 236 requirements=URL_NAME_REQUIREMENTS)
237 237
238 238 m.connect('delete_repo_group', '/repo_groups/{group_name}',
239 239 action='delete', conditions={'method': ['DELETE'],
240 240 'function': check_group},
241 241 requirements=URL_NAME_REQUIREMENTS)
242 242
243 243 # ADMIN USER ROUTES
244 244 with rmap.submapper(path_prefix=ADMIN_PREFIX,
245 245 controller='admin/users') as m:
246 246 m.connect('users', '/users',
247 247 action='create', conditions={'method': ['POST']})
248 248 m.connect('new_user', '/users/new',
249 249 action='new', conditions={'method': ['GET']})
250 250 m.connect('update_user', '/users/{user_id}',
251 251 action='update', conditions={'method': ['PUT']})
252 252 m.connect('delete_user', '/users/{user_id}',
253 253 action='delete', conditions={'method': ['DELETE']})
254 254 m.connect('edit_user', '/users/{user_id}/edit',
255 255 action='edit', conditions={'method': ['GET']}, jsroute=True)
256 256 m.connect('user', '/users/{user_id}',
257 257 action='show', conditions={'method': ['GET']})
258 258 m.connect('force_password_reset_user', '/users/{user_id}/password_reset',
259 259 action='reset_password', conditions={'method': ['POST']})
260 260 m.connect('create_personal_repo_group', '/users/{user_id}/create_repo_group',
261 261 action='create_personal_repo_group', conditions={'method': ['POST']})
262 262
263 263 # EXTRAS USER ROUTES
264 264 m.connect('edit_user_advanced', '/users/{user_id}/edit/advanced',
265 265 action='edit_advanced', conditions={'method': ['GET']})
266 266 m.connect('edit_user_advanced', '/users/{user_id}/edit/advanced',
267 267 action='update_advanced', conditions={'method': ['PUT']})
268 268
269 269 m.connect('edit_user_global_perms', '/users/{user_id}/edit/global_permissions',
270 270 action='edit_global_perms', conditions={'method': ['GET']})
271 271 m.connect('edit_user_global_perms', '/users/{user_id}/edit/global_permissions',
272 272 action='update_global_perms', conditions={'method': ['PUT']})
273 273
274 274 m.connect('edit_user_perms_summary', '/users/{user_id}/edit/permissions_summary',
275 275 action='edit_perms_summary', conditions={'method': ['GET']})
276 276
277 277 # ADMIN USER GROUPS REST ROUTES
278 278 with rmap.submapper(path_prefix=ADMIN_PREFIX,
279 279 controller='admin/user_groups') as m:
280 280 m.connect('users_groups', '/user_groups',
281 281 action='create', conditions={'method': ['POST']})
282 282 m.connect('new_users_group', '/user_groups/new',
283 283 action='new', conditions={'method': ['GET']})
284 284 m.connect('update_users_group', '/user_groups/{user_group_id}',
285 285 action='update', conditions={'method': ['PUT']})
286 286 m.connect('delete_users_group', '/user_groups/{user_group_id}',
287 287 action='delete', conditions={'method': ['DELETE']})
288 288 m.connect('edit_users_group', '/user_groups/{user_group_id}/edit',
289 289 action='edit', conditions={'method': ['GET']},
290 290 function=check_user_group)
291 291
292 292 # EXTRAS USER GROUP ROUTES
293 293 m.connect('edit_user_group_global_perms',
294 294 '/user_groups/{user_group_id}/edit/global_permissions',
295 295 action='edit_global_perms', conditions={'method': ['GET']})
296 296 m.connect('edit_user_group_global_perms',
297 297 '/user_groups/{user_group_id}/edit/global_permissions',
298 298 action='update_global_perms', conditions={'method': ['PUT']})
299 299 m.connect('edit_user_group_perms_summary',
300 300 '/user_groups/{user_group_id}/edit/permissions_summary',
301 301 action='edit_perms_summary', conditions={'method': ['GET']})
302 302
303 303 m.connect('edit_user_group_perms',
304 304 '/user_groups/{user_group_id}/edit/permissions',
305 305 action='edit_perms', conditions={'method': ['GET']})
306 306 m.connect('edit_user_group_perms',
307 307 '/user_groups/{user_group_id}/edit/permissions',
308 308 action='update_perms', conditions={'method': ['PUT']})
309 309
310 310 m.connect('edit_user_group_advanced',
311 311 '/user_groups/{user_group_id}/edit/advanced',
312 312 action='edit_advanced', conditions={'method': ['GET']})
313 313
314 314 m.connect('edit_user_group_advanced_sync',
315 315 '/user_groups/{user_group_id}/edit/advanced/sync',
316 316 action='edit_advanced_set_synchronization', conditions={'method': ['POST']})
317 317
318 318 # ADMIN DEFAULTS REST ROUTES
319 319 with rmap.submapper(path_prefix=ADMIN_PREFIX,
320 320 controller='admin/defaults') as m:
321 321 m.connect('admin_defaults_repositories', '/defaults/repositories',
322 322 action='update_repository_defaults', conditions={'method': ['POST']})
323 323 m.connect('admin_defaults_repositories', '/defaults/repositories',
324 324 action='index', conditions={'method': ['GET']})
325 325
326 326 # ADMIN SETTINGS ROUTES
327 327 with rmap.submapper(path_prefix=ADMIN_PREFIX,
328 328 controller='admin/settings') as m:
329 329
330 330 # default
331 331 m.connect('admin_settings', '/settings',
332 332 action='settings_global_update',
333 333 conditions={'method': ['POST']})
334 334 m.connect('admin_settings', '/settings',
335 335 action='settings_global', conditions={'method': ['GET']})
336 336
337 337 m.connect('admin_settings_vcs', '/settings/vcs',
338 338 action='settings_vcs_update',
339 339 conditions={'method': ['POST']})
340 340 m.connect('admin_settings_vcs', '/settings/vcs',
341 341 action='settings_vcs',
342 342 conditions={'method': ['GET']})
343 343 m.connect('admin_settings_vcs', '/settings/vcs',
344 344 action='delete_svn_pattern',
345 345 conditions={'method': ['DELETE']})
346 346
347 347 m.connect('admin_settings_mapping', '/settings/mapping',
348 348 action='settings_mapping_update',
349 349 conditions={'method': ['POST']})
350 350 m.connect('admin_settings_mapping', '/settings/mapping',
351 351 action='settings_mapping', conditions={'method': ['GET']})
352 352
353 353 m.connect('admin_settings_global', '/settings/global',
354 354 action='settings_global_update',
355 355 conditions={'method': ['POST']})
356 356 m.connect('admin_settings_global', '/settings/global',
357 357 action='settings_global', conditions={'method': ['GET']})
358 358
359 359 m.connect('admin_settings_visual', '/settings/visual',
360 360 action='settings_visual_update',
361 361 conditions={'method': ['POST']})
362 362 m.connect('admin_settings_visual', '/settings/visual',
363 363 action='settings_visual', conditions={'method': ['GET']})
364 364
365 365 m.connect('admin_settings_issuetracker',
366 366 '/settings/issue-tracker', action='settings_issuetracker',
367 367 conditions={'method': ['GET']})
368 368 m.connect('admin_settings_issuetracker_save',
369 369 '/settings/issue-tracker/save',
370 370 action='settings_issuetracker_save',
371 371 conditions={'method': ['POST']})
372 372 m.connect('admin_issuetracker_test', '/settings/issue-tracker/test',
373 373 action='settings_issuetracker_test',
374 374 conditions={'method': ['POST']})
375 375 m.connect('admin_issuetracker_delete',
376 376 '/settings/issue-tracker/delete',
377 377 action='settings_issuetracker_delete',
378 378 conditions={'method': ['DELETE']})
379 379
380 380 m.connect('admin_settings_email', '/settings/email',
381 381 action='settings_email_update',
382 382 conditions={'method': ['POST']})
383 383 m.connect('admin_settings_email', '/settings/email',
384 384 action='settings_email', conditions={'method': ['GET']})
385 385
386 386 m.connect('admin_settings_hooks', '/settings/hooks',
387 387 action='settings_hooks_update',
388 388 conditions={'method': ['POST', 'DELETE']})
389 389 m.connect('admin_settings_hooks', '/settings/hooks',
390 390 action='settings_hooks', conditions={'method': ['GET']})
391 391
392 392 m.connect('admin_settings_search', '/settings/search',
393 393 action='settings_search', conditions={'method': ['GET']})
394 394
395 395 m.connect('admin_settings_supervisor', '/settings/supervisor',
396 396 action='settings_supervisor', conditions={'method': ['GET']})
397 397 m.connect('admin_settings_supervisor_log', '/settings/supervisor/{procid}/log',
398 398 action='settings_supervisor_log', conditions={'method': ['GET']})
399 399
400 400 m.connect('admin_settings_labs', '/settings/labs',
401 401 action='settings_labs_update',
402 402 conditions={'method': ['POST']})
403 403 m.connect('admin_settings_labs', '/settings/labs',
404 404 action='settings_labs', conditions={'method': ['GET']})
405 405
406 406 # ADMIN MY ACCOUNT
407 407 with rmap.submapper(path_prefix=ADMIN_PREFIX,
408 408 controller='admin/my_account') as m:
409 409
410 410 # NOTE(marcink): this needs to be kept for password force flag to be
411 411 # handled in pylons controllers, remove after full migration to pyramid
412 412 m.connect('my_account_password', '/my_account/password',
413 413 action='my_account_password', conditions={'method': ['GET']})
414 414
415 415 #==========================================================================
416 416 # REPOSITORY ROUTES
417 417 #==========================================================================
418 418
419 419 # repo edit options
420 420 rmap.connect('edit_repo_fields', '/{repo_name}/settings/fields',
421 421 controller='admin/repos', action='edit_fields',
422 422 conditions={'method': ['GET'], 'function': check_repo},
423 423 requirements=URL_NAME_REQUIREMENTS)
424 424 rmap.connect('create_repo_fields', '/{repo_name}/settings/fields/new',
425 425 controller='admin/repos', action='create_repo_field',
426 426 conditions={'method': ['PUT'], 'function': check_repo},
427 427 requirements=URL_NAME_REQUIREMENTS)
428 428 rmap.connect('delete_repo_fields', '/{repo_name}/settings/fields/{field_id}',
429 429 controller='admin/repos', action='delete_repo_field',
430 430 conditions={'method': ['DELETE'], 'function': check_repo},
431 431 requirements=URL_NAME_REQUIREMENTS)
432 432
433 433 rmap.connect('toggle_locking', '/{repo_name}/settings/advanced/locking_toggle',
434 434 controller='admin/repos', action='toggle_locking',
435 435 conditions={'method': ['GET'], 'function': check_repo},
436 436 requirements=URL_NAME_REQUIREMENTS)
437 437
438 438 rmap.connect('edit_repo_remote', '/{repo_name}/settings/remote',
439 439 controller='admin/repos', action='edit_remote_form',
440 440 conditions={'method': ['GET'], 'function': check_repo},
441 441 requirements=URL_NAME_REQUIREMENTS)
442 442 rmap.connect('edit_repo_remote', '/{repo_name}/settings/remote',
443 443 controller='admin/repos', action='edit_remote',
444 444 conditions={'method': ['PUT'], 'function': check_repo},
445 445 requirements=URL_NAME_REQUIREMENTS)
446 446
447 447 rmap.connect('edit_repo_statistics', '/{repo_name}/settings/statistics',
448 448 controller='admin/repos', action='edit_statistics_form',
449 449 conditions={'method': ['GET'], 'function': check_repo},
450 450 requirements=URL_NAME_REQUIREMENTS)
451 451 rmap.connect('edit_repo_statistics', '/{repo_name}/settings/statistics',
452 452 controller='admin/repos', action='edit_statistics',
453 453 conditions={'method': ['PUT'], 'function': check_repo},
454 454 requirements=URL_NAME_REQUIREMENTS)
455 455 rmap.connect('repo_settings_issuetracker',
456 456 '/{repo_name}/settings/issue-tracker',
457 457 controller='admin/repos', action='repo_issuetracker',
458 458 conditions={'method': ['GET'], 'function': check_repo},
459 459 requirements=URL_NAME_REQUIREMENTS)
460 460 rmap.connect('repo_issuetracker_test',
461 461 '/{repo_name}/settings/issue-tracker/test',
462 462 controller='admin/repos', action='repo_issuetracker_test',
463 463 conditions={'method': ['POST'], 'function': check_repo},
464 464 requirements=URL_NAME_REQUIREMENTS)
465 465 rmap.connect('repo_issuetracker_delete',
466 466 '/{repo_name}/settings/issue-tracker/delete',
467 467 controller='admin/repos', action='repo_issuetracker_delete',
468 468 conditions={'method': ['DELETE'], 'function': check_repo},
469 469 requirements=URL_NAME_REQUIREMENTS)
470 470 rmap.connect('repo_issuetracker_save',
471 471 '/{repo_name}/settings/issue-tracker/save',
472 472 controller='admin/repos', action='repo_issuetracker_save',
473 473 conditions={'method': ['POST'], 'function': check_repo},
474 474 requirements=URL_NAME_REQUIREMENTS)
475 475 rmap.connect('repo_vcs_settings', '/{repo_name}/settings/vcs',
476 476 controller='admin/repos', action='repo_settings_vcs_update',
477 477 conditions={'method': ['POST'], 'function': check_repo},
478 478 requirements=URL_NAME_REQUIREMENTS)
479 479 rmap.connect('repo_vcs_settings', '/{repo_name}/settings/vcs',
480 480 controller='admin/repos', action='repo_settings_vcs',
481 481 conditions={'method': ['GET'], 'function': check_repo},
482 482 requirements=URL_NAME_REQUIREMENTS)
483 483 rmap.connect('repo_vcs_settings', '/{repo_name}/settings/vcs',
484 484 controller='admin/repos', action='repo_delete_svn_pattern',
485 485 conditions={'method': ['DELETE'], 'function': check_repo},
486 486 requirements=URL_NAME_REQUIREMENTS)
487 487 rmap.connect('repo_pullrequest_settings', '/{repo_name}/settings/pullrequest',
488 488 controller='admin/repos', action='repo_settings_pullrequest',
489 489 conditions={'method': ['GET', 'POST'], 'function': check_repo},
490 490 requirements=URL_NAME_REQUIREMENTS)
491 491
492
493 rmap.connect('repo_fork_create_home', '/{repo_name}/fork',
494 controller='forks', action='fork_create',
495 conditions={'function': check_repo, 'method': ['POST']},
496 requirements=URL_NAME_REQUIREMENTS)
497
498 rmap.connect('repo_fork_home', '/{repo_name}/fork',
499 controller='forks', action='fork',
500 conditions={'function': check_repo},
501 requirements=URL_NAME_REQUIREMENTS)
502
503 rmap.connect('repo_forks_home', '/{repo_name}/forks',
504 controller='forks', action='forks',
505 conditions={'function': check_repo},
506 requirements=URL_NAME_REQUIREMENTS)
507
508 492 return rmap
@@ -1,2027 +1,1994 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2010-2017 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 21 """
22 22 authentication and permission libraries
23 23 """
24 24
25 25 import os
26 26 import inspect
27 27 import collections
28 28 import fnmatch
29 29 import hashlib
30 30 import itertools
31 31 import logging
32 32 import random
33 33 import traceback
34 34 from functools import wraps
35 35
36 36 import ipaddress
37 37 from pyramid.httpexceptions import HTTPForbidden, HTTPFound, HTTPNotFound
38 38 from pylons.i18n.translation import _
39 39 # NOTE(marcink): this has to be removed only after pyramid migration,
40 40 # replace with _ = request.translate
41 41 from sqlalchemy.orm.exc import ObjectDeletedError
42 42 from sqlalchemy.orm import joinedload
43 43 from zope.cachedescriptors.property import Lazy as LazyProperty
44 44
45 45 import rhodecode
46 46 from rhodecode.model import meta
47 47 from rhodecode.model.meta import Session
48 48 from rhodecode.model.user import UserModel
49 49 from rhodecode.model.db import (
50 50 User, Repository, Permission, UserToPerm, UserGroupToPerm, UserGroupMember,
51 51 UserIpMap, UserApiKeys, RepoGroup)
52 52 from rhodecode.lib import caches
53 53 from rhodecode.lib.utils2 import safe_unicode, aslist, safe_str, md5
54 54 from rhodecode.lib.utils import (
55 55 get_repo_slug, get_repo_group_slug, get_user_group_slug)
56 56 from rhodecode.lib.caching_query import FromCache
57 57
58 58
59 59 if rhodecode.is_unix:
60 60 import bcrypt
61 61
62 62 log = logging.getLogger(__name__)
63 63
64 64 csrf_token_key = "csrf_token"
65 65
66 66
67 67 class PasswordGenerator(object):
68 68 """
69 69 This is a simple class for generating password from different sets of
70 70 characters
71 71 usage::
72 72
73 73 passwd_gen = PasswordGenerator()
74 74 #print 8-letter password containing only big and small letters
75 75 of alphabet
76 76 passwd_gen.gen_password(8, passwd_gen.ALPHABETS_BIG_SMALL)
77 77 """
78 78 ALPHABETS_NUM = r'''1234567890'''
79 79 ALPHABETS_SMALL = r'''qwertyuiopasdfghjklzxcvbnm'''
80 80 ALPHABETS_BIG = r'''QWERTYUIOPASDFGHJKLZXCVBNM'''
81 81 ALPHABETS_SPECIAL = r'''`-=[]\;',./~!@#$%^&*()_+{}|:"<>?'''
82 82 ALPHABETS_FULL = ALPHABETS_BIG + ALPHABETS_SMALL \
83 83 + ALPHABETS_NUM + ALPHABETS_SPECIAL
84 84 ALPHABETS_ALPHANUM = ALPHABETS_BIG + ALPHABETS_SMALL + ALPHABETS_NUM
85 85 ALPHABETS_BIG_SMALL = ALPHABETS_BIG + ALPHABETS_SMALL
86 86 ALPHABETS_ALPHANUM_BIG = ALPHABETS_BIG + ALPHABETS_NUM
87 87 ALPHABETS_ALPHANUM_SMALL = ALPHABETS_SMALL + ALPHABETS_NUM
88 88
89 89 def __init__(self, passwd=''):
90 90 self.passwd = passwd
91 91
92 92 def gen_password(self, length, type_=None):
93 93 if type_ is None:
94 94 type_ = self.ALPHABETS_FULL
95 95 self.passwd = ''.join([random.choice(type_) for _ in xrange(length)])
96 96 return self.passwd
97 97
98 98
99 99 class _RhodeCodeCryptoBase(object):
100 100 ENC_PREF = None
101 101
102 102 def hash_create(self, str_):
103 103 """
104 104 hash the string using
105 105
106 106 :param str_: password to hash
107 107 """
108 108 raise NotImplementedError
109 109
110 110 def hash_check_with_upgrade(self, password, hashed):
111 111 """
112 112 Returns tuple in which first element is boolean that states that
113 113 given password matches it's hashed version, and the second is new hash
114 114 of the password, in case this password should be migrated to new
115 115 cipher.
116 116 """
117 117 checked_hash = self.hash_check(password, hashed)
118 118 return checked_hash, None
119 119
120 120 def hash_check(self, password, hashed):
121 121 """
122 122 Checks matching password with it's hashed value.
123 123
124 124 :param password: password
125 125 :param hashed: password in hashed form
126 126 """
127 127 raise NotImplementedError
128 128
129 129 def _assert_bytes(self, value):
130 130 """
131 131 Passing in an `unicode` object can lead to hard to detect issues
132 132 if passwords contain non-ascii characters. Doing a type check
133 133 during runtime, so that such mistakes are detected early on.
134 134 """
135 135 if not isinstance(value, str):
136 136 raise TypeError(
137 137 "Bytestring required as input, got %r." % (value, ))
138 138
139 139
140 140 class _RhodeCodeCryptoBCrypt(_RhodeCodeCryptoBase):
141 141 ENC_PREF = ('$2a$10', '$2b$10')
142 142
143 143 def hash_create(self, str_):
144 144 self._assert_bytes(str_)
145 145 return bcrypt.hashpw(str_, bcrypt.gensalt(10))
146 146
147 147 def hash_check_with_upgrade(self, password, hashed):
148 148 """
149 149 Returns tuple in which first element is boolean that states that
150 150 given password matches it's hashed version, and the second is new hash
151 151 of the password, in case this password should be migrated to new
152 152 cipher.
153 153
154 154 This implements special upgrade logic which works like that:
155 155 - check if the given password == bcrypted hash, if yes then we
156 156 properly used password and it was already in bcrypt. Proceed
157 157 without any changes
158 158 - if bcrypt hash check is not working try with sha256. If hash compare
159 159 is ok, it means we using correct but old hashed password. indicate
160 160 hash change and proceed
161 161 """
162 162
163 163 new_hash = None
164 164
165 165 # regular pw check
166 166 password_match_bcrypt = self.hash_check(password, hashed)
167 167
168 168 # now we want to know if the password was maybe from sha256
169 169 # basically calling _RhodeCodeCryptoSha256().hash_check()
170 170 if not password_match_bcrypt:
171 171 if _RhodeCodeCryptoSha256().hash_check(password, hashed):
172 172 new_hash = self.hash_create(password) # make new bcrypt hash
173 173 password_match_bcrypt = True
174 174
175 175 return password_match_bcrypt, new_hash
176 176
177 177 def hash_check(self, password, hashed):
178 178 """
179 179 Checks matching password with it's hashed value.
180 180
181 181 :param password: password
182 182 :param hashed: password in hashed form
183 183 """
184 184 self._assert_bytes(password)
185 185 try:
186 186 return bcrypt.hashpw(password, hashed) == hashed
187 187 except ValueError as e:
188 188 # we're having a invalid salt here probably, we should not crash
189 189 # just return with False as it would be a wrong password.
190 190 log.debug('Failed to check password hash using bcrypt %s',
191 191 safe_str(e))
192 192
193 193 return False
194 194
195 195
196 196 class _RhodeCodeCryptoSha256(_RhodeCodeCryptoBase):
197 197 ENC_PREF = '_'
198 198
199 199 def hash_create(self, str_):
200 200 self._assert_bytes(str_)
201 201 return hashlib.sha256(str_).hexdigest()
202 202
203 203 def hash_check(self, password, hashed):
204 204 """
205 205 Checks matching password with it's hashed value.
206 206
207 207 :param password: password
208 208 :param hashed: password in hashed form
209 209 """
210 210 self._assert_bytes(password)
211 211 return hashlib.sha256(password).hexdigest() == hashed
212 212
213 213
214 214 class _RhodeCodeCryptoMd5(_RhodeCodeCryptoBase):
215 215 ENC_PREF = '_'
216 216
217 217 def hash_create(self, str_):
218 218 self._assert_bytes(str_)
219 219 return hashlib.md5(str_).hexdigest()
220 220
221 221 def hash_check(self, password, hashed):
222 222 """
223 223 Checks matching password with it's hashed value.
224 224
225 225 :param password: password
226 226 :param hashed: password in hashed form
227 227 """
228 228 self._assert_bytes(password)
229 229 return hashlib.md5(password).hexdigest() == hashed
230 230
231 231
232 232 def crypto_backend():
233 233 """
234 234 Return the matching crypto backend.
235 235
236 236 Selection is based on if we run tests or not, we pick md5 backend to run
237 237 tests faster since BCRYPT is expensive to calculate
238 238 """
239 239 if rhodecode.is_test:
240 240 RhodeCodeCrypto = _RhodeCodeCryptoMd5()
241 241 else:
242 242 RhodeCodeCrypto = _RhodeCodeCryptoBCrypt()
243 243
244 244 return RhodeCodeCrypto
245 245
246 246
247 247 def get_crypt_password(password):
248 248 """
249 249 Create the hash of `password` with the active crypto backend.
250 250
251 251 :param password: The cleartext password.
252 252 :type password: unicode
253 253 """
254 254 password = safe_str(password)
255 255 return crypto_backend().hash_create(password)
256 256
257 257
258 258 def check_password(password, hashed):
259 259 """
260 260 Check if the value in `password` matches the hash in `hashed`.
261 261
262 262 :param password: The cleartext password.
263 263 :type password: unicode
264 264
265 265 :param hashed: The expected hashed version of the password.
266 266 :type hashed: The hash has to be passed in in text representation.
267 267 """
268 268 password = safe_str(password)
269 269 return crypto_backend().hash_check(password, hashed)
270 270
271 271
272 272 def generate_auth_token(data, salt=None):
273 273 """
274 274 Generates API KEY from given string
275 275 """
276 276
277 277 if salt is None:
278 278 salt = os.urandom(16)
279 279 return hashlib.sha1(safe_str(data) + salt).hexdigest()
280 280
281 281
282 282 class CookieStoreWrapper(object):
283 283
284 284 def __init__(self, cookie_store):
285 285 self.cookie_store = cookie_store
286 286
287 287 def __repr__(self):
288 288 return 'CookieStore<%s>' % (self.cookie_store)
289 289
290 290 def get(self, key, other=None):
291 291 if isinstance(self.cookie_store, dict):
292 292 return self.cookie_store.get(key, other)
293 293 elif isinstance(self.cookie_store, AuthUser):
294 294 return self.cookie_store.__dict__.get(key, other)
295 295
296 296
297 297 def _cached_perms_data(user_id, scope, user_is_admin,
298 298 user_inherit_default_permissions, explicit, algo):
299 299
300 300 permissions = PermissionCalculator(
301 301 user_id, scope, user_is_admin, user_inherit_default_permissions,
302 302 explicit, algo)
303 303 return permissions.calculate()
304 304
305 305
306 306 class PermOrigin(object):
307 307 ADMIN = 'superadmin'
308 308
309 309 REPO_USER = 'user:%s'
310 310 REPO_USERGROUP = 'usergroup:%s'
311 311 REPO_OWNER = 'repo.owner'
312 312 REPO_DEFAULT = 'repo.default'
313 313 REPO_PRIVATE = 'repo.private'
314 314
315 315 REPOGROUP_USER = 'user:%s'
316 316 REPOGROUP_USERGROUP = 'usergroup:%s'
317 317 REPOGROUP_OWNER = 'group.owner'
318 318 REPOGROUP_DEFAULT = 'group.default'
319 319
320 320 USERGROUP_USER = 'user:%s'
321 321 USERGROUP_USERGROUP = 'usergroup:%s'
322 322 USERGROUP_OWNER = 'usergroup.owner'
323 323 USERGROUP_DEFAULT = 'usergroup.default'
324 324
325 325
326 326 class PermOriginDict(dict):
327 327 """
328 328 A special dict used for tracking permissions along with their origins.
329 329
330 330 `__setitem__` has been overridden to expect a tuple(perm, origin)
331 331 `__getitem__` will return only the perm
332 332 `.perm_origin_stack` will return the stack of (perm, origin) set per key
333 333
334 334 >>> perms = PermOriginDict()
335 335 >>> perms['resource'] = 'read', 'default'
336 336 >>> perms['resource']
337 337 'read'
338 338 >>> perms['resource'] = 'write', 'admin'
339 339 >>> perms['resource']
340 340 'write'
341 341 >>> perms.perm_origin_stack
342 342 {'resource': [('read', 'default'), ('write', 'admin')]}
343 343 """
344 344
345 345 def __init__(self, *args, **kw):
346 346 dict.__init__(self, *args, **kw)
347 347 self.perm_origin_stack = {}
348 348
349 349 def __setitem__(self, key, (perm, origin)):
350 350 self.perm_origin_stack.setdefault(key, []).append((perm, origin))
351 351 dict.__setitem__(self, key, perm)
352 352
353 353
354 354 class PermissionCalculator(object):
355 355
356 356 def __init__(
357 357 self, user_id, scope, user_is_admin,
358 358 user_inherit_default_permissions, explicit, algo):
359 359 self.user_id = user_id
360 360 self.user_is_admin = user_is_admin
361 361 self.inherit_default_permissions = user_inherit_default_permissions
362 362 self.explicit = explicit
363 363 self.algo = algo
364 364
365 365 scope = scope or {}
366 366 self.scope_repo_id = scope.get('repo_id')
367 367 self.scope_repo_group_id = scope.get('repo_group_id')
368 368 self.scope_user_group_id = scope.get('user_group_id')
369 369
370 370 self.default_user_id = User.get_default_user(cache=True).user_id
371 371
372 372 self.permissions_repositories = PermOriginDict()
373 373 self.permissions_repository_groups = PermOriginDict()
374 374 self.permissions_user_groups = PermOriginDict()
375 375 self.permissions_global = set()
376 376
377 377 self.default_repo_perms = Permission.get_default_repo_perms(
378 378 self.default_user_id, self.scope_repo_id)
379 379 self.default_repo_groups_perms = Permission.get_default_group_perms(
380 380 self.default_user_id, self.scope_repo_group_id)
381 381 self.default_user_group_perms = \
382 382 Permission.get_default_user_group_perms(
383 383 self.default_user_id, self.scope_user_group_id)
384 384
385 385 def calculate(self):
386 386 if self.user_is_admin:
387 387 return self._admin_permissions()
388 388
389 389 self._calculate_global_default_permissions()
390 390 self._calculate_global_permissions()
391 391 self._calculate_default_permissions()
392 392 self._calculate_repository_permissions()
393 393 self._calculate_repository_group_permissions()
394 394 self._calculate_user_group_permissions()
395 395 return self._permission_structure()
396 396
397 397 def _admin_permissions(self):
398 398 """
399 399 admin user have all default rights for repositories
400 400 and groups set to admin
401 401 """
402 402 self.permissions_global.add('hg.admin')
403 403 self.permissions_global.add('hg.create.write_on_repogroup.true')
404 404
405 405 # repositories
406 406 for perm in self.default_repo_perms:
407 407 r_k = perm.UserRepoToPerm.repository.repo_name
408 408 p = 'repository.admin'
409 409 self.permissions_repositories[r_k] = p, PermOrigin.ADMIN
410 410
411 411 # repository groups
412 412 for perm in self.default_repo_groups_perms:
413 413 rg_k = perm.UserRepoGroupToPerm.group.group_name
414 414 p = 'group.admin'
415 415 self.permissions_repository_groups[rg_k] = p, PermOrigin.ADMIN
416 416
417 417 # user groups
418 418 for perm in self.default_user_group_perms:
419 419 u_k = perm.UserUserGroupToPerm.user_group.users_group_name
420 420 p = 'usergroup.admin'
421 421 self.permissions_user_groups[u_k] = p, PermOrigin.ADMIN
422 422
423 423 return self._permission_structure()
424 424
425 425 def _calculate_global_default_permissions(self):
426 426 """
427 427 global permissions taken from the default user
428 428 """
429 429 default_global_perms = UserToPerm.query()\
430 430 .filter(UserToPerm.user_id == self.default_user_id)\
431 431 .options(joinedload(UserToPerm.permission))
432 432
433 433 for perm in default_global_perms:
434 434 self.permissions_global.add(perm.permission.permission_name)
435 435
436 436 def _calculate_global_permissions(self):
437 437 """
438 438 Set global system permissions with user permissions or permissions
439 439 taken from the user groups of the current user.
440 440
441 441 The permissions include repo creating, repo group creating, forking
442 442 etc.
443 443 """
444 444
445 445 # now we read the defined permissions and overwrite what we have set
446 446 # before those can be configured from groups or users explicitly.
447 447
448 448 # TODO: johbo: This seems to be out of sync, find out the reason
449 449 # for the comment below and update it.
450 450
451 451 # In case we want to extend this list we should be always in sync with
452 452 # User.DEFAULT_USER_PERMISSIONS definitions
453 453 _configurable = frozenset([
454 454 'hg.fork.none', 'hg.fork.repository',
455 455 'hg.create.none', 'hg.create.repository',
456 456 'hg.usergroup.create.false', 'hg.usergroup.create.true',
457 457 'hg.repogroup.create.false', 'hg.repogroup.create.true',
458 458 'hg.create.write_on_repogroup.false',
459 459 'hg.create.write_on_repogroup.true',
460 460 'hg.inherit_default_perms.false', 'hg.inherit_default_perms.true'
461 461 ])
462 462
463 463 # USER GROUPS comes first user group global permissions
464 464 user_perms_from_users_groups = Session().query(UserGroupToPerm)\
465 465 .options(joinedload(UserGroupToPerm.permission))\
466 466 .join((UserGroupMember, UserGroupToPerm.users_group_id ==
467 467 UserGroupMember.users_group_id))\
468 468 .filter(UserGroupMember.user_id == self.user_id)\
469 469 .order_by(UserGroupToPerm.users_group_id)\
470 470 .all()
471 471
472 472 # need to group here by groups since user can be in more than
473 473 # one group, so we get all groups
474 474 _explicit_grouped_perms = [
475 475 [x, list(y)] for x, y in
476 476 itertools.groupby(user_perms_from_users_groups,
477 477 lambda _x: _x.users_group)]
478 478
479 479 for gr, perms in _explicit_grouped_perms:
480 480 # since user can be in multiple groups iterate over them and
481 481 # select the lowest permissions first (more explicit)
482 482 # TODO: marcink: do this^^
483 483
484 484 # group doesn't inherit default permissions so we actually set them
485 485 if not gr.inherit_default_permissions:
486 486 # NEED TO IGNORE all previously set configurable permissions
487 487 # and replace them with explicitly set from this user
488 488 # group permissions
489 489 self.permissions_global = self.permissions_global.difference(
490 490 _configurable)
491 491 for perm in perms:
492 492 self.permissions_global.add(perm.permission.permission_name)
493 493
494 494 # user explicit global permissions
495 495 user_perms = Session().query(UserToPerm)\
496 496 .options(joinedload(UserToPerm.permission))\
497 497 .filter(UserToPerm.user_id == self.user_id).all()
498 498
499 499 if not self.inherit_default_permissions:
500 500 # NEED TO IGNORE all configurable permissions and
501 501 # replace them with explicitly set from this user permissions
502 502 self.permissions_global = self.permissions_global.difference(
503 503 _configurable)
504 504 for perm in user_perms:
505 505 self.permissions_global.add(perm.permission.permission_name)
506 506
507 507 def _calculate_default_permissions(self):
508 508 """
509 509 Set default user permissions for repositories, repository groups
510 510 taken from the default user.
511 511
512 512 Calculate inheritance of object permissions based on what we have now
513 513 in GLOBAL permissions. We check if .false is in GLOBAL since this is
514 514 explicitly set. Inherit is the opposite of .false being there.
515 515
516 516 .. note::
517 517
518 518 the syntax is little bit odd but what we need to check here is
519 519 the opposite of .false permission being in the list so even for
520 520 inconsistent state when both .true/.false is there
521 521 .false is more important
522 522
523 523 """
524 524 user_inherit_object_permissions = not ('hg.inherit_default_perms.false'
525 525 in self.permissions_global)
526 526
527 527 # defaults for repositories, taken from `default` user permissions
528 528 # on given repo
529 529 for perm in self.default_repo_perms:
530 530 r_k = perm.UserRepoToPerm.repository.repo_name
531 531 o = PermOrigin.REPO_DEFAULT
532 532 if perm.Repository.private and not (
533 533 perm.Repository.user_id == self.user_id):
534 534 # disable defaults for private repos,
535 535 p = 'repository.none'
536 536 o = PermOrigin.REPO_PRIVATE
537 537 elif perm.Repository.user_id == self.user_id:
538 538 # set admin if owner
539 539 p = 'repository.admin'
540 540 o = PermOrigin.REPO_OWNER
541 541 else:
542 542 p = perm.Permission.permission_name
543 543 # if we decide this user isn't inheriting permissions from
544 544 # default user we set him to .none so only explicit
545 545 # permissions work
546 546 if not user_inherit_object_permissions:
547 547 p = 'repository.none'
548 548 self.permissions_repositories[r_k] = p, o
549 549
550 550 # defaults for repository groups taken from `default` user permission
551 551 # on given group
552 552 for perm in self.default_repo_groups_perms:
553 553 rg_k = perm.UserRepoGroupToPerm.group.group_name
554 554 o = PermOrigin.REPOGROUP_DEFAULT
555 555 if perm.RepoGroup.user_id == self.user_id:
556 556 # set admin if owner
557 557 p = 'group.admin'
558 558 o = PermOrigin.REPOGROUP_OWNER
559 559 else:
560 560 p = perm.Permission.permission_name
561 561
562 562 # if we decide this user isn't inheriting permissions from default
563 563 # user we set him to .none so only explicit permissions work
564 564 if not user_inherit_object_permissions:
565 565 p = 'group.none'
566 566 self.permissions_repository_groups[rg_k] = p, o
567 567
568 568 # defaults for user groups taken from `default` user permission
569 569 # on given user group
570 570 for perm in self.default_user_group_perms:
571 571 u_k = perm.UserUserGroupToPerm.user_group.users_group_name
572 572 o = PermOrigin.USERGROUP_DEFAULT
573 573 if perm.UserGroup.user_id == self.user_id:
574 574 # set admin if owner
575 575 p = 'usergroup.admin'
576 576 o = PermOrigin.USERGROUP_OWNER
577 577 else:
578 578 p = perm.Permission.permission_name
579 579
580 580 # if we decide this user isn't inheriting permissions from default
581 581 # user we set him to .none so only explicit permissions work
582 582 if not user_inherit_object_permissions:
583 583 p = 'usergroup.none'
584 584 self.permissions_user_groups[u_k] = p, o
585 585
586 586 def _calculate_repository_permissions(self):
587 587 """
588 588 Repository permissions for the current user.
589 589
590 590 Check if the user is part of user groups for this repository and
591 591 fill in the permission from it. `_choose_permission` decides of which
592 592 permission should be selected based on selected method.
593 593 """
594 594
595 595 # user group for repositories permissions
596 596 user_repo_perms_from_user_group = Permission\
597 597 .get_default_repo_perms_from_user_group(
598 598 self.user_id, self.scope_repo_id)
599 599
600 600 multiple_counter = collections.defaultdict(int)
601 601 for perm in user_repo_perms_from_user_group:
602 602 r_k = perm.UserGroupRepoToPerm.repository.repo_name
603 603 ug_k = perm.UserGroupRepoToPerm.users_group.users_group_name
604 604 multiple_counter[r_k] += 1
605 605 p = perm.Permission.permission_name
606 606 o = PermOrigin.REPO_USERGROUP % ug_k
607 607
608 608 if perm.Repository.user_id == self.user_id:
609 609 # set admin if owner
610 610 p = 'repository.admin'
611 611 o = PermOrigin.REPO_OWNER
612 612 else:
613 613 if multiple_counter[r_k] > 1:
614 614 cur_perm = self.permissions_repositories[r_k]
615 615 p = self._choose_permission(p, cur_perm)
616 616 self.permissions_repositories[r_k] = p, o
617 617
618 618 # user explicit permissions for repositories, overrides any specified
619 619 # by the group permission
620 620 user_repo_perms = Permission.get_default_repo_perms(
621 621 self.user_id, self.scope_repo_id)
622 622 for perm in user_repo_perms:
623 623 r_k = perm.UserRepoToPerm.repository.repo_name
624 624 o = PermOrigin.REPO_USER % perm.UserRepoToPerm.user.username
625 625 # set admin if owner
626 626 if perm.Repository.user_id == self.user_id:
627 627 p = 'repository.admin'
628 628 o = PermOrigin.REPO_OWNER
629 629 else:
630 630 p = perm.Permission.permission_name
631 631 if not self.explicit:
632 632 cur_perm = self.permissions_repositories.get(
633 633 r_k, 'repository.none')
634 634 p = self._choose_permission(p, cur_perm)
635 635 self.permissions_repositories[r_k] = p, o
636 636
637 637 def _calculate_repository_group_permissions(self):
638 638 """
639 639 Repository group permissions for the current user.
640 640
641 641 Check if the user is part of user groups for repository groups and
642 642 fill in the permissions from it. `_choose_permmission` decides of which
643 643 permission should be selected based on selected method.
644 644 """
645 645 # user group for repo groups permissions
646 646 user_repo_group_perms_from_user_group = Permission\
647 647 .get_default_group_perms_from_user_group(
648 648 self.user_id, self.scope_repo_group_id)
649 649
650 650 multiple_counter = collections.defaultdict(int)
651 651 for perm in user_repo_group_perms_from_user_group:
652 652 g_k = perm.UserGroupRepoGroupToPerm.group.group_name
653 653 ug_k = perm.UserGroupRepoGroupToPerm.users_group.users_group_name
654 654 o = PermOrigin.REPOGROUP_USERGROUP % ug_k
655 655 multiple_counter[g_k] += 1
656 656 p = perm.Permission.permission_name
657 657 if perm.RepoGroup.user_id == self.user_id:
658 658 # set admin if owner, even for member of other user group
659 659 p = 'group.admin'
660 660 o = PermOrigin.REPOGROUP_OWNER
661 661 else:
662 662 if multiple_counter[g_k] > 1:
663 663 cur_perm = self.permissions_repository_groups[g_k]
664 664 p = self._choose_permission(p, cur_perm)
665 665 self.permissions_repository_groups[g_k] = p, o
666 666
667 667 # user explicit permissions for repository groups
668 668 user_repo_groups_perms = Permission.get_default_group_perms(
669 669 self.user_id, self.scope_repo_group_id)
670 670 for perm in user_repo_groups_perms:
671 671 rg_k = perm.UserRepoGroupToPerm.group.group_name
672 672 u_k = perm.UserRepoGroupToPerm.user.username
673 673 o = PermOrigin.REPOGROUP_USER % u_k
674 674
675 675 if perm.RepoGroup.user_id == self.user_id:
676 676 # set admin if owner
677 677 p = 'group.admin'
678 678 o = PermOrigin.REPOGROUP_OWNER
679 679 else:
680 680 p = perm.Permission.permission_name
681 681 if not self.explicit:
682 682 cur_perm = self.permissions_repository_groups.get(
683 683 rg_k, 'group.none')
684 684 p = self._choose_permission(p, cur_perm)
685 685 self.permissions_repository_groups[rg_k] = p, o
686 686
687 687 def _calculate_user_group_permissions(self):
688 688 """
689 689 User group permissions for the current user.
690 690 """
691 691 # user group for user group permissions
692 692 user_group_from_user_group = Permission\
693 693 .get_default_user_group_perms_from_user_group(
694 694 self.user_id, self.scope_user_group_id)
695 695
696 696 multiple_counter = collections.defaultdict(int)
697 697 for perm in user_group_from_user_group:
698 698 g_k = perm.UserGroupUserGroupToPerm\
699 699 .target_user_group.users_group_name
700 700 u_k = perm.UserGroupUserGroupToPerm\
701 701 .user_group.users_group_name
702 702 o = PermOrigin.USERGROUP_USERGROUP % u_k
703 703 multiple_counter[g_k] += 1
704 704 p = perm.Permission.permission_name
705 705
706 706 if perm.UserGroup.user_id == self.user_id:
707 707 # set admin if owner, even for member of other user group
708 708 p = 'usergroup.admin'
709 709 o = PermOrigin.USERGROUP_OWNER
710 710 else:
711 711 if multiple_counter[g_k] > 1:
712 712 cur_perm = self.permissions_user_groups[g_k]
713 713 p = self._choose_permission(p, cur_perm)
714 714 self.permissions_user_groups[g_k] = p, o
715 715
716 716 # user explicit permission for user groups
717 717 user_user_groups_perms = Permission.get_default_user_group_perms(
718 718 self.user_id, self.scope_user_group_id)
719 719 for perm in user_user_groups_perms:
720 720 ug_k = perm.UserUserGroupToPerm.user_group.users_group_name
721 721 u_k = perm.UserUserGroupToPerm.user.username
722 722 o = PermOrigin.USERGROUP_USER % u_k
723 723
724 724 if perm.UserGroup.user_id == self.user_id:
725 725 # set admin if owner
726 726 p = 'usergroup.admin'
727 727 o = PermOrigin.USERGROUP_OWNER
728 728 else:
729 729 p = perm.Permission.permission_name
730 730 if not self.explicit:
731 731 cur_perm = self.permissions_user_groups.get(
732 732 ug_k, 'usergroup.none')
733 733 p = self._choose_permission(p, cur_perm)
734 734 self.permissions_user_groups[ug_k] = p, o
735 735
736 736 def _choose_permission(self, new_perm, cur_perm):
737 737 new_perm_val = Permission.PERM_WEIGHTS[new_perm]
738 738 cur_perm_val = Permission.PERM_WEIGHTS[cur_perm]
739 739 if self.algo == 'higherwin':
740 740 if new_perm_val > cur_perm_val:
741 741 return new_perm
742 742 return cur_perm
743 743 elif self.algo == 'lowerwin':
744 744 if new_perm_val < cur_perm_val:
745 745 return new_perm
746 746 return cur_perm
747 747
748 748 def _permission_structure(self):
749 749 return {
750 750 'global': self.permissions_global,
751 751 'repositories': self.permissions_repositories,
752 752 'repositories_groups': self.permissions_repository_groups,
753 753 'user_groups': self.permissions_user_groups,
754 754 }
755 755
756 756
757 757 def allowed_auth_token_access(view_name, whitelist=None, auth_token=None):
758 758 """
759 759 Check if given controller_name is in whitelist of auth token access
760 760 """
761 761 if not whitelist:
762 762 from rhodecode import CONFIG
763 763 whitelist = aslist(
764 764 CONFIG.get('api_access_controllers_whitelist'), sep=',')
765 765 log.debug(
766 766 'Allowed controllers for AUTH TOKEN access: %s' % (whitelist,))
767 767
768 768 auth_token_access_valid = False
769 769 for entry in whitelist:
770 770 if fnmatch.fnmatch(view_name, entry):
771 771 auth_token_access_valid = True
772 772 break
773 773
774 774 if auth_token_access_valid:
775 775 log.debug('view: `%s` matches entry in whitelist: %s'
776 776 % (view_name, whitelist))
777 777 else:
778 778 msg = ('view: `%s` does *NOT* match any entry in whitelist: %s'
779 779 % (view_name, whitelist))
780 780 if auth_token:
781 781 # if we use auth token key and don't have access it's a warning
782 782 log.warning(msg)
783 783 else:
784 784 log.debug(msg)
785 785
786 786 return auth_token_access_valid
787 787
788 788
789 789 class AuthUser(object):
790 790 """
791 791 A simple object that handles all attributes of user in RhodeCode
792 792
793 793 It does lookup based on API key,given user, or user present in session
794 794 Then it fills all required information for such user. It also checks if
795 795 anonymous access is enabled and if so, it returns default user as logged in
796 796 """
797 797 GLOBAL_PERMS = [x[0] for x in Permission.PERMS]
798 798
799 799 def __init__(self, user_id=None, api_key=None, username=None, ip_addr=None):
800 800
801 801 self.user_id = user_id
802 802 self._api_key = api_key
803 803
804 804 self.api_key = None
805 805 self.feed_token = ''
806 806 self.username = username
807 807 self.ip_addr = ip_addr
808 808 self.name = ''
809 809 self.lastname = ''
810 810 self.first_name = ''
811 811 self.last_name = ''
812 812 self.email = ''
813 813 self.is_authenticated = False
814 814 self.admin = False
815 815 self.inherit_default_permissions = False
816 816 self.password = ''
817 817
818 818 self.anonymous_user = None # propagated on propagate_data
819 819 self.propagate_data()
820 820 self._instance = None
821 821 self._permissions_scoped_cache = {} # used to bind scoped calculation
822 822
823 823 @LazyProperty
824 824 def permissions(self):
825 825 return self.get_perms(user=self, cache=False)
826 826
827 827 def permissions_with_scope(self, scope):
828 828 """
829 829 Call the get_perms function with scoped data. The scope in that function
830 830 narrows the SQL calls to the given ID of objects resulting in fetching
831 831 Just particular permission we want to obtain. If scope is an empty dict
832 832 then it basically narrows the scope to GLOBAL permissions only.
833 833
834 834 :param scope: dict
835 835 """
836 836 if 'repo_name' in scope:
837 837 obj = Repository.get_by_repo_name(scope['repo_name'])
838 838 if obj:
839 839 scope['repo_id'] = obj.repo_id
840 840 _scope = {
841 841 'repo_id': -1,
842 842 'user_group_id': -1,
843 843 'repo_group_id': -1,
844 844 }
845 845 _scope.update(scope)
846 846 cache_key = "_".join(map(safe_str, reduce(lambda a, b: a+b,
847 847 _scope.items())))
848 848 if cache_key not in self._permissions_scoped_cache:
849 849 # store in cache to mimic how the @LazyProperty works,
850 850 # the difference here is that we use the unique key calculated
851 851 # from params and values
852 852 res = self.get_perms(user=self, cache=False, scope=_scope)
853 853 self._permissions_scoped_cache[cache_key] = res
854 854 return self._permissions_scoped_cache[cache_key]
855 855
856 856 def get_instance(self):
857 857 return User.get(self.user_id)
858 858
859 859 def update_lastactivity(self):
860 860 if self.user_id:
861 861 User.get(self.user_id).update_lastactivity()
862 862
863 863 def propagate_data(self):
864 864 """
865 865 Fills in user data and propagates values to this instance. Maps fetched
866 866 user attributes to this class instance attributes
867 867 """
868 868 log.debug('AuthUser: starting data propagation for new potential user')
869 869 user_model = UserModel()
870 870 anon_user = self.anonymous_user = User.get_default_user(cache=True)
871 871 is_user_loaded = False
872 872
873 873 # lookup by userid
874 874 if self.user_id is not None and self.user_id != anon_user.user_id:
875 875 log.debug('Trying Auth User lookup by USER ID: `%s`', self.user_id)
876 876 is_user_loaded = user_model.fill_data(self, user_id=self.user_id)
877 877
878 878 # try go get user by api key
879 879 elif self._api_key and self._api_key != anon_user.api_key:
880 880 log.debug('Trying Auth User lookup by API KEY: `%s`', self._api_key)
881 881 is_user_loaded = user_model.fill_data(self, api_key=self._api_key)
882 882
883 883 # lookup by username
884 884 elif self.username:
885 885 log.debug('Trying Auth User lookup by USER NAME: `%s`', self.username)
886 886 is_user_loaded = user_model.fill_data(self, username=self.username)
887 887 else:
888 888 log.debug('No data in %s that could been used to log in', self)
889 889
890 890 if not is_user_loaded:
891 891 log.debug('Failed to load user. Fallback to default user')
892 892 # if we cannot authenticate user try anonymous
893 893 if anon_user.active:
894 894 user_model.fill_data(self, user_id=anon_user.user_id)
895 895 # then we set this user is logged in
896 896 self.is_authenticated = True
897 897 else:
898 898 # in case of disabled anonymous user we reset some of the
899 899 # parameters so such user is "corrupted", skipping the fill_data
900 900 for attr in ['user_id', 'username', 'admin', 'active']:
901 901 setattr(self, attr, None)
902 902 self.is_authenticated = False
903 903
904 904 if not self.username:
905 905 self.username = 'None'
906 906
907 907 log.debug('AuthUser: propagated user is now %s', self)
908 908
909 909 def get_perms(self, user, scope=None, explicit=True, algo='higherwin',
910 910 cache=False):
911 911 """
912 912 Fills user permission attribute with permissions taken from database
913 913 works for permissions given for repositories, and for permissions that
914 914 are granted to groups
915 915
916 916 :param user: instance of User object from database
917 917 :param explicit: In case there are permissions both for user and a group
918 918 that user is part of, explicit flag will defiine if user will
919 919 explicitly override permissions from group, if it's False it will
920 920 make decision based on the algo
921 921 :param algo: algorithm to decide what permission should be choose if
922 922 it's multiple defined, eg user in two different groups. It also
923 923 decides if explicit flag is turned off how to specify the permission
924 924 for case when user is in a group + have defined separate permission
925 925 """
926 926 user_id = user.user_id
927 927 user_is_admin = user.is_admin
928 928
929 929 # inheritance of global permissions like create repo/fork repo etc
930 930 user_inherit_default_permissions = user.inherit_default_permissions
931 931
932 932 log.debug('Computing PERMISSION tree for scope %s' % (scope, ))
933 933 compute = caches.conditional_cache(
934 934 'short_term', 'cache_desc',
935 935 condition=cache, func=_cached_perms_data)
936 936 result = compute(user_id, scope, user_is_admin,
937 937 user_inherit_default_permissions, explicit, algo)
938 938
939 939 result_repr = []
940 940 for k in result:
941 941 result_repr.append((k, len(result[k])))
942 942
943 943 log.debug('PERMISSION tree computed %s' % (result_repr,))
944 944 return result
945 945
946 946 @property
947 947 def is_default(self):
948 948 return self.username == User.DEFAULT_USER
949 949
950 950 @property
951 951 def is_admin(self):
952 952 return self.admin
953 953
954 954 @property
955 955 def is_user_object(self):
956 956 return self.user_id is not None
957 957
958 958 @property
959 959 def repositories_admin(self):
960 960 """
961 961 Returns list of repositories you're an admin of
962 962 """
963 963 return [
964 964 x[0] for x in self.permissions['repositories'].iteritems()
965 965 if x[1] == 'repository.admin']
966 966
967 967 @property
968 968 def repository_groups_admin(self):
969 969 """
970 970 Returns list of repository groups you're an admin of
971 971 """
972 972 return [
973 973 x[0] for x in self.permissions['repositories_groups'].iteritems()
974 974 if x[1] == 'group.admin']
975 975
976 976 @property
977 977 def user_groups_admin(self):
978 978 """
979 979 Returns list of user groups you're an admin of
980 980 """
981 981 return [
982 982 x[0] for x in self.permissions['user_groups'].iteritems()
983 983 if x[1] == 'usergroup.admin']
984 984
985 985 @property
986 986 def ip_allowed(self):
987 987 """
988 988 Checks if ip_addr used in constructor is allowed from defined list of
989 989 allowed ip_addresses for user
990 990
991 991 :returns: boolean, True if ip is in allowed ip range
992 992 """
993 993 # check IP
994 994 inherit = self.inherit_default_permissions
995 995 return AuthUser.check_ip_allowed(self.user_id, self.ip_addr,
996 996 inherit_from_default=inherit)
997 997 @property
998 998 def personal_repo_group(self):
999 999 return RepoGroup.get_user_personal_repo_group(self.user_id)
1000 1000
1001 1001 @classmethod
1002 1002 def check_ip_allowed(cls, user_id, ip_addr, inherit_from_default):
1003 1003 allowed_ips = AuthUser.get_allowed_ips(
1004 1004 user_id, cache=True, inherit_from_default=inherit_from_default)
1005 1005 if check_ip_access(source_ip=ip_addr, allowed_ips=allowed_ips):
1006 1006 log.debug('IP:%s is in range of %s' % (ip_addr, allowed_ips))
1007 1007 return True
1008 1008 else:
1009 1009 log.info('Access for IP:%s forbidden, '
1010 1010 'not in %s' % (ip_addr, allowed_ips))
1011 1011 return False
1012 1012
1013 1013 def __repr__(self):
1014 1014 return "<AuthUser('id:%s[%s] ip:%s auth:%s')>"\
1015 1015 % (self.user_id, self.username, self.ip_addr, self.is_authenticated)
1016 1016
1017 1017 def set_authenticated(self, authenticated=True):
1018 1018 if self.user_id != self.anonymous_user.user_id:
1019 1019 self.is_authenticated = authenticated
1020 1020
1021 1021 def get_cookie_store(self):
1022 1022 return {
1023 1023 'username': self.username,
1024 1024 'password': md5(self.password),
1025 1025 'user_id': self.user_id,
1026 1026 'is_authenticated': self.is_authenticated
1027 1027 }
1028 1028
1029 1029 @classmethod
1030 1030 def from_cookie_store(cls, cookie_store):
1031 1031 """
1032 1032 Creates AuthUser from a cookie store
1033 1033
1034 1034 :param cls:
1035 1035 :param cookie_store:
1036 1036 """
1037 1037 user_id = cookie_store.get('user_id')
1038 1038 username = cookie_store.get('username')
1039 1039 api_key = cookie_store.get('api_key')
1040 1040 return AuthUser(user_id, api_key, username)
1041 1041
1042 1042 @classmethod
1043 1043 def get_allowed_ips(cls, user_id, cache=False, inherit_from_default=False):
1044 1044 _set = set()
1045 1045
1046 1046 if inherit_from_default:
1047 1047 default_ips = UserIpMap.query().filter(
1048 1048 UserIpMap.user == User.get_default_user(cache=True))
1049 1049 if cache:
1050 1050 default_ips = default_ips.options(
1051 1051 FromCache("sql_cache_short", "get_user_ips_default"))
1052 1052
1053 1053 # populate from default user
1054 1054 for ip in default_ips:
1055 1055 try:
1056 1056 _set.add(ip.ip_addr)
1057 1057 except ObjectDeletedError:
1058 1058 # since we use heavy caching sometimes it happens that
1059 1059 # we get deleted objects here, we just skip them
1060 1060 pass
1061 1061
1062 1062 user_ips = UserIpMap.query().filter(UserIpMap.user_id == user_id)
1063 1063 if cache:
1064 1064 user_ips = user_ips.options(
1065 1065 FromCache("sql_cache_short", "get_user_ips_%s" % user_id))
1066 1066
1067 1067 for ip in user_ips:
1068 1068 try:
1069 1069 _set.add(ip.ip_addr)
1070 1070 except ObjectDeletedError:
1071 1071 # since we use heavy caching sometimes it happens that we get
1072 1072 # deleted objects here, we just skip them
1073 1073 pass
1074 1074 return _set or set(['0.0.0.0/0', '::/0'])
1075 1075
1076 1076
1077 1077 def set_available_permissions(config):
1078 1078 """
1079 1079 This function will propagate pylons globals with all available defined
1080 1080 permission given in db. We don't want to check each time from db for new
1081 1081 permissions since adding a new permission also requires application restart
1082 1082 ie. to decorate new views with the newly created permission
1083 1083
1084 1084 :param config: current pylons config instance
1085 1085
1086 1086 """
1087 1087 log.info('getting information about all available permissions')
1088 1088 try:
1089 1089 sa = meta.Session
1090 1090 all_perms = sa.query(Permission).all()
1091 1091 config['available_permissions'] = [x.permission_name for x in all_perms]
1092 1092 except Exception:
1093 1093 log.error(traceback.format_exc())
1094 1094 finally:
1095 1095 meta.Session.remove()
1096 1096
1097 1097
1098 1098 def get_csrf_token(session=None, force_new=False, save_if_missing=True):
1099 1099 """
1100 1100 Return the current authentication token, creating one if one doesn't
1101 1101 already exist and the save_if_missing flag is present.
1102 1102
1103 1103 :param session: pass in the pylons session, else we use the global ones
1104 1104 :param force_new: force to re-generate the token and store it in session
1105 1105 :param save_if_missing: save the newly generated token if it's missing in
1106 1106 session
1107 1107 """
1108 1108 # NOTE(marcink): probably should be replaced with below one from pyramid 1.9
1109 1109 # from pyramid.csrf import get_csrf_token
1110 1110
1111 1111 if not session:
1112 1112 from pylons import session
1113 1113
1114 1114 if (csrf_token_key not in session and save_if_missing) or force_new:
1115 1115 token = hashlib.sha1(str(random.getrandbits(128))).hexdigest()
1116 1116 session[csrf_token_key] = token
1117 1117 if hasattr(session, 'save'):
1118 1118 session.save()
1119 1119 return session.get(csrf_token_key)
1120 1120
1121 1121
1122 1122 def get_request(perm_class):
1123 1123 from pyramid.threadlocal import get_current_request
1124 1124 pyramid_request = get_current_request()
1125 1125 if not pyramid_request:
1126 1126 # return global request of pylons in case pyramid isn't available
1127 1127 # NOTE(marcink): this should be removed after migration to pyramid
1128 1128 from pylons import request
1129 1129 return request
1130 1130 return pyramid_request
1131 1131
1132 1132
1133 1133 # CHECK DECORATORS
1134 1134 class CSRFRequired(object):
1135 1135 """
1136 1136 Decorator for authenticating a form
1137 1137
1138 1138 This decorator uses an authorization token stored in the client's
1139 1139 session for prevention of certain Cross-site request forgery (CSRF)
1140 1140 attacks (See
1141 1141 http://en.wikipedia.org/wiki/Cross-site_request_forgery for more
1142 1142 information).
1143 1143
1144 1144 For use with the ``webhelpers.secure_form`` helper functions.
1145 1145
1146 1146 """
1147 1147 def __init__(self, token=csrf_token_key, header='X-CSRF-Token',
1148 1148 except_methods=None):
1149 1149 self.token = token
1150 1150 self.header = header
1151 1151 self.except_methods = except_methods or []
1152 1152
1153 1153 def __call__(self, func):
1154 1154 return get_cython_compat_decorator(self.__wrapper, func)
1155 1155
1156 1156 def _get_csrf(self, _request):
1157 1157 return _request.POST.get(self.token, _request.headers.get(self.header))
1158 1158
1159 1159 def check_csrf(self, _request, cur_token):
1160 1160 supplied_token = self._get_csrf(_request)
1161 1161 return supplied_token and supplied_token == cur_token
1162 1162
1163 1163 def _get_request(self):
1164 1164 return get_request(self)
1165 1165
1166 1166 def __wrapper(self, func, *fargs, **fkwargs):
1167 1167 request = self._get_request()
1168 1168
1169 1169 if request.method in self.except_methods:
1170 1170 return func(*fargs, **fkwargs)
1171 1171
1172 1172 cur_token = get_csrf_token(save_if_missing=False)
1173 1173 if self.check_csrf(request, cur_token):
1174 1174 if request.POST.get(self.token):
1175 1175 del request.POST[self.token]
1176 1176 return func(*fargs, **fkwargs)
1177 1177 else:
1178 1178 reason = 'token-missing'
1179 1179 supplied_token = self._get_csrf(request)
1180 1180 if supplied_token and cur_token != supplied_token:
1181 1181 reason = 'token-mismatch [%s:%s]' % (
1182 1182 cur_token or ''[:6], supplied_token or ''[:6])
1183 1183
1184 1184 csrf_message = \
1185 1185 ("Cross-site request forgery detected, request denied. See "
1186 1186 "http://en.wikipedia.org/wiki/Cross-site_request_forgery for "
1187 1187 "more information.")
1188 1188 log.warn('Cross-site request forgery detected, request %r DENIED: %s '
1189 1189 'REMOTE_ADDR:%s, HEADERS:%s' % (
1190 1190 request, reason, request.remote_addr, request.headers))
1191 1191
1192 1192 raise HTTPForbidden(explanation=csrf_message)
1193 1193
1194 1194
1195 1195 class LoginRequired(object):
1196 1196 """
1197 1197 Must be logged in to execute this function else
1198 1198 redirect to login page
1199 1199
1200 1200 :param api_access: if enabled this checks only for valid auth token
1201 1201 and grants access based on valid token
1202 1202 """
1203 1203 def __init__(self, auth_token_access=None):
1204 1204 self.auth_token_access = auth_token_access
1205 1205
1206 1206 def __call__(self, func):
1207 1207 return get_cython_compat_decorator(self.__wrapper, func)
1208 1208
1209 1209 def _get_request(self):
1210 1210 return get_request(self)
1211 1211
1212 1212 def __wrapper(self, func, *fargs, **fkwargs):
1213 1213 from rhodecode.lib import helpers as h
1214 1214 cls = fargs[0]
1215 1215 user = cls._rhodecode_user
1216 1216 request = self._get_request()
1217 1217
1218 1218 loc = "%s:%s" % (cls.__class__.__name__, func.__name__)
1219 1219 log.debug('Starting login restriction checks for user: %s' % (user,))
1220 1220 # check if our IP is allowed
1221 1221 ip_access_valid = True
1222 1222 if not user.ip_allowed:
1223 1223 h.flash(h.literal(_('IP %s not allowed' % (user.ip_addr,))),
1224 1224 category='warning')
1225 1225 ip_access_valid = False
1226 1226
1227 1227 # check if we used an APIKEY and it's a valid one
1228 1228 # defined white-list of controllers which API access will be enabled
1229 1229 _auth_token = request.GET.get(
1230 1230 'auth_token', '') or request.GET.get('api_key', '')
1231 1231 auth_token_access_valid = allowed_auth_token_access(
1232 1232 loc, auth_token=_auth_token)
1233 1233
1234 1234 # explicit controller is enabled or API is in our whitelist
1235 1235 if self.auth_token_access or auth_token_access_valid:
1236 1236 log.debug('Checking AUTH TOKEN access for %s' % (cls,))
1237 1237 db_user = user.get_instance()
1238 1238
1239 1239 if db_user:
1240 1240 if self.auth_token_access:
1241 1241 roles = self.auth_token_access
1242 1242 else:
1243 1243 roles = [UserApiKeys.ROLE_HTTP]
1244 1244 token_match = db_user.authenticate_by_token(
1245 1245 _auth_token, roles=roles)
1246 1246 else:
1247 1247 log.debug('Unable to fetch db instance for auth user: %s', user)
1248 1248 token_match = False
1249 1249
1250 1250 if _auth_token and token_match:
1251 1251 auth_token_access_valid = True
1252 1252 log.debug('AUTH TOKEN ****%s is VALID' % (_auth_token[-4:],))
1253 1253 else:
1254 1254 auth_token_access_valid = False
1255 1255 if not _auth_token:
1256 1256 log.debug("AUTH TOKEN *NOT* present in request")
1257 1257 else:
1258 1258 log.warning(
1259 1259 "AUTH TOKEN ****%s *NOT* valid" % _auth_token[-4:])
1260 1260
1261 1261 log.debug('Checking if %s is authenticated @ %s' % (user.username, loc))
1262 1262 reason = 'RHODECODE_AUTH' if user.is_authenticated \
1263 1263 else 'AUTH_TOKEN_AUTH'
1264 1264
1265 1265 if ip_access_valid and (
1266 1266 user.is_authenticated or auth_token_access_valid):
1267 1267 log.info(
1268 1268 'user %s authenticating with:%s IS authenticated on func %s'
1269 1269 % (user, reason, loc))
1270 1270
1271 1271 # update user data to check last activity
1272 1272 user.update_lastactivity()
1273 1273 Session().commit()
1274 1274 return func(*fargs, **fkwargs)
1275 1275 else:
1276 1276 log.warning(
1277 1277 'user %s authenticating with:%s NOT authenticated on '
1278 1278 'func: %s: IP_ACCESS:%s AUTH_TOKEN_ACCESS:%s'
1279 1279 % (user, reason, loc, ip_access_valid,
1280 1280 auth_token_access_valid))
1281 1281 # we preserve the get PARAM
1282 1282 came_from = request.path_qs
1283 1283 log.debug('redirecting to login page with %s' % (came_from,))
1284 1284 raise HTTPFound(
1285 1285 h.route_path('login', _query={'came_from': came_from}))
1286 1286
1287 1287
1288 1288 class NotAnonymous(object):
1289 1289 """
1290 1290 Must be logged in to execute this function else
1291 1291 redirect to login page
1292 1292 """
1293 1293
1294 1294 def __call__(self, func):
1295 1295 return get_cython_compat_decorator(self.__wrapper, func)
1296 1296
1297 1297 def _get_request(self):
1298 1298 return get_request(self)
1299 1299
1300 1300 def __wrapper(self, func, *fargs, **fkwargs):
1301 1301 import rhodecode.lib.helpers as h
1302 1302 cls = fargs[0]
1303 1303 self.user = cls._rhodecode_user
1304 1304 request = self._get_request()
1305 1305
1306 1306 log.debug('Checking if user is not anonymous @%s' % cls)
1307 1307
1308 1308 anonymous = self.user.username == User.DEFAULT_USER
1309 1309
1310 1310 if anonymous:
1311 1311 came_from = request.path_qs
1312 1312 h.flash(_('You need to be a registered user to '
1313 1313 'perform this action'),
1314 1314 category='warning')
1315 1315 raise HTTPFound(
1316 1316 h.route_path('login', _query={'came_from': came_from}))
1317 1317 else:
1318 1318 return func(*fargs, **fkwargs)
1319 1319
1320 1320
1321 1321 class XHRRequired(object):
1322 1322 # TODO(marcink): remove this in favor of the predicates in pyramid routes
1323 1323
1324 1324 def __call__(self, func):
1325 1325 return get_cython_compat_decorator(self.__wrapper, func)
1326 1326
1327 1327 def _get_request(self):
1328 1328 return get_request(self)
1329 1329
1330 1330 def __wrapper(self, func, *fargs, **fkwargs):
1331 1331 from pylons.controllers.util import abort
1332 1332 request = self._get_request()
1333 1333
1334 1334 log.debug('Checking if request is XMLHttpRequest (XHR)')
1335 1335 xhr_message = 'This is not a valid XMLHttpRequest (XHR) request'
1336 1336
1337 1337 if not request.is_xhr:
1338 1338 abort(400, detail=xhr_message)
1339 1339
1340 1340 return func(*fargs, **fkwargs)
1341 1341
1342 1342
1343 class HasAcceptedRepoType(object):
1344 """
1345 Check if requested repo is within given repo type aliases
1346 """
1347
1348 # TODO(marcink): remove this in favor of the predicates in pyramid routes
1349
1350 def __init__(self, *repo_type_list):
1351 self.repo_type_list = set(repo_type_list)
1352
1353 def __call__(self, func):
1354 return get_cython_compat_decorator(self.__wrapper, func)
1355
1356 def __wrapper(self, func, *fargs, **fkwargs):
1357 import rhodecode.lib.helpers as h
1358 cls = fargs[0]
1359 rhodecode_repo = cls.rhodecode_repo
1360
1361 log.debug('%s checking repo type for %s in %s',
1362 self.__class__.__name__,
1363 rhodecode_repo.alias, self.repo_type_list)
1364
1365 if rhodecode_repo.alias in self.repo_type_list:
1366 return func(*fargs, **fkwargs)
1367 else:
1368 h.flash(h.literal(
1369 _('Action not supported for %s.' % rhodecode_repo.alias)),
1370 category='warning')
1371 raise HTTPFound(
1372 h.route_path('repo_summary',
1373 repo_name=cls.rhodecode_db_repo.repo_name))
1374
1375
1376 1343 class PermsDecorator(object):
1377 1344 """
1378 1345 Base class for controller decorators, we extract the current user from
1379 1346 the class itself, which has it stored in base controllers
1380 1347 """
1381 1348
1382 1349 def __init__(self, *required_perms):
1383 1350 self.required_perms = set(required_perms)
1384 1351
1385 1352 def __call__(self, func):
1386 1353 return get_cython_compat_decorator(self.__wrapper, func)
1387 1354
1388 1355 def _get_request(self):
1389 1356 return get_request(self)
1390 1357
1391 1358 def _get_came_from(self):
1392 1359 _request = self._get_request()
1393 1360
1394 1361 # both pylons/pyramid has this attribute
1395 1362 return _request.path_qs
1396 1363
1397 1364 def __wrapper(self, func, *fargs, **fkwargs):
1398 1365 import rhodecode.lib.helpers as h
1399 1366 cls = fargs[0]
1400 1367 _user = cls._rhodecode_user
1401 1368
1402 1369 log.debug('checking %s permissions %s for %s %s',
1403 1370 self.__class__.__name__, self.required_perms, cls, _user)
1404 1371
1405 1372 if self.check_permissions(_user):
1406 1373 log.debug('Permission granted for %s %s', cls, _user)
1407 1374 return func(*fargs, **fkwargs)
1408 1375
1409 1376 else:
1410 1377 log.debug('Permission denied for %s %s', cls, _user)
1411 1378 anonymous = _user.username == User.DEFAULT_USER
1412 1379
1413 1380 if anonymous:
1414 1381 came_from = self._get_came_from()
1415 1382 h.flash(_('You need to be signed in to view this page'),
1416 1383 category='warning')
1417 1384 raise HTTPFound(
1418 1385 h.route_path('login', _query={'came_from': came_from}))
1419 1386
1420 1387 else:
1421 1388 # redirect with 404 to prevent resource discovery
1422 1389 raise HTTPNotFound()
1423 1390
1424 1391 def check_permissions(self, user):
1425 1392 """Dummy function for overriding"""
1426 1393 raise NotImplementedError(
1427 1394 'You have to write this function in child class')
1428 1395
1429 1396
1430 1397 class HasPermissionAllDecorator(PermsDecorator):
1431 1398 """
1432 1399 Checks for access permission for all given predicates. All of them
1433 1400 have to be meet in order to fulfill the request
1434 1401 """
1435 1402
1436 1403 def check_permissions(self, user):
1437 1404 perms = user.permissions_with_scope({})
1438 1405 if self.required_perms.issubset(perms['global']):
1439 1406 return True
1440 1407 return False
1441 1408
1442 1409
1443 1410 class HasPermissionAnyDecorator(PermsDecorator):
1444 1411 """
1445 1412 Checks for access permission for any of given predicates. In order to
1446 1413 fulfill the request any of predicates must be meet
1447 1414 """
1448 1415
1449 1416 def check_permissions(self, user):
1450 1417 perms = user.permissions_with_scope({})
1451 1418 if self.required_perms.intersection(perms['global']):
1452 1419 return True
1453 1420 return False
1454 1421
1455 1422
1456 1423 class HasRepoPermissionAllDecorator(PermsDecorator):
1457 1424 """
1458 1425 Checks for access permission for all given predicates for specific
1459 1426 repository. All of them have to be meet in order to fulfill the request
1460 1427 """
1461 1428 def _get_repo_name(self):
1462 1429 _request = self._get_request()
1463 1430 return get_repo_slug(_request)
1464 1431
1465 1432 def check_permissions(self, user):
1466 1433 perms = user.permissions
1467 1434 repo_name = self._get_repo_name()
1468 1435
1469 1436 try:
1470 1437 user_perms = set([perms['repositories'][repo_name]])
1471 1438 except KeyError:
1472 1439 log.debug('cannot locate repo with name: `%s` in permissions defs',
1473 1440 repo_name)
1474 1441 return False
1475 1442
1476 1443 log.debug('checking `%s` permissions for repo `%s`',
1477 1444 user_perms, repo_name)
1478 1445 if self.required_perms.issubset(user_perms):
1479 1446 return True
1480 1447 return False
1481 1448
1482 1449
1483 1450 class HasRepoPermissionAnyDecorator(PermsDecorator):
1484 1451 """
1485 1452 Checks for access permission for any of given predicates for specific
1486 1453 repository. In order to fulfill the request any of predicates must be meet
1487 1454 """
1488 1455 def _get_repo_name(self):
1489 1456 _request = self._get_request()
1490 1457 return get_repo_slug(_request)
1491 1458
1492 1459 def check_permissions(self, user):
1493 1460 perms = user.permissions
1494 1461 repo_name = self._get_repo_name()
1495 1462
1496 1463 try:
1497 1464 user_perms = set([perms['repositories'][repo_name]])
1498 1465 except KeyError:
1499 1466 log.debug('cannot locate repo with name: `%s` in permissions defs',
1500 1467 repo_name)
1501 1468 return False
1502 1469
1503 1470 log.debug('checking `%s` permissions for repo `%s`',
1504 1471 user_perms, repo_name)
1505 1472 if self.required_perms.intersection(user_perms):
1506 1473 return True
1507 1474 return False
1508 1475
1509 1476
1510 1477 class HasRepoGroupPermissionAllDecorator(PermsDecorator):
1511 1478 """
1512 1479 Checks for access permission for all given predicates for specific
1513 1480 repository group. All of them have to be meet in order to
1514 1481 fulfill the request
1515 1482 """
1516 1483 def _get_repo_group_name(self):
1517 1484 _request = self._get_request()
1518 1485 return get_repo_group_slug(_request)
1519 1486
1520 1487 def check_permissions(self, user):
1521 1488 perms = user.permissions
1522 1489 group_name = self._get_repo_group_name()
1523 1490 try:
1524 1491 user_perms = set([perms['repositories_groups'][group_name]])
1525 1492 except KeyError:
1526 1493 log.debug('cannot locate repo group with name: `%s` in permissions defs',
1527 1494 group_name)
1528 1495 return False
1529 1496
1530 1497 log.debug('checking `%s` permissions for repo group `%s`',
1531 1498 user_perms, group_name)
1532 1499 if self.required_perms.issubset(user_perms):
1533 1500 return True
1534 1501 return False
1535 1502
1536 1503
1537 1504 class HasRepoGroupPermissionAnyDecorator(PermsDecorator):
1538 1505 """
1539 1506 Checks for access permission for any of given predicates for specific
1540 1507 repository group. In order to fulfill the request any
1541 1508 of predicates must be met
1542 1509 """
1543 1510 def _get_repo_group_name(self):
1544 1511 _request = self._get_request()
1545 1512 return get_repo_group_slug(_request)
1546 1513
1547 1514 def check_permissions(self, user):
1548 1515 perms = user.permissions
1549 1516 group_name = self._get_repo_group_name()
1550 1517
1551 1518 try:
1552 1519 user_perms = set([perms['repositories_groups'][group_name]])
1553 1520 except KeyError:
1554 1521 log.debug('cannot locate repo group with name: `%s` in permissions defs',
1555 1522 group_name)
1556 1523 return False
1557 1524
1558 1525 log.debug('checking `%s` permissions for repo group `%s`',
1559 1526 user_perms, group_name)
1560 1527 if self.required_perms.intersection(user_perms):
1561 1528 return True
1562 1529 return False
1563 1530
1564 1531
1565 1532 class HasUserGroupPermissionAllDecorator(PermsDecorator):
1566 1533 """
1567 1534 Checks for access permission for all given predicates for specific
1568 1535 user group. All of them have to be meet in order to fulfill the request
1569 1536 """
1570 1537 def _get_user_group_name(self):
1571 1538 _request = self._get_request()
1572 1539 return get_user_group_slug(_request)
1573 1540
1574 1541 def check_permissions(self, user):
1575 1542 perms = user.permissions
1576 1543 group_name = self._get_user_group_name()
1577 1544 try:
1578 1545 user_perms = set([perms['user_groups'][group_name]])
1579 1546 except KeyError:
1580 1547 return False
1581 1548
1582 1549 if self.required_perms.issubset(user_perms):
1583 1550 return True
1584 1551 return False
1585 1552
1586 1553
1587 1554 class HasUserGroupPermissionAnyDecorator(PermsDecorator):
1588 1555 """
1589 1556 Checks for access permission for any of given predicates for specific
1590 1557 user group. In order to fulfill the request any of predicates must be meet
1591 1558 """
1592 1559 def _get_user_group_name(self):
1593 1560 _request = self._get_request()
1594 1561 return get_user_group_slug(_request)
1595 1562
1596 1563 def check_permissions(self, user):
1597 1564 perms = user.permissions
1598 1565 group_name = self._get_user_group_name()
1599 1566 try:
1600 1567 user_perms = set([perms['user_groups'][group_name]])
1601 1568 except KeyError:
1602 1569 return False
1603 1570
1604 1571 if self.required_perms.intersection(user_perms):
1605 1572 return True
1606 1573 return False
1607 1574
1608 1575
1609 1576 # CHECK FUNCTIONS
1610 1577 class PermsFunction(object):
1611 1578 """Base function for other check functions"""
1612 1579
1613 1580 def __init__(self, *perms):
1614 1581 self.required_perms = set(perms)
1615 1582 self.repo_name = None
1616 1583 self.repo_group_name = None
1617 1584 self.user_group_name = None
1618 1585
1619 1586 def __bool__(self):
1620 1587 frame = inspect.currentframe()
1621 1588 stack_trace = traceback.format_stack(frame)
1622 1589 log.error('Checking bool value on a class instance of perm '
1623 1590 'function is not allowed: %s' % ''.join(stack_trace))
1624 1591 # rather than throwing errors, here we always return False so if by
1625 1592 # accident someone checks truth for just an instance it will always end
1626 1593 # up in returning False
1627 1594 return False
1628 1595 __nonzero__ = __bool__
1629 1596
1630 1597 def __call__(self, check_location='', user=None):
1631 1598 if not user:
1632 1599 log.debug('Using user attribute from global request')
1633 1600 # TODO: remove this someday,put as user as attribute here
1634 1601 request = self._get_request()
1635 1602 user = request.user
1636 1603
1637 1604 # init auth user if not already given
1638 1605 if not isinstance(user, AuthUser):
1639 1606 log.debug('Wrapping user %s into AuthUser', user)
1640 1607 user = AuthUser(user.user_id)
1641 1608
1642 1609 cls_name = self.__class__.__name__
1643 1610 check_scope = self._get_check_scope(cls_name)
1644 1611 check_location = check_location or 'unspecified location'
1645 1612
1646 1613 log.debug('checking cls:%s %s usr:%s %s @ %s', cls_name,
1647 1614 self.required_perms, user, check_scope, check_location)
1648 1615 if not user:
1649 1616 log.warning('Empty user given for permission check')
1650 1617 return False
1651 1618
1652 1619 if self.check_permissions(user):
1653 1620 log.debug('Permission to repo:`%s` GRANTED for user:`%s` @ %s',
1654 1621 check_scope, user, check_location)
1655 1622 return True
1656 1623
1657 1624 else:
1658 1625 log.debug('Permission to repo:`%s` DENIED for user:`%s` @ %s',
1659 1626 check_scope, user, check_location)
1660 1627 return False
1661 1628
1662 1629 def _get_request(self):
1663 1630 return get_request(self)
1664 1631
1665 1632 def _get_check_scope(self, cls_name):
1666 1633 return {
1667 1634 'HasPermissionAll': 'GLOBAL',
1668 1635 'HasPermissionAny': 'GLOBAL',
1669 1636 'HasRepoPermissionAll': 'repo:%s' % self.repo_name,
1670 1637 'HasRepoPermissionAny': 'repo:%s' % self.repo_name,
1671 1638 'HasRepoGroupPermissionAll': 'repo_group:%s' % self.repo_group_name,
1672 1639 'HasRepoGroupPermissionAny': 'repo_group:%s' % self.repo_group_name,
1673 1640 'HasUserGroupPermissionAll': 'user_group:%s' % self.user_group_name,
1674 1641 'HasUserGroupPermissionAny': 'user_group:%s' % self.user_group_name,
1675 1642 }.get(cls_name, '?:%s' % cls_name)
1676 1643
1677 1644 def check_permissions(self, user):
1678 1645 """Dummy function for overriding"""
1679 1646 raise Exception('You have to write this function in child class')
1680 1647
1681 1648
1682 1649 class HasPermissionAll(PermsFunction):
1683 1650 def check_permissions(self, user):
1684 1651 perms = user.permissions_with_scope({})
1685 1652 if self.required_perms.issubset(perms.get('global')):
1686 1653 return True
1687 1654 return False
1688 1655
1689 1656
1690 1657 class HasPermissionAny(PermsFunction):
1691 1658 def check_permissions(self, user):
1692 1659 perms = user.permissions_with_scope({})
1693 1660 if self.required_perms.intersection(perms.get('global')):
1694 1661 return True
1695 1662 return False
1696 1663
1697 1664
1698 1665 class HasRepoPermissionAll(PermsFunction):
1699 1666 def __call__(self, repo_name=None, check_location='', user=None):
1700 1667 self.repo_name = repo_name
1701 1668 return super(HasRepoPermissionAll, self).__call__(check_location, user)
1702 1669
1703 1670 def _get_repo_name(self):
1704 1671 if not self.repo_name:
1705 1672 _request = self._get_request()
1706 1673 self.repo_name = get_repo_slug(_request)
1707 1674 return self.repo_name
1708 1675
1709 1676 def check_permissions(self, user):
1710 1677 self.repo_name = self._get_repo_name()
1711 1678 perms = user.permissions
1712 1679 try:
1713 1680 user_perms = set([perms['repositories'][self.repo_name]])
1714 1681 except KeyError:
1715 1682 return False
1716 1683 if self.required_perms.issubset(user_perms):
1717 1684 return True
1718 1685 return False
1719 1686
1720 1687
1721 1688 class HasRepoPermissionAny(PermsFunction):
1722 1689 def __call__(self, repo_name=None, check_location='', user=None):
1723 1690 self.repo_name = repo_name
1724 1691 return super(HasRepoPermissionAny, self).__call__(check_location, user)
1725 1692
1726 1693 def _get_repo_name(self):
1727 1694 if not self.repo_name:
1728 1695 _request = self._get_request()
1729 1696 self.repo_name = get_repo_slug(_request)
1730 1697 return self.repo_name
1731 1698
1732 1699 def check_permissions(self, user):
1733 1700 self.repo_name = self._get_repo_name()
1734 1701 perms = user.permissions
1735 1702 try:
1736 1703 user_perms = set([perms['repositories'][self.repo_name]])
1737 1704 except KeyError:
1738 1705 return False
1739 1706 if self.required_perms.intersection(user_perms):
1740 1707 return True
1741 1708 return False
1742 1709
1743 1710
1744 1711 class HasRepoGroupPermissionAny(PermsFunction):
1745 1712 def __call__(self, group_name=None, check_location='', user=None):
1746 1713 self.repo_group_name = group_name
1747 1714 return super(HasRepoGroupPermissionAny, self).__call__(
1748 1715 check_location, user)
1749 1716
1750 1717 def check_permissions(self, user):
1751 1718 perms = user.permissions
1752 1719 try:
1753 1720 user_perms = set(
1754 1721 [perms['repositories_groups'][self.repo_group_name]])
1755 1722 except KeyError:
1756 1723 return False
1757 1724 if self.required_perms.intersection(user_perms):
1758 1725 return True
1759 1726 return False
1760 1727
1761 1728
1762 1729 class HasRepoGroupPermissionAll(PermsFunction):
1763 1730 def __call__(self, group_name=None, check_location='', user=None):
1764 1731 self.repo_group_name = group_name
1765 1732 return super(HasRepoGroupPermissionAll, self).__call__(
1766 1733 check_location, user)
1767 1734
1768 1735 def check_permissions(self, user):
1769 1736 perms = user.permissions
1770 1737 try:
1771 1738 user_perms = set(
1772 1739 [perms['repositories_groups'][self.repo_group_name]])
1773 1740 except KeyError:
1774 1741 return False
1775 1742 if self.required_perms.issubset(user_perms):
1776 1743 return True
1777 1744 return False
1778 1745
1779 1746
1780 1747 class HasUserGroupPermissionAny(PermsFunction):
1781 1748 def __call__(self, user_group_name=None, check_location='', user=None):
1782 1749 self.user_group_name = user_group_name
1783 1750 return super(HasUserGroupPermissionAny, self).__call__(
1784 1751 check_location, user)
1785 1752
1786 1753 def check_permissions(self, user):
1787 1754 perms = user.permissions
1788 1755 try:
1789 1756 user_perms = set([perms['user_groups'][self.user_group_name]])
1790 1757 except KeyError:
1791 1758 return False
1792 1759 if self.required_perms.intersection(user_perms):
1793 1760 return True
1794 1761 return False
1795 1762
1796 1763
1797 1764 class HasUserGroupPermissionAll(PermsFunction):
1798 1765 def __call__(self, user_group_name=None, check_location='', user=None):
1799 1766 self.user_group_name = user_group_name
1800 1767 return super(HasUserGroupPermissionAll, self).__call__(
1801 1768 check_location, user)
1802 1769
1803 1770 def check_permissions(self, user):
1804 1771 perms = user.permissions
1805 1772 try:
1806 1773 user_perms = set([perms['user_groups'][self.user_group_name]])
1807 1774 except KeyError:
1808 1775 return False
1809 1776 if self.required_perms.issubset(user_perms):
1810 1777 return True
1811 1778 return False
1812 1779
1813 1780
1814 1781 # SPECIAL VERSION TO HANDLE MIDDLEWARE AUTH
1815 1782 class HasPermissionAnyMiddleware(object):
1816 1783 def __init__(self, *perms):
1817 1784 self.required_perms = set(perms)
1818 1785
1819 1786 def __call__(self, user, repo_name):
1820 1787 # repo_name MUST be unicode, since we handle keys in permission
1821 1788 # dict by unicode
1822 1789 repo_name = safe_unicode(repo_name)
1823 1790 user = AuthUser(user.user_id)
1824 1791 log.debug(
1825 1792 'Checking VCS protocol permissions %s for user:%s repo:`%s`',
1826 1793 self.required_perms, user, repo_name)
1827 1794
1828 1795 if self.check_permissions(user, repo_name):
1829 1796 log.debug('Permission to repo:`%s` GRANTED for user:%s @ %s',
1830 1797 repo_name, user, 'PermissionMiddleware')
1831 1798 return True
1832 1799
1833 1800 else:
1834 1801 log.debug('Permission to repo:`%s` DENIED for user:%s @ %s',
1835 1802 repo_name, user, 'PermissionMiddleware')
1836 1803 return False
1837 1804
1838 1805 def check_permissions(self, user, repo_name):
1839 1806 perms = user.permissions_with_scope({'repo_name': repo_name})
1840 1807
1841 1808 try:
1842 1809 user_perms = set([perms['repositories'][repo_name]])
1843 1810 except Exception:
1844 1811 log.exception('Error while accessing user permissions')
1845 1812 return False
1846 1813
1847 1814 if self.required_perms.intersection(user_perms):
1848 1815 return True
1849 1816 return False
1850 1817
1851 1818
1852 1819 # SPECIAL VERSION TO HANDLE API AUTH
1853 1820 class _BaseApiPerm(object):
1854 1821 def __init__(self, *perms):
1855 1822 self.required_perms = set(perms)
1856 1823
1857 1824 def __call__(self, check_location=None, user=None, repo_name=None,
1858 1825 group_name=None, user_group_name=None):
1859 1826 cls_name = self.__class__.__name__
1860 1827 check_scope = 'global:%s' % (self.required_perms,)
1861 1828 if repo_name:
1862 1829 check_scope += ', repo_name:%s' % (repo_name,)
1863 1830
1864 1831 if group_name:
1865 1832 check_scope += ', repo_group_name:%s' % (group_name,)
1866 1833
1867 1834 if user_group_name:
1868 1835 check_scope += ', user_group_name:%s' % (user_group_name,)
1869 1836
1870 1837 log.debug(
1871 1838 'checking cls:%s %s %s @ %s'
1872 1839 % (cls_name, self.required_perms, check_scope, check_location))
1873 1840 if not user:
1874 1841 log.debug('Empty User passed into arguments')
1875 1842 return False
1876 1843
1877 1844 # process user
1878 1845 if not isinstance(user, AuthUser):
1879 1846 user = AuthUser(user.user_id)
1880 1847 if not check_location:
1881 1848 check_location = 'unspecified'
1882 1849 if self.check_permissions(user.permissions, repo_name, group_name,
1883 1850 user_group_name):
1884 1851 log.debug('Permission to repo:`%s` GRANTED for user:`%s` @ %s',
1885 1852 check_scope, user, check_location)
1886 1853 return True
1887 1854
1888 1855 else:
1889 1856 log.debug('Permission to repo:`%s` DENIED for user:`%s` @ %s',
1890 1857 check_scope, user, check_location)
1891 1858 return False
1892 1859
1893 1860 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1894 1861 user_group_name=None):
1895 1862 """
1896 1863 implement in child class should return True if permissions are ok,
1897 1864 False otherwise
1898 1865
1899 1866 :param perm_defs: dict with permission definitions
1900 1867 :param repo_name: repo name
1901 1868 """
1902 1869 raise NotImplementedError()
1903 1870
1904 1871
1905 1872 class HasPermissionAllApi(_BaseApiPerm):
1906 1873 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1907 1874 user_group_name=None):
1908 1875 if self.required_perms.issubset(perm_defs.get('global')):
1909 1876 return True
1910 1877 return False
1911 1878
1912 1879
1913 1880 class HasPermissionAnyApi(_BaseApiPerm):
1914 1881 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1915 1882 user_group_name=None):
1916 1883 if self.required_perms.intersection(perm_defs.get('global')):
1917 1884 return True
1918 1885 return False
1919 1886
1920 1887
1921 1888 class HasRepoPermissionAllApi(_BaseApiPerm):
1922 1889 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1923 1890 user_group_name=None):
1924 1891 try:
1925 1892 _user_perms = set([perm_defs['repositories'][repo_name]])
1926 1893 except KeyError:
1927 1894 log.warning(traceback.format_exc())
1928 1895 return False
1929 1896 if self.required_perms.issubset(_user_perms):
1930 1897 return True
1931 1898 return False
1932 1899
1933 1900
1934 1901 class HasRepoPermissionAnyApi(_BaseApiPerm):
1935 1902 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1936 1903 user_group_name=None):
1937 1904 try:
1938 1905 _user_perms = set([perm_defs['repositories'][repo_name]])
1939 1906 except KeyError:
1940 1907 log.warning(traceback.format_exc())
1941 1908 return False
1942 1909 if self.required_perms.intersection(_user_perms):
1943 1910 return True
1944 1911 return False
1945 1912
1946 1913
1947 1914 class HasRepoGroupPermissionAnyApi(_BaseApiPerm):
1948 1915 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1949 1916 user_group_name=None):
1950 1917 try:
1951 1918 _user_perms = set([perm_defs['repositories_groups'][group_name]])
1952 1919 except KeyError:
1953 1920 log.warning(traceback.format_exc())
1954 1921 return False
1955 1922 if self.required_perms.intersection(_user_perms):
1956 1923 return True
1957 1924 return False
1958 1925
1959 1926
1960 1927 class HasRepoGroupPermissionAllApi(_BaseApiPerm):
1961 1928 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1962 1929 user_group_name=None):
1963 1930 try:
1964 1931 _user_perms = set([perm_defs['repositories_groups'][group_name]])
1965 1932 except KeyError:
1966 1933 log.warning(traceback.format_exc())
1967 1934 return False
1968 1935 if self.required_perms.issubset(_user_perms):
1969 1936 return True
1970 1937 return False
1971 1938
1972 1939
1973 1940 class HasUserGroupPermissionAnyApi(_BaseApiPerm):
1974 1941 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1975 1942 user_group_name=None):
1976 1943 try:
1977 1944 _user_perms = set([perm_defs['user_groups'][user_group_name]])
1978 1945 except KeyError:
1979 1946 log.warning(traceback.format_exc())
1980 1947 return False
1981 1948 if self.required_perms.intersection(_user_perms):
1982 1949 return True
1983 1950 return False
1984 1951
1985 1952
1986 1953 def check_ip_access(source_ip, allowed_ips=None):
1987 1954 """
1988 1955 Checks if source_ip is a subnet of any of allowed_ips.
1989 1956
1990 1957 :param source_ip:
1991 1958 :param allowed_ips: list of allowed ips together with mask
1992 1959 """
1993 1960 log.debug('checking if ip:%s is subnet of %s' % (source_ip, allowed_ips))
1994 1961 source_ip_address = ipaddress.ip_address(safe_unicode(source_ip))
1995 1962 if isinstance(allowed_ips, (tuple, list, set)):
1996 1963 for ip in allowed_ips:
1997 1964 ip = safe_unicode(ip)
1998 1965 try:
1999 1966 network_address = ipaddress.ip_network(ip, strict=False)
2000 1967 if source_ip_address in network_address:
2001 1968 log.debug('IP %s is network %s' %
2002 1969 (source_ip_address, network_address))
2003 1970 return True
2004 1971 # for any case we cannot determine the IP, don't crash just
2005 1972 # skip it and log as error, we want to say forbidden still when
2006 1973 # sending bad IP
2007 1974 except Exception:
2008 1975 log.error(traceback.format_exc())
2009 1976 continue
2010 1977 return False
2011 1978
2012 1979
2013 1980 def get_cython_compat_decorator(wrapper, func):
2014 1981 """
2015 1982 Creates a cython compatible decorator. The previously used
2016 1983 decorator.decorator() function seems to be incompatible with cython.
2017 1984
2018 1985 :param wrapper: __wrapper method of the decorator class
2019 1986 :param func: decorated function
2020 1987 """
2021 1988 @wraps(func)
2022 1989 def local_wrapper(*args, **kwds):
2023 1990 return wrapper(func, *args, **kwds)
2024 1991 local_wrapper.__wrapped__ = func
2025 1992 return local_wrapper
2026 1993
2027 1994
@@ -1,222 +1,226 b''
1 1
2 2 /******************************************************************************
3 3 * *
4 4 * DO NOT CHANGE THIS FILE MANUALLY *
5 5 * *
6 6 * *
7 7 * This file is automatically generated when the app starts up with *
8 8 * generate_js_files = true *
9 9 * *
10 10 * To add a route here pass jsroute=True to the route definition in the app *
11 11 * *
12 12 ******************************************************************************/
13 13 function registerRCRoutes() {
14 14 // routes registration
15 15 pyroutes.register('new_repo', '/_admin/create_repository', []);
16 16 pyroutes.register('edit_user', '/_admin/users/%(user_id)s/edit', ['user_id']);
17 17 pyroutes.register('favicon', '/favicon.ico', []);
18 18 pyroutes.register('robots', '/robots.txt', []);
19 19 pyroutes.register('auth_home', '/_admin/auth*traverse', []);
20 20 pyroutes.register('global_integrations_new', '/_admin/integrations/new', []);
21 21 pyroutes.register('global_integrations_home', '/_admin/integrations', []);
22 22 pyroutes.register('global_integrations_list', '/_admin/integrations/%(integration)s', ['integration']);
23 23 pyroutes.register('global_integrations_create', '/_admin/integrations/%(integration)s/new', ['integration']);
24 24 pyroutes.register('global_integrations_edit', '/_admin/integrations/%(integration)s/%(integration_id)s', ['integration', 'integration_id']);
25 25 pyroutes.register('repo_group_integrations_home', '/%(repo_group_name)s/settings/integrations', ['repo_group_name']);
26 26 pyroutes.register('repo_group_integrations_list', '/%(repo_group_name)s/settings/integrations/%(integration)s', ['repo_group_name', 'integration']);
27 27 pyroutes.register('repo_group_integrations_new', '/%(repo_group_name)s/settings/integrations/new', ['repo_group_name']);
28 28 pyroutes.register('repo_group_integrations_create', '/%(repo_group_name)s/settings/integrations/%(integration)s/new', ['repo_group_name', 'integration']);
29 29 pyroutes.register('repo_group_integrations_edit', '/%(repo_group_name)s/settings/integrations/%(integration)s/%(integration_id)s', ['repo_group_name', 'integration', 'integration_id']);
30 30 pyroutes.register('repo_integrations_home', '/%(repo_name)s/settings/integrations', ['repo_name']);
31 31 pyroutes.register('repo_integrations_list', '/%(repo_name)s/settings/integrations/%(integration)s', ['repo_name', 'integration']);
32 32 pyroutes.register('repo_integrations_new', '/%(repo_name)s/settings/integrations/new', ['repo_name']);
33 33 pyroutes.register('repo_integrations_create', '/%(repo_name)s/settings/integrations/%(integration)s/new', ['repo_name', 'integration']);
34 34 pyroutes.register('repo_integrations_edit', '/%(repo_name)s/settings/integrations/%(integration)s/%(integration_id)s', ['repo_name', 'integration', 'integration_id']);
35 35 pyroutes.register('ops_ping', '/_admin/ops/ping', []);
36 36 pyroutes.register('ops_error_test', '/_admin/ops/error', []);
37 37 pyroutes.register('ops_redirect_test', '/_admin/ops/redirect', []);
38 38 pyroutes.register('admin_home', '/_admin', []);
39 39 pyroutes.register('admin_audit_logs', '/_admin/audit_logs', []);
40 40 pyroutes.register('pull_requests_global_0', '/_admin/pull_requests/%(pull_request_id)s', ['pull_request_id']);
41 41 pyroutes.register('pull_requests_global_1', '/_admin/pull-requests/%(pull_request_id)s', ['pull_request_id']);
42 42 pyroutes.register('pull_requests_global', '/_admin/pull-request/%(pull_request_id)s', ['pull_request_id']);
43 43 pyroutes.register('admin_settings_open_source', '/_admin/settings/open_source', []);
44 44 pyroutes.register('admin_settings_vcs_svn_generate_cfg', '/_admin/settings/vcs/svn_generate_cfg', []);
45 45 pyroutes.register('admin_settings_system', '/_admin/settings/system', []);
46 46 pyroutes.register('admin_settings_system_update', '/_admin/settings/system/updates', []);
47 47 pyroutes.register('admin_settings_sessions', '/_admin/settings/sessions', []);
48 48 pyroutes.register('admin_settings_sessions_cleanup', '/_admin/settings/sessions/cleanup', []);
49 49 pyroutes.register('admin_settings_process_management', '/_admin/settings/process_management', []);
50 50 pyroutes.register('admin_settings_process_management_signal', '/_admin/settings/process_management/signal', []);
51 51 pyroutes.register('admin_permissions_application', '/_admin/permissions/application', []);
52 52 pyroutes.register('admin_permissions_application_update', '/_admin/permissions/application/update', []);
53 53 pyroutes.register('admin_permissions_global', '/_admin/permissions/global', []);
54 54 pyroutes.register('admin_permissions_global_update', '/_admin/permissions/global/update', []);
55 55 pyroutes.register('admin_permissions_object', '/_admin/permissions/object', []);
56 56 pyroutes.register('admin_permissions_object_update', '/_admin/permissions/object/update', []);
57 57 pyroutes.register('admin_permissions_ips', '/_admin/permissions/ips', []);
58 58 pyroutes.register('admin_permissions_overview', '/_admin/permissions/overview', []);
59 59 pyroutes.register('admin_permissions_auth_token_access', '/_admin/permissions/auth_token_access', []);
60 60 pyroutes.register('users', '/_admin/users', []);
61 61 pyroutes.register('users_data', '/_admin/users_data', []);
62 62 pyroutes.register('edit_user_auth_tokens', '/_admin/users/%(user_id)s/edit/auth_tokens', ['user_id']);
63 63 pyroutes.register('edit_user_auth_tokens_add', '/_admin/users/%(user_id)s/edit/auth_tokens/new', ['user_id']);
64 64 pyroutes.register('edit_user_auth_tokens_delete', '/_admin/users/%(user_id)s/edit/auth_tokens/delete', ['user_id']);
65 65 pyroutes.register('edit_user_emails', '/_admin/users/%(user_id)s/edit/emails', ['user_id']);
66 66 pyroutes.register('edit_user_emails_add', '/_admin/users/%(user_id)s/edit/emails/new', ['user_id']);
67 67 pyroutes.register('edit_user_emails_delete', '/_admin/users/%(user_id)s/edit/emails/delete', ['user_id']);
68 68 pyroutes.register('edit_user_ips', '/_admin/users/%(user_id)s/edit/ips', ['user_id']);
69 69 pyroutes.register('edit_user_ips_add', '/_admin/users/%(user_id)s/edit/ips/new', ['user_id']);
70 70 pyroutes.register('edit_user_ips_delete', '/_admin/users/%(user_id)s/edit/ips/delete', ['user_id']);
71 71 pyroutes.register('edit_user_groups_management', '/_admin/users/%(user_id)s/edit/groups_management', ['user_id']);
72 72 pyroutes.register('edit_user_groups_management_updates', '/_admin/users/%(user_id)s/edit/edit_user_groups_management/updates', ['user_id']);
73 73 pyroutes.register('edit_user_audit_logs', '/_admin/users/%(user_id)s/edit/audit', ['user_id']);
74 74 pyroutes.register('user_groups', '/_admin/user_groups', []);
75 75 pyroutes.register('user_groups_data', '/_admin/user_groups_data', []);
76 76 pyroutes.register('user_group_members_data', '/_admin/user_groups/%(user_group_id)s/members', ['user_group_id']);
77 77 pyroutes.register('channelstream_connect', '/_admin/channelstream/connect', []);
78 78 pyroutes.register('channelstream_subscribe', '/_admin/channelstream/subscribe', []);
79 79 pyroutes.register('channelstream_proxy', '/_channelstream', []);
80 80 pyroutes.register('login', '/_admin/login', []);
81 81 pyroutes.register('logout', '/_admin/logout', []);
82 82 pyroutes.register('register', '/_admin/register', []);
83 83 pyroutes.register('reset_password', '/_admin/password_reset', []);
84 84 pyroutes.register('reset_password_confirmation', '/_admin/password_reset_confirmation', []);
85 85 pyroutes.register('home', '/', []);
86 86 pyroutes.register('user_autocomplete_data', '/_users', []);
87 87 pyroutes.register('user_group_autocomplete_data', '/_user_groups', []);
88 88 pyroutes.register('repo_list_data', '/_repos', []);
89 89 pyroutes.register('goto_switcher_data', '/_goto_data', []);
90 90 pyroutes.register('journal', '/_admin/journal', []);
91 91 pyroutes.register('journal_rss', '/_admin/journal/rss', []);
92 92 pyroutes.register('journal_atom', '/_admin/journal/atom', []);
93 93 pyroutes.register('journal_public', '/_admin/public_journal', []);
94 94 pyroutes.register('journal_public_atom', '/_admin/public_journal/atom', []);
95 95 pyroutes.register('journal_public_atom_old', '/_admin/public_journal_atom', []);
96 96 pyroutes.register('journal_public_rss', '/_admin/public_journal/rss', []);
97 97 pyroutes.register('journal_public_rss_old', '/_admin/public_journal_rss', []);
98 98 pyroutes.register('toggle_following', '/_admin/toggle_following', []);
99 99 pyroutes.register('repo_creating', '/%(repo_name)s/repo_creating', ['repo_name']);
100 100 pyroutes.register('repo_creating_check', '/%(repo_name)s/repo_creating_check', ['repo_name']);
101 101 pyroutes.register('repo_summary_explicit', '/%(repo_name)s/summary', ['repo_name']);
102 102 pyroutes.register('repo_summary_commits', '/%(repo_name)s/summary-commits', ['repo_name']);
103 103 pyroutes.register('repo_commit', '/%(repo_name)s/changeset/%(commit_id)s', ['repo_name', 'commit_id']);
104 104 pyroutes.register('repo_commit_children', '/%(repo_name)s/changeset_children/%(commit_id)s', ['repo_name', 'commit_id']);
105 105 pyroutes.register('repo_commit_parents', '/%(repo_name)s/changeset_parents/%(commit_id)s', ['repo_name', 'commit_id']);
106 106 pyroutes.register('repo_commit_raw', '/%(repo_name)s/changeset-diff/%(commit_id)s', ['repo_name', 'commit_id']);
107 107 pyroutes.register('repo_commit_patch', '/%(repo_name)s/changeset-patch/%(commit_id)s', ['repo_name', 'commit_id']);
108 108 pyroutes.register('repo_commit_download', '/%(repo_name)s/changeset-download/%(commit_id)s', ['repo_name', 'commit_id']);
109 109 pyroutes.register('repo_commit_data', '/%(repo_name)s/changeset-data/%(commit_id)s', ['repo_name', 'commit_id']);
110 110 pyroutes.register('repo_commit_comment_create', '/%(repo_name)s/changeset/%(commit_id)s/comment/create', ['repo_name', 'commit_id']);
111 111 pyroutes.register('repo_commit_comment_preview', '/%(repo_name)s/changeset/%(commit_id)s/comment/preview', ['repo_name', 'commit_id']);
112 112 pyroutes.register('repo_commit_comment_delete', '/%(repo_name)s/changeset/%(commit_id)s/comment/%(comment_id)s/delete', ['repo_name', 'commit_id', 'comment_id']);
113 113 pyroutes.register('repo_commit_raw_deprecated', '/%(repo_name)s/raw-changeset/%(commit_id)s', ['repo_name', 'commit_id']);
114 114 pyroutes.register('repo_archivefile', '/%(repo_name)s/archive/%(fname)s', ['repo_name', 'fname']);
115 115 pyroutes.register('repo_files_diff', '/%(repo_name)s/diff/%(f_path)s', ['repo_name', 'f_path']);
116 116 pyroutes.register('repo_files_diff_2way_redirect', '/%(repo_name)s/diff-2way/%(f_path)s', ['repo_name', 'f_path']);
117 117 pyroutes.register('repo_files', '/%(repo_name)s/files/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
118 118 pyroutes.register('repo_files:default_path', '/%(repo_name)s/files/%(commit_id)s/', ['repo_name', 'commit_id']);
119 119 pyroutes.register('repo_files:default_commit', '/%(repo_name)s/files', ['repo_name']);
120 120 pyroutes.register('repo_files:rendered', '/%(repo_name)s/render/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
121 121 pyroutes.register('repo_files:annotated', '/%(repo_name)s/annotate/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
122 122 pyroutes.register('repo_files:annotated_previous', '/%(repo_name)s/annotate-previous/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
123 123 pyroutes.register('repo_nodetree_full', '/%(repo_name)s/nodetree_full/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
124 124 pyroutes.register('repo_nodetree_full:default_path', '/%(repo_name)s/nodetree_full/%(commit_id)s/', ['repo_name', 'commit_id']);
125 125 pyroutes.register('repo_files_nodelist', '/%(repo_name)s/nodelist/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
126 126 pyroutes.register('repo_file_raw', '/%(repo_name)s/raw/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
127 127 pyroutes.register('repo_file_download', '/%(repo_name)s/download/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
128 128 pyroutes.register('repo_file_download:legacy', '/%(repo_name)s/rawfile/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
129 129 pyroutes.register('repo_file_history', '/%(repo_name)s/history/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
130 130 pyroutes.register('repo_file_authors', '/%(repo_name)s/authors/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
131 131 pyroutes.register('repo_files_remove_file', '/%(repo_name)s/remove_file/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
132 132 pyroutes.register('repo_files_delete_file', '/%(repo_name)s/delete_file/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
133 133 pyroutes.register('repo_files_edit_file', '/%(repo_name)s/edit_file/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
134 134 pyroutes.register('repo_files_update_file', '/%(repo_name)s/update_file/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
135 135 pyroutes.register('repo_files_add_file', '/%(repo_name)s/add_file/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
136 136 pyroutes.register('repo_files_create_file', '/%(repo_name)s/create_file/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
137 137 pyroutes.register('repo_refs_data', '/%(repo_name)s/refs-data', ['repo_name']);
138 138 pyroutes.register('repo_refs_changelog_data', '/%(repo_name)s/refs-data-changelog', ['repo_name']);
139 139 pyroutes.register('repo_stats', '/%(repo_name)s/repo_stats/%(commit_id)s', ['repo_name', 'commit_id']);
140 140 pyroutes.register('repo_changelog', '/%(repo_name)s/changelog', ['repo_name']);
141 141 pyroutes.register('repo_changelog_file', '/%(repo_name)s/changelog/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
142 142 pyroutes.register('repo_changelog_elements', '/%(repo_name)s/changelog_elements', ['repo_name']);
143 143 pyroutes.register('repo_compare_select', '/%(repo_name)s/compare', ['repo_name']);
144 144 pyroutes.register('repo_compare', '/%(repo_name)s/compare/%(source_ref_type)s@%(source_ref)s...%(target_ref_type)s@%(target_ref)s', ['repo_name', 'source_ref_type', 'source_ref', 'target_ref_type', 'target_ref']);
145 145 pyroutes.register('tags_home', '/%(repo_name)s/tags', ['repo_name']);
146 146 pyroutes.register('branches_home', '/%(repo_name)s/branches', ['repo_name']);
147 147 pyroutes.register('bookmarks_home', '/%(repo_name)s/bookmarks', ['repo_name']);
148 pyroutes.register('repo_fork_new', '/%(repo_name)s/fork', ['repo_name']);
149 pyroutes.register('repo_fork_create', '/%(repo_name)s/fork/create', ['repo_name']);
150 pyroutes.register('repo_forks_show_all', '/%(repo_name)s/forks', ['repo_name']);
151 pyroutes.register('repo_forks_data', '/%(repo_name)s/forks/data', ['repo_name']);
148 152 pyroutes.register('pullrequest_show', '/%(repo_name)s/pull-request/%(pull_request_id)s', ['repo_name', 'pull_request_id']);
149 153 pyroutes.register('pullrequest_show_all', '/%(repo_name)s/pull-request', ['repo_name']);
150 154 pyroutes.register('pullrequest_show_all_data', '/%(repo_name)s/pull-request-data', ['repo_name']);
151 155 pyroutes.register('pullrequest_repo_refs', '/%(repo_name)s/pull-request/refs/%(target_repo_name)s', ['repo_name', 'target_repo_name']);
152 156 pyroutes.register('pullrequest_repo_destinations', '/%(repo_name)s/pull-request/repo-destinations', ['repo_name']);
153 157 pyroutes.register('pullrequest_new', '/%(repo_name)s/pull-request/new', ['repo_name']);
154 158 pyroutes.register('pullrequest_create', '/%(repo_name)s/pull-request/create', ['repo_name']);
155 159 pyroutes.register('pullrequest_update', '/%(repo_name)s/pull-request/%(pull_request_id)s/update', ['repo_name', 'pull_request_id']);
156 160 pyroutes.register('pullrequest_merge', '/%(repo_name)s/pull-request/%(pull_request_id)s/merge', ['repo_name', 'pull_request_id']);
157 161 pyroutes.register('pullrequest_delete', '/%(repo_name)s/pull-request/%(pull_request_id)s/delete', ['repo_name', 'pull_request_id']);
158 162 pyroutes.register('pullrequest_comment_create', '/%(repo_name)s/pull-request/%(pull_request_id)s/comment', ['repo_name', 'pull_request_id']);
159 163 pyroutes.register('pullrequest_comment_delete', '/%(repo_name)s/pull-request/%(pull_request_id)s/comment/%(comment_id)s/delete', ['repo_name', 'pull_request_id', 'comment_id']);
160 164 pyroutes.register('edit_repo', '/%(repo_name)s/settings', ['repo_name']);
161 165 pyroutes.register('edit_repo_advanced', '/%(repo_name)s/settings/advanced', ['repo_name']);
162 166 pyroutes.register('edit_repo_advanced_delete', '/%(repo_name)s/settings/advanced/delete', ['repo_name']);
163 167 pyroutes.register('edit_repo_advanced_locking', '/%(repo_name)s/settings/advanced/locking', ['repo_name']);
164 168 pyroutes.register('edit_repo_advanced_journal', '/%(repo_name)s/settings/advanced/journal', ['repo_name']);
165 169 pyroutes.register('edit_repo_advanced_fork', '/%(repo_name)s/settings/advanced/fork', ['repo_name']);
166 170 pyroutes.register('edit_repo_caches', '/%(repo_name)s/settings/caches', ['repo_name']);
167 171 pyroutes.register('edit_repo_perms', '/%(repo_name)s/settings/permissions', ['repo_name']);
168 172 pyroutes.register('repo_reviewers', '/%(repo_name)s/settings/review/rules', ['repo_name']);
169 173 pyroutes.register('repo_default_reviewers_data', '/%(repo_name)s/settings/review/default-reviewers', ['repo_name']);
170 174 pyroutes.register('repo_maintenance', '/%(repo_name)s/settings/maintenance', ['repo_name']);
171 175 pyroutes.register('repo_maintenance_execute', '/%(repo_name)s/settings/maintenance/execute', ['repo_name']);
172 176 pyroutes.register('strip', '/%(repo_name)s/settings/strip', ['repo_name']);
173 177 pyroutes.register('strip_check', '/%(repo_name)s/settings/strip_check', ['repo_name']);
174 178 pyroutes.register('strip_execute', '/%(repo_name)s/settings/strip_execute', ['repo_name']);
175 179 pyroutes.register('rss_feed_home', '/%(repo_name)s/feed/rss', ['repo_name']);
176 180 pyroutes.register('atom_feed_home', '/%(repo_name)s/feed/atom', ['repo_name']);
177 181 pyroutes.register('repo_summary', '/%(repo_name)s', ['repo_name']);
178 182 pyroutes.register('repo_summary_slash', '/%(repo_name)s/', ['repo_name']);
179 183 pyroutes.register('repo_group_home', '/%(repo_group_name)s', ['repo_group_name']);
180 184 pyroutes.register('repo_group_home_slash', '/%(repo_group_name)s/', ['repo_group_name']);
181 185 pyroutes.register('search', '/_admin/search', []);
182 186 pyroutes.register('search_repo', '/%(repo_name)s/search', ['repo_name']);
183 187 pyroutes.register('user_profile', '/_profiles/%(username)s', ['username']);
184 188 pyroutes.register('my_account_profile', '/_admin/my_account/profile', []);
185 189 pyroutes.register('my_account_edit', '/_admin/my_account/edit', []);
186 190 pyroutes.register('my_account_update', '/_admin/my_account/update', []);
187 191 pyroutes.register('my_account_password', '/_admin/my_account/password', []);
188 192 pyroutes.register('my_account_password_update', '/_admin/my_account/password/update', []);
189 193 pyroutes.register('my_account_auth_tokens', '/_admin/my_account/auth_tokens', []);
190 194 pyroutes.register('my_account_auth_tokens_add', '/_admin/my_account/auth_tokens/new', []);
191 195 pyroutes.register('my_account_auth_tokens_delete', '/_admin/my_account/auth_tokens/delete', []);
192 196 pyroutes.register('my_account_emails', '/_admin/my_account/emails', []);
193 197 pyroutes.register('my_account_emails_add', '/_admin/my_account/emails/new', []);
194 198 pyroutes.register('my_account_emails_delete', '/_admin/my_account/emails/delete', []);
195 199 pyroutes.register('my_account_repos', '/_admin/my_account/repos', []);
196 200 pyroutes.register('my_account_watched', '/_admin/my_account/watched', []);
197 201 pyroutes.register('my_account_perms', '/_admin/my_account/perms', []);
198 202 pyroutes.register('my_account_notifications', '/_admin/my_account/notifications', []);
199 203 pyroutes.register('my_account_notifications_toggle_visibility', '/_admin/my_account/toggle_visibility', []);
200 204 pyroutes.register('my_account_pullrequests', '/_admin/my_account/pull_requests', []);
201 205 pyroutes.register('my_account_pullrequests_data', '/_admin/my_account/pull_requests/data', []);
202 206 pyroutes.register('notifications_show_all', '/_admin/notifications', []);
203 207 pyroutes.register('notifications_mark_all_read', '/_admin/notifications/mark_all_read', []);
204 208 pyroutes.register('notifications_show', '/_admin/notifications/%(notification_id)s', ['notification_id']);
205 209 pyroutes.register('notifications_update', '/_admin/notifications/%(notification_id)s/update', ['notification_id']);
206 210 pyroutes.register('notifications_delete', '/_admin/notifications/%(notification_id)s/delete', ['notification_id']);
207 211 pyroutes.register('my_account_notifications_test_channelstream', '/_admin/my_account/test_channelstream', []);
208 212 pyroutes.register('gists_show', '/_admin/gists', []);
209 213 pyroutes.register('gists_new', '/_admin/gists/new', []);
210 214 pyroutes.register('gists_create', '/_admin/gists/create', []);
211 215 pyroutes.register('gist_show', '/_admin/gists/%(gist_id)s', ['gist_id']);
212 216 pyroutes.register('gist_delete', '/_admin/gists/%(gist_id)s/delete', ['gist_id']);
213 217 pyroutes.register('gist_edit', '/_admin/gists/%(gist_id)s/edit', ['gist_id']);
214 218 pyroutes.register('gist_edit_check_revision', '/_admin/gists/%(gist_id)s/edit/check_revision', ['gist_id']);
215 219 pyroutes.register('gist_update', '/_admin/gists/%(gist_id)s/update', ['gist_id']);
216 220 pyroutes.register('gist_show_rev', '/_admin/gists/%(gist_id)s/%(revision)s', ['gist_id', 'revision']);
217 221 pyroutes.register('gist_show_formatted', '/_admin/gists/%(gist_id)s/%(revision)s/%(format)s', ['gist_id', 'revision', 'format']);
218 222 pyroutes.register('gist_show_formatted_path', '/_admin/gists/%(gist_id)s/%(revision)s/%(format)s/%(f_path)s', ['gist_id', 'revision', 'format', 'f_path']);
219 223 pyroutes.register('debug_style_home', '/_admin/debug_style', []);
220 224 pyroutes.register('debug_style_template', '/_admin/debug_style/t/%(t_path)s', ['t_path']);
221 225 pyroutes.register('apiv2', '/_admin/api', []);
222 226 }
@@ -1,609 +1,609 b''
1 1 ## -*- coding: utf-8 -*-
2 2 <%inherit file="root.mako"/>
3 3
4 4 <div class="outerwrapper">
5 5 <!-- HEADER -->
6 6 <div class="header">
7 7 <div id="header-inner" class="wrapper">
8 8 <div id="logo">
9 9 <div class="logo-wrapper">
10 10 <a href="${h.route_path('home')}"><img src="${h.asset('images/rhodecode-logo-white-216x60.png')}" alt="RhodeCode"/></a>
11 11 </div>
12 12 %if c.rhodecode_name:
13 13 <div class="branding">- ${h.branding(c.rhodecode_name)}</div>
14 14 %endif
15 15 </div>
16 16 <!-- MENU BAR NAV -->
17 17 ${self.menu_bar_nav()}
18 18 <!-- END MENU BAR NAV -->
19 19 </div>
20 20 </div>
21 21 ${self.menu_bar_subnav()}
22 22 <!-- END HEADER -->
23 23
24 24 <!-- CONTENT -->
25 25 <div id="content" class="wrapper">
26 26
27 27 <rhodecode-toast id="notifications"></rhodecode-toast>
28 28
29 29 <div class="main">
30 30 ${next.main()}
31 31 </div>
32 32 </div>
33 33 <!-- END CONTENT -->
34 34
35 35 </div>
36 36 <!-- FOOTER -->
37 37 <div id="footer">
38 38 <div id="footer-inner" class="title wrapper">
39 39 <div>
40 40 <p class="footer-link-right">
41 41 % if c.visual.show_version:
42 42 RhodeCode Enterprise ${c.rhodecode_version} ${c.rhodecode_edition}
43 43 % endif
44 44 &copy; 2010-${h.datetime.today().year}, <a href="${h.route_url('rhodecode_official')}" target="_blank">RhodeCode GmbH</a>. All rights reserved.
45 45 % if c.visual.rhodecode_support_url:
46 46 <a href="${c.visual.rhodecode_support_url}" target="_blank">${_('Support')}</a>
47 47 % endif
48 48 </p>
49 49 <% sid = 'block' if request.GET.get('showrcid') else 'none' %>
50 50 <p class="server-instance" style="display:${sid}">
51 51 ## display hidden instance ID if specially defined
52 52 % if c.rhodecode_instanceid:
53 53 ${_('RhodeCode instance id: %s') % c.rhodecode_instanceid}
54 54 % endif
55 55 </p>
56 56 </div>
57 57 </div>
58 58 </div>
59 59
60 60 <!-- END FOOTER -->
61 61
62 62 ### MAKO DEFS ###
63 63
64 64 <%def name="menu_bar_subnav()">
65 65 </%def>
66 66
67 67 <%def name="breadcrumbs(class_='breadcrumbs')">
68 68 <div class="${class_}">
69 69 ${self.breadcrumbs_links()}
70 70 </div>
71 71 </%def>
72 72
73 73 <%def name="admin_menu()">
74 74 <ul class="admin_menu submenu">
75 75 <li><a href="${h.route_path('admin_audit_logs')}">${_('Admin audit logs')}</a></li>
76 76 <li><a href="${h.url('repos')}">${_('Repositories')}</a></li>
77 77 <li><a href="${h.url('repo_groups')}">${_('Repository groups')}</a></li>
78 78 <li><a href="${h.route_path('users')}">${_('Users')}</a></li>
79 79 <li><a href="${h.url('users_groups')}">${_('User groups')}</a></li>
80 80 <li><a href="${h.route_path('admin_permissions_application')}">${_('Permissions')}</a></li>
81 81 <li><a href="${h.route_path('auth_home', traverse='')}">${_('Authentication')}</a></li>
82 82 <li><a href="${h.route_path('global_integrations_home')}">${_('Integrations')}</a></li>
83 83 <li><a href="${h.url('admin_defaults_repositories')}">${_('Defaults')}</a></li>
84 84 <li class="last"><a href="${h.url('admin_settings')}">${_('Settings')}</a></li>
85 85 </ul>
86 86 </%def>
87 87
88 88
89 89 <%def name="dt_info_panel(elements)">
90 90 <dl class="dl-horizontal">
91 91 %for dt, dd, title, show_items in elements:
92 92 <dt>${dt}:</dt>
93 93 <dd title="${h.tooltip(title)}">
94 94 %if callable(dd):
95 95 ## allow lazy evaluation of elements
96 96 ${dd()}
97 97 %else:
98 98 ${dd}
99 99 %endif
100 100 %if show_items:
101 101 <span class="btn-collapse" data-toggle="item-${h.md5_safe(dt)[:6]}-details">${_('Show More')} </span>
102 102 %endif
103 103 </dd>
104 104
105 105 %if show_items:
106 106 <div class="collapsable-content" data-toggle="item-${h.md5_safe(dt)[:6]}-details" style="display: none">
107 107 %for item in show_items:
108 108 <dt></dt>
109 109 <dd>${item}</dd>
110 110 %endfor
111 111 </div>
112 112 %endif
113 113
114 114 %endfor
115 115 </dl>
116 116 </%def>
117 117
118 118
119 119 <%def name="gravatar(email, size=16)">
120 120 <%
121 121 if (size > 16):
122 122 gravatar_class = 'gravatar gravatar-large'
123 123 else:
124 124 gravatar_class = 'gravatar'
125 125 %>
126 126 <%doc>
127 127 TODO: johbo: For now we serve double size images to make it smooth
128 128 for retina. This is how it worked until now. Should be replaced
129 129 with a better solution at some point.
130 130 </%doc>
131 131 <img class="${gravatar_class}" src="${h.gravatar_url(email, size * 2)}" height="${size}" width="${size}">
132 132 </%def>
133 133
134 134
135 135 <%def name="gravatar_with_user(contact, size=16, show_disabled=False)">
136 136 <% email = h.email_or_none(contact) %>
137 137 <div class="rc-user tooltip" title="${h.tooltip(h.author_string(email))}">
138 138 ${self.gravatar(email, size)}
139 139 <span class="${'user user-disabled' if show_disabled else 'user'}"> ${h.link_to_user(contact)}</span>
140 140 </div>
141 141 </%def>
142 142
143 143
144 144 ## admin menu used for people that have some admin resources
145 145 <%def name="admin_menu_simple(repositories=None, repository_groups=None, user_groups=None)">
146 146 <ul class="submenu">
147 147 %if repositories:
148 148 <li class="local-admin-repos"><a href="${h.url('repos')}">${_('Repositories')}</a></li>
149 149 %endif
150 150 %if repository_groups:
151 151 <li class="local-admin-repo-groups"><a href="${h.url('repo_groups')}">${_('Repository groups')}</a></li>
152 152 %endif
153 153 %if user_groups:
154 154 <li class="local-admin-user-groups"><a href="${h.url('users_groups')}">${_('User groups')}</a></li>
155 155 %endif
156 156 </ul>
157 157 </%def>
158 158
159 159 <%def name="repo_page_title(repo_instance)">
160 160 <div class="title-content">
161 161 <div class="title-main">
162 162 ## SVN/HG/GIT icons
163 163 %if h.is_hg(repo_instance):
164 164 <i class="icon-hg"></i>
165 165 %endif
166 166 %if h.is_git(repo_instance):
167 167 <i class="icon-git"></i>
168 168 %endif
169 169 %if h.is_svn(repo_instance):
170 170 <i class="icon-svn"></i>
171 171 %endif
172 172
173 173 ## public/private
174 174 %if repo_instance.private:
175 175 <i class="icon-repo-private"></i>
176 176 %else:
177 177 <i class="icon-repo-public"></i>
178 178 %endif
179 179
180 180 ## repo name with group name
181 181 ${h.breadcrumb_repo_link(c.rhodecode_db_repo)}
182 182
183 183 </div>
184 184
185 185 ## FORKED
186 186 %if repo_instance.fork:
187 187 <p>
188 188 <i class="icon-code-fork"></i> ${_('Fork of')}
189 189 <a href="${h.route_path('repo_summary',repo_name=repo_instance.fork.repo_name)}">${repo_instance.fork.repo_name}</a>
190 190 </p>
191 191 %endif
192 192
193 193 ## IMPORTED FROM REMOTE
194 194 %if repo_instance.clone_uri:
195 195 <p>
196 196 <i class="icon-code-fork"></i> ${_('Clone from')}
197 197 <a href="${h.url(h.safe_str(h.hide_credentials(repo_instance.clone_uri)))}">${h.hide_credentials(repo_instance.clone_uri)}</a>
198 198 </p>
199 199 %endif
200 200
201 201 ## LOCKING STATUS
202 202 %if repo_instance.locked[0]:
203 203 <p class="locking_locked">
204 204 <i class="icon-repo-lock"></i>
205 205 ${_('Repository locked by %(user)s') % {'user': h.person_by_id(repo_instance.locked[0])}}
206 206 </p>
207 207 %elif repo_instance.enable_locking:
208 208 <p class="locking_unlocked">
209 209 <i class="icon-repo-unlock"></i>
210 210 ${_('Repository not locked. Pull repository to lock it.')}
211 211 </p>
212 212 %endif
213 213
214 214 </div>
215 215 </%def>
216 216
217 217 <%def name="repo_menu(active=None)">
218 218 <%
219 219 def is_active(selected):
220 220 if selected == active:
221 221 return "active"
222 222 %>
223 223
224 224 <!--- CONTEXT BAR -->
225 225 <div id="context-bar">
226 226 <div class="wrapper">
227 227 <ul id="context-pages" class="horizontal-list navigation">
228 228 <li class="${is_active('summary')}"><a class="menulink" href="${h.route_path('repo_summary', repo_name=c.repo_name)}"><div class="menulabel">${_('Summary')}</div></a></li>
229 229 <li class="${is_active('changelog')}"><a class="menulink" href="${h.route_path('repo_changelog', repo_name=c.repo_name)}"><div class="menulabel">${_('Changelog')}</div></a></li>
230 230 <li class="${is_active('files')}"><a class="menulink" href="${h.route_path('repo_files', repo_name=c.repo_name, commit_id=c.rhodecode_db_repo.landing_rev[1], f_path='')}"><div class="menulabel">${_('Files')}</div></a></li>
231 231 <li class="${is_active('compare')}"><a class="menulink" href="${h.route_path('repo_compare_select',repo_name=c.repo_name)}"><div class="menulabel">${_('Compare')}</div></a></li>
232 232 ## TODO: anderson: ideally it would have a function on the scm_instance "enable_pullrequest() and enable_fork()"
233 233 %if c.rhodecode_db_repo.repo_type in ['git','hg']:
234 234 <li class="${is_active('showpullrequest')}">
235 235 <a class="menulink" href="${h.route_path('pullrequest_show_all', repo_name=c.repo_name)}" title="${h.tooltip(_('Show Pull Requests for %s') % c.repo_name)}">
236 236 %if c.repository_pull_requests:
237 237 <span class="pr_notifications">${c.repository_pull_requests}</span>
238 238 %endif
239 239 <div class="menulabel">${_('Pull Requests')}</div>
240 240 </a>
241 241 </li>
242 242 %endif
243 243 <li class="${is_active('options')}">
244 244 <a class="menulink dropdown">
245 245 <div class="menulabel">${_('Options')} <div class="show_more"></div></div>
246 246 </a>
247 247 <ul class="submenu">
248 248 %if h.HasRepoPermissionAll('repository.admin')(c.repo_name):
249 249 <li><a href="${h.route_path('edit_repo',repo_name=c.repo_name)}">${_('Settings')}</a></li>
250 250 %endif
251 251 %if c.rhodecode_db_repo.fork:
252 252 <li>
253 253 <a title="${h.tooltip(_('Compare fork with %s' % c.rhodecode_db_repo.fork.repo_name))}"
254 254 href="${h.route_path('repo_compare',
255 255 repo_name=c.rhodecode_db_repo.fork.repo_name,
256 256 source_ref_type=c.rhodecode_db_repo.landing_rev[0],
257 257 source_ref=c.rhodecode_db_repo.landing_rev[1],
258 258 target_repo=c.repo_name,target_ref_type='branch' if request.GET.get('branch') else c.rhodecode_db_repo.landing_rev[0],
259 259 target_ref=request.GET.get('branch') or c.rhodecode_db_repo.landing_rev[1],
260 260 _query=dict(merge=1))}"
261 261 >
262 262 ${_('Compare fork')}
263 263 </a>
264 264 </li>
265 265 %endif
266 266
267 267 <li><a href="${h.route_path('search_repo',repo_name=c.repo_name)}">${_('Search')}</a></li>
268 268
269 269 %if h.HasRepoPermissionAny('repository.write','repository.admin')(c.repo_name) and c.rhodecode_db_repo.enable_locking:
270 270 %if c.rhodecode_db_repo.locked[0]:
271 271 <li><a class="locking_del" href="${h.url('toggle_locking',repo_name=c.repo_name)}">${_('Unlock')}</a></li>
272 272 %else:
273 273 <li><a class="locking_add" href="${h.url('toggle_locking',repo_name=c.repo_name)}">${_('Lock')}</a></li>
274 274 %endif
275 275 %endif
276 276 %if c.rhodecode_user.username != h.DEFAULT_USER:
277 277 %if c.rhodecode_db_repo.repo_type in ['git','hg']:
278 <li><a href="${h.url('repo_fork_home',repo_name=c.repo_name)}">${_('Fork')}</a></li>
278 <li><a href="${h.route_path('repo_fork_new',repo_name=c.repo_name)}">${_('Fork')}</a></li>
279 279 <li><a href="${h.route_path('pullrequest_new',repo_name=c.repo_name)}">${_('Create Pull Request')}</a></li>
280 280 %endif
281 281 %endif
282 282 </ul>
283 283 </li>
284 284 </ul>
285 285 </div>
286 286 <div class="clear"></div>
287 287 </div>
288 288 <!--- END CONTEXT BAR -->
289 289
290 290 </%def>
291 291
292 292 <%def name="usermenu(active=False)">
293 293 ## USER MENU
294 294 <li id="quick_login_li" class="${'active' if active else ''}">
295 295 <a id="quick_login_link" class="menulink childs">
296 296 ${gravatar(c.rhodecode_user.email, 20)}
297 297 <span class="user">
298 298 %if c.rhodecode_user.username != h.DEFAULT_USER:
299 299 <span class="menu_link_user">${c.rhodecode_user.username}</span><div class="show_more"></div>
300 300 %else:
301 301 <span>${_('Sign in')}</span>
302 302 %endif
303 303 </span>
304 304 </a>
305 305
306 306 <div class="user-menu submenu">
307 307 <div id="quick_login">
308 308 %if c.rhodecode_user.username == h.DEFAULT_USER:
309 309 <h4>${_('Sign in to your account')}</h4>
310 310 ${h.form(h.route_path('login', _query={'came_from': h.url.current()}), needs_csrf_token=False)}
311 311 <div class="form form-vertical">
312 312 <div class="fields">
313 313 <div class="field">
314 314 <div class="label">
315 315 <label for="username">${_('Username')}:</label>
316 316 </div>
317 317 <div class="input">
318 318 ${h.text('username',class_='focus',tabindex=1)}
319 319 </div>
320 320
321 321 </div>
322 322 <div class="field">
323 323 <div class="label">
324 324 <label for="password">${_('Password')}:</label>
325 325 %if h.HasPermissionAny('hg.password_reset.enabled')():
326 326 <span class="forgot_password">${h.link_to(_('(Forgot password?)'),h.route_path('reset_password'), class_='pwd_reset')}</span>
327 327 %endif
328 328 </div>
329 329 <div class="input">
330 330 ${h.password('password',class_='focus',tabindex=2)}
331 331 </div>
332 332 </div>
333 333 <div class="buttons">
334 334 <div class="register">
335 335 %if h.HasPermissionAny('hg.admin', 'hg.register.auto_activate', 'hg.register.manual_activate')():
336 336 ${h.link_to(_("Don't have an account?"),h.route_path('register'))} <br/>
337 337 %endif
338 338 ${h.link_to(_("Using external auth? Sign In here."),h.route_path('login'))}
339 339 </div>
340 340 <div class="submit">
341 341 ${h.submit('sign_in',_('Sign In'),class_="btn btn-small",tabindex=3)}
342 342 </div>
343 343 </div>
344 344 </div>
345 345 </div>
346 346 ${h.end_form()}
347 347 %else:
348 348 <div class="">
349 349 <div class="big_gravatar">${gravatar(c.rhodecode_user.email, 48)}</div>
350 350 <div class="full_name">${c.rhodecode_user.full_name_or_username}</div>
351 351 <div class="email">${c.rhodecode_user.email}</div>
352 352 </div>
353 353 <div class="">
354 354 <ol class="links">
355 355 <li>${h.link_to(_(u'My account'),h.route_path('my_account_profile'))}</li>
356 356 % if c.rhodecode_user.personal_repo_group:
357 357 <li>${h.link_to(_(u'My personal group'), h.route_path('repo_group_home', repo_group_name=c.rhodecode_user.personal_repo_group.group_name))}</li>
358 358 % endif
359 359 <li class="logout">
360 360 ${h.secure_form(h.route_path('logout'), request=request)}
361 361 ${h.submit('log_out', _(u'Sign Out'),class_="btn btn-primary")}
362 362 ${h.end_form()}
363 363 </li>
364 364 </ol>
365 365 </div>
366 366 %endif
367 367 </div>
368 368 </div>
369 369 %if c.rhodecode_user.username != h.DEFAULT_USER:
370 370 <div class="pill_container">
371 371 <a class="menu_link_notifications ${'empty' if c.unread_notifications == 0 else ''}" href="${h.route_path('notifications_show_all')}">${c.unread_notifications}</a>
372 372 </div>
373 373 % endif
374 374 </li>
375 375 </%def>
376 376
377 377 <%def name="menu_items(active=None)">
378 378 <%
379 379 def is_active(selected):
380 380 if selected == active:
381 381 return "active"
382 382 return ""
383 383 %>
384 384 <ul id="quick" class="main_nav navigation horizontal-list">
385 385 <!-- repo switcher -->
386 386 <li class="${is_active('repositories')} repo_switcher_li has_select2">
387 387 <input id="repo_switcher" name="repo_switcher" type="hidden">
388 388 </li>
389 389
390 390 ## ROOT MENU
391 391 %if c.rhodecode_user.username != h.DEFAULT_USER:
392 392 <li class="${is_active('journal')}">
393 393 <a class="menulink" title="${_('Show activity journal')}" href="${h.route_path('journal')}">
394 394 <div class="menulabel">${_('Journal')}</div>
395 395 </a>
396 396 </li>
397 397 %else:
398 398 <li class="${is_active('journal')}">
399 399 <a class="menulink" title="${_('Show Public activity journal')}" href="${h.route_path('journal_public')}">
400 400 <div class="menulabel">${_('Public journal')}</div>
401 401 </a>
402 402 </li>
403 403 %endif
404 404 <li class="${is_active('gists')}">
405 405 <a class="menulink childs" title="${_('Show Gists')}" href="${h.route_path('gists_show')}">
406 406 <div class="menulabel">${_('Gists')}</div>
407 407 </a>
408 408 </li>
409 409 <li class="${is_active('search')}">
410 410 <a class="menulink" title="${_('Search in repositories you have access to')}" href="${h.route_path('search')}">
411 411 <div class="menulabel">${_('Search')}</div>
412 412 </a>
413 413 </li>
414 414 % if h.HasPermissionAll('hg.admin')('access admin main page'):
415 415 <li class="${is_active('admin')}">
416 416 <a class="menulink childs" title="${_('Admin settings')}" href="#" onclick="return false;">
417 417 <div class="menulabel">${_('Admin')} <div class="show_more"></div></div>
418 418 </a>
419 419 ${admin_menu()}
420 420 </li>
421 421 % elif c.rhodecode_user.repositories_admin or c.rhodecode_user.repository_groups_admin or c.rhodecode_user.user_groups_admin:
422 422 <li class="${is_active('admin')}">
423 423 <a class="menulink childs" title="${_('Delegated Admin settings')}">
424 424 <div class="menulabel">${_('Admin')} <div class="show_more"></div></div>
425 425 </a>
426 426 ${admin_menu_simple(c.rhodecode_user.repositories_admin,
427 427 c.rhodecode_user.repository_groups_admin,
428 428 c.rhodecode_user.user_groups_admin or h.HasPermissionAny('hg.usergroup.create.true')())}
429 429 </li>
430 430 % endif
431 431 % if c.debug_style:
432 432 <li class="${is_active('debug_style')}">
433 433 <a class="menulink" title="${_('Style')}" href="${h.route_path('debug_style_home')}">
434 434 <div class="menulabel">${_('Style')}</div>
435 435 </a>
436 436 </li>
437 437 % endif
438 438 ## render extra user menu
439 439 ${usermenu(active=(active=='my_account'))}
440 440 </ul>
441 441
442 442 <script type="text/javascript">
443 443 var visual_show_public_icon = "${c.visual.show_public_icon}" == "True";
444 444
445 445 /*format the look of items in the list*/
446 446 var format = function(state, escapeMarkup){
447 447 if (!state.id){
448 448 return state.text; // optgroup
449 449 }
450 450 var obj_dict = state.obj;
451 451 var tmpl = '';
452 452
453 453 if(obj_dict && state.type == 'repo'){
454 454 if(obj_dict['repo_type'] === 'hg'){
455 455 tmpl += '<i class="icon-hg"></i> ';
456 456 }
457 457 else if(obj_dict['repo_type'] === 'git'){
458 458 tmpl += '<i class="icon-git"></i> ';
459 459 }
460 460 else if(obj_dict['repo_type'] === 'svn'){
461 461 tmpl += '<i class="icon-svn"></i> ';
462 462 }
463 463 if(obj_dict['private']){
464 464 tmpl += '<i class="icon-lock" ></i> ';
465 465 }
466 466 else if(visual_show_public_icon){
467 467 tmpl += '<i class="icon-unlock-alt"></i> ';
468 468 }
469 469 }
470 470 if(obj_dict && state.type == 'commit') {
471 471 tmpl += '<i class="icon-tag"></i>';
472 472 }
473 473 if(obj_dict && state.type == 'group'){
474 474 tmpl += '<i class="icon-folder-close"></i> ';
475 475 }
476 476 tmpl += escapeMarkup(state.text);
477 477 return tmpl;
478 478 };
479 479
480 480 var formatResult = function(result, container, query, escapeMarkup) {
481 481 return format(result, escapeMarkup);
482 482 };
483 483
484 484 var formatSelection = function(data, container, escapeMarkup) {
485 485 return format(data, escapeMarkup);
486 486 };
487 487
488 488 $("#repo_switcher").select2({
489 489 cachedDataSource: {},
490 490 minimumInputLength: 2,
491 491 placeholder: '<div class="menulabel">${_('Go to')} <div class="show_more"></div></div>',
492 492 dropdownAutoWidth: true,
493 493 formatResult: formatResult,
494 494 formatSelection: formatSelection,
495 495 containerCssClass: "repo-switcher",
496 496 dropdownCssClass: "repo-switcher-dropdown",
497 497 escapeMarkup: function(m){
498 498 // don't escape our custom placeholder
499 499 if(m.substr(0,23) == '<div class="menulabel">'){
500 500 return m;
501 501 }
502 502
503 503 return Select2.util.escapeMarkup(m);
504 504 },
505 505 query: $.debounce(250, function(query){
506 506 self = this;
507 507 var cacheKey = query.term;
508 508 var cachedData = self.cachedDataSource[cacheKey];
509 509
510 510 if (cachedData) {
511 511 query.callback({results: cachedData.results});
512 512 } else {
513 513 $.ajax({
514 514 url: pyroutes.url('goto_switcher_data'),
515 515 data: {'query': query.term},
516 516 dataType: 'json',
517 517 type: 'GET',
518 518 success: function(data) {
519 519 self.cachedDataSource[cacheKey] = data;
520 520 query.callback({results: data.results});
521 521 },
522 522 error: function(data, textStatus, errorThrown) {
523 523 alert("Error while fetching entries.\nError code {0} ({1}).".format(data.status, data.statusText));
524 524 }
525 525 })
526 526 }
527 527 })
528 528 });
529 529
530 530 $("#repo_switcher").on('select2-selecting', function(e){
531 531 e.preventDefault();
532 532 window.location = e.choice.url;
533 533 });
534 534
535 535 </script>
536 536 <script src="${h.asset('js/rhodecode/base/keyboard-bindings.js', ver=c.rhodecode_version_hash)}"></script>
537 537 </%def>
538 538
539 539 <div class="modal" id="help_kb" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
540 540 <div class="modal-dialog">
541 541 <div class="modal-content">
542 542 <div class="modal-header">
543 543 <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
544 544 <h4 class="modal-title" id="myModalLabel">${_('Keyboard shortcuts')}</h4>
545 545 </div>
546 546 <div class="modal-body">
547 547 <div class="block-left">
548 548 <table class="keyboard-mappings">
549 549 <tbody>
550 550 <tr>
551 551 <th></th>
552 552 <th>${_('Site-wide shortcuts')}</th>
553 553 </tr>
554 554 <%
555 555 elems = [
556 556 ('/', 'Open quick search box'),
557 557 ('g h', 'Goto home page'),
558 558 ('g g', 'Goto my private gists page'),
559 559 ('g G', 'Goto my public gists page'),
560 560 ('n r', 'New repository page'),
561 561 ('n g', 'New gist page'),
562 562 ]
563 563 %>
564 564 %for key, desc in elems:
565 565 <tr>
566 566 <td class="keys">
567 567 <span class="key tag">${key}</span>
568 568 </td>
569 569 <td>${desc}</td>
570 570 </tr>
571 571 %endfor
572 572 </tbody>
573 573 </table>
574 574 </div>
575 575 <div class="block-left">
576 576 <table class="keyboard-mappings">
577 577 <tbody>
578 578 <tr>
579 579 <th></th>
580 580 <th>${_('Repositories')}</th>
581 581 </tr>
582 582 <%
583 583 elems = [
584 584 ('g s', 'Goto summary page'),
585 585 ('g c', 'Goto changelog page'),
586 586 ('g f', 'Goto files page'),
587 587 ('g F', 'Goto files page with file search activated'),
588 588 ('g p', 'Goto pull requests page'),
589 589 ('g o', 'Goto repository settings'),
590 590 ('g O', 'Goto repository permissions settings'),
591 591 ]
592 592 %>
593 593 %for key, desc in elems:
594 594 <tr>
595 595 <td class="keys">
596 596 <span class="key tag">${key}</span>
597 597 </td>
598 598 <td>${desc}</td>
599 599 </tr>
600 600 %endfor
601 601 </tbody>
602 602 </table>
603 603 </div>
604 604 </div>
605 605 <div class="modal-footer">
606 606 </div>
607 607 </div><!-- /.modal-content -->
608 608 </div><!-- /.modal-dialog -->
609 609 </div><!-- /.modal -->
@@ -1,319 +1,319 b''
1 1 ## DATA TABLE RE USABLE ELEMENTS
2 2 ## usage:
3 3 ## <%namespace name="dt" file="/data_table/_dt_elements.mako"/>
4 4 <%namespace name="base" file="/base/base.mako"/>
5 5
6 6 ## REPOSITORY RENDERERS
7 7 <%def name="quick_menu(repo_name)">
8 8 <i class="icon-more"></i>
9 9 <div class="menu_items_container hidden">
10 10 <ul class="menu_items">
11 11 <li>
12 12 <a title="${_('Summary')}" href="${h.route_path('repo_summary',repo_name=repo_name)}">
13 13 <span>${_('Summary')}</span>
14 14 </a>
15 15 </li>
16 16 <li>
17 17 <a title="${_('Changelog')}" href="${h.route_path('repo_changelog',repo_name=repo_name)}">
18 18 <span>${_('Changelog')}</span>
19 19 </a>
20 20 </li>
21 21 <li>
22 22 <a title="${_('Files')}" href="${h.route_path('repo_files:default_commit',repo_name=repo_name)}">
23 23 <span>${_('Files')}</span>
24 24 </a>
25 25 </li>
26 26 <li>
27 <a title="${_('Fork')}" href="${h.url('repo_fork_home',repo_name=repo_name)}">
27 <a title="${_('Fork')}" href="${h.route_path('repo_fork_new',repo_name=repo_name)}">
28 28 <span>${_('Fork')}</span>
29 29 </a>
30 30 </li>
31 31 </ul>
32 32 </div>
33 33 </%def>
34 34
35 35 <%def name="repo_name(name,rtype,rstate,private,fork_of,short_name=False,admin=False)">
36 36 <%
37 37 def get_name(name,short_name=short_name):
38 38 if short_name:
39 39 return name.split('/')[-1]
40 40 else:
41 41 return name
42 42 %>
43 43 <div class="${'repo_state_pending' if rstate == 'repo_state_pending' else ''} truncate">
44 44 ##NAME
45 45 <a href="${h.route_path('edit_repo',repo_name=name) if admin else h.route_path('repo_summary',repo_name=name)}">
46 46
47 47 ##TYPE OF REPO
48 48 %if h.is_hg(rtype):
49 49 <span title="${_('Mercurial repository')}"><i class="icon-hg"></i></span>
50 50 %elif h.is_git(rtype):
51 51 <span title="${_('Git repository')}"><i class="icon-git"></i></span>
52 52 %elif h.is_svn(rtype):
53 53 <span title="${_('Subversion repository')}"><i class="icon-svn"></i></span>
54 54 %endif
55 55
56 56 ##PRIVATE/PUBLIC
57 57 %if private and c.visual.show_private_icon:
58 58 <i class="icon-lock" title="${_('Private repository')}"></i>
59 59 %elif not private and c.visual.show_public_icon:
60 60 <i class="icon-unlock-alt" title="${_('Public repository')}"></i>
61 61 %else:
62 62 <span></span>
63 63 %endif
64 64 ${get_name(name)}
65 65 </a>
66 66 %if fork_of:
67 67 <a href="${h.route_path('repo_summary',repo_name=fork_of.repo_name)}"><i class="icon-code-fork"></i></a>
68 68 %endif
69 69 %if rstate == 'repo_state_pending':
70 70 <span class="creation_in_progress tooltip" title="${_('This repository is being created in a background task')}">
71 71 (${_('creating...')})
72 72 </span>
73 73 %endif
74 74 </div>
75 75 </%def>
76 76
77 77 <%def name="repo_desc(description)">
78 78 <div class="truncate-wrap">${description}</div>
79 79 </%def>
80 80
81 81 <%def name="last_change(last_change)">
82 82 ${h.age_component(last_change)}
83 83 </%def>
84 84
85 85 <%def name="revision(name,rev,tip,author,last_msg)">
86 86 <div>
87 87 %if rev >= 0:
88 88 <code><a title="${h.tooltip('%s:\n\n%s' % (author,last_msg))}" class="tooltip" href="${h.route_path('repo_commit',repo_name=name,commit_id=tip)}">${'r%s:%s' % (rev,h.short_id(tip))}</a></code>
89 89 %else:
90 90 ${_('No commits yet')}
91 91 %endif
92 92 </div>
93 93 </%def>
94 94
95 95 <%def name="rss(name)">
96 96 %if c.rhodecode_user.username != h.DEFAULT_USER:
97 97 <a title="${h.tooltip(_('Subscribe to %s rss feed')% name)}" href="${h.route_path('rss_feed_home', repo_name=name, _query=dict(auth_token=c.rhodecode_user.feed_token))}"><i class="icon-rss-sign"></i></a>
98 98 %else:
99 99 <a title="${h.tooltip(_('Subscribe to %s rss feed')% name)}" href="${h.route_path('rss_feed_home', repo_name=name)}"><i class="icon-rss-sign"></i></a>
100 100 %endif
101 101 </%def>
102 102
103 103 <%def name="atom(name)">
104 104 %if c.rhodecode_user.username != h.DEFAULT_USER:
105 105 <a title="${h.tooltip(_('Subscribe to %s atom feed')% name)}" href="${h.route_path('atom_feed_home', repo_name=name, _query=dict(auth_token=c.rhodecode_user.feed_token))}"><i class="icon-rss-sign"></i></a>
106 106 %else:
107 107 <a title="${h.tooltip(_('Subscribe to %s atom feed')% name)}" href="${h.route_path('atom_feed_home', repo_name=name)}"><i class="icon-rss-sign"></i></a>
108 108 %endif
109 109 </%def>
110 110
111 111 <%def name="user_gravatar(email, size=16)">
112 112 <div class="rc-user tooltip" title="${h.tooltip(h.author_string(email))}">
113 113 ${base.gravatar(email, 16)}
114 114 </div>
115 115 </%def>
116 116
117 117 <%def name="repo_actions(repo_name, super_user=True)">
118 118 <div>
119 119 <div class="grid_edit">
120 120 <a href="${h.route_path('edit_repo',repo_name=repo_name)}" title="${_('Edit')}">
121 121 <i class="icon-pencil"></i>Edit</a>
122 122 </div>
123 123 <div class="grid_delete">
124 124 ${h.secure_form(h.route_path('edit_repo_advanced_delete', repo_name=repo_name), method='POST', request=request)}
125 125 ${h.submit('remove_%s' % repo_name,_('Delete'),class_="btn btn-link btn-danger",
126 126 onclick="return confirm('"+_('Confirm to delete this repository: %s') % repo_name+"');")}
127 127 ${h.end_form()}
128 128 </div>
129 129 </div>
130 130 </%def>
131 131
132 132 <%def name="repo_state(repo_state)">
133 133 <div>
134 134 %if repo_state == 'repo_state_pending':
135 135 <div class="tag tag4">${_('Creating')}</div>
136 136 %elif repo_state == 'repo_state_created':
137 137 <div class="tag tag1">${_('Created')}</div>
138 138 %else:
139 139 <div class="tag alert2" title="${h.tooltip(repo_state)}">invalid</div>
140 140 %endif
141 141 </div>
142 142 </%def>
143 143
144 144
145 145 ## REPO GROUP RENDERERS
146 146 <%def name="quick_repo_group_menu(repo_group_name)">
147 147 <i class="icon-more"></i>
148 148 <div class="menu_items_container hidden">
149 149 <ul class="menu_items">
150 150 <li>
151 151 <a href="${h.route_path('repo_group_home', repo_group_name=repo_group_name)}">
152 152 <span class="icon">
153 153 <i class="icon-file-text"></i>
154 154 </span>
155 155 <span>${_('Summary')}</span>
156 156 </a>
157 157 </li>
158 158
159 159 </ul>
160 160 </div>
161 161 </%def>
162 162
163 163 <%def name="repo_group_name(repo_group_name, children_groups=None)">
164 164 <div>
165 165 <a href="${h.route_path('repo_group_home', repo_group_name=repo_group_name)}">
166 166 <i class="icon-folder-close" title="${_('Repository group')}"></i>
167 167 %if children_groups:
168 168 ${h.literal(' &raquo; '.join(children_groups))}
169 169 %else:
170 170 ${repo_group_name}
171 171 %endif
172 172 </a>
173 173 </div>
174 174 </%def>
175 175
176 176 <%def name="repo_group_desc(description)">
177 177 <div class="truncate-wrap">${description}</div>
178 178 </%def>
179 179
180 180 <%def name="repo_group_actions(repo_group_id, repo_group_name, gr_count)">
181 181 <div class="grid_edit">
182 182 <a href="${h.url('edit_repo_group',group_name=repo_group_name)}" title="${_('Edit')}">Edit</a>
183 183 </div>
184 184 <div class="grid_delete">
185 185 ${h.secure_form(h.url('delete_repo_group', group_name=repo_group_name),method='delete')}
186 186 ${h.submit('remove_%s' % repo_group_name,_('Delete'),class_="btn btn-link btn-danger",
187 187 onclick="return confirm('"+_ungettext('Confirm to delete this group: %s with %s repository','Confirm to delete this group: %s with %s repositories',gr_count) % (repo_group_name, gr_count)+"');")}
188 188 ${h.end_form()}
189 189 </div>
190 190 </%def>
191 191
192 192
193 193 <%def name="user_actions(user_id, username)">
194 194 <div class="grid_edit">
195 195 <a href="${h.url('edit_user',user_id=user_id)}" title="${_('Edit')}">
196 196 <i class="icon-pencil"></i>Edit</a>
197 197 </div>
198 198 <div class="grid_delete">
199 199 ${h.secure_form(h.url('delete_user', user_id=user_id),method='delete')}
200 200 ${h.submit('remove_',_('Delete'),id="remove_user_%s" % user_id, class_="btn btn-link btn-danger",
201 201 onclick="return confirm('"+_('Confirm to delete this user: %s') % username+"');")}
202 202 ${h.end_form()}
203 203 </div>
204 204 </%def>
205 205
206 206 <%def name="user_group_actions(user_group_id, user_group_name)">
207 207 <div class="grid_edit">
208 208 <a href="${h.url('edit_users_group', user_group_id=user_group_id)}" title="${_('Edit')}">Edit</a>
209 209 </div>
210 210 <div class="grid_delete">
211 211 ${h.secure_form(h.url('delete_users_group', user_group_id=user_group_id),method='delete')}
212 212 ${h.submit('remove_',_('Delete'),id="remove_group_%s" % user_group_id, class_="btn btn-link btn-danger",
213 213 onclick="return confirm('"+_('Confirm to delete this user group: %s') % user_group_name+"');")}
214 214 ${h.end_form()}
215 215 </div>
216 216 </%def>
217 217
218 218
219 219 <%def name="user_name(user_id, username)">
220 220 ${h.link_to(h.person(username, 'username_or_name_or_email'), h.url('edit_user', user_id=user_id))}
221 221 </%def>
222 222
223 223 <%def name="user_profile(username)">
224 224 ${base.gravatar_with_user(username, 16)}
225 225 </%def>
226 226
227 227 <%def name="user_group_name(user_group_id, user_group_name)">
228 228 <div>
229 229 <a href="${h.url('edit_users_group', user_group_id=user_group_id)}">
230 230 <i class="icon-group" title="${_('User group')}"></i> ${user_group_name}</a>
231 231 </div>
232 232 </%def>
233 233
234 234
235 235 ## GISTS
236 236
237 237 <%def name="gist_gravatar(full_contact)">
238 238 <div class="gist_gravatar">
239 239 ${base.gravatar(full_contact, 30)}
240 240 </div>
241 241 </%def>
242 242
243 243 <%def name="gist_access_id(gist_access_id, full_contact)">
244 244 <div>
245 245 <b>
246 246 <a href="${h.route_path('gist_show', gist_id=gist_access_id)}">gist: ${gist_access_id}</a>
247 247 </b>
248 248 </div>
249 249 </%def>
250 250
251 251 <%def name="gist_author(full_contact, created_on, expires)">
252 252 ${base.gravatar_with_user(full_contact, 16)}
253 253 </%def>
254 254
255 255
256 256 <%def name="gist_created(created_on)">
257 257 <div class="created">
258 258 ${h.age_component(created_on, time_is_local=True)}
259 259 </div>
260 260 </%def>
261 261
262 262 <%def name="gist_expires(expires)">
263 263 <div class="created">
264 264 %if expires == -1:
265 265 ${_('never')}
266 266 %else:
267 267 ${h.age_component(h.time_to_utcdatetime(expires))}
268 268 %endif
269 269 </div>
270 270 </%def>
271 271
272 272 <%def name="gist_type(gist_type)">
273 273 %if gist_type != 'public':
274 274 <div class="tag">${_('Private')}</div>
275 275 %endif
276 276 </%def>
277 277
278 278 <%def name="gist_description(gist_description)">
279 279 ${gist_description}
280 280 </%def>
281 281
282 282
283 283 ## PULL REQUESTS GRID RENDERERS
284 284
285 285 <%def name="pullrequest_target_repo(repo_name)">
286 286 <div class="truncate">
287 287 ${h.link_to(repo_name,h.route_path('repo_summary',repo_name=repo_name))}
288 288 </div>
289 289 </%def>
290 290 <%def name="pullrequest_status(status)">
291 291 <div class="${'flag_status %s' % status} pull-left"></div>
292 292 </%def>
293 293
294 294 <%def name="pullrequest_title(title, description)">
295 295 ${title} <br/>
296 296 ${h.shorter(description, 40)}
297 297 </%def>
298 298
299 299 <%def name="pullrequest_comments(comments_nr)">
300 300 <i class="icon-comment"></i> ${comments_nr}
301 301 </%def>
302 302
303 303 <%def name="pullrequest_name(pull_request_id, target_repo_name, short=False)">
304 304 <a href="${h.route_path('pullrequest_show',repo_name=target_repo_name,pull_request_id=pull_request_id)}">
305 305 % if short:
306 306 #${pull_request_id}
307 307 % else:
308 308 ${_('Pull request #%(pr_number)s') % {'pr_number': pull_request_id,}}
309 309 % endif
310 310 </a>
311 311 </%def>
312 312
313 313 <%def name="pullrequest_updated_on(updated_on)">
314 314 ${h.age_component(h.time_to_utcdatetime(updated_on))}
315 315 </%def>
316 316
317 317 <%def name="pullrequest_author(full_contact)">
318 318 ${base.gravatar_with_user(full_contact, 16)}
319 319 </%def>
@@ -1,129 +1,129 b''
1 1 ## -*- coding: utf-8 -*-
2 2 <%inherit file="/base/base.mako"/>
3 3
4 4 <%def name="title()">
5 5 ${_('Fork repository %s') % c.repo_name}
6 6 %if c.rhodecode_name:
7 7 &middot; ${h.branding(c.rhodecode_name)}
8 8 %endif
9 9 </%def>
10 10
11 11 <%def name="breadcrumbs_links()">
12 12 ${_('New Fork')}
13 13 </%def>
14 14
15 15 <%def name="menu_bar_nav()">
16 16 ${self.menu_items(active='repositories')}
17 17 </%def>
18 18
19 19 <%def name="menu_bar_subnav()">
20 20 ${self.repo_menu(active='options')}
21 21 </%def>
22 22
23 23 <%def name="main()">
24 24 <div class="box">
25 25 <div class="title">
26 26 ${self.repo_page_title(c.rhodecode_db_repo)}
27 27 ${self.breadcrumbs()}
28 28 </div>
29 29
30 ${h.secure_form(h.url('repo_fork_create_home',repo_name=c.repo_info.repo_name))}
30 ${h.secure_form(h.route_path('repo_fork_create',repo_name=c.repo_info.repo_name), method='POST', request=request)}
31 31 <div class="form">
32 32 <!-- fields -->
33 33 <div class="fields">
34 34
35 35 <div class="field">
36 36 <div class="label">
37 37 <label for="repo_name">${_('Fork name')}:</label>
38 38 </div>
39 39 <div class="input">
40 40 ${h.text('repo_name', class_="medium")}
41 41 ${h.hidden('repo_type',c.repo_info.repo_type)}
42 42 ${h.hidden('fork_parent_id',c.repo_info.repo_id)}
43 43 </div>
44 44 </div>
45 45
46 46 <div class="field">
47 47 <div class="label label-textarea">
48 48 <label for="description">${_('Description')}:</label>
49 49 </div>
50 50 <div class="textarea-repo textarea text-area editor">
51 51 ${h.textarea('description')}
52 52 <span class="help-block">${_('Keep it short and to the point. Use a README file for longer descriptions.')}</span>
53 53 </div>
54 54 </div>
55 55
56 56 <div class="field">
57 57 <div class="label">
58 58 <label for="repo_group">${_('Repository group')}:</label>
59 59 </div>
60 60 <div class="select">
61 61 ${h.select('repo_group','',c.repo_groups,class_="medium")}
62 62 % if c.personal_repo_group:
63 63 <a class="btn" href="#" id="select_my_group" data-personal-group-id="${c.personal_repo_group.group_id}">
64 64 ${_('Select my personal group (%(repo_group_name)s)') % {'repo_group_name': c.personal_repo_group.group_name}}
65 65 </a>
66 66 % endif
67 67 <span class="help-block">${_('Optionally select a group to put this repository into.')}</span>
68 68 </div>
69 69 </div>
70 70
71 71 <div class="field">
72 72 <div class="label">
73 73 <label for="landing_rev">${_('Landing commit')}:</label>
74 74 </div>
75 75 <div class="select">
76 76 ${h.select('landing_rev','',c.landing_revs,class_="medium")}
77 77 <span class="help-block">${_('Default commit for files page, downloads, whoosh and readme')}</span>
78 78 </div>
79 79 </div>
80 80
81 81 <div class="field">
82 82 <div class="label label-checkbox">
83 83 <label for="private">${_('Private')}:</label>
84 84 </div>
85 85 <div class="checkboxes">
86 86 ${h.checkbox('private',value="True")}
87 87 <span class="help-block">${_('Private repositories are only visible to people explicitly added as collaborators.')}</span>
88 88 </div>
89 89 </div>
90 90
91 91 <div class="field">
92 92 <div class="label label-checkbox">
93 93 <label for="private">${_('Copy permissions')}:</label>
94 94 </div>
95 95 <div class="checkboxes">
96 96 ${h.checkbox('copy_permissions',value="True", checked="checked")}
97 97 <span class="help-block">${_('Copy permissions from forked repository')}</span>
98 98 </div>
99 99 </div>
100 100
101 101 <div class="buttons">
102 102 ${h.submit('',_('Fork this Repository'),class_="btn")}
103 103 </div>
104 104 </div>
105 105 </div>
106 106 ${h.end_form()}
107 107 </div>
108 108 <script>
109 109 $(document).ready(function(){
110 110 $("#repo_group").select2({
111 111 'dropdownAutoWidth': true,
112 112 'containerCssClass': "drop-menu",
113 113 'dropdownCssClass': "drop-menu-dropdown",
114 114 'width': "resolve"
115 115 });
116 116 $("#landing_rev").select2({
117 117 'containerCssClass': "drop-menu",
118 118 'dropdownCssClass': "drop-menu-dropdown",
119 119 'minimumResultsForSearch': -1
120 120 });
121 121 $('#repo_name').focus();
122 122
123 123 $('#select_my_group').on('click', function(e){
124 124 e.preventDefault();
125 125 $("#repo_group").val($(this).data('personalGroupId')).trigger("change");
126 126 })
127 127 })
128 128 </script>
129 129 </%def>
@@ -1,45 +1,119 b''
1 1 ## -*- coding: utf-8 -*-
2 2 <%inherit file="/base/base.mako"/>
3 3
4 4 <%def name="title()">
5 5 ${_('%s Forks') % c.repo_name}
6 6 %if c.rhodecode_name:
7 7 &middot; ${h.branding(c.rhodecode_name)}
8 8 %endif
9 9 </%def>
10 10
11 11 <%def name="breadcrumbs_links()">
12 12 ${_('Forks')}
13 13 </%def>
14 14
15 15 <%def name="menu_bar_nav()">
16 16 ${self.menu_items(active='repositories')}
17 17 </%def>
18 18
19 19 <%def name="menu_bar_subnav()">
20 20 ${self.repo_menu(active='summary')}
21 21 </%def>
22 22
23 23 <%def name="main()">
24 24 <div class="box">
25 25 <div class="title">
26 26 ${self.repo_page_title(c.rhodecode_db_repo)}
27 27 <ul class="links">
28 28 <li>
29 ## fork open link
30 <span>
31 <a class="btn btn-small btn-success" href="${h.url('repo_fork_home',repo_name=c.repo_name)}">
29 <a class="btn btn-small btn-success" href="${h.route_path('repo_fork_new',repo_name=c.repo_name)}">
32 30 ${_('Create new fork')}
33 31 </a>
34 </span>
35
36 32 </li>
37 33 </ul>
38 34 </div>
39 <div class="table">
40 <div id="forks">
41 ${c.forks_data}
42 </div>
35
36 <div id="fork_list_wrap">
37 <table id="fork_list_table" class="display"></table>
43 38 </div>
44 39 </div>
40
41
42
43 <script type="text/javascript">
44
45 $(document).ready(function() {
46 var $userListTable = $('#fork_list_table');
47
48 var getDatatableCount = function(){
49 var table = $userListTable.dataTable();
50 var page = table.api().page.info();
51 var active = page.recordsDisplay;
52 var total = page.recordsTotal;
53
54 var _text = _gettext("{0} out of {1} users").format(active, total);
55 $('#user_count').text(_text);
56 };
57
58 // user list
59 $userListTable.DataTable({
60 processing: true,
61 serverSide: true,
62 ajax: "${h.route_path('repo_forks_data', repo_name=c.repo_name)}",
63 dom: 'rtp',
64 pageLength: ${c.visual.dashboard_items},
65 order: [[ 0, "asc" ]],
66 columns: [
67 { data: {"_": "username",
68 "sort": "username"}, title: "${_('Owner')}", className: "td-user" },
69 { data: {"_": "fork_name",
70 "sort": "fork_name"}, title: "${_('Fork name')}", className: "td-email" },
71 { data: {"_": "description",
72 "sort": "description"}, title: "${_('Description')}", className: "td-user" },
73 { data: {"_": "fork_date",
74 "sort": "fork_date"}, title: "${_('Forked')}", className: "td-user" },
75 { data: {"_": "last_activity",
76 "sort": "last_activity",
77 "type": Number}, title: "${_('Last activity')}", className: "td-time" },
78 { data: {"_": "action",
79 "sort": "action"}, title: "${_('Action')}", className: "td-action", orderable: false }
80 ],
81
82 language: {
83 paginate: DEFAULT_GRID_PAGINATION,
84 sProcessing: _gettext('loading...'),
85 emptyTable: _gettext("No forks available yet.")
86 },
87
88 "createdRow": function ( row, data, index ) {
89 if (!data['active_raw']){
90 $(row).addClass('closed')
91 }
92 }
93 });
94
95 $userListTable.on('xhr.dt', function(e, settings, json, xhr){
96 $userListTable.css('opacity', 1);
97 });
98
99 $userListTable.on('preXhr.dt', function(e, settings, data){
100 $userListTable.css('opacity', 0.3);
101 });
102
103 // refresh counters on draw
104 $userListTable.on('draw.dt', function(){
105 getDatatableCount();
106 });
107
108 // filter
109 $('#q_filter').on('keyup',
110 $.debounce(250, function() {
111 $userListTable.DataTable().search(
112 $('#q_filter').val()
113 ).draw();
114 })
115 );
116
117 });
118 </script>
45 119 </%def>
@@ -1,211 +1,211 b''
1 1 <%def name="refs_counters(branches, closed_branches, tags, bookmarks)">
2 2 <span class="branchtag tag">
3 3 <a href="${h.route_path('branches_home',repo_name=c.repo_name)}" class="childs">
4 4 <i class="icon-branch"></i>${_ungettext(
5 5 '%(num)s Branch','%(num)s Branches', len(branches)) % {'num': len(branches)}}</a>
6 6 </span>
7 7
8 8 %if closed_branches:
9 9 <span class="branchtag tag">
10 10 <a href="${h.route_path('branches_home',repo_name=c.repo_name)}" class="childs">
11 11 <i class="icon-branch"></i>${_ungettext(
12 12 '%(num)s Closed Branch', '%(num)s Closed Branches', len(closed_branches)) % {'num': len(closed_branches)}}</a>
13 13 </span>
14 14 %endif
15 15
16 16 <span class="tagtag tag">
17 17 <a href="${h.route_path('tags_home',repo_name=c.repo_name)}" class="childs">
18 18 <i class="icon-tag"></i>${_ungettext(
19 19 '%(num)s Tag', '%(num)s Tags', len(tags)) % {'num': len(tags)}}</a>
20 20 </span>
21 21
22 22 %if bookmarks:
23 23 <span class="booktag tag">
24 24 <a href="${h.route_path('bookmarks_home',repo_name=c.repo_name)}" class="childs">
25 25 <i class="icon-bookmark"></i>${_ungettext(
26 26 '%(num)s Bookmark', '%(num)s Bookmarks', len(bookmarks)) % {'num': len(bookmarks)}}</a>
27 27 </span>
28 28 %endif
29 29 </%def>
30 30
31 31 <%def name="summary_detail(breadcrumbs_links, show_downloads=True)">
32 32 <% summary = lambda n:{False:'summary-short'}.get(n) %>
33 33
34 34 <div id="summary-menu-stats" class="summary-detail">
35 35 <div class="summary-detail-header">
36 36 <div class="breadcrumbs files_location">
37 37 <h4>
38 38 ${breadcrumbs_links}
39 39 </h4>
40 40 </div>
41 41 <div id="summary_details_expand" class="btn-collapse" data-toggle="summary-details">
42 42 ${_('Show More')}
43 43 </div>
44 44 </div>
45 45
46 46 <div class="fieldset">
47 47 %if h.is_svn_without_proxy(c.rhodecode_db_repo):
48 48 <div class="left-label disabled">
49 49 ${_('Read-only url')}:
50 50 </div>
51 51 <div class="right-content disabled">
52 52 <input type="text" class="input-monospace" id="clone_url" disabled value="${c.clone_repo_url}"/>
53 53 <i id="clone_by_name_copy" class="tooltip icon-clipboard clipboard-action" data-clipboard-text="${c.clone_repo_url}" title="${_('Copy the clone url')}"></i>
54 54
55 55 <input type="text" class="input-monospace" id="clone_url_id" disabled value="${c.clone_repo_url_id}" style="display: none;"/>
56 56 <i id="clone_by_id_copy" class="tooltip icon-clipboard clipboard-action" data-clipboard-text="${c.clone_repo_url_id}" title="${_('Copy the clone by id url')}" style="display: none"></i>
57 57
58 58 <a id="clone_by_name" class="clone" style="display: none;">${_('Show by Name')}</a>
59 59 <a id="clone_by_id" class="clone">${_('Show by ID')}</a>
60 60
61 61 <p class="help-block">${_('SVN Protocol is disabled. To enable it, see the')} <a href="${h.route_url('enterprise_svn_setup')}" target="_blank">${_('documentation here')}</a>.</p>
62 62 </div>
63 63 %else:
64 64 <div class="left-label">
65 65 ${_('Clone url')}:
66 66 </div>
67 67 <div class="right-content">
68 68 <input type="text" class="input-monospace" id="clone_url" readonly="readonly" value="${c.clone_repo_url}"/>
69 69 <i id="clone_by_name_copy" class="tooltip icon-clipboard clipboard-action" data-clipboard-text="${c.clone_repo_url}" title="${_('Copy the clone url')}"></i>
70 70
71 71 <input type="text" class="input-monospace" id="clone_url_id" readonly="readonly" value="${c.clone_repo_url_id}" style="display: none;"/>
72 72 <i id="clone_by_id_copy" class="tooltip icon-clipboard clipboard-action" data-clipboard-text="${c.clone_repo_url_id}" title="${_('Copy the clone by id url')}" style="display: none"></i>
73 73
74 74 <a id="clone_by_name" class="clone" style="display: none;">${_('Show by Name')}</a>
75 75 <a id="clone_by_id" class="clone">${_('Show by ID')}</a>
76 76 </div>
77 77 %endif
78 78 </div>
79 79
80 80 <div class="fieldset collapsable-content" data-toggle="summary-details" style="display: none;">
81 81 <div class="left-label">
82 82 ${_('Description')}:
83 83 </div>
84 84 <div class="right-content">
85 85 %if c.visual.stylify_metatags:
86 86 <div class="input ${summary(c.show_stats)} desc">${h.urlify_text(h.escaped_stylize(c.rhodecode_db_repo.description))}</div>
87 87 %else:
88 88 <div class="input ${summary(c.show_stats)} desc">${h.urlify_text(h.html_escape(c.rhodecode_db_repo.description))}</div>
89 89 %endif
90 90 </div>
91 91 </div>
92 92
93 93 <div class="fieldset collapsable-content" data-toggle="summary-details" style="display: none;">
94 94 <div class="left-label">
95 95 ${_('Information')}:
96 96 </div>
97 97 <div class="right-content">
98 98
99 99 <div class="repo-size">
100 100 <% commit_rev = c.rhodecode_db_repo.changeset_cache.get('revision') %>
101 101
102 102 ## commits
103 103 % if commit_rev == -1:
104 104 ${_ungettext('%(num)s Commit', '%(num)s Commits', 0) % {'num': 0}},
105 105 % else:
106 106 <a href="${h.route_path('repo_changelog', repo_name=c.repo_name)}">
107 107 ${_ungettext('%(num)s Commit', '%(num)s Commits', commit_rev) % {'num': commit_rev}}</a>,
108 108 % endif
109 109
110 110 ## forks
111 <a title="${_('Number of Repository Forks')}" href="${h.url('repo_forks_home', repo_name=c.repo_name)}">
111 <a title="${_('Number of Repository Forks')}" href="${h.route_path('repo_forks_show_all', repo_name=c.repo_name)}">
112 112 ${c.repository_forks} ${_ungettext('Fork', 'Forks', c.repository_forks)}</a>,
113 113
114 114 ## repo size
115 115 % if commit_rev == -1:
116 116 <span class="stats-bullet">0 B</span>
117 117 % else:
118 118 <span class="stats-bullet" id="repo_size_container">
119 119 ${_('Calculating Repository Size...')}
120 120 </span>
121 121 % endif
122 122 </div>
123 123
124 124 <div class="commit-info">
125 125 <div class="tags">
126 126 % if c.rhodecode_repo:
127 127 ${refs_counters(
128 128 c.rhodecode_repo.branches,
129 129 c.rhodecode_repo.branches_closed,
130 130 c.rhodecode_repo.tags,
131 131 c.rhodecode_repo.bookmarks)}
132 132 % else:
133 133 ## missing requirements can make c.rhodecode_repo None
134 134 ${refs_counters([], [], [], [])}
135 135 % endif
136 136 </div>
137 137 </div>
138 138
139 139 </div>
140 140 </div>
141 141
142 142 <div class="fieldset collapsable-content" data-toggle="summary-details" style="display: none;">
143 143 <div class="left-label">
144 144 ${_('Statistics')}:
145 145 </div>
146 146 <div class="right-content">
147 147 <div class="input ${summary(c.show_stats)} statistics">
148 148 % if c.show_stats:
149 149 <div id="lang_stats" class="enabled">
150 150 ${_('Calculating Code Statistics...')}
151 151 </div>
152 152 % else:
153 153 <span class="disabled">
154 154 ${_('Statistics are disabled for this repository')}
155 155 </span>
156 156 % if h.HasPermissionAll('hg.admin')('enable stats on from summary'):
157 157 , ${h.link_to(_('enable statistics'),h.route_path('edit_repo',repo_name=c.repo_name, _anchor='repo_enable_statistics'))}
158 158 % endif
159 159 % endif
160 160 </div>
161 161
162 162 </div>
163 163 </div>
164 164
165 165 % if show_downloads:
166 166 <div class="fieldset collapsable-content" data-toggle="summary-details" style="display: none;">
167 167 <div class="left-label">
168 168 ${_('Downloads')}:
169 169 </div>
170 170 <div class="right-content">
171 171 <div class="input ${summary(c.show_stats)} downloads">
172 172 % if c.rhodecode_repo and len(c.rhodecode_repo.revisions) == 0:
173 173 <span class="disabled">
174 174 ${_('There are no downloads yet')}
175 175 </span>
176 176 % elif not c.enable_downloads:
177 177 <span class="disabled">
178 178 ${_('Downloads are disabled for this repository')}
179 179 </span>
180 180 % if h.HasPermissionAll('hg.admin')('enable downloads on from summary'):
181 181 , ${h.link_to(_('enable downloads'),h.route_path('edit_repo',repo_name=c.repo_name, _anchor='repo_enable_downloads'))}
182 182 % endif
183 183 % else:
184 184 <span class="enabled">
185 185 <a id="archive_link" class="btn btn-small" href="${h.route_path('repo_archivefile',repo_name=c.rhodecode_db_repo.repo_name,fname='tip.zip')}">
186 186 <i class="icon-archive"></i> tip.zip
187 187 ## replaced by some JS on select
188 188 </a>
189 189 </span>
190 190 ${h.hidden('download_options')}
191 191 % endif
192 192 </div>
193 193 </div>
194 194 </div>
195 195 % endif
196 196
197 197 </div><!--end summary-detail-->
198 198 </%def>
199 199
200 200 <%def name="summary_stats(gravatar_function)">
201 201 <div class="sidebar-right">
202 202 <div class="summary-detail-header">
203 203 <h4 class="item">
204 204 ${_('Owner')}
205 205 </h4>
206 206 </div>
207 207 <div class="sidebar-right-content">
208 208 ${gravatar_function(c.rhodecode_db_repo.user.email, 16)}
209 209 </div>
210 210 </div><!--end sidebar-right-->
211 211 </%def>
@@ -1,264 +1,259 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2010-2017 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 import mock
22 21 import pytest
23 from webob.exc import HTTPNotFound
24 22
25 import rhodecode
26 23 from rhodecode.model.db import Integration
27 24 from rhodecode.model.meta import Session
28 from rhodecode.tests import assert_session_flash, url, TEST_USER_ADMIN_LOGIN
29 from rhodecode.tests.utils import AssertResponse
30 25 from rhodecode.integrations import integration_type_registry
31 26 from rhodecode.config.routing import ADMIN_PREFIX
32 27
33 28
34 29 @pytest.mark.usefixtures('app', 'autologin_user')
35 30 class TestIntegrationsView(object):
36 31 pass
37 32
38 33
39 34 class TestGlobalIntegrationsView(TestIntegrationsView):
40 35 def test_index_no_integrations(self, app):
41 36 url = ADMIN_PREFIX + '/integrations'
42 37 response = app.get(url)
43 38
44 39 assert response.status_code == 200
45 40 assert 'exist yet' in response.body
46 41
47 42 def test_index_with_integrations(self, app, global_integration_stub):
48 43 url = ADMIN_PREFIX + '/integrations'
49 44 response = app.get(url)
50 45
51 46 assert response.status_code == 200
52 47 assert 'exist yet' not in response.body
53 48 assert global_integration_stub.name in response.body
54 49
55 50 def test_new_integration_page(self, app):
56 51 url = ADMIN_PREFIX + '/integrations/new'
57 52
58 53 response = app.get(url)
59 54
60 55 assert response.status_code == 200
61 56
62 57 for integration_key in integration_type_registry:
63 58 nurl = (ADMIN_PREFIX + '/integrations/{integration}/new').format(
64 59 integration=integration_key)
65 60 assert nurl in response.body
66 61
67 62 @pytest.mark.parametrize(
68 63 'IntegrationType', integration_type_registry.values())
69 64 def test_get_create_integration_page(self, app, IntegrationType):
70 65 url = ADMIN_PREFIX + '/integrations/{integration_key}/new'.format(
71 66 integration_key=IntegrationType.key)
72 67
73 68 response = app.get(url)
74 69
75 70 assert response.status_code == 200
76 71 assert IntegrationType.display_name in response.body
77 72
78 73 def test_post_integration_page(self, app, StubIntegrationType, csrf_token,
79 74 test_repo_group, backend_random):
80 75 url = ADMIN_PREFIX + '/integrations/{integration_key}/new'.format(
81 76 integration_key=StubIntegrationType.key)
82 77
83 78 _post_integration_test_helper(app, url, csrf_token, admin_view=True,
84 79 repo=backend_random.repo, repo_group=test_repo_group)
85 80
86 81
87 82 class TestRepoGroupIntegrationsView(TestIntegrationsView):
88 83 def test_index_no_integrations(self, app, test_repo_group):
89 84 url = '/{repo_group_name}/settings/integrations'.format(
90 85 repo_group_name=test_repo_group.group_name)
91 86 response = app.get(url)
92 87
93 88 assert response.status_code == 200
94 89 assert 'exist yet' in response.body
95 90
96 91 def test_index_with_integrations(self, app, test_repo_group,
97 92 repogroup_integration_stub):
98 93 url = '/{repo_group_name}/settings/integrations'.format(
99 94 repo_group_name=test_repo_group.group_name)
100 95
101 96 stub_name = repogroup_integration_stub.name
102 97 response = app.get(url)
103 98
104 99 assert response.status_code == 200
105 100 assert 'exist yet' not in response.body
106 101 assert stub_name in response.body
107 102
108 103 def test_new_integration_page(self, app, test_repo_group):
109 104 repo_group_name = test_repo_group.group_name
110 105 url = '/{repo_group_name}/settings/integrations/new'.format(
111 106 repo_group_name=test_repo_group.group_name)
112 107
113 108 response = app.get(url)
114 109
115 110 assert response.status_code == 200
116 111
117 112 for integration_key in integration_type_registry:
118 113 nurl = ('/{repo_group_name}/settings/integrations'
119 114 '/{integration}/new').format(
120 115 repo_group_name=repo_group_name,
121 116 integration=integration_key)
122 117
123 118 assert nurl in response.body
124 119
125 120 @pytest.mark.parametrize(
126 121 'IntegrationType', integration_type_registry.values())
127 122 def test_get_create_integration_page(self, app, test_repo_group,
128 123 IntegrationType):
129 124 repo_group_name = test_repo_group.group_name
130 125 url = ('/{repo_group_name}/settings/integrations/{integration_key}/new'
131 126 ).format(repo_group_name=repo_group_name,
132 127 integration_key=IntegrationType.key)
133 128
134 129 response = app.get(url)
135 130
136 131 assert response.status_code == 200
137 132 assert IntegrationType.display_name in response.body
138 133
139 134 def test_post_integration_page(self, app, test_repo_group, backend_random,
140 135 StubIntegrationType, csrf_token):
141 136 repo_group_name = test_repo_group.group_name
142 137 url = ('/{repo_group_name}/settings/integrations/{integration_key}/new'
143 138 ).format(repo_group_name=repo_group_name,
144 139 integration_key=StubIntegrationType.key)
145 140
146 141 _post_integration_test_helper(app, url, csrf_token, admin_view=False,
147 142 repo=backend_random.repo, repo_group=test_repo_group)
148 143
149 144
150 145 class TestRepoIntegrationsView(TestIntegrationsView):
151 146 def test_index_no_integrations(self, app, backend_random):
152 147 url = '/{repo_name}/settings/integrations'.format(
153 148 repo_name=backend_random.repo.repo_name)
154 149 response = app.get(url)
155 150
156 151 assert response.status_code == 200
157 152 assert 'exist yet' in response.body
158 153
159 154 def test_index_with_integrations(self, app, repo_integration_stub):
160 155 url = '/{repo_name}/settings/integrations'.format(
161 156 repo_name=repo_integration_stub.repo.repo_name)
162 157 stub_name = repo_integration_stub.name
163 158
164 159 response = app.get(url)
165 160
166 161 assert response.status_code == 200
167 162 assert stub_name in response.body
168 163 assert 'exist yet' not in response.body
169 164
170 165 def test_new_integration_page(self, app, backend_random):
171 166 repo_name = backend_random.repo.repo_name
172 167 url = '/{repo_name}/settings/integrations/new'.format(
173 168 repo_name=repo_name)
174 169
175 170 response = app.get(url)
176 171
177 172 assert response.status_code == 200
178 173
179 174 for integration_key in integration_type_registry:
180 175 nurl = ('/{repo_name}/settings/integrations'
181 176 '/{integration}/new').format(
182 177 repo_name=repo_name,
183 178 integration=integration_key)
184 179
185 180 assert nurl in response.body
186 181
187 182 @pytest.mark.parametrize(
188 183 'IntegrationType', integration_type_registry.values())
189 184 def test_get_create_integration_page(self, app, backend_random,
190 185 IntegrationType):
191 186 repo_name = backend_random.repo.repo_name
192 187 url = '/{repo_name}/settings/integrations/{integration_key}/new'.format(
193 188 repo_name=repo_name, integration_key=IntegrationType.key)
194 189
195 190 response = app.get(url)
196 191
197 192 assert response.status_code == 200
198 193 assert IntegrationType.display_name in response.body
199 194
200 195 def test_post_integration_page(self, app, backend_random, test_repo_group,
201 196 StubIntegrationType, csrf_token):
202 197 repo_name = backend_random.repo.repo_name
203 198 url = '/{repo_name}/settings/integrations/{integration_key}/new'.format(
204 199 repo_name=repo_name, integration_key=StubIntegrationType.key)
205 200
206 201 _post_integration_test_helper(app, url, csrf_token, admin_view=False,
207 202 repo=backend_random.repo, repo_group=test_repo_group)
208 203
209 204
210 205 def _post_integration_test_helper(app, url, csrf_token, repo, repo_group,
211 206 admin_view):
212 207 """
213 208 Posts form data to create integration at the url given then deletes it and
214 209 checks if the redirect url is correct.
215 210 """
216 211
217 212 app.post(url, params={}, status=403) # missing csrf check
218 213 response = app.post(url, params={'csrf_token': csrf_token})
219 214 assert response.status_code == 200
220 215 assert 'Errors exist' in response.body
221 216
222 217 scopes_destinations = [
223 218 ('global',
224 219 ADMIN_PREFIX + '/integrations'),
225 220 ('root-repos',
226 221 ADMIN_PREFIX + '/integrations'),
227 222 ('repo:%s' % repo.repo_name,
228 223 '/%s/settings/integrations' % repo.repo_name),
229 224 ('repogroup:%s' % repo_group.group_name,
230 225 '/%s/settings/integrations' % repo_group.group_name),
231 226 ('repogroup-recursive:%s' % repo_group.group_name,
232 227 '/%s/settings/integrations' % repo_group.group_name),
233 228 ]
234 229
235 230 for scope, destination in scopes_destinations:
236 231 if admin_view:
237 232 destination = ADMIN_PREFIX + '/integrations'
238 233
239 234 form_data = [
240 235 ('csrf_token', csrf_token),
241 236 ('__start__', 'options:mapping'),
242 237 ('name', 'test integration'),
243 238 ('scope', scope),
244 239 ('enabled', 'true'),
245 240 ('__end__', 'options:mapping'),
246 241 ('__start__', 'settings:mapping'),
247 242 ('test_int_field', '34'),
248 243 ('test_string_field', ''), # empty value on purpose as it's required
249 244 ('__end__', 'settings:mapping'),
250 245 ]
251 246 errors_response = app.post(url, form_data)
252 247 assert 'Errors exist' in errors_response.body
253 248
254 249 form_data[-2] = ('test_string_field', 'data!')
255 250 assert Session().query(Integration).count() == 0
256 251 created_response = app.post(url, form_data)
257 252 assert Session().query(Integration).count() == 1
258 253
259 254 delete_response = app.post(
260 255 created_response.location,
261 256 params={'csrf_token': csrf_token, 'delete': 'delete'})
262 257
263 258 assert Session().query(Integration).count() == 0
264 259 assert delete_response.location.endswith(destination)
1 NO CONTENT: file was removed
1 NO CONTENT: file was removed
1 NO CONTENT: file was removed
General Comments 0
You need to be logged in to leave comments. Login now