##// END OF EJS Templates
permissions: handle more cases for invalidating permission caches...
marcink -
r3383:c5723c68 default
parent child Browse files
Show More
@@ -1,207 +1,215 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2016-2019 RhodeCode GmbH
3 # Copyright (C) 2016-2019 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 import logging
21 import logging
22 import formencode
22 import formencode
23 import formencode.htmlfill
23 import formencode.htmlfill
24
24
25 from pyramid.httpexceptions import HTTPFound, HTTPForbidden
25 from pyramid.httpexceptions import HTTPFound, HTTPForbidden
26 from pyramid.view import view_config
26 from pyramid.view import view_config
27 from pyramid.renderers import render
27 from pyramid.renderers import render
28 from pyramid.response import Response
28 from pyramid.response import Response
29
29
30 from rhodecode import events
30 from rhodecode import events
31 from rhodecode.apps._base import BaseAppView, DataGridAppView
31 from rhodecode.apps._base import BaseAppView, DataGridAppView
32
32
33 from rhodecode.lib.ext_json import json
33 from rhodecode.lib.ext_json import json
34 from rhodecode.lib.auth import (
34 from rhodecode.lib.auth import (
35 LoginRequired, CSRFRequired, NotAnonymous,
35 LoginRequired, CSRFRequired, NotAnonymous,
36 HasPermissionAny, HasRepoGroupPermissionAny)
36 HasPermissionAny, HasRepoGroupPermissionAny)
37 from rhodecode.lib import helpers as h, audit_logger
37 from rhodecode.lib import helpers as h, audit_logger
38 from rhodecode.lib.utils2 import safe_int, safe_unicode
38 from rhodecode.lib.utils2 import safe_int, safe_unicode
39 from rhodecode.model.forms import RepoGroupForm
39 from rhodecode.model.forms import RepoGroupForm
40 from rhodecode.model.repo_group import RepoGroupModel
40 from rhodecode.model.repo_group import RepoGroupModel
41 from rhodecode.model.scm import RepoGroupList
41 from rhodecode.model.scm import RepoGroupList
42 from rhodecode.model.db import Session, RepoGroup
42 from rhodecode.model.db import Session, RepoGroup
43
43
44 log = logging.getLogger(__name__)
44 log = logging.getLogger(__name__)
45
45
46
46
47 class AdminRepoGroupsView(BaseAppView, DataGridAppView):
47 class AdminRepoGroupsView(BaseAppView, DataGridAppView):
48
48
49 def load_default_context(self):
49 def load_default_context(self):
50 c = self._get_local_tmpl_context()
50 c = self._get_local_tmpl_context()
51
51
52 return c
52 return c
53
53
54 def _load_form_data(self, c):
54 def _load_form_data(self, c):
55 allow_empty_group = False
55 allow_empty_group = False
56
56
57 if self._can_create_repo_group():
57 if self._can_create_repo_group():
58 # we're global admin, we're ok and we can create TOP level groups
58 # we're global admin, we're ok and we can create TOP level groups
59 allow_empty_group = True
59 allow_empty_group = True
60
60
61 # override the choices for this form, we need to filter choices
61 # override the choices for this form, we need to filter choices
62 # and display only those we have ADMIN right
62 # and display only those we have ADMIN right
63 groups_with_admin_rights = RepoGroupList(
63 groups_with_admin_rights = RepoGroupList(
64 RepoGroup.query().all(),
64 RepoGroup.query().all(),
65 perm_set=['group.admin'])
65 perm_set=['group.admin'])
66 c.repo_groups = RepoGroup.groups_choices(
66 c.repo_groups = RepoGroup.groups_choices(
67 groups=groups_with_admin_rights,
67 groups=groups_with_admin_rights,
68 show_empty_group=allow_empty_group)
68 show_empty_group=allow_empty_group)
69
69
70 def _can_create_repo_group(self, parent_group_id=None):
70 def _can_create_repo_group(self, parent_group_id=None):
71 is_admin = HasPermissionAny('hg.admin')('group create controller')
71 is_admin = HasPermissionAny('hg.admin')('group create controller')
72 create_repo_group = HasPermissionAny(
72 create_repo_group = HasPermissionAny(
73 'hg.repogroup.create.true')('group create controller')
73 'hg.repogroup.create.true')('group create controller')
74 if is_admin or (create_repo_group and not parent_group_id):
74 if is_admin or (create_repo_group and not parent_group_id):
75 # we're global admin, or we have global repo group create
75 # we're global admin, or we have global repo group create
76 # permission
76 # permission
77 # we're ok and we can create TOP level groups
77 # we're ok and we can create TOP level groups
78 return True
78 return True
79 elif parent_group_id:
79 elif parent_group_id:
80 # we check the permission if we can write to parent group
80 # we check the permission if we can write to parent group
81 group = RepoGroup.get(parent_group_id)
81 group = RepoGroup.get(parent_group_id)
82 group_name = group.group_name if group else None
82 group_name = group.group_name if group else None
83 if HasRepoGroupPermissionAny('group.admin')(
83 if HasRepoGroupPermissionAny('group.admin')(
84 group_name, 'check if user is an admin of group'):
84 group_name, 'check if user is an admin of group'):
85 # we're an admin of passed in group, we're ok.
85 # we're an admin of passed in group, we're ok.
86 return True
86 return True
87 else:
87 else:
88 return False
88 return False
89 return False
89 return False
90
90
91 @LoginRequired()
91 @LoginRequired()
92 @NotAnonymous()
92 @NotAnonymous()
93 # perms check inside
93 # perms check inside
94 @view_config(
94 @view_config(
95 route_name='repo_groups', request_method='GET',
95 route_name='repo_groups', request_method='GET',
96 renderer='rhodecode:templates/admin/repo_groups/repo_groups.mako')
96 renderer='rhodecode:templates/admin/repo_groups/repo_groups.mako')
97 def repo_group_list(self):
97 def repo_group_list(self):
98 c = self.load_default_context()
98 c = self.load_default_context()
99
99
100 repo_group_list = RepoGroup.get_all_repo_groups()
100 repo_group_list = RepoGroup.get_all_repo_groups()
101 repo_group_list_acl = RepoGroupList(
101 repo_group_list_acl = RepoGroupList(
102 repo_group_list, perm_set=['group.admin'])
102 repo_group_list, perm_set=['group.admin'])
103 repo_group_data = RepoGroupModel().get_repo_groups_as_dict(
103 repo_group_data = RepoGroupModel().get_repo_groups_as_dict(
104 repo_group_list=repo_group_list_acl, admin=True)
104 repo_group_list=repo_group_list_acl, admin=True)
105 c.data = json.dumps(repo_group_data)
105 c.data = json.dumps(repo_group_data)
106 return self._get_template_context(c)
106 return self._get_template_context(c)
107
107
108 @LoginRequired()
108 @LoginRequired()
109 @NotAnonymous()
109 @NotAnonymous()
110 # perm checks inside
110 # perm checks inside
111 @view_config(
111 @view_config(
112 route_name='repo_group_new', request_method='GET',
112 route_name='repo_group_new', request_method='GET',
113 renderer='rhodecode:templates/admin/repo_groups/repo_group_add.mako')
113 renderer='rhodecode:templates/admin/repo_groups/repo_group_add.mako')
114 def repo_group_new(self):
114 def repo_group_new(self):
115 c = self.load_default_context()
115 c = self.load_default_context()
116
116
117 # perm check for admin, create_group perm or admin of parent_group
117 # perm check for admin, create_group perm or admin of parent_group
118 parent_group_id = safe_int(self.request.GET.get('parent_group'))
118 parent_group_id = safe_int(self.request.GET.get('parent_group'))
119 if not self._can_create_repo_group(parent_group_id):
119 if not self._can_create_repo_group(parent_group_id):
120 raise HTTPForbidden()
120 raise HTTPForbidden()
121
121
122 self._load_form_data(c)
122 self._load_form_data(c)
123
123
124 defaults = {} # Future proof for default of repo group
124 defaults = {} # Future proof for default of repo group
125 data = render(
125 data = render(
126 'rhodecode:templates/admin/repo_groups/repo_group_add.mako',
126 'rhodecode:templates/admin/repo_groups/repo_group_add.mako',
127 self._get_template_context(c), self.request)
127 self._get_template_context(c), self.request)
128 html = formencode.htmlfill.render(
128 html = formencode.htmlfill.render(
129 data,
129 data,
130 defaults=defaults,
130 defaults=defaults,
131 encoding="UTF-8",
131 encoding="UTF-8",
132 force_defaults=False
132 force_defaults=False
133 )
133 )
134 return Response(html)
134 return Response(html)
135
135
136 @LoginRequired()
136 @LoginRequired()
137 @NotAnonymous()
137 @NotAnonymous()
138 @CSRFRequired()
138 @CSRFRequired()
139 # perm checks inside
139 # perm checks inside
140 @view_config(
140 @view_config(
141 route_name='repo_group_create', request_method='POST',
141 route_name='repo_group_create', request_method='POST',
142 renderer='rhodecode:templates/admin/repo_groups/repo_group_add.mako')
142 renderer='rhodecode:templates/admin/repo_groups/repo_group_add.mako')
143 def repo_group_create(self):
143 def repo_group_create(self):
144 c = self.load_default_context()
144 c = self.load_default_context()
145 _ = self.request.translate
145 _ = self.request.translate
146
146
147 parent_group_id = safe_int(self.request.POST.get('group_parent_id'))
147 parent_group_id = safe_int(self.request.POST.get('group_parent_id'))
148 can_create = self._can_create_repo_group(parent_group_id)
148 can_create = self._can_create_repo_group(parent_group_id)
149
149
150 self._load_form_data(c)
150 self._load_form_data(c)
151 # permissions for can create group based on parent_id are checked
151 # permissions for can create group based on parent_id are checked
152 # here in the Form
152 # here in the Form
153 available_groups = map(lambda k: safe_unicode(k[0]), c.repo_groups)
153 available_groups = map(lambda k: safe_unicode(k[0]), c.repo_groups)
154 repo_group_form = RepoGroupForm(
154 repo_group_form = RepoGroupForm(
155 self.request.translate, available_groups=available_groups,
155 self.request.translate, available_groups=available_groups,
156 can_create_in_root=can_create)()
156 can_create_in_root=can_create)()
157
157
158 repo_group_name = self.request.POST.get('group_name')
158 repo_group_name = self.request.POST.get('group_name')
159 try:
159 try:
160 owner = self._rhodecode_user
160 owner = self._rhodecode_user
161 form_result = repo_group_form.to_python(dict(self.request.POST))
161 form_result = repo_group_form.to_python(dict(self.request.POST))
162 copy_permissions = form_result.get('group_copy_permissions')
162 repo_group = RepoGroupModel().create(
163 repo_group = RepoGroupModel().create(
163 group_name=form_result['group_name_full'],
164 group_name=form_result['group_name_full'],
164 group_description=form_result['group_description'],
165 group_description=form_result['group_description'],
165 owner=owner.user_id,
166 owner=owner.user_id,
166 copy_permissions=form_result['group_copy_permissions']
167 copy_permissions=form_result['group_copy_permissions']
167 )
168 )
168 Session().flush()
169 Session().flush()
169
170
170 repo_group_data = repo_group.get_api_data()
171 repo_group_data = repo_group.get_api_data()
171 audit_logger.store_web(
172 audit_logger.store_web(
172 'repo_group.create', action_data={'data': repo_group_data},
173 'repo_group.create', action_data={'data': repo_group_data},
173 user=self._rhodecode_user)
174 user=self._rhodecode_user)
174
175
175 Session().commit()
176 Session().commit()
176
177
177 _new_group_name = form_result['group_name_full']
178 _new_group_name = form_result['group_name_full']
178
179
179 repo_group_url = h.link_to(
180 repo_group_url = h.link_to(
180 _new_group_name,
181 _new_group_name,
181 h.route_path('repo_group_home', repo_group_name=_new_group_name))
182 h.route_path('repo_group_home', repo_group_name=_new_group_name))
182 h.flash(h.literal(_('Created repository group %s')
183 h.flash(h.literal(_('Created repository group %s')
183 % repo_group_url), category='success')
184 % repo_group_url), category='success')
184
185
185 except formencode.Invalid as errors:
186 except formencode.Invalid as errors:
186 data = render(
187 data = render(
187 'rhodecode:templates/admin/repo_groups/repo_group_add.mako',
188 'rhodecode:templates/admin/repo_groups/repo_group_add.mako',
188 self._get_template_context(c), self.request)
189 self._get_template_context(c), self.request)
189 html = formencode.htmlfill.render(
190 html = formencode.htmlfill.render(
190 data,
191 data,
191 defaults=errors.value,
192 defaults=errors.value,
192 errors=errors.error_dict or {},
193 errors=errors.error_dict or {},
193 prefix_error=False,
194 prefix_error=False,
194 encoding="UTF-8",
195 encoding="UTF-8",
195 force_defaults=False
196 force_defaults=False
196 )
197 )
197 return Response(html)
198 return Response(html)
198 except Exception:
199 except Exception:
199 log.exception("Exception during creation of repository group")
200 log.exception("Exception during creation of repository group")
200 h.flash(_('Error occurred during creation of repository group %s')
201 h.flash(_('Error occurred during creation of repository group %s')
201 % repo_group_name, category='error')
202 % repo_group_name, category='error')
202 raise HTTPFound(h.route_path('home'))
203 raise HTTPFound(h.route_path('home'))
203
204
204 events.trigger(events.UserPermissionsChange([self._rhodecode_user.user_id]))
205 affected_user_ids = [self._rhodecode_user.user_id]
206 if copy_permissions:
207 user_group_perms = repo_group.permissions(expand_from_user_groups=True)
208 copy_perms = [perm['user_id'] for perm in user_group_perms]
209 # also include those newly created by copy
210 affected_user_ids.extend(copy_perms)
211 events.trigger(events.UserPermissionsChange(affected_user_ids))
212
205 raise HTTPFound(
213 raise HTTPFound(
206 h.route_path('repo_group_home',
214 h.route_path('repo_group_home',
207 repo_group_name=form_result['group_name_full']))
215 repo_group_name=form_result['group_name_full']))
@@ -1,184 +1,194 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2016-2019 RhodeCode GmbH
3 # Copyright (C) 2016-2019 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 import logging
21 import logging
22 import formencode
22 import formencode
23 import formencode.htmlfill
23 import formencode.htmlfill
24
24
25 from pyramid.httpexceptions import HTTPFound, HTTPForbidden
25 from pyramid.httpexceptions import HTTPFound, HTTPForbidden
26 from pyramid.view import view_config
26 from pyramid.view import view_config
27 from pyramid.renderers import render
27 from pyramid.renderers import render
28 from pyramid.response import Response
28 from pyramid.response import Response
29
29
30 from rhodecode import events
30 from rhodecode import events
31 from rhodecode.apps._base import BaseAppView, DataGridAppView
31 from rhodecode.apps._base import BaseAppView, DataGridAppView
32 from rhodecode.lib.celerylib.utils import get_task_id
32 from rhodecode.lib.celerylib.utils import get_task_id
33
33
34 from rhodecode.lib.ext_json import json
34 from rhodecode.lib.ext_json import json
35 from rhodecode.lib.auth import (
35 from rhodecode.lib.auth import (
36 LoginRequired, CSRFRequired, NotAnonymous,
36 LoginRequired, CSRFRequired, NotAnonymous,
37 HasPermissionAny, HasRepoGroupPermissionAny)
37 HasPermissionAny, HasRepoGroupPermissionAny)
38 from rhodecode.lib import helpers as h
38 from rhodecode.lib import helpers as h
39 from rhodecode.lib.utils import repo_name_slug
39 from rhodecode.lib.utils import repo_name_slug
40 from rhodecode.lib.utils2 import safe_int, safe_unicode
40 from rhodecode.lib.utils2 import safe_int, safe_unicode
41 from rhodecode.model.forms import RepoForm
41 from rhodecode.model.forms import RepoForm
42 from rhodecode.model.repo import RepoModel
42 from rhodecode.model.repo import RepoModel
43 from rhodecode.model.scm import RepoList, RepoGroupList, ScmModel
43 from rhodecode.model.scm import RepoList, RepoGroupList, ScmModel
44 from rhodecode.model.settings import SettingsModel
44 from rhodecode.model.settings import SettingsModel
45 from rhodecode.model.db import Repository, RepoGroup
45 from rhodecode.model.db import Repository, RepoGroup
46
46
47 log = logging.getLogger(__name__)
47 log = logging.getLogger(__name__)
48
48
49
49
50 class AdminReposView(BaseAppView, DataGridAppView):
50 class AdminReposView(BaseAppView, DataGridAppView):
51
51
52 def load_default_context(self):
52 def load_default_context(self):
53 c = self._get_local_tmpl_context()
53 c = self._get_local_tmpl_context()
54
54
55 return c
55 return c
56
56
57 def _load_form_data(self, c):
57 def _load_form_data(self, c):
58 acl_groups = RepoGroupList(RepoGroup.query().all(),
58 acl_groups = RepoGroupList(RepoGroup.query().all(),
59 perm_set=['group.write', 'group.admin'])
59 perm_set=['group.write', 'group.admin'])
60 c.repo_groups = RepoGroup.groups_choices(groups=acl_groups)
60 c.repo_groups = RepoGroup.groups_choices(groups=acl_groups)
61 c.repo_groups_choices = map(lambda k: safe_unicode(k[0]), c.repo_groups)
61 c.repo_groups_choices = map(lambda k: safe_unicode(k[0]), c.repo_groups)
62 c.landing_revs_choices, c.landing_revs = \
62 c.landing_revs_choices, c.landing_revs = \
63 ScmModel().get_repo_landing_revs(self.request.translate)
63 ScmModel().get_repo_landing_revs(self.request.translate)
64 c.personal_repo_group = self._rhodecode_user.personal_repo_group
64 c.personal_repo_group = self._rhodecode_user.personal_repo_group
65
65
66 @LoginRequired()
66 @LoginRequired()
67 @NotAnonymous()
67 @NotAnonymous()
68 # perms check inside
68 # perms check inside
69 @view_config(
69 @view_config(
70 route_name='repos', request_method='GET',
70 route_name='repos', request_method='GET',
71 renderer='rhodecode:templates/admin/repos/repos.mako')
71 renderer='rhodecode:templates/admin/repos/repos.mako')
72 def repository_list(self):
72 def repository_list(self):
73 c = self.load_default_context()
73 c = self.load_default_context()
74
74
75 repo_list = Repository.get_all_repos()
75 repo_list = Repository.get_all_repos()
76 c.repo_list = RepoList(repo_list, perm_set=['repository.admin'])
76 c.repo_list = RepoList(repo_list, perm_set=['repository.admin'])
77 repos_data = RepoModel().get_repos_as_dict(
77 repos_data = RepoModel().get_repos_as_dict(
78 repo_list=c.repo_list, admin=True, super_user_actions=True)
78 repo_list=c.repo_list, admin=True, super_user_actions=True)
79 # json used to render the grid
79 # json used to render the grid
80 c.data = json.dumps(repos_data)
80 c.data = json.dumps(repos_data)
81
81
82 return self._get_template_context(c)
82 return self._get_template_context(c)
83
83
84 @LoginRequired()
84 @LoginRequired()
85 @NotAnonymous()
85 @NotAnonymous()
86 # perms check inside
86 # perms check inside
87 @view_config(
87 @view_config(
88 route_name='repo_new', request_method='GET',
88 route_name='repo_new', request_method='GET',
89 renderer='rhodecode:templates/admin/repos/repo_add.mako')
89 renderer='rhodecode:templates/admin/repos/repo_add.mako')
90 def repository_new(self):
90 def repository_new(self):
91 c = self.load_default_context()
91 c = self.load_default_context()
92
92
93 new_repo = self.request.GET.get('repo', '')
93 new_repo = self.request.GET.get('repo', '')
94 parent_group = safe_int(self.request.GET.get('parent_group'))
94 parent_group = safe_int(self.request.GET.get('parent_group'))
95 _gr = RepoGroup.get(parent_group)
95 _gr = RepoGroup.get(parent_group)
96
96
97 if not HasPermissionAny('hg.admin', 'hg.create.repository')():
97 if not HasPermissionAny('hg.admin', 'hg.create.repository')():
98 # you're not super admin nor have global create permissions,
98 # you're not super admin nor have global create permissions,
99 # but maybe you have at least write permission to a parent group ?
99 # but maybe you have at least write permission to a parent group ?
100
100
101 gr_name = _gr.group_name if _gr else None
101 gr_name = _gr.group_name if _gr else None
102 # create repositories with write permission on group is set to true
102 # create repositories with write permission on group is set to true
103 create_on_write = HasPermissionAny('hg.create.write_on_repogroup.true')()
103 create_on_write = HasPermissionAny('hg.create.write_on_repogroup.true')()
104 group_admin = HasRepoGroupPermissionAny('group.admin')(group_name=gr_name)
104 group_admin = HasRepoGroupPermissionAny('group.admin')(group_name=gr_name)
105 group_write = HasRepoGroupPermissionAny('group.write')(group_name=gr_name)
105 group_write = HasRepoGroupPermissionAny('group.write')(group_name=gr_name)
106 if not (group_admin or (group_write and create_on_write)):
106 if not (group_admin or (group_write and create_on_write)):
107 raise HTTPForbidden()
107 raise HTTPForbidden()
108
108
109 self._load_form_data(c)
109 self._load_form_data(c)
110 c.new_repo = repo_name_slug(new_repo)
110 c.new_repo = repo_name_slug(new_repo)
111
111
112 # apply the defaults from defaults page
112 # apply the defaults from defaults page
113 defaults = SettingsModel().get_default_repo_settings(strip_prefix=True)
113 defaults = SettingsModel().get_default_repo_settings(strip_prefix=True)
114 # set checkbox to autochecked
114 # set checkbox to autochecked
115 defaults['repo_copy_permissions'] = True
115 defaults['repo_copy_permissions'] = True
116
116
117 parent_group_choice = '-1'
117 parent_group_choice = '-1'
118 if not self._rhodecode_user.is_admin and self._rhodecode_user.personal_repo_group:
118 if not self._rhodecode_user.is_admin and self._rhodecode_user.personal_repo_group:
119 parent_group_choice = self._rhodecode_user.personal_repo_group
119 parent_group_choice = self._rhodecode_user.personal_repo_group
120
120
121 if parent_group and _gr:
121 if parent_group and _gr:
122 if parent_group in [x[0] for x in c.repo_groups]:
122 if parent_group in [x[0] for x in c.repo_groups]:
123 parent_group_choice = safe_unicode(parent_group)
123 parent_group_choice = safe_unicode(parent_group)
124
124
125 defaults.update({'repo_group': parent_group_choice})
125 defaults.update({'repo_group': parent_group_choice})
126
126
127 data = render('rhodecode:templates/admin/repos/repo_add.mako',
127 data = render('rhodecode:templates/admin/repos/repo_add.mako',
128 self._get_template_context(c), self.request)
128 self._get_template_context(c), self.request)
129 html = formencode.htmlfill.render(
129 html = formencode.htmlfill.render(
130 data,
130 data,
131 defaults=defaults,
131 defaults=defaults,
132 encoding="UTF-8",
132 encoding="UTF-8",
133 force_defaults=False
133 force_defaults=False
134 )
134 )
135 return Response(html)
135 return Response(html)
136
136
137 @LoginRequired()
137 @LoginRequired()
138 @NotAnonymous()
138 @NotAnonymous()
139 @CSRFRequired()
139 @CSRFRequired()
140 # perms check inside
140 # perms check inside
141 @view_config(
141 @view_config(
142 route_name='repo_create', request_method='POST',
142 route_name='repo_create', request_method='POST',
143 renderer='rhodecode:templates/admin/repos/repos.mako')
143 renderer='rhodecode:templates/admin/repos/repos.mako')
144 def repository_create(self):
144 def repository_create(self):
145 c = self.load_default_context()
145 c = self.load_default_context()
146
146
147 form_result = {}
147 form_result = {}
148 self._load_form_data(c)
148 self._load_form_data(c)
149 task_id = None
149
150 try:
150 try:
151 # CanWriteToGroup validators checks permissions of this POST
151 # CanWriteToGroup validators checks permissions of this POST
152 form = RepoForm(
152 form = RepoForm(
153 self.request.translate, repo_groups=c.repo_groups_choices,
153 self.request.translate, repo_groups=c.repo_groups_choices,
154 landing_revs=c.landing_revs_choices)()
154 landing_revs=c.landing_revs_choices)()
155 form_result = form.to_python(dict(self.request.POST))
155 form_result = form.to_python(dict(self.request.POST))
156
156 copy_permissions = form_result.get('repo_copy_permissions')
157 # create is done sometimes async on celery, db transaction
157 # create is done sometimes async on celery, db transaction
158 # management is handled there.
158 # management is handled there.
159 task = RepoModel().create(form_result, self._rhodecode_user.user_id)
159 task = RepoModel().create(form_result, self._rhodecode_user.user_id)
160 task_id = get_task_id(task)
160 task_id = get_task_id(task)
161 except formencode.Invalid as errors:
161 except formencode.Invalid as errors:
162 data = render('rhodecode:templates/admin/repos/repo_add.mako',
162 data = render('rhodecode:templates/admin/repos/repo_add.mako',
163 self._get_template_context(c), self.request)
163 self._get_template_context(c), self.request)
164 html = formencode.htmlfill.render(
164 html = formencode.htmlfill.render(
165 data,
165 data,
166 defaults=errors.value,
166 defaults=errors.value,
167 errors=errors.error_dict or {},
167 errors=errors.error_dict or {},
168 prefix_error=False,
168 prefix_error=False,
169 encoding="UTF-8",
169 encoding="UTF-8",
170 force_defaults=False
170 force_defaults=False
171 )
171 )
172 return Response(html)
172 return Response(html)
173
173
174 except Exception as e:
174 except Exception as e:
175 msg = self._log_creation_exception(e, form_result.get('repo_name'))
175 msg = self._log_creation_exception(e, form_result.get('repo_name'))
176 h.flash(msg, category='error')
176 h.flash(msg, category='error')
177 raise HTTPFound(h.route_path('home'))
177 raise HTTPFound(h.route_path('home'))
178
178
179 events.trigger(events.UserPermissionsChange([self._rhodecode_user.user_id]))
179 repo_name = form_result.get('repo_name_full')
180
181 affected_user_ids = [self._rhodecode_user.user_id]
182 if copy_permissions:
183 repository = Repository.get_by_repo_name(repo_name)
184 # also include those newly created by copy
185 user_group_perms = repository.permissions(expand_from_user_groups=True)
186 copy_perms = [perm['user_id'] for perm in user_group_perms]
187 # also include those newly created by copy
188 affected_user_ids.extend(copy_perms)
189
190 events.trigger(events.UserPermissionsChange(affected_user_ids))
180
191
181 raise HTTPFound(
192 raise HTTPFound(
182 h.route_path('repo_creating',
193 h.route_path('repo_creating', repo_name=repo_name,
183 repo_name=form_result['repo_name_full'],
184 _query=dict(task_id=task_id)))
194 _query=dict(task_id=task_id)))
@@ -1,1261 +1,1266 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2016-2019 RhodeCode GmbH
3 # Copyright (C) 2016-2019 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 import logging
21 import logging
22 import datetime
22 import datetime
23 import formencode
23 import formencode
24 import formencode.htmlfill
24 import formencode.htmlfill
25
25
26 from pyramid.httpexceptions import HTTPFound
26 from pyramid.httpexceptions import HTTPFound
27 from pyramid.view import view_config
27 from pyramid.view import view_config
28 from pyramid.renderers import render
28 from pyramid.renderers import render
29 from pyramid.response import Response
29 from pyramid.response import Response
30
30
31 from rhodecode import events
31 from rhodecode.apps._base import BaseAppView, DataGridAppView, UserAppView
32 from rhodecode.apps._base import BaseAppView, DataGridAppView, UserAppView
32 from rhodecode.apps.ssh_support import SshKeyFileChangeEvent
33 from rhodecode.apps.ssh_support import SshKeyFileChangeEvent
33 from rhodecode.authentication.plugins import auth_rhodecode
34 from rhodecode.authentication.plugins import auth_rhodecode
34 from rhodecode.events import trigger
35 from rhodecode.events import trigger
35 from rhodecode.model.db import true
36 from rhodecode.model.db import true
36
37
37 from rhodecode.lib import audit_logger, rc_cache
38 from rhodecode.lib import audit_logger, rc_cache
38 from rhodecode.lib.exceptions import (
39 from rhodecode.lib.exceptions import (
39 UserCreationError, UserOwnsReposException, UserOwnsRepoGroupsException,
40 UserCreationError, UserOwnsReposException, UserOwnsRepoGroupsException,
40 UserOwnsUserGroupsException, DefaultUserException)
41 UserOwnsUserGroupsException, DefaultUserException)
41 from rhodecode.lib.ext_json import json
42 from rhodecode.lib.ext_json import json
42 from rhodecode.lib.auth import (
43 from rhodecode.lib.auth import (
43 LoginRequired, HasPermissionAllDecorator, CSRFRequired)
44 LoginRequired, HasPermissionAllDecorator, CSRFRequired)
44 from rhodecode.lib import helpers as h
45 from rhodecode.lib import helpers as h
45 from rhodecode.lib.utils2 import safe_int, safe_unicode, AttributeDict
46 from rhodecode.lib.utils2 import safe_int, safe_unicode, AttributeDict
46 from rhodecode.model.auth_token import AuthTokenModel
47 from rhodecode.model.auth_token import AuthTokenModel
47 from rhodecode.model.forms import (
48 from rhodecode.model.forms import (
48 UserForm, UserIndividualPermissionsForm, UserPermissionsForm,
49 UserForm, UserIndividualPermissionsForm, UserPermissionsForm,
49 UserExtraEmailForm, UserExtraIpForm)
50 UserExtraEmailForm, UserExtraIpForm)
50 from rhodecode.model.permission import PermissionModel
51 from rhodecode.model.permission import PermissionModel
51 from rhodecode.model.repo_group import RepoGroupModel
52 from rhodecode.model.repo_group import RepoGroupModel
52 from rhodecode.model.ssh_key import SshKeyModel
53 from rhodecode.model.ssh_key import SshKeyModel
53 from rhodecode.model.user import UserModel
54 from rhodecode.model.user import UserModel
54 from rhodecode.model.user_group import UserGroupModel
55 from rhodecode.model.user_group import UserGroupModel
55 from rhodecode.model.db import (
56 from rhodecode.model.db import (
56 or_, coalesce,IntegrityError, User, UserGroup, UserIpMap, UserEmailMap,
57 or_, coalesce,IntegrityError, User, UserGroup, UserIpMap, UserEmailMap,
57 UserApiKeys, UserSshKeys, RepoGroup)
58 UserApiKeys, UserSshKeys, RepoGroup)
58 from rhodecode.model.meta import Session
59 from rhodecode.model.meta import Session
59
60
60 log = logging.getLogger(__name__)
61 log = logging.getLogger(__name__)
61
62
62
63
63 class AdminUsersView(BaseAppView, DataGridAppView):
64 class AdminUsersView(BaseAppView, DataGridAppView):
64
65
65 def load_default_context(self):
66 def load_default_context(self):
66 c = self._get_local_tmpl_context()
67 c = self._get_local_tmpl_context()
67 return c
68 return c
68
69
69 @LoginRequired()
70 @LoginRequired()
70 @HasPermissionAllDecorator('hg.admin')
71 @HasPermissionAllDecorator('hg.admin')
71 @view_config(
72 @view_config(
72 route_name='users', request_method='GET',
73 route_name='users', request_method='GET',
73 renderer='rhodecode:templates/admin/users/users.mako')
74 renderer='rhodecode:templates/admin/users/users.mako')
74 def users_list(self):
75 def users_list(self):
75 c = self.load_default_context()
76 c = self.load_default_context()
76 return self._get_template_context(c)
77 return self._get_template_context(c)
77
78
78 @LoginRequired()
79 @LoginRequired()
79 @HasPermissionAllDecorator('hg.admin')
80 @HasPermissionAllDecorator('hg.admin')
80 @view_config(
81 @view_config(
81 # renderer defined below
82 # renderer defined below
82 route_name='users_data', request_method='GET',
83 route_name='users_data', request_method='GET',
83 renderer='json_ext', xhr=True)
84 renderer='json_ext', xhr=True)
84 def users_list_data(self):
85 def users_list_data(self):
85 self.load_default_context()
86 self.load_default_context()
86 column_map = {
87 column_map = {
87 'first_name': 'name',
88 'first_name': 'name',
88 'last_name': 'lastname',
89 'last_name': 'lastname',
89 }
90 }
90 draw, start, limit = self._extract_chunk(self.request)
91 draw, start, limit = self._extract_chunk(self.request)
91 search_q, order_by, order_dir = self._extract_ordering(
92 search_q, order_by, order_dir = self._extract_ordering(
92 self.request, column_map=column_map)
93 self.request, column_map=column_map)
93 _render = self.request.get_partial_renderer(
94 _render = self.request.get_partial_renderer(
94 'rhodecode:templates/data_table/_dt_elements.mako')
95 'rhodecode:templates/data_table/_dt_elements.mako')
95
96
96 def user_actions(user_id, username):
97 def user_actions(user_id, username):
97 return _render("user_actions", user_id, username)
98 return _render("user_actions", user_id, username)
98
99
99 users_data_total_count = User.query()\
100 users_data_total_count = User.query()\
100 .filter(User.username != User.DEFAULT_USER) \
101 .filter(User.username != User.DEFAULT_USER) \
101 .count()
102 .count()
102
103
103 users_data_total_inactive_count = User.query()\
104 users_data_total_inactive_count = User.query()\
104 .filter(User.username != User.DEFAULT_USER) \
105 .filter(User.username != User.DEFAULT_USER) \
105 .filter(User.active != true())\
106 .filter(User.active != true())\
106 .count()
107 .count()
107
108
108 # json generate
109 # json generate
109 base_q = User.query().filter(User.username != User.DEFAULT_USER)
110 base_q = User.query().filter(User.username != User.DEFAULT_USER)
110 base_inactive_q = base_q.filter(User.active != true())
111 base_inactive_q = base_q.filter(User.active != true())
111
112
112 if search_q:
113 if search_q:
113 like_expression = u'%{}%'.format(safe_unicode(search_q))
114 like_expression = u'%{}%'.format(safe_unicode(search_q))
114 base_q = base_q.filter(or_(
115 base_q = base_q.filter(or_(
115 User.username.ilike(like_expression),
116 User.username.ilike(like_expression),
116 User._email.ilike(like_expression),
117 User._email.ilike(like_expression),
117 User.name.ilike(like_expression),
118 User.name.ilike(like_expression),
118 User.lastname.ilike(like_expression),
119 User.lastname.ilike(like_expression),
119 ))
120 ))
120 base_inactive_q = base_q.filter(User.active != true())
121 base_inactive_q = base_q.filter(User.active != true())
121
122
122 users_data_total_filtered_count = base_q.count()
123 users_data_total_filtered_count = base_q.count()
123 users_data_total_filtered_inactive_count = base_inactive_q.count()
124 users_data_total_filtered_inactive_count = base_inactive_q.count()
124
125
125 sort_col = getattr(User, order_by, None)
126 sort_col = getattr(User, order_by, None)
126 if sort_col:
127 if sort_col:
127 if order_dir == 'asc':
128 if order_dir == 'asc':
128 # handle null values properly to order by NULL last
129 # handle null values properly to order by NULL last
129 if order_by in ['last_activity']:
130 if order_by in ['last_activity']:
130 sort_col = coalesce(sort_col, datetime.date.max)
131 sort_col = coalesce(sort_col, datetime.date.max)
131 sort_col = sort_col.asc()
132 sort_col = sort_col.asc()
132 else:
133 else:
133 # handle null values properly to order by NULL last
134 # handle null values properly to order by NULL last
134 if order_by in ['last_activity']:
135 if order_by in ['last_activity']:
135 sort_col = coalesce(sort_col, datetime.date.min)
136 sort_col = coalesce(sort_col, datetime.date.min)
136 sort_col = sort_col.desc()
137 sort_col = sort_col.desc()
137
138
138 base_q = base_q.order_by(sort_col)
139 base_q = base_q.order_by(sort_col)
139 base_q = base_q.offset(start).limit(limit)
140 base_q = base_q.offset(start).limit(limit)
140
141
141 users_list = base_q.all()
142 users_list = base_q.all()
142
143
143 users_data = []
144 users_data = []
144 for user in users_list:
145 for user in users_list:
145 users_data.append({
146 users_data.append({
146 "username": h.gravatar_with_user(self.request, user.username),
147 "username": h.gravatar_with_user(self.request, user.username),
147 "email": user.email,
148 "email": user.email,
148 "first_name": user.first_name,
149 "first_name": user.first_name,
149 "last_name": user.last_name,
150 "last_name": user.last_name,
150 "last_login": h.format_date(user.last_login),
151 "last_login": h.format_date(user.last_login),
151 "last_activity": h.format_date(user.last_activity),
152 "last_activity": h.format_date(user.last_activity),
152 "active": h.bool2icon(user.active),
153 "active": h.bool2icon(user.active),
153 "active_raw": user.active,
154 "active_raw": user.active,
154 "admin": h.bool2icon(user.admin),
155 "admin": h.bool2icon(user.admin),
155 "extern_type": user.extern_type,
156 "extern_type": user.extern_type,
156 "extern_name": user.extern_name,
157 "extern_name": user.extern_name,
157 "action": user_actions(user.user_id, user.username),
158 "action": user_actions(user.user_id, user.username),
158 })
159 })
159 data = ({
160 data = ({
160 'draw': draw,
161 'draw': draw,
161 'data': users_data,
162 'data': users_data,
162 'recordsTotal': users_data_total_count,
163 'recordsTotal': users_data_total_count,
163 'recordsFiltered': users_data_total_filtered_count,
164 'recordsFiltered': users_data_total_filtered_count,
164 'recordsTotalInactive': users_data_total_inactive_count,
165 'recordsTotalInactive': users_data_total_inactive_count,
165 'recordsFilteredInactive': users_data_total_filtered_inactive_count
166 'recordsFilteredInactive': users_data_total_filtered_inactive_count
166 })
167 })
167
168
168 return data
169 return data
169
170
170 def _set_personal_repo_group_template_vars(self, c_obj):
171 def _set_personal_repo_group_template_vars(self, c_obj):
171 DummyUser = AttributeDict({
172 DummyUser = AttributeDict({
172 'username': '${username}',
173 'username': '${username}',
173 'user_id': '${user_id}',
174 'user_id': '${user_id}',
174 })
175 })
175 c_obj.default_create_repo_group = RepoGroupModel() \
176 c_obj.default_create_repo_group = RepoGroupModel() \
176 .get_default_create_personal_repo_group()
177 .get_default_create_personal_repo_group()
177 c_obj.personal_repo_group_name = RepoGroupModel() \
178 c_obj.personal_repo_group_name = RepoGroupModel() \
178 .get_personal_group_name(DummyUser)
179 .get_personal_group_name(DummyUser)
179
180
180 @LoginRequired()
181 @LoginRequired()
181 @HasPermissionAllDecorator('hg.admin')
182 @HasPermissionAllDecorator('hg.admin')
182 @view_config(
183 @view_config(
183 route_name='users_new', request_method='GET',
184 route_name='users_new', request_method='GET',
184 renderer='rhodecode:templates/admin/users/user_add.mako')
185 renderer='rhodecode:templates/admin/users/user_add.mako')
185 def users_new(self):
186 def users_new(self):
186 _ = self.request.translate
187 _ = self.request.translate
187 c = self.load_default_context()
188 c = self.load_default_context()
188 c.default_extern_type = auth_rhodecode.RhodeCodeAuthPlugin.uid
189 c.default_extern_type = auth_rhodecode.RhodeCodeAuthPlugin.uid
189 self._set_personal_repo_group_template_vars(c)
190 self._set_personal_repo_group_template_vars(c)
190 return self._get_template_context(c)
191 return self._get_template_context(c)
191
192
192 @LoginRequired()
193 @LoginRequired()
193 @HasPermissionAllDecorator('hg.admin')
194 @HasPermissionAllDecorator('hg.admin')
194 @CSRFRequired()
195 @CSRFRequired()
195 @view_config(
196 @view_config(
196 route_name='users_create', request_method='POST',
197 route_name='users_create', request_method='POST',
197 renderer='rhodecode:templates/admin/users/user_add.mako')
198 renderer='rhodecode:templates/admin/users/user_add.mako')
198 def users_create(self):
199 def users_create(self):
199 _ = self.request.translate
200 _ = self.request.translate
200 c = self.load_default_context()
201 c = self.load_default_context()
201 c.default_extern_type = auth_rhodecode.RhodeCodeAuthPlugin.uid
202 c.default_extern_type = auth_rhodecode.RhodeCodeAuthPlugin.uid
202 user_model = UserModel()
203 user_model = UserModel()
203 user_form = UserForm(self.request.translate)()
204 user_form = UserForm(self.request.translate)()
204 try:
205 try:
205 form_result = user_form.to_python(dict(self.request.POST))
206 form_result = user_form.to_python(dict(self.request.POST))
206 user = user_model.create(form_result)
207 user = user_model.create(form_result)
207 Session().flush()
208 Session().flush()
208 creation_data = user.get_api_data()
209 creation_data = user.get_api_data()
209 username = form_result['username']
210 username = form_result['username']
210
211
211 audit_logger.store_web(
212 audit_logger.store_web(
212 'user.create', action_data={'data': creation_data},
213 'user.create', action_data={'data': creation_data},
213 user=c.rhodecode_user)
214 user=c.rhodecode_user)
214
215
215 user_link = h.link_to(
216 user_link = h.link_to(
216 h.escape(username),
217 h.escape(username),
217 h.route_path('user_edit', user_id=user.user_id))
218 h.route_path('user_edit', user_id=user.user_id))
218 h.flash(h.literal(_('Created user %(user_link)s')
219 h.flash(h.literal(_('Created user %(user_link)s')
219 % {'user_link': user_link}), category='success')
220 % {'user_link': user_link}), category='success')
220 Session().commit()
221 Session().commit()
221 except formencode.Invalid as errors:
222 except formencode.Invalid as errors:
222 self._set_personal_repo_group_template_vars(c)
223 self._set_personal_repo_group_template_vars(c)
223 data = render(
224 data = render(
224 'rhodecode:templates/admin/users/user_add.mako',
225 'rhodecode:templates/admin/users/user_add.mako',
225 self._get_template_context(c), self.request)
226 self._get_template_context(c), self.request)
226 html = formencode.htmlfill.render(
227 html = formencode.htmlfill.render(
227 data,
228 data,
228 defaults=errors.value,
229 defaults=errors.value,
229 errors=errors.error_dict or {},
230 errors=errors.error_dict or {},
230 prefix_error=False,
231 prefix_error=False,
231 encoding="UTF-8",
232 encoding="UTF-8",
232 force_defaults=False
233 force_defaults=False
233 )
234 )
234 return Response(html)
235 return Response(html)
235 except UserCreationError as e:
236 except UserCreationError as e:
236 h.flash(e, 'error')
237 h.flash(e, 'error')
237 except Exception:
238 except Exception:
238 log.exception("Exception creation of user")
239 log.exception("Exception creation of user")
239 h.flash(_('Error occurred during creation of user %s')
240 h.flash(_('Error occurred during creation of user %s')
240 % self.request.POST.get('username'), category='error')
241 % self.request.POST.get('username'), category='error')
241 raise HTTPFound(h.route_path('users'))
242 raise HTTPFound(h.route_path('users'))
242
243
243
244
244 class UsersView(UserAppView):
245 class UsersView(UserAppView):
245 ALLOW_SCOPED_TOKENS = False
246 ALLOW_SCOPED_TOKENS = False
246 """
247 """
247 This view has alternative version inside EE, if modified please take a look
248 This view has alternative version inside EE, if modified please take a look
248 in there as well.
249 in there as well.
249 """
250 """
250
251
251 def load_default_context(self):
252 def load_default_context(self):
252 c = self._get_local_tmpl_context()
253 c = self._get_local_tmpl_context()
253 c.allow_scoped_tokens = self.ALLOW_SCOPED_TOKENS
254 c.allow_scoped_tokens = self.ALLOW_SCOPED_TOKENS
254 c.allowed_languages = [
255 c.allowed_languages = [
255 ('en', 'English (en)'),
256 ('en', 'English (en)'),
256 ('de', 'German (de)'),
257 ('de', 'German (de)'),
257 ('fr', 'French (fr)'),
258 ('fr', 'French (fr)'),
258 ('it', 'Italian (it)'),
259 ('it', 'Italian (it)'),
259 ('ja', 'Japanese (ja)'),
260 ('ja', 'Japanese (ja)'),
260 ('pl', 'Polish (pl)'),
261 ('pl', 'Polish (pl)'),
261 ('pt', 'Portuguese (pt)'),
262 ('pt', 'Portuguese (pt)'),
262 ('ru', 'Russian (ru)'),
263 ('ru', 'Russian (ru)'),
263 ('zh', 'Chinese (zh)'),
264 ('zh', 'Chinese (zh)'),
264 ]
265 ]
265 req = self.request
266 req = self.request
266
267
267 c.available_permissions = req.registry.settings['available_permissions']
268 c.available_permissions = req.registry.settings['available_permissions']
268 PermissionModel().set_global_permission_choices(
269 PermissionModel().set_global_permission_choices(
269 c, gettext_translator=req.translate)
270 c, gettext_translator=req.translate)
270
271
271 return c
272 return c
272
273
273 @LoginRequired()
274 @LoginRequired()
274 @HasPermissionAllDecorator('hg.admin')
275 @HasPermissionAllDecorator('hg.admin')
275 @CSRFRequired()
276 @CSRFRequired()
276 @view_config(
277 @view_config(
277 route_name='user_update', request_method='POST',
278 route_name='user_update', request_method='POST',
278 renderer='rhodecode:templates/admin/users/user_edit.mako')
279 renderer='rhodecode:templates/admin/users/user_edit.mako')
279 def user_update(self):
280 def user_update(self):
280 _ = self.request.translate
281 _ = self.request.translate
281 c = self.load_default_context()
282 c = self.load_default_context()
282
283
283 user_id = self.db_user_id
284 user_id = self.db_user_id
284 c.user = self.db_user
285 c.user = self.db_user
285
286
286 c.active = 'profile'
287 c.active = 'profile'
287 c.extern_type = c.user.extern_type
288 c.extern_type = c.user.extern_type
288 c.extern_name = c.user.extern_name
289 c.extern_name = c.user.extern_name
289 c.perm_user = c.user.AuthUser(ip_addr=self.request.remote_addr)
290 c.perm_user = c.user.AuthUser(ip_addr=self.request.remote_addr)
290 available_languages = [x[0] for x in c.allowed_languages]
291 available_languages = [x[0] for x in c.allowed_languages]
291 _form = UserForm(self.request.translate, edit=True,
292 _form = UserForm(self.request.translate, edit=True,
292 available_languages=available_languages,
293 available_languages=available_languages,
293 old_data={'user_id': user_id,
294 old_data={'user_id': user_id,
294 'email': c.user.email})()
295 'email': c.user.email})()
295 form_result = {}
296 form_result = {}
296 old_values = c.user.get_api_data()
297 old_values = c.user.get_api_data()
297 try:
298 try:
298 form_result = _form.to_python(dict(self.request.POST))
299 form_result = _form.to_python(dict(self.request.POST))
299 skip_attrs = ['extern_type', 'extern_name']
300 skip_attrs = ['extern_type', 'extern_name']
300 # TODO: plugin should define if username can be updated
301 # TODO: plugin should define if username can be updated
301 if c.extern_type != "rhodecode":
302 if c.extern_type != "rhodecode":
302 # forbid updating username for external accounts
303 # forbid updating username for external accounts
303 skip_attrs.append('username')
304 skip_attrs.append('username')
304
305
305 UserModel().update_user(
306 UserModel().update_user(
306 user_id, skip_attrs=skip_attrs, **form_result)
307 user_id, skip_attrs=skip_attrs, **form_result)
307
308
308 audit_logger.store_web(
309 audit_logger.store_web(
309 'user.edit', action_data={'old_data': old_values},
310 'user.edit', action_data={'old_data': old_values},
310 user=c.rhodecode_user)
311 user=c.rhodecode_user)
311
312
312 Session().commit()
313 Session().commit()
313 h.flash(_('User updated successfully'), category='success')
314 h.flash(_('User updated successfully'), category='success')
314 except formencode.Invalid as errors:
315 except formencode.Invalid as errors:
315 data = render(
316 data = render(
316 'rhodecode:templates/admin/users/user_edit.mako',
317 'rhodecode:templates/admin/users/user_edit.mako',
317 self._get_template_context(c), self.request)
318 self._get_template_context(c), self.request)
318 html = formencode.htmlfill.render(
319 html = formencode.htmlfill.render(
319 data,
320 data,
320 defaults=errors.value,
321 defaults=errors.value,
321 errors=errors.error_dict or {},
322 errors=errors.error_dict or {},
322 prefix_error=False,
323 prefix_error=False,
323 encoding="UTF-8",
324 encoding="UTF-8",
324 force_defaults=False
325 force_defaults=False
325 )
326 )
326 return Response(html)
327 return Response(html)
327 except UserCreationError as e:
328 except UserCreationError as e:
328 h.flash(e, 'error')
329 h.flash(e, 'error')
329 except Exception:
330 except Exception:
330 log.exception("Exception updating user")
331 log.exception("Exception updating user")
331 h.flash(_('Error occurred during update of user %s')
332 h.flash(_('Error occurred during update of user %s')
332 % form_result.get('username'), category='error')
333 % form_result.get('username'), category='error')
333 raise HTTPFound(h.route_path('user_edit', user_id=user_id))
334 raise HTTPFound(h.route_path('user_edit', user_id=user_id))
334
335
335 @LoginRequired()
336 @LoginRequired()
336 @HasPermissionAllDecorator('hg.admin')
337 @HasPermissionAllDecorator('hg.admin')
337 @CSRFRequired()
338 @CSRFRequired()
338 @view_config(
339 @view_config(
339 route_name='user_delete', request_method='POST',
340 route_name='user_delete', request_method='POST',
340 renderer='rhodecode:templates/admin/users/user_edit.mako')
341 renderer='rhodecode:templates/admin/users/user_edit.mako')
341 def user_delete(self):
342 def user_delete(self):
342 _ = self.request.translate
343 _ = self.request.translate
343 c = self.load_default_context()
344 c = self.load_default_context()
344 c.user = self.db_user
345 c.user = self.db_user
345
346
346 _repos = c.user.repositories
347 _repos = c.user.repositories
347 _repo_groups = c.user.repository_groups
348 _repo_groups = c.user.repository_groups
348 _user_groups = c.user.user_groups
349 _user_groups = c.user.user_groups
349
350
350 handle_repos = None
351 handle_repos = None
351 handle_repo_groups = None
352 handle_repo_groups = None
352 handle_user_groups = None
353 handle_user_groups = None
353 # dummy call for flash of handle
354 # dummy call for flash of handle
354 set_handle_flash_repos = lambda: None
355 set_handle_flash_repos = lambda: None
355 set_handle_flash_repo_groups = lambda: None
356 set_handle_flash_repo_groups = lambda: None
356 set_handle_flash_user_groups = lambda: None
357 set_handle_flash_user_groups = lambda: None
357
358
358 if _repos and self.request.POST.get('user_repos'):
359 if _repos and self.request.POST.get('user_repos'):
359 do = self.request.POST['user_repos']
360 do = self.request.POST['user_repos']
360 if do == 'detach':
361 if do == 'detach':
361 handle_repos = 'detach'
362 handle_repos = 'detach'
362 set_handle_flash_repos = lambda: h.flash(
363 set_handle_flash_repos = lambda: h.flash(
363 _('Detached %s repositories') % len(_repos),
364 _('Detached %s repositories') % len(_repos),
364 category='success')
365 category='success')
365 elif do == 'delete':
366 elif do == 'delete':
366 handle_repos = 'delete'
367 handle_repos = 'delete'
367 set_handle_flash_repos = lambda: h.flash(
368 set_handle_flash_repos = lambda: h.flash(
368 _('Deleted %s repositories') % len(_repos),
369 _('Deleted %s repositories') % len(_repos),
369 category='success')
370 category='success')
370
371
371 if _repo_groups and self.request.POST.get('user_repo_groups'):
372 if _repo_groups and self.request.POST.get('user_repo_groups'):
372 do = self.request.POST['user_repo_groups']
373 do = self.request.POST['user_repo_groups']
373 if do == 'detach':
374 if do == 'detach':
374 handle_repo_groups = 'detach'
375 handle_repo_groups = 'detach'
375 set_handle_flash_repo_groups = lambda: h.flash(
376 set_handle_flash_repo_groups = lambda: h.flash(
376 _('Detached %s repository groups') % len(_repo_groups),
377 _('Detached %s repository groups') % len(_repo_groups),
377 category='success')
378 category='success')
378 elif do == 'delete':
379 elif do == 'delete':
379 handle_repo_groups = 'delete'
380 handle_repo_groups = 'delete'
380 set_handle_flash_repo_groups = lambda: h.flash(
381 set_handle_flash_repo_groups = lambda: h.flash(
381 _('Deleted %s repository groups') % len(_repo_groups),
382 _('Deleted %s repository groups') % len(_repo_groups),
382 category='success')
383 category='success')
383
384
384 if _user_groups and self.request.POST.get('user_user_groups'):
385 if _user_groups and self.request.POST.get('user_user_groups'):
385 do = self.request.POST['user_user_groups']
386 do = self.request.POST['user_user_groups']
386 if do == 'detach':
387 if do == 'detach':
387 handle_user_groups = 'detach'
388 handle_user_groups = 'detach'
388 set_handle_flash_user_groups = lambda: h.flash(
389 set_handle_flash_user_groups = lambda: h.flash(
389 _('Detached %s user groups') % len(_user_groups),
390 _('Detached %s user groups') % len(_user_groups),
390 category='success')
391 category='success')
391 elif do == 'delete':
392 elif do == 'delete':
392 handle_user_groups = 'delete'
393 handle_user_groups = 'delete'
393 set_handle_flash_user_groups = lambda: h.flash(
394 set_handle_flash_user_groups = lambda: h.flash(
394 _('Deleted %s user groups') % len(_user_groups),
395 _('Deleted %s user groups') % len(_user_groups),
395 category='success')
396 category='success')
396
397
397 old_values = c.user.get_api_data()
398 old_values = c.user.get_api_data()
398 try:
399 try:
399 UserModel().delete(c.user, handle_repos=handle_repos,
400 UserModel().delete(c.user, handle_repos=handle_repos,
400 handle_repo_groups=handle_repo_groups,
401 handle_repo_groups=handle_repo_groups,
401 handle_user_groups=handle_user_groups)
402 handle_user_groups=handle_user_groups)
402
403
403 audit_logger.store_web(
404 audit_logger.store_web(
404 'user.delete', action_data={'old_data': old_values},
405 'user.delete', action_data={'old_data': old_values},
405 user=c.rhodecode_user)
406 user=c.rhodecode_user)
406
407
407 Session().commit()
408 Session().commit()
408 set_handle_flash_repos()
409 set_handle_flash_repos()
409 set_handle_flash_repo_groups()
410 set_handle_flash_repo_groups()
410 set_handle_flash_user_groups()
411 set_handle_flash_user_groups()
411 h.flash(_('Successfully deleted user'), category='success')
412 h.flash(_('Successfully deleted user'), category='success')
412 except (UserOwnsReposException, UserOwnsRepoGroupsException,
413 except (UserOwnsReposException, UserOwnsRepoGroupsException,
413 UserOwnsUserGroupsException, DefaultUserException) as e:
414 UserOwnsUserGroupsException, DefaultUserException) as e:
414 h.flash(e, category='warning')
415 h.flash(e, category='warning')
415 except Exception:
416 except Exception:
416 log.exception("Exception during deletion of user")
417 log.exception("Exception during deletion of user")
417 h.flash(_('An error occurred during deletion of user'),
418 h.flash(_('An error occurred during deletion of user'),
418 category='error')
419 category='error')
419 raise HTTPFound(h.route_path('users'))
420 raise HTTPFound(h.route_path('users'))
420
421
421 @LoginRequired()
422 @LoginRequired()
422 @HasPermissionAllDecorator('hg.admin')
423 @HasPermissionAllDecorator('hg.admin')
423 @view_config(
424 @view_config(
424 route_name='user_edit', request_method='GET',
425 route_name='user_edit', request_method='GET',
425 renderer='rhodecode:templates/admin/users/user_edit.mako')
426 renderer='rhodecode:templates/admin/users/user_edit.mako')
426 def user_edit(self):
427 def user_edit(self):
427 _ = self.request.translate
428 _ = self.request.translate
428 c = self.load_default_context()
429 c = self.load_default_context()
429 c.user = self.db_user
430 c.user = self.db_user
430
431
431 c.active = 'profile'
432 c.active = 'profile'
432 c.extern_type = c.user.extern_type
433 c.extern_type = c.user.extern_type
433 c.extern_name = c.user.extern_name
434 c.extern_name = c.user.extern_name
434 c.perm_user = c.user.AuthUser(ip_addr=self.request.remote_addr)
435 c.perm_user = c.user.AuthUser(ip_addr=self.request.remote_addr)
435
436
436 defaults = c.user.get_dict()
437 defaults = c.user.get_dict()
437 defaults.update({'language': c.user.user_data.get('language')})
438 defaults.update({'language': c.user.user_data.get('language')})
438
439
439 data = render(
440 data = render(
440 'rhodecode:templates/admin/users/user_edit.mako',
441 'rhodecode:templates/admin/users/user_edit.mako',
441 self._get_template_context(c), self.request)
442 self._get_template_context(c), self.request)
442 html = formencode.htmlfill.render(
443 html = formencode.htmlfill.render(
443 data,
444 data,
444 defaults=defaults,
445 defaults=defaults,
445 encoding="UTF-8",
446 encoding="UTF-8",
446 force_defaults=False
447 force_defaults=False
447 )
448 )
448 return Response(html)
449 return Response(html)
449
450
450 @LoginRequired()
451 @LoginRequired()
451 @HasPermissionAllDecorator('hg.admin')
452 @HasPermissionAllDecorator('hg.admin')
452 @view_config(
453 @view_config(
453 route_name='user_edit_advanced', request_method='GET',
454 route_name='user_edit_advanced', request_method='GET',
454 renderer='rhodecode:templates/admin/users/user_edit.mako')
455 renderer='rhodecode:templates/admin/users/user_edit.mako')
455 def user_edit_advanced(self):
456 def user_edit_advanced(self):
456 _ = self.request.translate
457 _ = self.request.translate
457 c = self.load_default_context()
458 c = self.load_default_context()
458
459
459 user_id = self.db_user_id
460 user_id = self.db_user_id
460 c.user = self.db_user
461 c.user = self.db_user
461
462
462 c.active = 'advanced'
463 c.active = 'advanced'
463 c.personal_repo_group = RepoGroup.get_user_personal_repo_group(user_id)
464 c.personal_repo_group = RepoGroup.get_user_personal_repo_group(user_id)
464 c.personal_repo_group_name = RepoGroupModel()\
465 c.personal_repo_group_name = RepoGroupModel()\
465 .get_personal_group_name(c.user)
466 .get_personal_group_name(c.user)
466
467
467 c.user_to_review_rules = sorted(
468 c.user_to_review_rules = sorted(
468 (x.user for x in c.user.user_review_rules),
469 (x.user for x in c.user.user_review_rules),
469 key=lambda u: u.username.lower())
470 key=lambda u: u.username.lower())
470
471
471 c.first_admin = User.get_first_super_admin()
472 c.first_admin = User.get_first_super_admin()
472 defaults = c.user.get_dict()
473 defaults = c.user.get_dict()
473
474
474 # Interim workaround if the user participated on any pull requests as a
475 # Interim workaround if the user participated on any pull requests as a
475 # reviewer.
476 # reviewer.
476 has_review = len(c.user.reviewer_pull_requests)
477 has_review = len(c.user.reviewer_pull_requests)
477 c.can_delete_user = not has_review
478 c.can_delete_user = not has_review
478 c.can_delete_user_message = ''
479 c.can_delete_user_message = ''
479 inactive_link = h.link_to(
480 inactive_link = h.link_to(
480 'inactive', h.route_path('user_edit', user_id=user_id, _anchor='active'))
481 'inactive', h.route_path('user_edit', user_id=user_id, _anchor='active'))
481 if has_review == 1:
482 if has_review == 1:
482 c.can_delete_user_message = h.literal(_(
483 c.can_delete_user_message = h.literal(_(
483 'The user participates as reviewer in {} pull request and '
484 'The user participates as reviewer in {} pull request and '
484 'cannot be deleted. \nYou can set the user to '
485 'cannot be deleted. \nYou can set the user to '
485 '"{}" instead of deleting it.').format(
486 '"{}" instead of deleting it.').format(
486 has_review, inactive_link))
487 has_review, inactive_link))
487 elif has_review:
488 elif has_review:
488 c.can_delete_user_message = h.literal(_(
489 c.can_delete_user_message = h.literal(_(
489 'The user participates as reviewer in {} pull requests and '
490 'The user participates as reviewer in {} pull requests and '
490 'cannot be deleted. \nYou can set the user to '
491 'cannot be deleted. \nYou can set the user to '
491 '"{}" instead of deleting it.').format(
492 '"{}" instead of deleting it.').format(
492 has_review, inactive_link))
493 has_review, inactive_link))
493
494
494 data = render(
495 data = render(
495 'rhodecode:templates/admin/users/user_edit.mako',
496 'rhodecode:templates/admin/users/user_edit.mako',
496 self._get_template_context(c), self.request)
497 self._get_template_context(c), self.request)
497 html = formencode.htmlfill.render(
498 html = formencode.htmlfill.render(
498 data,
499 data,
499 defaults=defaults,
500 defaults=defaults,
500 encoding="UTF-8",
501 encoding="UTF-8",
501 force_defaults=False
502 force_defaults=False
502 )
503 )
503 return Response(html)
504 return Response(html)
504
505
505 @LoginRequired()
506 @LoginRequired()
506 @HasPermissionAllDecorator('hg.admin')
507 @HasPermissionAllDecorator('hg.admin')
507 @view_config(
508 @view_config(
508 route_name='user_edit_global_perms', request_method='GET',
509 route_name='user_edit_global_perms', request_method='GET',
509 renderer='rhodecode:templates/admin/users/user_edit.mako')
510 renderer='rhodecode:templates/admin/users/user_edit.mako')
510 def user_edit_global_perms(self):
511 def user_edit_global_perms(self):
511 _ = self.request.translate
512 _ = self.request.translate
512 c = self.load_default_context()
513 c = self.load_default_context()
513 c.user = self.db_user
514 c.user = self.db_user
514
515
515 c.active = 'global_perms'
516 c.active = 'global_perms'
516
517
517 c.default_user = User.get_default_user()
518 c.default_user = User.get_default_user()
518 defaults = c.user.get_dict()
519 defaults = c.user.get_dict()
519 defaults.update(c.default_user.get_default_perms(suffix='_inherited'))
520 defaults.update(c.default_user.get_default_perms(suffix='_inherited'))
520 defaults.update(c.default_user.get_default_perms())
521 defaults.update(c.default_user.get_default_perms())
521 defaults.update(c.user.get_default_perms())
522 defaults.update(c.user.get_default_perms())
522
523
523 data = render(
524 data = render(
524 'rhodecode:templates/admin/users/user_edit.mako',
525 'rhodecode:templates/admin/users/user_edit.mako',
525 self._get_template_context(c), self.request)
526 self._get_template_context(c), self.request)
526 html = formencode.htmlfill.render(
527 html = formencode.htmlfill.render(
527 data,
528 data,
528 defaults=defaults,
529 defaults=defaults,
529 encoding="UTF-8",
530 encoding="UTF-8",
530 force_defaults=False
531 force_defaults=False
531 )
532 )
532 return Response(html)
533 return Response(html)
533
534
534 @LoginRequired()
535 @LoginRequired()
535 @HasPermissionAllDecorator('hg.admin')
536 @HasPermissionAllDecorator('hg.admin')
536 @CSRFRequired()
537 @CSRFRequired()
537 @view_config(
538 @view_config(
538 route_name='user_edit_global_perms_update', request_method='POST',
539 route_name='user_edit_global_perms_update', request_method='POST',
539 renderer='rhodecode:templates/admin/users/user_edit.mako')
540 renderer='rhodecode:templates/admin/users/user_edit.mako')
540 def user_edit_global_perms_update(self):
541 def user_edit_global_perms_update(self):
541 _ = self.request.translate
542 _ = self.request.translate
542 c = self.load_default_context()
543 c = self.load_default_context()
543
544
544 user_id = self.db_user_id
545 user_id = self.db_user_id
545 c.user = self.db_user
546 c.user = self.db_user
546
547
547 c.active = 'global_perms'
548 c.active = 'global_perms'
548 try:
549 try:
549 # first stage that verifies the checkbox
550 # first stage that verifies the checkbox
550 _form = UserIndividualPermissionsForm(self.request.translate)
551 _form = UserIndividualPermissionsForm(self.request.translate)
551 form_result = _form.to_python(dict(self.request.POST))
552 form_result = _form.to_python(dict(self.request.POST))
552 inherit_perms = form_result['inherit_default_permissions']
553 inherit_perms = form_result['inherit_default_permissions']
553 c.user.inherit_default_permissions = inherit_perms
554 c.user.inherit_default_permissions = inherit_perms
554 Session().add(c.user)
555 Session().add(c.user)
555
556
556 if not inherit_perms:
557 if not inherit_perms:
557 # only update the individual ones if we un check the flag
558 # only update the individual ones if we un check the flag
558 _form = UserPermissionsForm(
559 _form = UserPermissionsForm(
559 self.request.translate,
560 self.request.translate,
560 [x[0] for x in c.repo_create_choices],
561 [x[0] for x in c.repo_create_choices],
561 [x[0] for x in c.repo_create_on_write_choices],
562 [x[0] for x in c.repo_create_on_write_choices],
562 [x[0] for x in c.repo_group_create_choices],
563 [x[0] for x in c.repo_group_create_choices],
563 [x[0] for x in c.user_group_create_choices],
564 [x[0] for x in c.user_group_create_choices],
564 [x[0] for x in c.fork_choices],
565 [x[0] for x in c.fork_choices],
565 [x[0] for x in c.inherit_default_permission_choices])()
566 [x[0] for x in c.inherit_default_permission_choices])()
566
567
567 form_result = _form.to_python(dict(self.request.POST))
568 form_result = _form.to_python(dict(self.request.POST))
568 form_result.update({'perm_user_id': c.user.user_id})
569 form_result.update({'perm_user_id': c.user.user_id})
569
570
570 PermissionModel().update_user_permissions(form_result)
571 PermissionModel().update_user_permissions(form_result)
571
572
572 # TODO(marcink): implement global permissions
573 # TODO(marcink): implement global permissions
573 # audit_log.store_web('user.edit.permissions')
574 # audit_log.store_web('user.edit.permissions')
574
575
575 Session().commit()
576 Session().commit()
577
576 h.flash(_('User global permissions updated successfully'),
578 h.flash(_('User global permissions updated successfully'),
577 category='success')
579 category='success')
578
580
579 except formencode.Invalid as errors:
581 except formencode.Invalid as errors:
580 data = render(
582 data = render(
581 'rhodecode:templates/admin/users/user_edit.mako',
583 'rhodecode:templates/admin/users/user_edit.mako',
582 self._get_template_context(c), self.request)
584 self._get_template_context(c), self.request)
583 html = formencode.htmlfill.render(
585 html = formencode.htmlfill.render(
584 data,
586 data,
585 defaults=errors.value,
587 defaults=errors.value,
586 errors=errors.error_dict or {},
588 errors=errors.error_dict or {},
587 prefix_error=False,
589 prefix_error=False,
588 encoding="UTF-8",
590 encoding="UTF-8",
589 force_defaults=False
591 force_defaults=False
590 )
592 )
591 return Response(html)
593 return Response(html)
592 except Exception:
594 except Exception:
593 log.exception("Exception during permissions saving")
595 log.exception("Exception during permissions saving")
594 h.flash(_('An error occurred during permissions saving'),
596 h.flash(_('An error occurred during permissions saving'),
595 category='error')
597 category='error')
598
599 affected_user_ids = [user_id]
600 events.trigger(events.UserPermissionsChange(affected_user_ids))
596 raise HTTPFound(h.route_path('user_edit_global_perms', user_id=user_id))
601 raise HTTPFound(h.route_path('user_edit_global_perms', user_id=user_id))
597
602
598 @LoginRequired()
603 @LoginRequired()
599 @HasPermissionAllDecorator('hg.admin')
604 @HasPermissionAllDecorator('hg.admin')
600 @CSRFRequired()
605 @CSRFRequired()
601 @view_config(
606 @view_config(
602 route_name='user_enable_force_password_reset', request_method='POST',
607 route_name='user_enable_force_password_reset', request_method='POST',
603 renderer='rhodecode:templates/admin/users/user_edit.mako')
608 renderer='rhodecode:templates/admin/users/user_edit.mako')
604 def user_enable_force_password_reset(self):
609 def user_enable_force_password_reset(self):
605 _ = self.request.translate
610 _ = self.request.translate
606 c = self.load_default_context()
611 c = self.load_default_context()
607
612
608 user_id = self.db_user_id
613 user_id = self.db_user_id
609 c.user = self.db_user
614 c.user = self.db_user
610
615
611 try:
616 try:
612 c.user.update_userdata(force_password_change=True)
617 c.user.update_userdata(force_password_change=True)
613
618
614 msg = _('Force password change enabled for user')
619 msg = _('Force password change enabled for user')
615 audit_logger.store_web('user.edit.password_reset.enabled',
620 audit_logger.store_web('user.edit.password_reset.enabled',
616 user=c.rhodecode_user)
621 user=c.rhodecode_user)
617
622
618 Session().commit()
623 Session().commit()
619 h.flash(msg, category='success')
624 h.flash(msg, category='success')
620 except Exception:
625 except Exception:
621 log.exception("Exception during password reset for user")
626 log.exception("Exception during password reset for user")
622 h.flash(_('An error occurred during password reset for user'),
627 h.flash(_('An error occurred during password reset for user'),
623 category='error')
628 category='error')
624
629
625 raise HTTPFound(h.route_path('user_edit_advanced', user_id=user_id))
630 raise HTTPFound(h.route_path('user_edit_advanced', user_id=user_id))
626
631
627 @LoginRequired()
632 @LoginRequired()
628 @HasPermissionAllDecorator('hg.admin')
633 @HasPermissionAllDecorator('hg.admin')
629 @CSRFRequired()
634 @CSRFRequired()
630 @view_config(
635 @view_config(
631 route_name='user_disable_force_password_reset', request_method='POST',
636 route_name='user_disable_force_password_reset', request_method='POST',
632 renderer='rhodecode:templates/admin/users/user_edit.mako')
637 renderer='rhodecode:templates/admin/users/user_edit.mako')
633 def user_disable_force_password_reset(self):
638 def user_disable_force_password_reset(self):
634 _ = self.request.translate
639 _ = self.request.translate
635 c = self.load_default_context()
640 c = self.load_default_context()
636
641
637 user_id = self.db_user_id
642 user_id = self.db_user_id
638 c.user = self.db_user
643 c.user = self.db_user
639
644
640 try:
645 try:
641 c.user.update_userdata(force_password_change=False)
646 c.user.update_userdata(force_password_change=False)
642
647
643 msg = _('Force password change disabled for user')
648 msg = _('Force password change disabled for user')
644 audit_logger.store_web(
649 audit_logger.store_web(
645 'user.edit.password_reset.disabled',
650 'user.edit.password_reset.disabled',
646 user=c.rhodecode_user)
651 user=c.rhodecode_user)
647
652
648 Session().commit()
653 Session().commit()
649 h.flash(msg, category='success')
654 h.flash(msg, category='success')
650 except Exception:
655 except Exception:
651 log.exception("Exception during password reset for user")
656 log.exception("Exception during password reset for user")
652 h.flash(_('An error occurred during password reset for user'),
657 h.flash(_('An error occurred during password reset for user'),
653 category='error')
658 category='error')
654
659
655 raise HTTPFound(h.route_path('user_edit_advanced', user_id=user_id))
660 raise HTTPFound(h.route_path('user_edit_advanced', user_id=user_id))
656
661
657 @LoginRequired()
662 @LoginRequired()
658 @HasPermissionAllDecorator('hg.admin')
663 @HasPermissionAllDecorator('hg.admin')
659 @CSRFRequired()
664 @CSRFRequired()
660 @view_config(
665 @view_config(
661 route_name='user_create_personal_repo_group', request_method='POST',
666 route_name='user_create_personal_repo_group', request_method='POST',
662 renderer='rhodecode:templates/admin/users/user_edit.mako')
667 renderer='rhodecode:templates/admin/users/user_edit.mako')
663 def user_create_personal_repo_group(self):
668 def user_create_personal_repo_group(self):
664 """
669 """
665 Create personal repository group for this user
670 Create personal repository group for this user
666 """
671 """
667 from rhodecode.model.repo_group import RepoGroupModel
672 from rhodecode.model.repo_group import RepoGroupModel
668
673
669 _ = self.request.translate
674 _ = self.request.translate
670 c = self.load_default_context()
675 c = self.load_default_context()
671
676
672 user_id = self.db_user_id
677 user_id = self.db_user_id
673 c.user = self.db_user
678 c.user = self.db_user
674
679
675 personal_repo_group = RepoGroup.get_user_personal_repo_group(
680 personal_repo_group = RepoGroup.get_user_personal_repo_group(
676 c.user.user_id)
681 c.user.user_id)
677 if personal_repo_group:
682 if personal_repo_group:
678 raise HTTPFound(h.route_path('user_edit_advanced', user_id=user_id))
683 raise HTTPFound(h.route_path('user_edit_advanced', user_id=user_id))
679
684
680 personal_repo_group_name = RepoGroupModel().get_personal_group_name(
685 personal_repo_group_name = RepoGroupModel().get_personal_group_name(
681 c.user)
686 c.user)
682 named_personal_group = RepoGroup.get_by_group_name(
687 named_personal_group = RepoGroup.get_by_group_name(
683 personal_repo_group_name)
688 personal_repo_group_name)
684 try:
689 try:
685
690
686 if named_personal_group and named_personal_group.user_id == c.user.user_id:
691 if named_personal_group and named_personal_group.user_id == c.user.user_id:
687 # migrate the same named group, and mark it as personal
692 # migrate the same named group, and mark it as personal
688 named_personal_group.personal = True
693 named_personal_group.personal = True
689 Session().add(named_personal_group)
694 Session().add(named_personal_group)
690 Session().commit()
695 Session().commit()
691 msg = _('Linked repository group `%s` as personal' % (
696 msg = _('Linked repository group `%s` as personal' % (
692 personal_repo_group_name,))
697 personal_repo_group_name,))
693 h.flash(msg, category='success')
698 h.flash(msg, category='success')
694 elif not named_personal_group:
699 elif not named_personal_group:
695 RepoGroupModel().create_personal_repo_group(c.user)
700 RepoGroupModel().create_personal_repo_group(c.user)
696
701
697 msg = _('Created repository group `%s`' % (
702 msg = _('Created repository group `%s`' % (
698 personal_repo_group_name,))
703 personal_repo_group_name,))
699 h.flash(msg, category='success')
704 h.flash(msg, category='success')
700 else:
705 else:
701 msg = _('Repository group `%s` is already taken' % (
706 msg = _('Repository group `%s` is already taken' % (
702 personal_repo_group_name,))
707 personal_repo_group_name,))
703 h.flash(msg, category='warning')
708 h.flash(msg, category='warning')
704 except Exception:
709 except Exception:
705 log.exception("Exception during repository group creation")
710 log.exception("Exception during repository group creation")
706 msg = _(
711 msg = _(
707 'An error occurred during repository group creation for user')
712 'An error occurred during repository group creation for user')
708 h.flash(msg, category='error')
713 h.flash(msg, category='error')
709 Session().rollback()
714 Session().rollback()
710
715
711 raise HTTPFound(h.route_path('user_edit_advanced', user_id=user_id))
716 raise HTTPFound(h.route_path('user_edit_advanced', user_id=user_id))
712
717
713 @LoginRequired()
718 @LoginRequired()
714 @HasPermissionAllDecorator('hg.admin')
719 @HasPermissionAllDecorator('hg.admin')
715 @view_config(
720 @view_config(
716 route_name='edit_user_auth_tokens', request_method='GET',
721 route_name='edit_user_auth_tokens', request_method='GET',
717 renderer='rhodecode:templates/admin/users/user_edit.mako')
722 renderer='rhodecode:templates/admin/users/user_edit.mako')
718 def auth_tokens(self):
723 def auth_tokens(self):
719 _ = self.request.translate
724 _ = self.request.translate
720 c = self.load_default_context()
725 c = self.load_default_context()
721 c.user = self.db_user
726 c.user = self.db_user
722
727
723 c.active = 'auth_tokens'
728 c.active = 'auth_tokens'
724
729
725 c.lifetime_values = AuthTokenModel.get_lifetime_values(translator=_)
730 c.lifetime_values = AuthTokenModel.get_lifetime_values(translator=_)
726 c.role_values = [
731 c.role_values = [
727 (x, AuthTokenModel.cls._get_role_name(x))
732 (x, AuthTokenModel.cls._get_role_name(x))
728 for x in AuthTokenModel.cls.ROLES]
733 for x in AuthTokenModel.cls.ROLES]
729 c.role_options = [(c.role_values, _("Role"))]
734 c.role_options = [(c.role_values, _("Role"))]
730 c.user_auth_tokens = AuthTokenModel().get_auth_tokens(
735 c.user_auth_tokens = AuthTokenModel().get_auth_tokens(
731 c.user.user_id, show_expired=True)
736 c.user.user_id, show_expired=True)
732 c.role_vcs = AuthTokenModel.cls.ROLE_VCS
737 c.role_vcs = AuthTokenModel.cls.ROLE_VCS
733 return self._get_template_context(c)
738 return self._get_template_context(c)
734
739
735 def maybe_attach_token_scope(self, token):
740 def maybe_attach_token_scope(self, token):
736 # implemented in EE edition
741 # implemented in EE edition
737 pass
742 pass
738
743
739 @LoginRequired()
744 @LoginRequired()
740 @HasPermissionAllDecorator('hg.admin')
745 @HasPermissionAllDecorator('hg.admin')
741 @CSRFRequired()
746 @CSRFRequired()
742 @view_config(
747 @view_config(
743 route_name='edit_user_auth_tokens_add', request_method='POST')
748 route_name='edit_user_auth_tokens_add', request_method='POST')
744 def auth_tokens_add(self):
749 def auth_tokens_add(self):
745 _ = self.request.translate
750 _ = self.request.translate
746 c = self.load_default_context()
751 c = self.load_default_context()
747
752
748 user_id = self.db_user_id
753 user_id = self.db_user_id
749 c.user = self.db_user
754 c.user = self.db_user
750
755
751 user_data = c.user.get_api_data()
756 user_data = c.user.get_api_data()
752 lifetime = safe_int(self.request.POST.get('lifetime'), -1)
757 lifetime = safe_int(self.request.POST.get('lifetime'), -1)
753 description = self.request.POST.get('description')
758 description = self.request.POST.get('description')
754 role = self.request.POST.get('role')
759 role = self.request.POST.get('role')
755
760
756 token = UserModel().add_auth_token(
761 token = UserModel().add_auth_token(
757 user=c.user.user_id,
762 user=c.user.user_id,
758 lifetime_minutes=lifetime, role=role, description=description,
763 lifetime_minutes=lifetime, role=role, description=description,
759 scope_callback=self.maybe_attach_token_scope)
764 scope_callback=self.maybe_attach_token_scope)
760 token_data = token.get_api_data()
765 token_data = token.get_api_data()
761
766
762 audit_logger.store_web(
767 audit_logger.store_web(
763 'user.edit.token.add', action_data={
768 'user.edit.token.add', action_data={
764 'data': {'token': token_data, 'user': user_data}},
769 'data': {'token': token_data, 'user': user_data}},
765 user=self._rhodecode_user, )
770 user=self._rhodecode_user, )
766 Session().commit()
771 Session().commit()
767
772
768 h.flash(_("Auth token successfully created"), category='success')
773 h.flash(_("Auth token successfully created"), category='success')
769 return HTTPFound(h.route_path('edit_user_auth_tokens', user_id=user_id))
774 return HTTPFound(h.route_path('edit_user_auth_tokens', user_id=user_id))
770
775
771 @LoginRequired()
776 @LoginRequired()
772 @HasPermissionAllDecorator('hg.admin')
777 @HasPermissionAllDecorator('hg.admin')
773 @CSRFRequired()
778 @CSRFRequired()
774 @view_config(
779 @view_config(
775 route_name='edit_user_auth_tokens_delete', request_method='POST')
780 route_name='edit_user_auth_tokens_delete', request_method='POST')
776 def auth_tokens_delete(self):
781 def auth_tokens_delete(self):
777 _ = self.request.translate
782 _ = self.request.translate
778 c = self.load_default_context()
783 c = self.load_default_context()
779
784
780 user_id = self.db_user_id
785 user_id = self.db_user_id
781 c.user = self.db_user
786 c.user = self.db_user
782
787
783 user_data = c.user.get_api_data()
788 user_data = c.user.get_api_data()
784
789
785 del_auth_token = self.request.POST.get('del_auth_token')
790 del_auth_token = self.request.POST.get('del_auth_token')
786
791
787 if del_auth_token:
792 if del_auth_token:
788 token = UserApiKeys.get_or_404(del_auth_token)
793 token = UserApiKeys.get_or_404(del_auth_token)
789 token_data = token.get_api_data()
794 token_data = token.get_api_data()
790
795
791 AuthTokenModel().delete(del_auth_token, c.user.user_id)
796 AuthTokenModel().delete(del_auth_token, c.user.user_id)
792 audit_logger.store_web(
797 audit_logger.store_web(
793 'user.edit.token.delete', action_data={
798 'user.edit.token.delete', action_data={
794 'data': {'token': token_data, 'user': user_data}},
799 'data': {'token': token_data, 'user': user_data}},
795 user=self._rhodecode_user,)
800 user=self._rhodecode_user,)
796 Session().commit()
801 Session().commit()
797 h.flash(_("Auth token successfully deleted"), category='success')
802 h.flash(_("Auth token successfully deleted"), category='success')
798
803
799 return HTTPFound(h.route_path('edit_user_auth_tokens', user_id=user_id))
804 return HTTPFound(h.route_path('edit_user_auth_tokens', user_id=user_id))
800
805
801 @LoginRequired()
806 @LoginRequired()
802 @HasPermissionAllDecorator('hg.admin')
807 @HasPermissionAllDecorator('hg.admin')
803 @view_config(
808 @view_config(
804 route_name='edit_user_ssh_keys', request_method='GET',
809 route_name='edit_user_ssh_keys', request_method='GET',
805 renderer='rhodecode:templates/admin/users/user_edit.mako')
810 renderer='rhodecode:templates/admin/users/user_edit.mako')
806 def ssh_keys(self):
811 def ssh_keys(self):
807 _ = self.request.translate
812 _ = self.request.translate
808 c = self.load_default_context()
813 c = self.load_default_context()
809 c.user = self.db_user
814 c.user = self.db_user
810
815
811 c.active = 'ssh_keys'
816 c.active = 'ssh_keys'
812 c.default_key = self.request.GET.get('default_key')
817 c.default_key = self.request.GET.get('default_key')
813 c.user_ssh_keys = SshKeyModel().get_ssh_keys(c.user.user_id)
818 c.user_ssh_keys = SshKeyModel().get_ssh_keys(c.user.user_id)
814 return self._get_template_context(c)
819 return self._get_template_context(c)
815
820
816 @LoginRequired()
821 @LoginRequired()
817 @HasPermissionAllDecorator('hg.admin')
822 @HasPermissionAllDecorator('hg.admin')
818 @view_config(
823 @view_config(
819 route_name='edit_user_ssh_keys_generate_keypair', request_method='GET',
824 route_name='edit_user_ssh_keys_generate_keypair', request_method='GET',
820 renderer='rhodecode:templates/admin/users/user_edit.mako')
825 renderer='rhodecode:templates/admin/users/user_edit.mako')
821 def ssh_keys_generate_keypair(self):
826 def ssh_keys_generate_keypair(self):
822 _ = self.request.translate
827 _ = self.request.translate
823 c = self.load_default_context()
828 c = self.load_default_context()
824
829
825 c.user = self.db_user
830 c.user = self.db_user
826
831
827 c.active = 'ssh_keys_generate'
832 c.active = 'ssh_keys_generate'
828 comment = 'RhodeCode-SSH {}'.format(c.user.email or '')
833 comment = 'RhodeCode-SSH {}'.format(c.user.email or '')
829 c.private, c.public = SshKeyModel().generate_keypair(comment=comment)
834 c.private, c.public = SshKeyModel().generate_keypair(comment=comment)
830
835
831 return self._get_template_context(c)
836 return self._get_template_context(c)
832
837
833 @LoginRequired()
838 @LoginRequired()
834 @HasPermissionAllDecorator('hg.admin')
839 @HasPermissionAllDecorator('hg.admin')
835 @CSRFRequired()
840 @CSRFRequired()
836 @view_config(
841 @view_config(
837 route_name='edit_user_ssh_keys_add', request_method='POST')
842 route_name='edit_user_ssh_keys_add', request_method='POST')
838 def ssh_keys_add(self):
843 def ssh_keys_add(self):
839 _ = self.request.translate
844 _ = self.request.translate
840 c = self.load_default_context()
845 c = self.load_default_context()
841
846
842 user_id = self.db_user_id
847 user_id = self.db_user_id
843 c.user = self.db_user
848 c.user = self.db_user
844
849
845 user_data = c.user.get_api_data()
850 user_data = c.user.get_api_data()
846 key_data = self.request.POST.get('key_data')
851 key_data = self.request.POST.get('key_data')
847 description = self.request.POST.get('description')
852 description = self.request.POST.get('description')
848
853
849 fingerprint = 'unknown'
854 fingerprint = 'unknown'
850 try:
855 try:
851 if not key_data:
856 if not key_data:
852 raise ValueError('Please add a valid public key')
857 raise ValueError('Please add a valid public key')
853
858
854 key = SshKeyModel().parse_key(key_data.strip())
859 key = SshKeyModel().parse_key(key_data.strip())
855 fingerprint = key.hash_md5()
860 fingerprint = key.hash_md5()
856
861
857 ssh_key = SshKeyModel().create(
862 ssh_key = SshKeyModel().create(
858 c.user.user_id, fingerprint, key.keydata, description)
863 c.user.user_id, fingerprint, key.keydata, description)
859 ssh_key_data = ssh_key.get_api_data()
864 ssh_key_data = ssh_key.get_api_data()
860
865
861 audit_logger.store_web(
866 audit_logger.store_web(
862 'user.edit.ssh_key.add', action_data={
867 'user.edit.ssh_key.add', action_data={
863 'data': {'ssh_key': ssh_key_data, 'user': user_data}},
868 'data': {'ssh_key': ssh_key_data, 'user': user_data}},
864 user=self._rhodecode_user, )
869 user=self._rhodecode_user, )
865 Session().commit()
870 Session().commit()
866
871
867 # Trigger an event on change of keys.
872 # Trigger an event on change of keys.
868 trigger(SshKeyFileChangeEvent(), self.request.registry)
873 trigger(SshKeyFileChangeEvent(), self.request.registry)
869
874
870 h.flash(_("Ssh Key successfully created"), category='success')
875 h.flash(_("Ssh Key successfully created"), category='success')
871
876
872 except IntegrityError:
877 except IntegrityError:
873 log.exception("Exception during ssh key saving")
878 log.exception("Exception during ssh key saving")
874 err = 'Such key with fingerprint `{}` already exists, ' \
879 err = 'Such key with fingerprint `{}` already exists, ' \
875 'please use a different one'.format(fingerprint)
880 'please use a different one'.format(fingerprint)
876 h.flash(_('An error occurred during ssh key saving: {}').format(err),
881 h.flash(_('An error occurred during ssh key saving: {}').format(err),
877 category='error')
882 category='error')
878 except Exception as e:
883 except Exception as e:
879 log.exception("Exception during ssh key saving")
884 log.exception("Exception during ssh key saving")
880 h.flash(_('An error occurred during ssh key saving: {}').format(e),
885 h.flash(_('An error occurred during ssh key saving: {}').format(e),
881 category='error')
886 category='error')
882
887
883 return HTTPFound(
888 return HTTPFound(
884 h.route_path('edit_user_ssh_keys', user_id=user_id))
889 h.route_path('edit_user_ssh_keys', user_id=user_id))
885
890
886 @LoginRequired()
891 @LoginRequired()
887 @HasPermissionAllDecorator('hg.admin')
892 @HasPermissionAllDecorator('hg.admin')
888 @CSRFRequired()
893 @CSRFRequired()
889 @view_config(
894 @view_config(
890 route_name='edit_user_ssh_keys_delete', request_method='POST')
895 route_name='edit_user_ssh_keys_delete', request_method='POST')
891 def ssh_keys_delete(self):
896 def ssh_keys_delete(self):
892 _ = self.request.translate
897 _ = self.request.translate
893 c = self.load_default_context()
898 c = self.load_default_context()
894
899
895 user_id = self.db_user_id
900 user_id = self.db_user_id
896 c.user = self.db_user
901 c.user = self.db_user
897
902
898 user_data = c.user.get_api_data()
903 user_data = c.user.get_api_data()
899
904
900 del_ssh_key = self.request.POST.get('del_ssh_key')
905 del_ssh_key = self.request.POST.get('del_ssh_key')
901
906
902 if del_ssh_key:
907 if del_ssh_key:
903 ssh_key = UserSshKeys.get_or_404(del_ssh_key)
908 ssh_key = UserSshKeys.get_or_404(del_ssh_key)
904 ssh_key_data = ssh_key.get_api_data()
909 ssh_key_data = ssh_key.get_api_data()
905
910
906 SshKeyModel().delete(del_ssh_key, c.user.user_id)
911 SshKeyModel().delete(del_ssh_key, c.user.user_id)
907 audit_logger.store_web(
912 audit_logger.store_web(
908 'user.edit.ssh_key.delete', action_data={
913 'user.edit.ssh_key.delete', action_data={
909 'data': {'ssh_key': ssh_key_data, 'user': user_data}},
914 'data': {'ssh_key': ssh_key_data, 'user': user_data}},
910 user=self._rhodecode_user,)
915 user=self._rhodecode_user,)
911 Session().commit()
916 Session().commit()
912 # Trigger an event on change of keys.
917 # Trigger an event on change of keys.
913 trigger(SshKeyFileChangeEvent(), self.request.registry)
918 trigger(SshKeyFileChangeEvent(), self.request.registry)
914 h.flash(_("Ssh key successfully deleted"), category='success')
919 h.flash(_("Ssh key successfully deleted"), category='success')
915
920
916 return HTTPFound(h.route_path('edit_user_ssh_keys', user_id=user_id))
921 return HTTPFound(h.route_path('edit_user_ssh_keys', user_id=user_id))
917
922
918 @LoginRequired()
923 @LoginRequired()
919 @HasPermissionAllDecorator('hg.admin')
924 @HasPermissionAllDecorator('hg.admin')
920 @view_config(
925 @view_config(
921 route_name='edit_user_emails', request_method='GET',
926 route_name='edit_user_emails', request_method='GET',
922 renderer='rhodecode:templates/admin/users/user_edit.mako')
927 renderer='rhodecode:templates/admin/users/user_edit.mako')
923 def emails(self):
928 def emails(self):
924 _ = self.request.translate
929 _ = self.request.translate
925 c = self.load_default_context()
930 c = self.load_default_context()
926 c.user = self.db_user
931 c.user = self.db_user
927
932
928 c.active = 'emails'
933 c.active = 'emails'
929 c.user_email_map = UserEmailMap.query() \
934 c.user_email_map = UserEmailMap.query() \
930 .filter(UserEmailMap.user == c.user).all()
935 .filter(UserEmailMap.user == c.user).all()
931
936
932 return self._get_template_context(c)
937 return self._get_template_context(c)
933
938
934 @LoginRequired()
939 @LoginRequired()
935 @HasPermissionAllDecorator('hg.admin')
940 @HasPermissionAllDecorator('hg.admin')
936 @CSRFRequired()
941 @CSRFRequired()
937 @view_config(
942 @view_config(
938 route_name='edit_user_emails_add', request_method='POST')
943 route_name='edit_user_emails_add', request_method='POST')
939 def emails_add(self):
944 def emails_add(self):
940 _ = self.request.translate
945 _ = self.request.translate
941 c = self.load_default_context()
946 c = self.load_default_context()
942
947
943 user_id = self.db_user_id
948 user_id = self.db_user_id
944 c.user = self.db_user
949 c.user = self.db_user
945
950
946 email = self.request.POST.get('new_email')
951 email = self.request.POST.get('new_email')
947 user_data = c.user.get_api_data()
952 user_data = c.user.get_api_data()
948 try:
953 try:
949
954
950 form = UserExtraEmailForm(self.request.translate)()
955 form = UserExtraEmailForm(self.request.translate)()
951 data = form.to_python({'email': email})
956 data = form.to_python({'email': email})
952 email = data['email']
957 email = data['email']
953
958
954 UserModel().add_extra_email(c.user.user_id, email)
959 UserModel().add_extra_email(c.user.user_id, email)
955 audit_logger.store_web(
960 audit_logger.store_web(
956 'user.edit.email.add',
961 'user.edit.email.add',
957 action_data={'email': email, 'user': user_data},
962 action_data={'email': email, 'user': user_data},
958 user=self._rhodecode_user)
963 user=self._rhodecode_user)
959 Session().commit()
964 Session().commit()
960 h.flash(_("Added new email address `%s` for user account") % email,
965 h.flash(_("Added new email address `%s` for user account") % email,
961 category='success')
966 category='success')
962 except formencode.Invalid as error:
967 except formencode.Invalid as error:
963 h.flash(h.escape(error.error_dict['email']), category='error')
968 h.flash(h.escape(error.error_dict['email']), category='error')
964 except IntegrityError:
969 except IntegrityError:
965 log.warning("Email %s already exists", email)
970 log.warning("Email %s already exists", email)
966 h.flash(_('Email `{}` is already registered for another user.').format(email),
971 h.flash(_('Email `{}` is already registered for another user.').format(email),
967 category='error')
972 category='error')
968 except Exception:
973 except Exception:
969 log.exception("Exception during email saving")
974 log.exception("Exception during email saving")
970 h.flash(_('An error occurred during email saving'),
975 h.flash(_('An error occurred during email saving'),
971 category='error')
976 category='error')
972 raise HTTPFound(h.route_path('edit_user_emails', user_id=user_id))
977 raise HTTPFound(h.route_path('edit_user_emails', user_id=user_id))
973
978
974 @LoginRequired()
979 @LoginRequired()
975 @HasPermissionAllDecorator('hg.admin')
980 @HasPermissionAllDecorator('hg.admin')
976 @CSRFRequired()
981 @CSRFRequired()
977 @view_config(
982 @view_config(
978 route_name='edit_user_emails_delete', request_method='POST')
983 route_name='edit_user_emails_delete', request_method='POST')
979 def emails_delete(self):
984 def emails_delete(self):
980 _ = self.request.translate
985 _ = self.request.translate
981 c = self.load_default_context()
986 c = self.load_default_context()
982
987
983 user_id = self.db_user_id
988 user_id = self.db_user_id
984 c.user = self.db_user
989 c.user = self.db_user
985
990
986 email_id = self.request.POST.get('del_email_id')
991 email_id = self.request.POST.get('del_email_id')
987 user_model = UserModel()
992 user_model = UserModel()
988
993
989 email = UserEmailMap.query().get(email_id).email
994 email = UserEmailMap.query().get(email_id).email
990 user_data = c.user.get_api_data()
995 user_data = c.user.get_api_data()
991 user_model.delete_extra_email(c.user.user_id, email_id)
996 user_model.delete_extra_email(c.user.user_id, email_id)
992 audit_logger.store_web(
997 audit_logger.store_web(
993 'user.edit.email.delete',
998 'user.edit.email.delete',
994 action_data={'email': email, 'user': user_data},
999 action_data={'email': email, 'user': user_data},
995 user=self._rhodecode_user)
1000 user=self._rhodecode_user)
996 Session().commit()
1001 Session().commit()
997 h.flash(_("Removed email address from user account"),
1002 h.flash(_("Removed email address from user account"),
998 category='success')
1003 category='success')
999 raise HTTPFound(h.route_path('edit_user_emails', user_id=user_id))
1004 raise HTTPFound(h.route_path('edit_user_emails', user_id=user_id))
1000
1005
1001 @LoginRequired()
1006 @LoginRequired()
1002 @HasPermissionAllDecorator('hg.admin')
1007 @HasPermissionAllDecorator('hg.admin')
1003 @view_config(
1008 @view_config(
1004 route_name='edit_user_ips', request_method='GET',
1009 route_name='edit_user_ips', request_method='GET',
1005 renderer='rhodecode:templates/admin/users/user_edit.mako')
1010 renderer='rhodecode:templates/admin/users/user_edit.mako')
1006 def ips(self):
1011 def ips(self):
1007 _ = self.request.translate
1012 _ = self.request.translate
1008 c = self.load_default_context()
1013 c = self.load_default_context()
1009 c.user = self.db_user
1014 c.user = self.db_user
1010
1015
1011 c.active = 'ips'
1016 c.active = 'ips'
1012 c.user_ip_map = UserIpMap.query() \
1017 c.user_ip_map = UserIpMap.query() \
1013 .filter(UserIpMap.user == c.user).all()
1018 .filter(UserIpMap.user == c.user).all()
1014
1019
1015 c.inherit_default_ips = c.user.inherit_default_permissions
1020 c.inherit_default_ips = c.user.inherit_default_permissions
1016 c.default_user_ip_map = UserIpMap.query() \
1021 c.default_user_ip_map = UserIpMap.query() \
1017 .filter(UserIpMap.user == User.get_default_user()).all()
1022 .filter(UserIpMap.user == User.get_default_user()).all()
1018
1023
1019 return self._get_template_context(c)
1024 return self._get_template_context(c)
1020
1025
1021 @LoginRequired()
1026 @LoginRequired()
1022 @HasPermissionAllDecorator('hg.admin')
1027 @HasPermissionAllDecorator('hg.admin')
1023 @CSRFRequired()
1028 @CSRFRequired()
1024 @view_config(
1029 @view_config(
1025 route_name='edit_user_ips_add', request_method='POST')
1030 route_name='edit_user_ips_add', request_method='POST')
1026 # NOTE(marcink): this view is allowed for default users, as we can
1031 # NOTE(marcink): this view is allowed for default users, as we can
1027 # edit their IP white list
1032 # edit their IP white list
1028 def ips_add(self):
1033 def ips_add(self):
1029 _ = self.request.translate
1034 _ = self.request.translate
1030 c = self.load_default_context()
1035 c = self.load_default_context()
1031
1036
1032 user_id = self.db_user_id
1037 user_id = self.db_user_id
1033 c.user = self.db_user
1038 c.user = self.db_user
1034
1039
1035 user_model = UserModel()
1040 user_model = UserModel()
1036 desc = self.request.POST.get('description')
1041 desc = self.request.POST.get('description')
1037 try:
1042 try:
1038 ip_list = user_model.parse_ip_range(
1043 ip_list = user_model.parse_ip_range(
1039 self.request.POST.get('new_ip'))
1044 self.request.POST.get('new_ip'))
1040 except Exception as e:
1045 except Exception as e:
1041 ip_list = []
1046 ip_list = []
1042 log.exception("Exception during ip saving")
1047 log.exception("Exception during ip saving")
1043 h.flash(_('An error occurred during ip saving:%s' % (e,)),
1048 h.flash(_('An error occurred during ip saving:%s' % (e,)),
1044 category='error')
1049 category='error')
1045 added = []
1050 added = []
1046 user_data = c.user.get_api_data()
1051 user_data = c.user.get_api_data()
1047 for ip in ip_list:
1052 for ip in ip_list:
1048 try:
1053 try:
1049 form = UserExtraIpForm(self.request.translate)()
1054 form = UserExtraIpForm(self.request.translate)()
1050 data = form.to_python({'ip': ip})
1055 data = form.to_python({'ip': ip})
1051 ip = data['ip']
1056 ip = data['ip']
1052
1057
1053 user_model.add_extra_ip(c.user.user_id, ip, desc)
1058 user_model.add_extra_ip(c.user.user_id, ip, desc)
1054 audit_logger.store_web(
1059 audit_logger.store_web(
1055 'user.edit.ip.add',
1060 'user.edit.ip.add',
1056 action_data={'ip': ip, 'user': user_data},
1061 action_data={'ip': ip, 'user': user_data},
1057 user=self._rhodecode_user)
1062 user=self._rhodecode_user)
1058 Session().commit()
1063 Session().commit()
1059 added.append(ip)
1064 added.append(ip)
1060 except formencode.Invalid as error:
1065 except formencode.Invalid as error:
1061 msg = error.error_dict['ip']
1066 msg = error.error_dict['ip']
1062 h.flash(msg, category='error')
1067 h.flash(msg, category='error')
1063 except Exception:
1068 except Exception:
1064 log.exception("Exception during ip saving")
1069 log.exception("Exception during ip saving")
1065 h.flash(_('An error occurred during ip saving'),
1070 h.flash(_('An error occurred during ip saving'),
1066 category='error')
1071 category='error')
1067 if added:
1072 if added:
1068 h.flash(
1073 h.flash(
1069 _("Added ips %s to user whitelist") % (', '.join(ip_list), ),
1074 _("Added ips %s to user whitelist") % (', '.join(ip_list), ),
1070 category='success')
1075 category='success')
1071 if 'default_user' in self.request.POST:
1076 if 'default_user' in self.request.POST:
1072 # case for editing global IP list we do it for 'DEFAULT' user
1077 # case for editing global IP list we do it for 'DEFAULT' user
1073 raise HTTPFound(h.route_path('admin_permissions_ips'))
1078 raise HTTPFound(h.route_path('admin_permissions_ips'))
1074 raise HTTPFound(h.route_path('edit_user_ips', user_id=user_id))
1079 raise HTTPFound(h.route_path('edit_user_ips', user_id=user_id))
1075
1080
1076 @LoginRequired()
1081 @LoginRequired()
1077 @HasPermissionAllDecorator('hg.admin')
1082 @HasPermissionAllDecorator('hg.admin')
1078 @CSRFRequired()
1083 @CSRFRequired()
1079 @view_config(
1084 @view_config(
1080 route_name='edit_user_ips_delete', request_method='POST')
1085 route_name='edit_user_ips_delete', request_method='POST')
1081 # NOTE(marcink): this view is allowed for default users, as we can
1086 # NOTE(marcink): this view is allowed for default users, as we can
1082 # edit their IP white list
1087 # edit their IP white list
1083 def ips_delete(self):
1088 def ips_delete(self):
1084 _ = self.request.translate
1089 _ = self.request.translate
1085 c = self.load_default_context()
1090 c = self.load_default_context()
1086
1091
1087 user_id = self.db_user_id
1092 user_id = self.db_user_id
1088 c.user = self.db_user
1093 c.user = self.db_user
1089
1094
1090 ip_id = self.request.POST.get('del_ip_id')
1095 ip_id = self.request.POST.get('del_ip_id')
1091 user_model = UserModel()
1096 user_model = UserModel()
1092 user_data = c.user.get_api_data()
1097 user_data = c.user.get_api_data()
1093 ip = UserIpMap.query().get(ip_id).ip_addr
1098 ip = UserIpMap.query().get(ip_id).ip_addr
1094 user_model.delete_extra_ip(c.user.user_id, ip_id)
1099 user_model.delete_extra_ip(c.user.user_id, ip_id)
1095 audit_logger.store_web(
1100 audit_logger.store_web(
1096 'user.edit.ip.delete', action_data={'ip': ip, 'user': user_data},
1101 'user.edit.ip.delete', action_data={'ip': ip, 'user': user_data},
1097 user=self._rhodecode_user)
1102 user=self._rhodecode_user)
1098 Session().commit()
1103 Session().commit()
1099 h.flash(_("Removed ip address from user whitelist"), category='success')
1104 h.flash(_("Removed ip address from user whitelist"), category='success')
1100
1105
1101 if 'default_user' in self.request.POST:
1106 if 'default_user' in self.request.POST:
1102 # case for editing global IP list we do it for 'DEFAULT' user
1107 # case for editing global IP list we do it for 'DEFAULT' user
1103 raise HTTPFound(h.route_path('admin_permissions_ips'))
1108 raise HTTPFound(h.route_path('admin_permissions_ips'))
1104 raise HTTPFound(h.route_path('edit_user_ips', user_id=user_id))
1109 raise HTTPFound(h.route_path('edit_user_ips', user_id=user_id))
1105
1110
1106 @LoginRequired()
1111 @LoginRequired()
1107 @HasPermissionAllDecorator('hg.admin')
1112 @HasPermissionAllDecorator('hg.admin')
1108 @view_config(
1113 @view_config(
1109 route_name='edit_user_groups_management', request_method='GET',
1114 route_name='edit_user_groups_management', request_method='GET',
1110 renderer='rhodecode:templates/admin/users/user_edit.mako')
1115 renderer='rhodecode:templates/admin/users/user_edit.mako')
1111 def groups_management(self):
1116 def groups_management(self):
1112 c = self.load_default_context()
1117 c = self.load_default_context()
1113 c.user = self.db_user
1118 c.user = self.db_user
1114 c.data = c.user.group_member
1119 c.data = c.user.group_member
1115
1120
1116 groups = [UserGroupModel.get_user_groups_as_dict(group.users_group)
1121 groups = [UserGroupModel.get_user_groups_as_dict(group.users_group)
1117 for group in c.user.group_member]
1122 for group in c.user.group_member]
1118 c.groups = json.dumps(groups)
1123 c.groups = json.dumps(groups)
1119 c.active = 'groups'
1124 c.active = 'groups'
1120
1125
1121 return self._get_template_context(c)
1126 return self._get_template_context(c)
1122
1127
1123 @LoginRequired()
1128 @LoginRequired()
1124 @HasPermissionAllDecorator('hg.admin')
1129 @HasPermissionAllDecorator('hg.admin')
1125 @CSRFRequired()
1130 @CSRFRequired()
1126 @view_config(
1131 @view_config(
1127 route_name='edit_user_groups_management_updates', request_method='POST')
1132 route_name='edit_user_groups_management_updates', request_method='POST')
1128 def groups_management_updates(self):
1133 def groups_management_updates(self):
1129 _ = self.request.translate
1134 _ = self.request.translate
1130 c = self.load_default_context()
1135 c = self.load_default_context()
1131
1136
1132 user_id = self.db_user_id
1137 user_id = self.db_user_id
1133 c.user = self.db_user
1138 c.user = self.db_user
1134
1139
1135 user_groups = set(self.request.POST.getall('users_group_id'))
1140 user_groups = set(self.request.POST.getall('users_group_id'))
1136 user_groups_objects = []
1141 user_groups_objects = []
1137
1142
1138 for ugid in user_groups:
1143 for ugid in user_groups:
1139 user_groups_objects.append(
1144 user_groups_objects.append(
1140 UserGroupModel().get_group(safe_int(ugid)))
1145 UserGroupModel().get_group(safe_int(ugid)))
1141 user_group_model = UserGroupModel()
1146 user_group_model = UserGroupModel()
1142 added_to_groups, removed_from_groups = \
1147 added_to_groups, removed_from_groups = \
1143 user_group_model.change_groups(c.user, user_groups_objects)
1148 user_group_model.change_groups(c.user, user_groups_objects)
1144
1149
1145 user_data = c.user.get_api_data()
1150 user_data = c.user.get_api_data()
1146 for user_group_id in added_to_groups:
1151 for user_group_id in added_to_groups:
1147 user_group = UserGroup.get(user_group_id)
1152 user_group = UserGroup.get(user_group_id)
1148 old_values = user_group.get_api_data()
1153 old_values = user_group.get_api_data()
1149 audit_logger.store_web(
1154 audit_logger.store_web(
1150 'user_group.edit.member.add',
1155 'user_group.edit.member.add',
1151 action_data={'user': user_data, 'old_data': old_values},
1156 action_data={'user': user_data, 'old_data': old_values},
1152 user=self._rhodecode_user)
1157 user=self._rhodecode_user)
1153
1158
1154 for user_group_id in removed_from_groups:
1159 for user_group_id in removed_from_groups:
1155 user_group = UserGroup.get(user_group_id)
1160 user_group = UserGroup.get(user_group_id)
1156 old_values = user_group.get_api_data()
1161 old_values = user_group.get_api_data()
1157 audit_logger.store_web(
1162 audit_logger.store_web(
1158 'user_group.edit.member.delete',
1163 'user_group.edit.member.delete',
1159 action_data={'user': user_data, 'old_data': old_values},
1164 action_data={'user': user_data, 'old_data': old_values},
1160 user=self._rhodecode_user)
1165 user=self._rhodecode_user)
1161
1166
1162 Session().commit()
1167 Session().commit()
1163 c.active = 'user_groups_management'
1168 c.active = 'user_groups_management'
1164 h.flash(_("Groups successfully changed"), category='success')
1169 h.flash(_("Groups successfully changed"), category='success')
1165
1170
1166 return HTTPFound(h.route_path(
1171 return HTTPFound(h.route_path(
1167 'edit_user_groups_management', user_id=user_id))
1172 'edit_user_groups_management', user_id=user_id))
1168
1173
1169 @LoginRequired()
1174 @LoginRequired()
1170 @HasPermissionAllDecorator('hg.admin')
1175 @HasPermissionAllDecorator('hg.admin')
1171 @view_config(
1176 @view_config(
1172 route_name='edit_user_audit_logs', request_method='GET',
1177 route_name='edit_user_audit_logs', request_method='GET',
1173 renderer='rhodecode:templates/admin/users/user_edit.mako')
1178 renderer='rhodecode:templates/admin/users/user_edit.mako')
1174 def user_audit_logs(self):
1179 def user_audit_logs(self):
1175 _ = self.request.translate
1180 _ = self.request.translate
1176 c = self.load_default_context()
1181 c = self.load_default_context()
1177 c.user = self.db_user
1182 c.user = self.db_user
1178
1183
1179 c.active = 'audit'
1184 c.active = 'audit'
1180
1185
1181 p = safe_int(self.request.GET.get('page', 1), 1)
1186 p = safe_int(self.request.GET.get('page', 1), 1)
1182
1187
1183 filter_term = self.request.GET.get('filter')
1188 filter_term = self.request.GET.get('filter')
1184 user_log = UserModel().get_user_log(c.user, filter_term)
1189 user_log = UserModel().get_user_log(c.user, filter_term)
1185
1190
1186 def url_generator(**kw):
1191 def url_generator(**kw):
1187 if filter_term:
1192 if filter_term:
1188 kw['filter'] = filter_term
1193 kw['filter'] = filter_term
1189 return self.request.current_route_path(_query=kw)
1194 return self.request.current_route_path(_query=kw)
1190
1195
1191 c.audit_logs = h.Page(
1196 c.audit_logs = h.Page(
1192 user_log, page=p, items_per_page=10, url=url_generator)
1197 user_log, page=p, items_per_page=10, url=url_generator)
1193 c.filter_term = filter_term
1198 c.filter_term = filter_term
1194 return self._get_template_context(c)
1199 return self._get_template_context(c)
1195
1200
1196 @LoginRequired()
1201 @LoginRequired()
1197 @HasPermissionAllDecorator('hg.admin')
1202 @HasPermissionAllDecorator('hg.admin')
1198 @view_config(
1203 @view_config(
1199 route_name='edit_user_perms_summary', request_method='GET',
1204 route_name='edit_user_perms_summary', request_method='GET',
1200 renderer='rhodecode:templates/admin/users/user_edit.mako')
1205 renderer='rhodecode:templates/admin/users/user_edit.mako')
1201 def user_perms_summary(self):
1206 def user_perms_summary(self):
1202 _ = self.request.translate
1207 _ = self.request.translate
1203 c = self.load_default_context()
1208 c = self.load_default_context()
1204 c.user = self.db_user
1209 c.user = self.db_user
1205
1210
1206 c.active = 'perms_summary'
1211 c.active = 'perms_summary'
1207 c.perm_user = c.user.AuthUser(ip_addr=self.request.remote_addr)
1212 c.perm_user = c.user.AuthUser(ip_addr=self.request.remote_addr)
1208
1213
1209 return self._get_template_context(c)
1214 return self._get_template_context(c)
1210
1215
1211 @LoginRequired()
1216 @LoginRequired()
1212 @HasPermissionAllDecorator('hg.admin')
1217 @HasPermissionAllDecorator('hg.admin')
1213 @view_config(
1218 @view_config(
1214 route_name='edit_user_perms_summary_json', request_method='GET',
1219 route_name='edit_user_perms_summary_json', request_method='GET',
1215 renderer='json_ext')
1220 renderer='json_ext')
1216 def user_perms_summary_json(self):
1221 def user_perms_summary_json(self):
1217 self.load_default_context()
1222 self.load_default_context()
1218 perm_user = self.db_user.AuthUser(ip_addr=self.request.remote_addr)
1223 perm_user = self.db_user.AuthUser(ip_addr=self.request.remote_addr)
1219
1224
1220 return perm_user.permissions
1225 return perm_user.permissions
1221
1226
1222 @LoginRequired()
1227 @LoginRequired()
1223 @HasPermissionAllDecorator('hg.admin')
1228 @HasPermissionAllDecorator('hg.admin')
1224 @view_config(
1229 @view_config(
1225 route_name='edit_user_caches', request_method='GET',
1230 route_name='edit_user_caches', request_method='GET',
1226 renderer='rhodecode:templates/admin/users/user_edit.mako')
1231 renderer='rhodecode:templates/admin/users/user_edit.mako')
1227 def user_caches(self):
1232 def user_caches(self):
1228 _ = self.request.translate
1233 _ = self.request.translate
1229 c = self.load_default_context()
1234 c = self.load_default_context()
1230 c.user = self.db_user
1235 c.user = self.db_user
1231
1236
1232 c.active = 'caches'
1237 c.active = 'caches'
1233 c.perm_user = c.user.AuthUser(ip_addr=self.request.remote_addr)
1238 c.perm_user = c.user.AuthUser(ip_addr=self.request.remote_addr)
1234
1239
1235 cache_namespace_uid = 'cache_user_auth.{}'.format(self.db_user.user_id)
1240 cache_namespace_uid = 'cache_user_auth.{}'.format(self.db_user.user_id)
1236 c.region = rc_cache.get_or_create_region('cache_perms', cache_namespace_uid)
1241 c.region = rc_cache.get_or_create_region('cache_perms', cache_namespace_uid)
1237 c.backend = c.region.backend
1242 c.backend = c.region.backend
1238 c.user_keys = sorted(c.region.backend.list_keys(prefix=cache_namespace_uid))
1243 c.user_keys = sorted(c.region.backend.list_keys(prefix=cache_namespace_uid))
1239
1244
1240 return self._get_template_context(c)
1245 return self._get_template_context(c)
1241
1246
1242 @LoginRequired()
1247 @LoginRequired()
1243 @HasPermissionAllDecorator('hg.admin')
1248 @HasPermissionAllDecorator('hg.admin')
1244 @CSRFRequired()
1249 @CSRFRequired()
1245 @view_config(
1250 @view_config(
1246 route_name='edit_user_caches_update', request_method='POST')
1251 route_name='edit_user_caches_update', request_method='POST')
1247 def user_caches_update(self):
1252 def user_caches_update(self):
1248 _ = self.request.translate
1253 _ = self.request.translate
1249 c = self.load_default_context()
1254 c = self.load_default_context()
1250 c.user = self.db_user
1255 c.user = self.db_user
1251
1256
1252 c.active = 'caches'
1257 c.active = 'caches'
1253 c.perm_user = c.user.AuthUser(ip_addr=self.request.remote_addr)
1258 c.perm_user = c.user.AuthUser(ip_addr=self.request.remote_addr)
1254
1259
1255 cache_namespace_uid = 'cache_user_auth.{}'.format(self.db_user.user_id)
1260 cache_namespace_uid = 'cache_user_auth.{}'.format(self.db_user.user_id)
1256 del_keys = rc_cache.clear_cache_namespace('cache_perms', cache_namespace_uid)
1261 del_keys = rc_cache.clear_cache_namespace('cache_perms', cache_namespace_uid)
1257
1262
1258 h.flash(_("Deleted {} cache keys").format(del_keys), category='success')
1263 h.flash(_("Deleted {} cache keys").format(del_keys), category='success')
1259
1264
1260 return HTTPFound(h.route_path(
1265 return HTTPFound(h.route_path(
1261 'edit_user_caches', user_id=c.user.user_id))
1266 'edit_user_caches', user_id=c.user.user_id))
@@ -1,189 +1,193 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2011-2019 RhodeCode GmbH
3 # Copyright (C) 2011-2019 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 import logging
21 import logging
22 import deform
22 import deform
23
23
24 from pyramid.view import view_config
24 from pyramid.view import view_config
25 from pyramid.httpexceptions import HTTPFound
25 from pyramid.httpexceptions import HTTPFound
26
26
27 from rhodecode import events
27 from rhodecode import events
28 from rhodecode.apps._base import RepoGroupAppView
28 from rhodecode.apps._base import RepoGroupAppView
29 from rhodecode.forms import RcForm
29 from rhodecode.forms import RcForm
30 from rhodecode.lib import helpers as h
30 from rhodecode.lib import helpers as h
31 from rhodecode.lib import audit_logger
31 from rhodecode.lib import audit_logger
32 from rhodecode.lib.auth import (
32 from rhodecode.lib.auth import (
33 LoginRequired, HasPermissionAll,
33 LoginRequired, HasPermissionAll,
34 HasRepoGroupPermissionAny, HasRepoGroupPermissionAnyDecorator, CSRFRequired)
34 HasRepoGroupPermissionAny, HasRepoGroupPermissionAnyDecorator, CSRFRequired)
35 from rhodecode.model.db import Session, RepoGroup, User
35 from rhodecode.model.db import Session, RepoGroup, User
36 from rhodecode.model.scm import RepoGroupList
36 from rhodecode.model.scm import RepoGroupList
37 from rhodecode.model.repo_group import RepoGroupModel
37 from rhodecode.model.repo_group import RepoGroupModel
38 from rhodecode.model.validation_schema.schemas import repo_group_schema
38 from rhodecode.model.validation_schema.schemas import repo_group_schema
39
39
40 log = logging.getLogger(__name__)
40 log = logging.getLogger(__name__)
41
41
42
42
43 class RepoGroupSettingsView(RepoGroupAppView):
43 class RepoGroupSettingsView(RepoGroupAppView):
44 def load_default_context(self):
44 def load_default_context(self):
45 c = self._get_local_tmpl_context()
45 c = self._get_local_tmpl_context()
46 c.repo_group = self.db_repo_group
46 c.repo_group = self.db_repo_group
47 no_parrent = not c.repo_group.parent_group
47 no_parrent = not c.repo_group.parent_group
48 can_create_in_root = self._can_create_repo_group()
48 can_create_in_root = self._can_create_repo_group()
49
49
50 show_root_location = False
50 show_root_location = False
51 if no_parrent or can_create_in_root:
51 if no_parrent or can_create_in_root:
52 # we're global admin, we're ok and we can create TOP level groups
52 # we're global admin, we're ok and we can create TOP level groups
53 # or in case this group is already at top-level we also allow
53 # or in case this group is already at top-level we also allow
54 # creation in root
54 # creation in root
55 show_root_location = True
55 show_root_location = True
56
56
57 acl_groups = RepoGroupList(
57 acl_groups = RepoGroupList(
58 RepoGroup.query().all(),
58 RepoGroup.query().all(),
59 perm_set=['group.admin'])
59 perm_set=['group.admin'])
60 c.repo_groups = RepoGroup.groups_choices(
60 c.repo_groups = RepoGroup.groups_choices(
61 groups=acl_groups,
61 groups=acl_groups,
62 show_empty_group=show_root_location)
62 show_empty_group=show_root_location)
63 # filter out current repo group
63 # filter out current repo group
64 exclude_group_ids = [c.repo_group.group_id]
64 exclude_group_ids = [c.repo_group.group_id]
65 c.repo_groups = filter(lambda x: x[0] not in exclude_group_ids,
65 c.repo_groups = filter(lambda x: x[0] not in exclude_group_ids,
66 c.repo_groups)
66 c.repo_groups)
67 c.repo_groups_choices = map(lambda k: k[0], c.repo_groups)
67 c.repo_groups_choices = map(lambda k: k[0], c.repo_groups)
68
68
69 parent_group = c.repo_group.parent_group
69 parent_group = c.repo_group.parent_group
70
70
71 add_parent_group = (parent_group and (
71 add_parent_group = (parent_group and (
72 parent_group.group_id not in c.repo_groups_choices))
72 parent_group.group_id not in c.repo_groups_choices))
73 if add_parent_group:
73 if add_parent_group:
74 c.repo_groups_choices.append(parent_group.group_id)
74 c.repo_groups_choices.append(parent_group.group_id)
75 c.repo_groups.append(RepoGroup._generate_choice(parent_group))
75 c.repo_groups.append(RepoGroup._generate_choice(parent_group))
76 return c
76 return c
77
77
78 def _can_create_repo_group(self, parent_group_id=None):
78 def _can_create_repo_group(self, parent_group_id=None):
79 is_admin = HasPermissionAll('hg.admin')('group create controller')
79 is_admin = HasPermissionAll('hg.admin')('group create controller')
80 create_repo_group = HasPermissionAll(
80 create_repo_group = HasPermissionAll(
81 'hg.repogroup.create.true')('group create controller')
81 'hg.repogroup.create.true')('group create controller')
82 if is_admin or (create_repo_group and not parent_group_id):
82 if is_admin or (create_repo_group and not parent_group_id):
83 # we're global admin, or we have global repo group create
83 # we're global admin, or we have global repo group create
84 # permission
84 # permission
85 # we're ok and we can create TOP level groups
85 # we're ok and we can create TOP level groups
86 return True
86 return True
87 elif parent_group_id:
87 elif parent_group_id:
88 # we check the permission if we can write to parent group
88 # we check the permission if we can write to parent group
89 group = RepoGroup.get(parent_group_id)
89 group = RepoGroup.get(parent_group_id)
90 group_name = group.group_name if group else None
90 group_name = group.group_name if group else None
91 if HasRepoGroupPermissionAny('group.admin')(
91 if HasRepoGroupPermissionAny('group.admin')(
92 group_name, 'check if user is an admin of group'):
92 group_name, 'check if user is an admin of group'):
93 # we're an admin of passed in group, we're ok.
93 # we're an admin of passed in group, we're ok.
94 return True
94 return True
95 else:
95 else:
96 return False
96 return False
97 return False
97 return False
98
98
99 def _get_schema(self, c, old_values=None):
99 def _get_schema(self, c, old_values=None):
100 return repo_group_schema.RepoGroupSettingsSchema().bind(
100 return repo_group_schema.RepoGroupSettingsSchema().bind(
101 repo_group_repo_group_options=c.repo_groups_choices,
101 repo_group_repo_group_options=c.repo_groups_choices,
102 repo_group_repo_group_items=c.repo_groups,
102 repo_group_repo_group_items=c.repo_groups,
103
103
104 # user caller
104 # user caller
105 user=self._rhodecode_user,
105 user=self._rhodecode_user,
106 old_values=old_values
106 old_values=old_values
107 )
107 )
108
108
109 @LoginRequired()
109 @LoginRequired()
110 @HasRepoGroupPermissionAnyDecorator('group.admin')
110 @HasRepoGroupPermissionAnyDecorator('group.admin')
111 @view_config(
111 @view_config(
112 route_name='edit_repo_group', request_method='GET',
112 route_name='edit_repo_group', request_method='GET',
113 renderer='rhodecode:templates/admin/repo_groups/repo_group_edit.mako')
113 renderer='rhodecode:templates/admin/repo_groups/repo_group_edit.mako')
114 def edit_settings(self):
114 def edit_settings(self):
115 c = self.load_default_context()
115 c = self.load_default_context()
116 c.active = 'settings'
116 c.active = 'settings'
117
117
118 defaults = RepoGroupModel()._get_defaults(self.db_repo_group_name)
118 defaults = RepoGroupModel()._get_defaults(self.db_repo_group_name)
119 defaults['repo_group_owner'] = defaults['user']
119 defaults['repo_group_owner'] = defaults['user']
120
120
121 schema = self._get_schema(c)
121 schema = self._get_schema(c)
122 c.form = RcForm(schema, appstruct=defaults)
122 c.form = RcForm(schema, appstruct=defaults)
123 return self._get_template_context(c)
123 return self._get_template_context(c)
124
124
125 @LoginRequired()
125 @LoginRequired()
126 @HasRepoGroupPermissionAnyDecorator('group.admin')
126 @HasRepoGroupPermissionAnyDecorator('group.admin')
127 @CSRFRequired()
127 @CSRFRequired()
128 @view_config(
128 @view_config(
129 route_name='edit_repo_group', request_method='POST',
129 route_name='edit_repo_group', request_method='POST',
130 renderer='rhodecode:templates/admin/repo_groups/repo_group_edit.mako')
130 renderer='rhodecode:templates/admin/repo_groups/repo_group_edit.mako')
131 def edit_settings_update(self):
131 def edit_settings_update(self):
132 _ = self.request.translate
132 _ = self.request.translate
133 c = self.load_default_context()
133 c = self.load_default_context()
134 c.active = 'settings'
134 c.active = 'settings'
135
135
136 old_repo_group_name = self.db_repo_group_name
136 old_repo_group_name = self.db_repo_group_name
137 new_repo_group_name = old_repo_group_name
137 new_repo_group_name = old_repo_group_name
138
138
139 old_values = RepoGroupModel()._get_defaults(self.db_repo_group_name)
139 old_values = RepoGroupModel()._get_defaults(self.db_repo_group_name)
140 schema = self._get_schema(c, old_values=old_values)
140 schema = self._get_schema(c, old_values=old_values)
141
141
142 c.form = RcForm(schema)
142 c.form = RcForm(schema)
143 pstruct = self.request.POST.items()
143 pstruct = self.request.POST.items()
144
144
145 try:
145 try:
146 schema_data = c.form.validate(pstruct)
146 schema_data = c.form.validate(pstruct)
147 except deform.ValidationFailure as err_form:
147 except deform.ValidationFailure as err_form:
148 return self._get_template_context(c)
148 return self._get_template_context(c)
149
149
150 # data is now VALID, proceed with updates
150 # data is now VALID, proceed with updates
151 # save validated data back into the updates dict
151 # save validated data back into the updates dict
152 validated_updates = dict(
152 validated_updates = dict(
153 group_name=schema_data['repo_group']['repo_group_name_without_group'],
153 group_name=schema_data['repo_group']['repo_group_name_without_group'],
154 group_parent_id=schema_data['repo_group']['repo_group_id'],
154 group_parent_id=schema_data['repo_group']['repo_group_id'],
155 user=schema_data['repo_group_owner'],
155 user=schema_data['repo_group_owner'],
156 group_description=schema_data['repo_group_description'],
156 group_description=schema_data['repo_group_description'],
157 enable_locking=schema_data['repo_group_enable_locking'],
157 enable_locking=schema_data['repo_group_enable_locking'],
158 )
158 )
159
159
160 try:
160 try:
161 RepoGroupModel().update(self.db_repo_group, validated_updates)
161 RepoGroupModel().update(self.db_repo_group, validated_updates)
162
162
163 audit_logger.store_web(
163 audit_logger.store_web(
164 'repo_group.edit', action_data={'old_data': old_values},
164 'repo_group.edit', action_data={'old_data': old_values},
165 user=c.rhodecode_user)
165 user=c.rhodecode_user)
166
166
167 Session().commit()
167 Session().commit()
168
168
169 # use the new full name for redirect once we know we updated
169 # use the new full name for redirect once we know we updated
170 # the name on filesystem and in DB
170 # the name on filesystem and in DB
171 new_repo_group_name = schema_data['repo_group']['repo_group_name_with_group']
171 new_repo_group_name = schema_data['repo_group']['repo_group_name_with_group']
172
172
173 h.flash(_('Repository Group `{}` updated successfully').format(
173 h.flash(_('Repository Group `{}` updated successfully').format(
174 old_repo_group_name), category='success')
174 old_repo_group_name), category='success')
175
175
176 except Exception:
176 except Exception:
177 log.exception("Exception during update or repository group")
177 log.exception("Exception during update or repository group")
178 h.flash(_('Error occurred during update of repository group %s')
178 h.flash(_('Error occurred during update of repository group %s')
179 % old_repo_group_name, category='error')
179 % old_repo_group_name, category='error')
180
180
181 name_changed = old_repo_group_name != new_repo_group_name
181 name_changed = old_repo_group_name != new_repo_group_name
182 if name_changed:
182 if name_changed:
183 current_perms = self.db_repo_group.permissions(expand_from_user_groups=True)
184 affected_user_ids = [perm['user_id'] for perm in current_perms]
185
186 # NOTE(marcink): also add owner maybe it has changed
183 owner = User.get_by_username(schema_data['repo_group_owner'])
187 owner = User.get_by_username(schema_data['repo_group_owner'])
184 owner_id = owner.user_id if owner else self._rhodecode_user.user_id
188 owner_id = owner.user_id if owner else self._rhodecode_user.user_id
185 events.trigger(events.UserPermissionsChange([
189 affected_user_ids.extend([self._rhodecode_user.user_id, owner_id])
186 self._rhodecode_user.user_id, owner_id]))
190 events.trigger(events.UserPermissionsChange(affected_user_ids))
187
191
188 raise HTTPFound(
192 raise HTTPFound(
189 h.route_path('edit_repo_group', repo_group_name=new_repo_group_name))
193 h.route_path('edit_repo_group', repo_group_name=new_repo_group_name))
@@ -1,263 +1,270 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2011-2019 RhodeCode GmbH
3 # Copyright (C) 2011-2019 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 import logging
21 import logging
22 import datetime
22 import datetime
23 import formencode
23 import formencode
24 import formencode.htmlfill
24 import formencode.htmlfill
25
25
26 from pyramid.httpexceptions import HTTPFound
26 from pyramid.httpexceptions import HTTPFound
27 from pyramid.view import view_config
27 from pyramid.view import view_config
28 from pyramid.renderers import render
28 from pyramid.renderers import render
29 from pyramid.response import Response
29 from pyramid.response import Response
30
30
31 from rhodecode import events
31 from rhodecode import events
32 from rhodecode.apps._base import RepoAppView, DataGridAppView
32 from rhodecode.apps._base import RepoAppView, DataGridAppView
33 from rhodecode.lib.auth import (
33 from rhodecode.lib.auth import (
34 LoginRequired, HasRepoPermissionAnyDecorator, NotAnonymous,
34 LoginRequired, HasRepoPermissionAnyDecorator, NotAnonymous,
35 HasRepoPermissionAny, HasPermissionAnyDecorator, CSRFRequired)
35 HasRepoPermissionAny, HasPermissionAnyDecorator, CSRFRequired)
36 import rhodecode.lib.helpers as h
36 import rhodecode.lib.helpers as h
37 from rhodecode.lib.celerylib.utils import get_task_id
37 from rhodecode.lib.celerylib.utils import get_task_id
38 from rhodecode.model.db import coalesce, or_, Repository, RepoGroup
38 from rhodecode.model.db import coalesce, or_, Repository, RepoGroup
39 from rhodecode.model.repo import RepoModel
39 from rhodecode.model.repo import RepoModel
40 from rhodecode.model.forms import RepoForkForm
40 from rhodecode.model.forms import RepoForkForm
41 from rhodecode.model.scm import ScmModel, RepoGroupList
41 from rhodecode.model.scm import ScmModel, RepoGroupList
42 from rhodecode.lib.utils2 import safe_int, safe_unicode
42 from rhodecode.lib.utils2 import safe_int, safe_unicode
43
43
44 log = logging.getLogger(__name__)
44 log = logging.getLogger(__name__)
45
45
46
46
47 class RepoForksView(RepoAppView, DataGridAppView):
47 class RepoForksView(RepoAppView, DataGridAppView):
48
48
49 def load_default_context(self):
49 def load_default_context(self):
50 c = self._get_local_tmpl_context(include_app_defaults=True)
50 c = self._get_local_tmpl_context(include_app_defaults=True)
51 c.rhodecode_repo = self.rhodecode_vcs_repo
51 c.rhodecode_repo = self.rhodecode_vcs_repo
52
52
53 acl_groups = RepoGroupList(
53 acl_groups = RepoGroupList(
54 RepoGroup.query().all(),
54 RepoGroup.query().all(),
55 perm_set=['group.write', 'group.admin'])
55 perm_set=['group.write', 'group.admin'])
56 c.repo_groups = RepoGroup.groups_choices(groups=acl_groups)
56 c.repo_groups = RepoGroup.groups_choices(groups=acl_groups)
57 c.repo_groups_choices = map(lambda k: safe_unicode(k[0]), c.repo_groups)
57 c.repo_groups_choices = map(lambda k: safe_unicode(k[0]), c.repo_groups)
58 choices, c.landing_revs = ScmModel().get_repo_landing_revs(
58 choices, c.landing_revs = ScmModel().get_repo_landing_revs(
59 self.request.translate)
59 self.request.translate)
60 c.landing_revs_choices = choices
60 c.landing_revs_choices = choices
61 c.personal_repo_group = c.rhodecode_user.personal_repo_group
61 c.personal_repo_group = c.rhodecode_user.personal_repo_group
62
62
63 return c
63 return c
64
64
65 @LoginRequired()
65 @LoginRequired()
66 @HasRepoPermissionAnyDecorator(
66 @HasRepoPermissionAnyDecorator(
67 'repository.read', 'repository.write', 'repository.admin')
67 'repository.read', 'repository.write', 'repository.admin')
68 @view_config(
68 @view_config(
69 route_name='repo_forks_show_all', request_method='GET',
69 route_name='repo_forks_show_all', request_method='GET',
70 renderer='rhodecode:templates/forks/forks.mako')
70 renderer='rhodecode:templates/forks/forks.mako')
71 def repo_forks_show_all(self):
71 def repo_forks_show_all(self):
72 c = self.load_default_context()
72 c = self.load_default_context()
73 return self._get_template_context(c)
73 return self._get_template_context(c)
74
74
75 @LoginRequired()
75 @LoginRequired()
76 @HasRepoPermissionAnyDecorator(
76 @HasRepoPermissionAnyDecorator(
77 'repository.read', 'repository.write', 'repository.admin')
77 'repository.read', 'repository.write', 'repository.admin')
78 @view_config(
78 @view_config(
79 route_name='repo_forks_data', request_method='GET',
79 route_name='repo_forks_data', request_method='GET',
80 renderer='json_ext', xhr=True)
80 renderer='json_ext', xhr=True)
81 def repo_forks_data(self):
81 def repo_forks_data(self):
82 _ = self.request.translate
82 _ = self.request.translate
83 self.load_default_context()
83 self.load_default_context()
84 column_map = {
84 column_map = {
85 'fork_name': 'repo_name',
85 'fork_name': 'repo_name',
86 'fork_date': 'created_on',
86 'fork_date': 'created_on',
87 'last_activity': 'updated_on'
87 'last_activity': 'updated_on'
88 }
88 }
89 draw, start, limit = self._extract_chunk(self.request)
89 draw, start, limit = self._extract_chunk(self.request)
90 search_q, order_by, order_dir = self._extract_ordering(
90 search_q, order_by, order_dir = self._extract_ordering(
91 self.request, column_map=column_map)
91 self.request, column_map=column_map)
92
92
93 acl_check = HasRepoPermissionAny(
93 acl_check = HasRepoPermissionAny(
94 'repository.read', 'repository.write', 'repository.admin')
94 'repository.read', 'repository.write', 'repository.admin')
95 repo_id = self.db_repo.repo_id
95 repo_id = self.db_repo.repo_id
96 allowed_ids = [-1]
96 allowed_ids = [-1]
97 for f in Repository.query().filter(Repository.fork_id == repo_id):
97 for f in Repository.query().filter(Repository.fork_id == repo_id):
98 if acl_check(f.repo_name, 'get forks check'):
98 if acl_check(f.repo_name, 'get forks check'):
99 allowed_ids.append(f.repo_id)
99 allowed_ids.append(f.repo_id)
100
100
101 forks_data_total_count = Repository.query()\
101 forks_data_total_count = Repository.query()\
102 .filter(Repository.fork_id == repo_id)\
102 .filter(Repository.fork_id == repo_id)\
103 .filter(Repository.repo_id.in_(allowed_ids))\
103 .filter(Repository.repo_id.in_(allowed_ids))\
104 .count()
104 .count()
105
105
106 # json generate
106 # json generate
107 base_q = Repository.query()\
107 base_q = Repository.query()\
108 .filter(Repository.fork_id == repo_id)\
108 .filter(Repository.fork_id == repo_id)\
109 .filter(Repository.repo_id.in_(allowed_ids))\
109 .filter(Repository.repo_id.in_(allowed_ids))\
110
110
111 if search_q:
111 if search_q:
112 like_expression = u'%{}%'.format(safe_unicode(search_q))
112 like_expression = u'%{}%'.format(safe_unicode(search_q))
113 base_q = base_q.filter(or_(
113 base_q = base_q.filter(or_(
114 Repository.repo_name.ilike(like_expression),
114 Repository.repo_name.ilike(like_expression),
115 Repository.description.ilike(like_expression),
115 Repository.description.ilike(like_expression),
116 ))
116 ))
117
117
118 forks_data_total_filtered_count = base_q.count()
118 forks_data_total_filtered_count = base_q.count()
119
119
120 sort_col = getattr(Repository, order_by, None)
120 sort_col = getattr(Repository, order_by, None)
121 if sort_col:
121 if sort_col:
122 if order_dir == 'asc':
122 if order_dir == 'asc':
123 # handle null values properly to order by NULL last
123 # handle null values properly to order by NULL last
124 if order_by in ['last_activity']:
124 if order_by in ['last_activity']:
125 sort_col = coalesce(sort_col, datetime.date.max)
125 sort_col = coalesce(sort_col, datetime.date.max)
126 sort_col = sort_col.asc()
126 sort_col = sort_col.asc()
127 else:
127 else:
128 # handle null values properly to order by NULL last
128 # handle null values properly to order by NULL last
129 if order_by in ['last_activity']:
129 if order_by in ['last_activity']:
130 sort_col = coalesce(sort_col, datetime.date.min)
130 sort_col = coalesce(sort_col, datetime.date.min)
131 sort_col = sort_col.desc()
131 sort_col = sort_col.desc()
132
132
133 base_q = base_q.order_by(sort_col)
133 base_q = base_q.order_by(sort_col)
134 base_q = base_q.offset(start).limit(limit)
134 base_q = base_q.offset(start).limit(limit)
135
135
136 fork_list = base_q.all()
136 fork_list = base_q.all()
137
137
138 def fork_actions(fork):
138 def fork_actions(fork):
139 url_link = h.route_path(
139 url_link = h.route_path(
140 'repo_compare',
140 'repo_compare',
141 repo_name=fork.repo_name,
141 repo_name=fork.repo_name,
142 source_ref_type=self.db_repo.landing_rev[0],
142 source_ref_type=self.db_repo.landing_rev[0],
143 source_ref=self.db_repo.landing_rev[1],
143 source_ref=self.db_repo.landing_rev[1],
144 target_ref_type=self.db_repo.landing_rev[0],
144 target_ref_type=self.db_repo.landing_rev[0],
145 target_ref=self.db_repo.landing_rev[1],
145 target_ref=self.db_repo.landing_rev[1],
146 _query=dict(merge=1, target_repo=f.repo_name))
146 _query=dict(merge=1, target_repo=f.repo_name))
147 return h.link_to(_('Compare fork'), url_link, class_='btn-link')
147 return h.link_to(_('Compare fork'), url_link, class_='btn-link')
148
148
149 def fork_name(fork):
149 def fork_name(fork):
150 return h.link_to(fork.repo_name,
150 return h.link_to(fork.repo_name,
151 h.route_path('repo_summary', repo_name=fork.repo_name))
151 h.route_path('repo_summary', repo_name=fork.repo_name))
152
152
153 forks_data = []
153 forks_data = []
154 for fork in fork_list:
154 for fork in fork_list:
155 forks_data.append({
155 forks_data.append({
156 "username": h.gravatar_with_user(self.request, fork.user.username),
156 "username": h.gravatar_with_user(self.request, fork.user.username),
157 "fork_name": fork_name(fork),
157 "fork_name": fork_name(fork),
158 "description": fork.description_safe,
158 "description": fork.description_safe,
159 "fork_date": h.age_component(fork.created_on, time_is_local=True),
159 "fork_date": h.age_component(fork.created_on, time_is_local=True),
160 "last_activity": h.format_date(fork.updated_on),
160 "last_activity": h.format_date(fork.updated_on),
161 "action": fork_actions(fork),
161 "action": fork_actions(fork),
162 })
162 })
163
163
164 data = ({
164 data = ({
165 'draw': draw,
165 'draw': draw,
166 'data': forks_data,
166 'data': forks_data,
167 'recordsTotal': forks_data_total_count,
167 'recordsTotal': forks_data_total_count,
168 'recordsFiltered': forks_data_total_filtered_count,
168 'recordsFiltered': forks_data_total_filtered_count,
169 })
169 })
170
170
171 return data
171 return data
172
172
173 @LoginRequired()
173 @LoginRequired()
174 @NotAnonymous()
174 @NotAnonymous()
175 @HasPermissionAnyDecorator('hg.admin', 'hg.fork.repository')
175 @HasPermissionAnyDecorator('hg.admin', 'hg.fork.repository')
176 @HasRepoPermissionAnyDecorator(
176 @HasRepoPermissionAnyDecorator(
177 'repository.read', 'repository.write', 'repository.admin')
177 'repository.read', 'repository.write', 'repository.admin')
178 @view_config(
178 @view_config(
179 route_name='repo_fork_new', request_method='GET',
179 route_name='repo_fork_new', request_method='GET',
180 renderer='rhodecode:templates/forks/forks.mako')
180 renderer='rhodecode:templates/forks/forks.mako')
181 def repo_fork_new(self):
181 def repo_fork_new(self):
182 c = self.load_default_context()
182 c = self.load_default_context()
183
183
184 defaults = RepoModel()._get_defaults(self.db_repo_name)
184 defaults = RepoModel()._get_defaults(self.db_repo_name)
185 # alter the description to indicate a fork
185 # alter the description to indicate a fork
186 defaults['description'] = (
186 defaults['description'] = (
187 'fork of repository: %s \n%s' % (
187 'fork of repository: %s \n%s' % (
188 defaults['repo_name'], defaults['description']))
188 defaults['repo_name'], defaults['description']))
189 # add suffix to fork
189 # add suffix to fork
190 defaults['repo_name'] = '%s-fork' % defaults['repo_name']
190 defaults['repo_name'] = '%s-fork' % defaults['repo_name']
191
191
192 data = render('rhodecode:templates/forks/fork.mako',
192 data = render('rhodecode:templates/forks/fork.mako',
193 self._get_template_context(c), self.request)
193 self._get_template_context(c), self.request)
194 html = formencode.htmlfill.render(
194 html = formencode.htmlfill.render(
195 data,
195 data,
196 defaults=defaults,
196 defaults=defaults,
197 encoding="UTF-8",
197 encoding="UTF-8",
198 force_defaults=False
198 force_defaults=False
199 )
199 )
200 return Response(html)
200 return Response(html)
201
201
202 @LoginRequired()
202 @LoginRequired()
203 @NotAnonymous()
203 @NotAnonymous()
204 @HasPermissionAnyDecorator('hg.admin', 'hg.fork.repository')
204 @HasPermissionAnyDecorator('hg.admin', 'hg.fork.repository')
205 @HasRepoPermissionAnyDecorator(
205 @HasRepoPermissionAnyDecorator(
206 'repository.read', 'repository.write', 'repository.admin')
206 'repository.read', 'repository.write', 'repository.admin')
207 @CSRFRequired()
207 @CSRFRequired()
208 @view_config(
208 @view_config(
209 route_name='repo_fork_create', request_method='POST',
209 route_name='repo_fork_create', request_method='POST',
210 renderer='rhodecode:templates/forks/fork.mako')
210 renderer='rhodecode:templates/forks/fork.mako')
211 def repo_fork_create(self):
211 def repo_fork_create(self):
212 _ = self.request.translate
212 _ = self.request.translate
213 c = self.load_default_context()
213 c = self.load_default_context()
214
214
215 _form = RepoForkForm(self.request.translate, old_data={'repo_type': self.db_repo.repo_type},
215 _form = RepoForkForm(self.request.translate, old_data={'repo_type': self.db_repo.repo_type},
216 repo_groups=c.repo_groups_choices,
216 repo_groups=c.repo_groups_choices,
217 landing_revs=c.landing_revs_choices)()
217 landing_revs=c.landing_revs_choices)()
218 post_data = dict(self.request.POST)
218 post_data = dict(self.request.POST)
219
219
220 # forbid injecting other repo by forging a request
220 # forbid injecting other repo by forging a request
221 post_data['fork_parent_id'] = self.db_repo.repo_id
221 post_data['fork_parent_id'] = self.db_repo.repo_id
222
222
223 form_result = {}
223 form_result = {}
224 task_id = None
224 task_id = None
225 try:
225 try:
226 form_result = _form.to_python(post_data)
226 form_result = _form.to_python(post_data)
227 copy_permissions = form_result.get('copy_permissions')
227 # create fork is done sometimes async on celery, db transaction
228 # create fork is done sometimes async on celery, db transaction
228 # management is handled there.
229 # management is handled there.
229 task = RepoModel().create_fork(
230 task = RepoModel().create_fork(
230 form_result, c.rhodecode_user.user_id)
231 form_result, c.rhodecode_user.user_id)
231
232
232 task_id = get_task_id(task)
233 task_id = get_task_id(task)
233 except formencode.Invalid as errors:
234 except formencode.Invalid as errors:
234 c.rhodecode_db_repo = self.db_repo
235 c.rhodecode_db_repo = self.db_repo
235
236
236 data = render('rhodecode:templates/forks/fork.mako',
237 data = render('rhodecode:templates/forks/fork.mako',
237 self._get_template_context(c), self.request)
238 self._get_template_context(c), self.request)
238 html = formencode.htmlfill.render(
239 html = formencode.htmlfill.render(
239 data,
240 data,
240 defaults=errors.value,
241 defaults=errors.value,
241 errors=errors.error_dict or {},
242 errors=errors.error_dict or {},
242 prefix_error=False,
243 prefix_error=False,
243 encoding="UTF-8",
244 encoding="UTF-8",
244 force_defaults=False
245 force_defaults=False
245 )
246 )
246 return Response(html)
247 return Response(html)
247 except Exception:
248 except Exception:
248 log.exception(
249 log.exception(
249 u'Exception while trying to fork the repository %s',
250 u'Exception while trying to fork the repository %s', self.db_repo_name)
250 self.db_repo_name)
251 msg = _('An error occurred during repository forking %s') % (self.db_repo_name, )
251 msg = (
252 _('An error occurred during repository forking %s') % (
253 self.db_repo_name, ))
254 h.flash(msg, category='error')
252 h.flash(msg, category='error')
253 raise HTTPFound(h.route_path('home'))
255
254
256 repo_name = form_result.get('repo_name_full', self.db_repo_name)
255 repo_name = form_result.get('repo_name_full', self.db_repo_name)
257
256
258 events.trigger(events.UserPermissionsChange([self._rhodecode_user.user_id]))
257 affected_user_ids = [self._rhodecode_user.user_id]
258 if copy_permissions:
259 repository = Repository.get_by_repo_name(repo_name)
260 # also include those newly created by copy
261 user_group_perms = repository.permissions(expand_from_user_groups=True)
262 copy_perms = [perm['user_id'] for perm in user_group_perms]
263 # also include those newly created by copy
264 affected_user_ids.extend(copy_perms)
265
266 events.trigger(events.UserPermissionsChange(affected_user_ids))
259
267
260 raise HTTPFound(
268 raise HTTPFound(
261 h.route_path('repo_creating',
269 h.route_path('repo_creating', repo_name=repo_name,
262 repo_name=repo_name,
263 _query=dict(task_id=task_id)))
270 _query=dict(task_id=task_id)))
@@ -1,262 +1,266 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2011-2019 RhodeCode GmbH
3 # Copyright (C) 2011-2019 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 import logging
21 import logging
22
22
23 import deform
23 import deform
24 from pyramid.httpexceptions import HTTPFound
24 from pyramid.httpexceptions import HTTPFound
25 from pyramid.view import view_config
25 from pyramid.view import view_config
26
26
27 from rhodecode import events
27 from rhodecode import events
28 from rhodecode.apps._base import RepoAppView
28 from rhodecode.apps._base import RepoAppView
29 from rhodecode.forms import RcForm
29 from rhodecode.forms import RcForm
30 from rhodecode.lib import helpers as h
30 from rhodecode.lib import helpers as h
31 from rhodecode.lib import audit_logger
31 from rhodecode.lib import audit_logger
32 from rhodecode.lib.auth import (
32 from rhodecode.lib.auth import (
33 LoginRequired, HasRepoPermissionAnyDecorator, CSRFRequired)
33 LoginRequired, HasRepoPermissionAnyDecorator, CSRFRequired)
34 from rhodecode.model.db import RepositoryField, RepoGroup, Repository, User
34 from rhodecode.model.db import RepositoryField, RepoGroup, Repository, User
35 from rhodecode.model.meta import Session
35 from rhodecode.model.meta import Session
36 from rhodecode.model.repo import RepoModel
36 from rhodecode.model.repo import RepoModel
37 from rhodecode.model.scm import RepoGroupList, ScmModel
37 from rhodecode.model.scm import RepoGroupList, ScmModel
38 from rhodecode.model.validation_schema.schemas import repo_schema
38 from rhodecode.model.validation_schema.schemas import repo_schema
39
39
40 log = logging.getLogger(__name__)
40 log = logging.getLogger(__name__)
41
41
42
42
43 class RepoSettingsView(RepoAppView):
43 class RepoSettingsView(RepoAppView):
44
44
45 def load_default_context(self):
45 def load_default_context(self):
46 c = self._get_local_tmpl_context()
46 c = self._get_local_tmpl_context()
47
47
48 acl_groups = RepoGroupList(
48 acl_groups = RepoGroupList(
49 RepoGroup.query().all(),
49 RepoGroup.query().all(),
50 perm_set=['group.write', 'group.admin'])
50 perm_set=['group.write', 'group.admin'])
51 c.repo_groups = RepoGroup.groups_choices(groups=acl_groups)
51 c.repo_groups = RepoGroup.groups_choices(groups=acl_groups)
52 c.repo_groups_choices = map(lambda k: k[0], c.repo_groups)
52 c.repo_groups_choices = map(lambda k: k[0], c.repo_groups)
53
53
54 # in case someone no longer have a group.write access to a repository
54 # in case someone no longer have a group.write access to a repository
55 # pre fill the list with this entry, we don't care if this is the same
55 # pre fill the list with this entry, we don't care if this is the same
56 # but it will allow saving repo data properly.
56 # but it will allow saving repo data properly.
57 repo_group = self.db_repo.group
57 repo_group = self.db_repo.group
58 if repo_group and repo_group.group_id not in c.repo_groups_choices:
58 if repo_group and repo_group.group_id not in c.repo_groups_choices:
59 c.repo_groups_choices.append(repo_group.group_id)
59 c.repo_groups_choices.append(repo_group.group_id)
60 c.repo_groups.append(RepoGroup._generate_choice(repo_group))
60 c.repo_groups.append(RepoGroup._generate_choice(repo_group))
61
61
62 if c.repository_requirements_missing or self.rhodecode_vcs_repo is None:
62 if c.repository_requirements_missing or self.rhodecode_vcs_repo is None:
63 # we might be in missing requirement state, so we load things
63 # we might be in missing requirement state, so we load things
64 # without touching scm_instance()
64 # without touching scm_instance()
65 c.landing_revs_choices, c.landing_revs = \
65 c.landing_revs_choices, c.landing_revs = \
66 ScmModel().get_repo_landing_revs(self.request.translate)
66 ScmModel().get_repo_landing_revs(self.request.translate)
67 else:
67 else:
68 c.landing_revs_choices, c.landing_revs = \
68 c.landing_revs_choices, c.landing_revs = \
69 ScmModel().get_repo_landing_revs(
69 ScmModel().get_repo_landing_revs(
70 self.request.translate, self.db_repo)
70 self.request.translate, self.db_repo)
71
71
72 c.personal_repo_group = c.auth_user.personal_repo_group
72 c.personal_repo_group = c.auth_user.personal_repo_group
73 c.repo_fields = RepositoryField.query()\
73 c.repo_fields = RepositoryField.query()\
74 .filter(RepositoryField.repository == self.db_repo).all()
74 .filter(RepositoryField.repository == self.db_repo).all()
75 return c
75 return c
76
76
77 def _get_schema(self, c, old_values=None):
77 def _get_schema(self, c, old_values=None):
78 return repo_schema.RepoSettingsSchema().bind(
78 return repo_schema.RepoSettingsSchema().bind(
79 repo_type=self.db_repo.repo_type,
79 repo_type=self.db_repo.repo_type,
80 repo_type_options=[self.db_repo.repo_type],
80 repo_type_options=[self.db_repo.repo_type],
81 repo_ref_options=c.landing_revs_choices,
81 repo_ref_options=c.landing_revs_choices,
82 repo_ref_items=c.landing_revs,
82 repo_ref_items=c.landing_revs,
83 repo_repo_group_options=c.repo_groups_choices,
83 repo_repo_group_options=c.repo_groups_choices,
84 repo_repo_group_items=c.repo_groups,
84 repo_repo_group_items=c.repo_groups,
85 # user caller
85 # user caller
86 user=self._rhodecode_user,
86 user=self._rhodecode_user,
87 old_values=old_values
87 old_values=old_values
88 )
88 )
89
89
90 @LoginRequired()
90 @LoginRequired()
91 @HasRepoPermissionAnyDecorator('repository.admin')
91 @HasRepoPermissionAnyDecorator('repository.admin')
92 @view_config(
92 @view_config(
93 route_name='edit_repo', request_method='GET',
93 route_name='edit_repo', request_method='GET',
94 renderer='rhodecode:templates/admin/repos/repo_edit.mako')
94 renderer='rhodecode:templates/admin/repos/repo_edit.mako')
95 def edit_settings(self):
95 def edit_settings(self):
96 c = self.load_default_context()
96 c = self.load_default_context()
97 c.active = 'settings'
97 c.active = 'settings'
98
98
99 defaults = RepoModel()._get_defaults(self.db_repo_name)
99 defaults = RepoModel()._get_defaults(self.db_repo_name)
100 defaults['repo_owner'] = defaults['user']
100 defaults['repo_owner'] = defaults['user']
101 defaults['repo_landing_commit_ref'] = defaults['repo_landing_rev']
101 defaults['repo_landing_commit_ref'] = defaults['repo_landing_rev']
102
102
103 schema = self._get_schema(c)
103 schema = self._get_schema(c)
104 c.form = RcForm(schema, appstruct=defaults)
104 c.form = RcForm(schema, appstruct=defaults)
105 return self._get_template_context(c)
105 return self._get_template_context(c)
106
106
107 @LoginRequired()
107 @LoginRequired()
108 @HasRepoPermissionAnyDecorator('repository.admin')
108 @HasRepoPermissionAnyDecorator('repository.admin')
109 @CSRFRequired()
109 @CSRFRequired()
110 @view_config(
110 @view_config(
111 route_name='edit_repo', request_method='POST',
111 route_name='edit_repo', request_method='POST',
112 renderer='rhodecode:templates/admin/repos/repo_edit.mako')
112 renderer='rhodecode:templates/admin/repos/repo_edit.mako')
113 def edit_settings_update(self):
113 def edit_settings_update(self):
114 _ = self.request.translate
114 _ = self.request.translate
115 c = self.load_default_context()
115 c = self.load_default_context()
116 c.active = 'settings'
116 c.active = 'settings'
117 old_repo_name = self.db_repo_name
117 old_repo_name = self.db_repo_name
118
118
119 old_values = self.db_repo.get_api_data()
119 old_values = self.db_repo.get_api_data()
120 schema = self._get_schema(c, old_values=old_values)
120 schema = self._get_schema(c, old_values=old_values)
121
121
122 c.form = RcForm(schema)
122 c.form = RcForm(schema)
123 pstruct = self.request.POST.items()
123 pstruct = self.request.POST.items()
124 pstruct.append(('repo_type', self.db_repo.repo_type))
124 pstruct.append(('repo_type', self.db_repo.repo_type))
125 try:
125 try:
126 schema_data = c.form.validate(pstruct)
126 schema_data = c.form.validate(pstruct)
127 except deform.ValidationFailure as err_form:
127 except deform.ValidationFailure as err_form:
128 return self._get_template_context(c)
128 return self._get_template_context(c)
129
129
130 # data is now VALID, proceed with updates
130 # data is now VALID, proceed with updates
131 # save validated data back into the updates dict
131 # save validated data back into the updates dict
132 validated_updates = dict(
132 validated_updates = dict(
133 repo_name=schema_data['repo_group']['repo_name_without_group'],
133 repo_name=schema_data['repo_group']['repo_name_without_group'],
134 repo_group=schema_data['repo_group']['repo_group_id'],
134 repo_group=schema_data['repo_group']['repo_group_id'],
135
135
136 user=schema_data['repo_owner'],
136 user=schema_data['repo_owner'],
137 repo_description=schema_data['repo_description'],
137 repo_description=schema_data['repo_description'],
138 repo_private=schema_data['repo_private'],
138 repo_private=schema_data['repo_private'],
139 clone_uri=schema_data['repo_clone_uri'],
139 clone_uri=schema_data['repo_clone_uri'],
140 push_uri=schema_data['repo_push_uri'],
140 push_uri=schema_data['repo_push_uri'],
141 repo_landing_rev=schema_data['repo_landing_commit_ref'],
141 repo_landing_rev=schema_data['repo_landing_commit_ref'],
142 repo_enable_statistics=schema_data['repo_enable_statistics'],
142 repo_enable_statistics=schema_data['repo_enable_statistics'],
143 repo_enable_locking=schema_data['repo_enable_locking'],
143 repo_enable_locking=schema_data['repo_enable_locking'],
144 repo_enable_downloads=schema_data['repo_enable_downloads'],
144 repo_enable_downloads=schema_data['repo_enable_downloads'],
145 )
145 )
146 # detect if SYNC URI changed, if we get OLD means we keep old values
146 # detect if SYNC URI changed, if we get OLD means we keep old values
147 if schema_data['repo_clone_uri_change'] == 'OLD':
147 if schema_data['repo_clone_uri_change'] == 'OLD':
148 validated_updates['clone_uri'] = self.db_repo.clone_uri
148 validated_updates['clone_uri'] = self.db_repo.clone_uri
149
149
150 if schema_data['repo_push_uri_change'] == 'OLD':
150 if schema_data['repo_push_uri_change'] == 'OLD':
151 validated_updates['push_uri'] = self.db_repo.push_uri
151 validated_updates['push_uri'] = self.db_repo.push_uri
152
152
153 # use the new full name for redirect
153 # use the new full name for redirect
154 new_repo_name = schema_data['repo_group']['repo_name_with_group']
154 new_repo_name = schema_data['repo_group']['repo_name_with_group']
155
155
156 # save extra fields into our validated data
156 # save extra fields into our validated data
157 for key, value in pstruct:
157 for key, value in pstruct:
158 if key.startswith(RepositoryField.PREFIX):
158 if key.startswith(RepositoryField.PREFIX):
159 validated_updates[key] = value
159 validated_updates[key] = value
160
160
161 try:
161 try:
162 RepoModel().update(self.db_repo, **validated_updates)
162 RepoModel().update(self.db_repo, **validated_updates)
163 ScmModel().mark_for_invalidation(new_repo_name)
163 ScmModel().mark_for_invalidation(new_repo_name)
164
164
165 audit_logger.store_web(
165 audit_logger.store_web(
166 'repo.edit', action_data={'old_data': old_values},
166 'repo.edit', action_data={'old_data': old_values},
167 user=self._rhodecode_user, repo=self.db_repo)
167 user=self._rhodecode_user, repo=self.db_repo)
168
168
169 Session().commit()
169 Session().commit()
170
170
171 h.flash(_('Repository `{}` updated successfully').format(
171 h.flash(_('Repository `{}` updated successfully').format(old_repo_name),
172 old_repo_name), category='success')
172 category='success')
173 except Exception:
173 except Exception:
174 log.exception("Exception during update of repository")
174 log.exception("Exception during update of repository")
175 h.flash(_('Error occurred during update of repository {}').format(
175 h.flash(_('Error occurred during update of repository {}').format(
176 old_repo_name), category='error')
176 old_repo_name), category='error')
177
177
178 name_changed = old_repo_name != new_repo_name
178 name_changed = old_repo_name != new_repo_name
179 if name_changed:
179 if name_changed:
180 current_perms = self.db_repo.permissions(expand_from_user_groups=True)
181 affected_user_ids = [perm['user_id'] for perm in current_perms]
182
183 # NOTE(marcink): also add owner maybe it has changed
180 owner = User.get_by_username(schema_data['repo_owner'])
184 owner = User.get_by_username(schema_data['repo_owner'])
181 owner_id = owner.user_id if owner else self._rhodecode_user.user_id
185 owner_id = owner.user_id if owner else self._rhodecode_user.user_id
182 events.trigger(events.UserPermissionsChange([
186 affected_user_ids.extend([self._rhodecode_user.user_id, owner_id])
183 self._rhodecode_user.user_id, owner_id]))
187 events.trigger(events.UserPermissionsChange(affected_user_ids))
184
188
185 raise HTTPFound(
189 raise HTTPFound(
186 h.route_path('edit_repo', repo_name=new_repo_name))
190 h.route_path('edit_repo', repo_name=new_repo_name))
187
191
188 @LoginRequired()
192 @LoginRequired()
189 @HasRepoPermissionAnyDecorator('repository.write', 'repository.admin')
193 @HasRepoPermissionAnyDecorator('repository.write', 'repository.admin')
190 @view_config(
194 @view_config(
191 route_name='repo_edit_toggle_locking', request_method='GET',
195 route_name='repo_edit_toggle_locking', request_method='GET',
192 renderer='rhodecode:templates/admin/repos/repo_edit.mako')
196 renderer='rhodecode:templates/admin/repos/repo_edit.mako')
193 def toggle_locking(self):
197 def toggle_locking(self):
194 """
198 """
195 Toggle locking of repository by simple GET call to url
199 Toggle locking of repository by simple GET call to url
196 """
200 """
197 _ = self.request.translate
201 _ = self.request.translate
198 repo = self.db_repo
202 repo = self.db_repo
199
203
200 try:
204 try:
201 if repo.enable_locking:
205 if repo.enable_locking:
202 if repo.locked[0]:
206 if repo.locked[0]:
203 Repository.unlock(repo)
207 Repository.unlock(repo)
204 action = _('Unlocked')
208 action = _('Unlocked')
205 else:
209 else:
206 Repository.lock(
210 Repository.lock(
207 repo, self._rhodecode_user.user_id,
211 repo, self._rhodecode_user.user_id,
208 lock_reason=Repository.LOCK_WEB)
212 lock_reason=Repository.LOCK_WEB)
209 action = _('Locked')
213 action = _('Locked')
210
214
211 h.flash(_('Repository has been %s') % action,
215 h.flash(_('Repository has been %s') % action,
212 category='success')
216 category='success')
213 except Exception:
217 except Exception:
214 log.exception("Exception during unlocking")
218 log.exception("Exception during unlocking")
215 h.flash(_('An error occurred during unlocking'),
219 h.flash(_('An error occurred during unlocking'),
216 category='error')
220 category='error')
217 raise HTTPFound(
221 raise HTTPFound(
218 h.route_path('repo_summary', repo_name=self.db_repo_name))
222 h.route_path('repo_summary', repo_name=self.db_repo_name))
219
223
220 @LoginRequired()
224 @LoginRequired()
221 @HasRepoPermissionAnyDecorator('repository.admin')
225 @HasRepoPermissionAnyDecorator('repository.admin')
222 @view_config(
226 @view_config(
223 route_name='edit_repo_statistics', request_method='GET',
227 route_name='edit_repo_statistics', request_method='GET',
224 renderer='rhodecode:templates/admin/repos/repo_edit.mako')
228 renderer='rhodecode:templates/admin/repos/repo_edit.mako')
225 def edit_statistics_form(self):
229 def edit_statistics_form(self):
226 c = self.load_default_context()
230 c = self.load_default_context()
227
231
228 if self.db_repo.stats:
232 if self.db_repo.stats:
229 # this is on what revision we ended up so we add +1 for count
233 # this is on what revision we ended up so we add +1 for count
230 last_rev = self.db_repo.stats.stat_on_revision + 1
234 last_rev = self.db_repo.stats.stat_on_revision + 1
231 else:
235 else:
232 last_rev = 0
236 last_rev = 0
233
237
234 c.active = 'statistics'
238 c.active = 'statistics'
235 c.stats_revision = last_rev
239 c.stats_revision = last_rev
236 c.repo_last_rev = self.rhodecode_vcs_repo.count()
240 c.repo_last_rev = self.rhodecode_vcs_repo.count()
237
241
238 if last_rev == 0 or c.repo_last_rev == 0:
242 if last_rev == 0 or c.repo_last_rev == 0:
239 c.stats_percentage = 0
243 c.stats_percentage = 0
240 else:
244 else:
241 c.stats_percentage = '%.2f' % (
245 c.stats_percentage = '%.2f' % (
242 (float((last_rev)) / c.repo_last_rev) * 100)
246 (float((last_rev)) / c.repo_last_rev) * 100)
243 return self._get_template_context(c)
247 return self._get_template_context(c)
244
248
245 @LoginRequired()
249 @LoginRequired()
246 @HasRepoPermissionAnyDecorator('repository.admin')
250 @HasRepoPermissionAnyDecorator('repository.admin')
247 @CSRFRequired()
251 @CSRFRequired()
248 @view_config(
252 @view_config(
249 route_name='edit_repo_statistics_reset', request_method='POST',
253 route_name='edit_repo_statistics_reset', request_method='POST',
250 renderer='rhodecode:templates/admin/repos/repo_edit.mako')
254 renderer='rhodecode:templates/admin/repos/repo_edit.mako')
251 def repo_statistics_reset(self):
255 def repo_statistics_reset(self):
252 _ = self.request.translate
256 _ = self.request.translate
253
257
254 try:
258 try:
255 RepoModel().delete_stats(self.db_repo_name)
259 RepoModel().delete_stats(self.db_repo_name)
256 Session().commit()
260 Session().commit()
257 except Exception:
261 except Exception:
258 log.exception('Edit statistics failure')
262 log.exception('Edit statistics failure')
259 h.flash(_('An error occurred during deletion of repository stats'),
263 h.flash(_('An error occurred during deletion of repository stats'),
260 category='error')
264 category='error')
261 raise HTTPFound(
265 raise HTTPFound(
262 h.route_path('edit_repo_statistics', repo_name=self.db_repo_name))
266 h.route_path('edit_repo_statistics', repo_name=self.db_repo_name))
@@ -1,4800 +1,4833 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2010-2019 RhodeCode GmbH
3 # Copyright (C) 2010-2019 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 """
21 """
22 Database Models for RhodeCode Enterprise
22 Database Models for RhodeCode Enterprise
23 """
23 """
24
24
25 import re
25 import re
26 import os
26 import os
27 import time
27 import time
28 import hashlib
28 import hashlib
29 import logging
29 import logging
30 import datetime
30 import datetime
31 import warnings
31 import warnings
32 import ipaddress
32 import ipaddress
33 import functools
33 import functools
34 import traceback
34 import traceback
35 import collections
35 import collections
36
36
37 from sqlalchemy import (
37 from sqlalchemy import (
38 or_, and_, not_, func, TypeDecorator, event,
38 or_, and_, not_, func, TypeDecorator, event,
39 Index, Sequence, UniqueConstraint, ForeignKey, CheckConstraint, Column,
39 Index, Sequence, UniqueConstraint, ForeignKey, CheckConstraint, Column,
40 Boolean, String, Unicode, UnicodeText, DateTime, Integer, LargeBinary,
40 Boolean, String, Unicode, UnicodeText, DateTime, Integer, LargeBinary,
41 Text, Float, PickleType)
41 Text, Float, PickleType)
42 from sqlalchemy.sql.expression import true, false
42 from sqlalchemy.sql.expression import true, false
43 from sqlalchemy.sql.functions import coalesce, count # pragma: no cover
43 from sqlalchemy.sql.functions import coalesce, count # pragma: no cover
44 from sqlalchemy.orm import (
44 from sqlalchemy.orm import (
45 relationship, joinedload, class_mapper, validates, aliased)
45 relationship, joinedload, class_mapper, validates, aliased)
46 from sqlalchemy.ext.declarative import declared_attr
46 from sqlalchemy.ext.declarative import declared_attr
47 from sqlalchemy.ext.hybrid import hybrid_property
47 from sqlalchemy.ext.hybrid import hybrid_property
48 from sqlalchemy.exc import IntegrityError # pragma: no cover
48 from sqlalchemy.exc import IntegrityError # pragma: no cover
49 from sqlalchemy.dialects.mysql import LONGTEXT
49 from sqlalchemy.dialects.mysql import LONGTEXT
50 from zope.cachedescriptors.property import Lazy as LazyProperty
50 from zope.cachedescriptors.property import Lazy as LazyProperty
51
51
52 from pyramid.threadlocal import get_current_request
52 from pyramid.threadlocal import get_current_request
53
53
54 from rhodecode.translation import _
54 from rhodecode.translation import _
55 from rhodecode.lib.vcs import get_vcs_instance
55 from rhodecode.lib.vcs import get_vcs_instance
56 from rhodecode.lib.vcs.backends.base import EmptyCommit, Reference
56 from rhodecode.lib.vcs.backends.base import EmptyCommit, Reference
57 from rhodecode.lib.utils2 import (
57 from rhodecode.lib.utils2 import (
58 str2bool, safe_str, get_commit_safe, safe_unicode, sha1_safe,
58 str2bool, safe_str, get_commit_safe, safe_unicode, sha1_safe,
59 time_to_datetime, aslist, Optional, safe_int, get_clone_url, AttributeDict,
59 time_to_datetime, aslist, Optional, safe_int, get_clone_url, AttributeDict,
60 glob2re, StrictAttributeDict, cleaned_uri)
60 glob2re, StrictAttributeDict, cleaned_uri)
61 from rhodecode.lib.jsonalchemy import MutationObj, MutationList, JsonType, \
61 from rhodecode.lib.jsonalchemy import MutationObj, MutationList, JsonType, \
62 JsonRaw
62 JsonRaw
63 from rhodecode.lib.ext_json import json
63 from rhodecode.lib.ext_json import json
64 from rhodecode.lib.caching_query import FromCache
64 from rhodecode.lib.caching_query import FromCache
65 from rhodecode.lib.encrypt import AESCipher
65 from rhodecode.lib.encrypt import AESCipher
66
66
67 from rhodecode.model.meta import Base, Session
67 from rhodecode.model.meta import Base, Session
68
68
69 URL_SEP = '/'
69 URL_SEP = '/'
70 log = logging.getLogger(__name__)
70 log = logging.getLogger(__name__)
71
71
72 # =============================================================================
72 # =============================================================================
73 # BASE CLASSES
73 # BASE CLASSES
74 # =============================================================================
74 # =============================================================================
75
75
76 # this is propagated from .ini file rhodecode.encrypted_values.secret or
76 # this is propagated from .ini file rhodecode.encrypted_values.secret or
77 # beaker.session.secret if first is not set.
77 # beaker.session.secret if first is not set.
78 # and initialized at environment.py
78 # and initialized at environment.py
79 ENCRYPTION_KEY = None
79 ENCRYPTION_KEY = None
80
80
81 # used to sort permissions by types, '#' used here is not allowed to be in
81 # used to sort permissions by types, '#' used here is not allowed to be in
82 # usernames, and it's very early in sorted string.printable table.
82 # usernames, and it's very early in sorted string.printable table.
83 PERMISSION_TYPE_SORT = {
83 PERMISSION_TYPE_SORT = {
84 'admin': '####',
84 'admin': '####',
85 'write': '###',
85 'write': '###',
86 'read': '##',
86 'read': '##',
87 'none': '#',
87 'none': '#',
88 }
88 }
89
89
90
90
91 def display_user_sort(obj):
91 def display_user_sort(obj):
92 """
92 """
93 Sort function used to sort permissions in .permissions() function of
93 Sort function used to sort permissions in .permissions() function of
94 Repository, RepoGroup, UserGroup. Also it put the default user in front
94 Repository, RepoGroup, UserGroup. Also it put the default user in front
95 of all other resources
95 of all other resources
96 """
96 """
97
97
98 if obj.username == User.DEFAULT_USER:
98 if obj.username == User.DEFAULT_USER:
99 return '#####'
99 return '#####'
100 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
100 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
101 return prefix + obj.username
101 return prefix + obj.username
102
102
103
103
104 def display_user_group_sort(obj):
104 def display_user_group_sort(obj):
105 """
105 """
106 Sort function used to sort permissions in .permissions() function of
106 Sort function used to sort permissions in .permissions() function of
107 Repository, RepoGroup, UserGroup. Also it put the default user in front
107 Repository, RepoGroup, UserGroup. Also it put the default user in front
108 of all other resources
108 of all other resources
109 """
109 """
110
110
111 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
111 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
112 return prefix + obj.users_group_name
112 return prefix + obj.users_group_name
113
113
114
114
115 def _hash_key(k):
115 def _hash_key(k):
116 return sha1_safe(k)
116 return sha1_safe(k)
117
117
118
118
119 def in_filter_generator(qry, items, limit=500):
119 def in_filter_generator(qry, items, limit=500):
120 """
120 """
121 Splits IN() into multiple with OR
121 Splits IN() into multiple with OR
122 e.g.::
122 e.g.::
123 cnt = Repository.query().filter(
123 cnt = Repository.query().filter(
124 or_(
124 or_(
125 *in_filter_generator(Repository.repo_id, range(100000))
125 *in_filter_generator(Repository.repo_id, range(100000))
126 )).count()
126 )).count()
127 """
127 """
128 if not items:
128 if not items:
129 # empty list will cause empty query which might cause security issues
129 # empty list will cause empty query which might cause security issues
130 # this can lead to hidden unpleasant results
130 # this can lead to hidden unpleasant results
131 items = [-1]
131 items = [-1]
132
132
133 parts = []
133 parts = []
134 for chunk in xrange(0, len(items), limit):
134 for chunk in xrange(0, len(items), limit):
135 parts.append(
135 parts.append(
136 qry.in_(items[chunk: chunk + limit])
136 qry.in_(items[chunk: chunk + limit])
137 )
137 )
138
138
139 return parts
139 return parts
140
140
141
141
142 base_table_args = {
142 base_table_args = {
143 'extend_existing': True,
143 'extend_existing': True,
144 'mysql_engine': 'InnoDB',
144 'mysql_engine': 'InnoDB',
145 'mysql_charset': 'utf8',
145 'mysql_charset': 'utf8',
146 'sqlite_autoincrement': True
146 'sqlite_autoincrement': True
147 }
147 }
148
148
149
149
150 class EncryptedTextValue(TypeDecorator):
150 class EncryptedTextValue(TypeDecorator):
151 """
151 """
152 Special column for encrypted long text data, use like::
152 Special column for encrypted long text data, use like::
153
153
154 value = Column("encrypted_value", EncryptedValue(), nullable=False)
154 value = Column("encrypted_value", EncryptedValue(), nullable=False)
155
155
156 This column is intelligent so if value is in unencrypted form it return
156 This column is intelligent so if value is in unencrypted form it return
157 unencrypted form, but on save it always encrypts
157 unencrypted form, but on save it always encrypts
158 """
158 """
159 impl = Text
159 impl = Text
160
160
161 def process_bind_param(self, value, dialect):
161 def process_bind_param(self, value, dialect):
162 if not value:
162 if not value:
163 return value
163 return value
164 if value.startswith('enc$aes$') or value.startswith('enc$aes_hmac$'):
164 if value.startswith('enc$aes$') or value.startswith('enc$aes_hmac$'):
165 # protect against double encrypting if someone manually starts
165 # protect against double encrypting if someone manually starts
166 # doing
166 # doing
167 raise ValueError('value needs to be in unencrypted format, ie. '
167 raise ValueError('value needs to be in unencrypted format, ie. '
168 'not starting with enc$aes')
168 'not starting with enc$aes')
169 return 'enc$aes_hmac$%s' % AESCipher(
169 return 'enc$aes_hmac$%s' % AESCipher(
170 ENCRYPTION_KEY, hmac=True).encrypt(value)
170 ENCRYPTION_KEY, hmac=True).encrypt(value)
171
171
172 def process_result_value(self, value, dialect):
172 def process_result_value(self, value, dialect):
173 import rhodecode
173 import rhodecode
174
174
175 if not value:
175 if not value:
176 return value
176 return value
177
177
178 parts = value.split('$', 3)
178 parts = value.split('$', 3)
179 if not len(parts) == 3:
179 if not len(parts) == 3:
180 # probably not encrypted values
180 # probably not encrypted values
181 return value
181 return value
182 else:
182 else:
183 if parts[0] != 'enc':
183 if parts[0] != 'enc':
184 # parts ok but without our header ?
184 # parts ok but without our header ?
185 return value
185 return value
186 enc_strict_mode = str2bool(rhodecode.CONFIG.get(
186 enc_strict_mode = str2bool(rhodecode.CONFIG.get(
187 'rhodecode.encrypted_values.strict') or True)
187 'rhodecode.encrypted_values.strict') or True)
188 # at that stage we know it's our encryption
188 # at that stage we know it's our encryption
189 if parts[1] == 'aes':
189 if parts[1] == 'aes':
190 decrypted_data = AESCipher(ENCRYPTION_KEY).decrypt(parts[2])
190 decrypted_data = AESCipher(ENCRYPTION_KEY).decrypt(parts[2])
191 elif parts[1] == 'aes_hmac':
191 elif parts[1] == 'aes_hmac':
192 decrypted_data = AESCipher(
192 decrypted_data = AESCipher(
193 ENCRYPTION_KEY, hmac=True,
193 ENCRYPTION_KEY, hmac=True,
194 strict_verification=enc_strict_mode).decrypt(parts[2])
194 strict_verification=enc_strict_mode).decrypt(parts[2])
195 else:
195 else:
196 raise ValueError(
196 raise ValueError(
197 'Encryption type part is wrong, must be `aes` '
197 'Encryption type part is wrong, must be `aes` '
198 'or `aes_hmac`, got `%s` instead' % (parts[1]))
198 'or `aes_hmac`, got `%s` instead' % (parts[1]))
199 return decrypted_data
199 return decrypted_data
200
200
201
201
202 class BaseModel(object):
202 class BaseModel(object):
203 """
203 """
204 Base Model for all classes
204 Base Model for all classes
205 """
205 """
206
206
207 @classmethod
207 @classmethod
208 def _get_keys(cls):
208 def _get_keys(cls):
209 """return column names for this model """
209 """return column names for this model """
210 return class_mapper(cls).c.keys()
210 return class_mapper(cls).c.keys()
211
211
212 def get_dict(self):
212 def get_dict(self):
213 """
213 """
214 return dict with keys and values corresponding
214 return dict with keys and values corresponding
215 to this model data """
215 to this model data """
216
216
217 d = {}
217 d = {}
218 for k in self._get_keys():
218 for k in self._get_keys():
219 d[k] = getattr(self, k)
219 d[k] = getattr(self, k)
220
220
221 # also use __json__() if present to get additional fields
221 # also use __json__() if present to get additional fields
222 _json_attr = getattr(self, '__json__', None)
222 _json_attr = getattr(self, '__json__', None)
223 if _json_attr:
223 if _json_attr:
224 # update with attributes from __json__
224 # update with attributes from __json__
225 if callable(_json_attr):
225 if callable(_json_attr):
226 _json_attr = _json_attr()
226 _json_attr = _json_attr()
227 for k, val in _json_attr.iteritems():
227 for k, val in _json_attr.iteritems():
228 d[k] = val
228 d[k] = val
229 return d
229 return d
230
230
231 def get_appstruct(self):
231 def get_appstruct(self):
232 """return list with keys and values tuples corresponding
232 """return list with keys and values tuples corresponding
233 to this model data """
233 to this model data """
234
234
235 lst = []
235 lst = []
236 for k in self._get_keys():
236 for k in self._get_keys():
237 lst.append((k, getattr(self, k),))
237 lst.append((k, getattr(self, k),))
238 return lst
238 return lst
239
239
240 def populate_obj(self, populate_dict):
240 def populate_obj(self, populate_dict):
241 """populate model with data from given populate_dict"""
241 """populate model with data from given populate_dict"""
242
242
243 for k in self._get_keys():
243 for k in self._get_keys():
244 if k in populate_dict:
244 if k in populate_dict:
245 setattr(self, k, populate_dict[k])
245 setattr(self, k, populate_dict[k])
246
246
247 @classmethod
247 @classmethod
248 def query(cls):
248 def query(cls):
249 return Session().query(cls)
249 return Session().query(cls)
250
250
251 @classmethod
251 @classmethod
252 def get(cls, id_):
252 def get(cls, id_):
253 if id_:
253 if id_:
254 return cls.query().get(id_)
254 return cls.query().get(id_)
255
255
256 @classmethod
256 @classmethod
257 def get_or_404(cls, id_):
257 def get_or_404(cls, id_):
258 from pyramid.httpexceptions import HTTPNotFound
258 from pyramid.httpexceptions import HTTPNotFound
259
259
260 try:
260 try:
261 id_ = int(id_)
261 id_ = int(id_)
262 except (TypeError, ValueError):
262 except (TypeError, ValueError):
263 raise HTTPNotFound()
263 raise HTTPNotFound()
264
264
265 res = cls.query().get(id_)
265 res = cls.query().get(id_)
266 if not res:
266 if not res:
267 raise HTTPNotFound()
267 raise HTTPNotFound()
268 return res
268 return res
269
269
270 @classmethod
270 @classmethod
271 def getAll(cls):
271 def getAll(cls):
272 # deprecated and left for backward compatibility
272 # deprecated and left for backward compatibility
273 return cls.get_all()
273 return cls.get_all()
274
274
275 @classmethod
275 @classmethod
276 def get_all(cls):
276 def get_all(cls):
277 return cls.query().all()
277 return cls.query().all()
278
278
279 @classmethod
279 @classmethod
280 def delete(cls, id_):
280 def delete(cls, id_):
281 obj = cls.query().get(id_)
281 obj = cls.query().get(id_)
282 Session().delete(obj)
282 Session().delete(obj)
283
283
284 @classmethod
284 @classmethod
285 def identity_cache(cls, session, attr_name, value):
285 def identity_cache(cls, session, attr_name, value):
286 exist_in_session = []
286 exist_in_session = []
287 for (item_cls, pkey), instance in session.identity_map.items():
287 for (item_cls, pkey), instance in session.identity_map.items():
288 if cls == item_cls and getattr(instance, attr_name) == value:
288 if cls == item_cls and getattr(instance, attr_name) == value:
289 exist_in_session.append(instance)
289 exist_in_session.append(instance)
290 if exist_in_session:
290 if exist_in_session:
291 if len(exist_in_session) == 1:
291 if len(exist_in_session) == 1:
292 return exist_in_session[0]
292 return exist_in_session[0]
293 log.exception(
293 log.exception(
294 'multiple objects with attr %s and '
294 'multiple objects with attr %s and '
295 'value %s found with same name: %r',
295 'value %s found with same name: %r',
296 attr_name, value, exist_in_session)
296 attr_name, value, exist_in_session)
297
297
298 def __repr__(self):
298 def __repr__(self):
299 if hasattr(self, '__unicode__'):
299 if hasattr(self, '__unicode__'):
300 # python repr needs to return str
300 # python repr needs to return str
301 try:
301 try:
302 return safe_str(self.__unicode__())
302 return safe_str(self.__unicode__())
303 except UnicodeDecodeError:
303 except UnicodeDecodeError:
304 pass
304 pass
305 return '<DB:%s>' % (self.__class__.__name__)
305 return '<DB:%s>' % (self.__class__.__name__)
306
306
307
307
308 class RhodeCodeSetting(Base, BaseModel):
308 class RhodeCodeSetting(Base, BaseModel):
309 __tablename__ = 'rhodecode_settings'
309 __tablename__ = 'rhodecode_settings'
310 __table_args__ = (
310 __table_args__ = (
311 UniqueConstraint('app_settings_name'),
311 UniqueConstraint('app_settings_name'),
312 base_table_args
312 base_table_args
313 )
313 )
314
314
315 SETTINGS_TYPES = {
315 SETTINGS_TYPES = {
316 'str': safe_str,
316 'str': safe_str,
317 'int': safe_int,
317 'int': safe_int,
318 'unicode': safe_unicode,
318 'unicode': safe_unicode,
319 'bool': str2bool,
319 'bool': str2bool,
320 'list': functools.partial(aslist, sep=',')
320 'list': functools.partial(aslist, sep=',')
321 }
321 }
322 DEFAULT_UPDATE_URL = 'https://rhodecode.com/api/v1/info/versions'
322 DEFAULT_UPDATE_URL = 'https://rhodecode.com/api/v1/info/versions'
323 GLOBAL_CONF_KEY = 'app_settings'
323 GLOBAL_CONF_KEY = 'app_settings'
324
324
325 app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
325 app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
326 app_settings_name = Column("app_settings_name", String(255), nullable=True, unique=None, default=None)
326 app_settings_name = Column("app_settings_name", String(255), nullable=True, unique=None, default=None)
327 _app_settings_value = Column("app_settings_value", String(4096), nullable=True, unique=None, default=None)
327 _app_settings_value = Column("app_settings_value", String(4096), nullable=True, unique=None, default=None)
328 _app_settings_type = Column("app_settings_type", String(255), nullable=True, unique=None, default=None)
328 _app_settings_type = Column("app_settings_type", String(255), nullable=True, unique=None, default=None)
329
329
330 def __init__(self, key='', val='', type='unicode'):
330 def __init__(self, key='', val='', type='unicode'):
331 self.app_settings_name = key
331 self.app_settings_name = key
332 self.app_settings_type = type
332 self.app_settings_type = type
333 self.app_settings_value = val
333 self.app_settings_value = val
334
334
335 @validates('_app_settings_value')
335 @validates('_app_settings_value')
336 def validate_settings_value(self, key, val):
336 def validate_settings_value(self, key, val):
337 assert type(val) == unicode
337 assert type(val) == unicode
338 return val
338 return val
339
339
340 @hybrid_property
340 @hybrid_property
341 def app_settings_value(self):
341 def app_settings_value(self):
342 v = self._app_settings_value
342 v = self._app_settings_value
343 _type = self.app_settings_type
343 _type = self.app_settings_type
344 if _type:
344 if _type:
345 _type = self.app_settings_type.split('.')[0]
345 _type = self.app_settings_type.split('.')[0]
346 # decode the encrypted value
346 # decode the encrypted value
347 if 'encrypted' in self.app_settings_type:
347 if 'encrypted' in self.app_settings_type:
348 cipher = EncryptedTextValue()
348 cipher = EncryptedTextValue()
349 v = safe_unicode(cipher.process_result_value(v, None))
349 v = safe_unicode(cipher.process_result_value(v, None))
350
350
351 converter = self.SETTINGS_TYPES.get(_type) or \
351 converter = self.SETTINGS_TYPES.get(_type) or \
352 self.SETTINGS_TYPES['unicode']
352 self.SETTINGS_TYPES['unicode']
353 return converter(v)
353 return converter(v)
354
354
355 @app_settings_value.setter
355 @app_settings_value.setter
356 def app_settings_value(self, val):
356 def app_settings_value(self, val):
357 """
357 """
358 Setter that will always make sure we use unicode in app_settings_value
358 Setter that will always make sure we use unicode in app_settings_value
359
359
360 :param val:
360 :param val:
361 """
361 """
362 val = safe_unicode(val)
362 val = safe_unicode(val)
363 # encode the encrypted value
363 # encode the encrypted value
364 if 'encrypted' in self.app_settings_type:
364 if 'encrypted' in self.app_settings_type:
365 cipher = EncryptedTextValue()
365 cipher = EncryptedTextValue()
366 val = safe_unicode(cipher.process_bind_param(val, None))
366 val = safe_unicode(cipher.process_bind_param(val, None))
367 self._app_settings_value = val
367 self._app_settings_value = val
368
368
369 @hybrid_property
369 @hybrid_property
370 def app_settings_type(self):
370 def app_settings_type(self):
371 return self._app_settings_type
371 return self._app_settings_type
372
372
373 @app_settings_type.setter
373 @app_settings_type.setter
374 def app_settings_type(self, val):
374 def app_settings_type(self, val):
375 if val.split('.')[0] not in self.SETTINGS_TYPES:
375 if val.split('.')[0] not in self.SETTINGS_TYPES:
376 raise Exception('type must be one of %s got %s'
376 raise Exception('type must be one of %s got %s'
377 % (self.SETTINGS_TYPES.keys(), val))
377 % (self.SETTINGS_TYPES.keys(), val))
378 self._app_settings_type = val
378 self._app_settings_type = val
379
379
380 @classmethod
380 @classmethod
381 def get_by_prefix(cls, prefix):
381 def get_by_prefix(cls, prefix):
382 return RhodeCodeSetting.query()\
382 return RhodeCodeSetting.query()\
383 .filter(RhodeCodeSetting.app_settings_name.startswith(prefix))\
383 .filter(RhodeCodeSetting.app_settings_name.startswith(prefix))\
384 .all()
384 .all()
385
385
386 def __unicode__(self):
386 def __unicode__(self):
387 return u"<%s('%s:%s[%s]')>" % (
387 return u"<%s('%s:%s[%s]')>" % (
388 self.__class__.__name__,
388 self.__class__.__name__,
389 self.app_settings_name, self.app_settings_value,
389 self.app_settings_name, self.app_settings_value,
390 self.app_settings_type
390 self.app_settings_type
391 )
391 )
392
392
393
393
394 class RhodeCodeUi(Base, BaseModel):
394 class RhodeCodeUi(Base, BaseModel):
395 __tablename__ = 'rhodecode_ui'
395 __tablename__ = 'rhodecode_ui'
396 __table_args__ = (
396 __table_args__ = (
397 UniqueConstraint('ui_key'),
397 UniqueConstraint('ui_key'),
398 base_table_args
398 base_table_args
399 )
399 )
400
400
401 HOOK_REPO_SIZE = 'changegroup.repo_size'
401 HOOK_REPO_SIZE = 'changegroup.repo_size'
402 # HG
402 # HG
403 HOOK_PRE_PULL = 'preoutgoing.pre_pull'
403 HOOK_PRE_PULL = 'preoutgoing.pre_pull'
404 HOOK_PULL = 'outgoing.pull_logger'
404 HOOK_PULL = 'outgoing.pull_logger'
405 HOOK_PRE_PUSH = 'prechangegroup.pre_push'
405 HOOK_PRE_PUSH = 'prechangegroup.pre_push'
406 HOOK_PRETX_PUSH = 'pretxnchangegroup.pre_push'
406 HOOK_PRETX_PUSH = 'pretxnchangegroup.pre_push'
407 HOOK_PUSH = 'changegroup.push_logger'
407 HOOK_PUSH = 'changegroup.push_logger'
408 HOOK_PUSH_KEY = 'pushkey.key_push'
408 HOOK_PUSH_KEY = 'pushkey.key_push'
409
409
410 # TODO: johbo: Unify way how hooks are configured for git and hg,
410 # TODO: johbo: Unify way how hooks are configured for git and hg,
411 # git part is currently hardcoded.
411 # git part is currently hardcoded.
412
412
413 # SVN PATTERNS
413 # SVN PATTERNS
414 SVN_BRANCH_ID = 'vcs_svn_branch'
414 SVN_BRANCH_ID = 'vcs_svn_branch'
415 SVN_TAG_ID = 'vcs_svn_tag'
415 SVN_TAG_ID = 'vcs_svn_tag'
416
416
417 ui_id = Column(
417 ui_id = Column(
418 "ui_id", Integer(), nullable=False, unique=True, default=None,
418 "ui_id", Integer(), nullable=False, unique=True, default=None,
419 primary_key=True)
419 primary_key=True)
420 ui_section = Column(
420 ui_section = Column(
421 "ui_section", String(255), nullable=True, unique=None, default=None)
421 "ui_section", String(255), nullable=True, unique=None, default=None)
422 ui_key = Column(
422 ui_key = Column(
423 "ui_key", String(255), nullable=True, unique=None, default=None)
423 "ui_key", String(255), nullable=True, unique=None, default=None)
424 ui_value = Column(
424 ui_value = Column(
425 "ui_value", String(255), nullable=True, unique=None, default=None)
425 "ui_value", String(255), nullable=True, unique=None, default=None)
426 ui_active = Column(
426 ui_active = Column(
427 "ui_active", Boolean(), nullable=True, unique=None, default=True)
427 "ui_active", Boolean(), nullable=True, unique=None, default=True)
428
428
429 def __repr__(self):
429 def __repr__(self):
430 return '<%s[%s]%s=>%s]>' % (self.__class__.__name__, self.ui_section,
430 return '<%s[%s]%s=>%s]>' % (self.__class__.__name__, self.ui_section,
431 self.ui_key, self.ui_value)
431 self.ui_key, self.ui_value)
432
432
433
433
434 class RepoRhodeCodeSetting(Base, BaseModel):
434 class RepoRhodeCodeSetting(Base, BaseModel):
435 __tablename__ = 'repo_rhodecode_settings'
435 __tablename__ = 'repo_rhodecode_settings'
436 __table_args__ = (
436 __table_args__ = (
437 UniqueConstraint(
437 UniqueConstraint(
438 'app_settings_name', 'repository_id',
438 'app_settings_name', 'repository_id',
439 name='uq_repo_rhodecode_setting_name_repo_id'),
439 name='uq_repo_rhodecode_setting_name_repo_id'),
440 base_table_args
440 base_table_args
441 )
441 )
442
442
443 repository_id = Column(
443 repository_id = Column(
444 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
444 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
445 nullable=False)
445 nullable=False)
446 app_settings_id = Column(
446 app_settings_id = Column(
447 "app_settings_id", Integer(), nullable=False, unique=True,
447 "app_settings_id", Integer(), nullable=False, unique=True,
448 default=None, primary_key=True)
448 default=None, primary_key=True)
449 app_settings_name = Column(
449 app_settings_name = Column(
450 "app_settings_name", String(255), nullable=True, unique=None,
450 "app_settings_name", String(255), nullable=True, unique=None,
451 default=None)
451 default=None)
452 _app_settings_value = Column(
452 _app_settings_value = Column(
453 "app_settings_value", String(4096), nullable=True, unique=None,
453 "app_settings_value", String(4096), nullable=True, unique=None,
454 default=None)
454 default=None)
455 _app_settings_type = Column(
455 _app_settings_type = Column(
456 "app_settings_type", String(255), nullable=True, unique=None,
456 "app_settings_type", String(255), nullable=True, unique=None,
457 default=None)
457 default=None)
458
458
459 repository = relationship('Repository')
459 repository = relationship('Repository')
460
460
461 def __init__(self, repository_id, key='', val='', type='unicode'):
461 def __init__(self, repository_id, key='', val='', type='unicode'):
462 self.repository_id = repository_id
462 self.repository_id = repository_id
463 self.app_settings_name = key
463 self.app_settings_name = key
464 self.app_settings_type = type
464 self.app_settings_type = type
465 self.app_settings_value = val
465 self.app_settings_value = val
466
466
467 @validates('_app_settings_value')
467 @validates('_app_settings_value')
468 def validate_settings_value(self, key, val):
468 def validate_settings_value(self, key, val):
469 assert type(val) == unicode
469 assert type(val) == unicode
470 return val
470 return val
471
471
472 @hybrid_property
472 @hybrid_property
473 def app_settings_value(self):
473 def app_settings_value(self):
474 v = self._app_settings_value
474 v = self._app_settings_value
475 type_ = self.app_settings_type
475 type_ = self.app_settings_type
476 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
476 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
477 converter = SETTINGS_TYPES.get(type_) or SETTINGS_TYPES['unicode']
477 converter = SETTINGS_TYPES.get(type_) or SETTINGS_TYPES['unicode']
478 return converter(v)
478 return converter(v)
479
479
480 @app_settings_value.setter
480 @app_settings_value.setter
481 def app_settings_value(self, val):
481 def app_settings_value(self, val):
482 """
482 """
483 Setter that will always make sure we use unicode in app_settings_value
483 Setter that will always make sure we use unicode in app_settings_value
484
484
485 :param val:
485 :param val:
486 """
486 """
487 self._app_settings_value = safe_unicode(val)
487 self._app_settings_value = safe_unicode(val)
488
488
489 @hybrid_property
489 @hybrid_property
490 def app_settings_type(self):
490 def app_settings_type(self):
491 return self._app_settings_type
491 return self._app_settings_type
492
492
493 @app_settings_type.setter
493 @app_settings_type.setter
494 def app_settings_type(self, val):
494 def app_settings_type(self, val):
495 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
495 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
496 if val not in SETTINGS_TYPES:
496 if val not in SETTINGS_TYPES:
497 raise Exception('type must be one of %s got %s'
497 raise Exception('type must be one of %s got %s'
498 % (SETTINGS_TYPES.keys(), val))
498 % (SETTINGS_TYPES.keys(), val))
499 self._app_settings_type = val
499 self._app_settings_type = val
500
500
501 def __unicode__(self):
501 def __unicode__(self):
502 return u"<%s('%s:%s:%s[%s]')>" % (
502 return u"<%s('%s:%s:%s[%s]')>" % (
503 self.__class__.__name__, self.repository.repo_name,
503 self.__class__.__name__, self.repository.repo_name,
504 self.app_settings_name, self.app_settings_value,
504 self.app_settings_name, self.app_settings_value,
505 self.app_settings_type
505 self.app_settings_type
506 )
506 )
507
507
508
508
509 class RepoRhodeCodeUi(Base, BaseModel):
509 class RepoRhodeCodeUi(Base, BaseModel):
510 __tablename__ = 'repo_rhodecode_ui'
510 __tablename__ = 'repo_rhodecode_ui'
511 __table_args__ = (
511 __table_args__ = (
512 UniqueConstraint(
512 UniqueConstraint(
513 'repository_id', 'ui_section', 'ui_key',
513 'repository_id', 'ui_section', 'ui_key',
514 name='uq_repo_rhodecode_ui_repository_id_section_key'),
514 name='uq_repo_rhodecode_ui_repository_id_section_key'),
515 base_table_args
515 base_table_args
516 )
516 )
517
517
518 repository_id = Column(
518 repository_id = Column(
519 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
519 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
520 nullable=False)
520 nullable=False)
521 ui_id = Column(
521 ui_id = Column(
522 "ui_id", Integer(), nullable=False, unique=True, default=None,
522 "ui_id", Integer(), nullable=False, unique=True, default=None,
523 primary_key=True)
523 primary_key=True)
524 ui_section = Column(
524 ui_section = Column(
525 "ui_section", String(255), nullable=True, unique=None, default=None)
525 "ui_section", String(255), nullable=True, unique=None, default=None)
526 ui_key = Column(
526 ui_key = Column(
527 "ui_key", String(255), nullable=True, unique=None, default=None)
527 "ui_key", String(255), nullable=True, unique=None, default=None)
528 ui_value = Column(
528 ui_value = Column(
529 "ui_value", String(255), nullable=True, unique=None, default=None)
529 "ui_value", String(255), nullable=True, unique=None, default=None)
530 ui_active = Column(
530 ui_active = Column(
531 "ui_active", Boolean(), nullable=True, unique=None, default=True)
531 "ui_active", Boolean(), nullable=True, unique=None, default=True)
532
532
533 repository = relationship('Repository')
533 repository = relationship('Repository')
534
534
535 def __repr__(self):
535 def __repr__(self):
536 return '<%s[%s:%s]%s=>%s]>' % (
536 return '<%s[%s:%s]%s=>%s]>' % (
537 self.__class__.__name__, self.repository.repo_name,
537 self.__class__.__name__, self.repository.repo_name,
538 self.ui_section, self.ui_key, self.ui_value)
538 self.ui_section, self.ui_key, self.ui_value)
539
539
540
540
541 class User(Base, BaseModel):
541 class User(Base, BaseModel):
542 __tablename__ = 'users'
542 __tablename__ = 'users'
543 __table_args__ = (
543 __table_args__ = (
544 UniqueConstraint('username'), UniqueConstraint('email'),
544 UniqueConstraint('username'), UniqueConstraint('email'),
545 Index('u_username_idx', 'username'),
545 Index('u_username_idx', 'username'),
546 Index('u_email_idx', 'email'),
546 Index('u_email_idx', 'email'),
547 base_table_args
547 base_table_args
548 )
548 )
549
549
550 DEFAULT_USER = 'default'
550 DEFAULT_USER = 'default'
551 DEFAULT_USER_EMAIL = 'anonymous@rhodecode.org'
551 DEFAULT_USER_EMAIL = 'anonymous@rhodecode.org'
552 DEFAULT_GRAVATAR_URL = 'https://secure.gravatar.com/avatar/{md5email}?d=identicon&s={size}'
552 DEFAULT_GRAVATAR_URL = 'https://secure.gravatar.com/avatar/{md5email}?d=identicon&s={size}'
553
553
554 user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
554 user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
555 username = Column("username", String(255), nullable=True, unique=None, default=None)
555 username = Column("username", String(255), nullable=True, unique=None, default=None)
556 password = Column("password", String(255), nullable=True, unique=None, default=None)
556 password = Column("password", String(255), nullable=True, unique=None, default=None)
557 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
557 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
558 admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
558 admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
559 name = Column("firstname", String(255), nullable=True, unique=None, default=None)
559 name = Column("firstname", String(255), nullable=True, unique=None, default=None)
560 lastname = Column("lastname", String(255), nullable=True, unique=None, default=None)
560 lastname = Column("lastname", String(255), nullable=True, unique=None, default=None)
561 _email = Column("email", String(255), nullable=True, unique=None, default=None)
561 _email = Column("email", String(255), nullable=True, unique=None, default=None)
562 last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
562 last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
563 last_activity = Column('last_activity', DateTime(timezone=False), nullable=True, unique=None, default=None)
563 last_activity = Column('last_activity', DateTime(timezone=False), nullable=True, unique=None, default=None)
564
564
565 extern_type = Column("extern_type", String(255), nullable=True, unique=None, default=None)
565 extern_type = Column("extern_type", String(255), nullable=True, unique=None, default=None)
566 extern_name = Column("extern_name", String(255), nullable=True, unique=None, default=None)
566 extern_name = Column("extern_name", String(255), nullable=True, unique=None, default=None)
567 _api_key = Column("api_key", String(255), nullable=True, unique=None, default=None)
567 _api_key = Column("api_key", String(255), nullable=True, unique=None, default=None)
568 inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
568 inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
569 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
569 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
570 _user_data = Column("user_data", LargeBinary(), nullable=True) # JSON data
570 _user_data = Column("user_data", LargeBinary(), nullable=True) # JSON data
571
571
572 user_log = relationship('UserLog')
572 user_log = relationship('UserLog')
573 user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
573 user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
574
574
575 repositories = relationship('Repository')
575 repositories = relationship('Repository')
576 repository_groups = relationship('RepoGroup')
576 repository_groups = relationship('RepoGroup')
577 user_groups = relationship('UserGroup')
577 user_groups = relationship('UserGroup')
578
578
579 user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
579 user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
580 followings = relationship('UserFollowing', primaryjoin='UserFollowing.user_id==User.user_id', cascade='all')
580 followings = relationship('UserFollowing', primaryjoin='UserFollowing.user_id==User.user_id', cascade='all')
581
581
582 repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all')
582 repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all')
583 repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all')
583 repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all')
584 user_group_to_perm = relationship('UserUserGroupToPerm', primaryjoin='UserUserGroupToPerm.user_id==User.user_id', cascade='all')
584 user_group_to_perm = relationship('UserUserGroupToPerm', primaryjoin='UserUserGroupToPerm.user_id==User.user_id', cascade='all')
585
585
586 group_member = relationship('UserGroupMember', cascade='all')
586 group_member = relationship('UserGroupMember', cascade='all')
587
587
588 notifications = relationship('UserNotification', cascade='all')
588 notifications = relationship('UserNotification', cascade='all')
589 # notifications assigned to this user
589 # notifications assigned to this user
590 user_created_notifications = relationship('Notification', cascade='all')
590 user_created_notifications = relationship('Notification', cascade='all')
591 # comments created by this user
591 # comments created by this user
592 user_comments = relationship('ChangesetComment', cascade='all')
592 user_comments = relationship('ChangesetComment', cascade='all')
593 # user profile extra info
593 # user profile extra info
594 user_emails = relationship('UserEmailMap', cascade='all')
594 user_emails = relationship('UserEmailMap', cascade='all')
595 user_ip_map = relationship('UserIpMap', cascade='all')
595 user_ip_map = relationship('UserIpMap', cascade='all')
596 user_auth_tokens = relationship('UserApiKeys', cascade='all')
596 user_auth_tokens = relationship('UserApiKeys', cascade='all')
597 user_ssh_keys = relationship('UserSshKeys', cascade='all')
597 user_ssh_keys = relationship('UserSshKeys', cascade='all')
598
598
599 # gists
599 # gists
600 user_gists = relationship('Gist', cascade='all')
600 user_gists = relationship('Gist', cascade='all')
601 # user pull requests
601 # user pull requests
602 user_pull_requests = relationship('PullRequest', cascade='all')
602 user_pull_requests = relationship('PullRequest', cascade='all')
603 # external identities
603 # external identities
604 extenal_identities = relationship(
604 extenal_identities = relationship(
605 'ExternalIdentity',
605 'ExternalIdentity',
606 primaryjoin="User.user_id==ExternalIdentity.local_user_id",
606 primaryjoin="User.user_id==ExternalIdentity.local_user_id",
607 cascade='all')
607 cascade='all')
608 # review rules
608 # review rules
609 user_review_rules = relationship('RepoReviewRuleUser', cascade='all')
609 user_review_rules = relationship('RepoReviewRuleUser', cascade='all')
610
610
611 def __unicode__(self):
611 def __unicode__(self):
612 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
612 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
613 self.user_id, self.username)
613 self.user_id, self.username)
614
614
615 @hybrid_property
615 @hybrid_property
616 def email(self):
616 def email(self):
617 return self._email
617 return self._email
618
618
619 @email.setter
619 @email.setter
620 def email(self, val):
620 def email(self, val):
621 self._email = val.lower() if val else None
621 self._email = val.lower() if val else None
622
622
623 @hybrid_property
623 @hybrid_property
624 def first_name(self):
624 def first_name(self):
625 from rhodecode.lib import helpers as h
625 from rhodecode.lib import helpers as h
626 if self.name:
626 if self.name:
627 return h.escape(self.name)
627 return h.escape(self.name)
628 return self.name
628 return self.name
629
629
630 @hybrid_property
630 @hybrid_property
631 def last_name(self):
631 def last_name(self):
632 from rhodecode.lib import helpers as h
632 from rhodecode.lib import helpers as h
633 if self.lastname:
633 if self.lastname:
634 return h.escape(self.lastname)
634 return h.escape(self.lastname)
635 return self.lastname
635 return self.lastname
636
636
637 @hybrid_property
637 @hybrid_property
638 def api_key(self):
638 def api_key(self):
639 """
639 """
640 Fetch if exist an auth-token with role ALL connected to this user
640 Fetch if exist an auth-token with role ALL connected to this user
641 """
641 """
642 user_auth_token = UserApiKeys.query()\
642 user_auth_token = UserApiKeys.query()\
643 .filter(UserApiKeys.user_id == self.user_id)\
643 .filter(UserApiKeys.user_id == self.user_id)\
644 .filter(or_(UserApiKeys.expires == -1,
644 .filter(or_(UserApiKeys.expires == -1,
645 UserApiKeys.expires >= time.time()))\
645 UserApiKeys.expires >= time.time()))\
646 .filter(UserApiKeys.role == UserApiKeys.ROLE_ALL).first()
646 .filter(UserApiKeys.role == UserApiKeys.ROLE_ALL).first()
647 if user_auth_token:
647 if user_auth_token:
648 user_auth_token = user_auth_token.api_key
648 user_auth_token = user_auth_token.api_key
649
649
650 return user_auth_token
650 return user_auth_token
651
651
652 @api_key.setter
652 @api_key.setter
653 def api_key(self, val):
653 def api_key(self, val):
654 # don't allow to set API key this is deprecated for now
654 # don't allow to set API key this is deprecated for now
655 self._api_key = None
655 self._api_key = None
656
656
657 @property
657 @property
658 def reviewer_pull_requests(self):
658 def reviewer_pull_requests(self):
659 return PullRequestReviewers.query() \
659 return PullRequestReviewers.query() \
660 .options(joinedload(PullRequestReviewers.pull_request)) \
660 .options(joinedload(PullRequestReviewers.pull_request)) \
661 .filter(PullRequestReviewers.user_id == self.user_id) \
661 .filter(PullRequestReviewers.user_id == self.user_id) \
662 .all()
662 .all()
663
663
664 @property
664 @property
665 def firstname(self):
665 def firstname(self):
666 # alias for future
666 # alias for future
667 return self.name
667 return self.name
668
668
669 @property
669 @property
670 def emails(self):
670 def emails(self):
671 other = UserEmailMap.query()\
671 other = UserEmailMap.query()\
672 .filter(UserEmailMap.user == self) \
672 .filter(UserEmailMap.user == self) \
673 .order_by(UserEmailMap.email_id.asc()) \
673 .order_by(UserEmailMap.email_id.asc()) \
674 .all()
674 .all()
675 return [self.email] + [x.email for x in other]
675 return [self.email] + [x.email for x in other]
676
676
677 @property
677 @property
678 def auth_tokens(self):
678 def auth_tokens(self):
679 auth_tokens = self.get_auth_tokens()
679 auth_tokens = self.get_auth_tokens()
680 return [x.api_key for x in auth_tokens]
680 return [x.api_key for x in auth_tokens]
681
681
682 def get_auth_tokens(self):
682 def get_auth_tokens(self):
683 return UserApiKeys.query()\
683 return UserApiKeys.query()\
684 .filter(UserApiKeys.user == self)\
684 .filter(UserApiKeys.user == self)\
685 .order_by(UserApiKeys.user_api_key_id.asc())\
685 .order_by(UserApiKeys.user_api_key_id.asc())\
686 .all()
686 .all()
687
687
688 @LazyProperty
688 @LazyProperty
689 def feed_token(self):
689 def feed_token(self):
690 return self.get_feed_token()
690 return self.get_feed_token()
691
691
692 def get_feed_token(self, cache=True):
692 def get_feed_token(self, cache=True):
693 feed_tokens = UserApiKeys.query()\
693 feed_tokens = UserApiKeys.query()\
694 .filter(UserApiKeys.user == self)\
694 .filter(UserApiKeys.user == self)\
695 .filter(UserApiKeys.role == UserApiKeys.ROLE_FEED)
695 .filter(UserApiKeys.role == UserApiKeys.ROLE_FEED)
696 if cache:
696 if cache:
697 feed_tokens = feed_tokens.options(
697 feed_tokens = feed_tokens.options(
698 FromCache("sql_cache_short", "get_user_feed_token_%s" % self.user_id))
698 FromCache("sql_cache_short", "get_user_feed_token_%s" % self.user_id))
699
699
700 feed_tokens = feed_tokens.all()
700 feed_tokens = feed_tokens.all()
701 if feed_tokens:
701 if feed_tokens:
702 return feed_tokens[0].api_key
702 return feed_tokens[0].api_key
703 return 'NO_FEED_TOKEN_AVAILABLE'
703 return 'NO_FEED_TOKEN_AVAILABLE'
704
704
705 @classmethod
705 @classmethod
706 def get(cls, user_id, cache=False):
706 def get(cls, user_id, cache=False):
707 if not user_id:
707 if not user_id:
708 return
708 return
709
709
710 user = cls.query()
710 user = cls.query()
711 if cache:
711 if cache:
712 user = user.options(
712 user = user.options(
713 FromCache("sql_cache_short", "get_users_%s" % user_id))
713 FromCache("sql_cache_short", "get_users_%s" % user_id))
714 return user.get(user_id)
714 return user.get(user_id)
715
715
716 @classmethod
716 @classmethod
717 def extra_valid_auth_tokens(cls, user, role=None):
717 def extra_valid_auth_tokens(cls, user, role=None):
718 tokens = UserApiKeys.query().filter(UserApiKeys.user == user)\
718 tokens = UserApiKeys.query().filter(UserApiKeys.user == user)\
719 .filter(or_(UserApiKeys.expires == -1,
719 .filter(or_(UserApiKeys.expires == -1,
720 UserApiKeys.expires >= time.time()))
720 UserApiKeys.expires >= time.time()))
721 if role:
721 if role:
722 tokens = tokens.filter(or_(UserApiKeys.role == role,
722 tokens = tokens.filter(or_(UserApiKeys.role == role,
723 UserApiKeys.role == UserApiKeys.ROLE_ALL))
723 UserApiKeys.role == UserApiKeys.ROLE_ALL))
724 return tokens.all()
724 return tokens.all()
725
725
726 def authenticate_by_token(self, auth_token, roles=None, scope_repo_id=None):
726 def authenticate_by_token(self, auth_token, roles=None, scope_repo_id=None):
727 from rhodecode.lib import auth
727 from rhodecode.lib import auth
728
728
729 log.debug('Trying to authenticate user: %s via auth-token, '
729 log.debug('Trying to authenticate user: %s via auth-token, '
730 'and roles: %s', self, roles)
730 'and roles: %s', self, roles)
731
731
732 if not auth_token:
732 if not auth_token:
733 return False
733 return False
734
734
735 crypto_backend = auth.crypto_backend()
735 crypto_backend = auth.crypto_backend()
736
736
737 roles = (roles or []) + [UserApiKeys.ROLE_ALL]
737 roles = (roles or []) + [UserApiKeys.ROLE_ALL]
738 tokens_q = UserApiKeys.query()\
738 tokens_q = UserApiKeys.query()\
739 .filter(UserApiKeys.user_id == self.user_id)\
739 .filter(UserApiKeys.user_id == self.user_id)\
740 .filter(or_(UserApiKeys.expires == -1,
740 .filter(or_(UserApiKeys.expires == -1,
741 UserApiKeys.expires >= time.time()))
741 UserApiKeys.expires >= time.time()))
742
742
743 tokens_q = tokens_q.filter(UserApiKeys.role.in_(roles))
743 tokens_q = tokens_q.filter(UserApiKeys.role.in_(roles))
744
744
745 plain_tokens = []
745 plain_tokens = []
746 hash_tokens = []
746 hash_tokens = []
747
747
748 user_tokens = tokens_q.all()
748 user_tokens = tokens_q.all()
749 log.debug('Found %s user tokens to check for authentication', len(user_tokens))
749 log.debug('Found %s user tokens to check for authentication', len(user_tokens))
750 for token in user_tokens:
750 for token in user_tokens:
751 log.debug('AUTH_TOKEN: checking if user token with id `%s` matches',
751 log.debug('AUTH_TOKEN: checking if user token with id `%s` matches',
752 token.user_api_key_id)
752 token.user_api_key_id)
753 # verify scope first, since it's way faster than hash calculation of
753 # verify scope first, since it's way faster than hash calculation of
754 # encrypted tokens
754 # encrypted tokens
755 if token.repo_id:
755 if token.repo_id:
756 # token has a scope, we need to verify it
756 # token has a scope, we need to verify it
757 if scope_repo_id != token.repo_id:
757 if scope_repo_id != token.repo_id:
758 log.debug(
758 log.debug(
759 'AUTH_TOKEN: scope mismatch, token has a set repo scope: %s, '
759 'AUTH_TOKEN: scope mismatch, token has a set repo scope: %s, '
760 'and calling scope is:%s, skipping further checks',
760 'and calling scope is:%s, skipping further checks',
761 token.repo, scope_repo_id)
761 token.repo, scope_repo_id)
762 # token has a scope, and it doesn't match, skip token
762 # token has a scope, and it doesn't match, skip token
763 continue
763 continue
764
764
765 if token.api_key.startswith(crypto_backend.ENC_PREF):
765 if token.api_key.startswith(crypto_backend.ENC_PREF):
766 hash_tokens.append(token.api_key)
766 hash_tokens.append(token.api_key)
767 else:
767 else:
768 plain_tokens.append(token.api_key)
768 plain_tokens.append(token.api_key)
769
769
770 is_plain_match = auth_token in plain_tokens
770 is_plain_match = auth_token in plain_tokens
771 if is_plain_match:
771 if is_plain_match:
772 return True
772 return True
773
773
774 for hashed in hash_tokens:
774 for hashed in hash_tokens:
775 # NOTE(marcink): this is expensive to calculate, but most secure
775 # NOTE(marcink): this is expensive to calculate, but most secure
776 match = crypto_backend.hash_check(auth_token, hashed)
776 match = crypto_backend.hash_check(auth_token, hashed)
777 if match:
777 if match:
778 return True
778 return True
779
779
780 return False
780 return False
781
781
782 @property
782 @property
783 def ip_addresses(self):
783 def ip_addresses(self):
784 ret = UserIpMap.query().filter(UserIpMap.user == self).all()
784 ret = UserIpMap.query().filter(UserIpMap.user == self).all()
785 return [x.ip_addr for x in ret]
785 return [x.ip_addr for x in ret]
786
786
787 @property
787 @property
788 def username_and_name(self):
788 def username_and_name(self):
789 return '%s (%s %s)' % (self.username, self.first_name, self.last_name)
789 return '%s (%s %s)' % (self.username, self.first_name, self.last_name)
790
790
791 @property
791 @property
792 def username_or_name_or_email(self):
792 def username_or_name_or_email(self):
793 full_name = self.full_name if self.full_name is not ' ' else None
793 full_name = self.full_name if self.full_name is not ' ' else None
794 return self.username or full_name or self.email
794 return self.username or full_name or self.email
795
795
796 @property
796 @property
797 def full_name(self):
797 def full_name(self):
798 return '%s %s' % (self.first_name, self.last_name)
798 return '%s %s' % (self.first_name, self.last_name)
799
799
800 @property
800 @property
801 def full_name_or_username(self):
801 def full_name_or_username(self):
802 return ('%s %s' % (self.first_name, self.last_name)
802 return ('%s %s' % (self.first_name, self.last_name)
803 if (self.first_name and self.last_name) else self.username)
803 if (self.first_name and self.last_name) else self.username)
804
804
805 @property
805 @property
806 def full_contact(self):
806 def full_contact(self):
807 return '%s %s <%s>' % (self.first_name, self.last_name, self.email)
807 return '%s %s <%s>' % (self.first_name, self.last_name, self.email)
808
808
809 @property
809 @property
810 def short_contact(self):
810 def short_contact(self):
811 return '%s %s' % (self.first_name, self.last_name)
811 return '%s %s' % (self.first_name, self.last_name)
812
812
813 @property
813 @property
814 def is_admin(self):
814 def is_admin(self):
815 return self.admin
815 return self.admin
816
816
817 def AuthUser(self, **kwargs):
817 def AuthUser(self, **kwargs):
818 """
818 """
819 Returns instance of AuthUser for this user
819 Returns instance of AuthUser for this user
820 """
820 """
821 from rhodecode.lib.auth import AuthUser
821 from rhodecode.lib.auth import AuthUser
822 return AuthUser(user_id=self.user_id, username=self.username, **kwargs)
822 return AuthUser(user_id=self.user_id, username=self.username, **kwargs)
823
823
824 @hybrid_property
824 @hybrid_property
825 def user_data(self):
825 def user_data(self):
826 if not self._user_data:
826 if not self._user_data:
827 return {}
827 return {}
828
828
829 try:
829 try:
830 return json.loads(self._user_data)
830 return json.loads(self._user_data)
831 except TypeError:
831 except TypeError:
832 return {}
832 return {}
833
833
834 @user_data.setter
834 @user_data.setter
835 def user_data(self, val):
835 def user_data(self, val):
836 if not isinstance(val, dict):
836 if not isinstance(val, dict):
837 raise Exception('user_data must be dict, got %s' % type(val))
837 raise Exception('user_data must be dict, got %s' % type(val))
838 try:
838 try:
839 self._user_data = json.dumps(val)
839 self._user_data = json.dumps(val)
840 except Exception:
840 except Exception:
841 log.error(traceback.format_exc())
841 log.error(traceback.format_exc())
842
842
843 @classmethod
843 @classmethod
844 def get_by_username(cls, username, case_insensitive=False,
844 def get_by_username(cls, username, case_insensitive=False,
845 cache=False, identity_cache=False):
845 cache=False, identity_cache=False):
846 session = Session()
846 session = Session()
847
847
848 if case_insensitive:
848 if case_insensitive:
849 q = cls.query().filter(
849 q = cls.query().filter(
850 func.lower(cls.username) == func.lower(username))
850 func.lower(cls.username) == func.lower(username))
851 else:
851 else:
852 q = cls.query().filter(cls.username == username)
852 q = cls.query().filter(cls.username == username)
853
853
854 if cache:
854 if cache:
855 if identity_cache:
855 if identity_cache:
856 val = cls.identity_cache(session, 'username', username)
856 val = cls.identity_cache(session, 'username', username)
857 if val:
857 if val:
858 return val
858 return val
859 else:
859 else:
860 cache_key = "get_user_by_name_%s" % _hash_key(username)
860 cache_key = "get_user_by_name_%s" % _hash_key(username)
861 q = q.options(
861 q = q.options(
862 FromCache("sql_cache_short", cache_key))
862 FromCache("sql_cache_short", cache_key))
863
863
864 return q.scalar()
864 return q.scalar()
865
865
866 @classmethod
866 @classmethod
867 def get_by_auth_token(cls, auth_token, cache=False):
867 def get_by_auth_token(cls, auth_token, cache=False):
868 q = UserApiKeys.query()\
868 q = UserApiKeys.query()\
869 .filter(UserApiKeys.api_key == auth_token)\
869 .filter(UserApiKeys.api_key == auth_token)\
870 .filter(or_(UserApiKeys.expires == -1,
870 .filter(or_(UserApiKeys.expires == -1,
871 UserApiKeys.expires >= time.time()))
871 UserApiKeys.expires >= time.time()))
872 if cache:
872 if cache:
873 q = q.options(
873 q = q.options(
874 FromCache("sql_cache_short", "get_auth_token_%s" % auth_token))
874 FromCache("sql_cache_short", "get_auth_token_%s" % auth_token))
875
875
876 match = q.first()
876 match = q.first()
877 if match:
877 if match:
878 return match.user
878 return match.user
879
879
880 @classmethod
880 @classmethod
881 def get_by_email(cls, email, case_insensitive=False, cache=False):
881 def get_by_email(cls, email, case_insensitive=False, cache=False):
882
882
883 if case_insensitive:
883 if case_insensitive:
884 q = cls.query().filter(func.lower(cls.email) == func.lower(email))
884 q = cls.query().filter(func.lower(cls.email) == func.lower(email))
885
885
886 else:
886 else:
887 q = cls.query().filter(cls.email == email)
887 q = cls.query().filter(cls.email == email)
888
888
889 email_key = _hash_key(email)
889 email_key = _hash_key(email)
890 if cache:
890 if cache:
891 q = q.options(
891 q = q.options(
892 FromCache("sql_cache_short", "get_email_key_%s" % email_key))
892 FromCache("sql_cache_short", "get_email_key_%s" % email_key))
893
893
894 ret = q.scalar()
894 ret = q.scalar()
895 if ret is None:
895 if ret is None:
896 q = UserEmailMap.query()
896 q = UserEmailMap.query()
897 # try fetching in alternate email map
897 # try fetching in alternate email map
898 if case_insensitive:
898 if case_insensitive:
899 q = q.filter(func.lower(UserEmailMap.email) == func.lower(email))
899 q = q.filter(func.lower(UserEmailMap.email) == func.lower(email))
900 else:
900 else:
901 q = q.filter(UserEmailMap.email == email)
901 q = q.filter(UserEmailMap.email == email)
902 q = q.options(joinedload(UserEmailMap.user))
902 q = q.options(joinedload(UserEmailMap.user))
903 if cache:
903 if cache:
904 q = q.options(
904 q = q.options(
905 FromCache("sql_cache_short", "get_email_map_key_%s" % email_key))
905 FromCache("sql_cache_short", "get_email_map_key_%s" % email_key))
906 ret = getattr(q.scalar(), 'user', None)
906 ret = getattr(q.scalar(), 'user', None)
907
907
908 return ret
908 return ret
909
909
910 @classmethod
910 @classmethod
911 def get_from_cs_author(cls, author):
911 def get_from_cs_author(cls, author):
912 """
912 """
913 Tries to get User objects out of commit author string
913 Tries to get User objects out of commit author string
914
914
915 :param author:
915 :param author:
916 """
916 """
917 from rhodecode.lib.helpers import email, author_name
917 from rhodecode.lib.helpers import email, author_name
918 # Valid email in the attribute passed, see if they're in the system
918 # Valid email in the attribute passed, see if they're in the system
919 _email = email(author)
919 _email = email(author)
920 if _email:
920 if _email:
921 user = cls.get_by_email(_email, case_insensitive=True)
921 user = cls.get_by_email(_email, case_insensitive=True)
922 if user:
922 if user:
923 return user
923 return user
924 # Maybe we can match by username?
924 # Maybe we can match by username?
925 _author = author_name(author)
925 _author = author_name(author)
926 user = cls.get_by_username(_author, case_insensitive=True)
926 user = cls.get_by_username(_author, case_insensitive=True)
927 if user:
927 if user:
928 return user
928 return user
929
929
930 def update_userdata(self, **kwargs):
930 def update_userdata(self, **kwargs):
931 usr = self
931 usr = self
932 old = usr.user_data
932 old = usr.user_data
933 old.update(**kwargs)
933 old.update(**kwargs)
934 usr.user_data = old
934 usr.user_data = old
935 Session().add(usr)
935 Session().add(usr)
936 log.debug('updated userdata with ', kwargs)
936 log.debug('updated userdata with ', kwargs)
937
937
938 def update_lastlogin(self):
938 def update_lastlogin(self):
939 """Update user lastlogin"""
939 """Update user lastlogin"""
940 self.last_login = datetime.datetime.now()
940 self.last_login = datetime.datetime.now()
941 Session().add(self)
941 Session().add(self)
942 log.debug('updated user %s lastlogin', self.username)
942 log.debug('updated user %s lastlogin', self.username)
943
943
944 def update_password(self, new_password):
944 def update_password(self, new_password):
945 from rhodecode.lib.auth import get_crypt_password
945 from rhodecode.lib.auth import get_crypt_password
946
946
947 self.password = get_crypt_password(new_password)
947 self.password = get_crypt_password(new_password)
948 Session().add(self)
948 Session().add(self)
949
949
950 @classmethod
950 @classmethod
951 def get_first_super_admin(cls):
951 def get_first_super_admin(cls):
952 user = User.query()\
952 user = User.query()\
953 .filter(User.admin == true()) \
953 .filter(User.admin == true()) \
954 .order_by(User.user_id.asc()) \
954 .order_by(User.user_id.asc()) \
955 .first()
955 .first()
956
956
957 if user is None:
957 if user is None:
958 raise Exception('FATAL: Missing administrative account!')
958 raise Exception('FATAL: Missing administrative account!')
959 return user
959 return user
960
960
961 @classmethod
961 @classmethod
962 def get_all_super_admins(cls):
962 def get_all_super_admins(cls, only_active=False):
963 """
963 """
964 Returns all admin accounts sorted by username
964 Returns all admin accounts sorted by username
965 """
965 """
966 return User.query().filter(User.admin == true())\
966 qry = User.query().filter(User.admin == true()).order_by(User.username.asc())
967 .order_by(User.username.asc()).all()
967 if only_active:
968 qry = qry.filter(User.active == true())
969 return qry.all()
968
970
969 @classmethod
971 @classmethod
970 def get_default_user(cls, cache=False, refresh=False):
972 def get_default_user(cls, cache=False, refresh=False):
971 user = User.get_by_username(User.DEFAULT_USER, cache=cache)
973 user = User.get_by_username(User.DEFAULT_USER, cache=cache)
972 if user is None:
974 if user is None:
973 raise Exception('FATAL: Missing default account!')
975 raise Exception('FATAL: Missing default account!')
974 if refresh:
976 if refresh:
975 # The default user might be based on outdated state which
977 # The default user might be based on outdated state which
976 # has been loaded from the cache.
978 # has been loaded from the cache.
977 # A call to refresh() ensures that the
979 # A call to refresh() ensures that the
978 # latest state from the database is used.
980 # latest state from the database is used.
979 Session().refresh(user)
981 Session().refresh(user)
980 return user
982 return user
981
983
982 def _get_default_perms(self, user, suffix=''):
984 def _get_default_perms(self, user, suffix=''):
983 from rhodecode.model.permission import PermissionModel
985 from rhodecode.model.permission import PermissionModel
984 return PermissionModel().get_default_perms(user.user_perms, suffix)
986 return PermissionModel().get_default_perms(user.user_perms, suffix)
985
987
986 def get_default_perms(self, suffix=''):
988 def get_default_perms(self, suffix=''):
987 return self._get_default_perms(self, suffix)
989 return self._get_default_perms(self, suffix)
988
990
989 def get_api_data(self, include_secrets=False, details='full'):
991 def get_api_data(self, include_secrets=False, details='full'):
990 """
992 """
991 Common function for generating user related data for API
993 Common function for generating user related data for API
992
994
993 :param include_secrets: By default secrets in the API data will be replaced
995 :param include_secrets: By default secrets in the API data will be replaced
994 by a placeholder value to prevent exposing this data by accident. In case
996 by a placeholder value to prevent exposing this data by accident. In case
995 this data shall be exposed, set this flag to ``True``.
997 this data shall be exposed, set this flag to ``True``.
996
998
997 :param details: details can be 'basic|full' basic gives only a subset of
999 :param details: details can be 'basic|full' basic gives only a subset of
998 the available user information that includes user_id, name and emails.
1000 the available user information that includes user_id, name and emails.
999 """
1001 """
1000 user = self
1002 user = self
1001 user_data = self.user_data
1003 user_data = self.user_data
1002 data = {
1004 data = {
1003 'user_id': user.user_id,
1005 'user_id': user.user_id,
1004 'username': user.username,
1006 'username': user.username,
1005 'firstname': user.name,
1007 'firstname': user.name,
1006 'lastname': user.lastname,
1008 'lastname': user.lastname,
1007 'email': user.email,
1009 'email': user.email,
1008 'emails': user.emails,
1010 'emails': user.emails,
1009 }
1011 }
1010 if details == 'basic':
1012 if details == 'basic':
1011 return data
1013 return data
1012
1014
1013 auth_token_length = 40
1015 auth_token_length = 40
1014 auth_token_replacement = '*' * auth_token_length
1016 auth_token_replacement = '*' * auth_token_length
1015
1017
1016 extras = {
1018 extras = {
1017 'auth_tokens': [auth_token_replacement],
1019 'auth_tokens': [auth_token_replacement],
1018 'active': user.active,
1020 'active': user.active,
1019 'admin': user.admin,
1021 'admin': user.admin,
1020 'extern_type': user.extern_type,
1022 'extern_type': user.extern_type,
1021 'extern_name': user.extern_name,
1023 'extern_name': user.extern_name,
1022 'last_login': user.last_login,
1024 'last_login': user.last_login,
1023 'last_activity': user.last_activity,
1025 'last_activity': user.last_activity,
1024 'ip_addresses': user.ip_addresses,
1026 'ip_addresses': user.ip_addresses,
1025 'language': user_data.get('language')
1027 'language': user_data.get('language')
1026 }
1028 }
1027 data.update(extras)
1029 data.update(extras)
1028
1030
1029 if include_secrets:
1031 if include_secrets:
1030 data['auth_tokens'] = user.auth_tokens
1032 data['auth_tokens'] = user.auth_tokens
1031 return data
1033 return data
1032
1034
1033 def __json__(self):
1035 def __json__(self):
1034 data = {
1036 data = {
1035 'full_name': self.full_name,
1037 'full_name': self.full_name,
1036 'full_name_or_username': self.full_name_or_username,
1038 'full_name_or_username': self.full_name_or_username,
1037 'short_contact': self.short_contact,
1039 'short_contact': self.short_contact,
1038 'full_contact': self.full_contact,
1040 'full_contact': self.full_contact,
1039 }
1041 }
1040 data.update(self.get_api_data())
1042 data.update(self.get_api_data())
1041 return data
1043 return data
1042
1044
1043
1045
1044 class UserApiKeys(Base, BaseModel):
1046 class UserApiKeys(Base, BaseModel):
1045 __tablename__ = 'user_api_keys'
1047 __tablename__ = 'user_api_keys'
1046 __table_args__ = (
1048 __table_args__ = (
1047 Index('uak_api_key_idx', 'api_key', unique=True),
1049 Index('uak_api_key_idx', 'api_key', unique=True),
1048 Index('uak_api_key_expires_idx', 'api_key', 'expires'),
1050 Index('uak_api_key_expires_idx', 'api_key', 'expires'),
1049 base_table_args
1051 base_table_args
1050 )
1052 )
1051 __mapper_args__ = {}
1053 __mapper_args__ = {}
1052
1054
1053 # ApiKey role
1055 # ApiKey role
1054 ROLE_ALL = 'token_role_all'
1056 ROLE_ALL = 'token_role_all'
1055 ROLE_HTTP = 'token_role_http'
1057 ROLE_HTTP = 'token_role_http'
1056 ROLE_VCS = 'token_role_vcs'
1058 ROLE_VCS = 'token_role_vcs'
1057 ROLE_API = 'token_role_api'
1059 ROLE_API = 'token_role_api'
1058 ROLE_FEED = 'token_role_feed'
1060 ROLE_FEED = 'token_role_feed'
1059 ROLE_PASSWORD_RESET = 'token_password_reset'
1061 ROLE_PASSWORD_RESET = 'token_password_reset'
1060
1062
1061 ROLES = [ROLE_ALL, ROLE_HTTP, ROLE_VCS, ROLE_API, ROLE_FEED]
1063 ROLES = [ROLE_ALL, ROLE_HTTP, ROLE_VCS, ROLE_API, ROLE_FEED]
1062
1064
1063 user_api_key_id = Column("user_api_key_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1065 user_api_key_id = Column("user_api_key_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1064 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1066 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1065 api_key = Column("api_key", String(255), nullable=False, unique=True)
1067 api_key = Column("api_key", String(255), nullable=False, unique=True)
1066 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1068 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1067 expires = Column('expires', Float(53), nullable=False)
1069 expires = Column('expires', Float(53), nullable=False)
1068 role = Column('role', String(255), nullable=True)
1070 role = Column('role', String(255), nullable=True)
1069 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1071 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1070
1072
1071 # scope columns
1073 # scope columns
1072 repo_id = Column(
1074 repo_id = Column(
1073 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
1075 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
1074 nullable=True, unique=None, default=None)
1076 nullable=True, unique=None, default=None)
1075 repo = relationship('Repository', lazy='joined')
1077 repo = relationship('Repository', lazy='joined')
1076
1078
1077 repo_group_id = Column(
1079 repo_group_id = Column(
1078 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
1080 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
1079 nullable=True, unique=None, default=None)
1081 nullable=True, unique=None, default=None)
1080 repo_group = relationship('RepoGroup', lazy='joined')
1082 repo_group = relationship('RepoGroup', lazy='joined')
1081
1083
1082 user = relationship('User', lazy='joined')
1084 user = relationship('User', lazy='joined')
1083
1085
1084 def __unicode__(self):
1086 def __unicode__(self):
1085 return u"<%s('%s')>" % (self.__class__.__name__, self.role)
1087 return u"<%s('%s')>" % (self.__class__.__name__, self.role)
1086
1088
1087 def __json__(self):
1089 def __json__(self):
1088 data = {
1090 data = {
1089 'auth_token': self.api_key,
1091 'auth_token': self.api_key,
1090 'role': self.role,
1092 'role': self.role,
1091 'scope': self.scope_humanized,
1093 'scope': self.scope_humanized,
1092 'expired': self.expired
1094 'expired': self.expired
1093 }
1095 }
1094 return data
1096 return data
1095
1097
1096 def get_api_data(self, include_secrets=False):
1098 def get_api_data(self, include_secrets=False):
1097 data = self.__json__()
1099 data = self.__json__()
1098 if include_secrets:
1100 if include_secrets:
1099 return data
1101 return data
1100 else:
1102 else:
1101 data['auth_token'] = self.token_obfuscated
1103 data['auth_token'] = self.token_obfuscated
1102 return data
1104 return data
1103
1105
1104 @hybrid_property
1106 @hybrid_property
1105 def description_safe(self):
1107 def description_safe(self):
1106 from rhodecode.lib import helpers as h
1108 from rhodecode.lib import helpers as h
1107 return h.escape(self.description)
1109 return h.escape(self.description)
1108
1110
1109 @property
1111 @property
1110 def expired(self):
1112 def expired(self):
1111 if self.expires == -1:
1113 if self.expires == -1:
1112 return False
1114 return False
1113 return time.time() > self.expires
1115 return time.time() > self.expires
1114
1116
1115 @classmethod
1117 @classmethod
1116 def _get_role_name(cls, role):
1118 def _get_role_name(cls, role):
1117 return {
1119 return {
1118 cls.ROLE_ALL: _('all'),
1120 cls.ROLE_ALL: _('all'),
1119 cls.ROLE_HTTP: _('http/web interface'),
1121 cls.ROLE_HTTP: _('http/web interface'),
1120 cls.ROLE_VCS: _('vcs (git/hg/svn protocol)'),
1122 cls.ROLE_VCS: _('vcs (git/hg/svn protocol)'),
1121 cls.ROLE_API: _('api calls'),
1123 cls.ROLE_API: _('api calls'),
1122 cls.ROLE_FEED: _('feed access'),
1124 cls.ROLE_FEED: _('feed access'),
1123 }.get(role, role)
1125 }.get(role, role)
1124
1126
1125 @property
1127 @property
1126 def role_humanized(self):
1128 def role_humanized(self):
1127 return self._get_role_name(self.role)
1129 return self._get_role_name(self.role)
1128
1130
1129 def _get_scope(self):
1131 def _get_scope(self):
1130 if self.repo:
1132 if self.repo:
1131 return repr(self.repo)
1133 return repr(self.repo)
1132 if self.repo_group:
1134 if self.repo_group:
1133 return repr(self.repo_group) + ' (recursive)'
1135 return repr(self.repo_group) + ' (recursive)'
1134 return 'global'
1136 return 'global'
1135
1137
1136 @property
1138 @property
1137 def scope_humanized(self):
1139 def scope_humanized(self):
1138 return self._get_scope()
1140 return self._get_scope()
1139
1141
1140 @property
1142 @property
1141 def token_obfuscated(self):
1143 def token_obfuscated(self):
1142 if self.api_key:
1144 if self.api_key:
1143 return self.api_key[:4] + "****"
1145 return self.api_key[:4] + "****"
1144
1146
1145
1147
1146 class UserEmailMap(Base, BaseModel):
1148 class UserEmailMap(Base, BaseModel):
1147 __tablename__ = 'user_email_map'
1149 __tablename__ = 'user_email_map'
1148 __table_args__ = (
1150 __table_args__ = (
1149 Index('uem_email_idx', 'email'),
1151 Index('uem_email_idx', 'email'),
1150 UniqueConstraint('email'),
1152 UniqueConstraint('email'),
1151 base_table_args
1153 base_table_args
1152 )
1154 )
1153 __mapper_args__ = {}
1155 __mapper_args__ = {}
1154
1156
1155 email_id = Column("email_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1157 email_id = Column("email_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1156 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1158 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1157 _email = Column("email", String(255), nullable=True, unique=False, default=None)
1159 _email = Column("email", String(255), nullable=True, unique=False, default=None)
1158 user = relationship('User', lazy='joined')
1160 user = relationship('User', lazy='joined')
1159
1161
1160 @validates('_email')
1162 @validates('_email')
1161 def validate_email(self, key, email):
1163 def validate_email(self, key, email):
1162 # check if this email is not main one
1164 # check if this email is not main one
1163 main_email = Session().query(User).filter(User.email == email).scalar()
1165 main_email = Session().query(User).filter(User.email == email).scalar()
1164 if main_email is not None:
1166 if main_email is not None:
1165 raise AttributeError('email %s is present is user table' % email)
1167 raise AttributeError('email %s is present is user table' % email)
1166 return email
1168 return email
1167
1169
1168 @hybrid_property
1170 @hybrid_property
1169 def email(self):
1171 def email(self):
1170 return self._email
1172 return self._email
1171
1173
1172 @email.setter
1174 @email.setter
1173 def email(self, val):
1175 def email(self, val):
1174 self._email = val.lower() if val else None
1176 self._email = val.lower() if val else None
1175
1177
1176
1178
1177 class UserIpMap(Base, BaseModel):
1179 class UserIpMap(Base, BaseModel):
1178 __tablename__ = 'user_ip_map'
1180 __tablename__ = 'user_ip_map'
1179 __table_args__ = (
1181 __table_args__ = (
1180 UniqueConstraint('user_id', 'ip_addr'),
1182 UniqueConstraint('user_id', 'ip_addr'),
1181 base_table_args
1183 base_table_args
1182 )
1184 )
1183 __mapper_args__ = {}
1185 __mapper_args__ = {}
1184
1186
1185 ip_id = Column("ip_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1187 ip_id = Column("ip_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1186 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1188 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1187 ip_addr = Column("ip_addr", String(255), nullable=True, unique=False, default=None)
1189 ip_addr = Column("ip_addr", String(255), nullable=True, unique=False, default=None)
1188 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
1190 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
1189 description = Column("description", String(10000), nullable=True, unique=None, default=None)
1191 description = Column("description", String(10000), nullable=True, unique=None, default=None)
1190 user = relationship('User', lazy='joined')
1192 user = relationship('User', lazy='joined')
1191
1193
1192 @hybrid_property
1194 @hybrid_property
1193 def description_safe(self):
1195 def description_safe(self):
1194 from rhodecode.lib import helpers as h
1196 from rhodecode.lib import helpers as h
1195 return h.escape(self.description)
1197 return h.escape(self.description)
1196
1198
1197 @classmethod
1199 @classmethod
1198 def _get_ip_range(cls, ip_addr):
1200 def _get_ip_range(cls, ip_addr):
1199 net = ipaddress.ip_network(safe_unicode(ip_addr), strict=False)
1201 net = ipaddress.ip_network(safe_unicode(ip_addr), strict=False)
1200 return [str(net.network_address), str(net.broadcast_address)]
1202 return [str(net.network_address), str(net.broadcast_address)]
1201
1203
1202 def __json__(self):
1204 def __json__(self):
1203 return {
1205 return {
1204 'ip_addr': self.ip_addr,
1206 'ip_addr': self.ip_addr,
1205 'ip_range': self._get_ip_range(self.ip_addr),
1207 'ip_range': self._get_ip_range(self.ip_addr),
1206 }
1208 }
1207
1209
1208 def __unicode__(self):
1210 def __unicode__(self):
1209 return u"<%s('user_id:%s=>%s')>" % (self.__class__.__name__,
1211 return u"<%s('user_id:%s=>%s')>" % (self.__class__.__name__,
1210 self.user_id, self.ip_addr)
1212 self.user_id, self.ip_addr)
1211
1213
1212
1214
1213 class UserSshKeys(Base, BaseModel):
1215 class UserSshKeys(Base, BaseModel):
1214 __tablename__ = 'user_ssh_keys'
1216 __tablename__ = 'user_ssh_keys'
1215 __table_args__ = (
1217 __table_args__ = (
1216 Index('usk_ssh_key_fingerprint_idx', 'ssh_key_fingerprint'),
1218 Index('usk_ssh_key_fingerprint_idx', 'ssh_key_fingerprint'),
1217
1219
1218 UniqueConstraint('ssh_key_fingerprint'),
1220 UniqueConstraint('ssh_key_fingerprint'),
1219
1221
1220 base_table_args
1222 base_table_args
1221 )
1223 )
1222 __mapper_args__ = {}
1224 __mapper_args__ = {}
1223
1225
1224 ssh_key_id = Column('ssh_key_id', Integer(), nullable=False, unique=True, default=None, primary_key=True)
1226 ssh_key_id = Column('ssh_key_id', Integer(), nullable=False, unique=True, default=None, primary_key=True)
1225 ssh_key_data = Column('ssh_key_data', String(10240), nullable=False, unique=None, default=None)
1227 ssh_key_data = Column('ssh_key_data', String(10240), nullable=False, unique=None, default=None)
1226 ssh_key_fingerprint = Column('ssh_key_fingerprint', String(255), nullable=False, unique=None, default=None)
1228 ssh_key_fingerprint = Column('ssh_key_fingerprint', String(255), nullable=False, unique=None, default=None)
1227
1229
1228 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1230 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1229
1231
1230 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1232 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1231 accessed_on = Column('accessed_on', DateTime(timezone=False), nullable=True, default=None)
1233 accessed_on = Column('accessed_on', DateTime(timezone=False), nullable=True, default=None)
1232 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1234 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1233
1235
1234 user = relationship('User', lazy='joined')
1236 user = relationship('User', lazy='joined')
1235
1237
1236 def __json__(self):
1238 def __json__(self):
1237 data = {
1239 data = {
1238 'ssh_fingerprint': self.ssh_key_fingerprint,
1240 'ssh_fingerprint': self.ssh_key_fingerprint,
1239 'description': self.description,
1241 'description': self.description,
1240 'created_on': self.created_on
1242 'created_on': self.created_on
1241 }
1243 }
1242 return data
1244 return data
1243
1245
1244 def get_api_data(self):
1246 def get_api_data(self):
1245 data = self.__json__()
1247 data = self.__json__()
1246 return data
1248 return data
1247
1249
1248
1250
1249 class UserLog(Base, BaseModel):
1251 class UserLog(Base, BaseModel):
1250 __tablename__ = 'user_logs'
1252 __tablename__ = 'user_logs'
1251 __table_args__ = (
1253 __table_args__ = (
1252 base_table_args,
1254 base_table_args,
1253 )
1255 )
1254
1256
1255 VERSION_1 = 'v1'
1257 VERSION_1 = 'v1'
1256 VERSION_2 = 'v2'
1258 VERSION_2 = 'v2'
1257 VERSIONS = [VERSION_1, VERSION_2]
1259 VERSIONS = [VERSION_1, VERSION_2]
1258
1260
1259 user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1261 user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1260 user_id = Column("user_id", Integer(), ForeignKey('users.user_id',ondelete='SET NULL'), nullable=True, unique=None, default=None)
1262 user_id = Column("user_id", Integer(), ForeignKey('users.user_id',ondelete='SET NULL'), nullable=True, unique=None, default=None)
1261 username = Column("username", String(255), nullable=True, unique=None, default=None)
1263 username = Column("username", String(255), nullable=True, unique=None, default=None)
1262 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id', ondelete='SET NULL'), nullable=True, unique=None, default=None)
1264 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id', ondelete='SET NULL'), nullable=True, unique=None, default=None)
1263 repository_name = Column("repository_name", String(255), nullable=True, unique=None, default=None)
1265 repository_name = Column("repository_name", String(255), nullable=True, unique=None, default=None)
1264 user_ip = Column("user_ip", String(255), nullable=True, unique=None, default=None)
1266 user_ip = Column("user_ip", String(255), nullable=True, unique=None, default=None)
1265 action = Column("action", Text().with_variant(Text(1200000), 'mysql'), nullable=True, unique=None, default=None)
1267 action = Column("action", Text().with_variant(Text(1200000), 'mysql'), nullable=True, unique=None, default=None)
1266 action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
1268 action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
1267
1269
1268 version = Column("version", String(255), nullable=True, default=VERSION_1)
1270 version = Column("version", String(255), nullable=True, default=VERSION_1)
1269 user_data = Column('user_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1271 user_data = Column('user_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1270 action_data = Column('action_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1272 action_data = Column('action_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1271
1273
1272 def __unicode__(self):
1274 def __unicode__(self):
1273 return u"<%s('id:%s:%s')>" % (
1275 return u"<%s('id:%s:%s')>" % (
1274 self.__class__.__name__, self.repository_name, self.action)
1276 self.__class__.__name__, self.repository_name, self.action)
1275
1277
1276 def __json__(self):
1278 def __json__(self):
1277 return {
1279 return {
1278 'user_id': self.user_id,
1280 'user_id': self.user_id,
1279 'username': self.username,
1281 'username': self.username,
1280 'repository_id': self.repository_id,
1282 'repository_id': self.repository_id,
1281 'repository_name': self.repository_name,
1283 'repository_name': self.repository_name,
1282 'user_ip': self.user_ip,
1284 'user_ip': self.user_ip,
1283 'action_date': self.action_date,
1285 'action_date': self.action_date,
1284 'action': self.action,
1286 'action': self.action,
1285 }
1287 }
1286
1288
1287 @hybrid_property
1289 @hybrid_property
1288 def entry_id(self):
1290 def entry_id(self):
1289 return self.user_log_id
1291 return self.user_log_id
1290
1292
1291 @property
1293 @property
1292 def action_as_day(self):
1294 def action_as_day(self):
1293 return datetime.date(*self.action_date.timetuple()[:3])
1295 return datetime.date(*self.action_date.timetuple()[:3])
1294
1296
1295 user = relationship('User')
1297 user = relationship('User')
1296 repository = relationship('Repository', cascade='')
1298 repository = relationship('Repository', cascade='')
1297
1299
1298
1300
1299 class UserGroup(Base, BaseModel):
1301 class UserGroup(Base, BaseModel):
1300 __tablename__ = 'users_groups'
1302 __tablename__ = 'users_groups'
1301 __table_args__ = (
1303 __table_args__ = (
1302 base_table_args,
1304 base_table_args,
1303 )
1305 )
1304
1306
1305 users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1307 users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1306 users_group_name = Column("users_group_name", String(255), nullable=False, unique=True, default=None)
1308 users_group_name = Column("users_group_name", String(255), nullable=False, unique=True, default=None)
1307 user_group_description = Column("user_group_description", String(10000), nullable=True, unique=None, default=None)
1309 user_group_description = Column("user_group_description", String(10000), nullable=True, unique=None, default=None)
1308 users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
1310 users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
1309 inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
1311 inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
1310 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
1312 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
1311 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1313 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1312 _group_data = Column("group_data", LargeBinary(), nullable=True) # JSON data
1314 _group_data = Column("group_data", LargeBinary(), nullable=True) # JSON data
1313
1315
1314 members = relationship('UserGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
1316 members = relationship('UserGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
1315 users_group_to_perm = relationship('UserGroupToPerm', cascade='all')
1317 users_group_to_perm = relationship('UserGroupToPerm', cascade='all')
1316 users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1318 users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1317 users_group_repo_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
1319 users_group_repo_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
1318 user_user_group_to_perm = relationship('UserUserGroupToPerm', cascade='all')
1320 user_user_group_to_perm = relationship('UserUserGroupToPerm', cascade='all')
1319 user_group_user_group_to_perm = relationship('UserGroupUserGroupToPerm ', primaryjoin="UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id", cascade='all')
1321 user_group_user_group_to_perm = relationship('UserGroupUserGroupToPerm ', primaryjoin="UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id", cascade='all')
1320
1322
1321 user_group_review_rules = relationship('RepoReviewRuleUserGroup', cascade='all')
1323 user_group_review_rules = relationship('RepoReviewRuleUserGroup', cascade='all')
1322 user = relationship('User', primaryjoin="User.user_id==UserGroup.user_id")
1324 user = relationship('User', primaryjoin="User.user_id==UserGroup.user_id")
1323
1325
1324 @classmethod
1326 @classmethod
1325 def _load_group_data(cls, column):
1327 def _load_group_data(cls, column):
1326 if not column:
1328 if not column:
1327 return {}
1329 return {}
1328
1330
1329 try:
1331 try:
1330 return json.loads(column) or {}
1332 return json.loads(column) or {}
1331 except TypeError:
1333 except TypeError:
1332 return {}
1334 return {}
1333
1335
1334 @hybrid_property
1336 @hybrid_property
1335 def description_safe(self):
1337 def description_safe(self):
1336 from rhodecode.lib import helpers as h
1338 from rhodecode.lib import helpers as h
1337 return h.escape(self.user_group_description)
1339 return h.escape(self.user_group_description)
1338
1340
1339 @hybrid_property
1341 @hybrid_property
1340 def group_data(self):
1342 def group_data(self):
1341 return self._load_group_data(self._group_data)
1343 return self._load_group_data(self._group_data)
1342
1344
1343 @group_data.expression
1345 @group_data.expression
1344 def group_data(self, **kwargs):
1346 def group_data(self, **kwargs):
1345 return self._group_data
1347 return self._group_data
1346
1348
1347 @group_data.setter
1349 @group_data.setter
1348 def group_data(self, val):
1350 def group_data(self, val):
1349 try:
1351 try:
1350 self._group_data = json.dumps(val)
1352 self._group_data = json.dumps(val)
1351 except Exception:
1353 except Exception:
1352 log.error(traceback.format_exc())
1354 log.error(traceback.format_exc())
1353
1355
1354 @classmethod
1356 @classmethod
1355 def _load_sync(cls, group_data):
1357 def _load_sync(cls, group_data):
1356 if group_data:
1358 if group_data:
1357 return group_data.get('extern_type')
1359 return group_data.get('extern_type')
1358
1360
1359 @property
1361 @property
1360 def sync(self):
1362 def sync(self):
1361 return self._load_sync(self.group_data)
1363 return self._load_sync(self.group_data)
1362
1364
1363 def __unicode__(self):
1365 def __unicode__(self):
1364 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
1366 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
1365 self.users_group_id,
1367 self.users_group_id,
1366 self.users_group_name)
1368 self.users_group_name)
1367
1369
1368 @classmethod
1370 @classmethod
1369 def get_by_group_name(cls, group_name, cache=False,
1371 def get_by_group_name(cls, group_name, cache=False,
1370 case_insensitive=False):
1372 case_insensitive=False):
1371 if case_insensitive:
1373 if case_insensitive:
1372 q = cls.query().filter(func.lower(cls.users_group_name) ==
1374 q = cls.query().filter(func.lower(cls.users_group_name) ==
1373 func.lower(group_name))
1375 func.lower(group_name))
1374
1376
1375 else:
1377 else:
1376 q = cls.query().filter(cls.users_group_name == group_name)
1378 q = cls.query().filter(cls.users_group_name == group_name)
1377 if cache:
1379 if cache:
1378 q = q.options(
1380 q = q.options(
1379 FromCache("sql_cache_short", "get_group_%s" % _hash_key(group_name)))
1381 FromCache("sql_cache_short", "get_group_%s" % _hash_key(group_name)))
1380 return q.scalar()
1382 return q.scalar()
1381
1383
1382 @classmethod
1384 @classmethod
1383 def get(cls, user_group_id, cache=False):
1385 def get(cls, user_group_id, cache=False):
1384 if not user_group_id:
1386 if not user_group_id:
1385 return
1387 return
1386
1388
1387 user_group = cls.query()
1389 user_group = cls.query()
1388 if cache:
1390 if cache:
1389 user_group = user_group.options(
1391 user_group = user_group.options(
1390 FromCache("sql_cache_short", "get_users_group_%s" % user_group_id))
1392 FromCache("sql_cache_short", "get_users_group_%s" % user_group_id))
1391 return user_group.get(user_group_id)
1393 return user_group.get(user_group_id)
1392
1394
1393 def permissions(self, with_admins=True, with_owner=True):
1395 def permissions(self, with_admins=True, with_owner=True,
1396 expand_from_user_groups=False):
1394 """
1397 """
1395 Permissions for user groups
1398 Permissions for user groups
1396 """
1399 """
1397 _admin_perm = 'usergroup.admin'
1400 _admin_perm = 'usergroup.admin'
1398
1401
1399 owner_row = []
1402 owner_row = []
1400 if with_owner:
1403 if with_owner:
1401 usr = AttributeDict(self.user.get_dict())
1404 usr = AttributeDict(self.user.get_dict())
1402 usr.owner_row = True
1405 usr.owner_row = True
1403 usr.permission = _admin_perm
1406 usr.permission = _admin_perm
1404 owner_row.append(usr)
1407 owner_row.append(usr)
1405
1408
1406 super_admin_ids = []
1409 super_admin_ids = []
1407 super_admin_rows = []
1410 super_admin_rows = []
1408 if with_admins:
1411 if with_admins:
1409 for usr in User.get_all_super_admins():
1412 for usr in User.get_all_super_admins():
1410 super_admin_ids.append(usr.user_id)
1413 super_admin_ids.append(usr.user_id)
1411 # if this admin is also owner, don't double the record
1414 # if this admin is also owner, don't double the record
1412 if usr.user_id == owner_row[0].user_id:
1415 if usr.user_id == owner_row[0].user_id:
1413 owner_row[0].admin_row = True
1416 owner_row[0].admin_row = True
1414 else:
1417 else:
1415 usr = AttributeDict(usr.get_dict())
1418 usr = AttributeDict(usr.get_dict())
1416 usr.admin_row = True
1419 usr.admin_row = True
1417 usr.permission = _admin_perm
1420 usr.permission = _admin_perm
1418 super_admin_rows.append(usr)
1421 super_admin_rows.append(usr)
1419
1422
1420 q = UserUserGroupToPerm.query().filter(UserUserGroupToPerm.user_group == self)
1423 q = UserUserGroupToPerm.query().filter(UserUserGroupToPerm.user_group == self)
1421 q = q.options(joinedload(UserUserGroupToPerm.user_group),
1424 q = q.options(joinedload(UserUserGroupToPerm.user_group),
1422 joinedload(UserUserGroupToPerm.user),
1425 joinedload(UserUserGroupToPerm.user),
1423 joinedload(UserUserGroupToPerm.permission),)
1426 joinedload(UserUserGroupToPerm.permission),)
1424
1427
1425 # get owners and admins and permissions. We do a trick of re-writing
1428 # get owners and admins and permissions. We do a trick of re-writing
1426 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1429 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1427 # has a global reference and changing one object propagates to all
1430 # has a global reference and changing one object propagates to all
1428 # others. This means if admin is also an owner admin_row that change
1431 # others. This means if admin is also an owner admin_row that change
1429 # would propagate to both objects
1432 # would propagate to both objects
1430 perm_rows = []
1433 perm_rows = []
1431 for _usr in q.all():
1434 for _usr in q.all():
1432 usr = AttributeDict(_usr.user.get_dict())
1435 usr = AttributeDict(_usr.user.get_dict())
1433 # if this user is also owner/admin, mark as duplicate record
1436 # if this user is also owner/admin, mark as duplicate record
1434 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
1437 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
1435 usr.duplicate_perm = True
1438 usr.duplicate_perm = True
1436 usr.permission = _usr.permission.permission_name
1439 usr.permission = _usr.permission.permission_name
1437 perm_rows.append(usr)
1440 perm_rows.append(usr)
1438
1441
1439 # filter the perm rows by 'default' first and then sort them by
1442 # filter the perm rows by 'default' first and then sort them by
1440 # admin,write,read,none permissions sorted again alphabetically in
1443 # admin,write,read,none permissions sorted again alphabetically in
1441 # each group
1444 # each group
1442 perm_rows = sorted(perm_rows, key=display_user_sort)
1445 perm_rows = sorted(perm_rows, key=display_user_sort)
1443
1446
1444 return super_admin_rows + owner_row + perm_rows
1447 user_groups_rows = []
1445
1448 if expand_from_user_groups:
1446 def permission_user_groups(self):
1449 for ug in self.permission_user_groups(with_members=True):
1447 q = UserGroupUserGroupToPerm.query().filter(UserGroupUserGroupToPerm.target_user_group == self)
1450 for user_data in ug.members:
1451 user_groups_rows.append(user_data)
1452
1453 return super_admin_rows + owner_row + perm_rows + user_groups_rows
1454
1455 def permission_user_groups(self, with_members=False):
1456 q = UserGroupUserGroupToPerm.query()\
1457 .filter(UserGroupUserGroupToPerm.target_user_group == self)
1448 q = q.options(joinedload(UserGroupUserGroupToPerm.user_group),
1458 q = q.options(joinedload(UserGroupUserGroupToPerm.user_group),
1449 joinedload(UserGroupUserGroupToPerm.target_user_group),
1459 joinedload(UserGroupUserGroupToPerm.target_user_group),
1450 joinedload(UserGroupUserGroupToPerm.permission),)
1460 joinedload(UserGroupUserGroupToPerm.permission),)
1451
1461
1452 perm_rows = []
1462 perm_rows = []
1453 for _user_group in q.all():
1463 for _user_group in q.all():
1454 usr = AttributeDict(_user_group.user_group.get_dict())
1464 entry = AttributeDict(_user_group.user_group.get_dict())
1455 usr.permission = _user_group.permission.permission_name
1465 entry.permission = _user_group.permission.permission_name
1456 perm_rows.append(usr)
1466 if with_members:
1467 entry.members = [x.user.get_dict()
1468 for x in _user_group.users_group.members]
1469 perm_rows.append(entry)
1457
1470
1458 perm_rows = sorted(perm_rows, key=display_user_group_sort)
1471 perm_rows = sorted(perm_rows, key=display_user_group_sort)
1459 return perm_rows
1472 return perm_rows
1460
1473
1461 def _get_default_perms(self, user_group, suffix=''):
1474 def _get_default_perms(self, user_group, suffix=''):
1462 from rhodecode.model.permission import PermissionModel
1475 from rhodecode.model.permission import PermissionModel
1463 return PermissionModel().get_default_perms(user_group.users_group_to_perm, suffix)
1476 return PermissionModel().get_default_perms(user_group.users_group_to_perm, suffix)
1464
1477
1465 def get_default_perms(self, suffix=''):
1478 def get_default_perms(self, suffix=''):
1466 return self._get_default_perms(self, suffix)
1479 return self._get_default_perms(self, suffix)
1467
1480
1468 def get_api_data(self, with_group_members=True, include_secrets=False):
1481 def get_api_data(self, with_group_members=True, include_secrets=False):
1469 """
1482 """
1470 :param include_secrets: See :meth:`User.get_api_data`, this parameter is
1483 :param include_secrets: See :meth:`User.get_api_data`, this parameter is
1471 basically forwarded.
1484 basically forwarded.
1472
1485
1473 """
1486 """
1474 user_group = self
1487 user_group = self
1475 data = {
1488 data = {
1476 'users_group_id': user_group.users_group_id,
1489 'users_group_id': user_group.users_group_id,
1477 'group_name': user_group.users_group_name,
1490 'group_name': user_group.users_group_name,
1478 'group_description': user_group.user_group_description,
1491 'group_description': user_group.user_group_description,
1479 'active': user_group.users_group_active,
1492 'active': user_group.users_group_active,
1480 'owner': user_group.user.username,
1493 'owner': user_group.user.username,
1481 'sync': user_group.sync,
1494 'sync': user_group.sync,
1482 'owner_email': user_group.user.email,
1495 'owner_email': user_group.user.email,
1483 }
1496 }
1484
1497
1485 if with_group_members:
1498 if with_group_members:
1486 users = []
1499 users = []
1487 for user in user_group.members:
1500 for user in user_group.members:
1488 user = user.user
1501 user = user.user
1489 users.append(user.get_api_data(include_secrets=include_secrets))
1502 users.append(user.get_api_data(include_secrets=include_secrets))
1490 data['users'] = users
1503 data['users'] = users
1491
1504
1492 return data
1505 return data
1493
1506
1494
1507
1495 class UserGroupMember(Base, BaseModel):
1508 class UserGroupMember(Base, BaseModel):
1496 __tablename__ = 'users_groups_members'
1509 __tablename__ = 'users_groups_members'
1497 __table_args__ = (
1510 __table_args__ = (
1498 base_table_args,
1511 base_table_args,
1499 )
1512 )
1500
1513
1501 users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1514 users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1502 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
1515 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
1503 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
1516 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
1504
1517
1505 user = relationship('User', lazy='joined')
1518 user = relationship('User', lazy='joined')
1506 users_group = relationship('UserGroup')
1519 users_group = relationship('UserGroup')
1507
1520
1508 def __init__(self, gr_id='', u_id=''):
1521 def __init__(self, gr_id='', u_id=''):
1509 self.users_group_id = gr_id
1522 self.users_group_id = gr_id
1510 self.user_id = u_id
1523 self.user_id = u_id
1511
1524
1512
1525
1513 class RepositoryField(Base, BaseModel):
1526 class RepositoryField(Base, BaseModel):
1514 __tablename__ = 'repositories_fields'
1527 __tablename__ = 'repositories_fields'
1515 __table_args__ = (
1528 __table_args__ = (
1516 UniqueConstraint('repository_id', 'field_key'), # no-multi field
1529 UniqueConstraint('repository_id', 'field_key'), # no-multi field
1517 base_table_args,
1530 base_table_args,
1518 )
1531 )
1519
1532
1520 PREFIX = 'ex_' # prefix used in form to not conflict with already existing fields
1533 PREFIX = 'ex_' # prefix used in form to not conflict with already existing fields
1521
1534
1522 repo_field_id = Column("repo_field_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1535 repo_field_id = Column("repo_field_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1523 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
1536 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
1524 field_key = Column("field_key", String(250))
1537 field_key = Column("field_key", String(250))
1525 field_label = Column("field_label", String(1024), nullable=False)
1538 field_label = Column("field_label", String(1024), nullable=False)
1526 field_value = Column("field_value", String(10000), nullable=False)
1539 field_value = Column("field_value", String(10000), nullable=False)
1527 field_desc = Column("field_desc", String(1024), nullable=False)
1540 field_desc = Column("field_desc", String(1024), nullable=False)
1528 field_type = Column("field_type", String(255), nullable=False, unique=None)
1541 field_type = Column("field_type", String(255), nullable=False, unique=None)
1529 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1542 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1530
1543
1531 repository = relationship('Repository')
1544 repository = relationship('Repository')
1532
1545
1533 @property
1546 @property
1534 def field_key_prefixed(self):
1547 def field_key_prefixed(self):
1535 return 'ex_%s' % self.field_key
1548 return 'ex_%s' % self.field_key
1536
1549
1537 @classmethod
1550 @classmethod
1538 def un_prefix_key(cls, key):
1551 def un_prefix_key(cls, key):
1539 if key.startswith(cls.PREFIX):
1552 if key.startswith(cls.PREFIX):
1540 return key[len(cls.PREFIX):]
1553 return key[len(cls.PREFIX):]
1541 return key
1554 return key
1542
1555
1543 @classmethod
1556 @classmethod
1544 def get_by_key_name(cls, key, repo):
1557 def get_by_key_name(cls, key, repo):
1545 row = cls.query()\
1558 row = cls.query()\
1546 .filter(cls.repository == repo)\
1559 .filter(cls.repository == repo)\
1547 .filter(cls.field_key == key).scalar()
1560 .filter(cls.field_key == key).scalar()
1548 return row
1561 return row
1549
1562
1550
1563
1551 class Repository(Base, BaseModel):
1564 class Repository(Base, BaseModel):
1552 __tablename__ = 'repositories'
1565 __tablename__ = 'repositories'
1553 __table_args__ = (
1566 __table_args__ = (
1554 Index('r_repo_name_idx', 'repo_name', mysql_length=255),
1567 Index('r_repo_name_idx', 'repo_name', mysql_length=255),
1555 base_table_args,
1568 base_table_args,
1556 )
1569 )
1557 DEFAULT_CLONE_URI = '{scheme}://{user}@{netloc}/{repo}'
1570 DEFAULT_CLONE_URI = '{scheme}://{user}@{netloc}/{repo}'
1558 DEFAULT_CLONE_URI_ID = '{scheme}://{user}@{netloc}/_{repoid}'
1571 DEFAULT_CLONE_URI_ID = '{scheme}://{user}@{netloc}/_{repoid}'
1559 DEFAULT_CLONE_URI_SSH = 'ssh://{sys_user}@{hostname}/{repo}'
1572 DEFAULT_CLONE_URI_SSH = 'ssh://{sys_user}@{hostname}/{repo}'
1560
1573
1561 STATE_CREATED = 'repo_state_created'
1574 STATE_CREATED = 'repo_state_created'
1562 STATE_PENDING = 'repo_state_pending'
1575 STATE_PENDING = 'repo_state_pending'
1563 STATE_ERROR = 'repo_state_error'
1576 STATE_ERROR = 'repo_state_error'
1564
1577
1565 LOCK_AUTOMATIC = 'lock_auto'
1578 LOCK_AUTOMATIC = 'lock_auto'
1566 LOCK_API = 'lock_api'
1579 LOCK_API = 'lock_api'
1567 LOCK_WEB = 'lock_web'
1580 LOCK_WEB = 'lock_web'
1568 LOCK_PULL = 'lock_pull'
1581 LOCK_PULL = 'lock_pull'
1569
1582
1570 NAME_SEP = URL_SEP
1583 NAME_SEP = URL_SEP
1571
1584
1572 repo_id = Column(
1585 repo_id = Column(
1573 "repo_id", Integer(), nullable=False, unique=True, default=None,
1586 "repo_id", Integer(), nullable=False, unique=True, default=None,
1574 primary_key=True)
1587 primary_key=True)
1575 _repo_name = Column(
1588 _repo_name = Column(
1576 "repo_name", Text(), nullable=False, default=None)
1589 "repo_name", Text(), nullable=False, default=None)
1577 _repo_name_hash = Column(
1590 _repo_name_hash = Column(
1578 "repo_name_hash", String(255), nullable=False, unique=True)
1591 "repo_name_hash", String(255), nullable=False, unique=True)
1579 repo_state = Column("repo_state", String(255), nullable=True)
1592 repo_state = Column("repo_state", String(255), nullable=True)
1580
1593
1581 clone_uri = Column(
1594 clone_uri = Column(
1582 "clone_uri", EncryptedTextValue(), nullable=True, unique=False,
1595 "clone_uri", EncryptedTextValue(), nullable=True, unique=False,
1583 default=None)
1596 default=None)
1584 push_uri = Column(
1597 push_uri = Column(
1585 "push_uri", EncryptedTextValue(), nullable=True, unique=False,
1598 "push_uri", EncryptedTextValue(), nullable=True, unique=False,
1586 default=None)
1599 default=None)
1587 repo_type = Column(
1600 repo_type = Column(
1588 "repo_type", String(255), nullable=False, unique=False, default=None)
1601 "repo_type", String(255), nullable=False, unique=False, default=None)
1589 user_id = Column(
1602 user_id = Column(
1590 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
1603 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
1591 unique=False, default=None)
1604 unique=False, default=None)
1592 private = Column(
1605 private = Column(
1593 "private", Boolean(), nullable=True, unique=None, default=None)
1606 "private", Boolean(), nullable=True, unique=None, default=None)
1594 archived = Column(
1607 archived = Column(
1595 "archived", Boolean(), nullable=True, unique=None, default=None)
1608 "archived", Boolean(), nullable=True, unique=None, default=None)
1596 enable_statistics = Column(
1609 enable_statistics = Column(
1597 "statistics", Boolean(), nullable=True, unique=None, default=True)
1610 "statistics", Boolean(), nullable=True, unique=None, default=True)
1598 enable_downloads = Column(
1611 enable_downloads = Column(
1599 "downloads", Boolean(), nullable=True, unique=None, default=True)
1612 "downloads", Boolean(), nullable=True, unique=None, default=True)
1600 description = Column(
1613 description = Column(
1601 "description", String(10000), nullable=True, unique=None, default=None)
1614 "description", String(10000), nullable=True, unique=None, default=None)
1602 created_on = Column(
1615 created_on = Column(
1603 'created_on', DateTime(timezone=False), nullable=True, unique=None,
1616 'created_on', DateTime(timezone=False), nullable=True, unique=None,
1604 default=datetime.datetime.now)
1617 default=datetime.datetime.now)
1605 updated_on = Column(
1618 updated_on = Column(
1606 'updated_on', DateTime(timezone=False), nullable=True, unique=None,
1619 'updated_on', DateTime(timezone=False), nullable=True, unique=None,
1607 default=datetime.datetime.now)
1620 default=datetime.datetime.now)
1608 _landing_revision = Column(
1621 _landing_revision = Column(
1609 "landing_revision", String(255), nullable=False, unique=False,
1622 "landing_revision", String(255), nullable=False, unique=False,
1610 default=None)
1623 default=None)
1611 enable_locking = Column(
1624 enable_locking = Column(
1612 "enable_locking", Boolean(), nullable=False, unique=None,
1625 "enable_locking", Boolean(), nullable=False, unique=None,
1613 default=False)
1626 default=False)
1614 _locked = Column(
1627 _locked = Column(
1615 "locked", String(255), nullable=True, unique=False, default=None)
1628 "locked", String(255), nullable=True, unique=False, default=None)
1616 _changeset_cache = Column(
1629 _changeset_cache = Column(
1617 "changeset_cache", LargeBinary(), nullable=True) # JSON data
1630 "changeset_cache", LargeBinary(), nullable=True) # JSON data
1618
1631
1619 fork_id = Column(
1632 fork_id = Column(
1620 "fork_id", Integer(), ForeignKey('repositories.repo_id'),
1633 "fork_id", Integer(), ForeignKey('repositories.repo_id'),
1621 nullable=True, unique=False, default=None)
1634 nullable=True, unique=False, default=None)
1622 group_id = Column(
1635 group_id = Column(
1623 "group_id", Integer(), ForeignKey('groups.group_id'), nullable=True,
1636 "group_id", Integer(), ForeignKey('groups.group_id'), nullable=True,
1624 unique=False, default=None)
1637 unique=False, default=None)
1625
1638
1626 user = relationship('User', lazy='joined')
1639 user = relationship('User', lazy='joined')
1627 fork = relationship('Repository', remote_side=repo_id, lazy='joined')
1640 fork = relationship('Repository', remote_side=repo_id, lazy='joined')
1628 group = relationship('RepoGroup', lazy='joined')
1641 group = relationship('RepoGroup', lazy='joined')
1629 repo_to_perm = relationship(
1642 repo_to_perm = relationship(
1630 'UserRepoToPerm', cascade='all',
1643 'UserRepoToPerm', cascade='all',
1631 order_by='UserRepoToPerm.repo_to_perm_id')
1644 order_by='UserRepoToPerm.repo_to_perm_id')
1632 users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1645 users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1633 stats = relationship('Statistics', cascade='all', uselist=False)
1646 stats = relationship('Statistics', cascade='all', uselist=False)
1634
1647
1635 followers = relationship(
1648 followers = relationship(
1636 'UserFollowing',
1649 'UserFollowing',
1637 primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id',
1650 primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id',
1638 cascade='all')
1651 cascade='all')
1639 extra_fields = relationship(
1652 extra_fields = relationship(
1640 'RepositoryField', cascade="all, delete, delete-orphan")
1653 'RepositoryField', cascade="all, delete, delete-orphan")
1641 logs = relationship('UserLog')
1654 logs = relationship('UserLog')
1642 comments = relationship(
1655 comments = relationship(
1643 'ChangesetComment', cascade="all, delete, delete-orphan")
1656 'ChangesetComment', cascade="all, delete, delete-orphan")
1644 pull_requests_source = relationship(
1657 pull_requests_source = relationship(
1645 'PullRequest',
1658 'PullRequest',
1646 primaryjoin='PullRequest.source_repo_id==Repository.repo_id',
1659 primaryjoin='PullRequest.source_repo_id==Repository.repo_id',
1647 cascade="all, delete, delete-orphan")
1660 cascade="all, delete, delete-orphan")
1648 pull_requests_target = relationship(
1661 pull_requests_target = relationship(
1649 'PullRequest',
1662 'PullRequest',
1650 primaryjoin='PullRequest.target_repo_id==Repository.repo_id',
1663 primaryjoin='PullRequest.target_repo_id==Repository.repo_id',
1651 cascade="all, delete, delete-orphan")
1664 cascade="all, delete, delete-orphan")
1652 ui = relationship('RepoRhodeCodeUi', cascade="all")
1665 ui = relationship('RepoRhodeCodeUi', cascade="all")
1653 settings = relationship('RepoRhodeCodeSetting', cascade="all")
1666 settings = relationship('RepoRhodeCodeSetting', cascade="all")
1654 integrations = relationship('Integration',
1667 integrations = relationship('Integration',
1655 cascade="all, delete, delete-orphan")
1668 cascade="all, delete, delete-orphan")
1656
1669
1657 scoped_tokens = relationship('UserApiKeys', cascade="all")
1670 scoped_tokens = relationship('UserApiKeys', cascade="all")
1658
1671
1659 def __unicode__(self):
1672 def __unicode__(self):
1660 return u"<%s('%s:%s')>" % (self.__class__.__name__, self.repo_id,
1673 return u"<%s('%s:%s')>" % (self.__class__.__name__, self.repo_id,
1661 safe_unicode(self.repo_name))
1674 safe_unicode(self.repo_name))
1662
1675
1663 @hybrid_property
1676 @hybrid_property
1664 def description_safe(self):
1677 def description_safe(self):
1665 from rhodecode.lib import helpers as h
1678 from rhodecode.lib import helpers as h
1666 return h.escape(self.description)
1679 return h.escape(self.description)
1667
1680
1668 @hybrid_property
1681 @hybrid_property
1669 def landing_rev(self):
1682 def landing_rev(self):
1670 # always should return [rev_type, rev]
1683 # always should return [rev_type, rev]
1671 if self._landing_revision:
1684 if self._landing_revision:
1672 _rev_info = self._landing_revision.split(':')
1685 _rev_info = self._landing_revision.split(':')
1673 if len(_rev_info) < 2:
1686 if len(_rev_info) < 2:
1674 _rev_info.insert(0, 'rev')
1687 _rev_info.insert(0, 'rev')
1675 return [_rev_info[0], _rev_info[1]]
1688 return [_rev_info[0], _rev_info[1]]
1676 return [None, None]
1689 return [None, None]
1677
1690
1678 @landing_rev.setter
1691 @landing_rev.setter
1679 def landing_rev(self, val):
1692 def landing_rev(self, val):
1680 if ':' not in val:
1693 if ':' not in val:
1681 raise ValueError('value must be delimited with `:` and consist '
1694 raise ValueError('value must be delimited with `:` and consist '
1682 'of <rev_type>:<rev>, got %s instead' % val)
1695 'of <rev_type>:<rev>, got %s instead' % val)
1683 self._landing_revision = val
1696 self._landing_revision = val
1684
1697
1685 @hybrid_property
1698 @hybrid_property
1686 def locked(self):
1699 def locked(self):
1687 if self._locked:
1700 if self._locked:
1688 user_id, timelocked, reason = self._locked.split(':')
1701 user_id, timelocked, reason = self._locked.split(':')
1689 lock_values = int(user_id), timelocked, reason
1702 lock_values = int(user_id), timelocked, reason
1690 else:
1703 else:
1691 lock_values = [None, None, None]
1704 lock_values = [None, None, None]
1692 return lock_values
1705 return lock_values
1693
1706
1694 @locked.setter
1707 @locked.setter
1695 def locked(self, val):
1708 def locked(self, val):
1696 if val and isinstance(val, (list, tuple)):
1709 if val and isinstance(val, (list, tuple)):
1697 self._locked = ':'.join(map(str, val))
1710 self._locked = ':'.join(map(str, val))
1698 else:
1711 else:
1699 self._locked = None
1712 self._locked = None
1700
1713
1701 @hybrid_property
1714 @hybrid_property
1702 def changeset_cache(self):
1715 def changeset_cache(self):
1703 from rhodecode.lib.vcs.backends.base import EmptyCommit
1716 from rhodecode.lib.vcs.backends.base import EmptyCommit
1704 dummy = EmptyCommit().__json__()
1717 dummy = EmptyCommit().__json__()
1705 if not self._changeset_cache:
1718 if not self._changeset_cache:
1706 return dummy
1719 return dummy
1707 try:
1720 try:
1708 return json.loads(self._changeset_cache)
1721 return json.loads(self._changeset_cache)
1709 except TypeError:
1722 except TypeError:
1710 return dummy
1723 return dummy
1711 except Exception:
1724 except Exception:
1712 log.error(traceback.format_exc())
1725 log.error(traceback.format_exc())
1713 return dummy
1726 return dummy
1714
1727
1715 @changeset_cache.setter
1728 @changeset_cache.setter
1716 def changeset_cache(self, val):
1729 def changeset_cache(self, val):
1717 try:
1730 try:
1718 self._changeset_cache = json.dumps(val)
1731 self._changeset_cache = json.dumps(val)
1719 except Exception:
1732 except Exception:
1720 log.error(traceback.format_exc())
1733 log.error(traceback.format_exc())
1721
1734
1722 @hybrid_property
1735 @hybrid_property
1723 def repo_name(self):
1736 def repo_name(self):
1724 return self._repo_name
1737 return self._repo_name
1725
1738
1726 @repo_name.setter
1739 @repo_name.setter
1727 def repo_name(self, value):
1740 def repo_name(self, value):
1728 self._repo_name = value
1741 self._repo_name = value
1729 self._repo_name_hash = hashlib.sha1(safe_str(value)).hexdigest()
1742 self._repo_name_hash = hashlib.sha1(safe_str(value)).hexdigest()
1730
1743
1731 @classmethod
1744 @classmethod
1732 def normalize_repo_name(cls, repo_name):
1745 def normalize_repo_name(cls, repo_name):
1733 """
1746 """
1734 Normalizes os specific repo_name to the format internally stored inside
1747 Normalizes os specific repo_name to the format internally stored inside
1735 database using URL_SEP
1748 database using URL_SEP
1736
1749
1737 :param cls:
1750 :param cls:
1738 :param repo_name:
1751 :param repo_name:
1739 """
1752 """
1740 return cls.NAME_SEP.join(repo_name.split(os.sep))
1753 return cls.NAME_SEP.join(repo_name.split(os.sep))
1741
1754
1742 @classmethod
1755 @classmethod
1743 def get_by_repo_name(cls, repo_name, cache=False, identity_cache=False):
1756 def get_by_repo_name(cls, repo_name, cache=False, identity_cache=False):
1744 session = Session()
1757 session = Session()
1745 q = session.query(cls).filter(cls.repo_name == repo_name)
1758 q = session.query(cls).filter(cls.repo_name == repo_name)
1746
1759
1747 if cache:
1760 if cache:
1748 if identity_cache:
1761 if identity_cache:
1749 val = cls.identity_cache(session, 'repo_name', repo_name)
1762 val = cls.identity_cache(session, 'repo_name', repo_name)
1750 if val:
1763 if val:
1751 return val
1764 return val
1752 else:
1765 else:
1753 cache_key = "get_repo_by_name_%s" % _hash_key(repo_name)
1766 cache_key = "get_repo_by_name_%s" % _hash_key(repo_name)
1754 q = q.options(
1767 q = q.options(
1755 FromCache("sql_cache_short", cache_key))
1768 FromCache("sql_cache_short", cache_key))
1756
1769
1757 return q.scalar()
1770 return q.scalar()
1758
1771
1759 @classmethod
1772 @classmethod
1760 def get_by_id_or_repo_name(cls, repoid):
1773 def get_by_id_or_repo_name(cls, repoid):
1761 if isinstance(repoid, (int, long)):
1774 if isinstance(repoid, (int, long)):
1762 try:
1775 try:
1763 repo = cls.get(repoid)
1776 repo = cls.get(repoid)
1764 except ValueError:
1777 except ValueError:
1765 repo = None
1778 repo = None
1766 else:
1779 else:
1767 repo = cls.get_by_repo_name(repoid)
1780 repo = cls.get_by_repo_name(repoid)
1768 return repo
1781 return repo
1769
1782
1770 @classmethod
1783 @classmethod
1771 def get_by_full_path(cls, repo_full_path):
1784 def get_by_full_path(cls, repo_full_path):
1772 repo_name = repo_full_path.split(cls.base_path(), 1)[-1]
1785 repo_name = repo_full_path.split(cls.base_path(), 1)[-1]
1773 repo_name = cls.normalize_repo_name(repo_name)
1786 repo_name = cls.normalize_repo_name(repo_name)
1774 return cls.get_by_repo_name(repo_name.strip(URL_SEP))
1787 return cls.get_by_repo_name(repo_name.strip(URL_SEP))
1775
1788
1776 @classmethod
1789 @classmethod
1777 def get_repo_forks(cls, repo_id):
1790 def get_repo_forks(cls, repo_id):
1778 return cls.query().filter(Repository.fork_id == repo_id)
1791 return cls.query().filter(Repository.fork_id == repo_id)
1779
1792
1780 @classmethod
1793 @classmethod
1781 def base_path(cls):
1794 def base_path(cls):
1782 """
1795 """
1783 Returns base path when all repos are stored
1796 Returns base path when all repos are stored
1784
1797
1785 :param cls:
1798 :param cls:
1786 """
1799 """
1787 q = Session().query(RhodeCodeUi)\
1800 q = Session().query(RhodeCodeUi)\
1788 .filter(RhodeCodeUi.ui_key == cls.NAME_SEP)
1801 .filter(RhodeCodeUi.ui_key == cls.NAME_SEP)
1789 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1802 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1790 return q.one().ui_value
1803 return q.one().ui_value
1791
1804
1792 @classmethod
1805 @classmethod
1793 def get_all_repos(cls, user_id=Optional(None), group_id=Optional(None),
1806 def get_all_repos(cls, user_id=Optional(None), group_id=Optional(None),
1794 case_insensitive=True, archived=False):
1807 case_insensitive=True, archived=False):
1795 q = Repository.query()
1808 q = Repository.query()
1796
1809
1797 if not archived:
1810 if not archived:
1798 q = q.filter(Repository.archived.isnot(true()))
1811 q = q.filter(Repository.archived.isnot(true()))
1799
1812
1800 if not isinstance(user_id, Optional):
1813 if not isinstance(user_id, Optional):
1801 q = q.filter(Repository.user_id == user_id)
1814 q = q.filter(Repository.user_id == user_id)
1802
1815
1803 if not isinstance(group_id, Optional):
1816 if not isinstance(group_id, Optional):
1804 q = q.filter(Repository.group_id == group_id)
1817 q = q.filter(Repository.group_id == group_id)
1805
1818
1806 if case_insensitive:
1819 if case_insensitive:
1807 q = q.order_by(func.lower(Repository.repo_name))
1820 q = q.order_by(func.lower(Repository.repo_name))
1808 else:
1821 else:
1809 q = q.order_by(Repository.repo_name)
1822 q = q.order_by(Repository.repo_name)
1810
1823
1811 return q.all()
1824 return q.all()
1812
1825
1813 @property
1826 @property
1814 def forks(self):
1827 def forks(self):
1815 """
1828 """
1816 Return forks of this repo
1829 Return forks of this repo
1817 """
1830 """
1818 return Repository.get_repo_forks(self.repo_id)
1831 return Repository.get_repo_forks(self.repo_id)
1819
1832
1820 @property
1833 @property
1821 def parent(self):
1834 def parent(self):
1822 """
1835 """
1823 Returns fork parent
1836 Returns fork parent
1824 """
1837 """
1825 return self.fork
1838 return self.fork
1826
1839
1827 @property
1840 @property
1828 def just_name(self):
1841 def just_name(self):
1829 return self.repo_name.split(self.NAME_SEP)[-1]
1842 return self.repo_name.split(self.NAME_SEP)[-1]
1830
1843
1831 @property
1844 @property
1832 def groups_with_parents(self):
1845 def groups_with_parents(self):
1833 groups = []
1846 groups = []
1834 if self.group is None:
1847 if self.group is None:
1835 return groups
1848 return groups
1836
1849
1837 cur_gr = self.group
1850 cur_gr = self.group
1838 groups.insert(0, cur_gr)
1851 groups.insert(0, cur_gr)
1839 while 1:
1852 while 1:
1840 gr = getattr(cur_gr, 'parent_group', None)
1853 gr = getattr(cur_gr, 'parent_group', None)
1841 cur_gr = cur_gr.parent_group
1854 cur_gr = cur_gr.parent_group
1842 if gr is None:
1855 if gr is None:
1843 break
1856 break
1844 groups.insert(0, gr)
1857 groups.insert(0, gr)
1845
1858
1846 return groups
1859 return groups
1847
1860
1848 @property
1861 @property
1849 def groups_and_repo(self):
1862 def groups_and_repo(self):
1850 return self.groups_with_parents, self
1863 return self.groups_with_parents, self
1851
1864
1852 @LazyProperty
1865 @LazyProperty
1853 def repo_path(self):
1866 def repo_path(self):
1854 """
1867 """
1855 Returns base full path for that repository means where it actually
1868 Returns base full path for that repository means where it actually
1856 exists on a filesystem
1869 exists on a filesystem
1857 """
1870 """
1858 q = Session().query(RhodeCodeUi).filter(
1871 q = Session().query(RhodeCodeUi).filter(
1859 RhodeCodeUi.ui_key == self.NAME_SEP)
1872 RhodeCodeUi.ui_key == self.NAME_SEP)
1860 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1873 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1861 return q.one().ui_value
1874 return q.one().ui_value
1862
1875
1863 @property
1876 @property
1864 def repo_full_path(self):
1877 def repo_full_path(self):
1865 p = [self.repo_path]
1878 p = [self.repo_path]
1866 # we need to split the name by / since this is how we store the
1879 # we need to split the name by / since this is how we store the
1867 # names in the database, but that eventually needs to be converted
1880 # names in the database, but that eventually needs to be converted
1868 # into a valid system path
1881 # into a valid system path
1869 p += self.repo_name.split(self.NAME_SEP)
1882 p += self.repo_name.split(self.NAME_SEP)
1870 return os.path.join(*map(safe_unicode, p))
1883 return os.path.join(*map(safe_unicode, p))
1871
1884
1872 @property
1885 @property
1873 def cache_keys(self):
1886 def cache_keys(self):
1874 """
1887 """
1875 Returns associated cache keys for that repo
1888 Returns associated cache keys for that repo
1876 """
1889 """
1877 invalidation_namespace = CacheKey.REPO_INVALIDATION_NAMESPACE.format(
1890 invalidation_namespace = CacheKey.REPO_INVALIDATION_NAMESPACE.format(
1878 repo_id=self.repo_id)
1891 repo_id=self.repo_id)
1879 return CacheKey.query()\
1892 return CacheKey.query()\
1880 .filter(CacheKey.cache_args == invalidation_namespace)\
1893 .filter(CacheKey.cache_args == invalidation_namespace)\
1881 .order_by(CacheKey.cache_key)\
1894 .order_by(CacheKey.cache_key)\
1882 .all()
1895 .all()
1883
1896
1884 @property
1897 @property
1885 def cached_diffs_relative_dir(self):
1898 def cached_diffs_relative_dir(self):
1886 """
1899 """
1887 Return a relative to the repository store path of cached diffs
1900 Return a relative to the repository store path of cached diffs
1888 used for safe display for users, who shouldn't know the absolute store
1901 used for safe display for users, who shouldn't know the absolute store
1889 path
1902 path
1890 """
1903 """
1891 return os.path.join(
1904 return os.path.join(
1892 os.path.dirname(self.repo_name),
1905 os.path.dirname(self.repo_name),
1893 self.cached_diffs_dir.split(os.path.sep)[-1])
1906 self.cached_diffs_dir.split(os.path.sep)[-1])
1894
1907
1895 @property
1908 @property
1896 def cached_diffs_dir(self):
1909 def cached_diffs_dir(self):
1897 path = self.repo_full_path
1910 path = self.repo_full_path
1898 return os.path.join(
1911 return os.path.join(
1899 os.path.dirname(path),
1912 os.path.dirname(path),
1900 '.__shadow_diff_cache_repo_{}'.format(self.repo_id))
1913 '.__shadow_diff_cache_repo_{}'.format(self.repo_id))
1901
1914
1902 def cached_diffs(self):
1915 def cached_diffs(self):
1903 diff_cache_dir = self.cached_diffs_dir
1916 diff_cache_dir = self.cached_diffs_dir
1904 if os.path.isdir(diff_cache_dir):
1917 if os.path.isdir(diff_cache_dir):
1905 return os.listdir(diff_cache_dir)
1918 return os.listdir(diff_cache_dir)
1906 return []
1919 return []
1907
1920
1908 def shadow_repos(self):
1921 def shadow_repos(self):
1909 shadow_repos_pattern = '.__shadow_repo_{}'.format(self.repo_id)
1922 shadow_repos_pattern = '.__shadow_repo_{}'.format(self.repo_id)
1910 return [
1923 return [
1911 x for x in os.listdir(os.path.dirname(self.repo_full_path))
1924 x for x in os.listdir(os.path.dirname(self.repo_full_path))
1912 if x.startswith(shadow_repos_pattern)]
1925 if x.startswith(shadow_repos_pattern)]
1913
1926
1914 def get_new_name(self, repo_name):
1927 def get_new_name(self, repo_name):
1915 """
1928 """
1916 returns new full repository name based on assigned group and new new
1929 returns new full repository name based on assigned group and new new
1917
1930
1918 :param group_name:
1931 :param group_name:
1919 """
1932 """
1920 path_prefix = self.group.full_path_splitted if self.group else []
1933 path_prefix = self.group.full_path_splitted if self.group else []
1921 return self.NAME_SEP.join(path_prefix + [repo_name])
1934 return self.NAME_SEP.join(path_prefix + [repo_name])
1922
1935
1923 @property
1936 @property
1924 def _config(self):
1937 def _config(self):
1925 """
1938 """
1926 Returns db based config object.
1939 Returns db based config object.
1927 """
1940 """
1928 from rhodecode.lib.utils import make_db_config
1941 from rhodecode.lib.utils import make_db_config
1929 return make_db_config(clear_session=False, repo=self)
1942 return make_db_config(clear_session=False, repo=self)
1930
1943
1931 def permissions(self, with_admins=True, with_owner=True):
1944 def permissions(self, with_admins=True, with_owner=True,
1945 expand_from_user_groups=False):
1932 """
1946 """
1933 Permissions for repositories
1947 Permissions for repositories
1934 """
1948 """
1935 _admin_perm = 'repository.admin'
1949 _admin_perm = 'repository.admin'
1936
1950
1937 owner_row = []
1951 owner_row = []
1938 if with_owner:
1952 if with_owner:
1939 usr = AttributeDict(self.user.get_dict())
1953 usr = AttributeDict(self.user.get_dict())
1940 usr.owner_row = True
1954 usr.owner_row = True
1941 usr.permission = _admin_perm
1955 usr.permission = _admin_perm
1942 usr.permission_id = None
1956 usr.permission_id = None
1943 owner_row.append(usr)
1957 owner_row.append(usr)
1944
1958
1945 super_admin_ids = []
1959 super_admin_ids = []
1946 super_admin_rows = []
1960 super_admin_rows = []
1947 if with_admins:
1961 if with_admins:
1948 for usr in User.get_all_super_admins():
1962 for usr in User.get_all_super_admins():
1949 super_admin_ids.append(usr.user_id)
1963 super_admin_ids.append(usr.user_id)
1950 # if this admin is also owner, don't double the record
1964 # if this admin is also owner, don't double the record
1951 if usr.user_id == owner_row[0].user_id:
1965 if usr.user_id == owner_row[0].user_id:
1952 owner_row[0].admin_row = True
1966 owner_row[0].admin_row = True
1953 else:
1967 else:
1954 usr = AttributeDict(usr.get_dict())
1968 usr = AttributeDict(usr.get_dict())
1955 usr.admin_row = True
1969 usr.admin_row = True
1956 usr.permission = _admin_perm
1970 usr.permission = _admin_perm
1957 usr.permission_id = None
1971 usr.permission_id = None
1958 super_admin_rows.append(usr)
1972 super_admin_rows.append(usr)
1959
1973
1960 q = UserRepoToPerm.query().filter(UserRepoToPerm.repository == self)
1974 q = UserRepoToPerm.query().filter(UserRepoToPerm.repository == self)
1961 q = q.options(joinedload(UserRepoToPerm.repository),
1975 q = q.options(joinedload(UserRepoToPerm.repository),
1962 joinedload(UserRepoToPerm.user),
1976 joinedload(UserRepoToPerm.user),
1963 joinedload(UserRepoToPerm.permission),)
1977 joinedload(UserRepoToPerm.permission),)
1964
1978
1965 # get owners and admins and permissions. We do a trick of re-writing
1979 # get owners and admins and permissions. We do a trick of re-writing
1966 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1980 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1967 # has a global reference and changing one object propagates to all
1981 # has a global reference and changing one object propagates to all
1968 # others. This means if admin is also an owner admin_row that change
1982 # others. This means if admin is also an owner admin_row that change
1969 # would propagate to both objects
1983 # would propagate to both objects
1970 perm_rows = []
1984 perm_rows = []
1971 for _usr in q.all():
1985 for _usr in q.all():
1972 usr = AttributeDict(_usr.user.get_dict())
1986 usr = AttributeDict(_usr.user.get_dict())
1973 # if this user is also owner/admin, mark as duplicate record
1987 # if this user is also owner/admin, mark as duplicate record
1974 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
1988 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
1975 usr.duplicate_perm = True
1989 usr.duplicate_perm = True
1976 # also check if this permission is maybe used by branch_permissions
1990 # also check if this permission is maybe used by branch_permissions
1977 if _usr.branch_perm_entry:
1991 if _usr.branch_perm_entry:
1978 usr.branch_rules = [x.branch_rule_id for x in _usr.branch_perm_entry]
1992 usr.branch_rules = [x.branch_rule_id for x in _usr.branch_perm_entry]
1979
1993
1980 usr.permission = _usr.permission.permission_name
1994 usr.permission = _usr.permission.permission_name
1981 usr.permission_id = _usr.repo_to_perm_id
1995 usr.permission_id = _usr.repo_to_perm_id
1982 perm_rows.append(usr)
1996 perm_rows.append(usr)
1983
1997
1984 # filter the perm rows by 'default' first and then sort them by
1998 # filter the perm rows by 'default' first and then sort them by
1985 # admin,write,read,none permissions sorted again alphabetically in
1999 # admin,write,read,none permissions sorted again alphabetically in
1986 # each group
2000 # each group
1987 perm_rows = sorted(perm_rows, key=display_user_sort)
2001 perm_rows = sorted(perm_rows, key=display_user_sort)
1988
2002
1989 return super_admin_rows + owner_row + perm_rows
2003 user_groups_rows = []
1990
2004 if expand_from_user_groups:
1991 def permission_user_groups(self):
2005 for ug in self.permission_user_groups(with_members=True):
1992 q = UserGroupRepoToPerm.query().filter(
2006 for user_data in ug.members:
1993 UserGroupRepoToPerm.repository == self)
2007 user_groups_rows.append(user_data)
2008
2009 return super_admin_rows + owner_row + perm_rows + user_groups_rows
2010
2011 def permission_user_groups(self, with_members=True):
2012 q = UserGroupRepoToPerm.query()\
2013 .filter(UserGroupRepoToPerm.repository == self)
1994 q = q.options(joinedload(UserGroupRepoToPerm.repository),
2014 q = q.options(joinedload(UserGroupRepoToPerm.repository),
1995 joinedload(UserGroupRepoToPerm.users_group),
2015 joinedload(UserGroupRepoToPerm.users_group),
1996 joinedload(UserGroupRepoToPerm.permission),)
2016 joinedload(UserGroupRepoToPerm.permission),)
1997
2017
1998 perm_rows = []
2018 perm_rows = []
1999 for _user_group in q.all():
2019 for _user_group in q.all():
2000 usr = AttributeDict(_user_group.users_group.get_dict())
2020 entry = AttributeDict(_user_group.users_group.get_dict())
2001 usr.permission = _user_group.permission.permission_name
2021 entry.permission = _user_group.permission.permission_name
2002 perm_rows.append(usr)
2022 if with_members:
2023 entry.members = [x.user.get_dict()
2024 for x in _user_group.users_group.members]
2025 perm_rows.append(entry)
2003
2026
2004 perm_rows = sorted(perm_rows, key=display_user_group_sort)
2027 perm_rows = sorted(perm_rows, key=display_user_group_sort)
2005 return perm_rows
2028 return perm_rows
2006
2029
2007 def get_api_data(self, include_secrets=False):
2030 def get_api_data(self, include_secrets=False):
2008 """
2031 """
2009 Common function for generating repo api data
2032 Common function for generating repo api data
2010
2033
2011 :param include_secrets: See :meth:`User.get_api_data`.
2034 :param include_secrets: See :meth:`User.get_api_data`.
2012
2035
2013 """
2036 """
2014 # TODO: mikhail: Here there is an anti-pattern, we probably need to
2037 # TODO: mikhail: Here there is an anti-pattern, we probably need to
2015 # move this methods on models level.
2038 # move this methods on models level.
2016 from rhodecode.model.settings import SettingsModel
2039 from rhodecode.model.settings import SettingsModel
2017 from rhodecode.model.repo import RepoModel
2040 from rhodecode.model.repo import RepoModel
2018
2041
2019 repo = self
2042 repo = self
2020 _user_id, _time, _reason = self.locked
2043 _user_id, _time, _reason = self.locked
2021
2044
2022 data = {
2045 data = {
2023 'repo_id': repo.repo_id,
2046 'repo_id': repo.repo_id,
2024 'repo_name': repo.repo_name,
2047 'repo_name': repo.repo_name,
2025 'repo_type': repo.repo_type,
2048 'repo_type': repo.repo_type,
2026 'clone_uri': repo.clone_uri or '',
2049 'clone_uri': repo.clone_uri or '',
2027 'push_uri': repo.push_uri or '',
2050 'push_uri': repo.push_uri or '',
2028 'url': RepoModel().get_url(self),
2051 'url': RepoModel().get_url(self),
2029 'private': repo.private,
2052 'private': repo.private,
2030 'created_on': repo.created_on,
2053 'created_on': repo.created_on,
2031 'description': repo.description_safe,
2054 'description': repo.description_safe,
2032 'landing_rev': repo.landing_rev,
2055 'landing_rev': repo.landing_rev,
2033 'owner': repo.user.username,
2056 'owner': repo.user.username,
2034 'fork_of': repo.fork.repo_name if repo.fork else None,
2057 'fork_of': repo.fork.repo_name if repo.fork else None,
2035 'fork_of_id': repo.fork.repo_id if repo.fork else None,
2058 'fork_of_id': repo.fork.repo_id if repo.fork else None,
2036 'enable_statistics': repo.enable_statistics,
2059 'enable_statistics': repo.enable_statistics,
2037 'enable_locking': repo.enable_locking,
2060 'enable_locking': repo.enable_locking,
2038 'enable_downloads': repo.enable_downloads,
2061 'enable_downloads': repo.enable_downloads,
2039 'last_changeset': repo.changeset_cache,
2062 'last_changeset': repo.changeset_cache,
2040 'locked_by': User.get(_user_id).get_api_data(
2063 'locked_by': User.get(_user_id).get_api_data(
2041 include_secrets=include_secrets) if _user_id else None,
2064 include_secrets=include_secrets) if _user_id else None,
2042 'locked_date': time_to_datetime(_time) if _time else None,
2065 'locked_date': time_to_datetime(_time) if _time else None,
2043 'lock_reason': _reason if _reason else None,
2066 'lock_reason': _reason if _reason else None,
2044 }
2067 }
2045
2068
2046 # TODO: mikhail: should be per-repo settings here
2069 # TODO: mikhail: should be per-repo settings here
2047 rc_config = SettingsModel().get_all_settings()
2070 rc_config = SettingsModel().get_all_settings()
2048 repository_fields = str2bool(
2071 repository_fields = str2bool(
2049 rc_config.get('rhodecode_repository_fields'))
2072 rc_config.get('rhodecode_repository_fields'))
2050 if repository_fields:
2073 if repository_fields:
2051 for f in self.extra_fields:
2074 for f in self.extra_fields:
2052 data[f.field_key_prefixed] = f.field_value
2075 data[f.field_key_prefixed] = f.field_value
2053
2076
2054 return data
2077 return data
2055
2078
2056 @classmethod
2079 @classmethod
2057 def lock(cls, repo, user_id, lock_time=None, lock_reason=None):
2080 def lock(cls, repo, user_id, lock_time=None, lock_reason=None):
2058 if not lock_time:
2081 if not lock_time:
2059 lock_time = time.time()
2082 lock_time = time.time()
2060 if not lock_reason:
2083 if not lock_reason:
2061 lock_reason = cls.LOCK_AUTOMATIC
2084 lock_reason = cls.LOCK_AUTOMATIC
2062 repo.locked = [user_id, lock_time, lock_reason]
2085 repo.locked = [user_id, lock_time, lock_reason]
2063 Session().add(repo)
2086 Session().add(repo)
2064 Session().commit()
2087 Session().commit()
2065
2088
2066 @classmethod
2089 @classmethod
2067 def unlock(cls, repo):
2090 def unlock(cls, repo):
2068 repo.locked = None
2091 repo.locked = None
2069 Session().add(repo)
2092 Session().add(repo)
2070 Session().commit()
2093 Session().commit()
2071
2094
2072 @classmethod
2095 @classmethod
2073 def getlock(cls, repo):
2096 def getlock(cls, repo):
2074 return repo.locked
2097 return repo.locked
2075
2098
2076 def is_user_lock(self, user_id):
2099 def is_user_lock(self, user_id):
2077 if self.lock[0]:
2100 if self.lock[0]:
2078 lock_user_id = safe_int(self.lock[0])
2101 lock_user_id = safe_int(self.lock[0])
2079 user_id = safe_int(user_id)
2102 user_id = safe_int(user_id)
2080 # both are ints, and they are equal
2103 # both are ints, and they are equal
2081 return all([lock_user_id, user_id]) and lock_user_id == user_id
2104 return all([lock_user_id, user_id]) and lock_user_id == user_id
2082
2105
2083 return False
2106 return False
2084
2107
2085 def get_locking_state(self, action, user_id, only_when_enabled=True):
2108 def get_locking_state(self, action, user_id, only_when_enabled=True):
2086 """
2109 """
2087 Checks locking on this repository, if locking is enabled and lock is
2110 Checks locking on this repository, if locking is enabled and lock is
2088 present returns a tuple of make_lock, locked, locked_by.
2111 present returns a tuple of make_lock, locked, locked_by.
2089 make_lock can have 3 states None (do nothing) True, make lock
2112 make_lock can have 3 states None (do nothing) True, make lock
2090 False release lock, This value is later propagated to hooks, which
2113 False release lock, This value is later propagated to hooks, which
2091 do the locking. Think about this as signals passed to hooks what to do.
2114 do the locking. Think about this as signals passed to hooks what to do.
2092
2115
2093 """
2116 """
2094 # TODO: johbo: This is part of the business logic and should be moved
2117 # TODO: johbo: This is part of the business logic and should be moved
2095 # into the RepositoryModel.
2118 # into the RepositoryModel.
2096
2119
2097 if action not in ('push', 'pull'):
2120 if action not in ('push', 'pull'):
2098 raise ValueError("Invalid action value: %s" % repr(action))
2121 raise ValueError("Invalid action value: %s" % repr(action))
2099
2122
2100 # defines if locked error should be thrown to user
2123 # defines if locked error should be thrown to user
2101 currently_locked = False
2124 currently_locked = False
2102 # defines if new lock should be made, tri-state
2125 # defines if new lock should be made, tri-state
2103 make_lock = None
2126 make_lock = None
2104 repo = self
2127 repo = self
2105 user = User.get(user_id)
2128 user = User.get(user_id)
2106
2129
2107 lock_info = repo.locked
2130 lock_info = repo.locked
2108
2131
2109 if repo and (repo.enable_locking or not only_when_enabled):
2132 if repo and (repo.enable_locking or not only_when_enabled):
2110 if action == 'push':
2133 if action == 'push':
2111 # check if it's already locked !, if it is compare users
2134 # check if it's already locked !, if it is compare users
2112 locked_by_user_id = lock_info[0]
2135 locked_by_user_id = lock_info[0]
2113 if user.user_id == locked_by_user_id:
2136 if user.user_id == locked_by_user_id:
2114 log.debug(
2137 log.debug(
2115 'Got `push` action from user %s, now unlocking', user)
2138 'Got `push` action from user %s, now unlocking', user)
2116 # unlock if we have push from user who locked
2139 # unlock if we have push from user who locked
2117 make_lock = False
2140 make_lock = False
2118 else:
2141 else:
2119 # we're not the same user who locked, ban with
2142 # we're not the same user who locked, ban with
2120 # code defined in settings (default is 423 HTTP Locked) !
2143 # code defined in settings (default is 423 HTTP Locked) !
2121 log.debug('Repo %s is currently locked by %s', repo, user)
2144 log.debug('Repo %s is currently locked by %s', repo, user)
2122 currently_locked = True
2145 currently_locked = True
2123 elif action == 'pull':
2146 elif action == 'pull':
2124 # [0] user [1] date
2147 # [0] user [1] date
2125 if lock_info[0] and lock_info[1]:
2148 if lock_info[0] and lock_info[1]:
2126 log.debug('Repo %s is currently locked by %s', repo, user)
2149 log.debug('Repo %s is currently locked by %s', repo, user)
2127 currently_locked = True
2150 currently_locked = True
2128 else:
2151 else:
2129 log.debug('Setting lock on repo %s by %s', repo, user)
2152 log.debug('Setting lock on repo %s by %s', repo, user)
2130 make_lock = True
2153 make_lock = True
2131
2154
2132 else:
2155 else:
2133 log.debug('Repository %s do not have locking enabled', repo)
2156 log.debug('Repository %s do not have locking enabled', repo)
2134
2157
2135 log.debug('FINAL locking values make_lock:%s,locked:%s,locked_by:%s',
2158 log.debug('FINAL locking values make_lock:%s,locked:%s,locked_by:%s',
2136 make_lock, currently_locked, lock_info)
2159 make_lock, currently_locked, lock_info)
2137
2160
2138 from rhodecode.lib.auth import HasRepoPermissionAny
2161 from rhodecode.lib.auth import HasRepoPermissionAny
2139 perm_check = HasRepoPermissionAny('repository.write', 'repository.admin')
2162 perm_check = HasRepoPermissionAny('repository.write', 'repository.admin')
2140 if make_lock and not perm_check(repo_name=repo.repo_name, user=user):
2163 if make_lock and not perm_check(repo_name=repo.repo_name, user=user):
2141 # if we don't have at least write permission we cannot make a lock
2164 # if we don't have at least write permission we cannot make a lock
2142 log.debug('lock state reset back to FALSE due to lack '
2165 log.debug('lock state reset back to FALSE due to lack '
2143 'of at least read permission')
2166 'of at least read permission')
2144 make_lock = False
2167 make_lock = False
2145
2168
2146 return make_lock, currently_locked, lock_info
2169 return make_lock, currently_locked, lock_info
2147
2170
2148 @property
2171 @property
2149 def last_db_change(self):
2172 def last_db_change(self):
2150 return self.updated_on
2173 return self.updated_on
2151
2174
2152 @property
2175 @property
2153 def clone_uri_hidden(self):
2176 def clone_uri_hidden(self):
2154 clone_uri = self.clone_uri
2177 clone_uri = self.clone_uri
2155 if clone_uri:
2178 if clone_uri:
2156 import urlobject
2179 import urlobject
2157 url_obj = urlobject.URLObject(cleaned_uri(clone_uri))
2180 url_obj = urlobject.URLObject(cleaned_uri(clone_uri))
2158 if url_obj.password:
2181 if url_obj.password:
2159 clone_uri = url_obj.with_password('*****')
2182 clone_uri = url_obj.with_password('*****')
2160 return clone_uri
2183 return clone_uri
2161
2184
2162 @property
2185 @property
2163 def push_uri_hidden(self):
2186 def push_uri_hidden(self):
2164 push_uri = self.push_uri
2187 push_uri = self.push_uri
2165 if push_uri:
2188 if push_uri:
2166 import urlobject
2189 import urlobject
2167 url_obj = urlobject.URLObject(cleaned_uri(push_uri))
2190 url_obj = urlobject.URLObject(cleaned_uri(push_uri))
2168 if url_obj.password:
2191 if url_obj.password:
2169 push_uri = url_obj.with_password('*****')
2192 push_uri = url_obj.with_password('*****')
2170 return push_uri
2193 return push_uri
2171
2194
2172 def clone_url(self, **override):
2195 def clone_url(self, **override):
2173 from rhodecode.model.settings import SettingsModel
2196 from rhodecode.model.settings import SettingsModel
2174
2197
2175 uri_tmpl = None
2198 uri_tmpl = None
2176 if 'with_id' in override:
2199 if 'with_id' in override:
2177 uri_tmpl = self.DEFAULT_CLONE_URI_ID
2200 uri_tmpl = self.DEFAULT_CLONE_URI_ID
2178 del override['with_id']
2201 del override['with_id']
2179
2202
2180 if 'uri_tmpl' in override:
2203 if 'uri_tmpl' in override:
2181 uri_tmpl = override['uri_tmpl']
2204 uri_tmpl = override['uri_tmpl']
2182 del override['uri_tmpl']
2205 del override['uri_tmpl']
2183
2206
2184 ssh = False
2207 ssh = False
2185 if 'ssh' in override:
2208 if 'ssh' in override:
2186 ssh = True
2209 ssh = True
2187 del override['ssh']
2210 del override['ssh']
2188
2211
2189 # we didn't override our tmpl from **overrides
2212 # we didn't override our tmpl from **overrides
2190 if not uri_tmpl:
2213 if not uri_tmpl:
2191 rc_config = SettingsModel().get_all_settings(cache=True)
2214 rc_config = SettingsModel().get_all_settings(cache=True)
2192 if ssh:
2215 if ssh:
2193 uri_tmpl = rc_config.get(
2216 uri_tmpl = rc_config.get(
2194 'rhodecode_clone_uri_ssh_tmpl') or self.DEFAULT_CLONE_URI_SSH
2217 'rhodecode_clone_uri_ssh_tmpl') or self.DEFAULT_CLONE_URI_SSH
2195 else:
2218 else:
2196 uri_tmpl = rc_config.get(
2219 uri_tmpl = rc_config.get(
2197 'rhodecode_clone_uri_tmpl') or self.DEFAULT_CLONE_URI
2220 'rhodecode_clone_uri_tmpl') or self.DEFAULT_CLONE_URI
2198
2221
2199 request = get_current_request()
2222 request = get_current_request()
2200 return get_clone_url(request=request,
2223 return get_clone_url(request=request,
2201 uri_tmpl=uri_tmpl,
2224 uri_tmpl=uri_tmpl,
2202 repo_name=self.repo_name,
2225 repo_name=self.repo_name,
2203 repo_id=self.repo_id, **override)
2226 repo_id=self.repo_id, **override)
2204
2227
2205 def set_state(self, state):
2228 def set_state(self, state):
2206 self.repo_state = state
2229 self.repo_state = state
2207 Session().add(self)
2230 Session().add(self)
2208 #==========================================================================
2231 #==========================================================================
2209 # SCM PROPERTIES
2232 # SCM PROPERTIES
2210 #==========================================================================
2233 #==========================================================================
2211
2234
2212 def get_commit(self, commit_id=None, commit_idx=None, pre_load=None):
2235 def get_commit(self, commit_id=None, commit_idx=None, pre_load=None):
2213 return get_commit_safe(
2236 return get_commit_safe(
2214 self.scm_instance(), commit_id, commit_idx, pre_load=pre_load)
2237 self.scm_instance(), commit_id, commit_idx, pre_load=pre_load)
2215
2238
2216 def get_changeset(self, rev=None, pre_load=None):
2239 def get_changeset(self, rev=None, pre_load=None):
2217 warnings.warn("Use get_commit", DeprecationWarning)
2240 warnings.warn("Use get_commit", DeprecationWarning)
2218 commit_id = None
2241 commit_id = None
2219 commit_idx = None
2242 commit_idx = None
2220 if isinstance(rev, basestring):
2243 if isinstance(rev, basestring):
2221 commit_id = rev
2244 commit_id = rev
2222 else:
2245 else:
2223 commit_idx = rev
2246 commit_idx = rev
2224 return self.get_commit(commit_id=commit_id, commit_idx=commit_idx,
2247 return self.get_commit(commit_id=commit_id, commit_idx=commit_idx,
2225 pre_load=pre_load)
2248 pre_load=pre_load)
2226
2249
2227 def get_landing_commit(self):
2250 def get_landing_commit(self):
2228 """
2251 """
2229 Returns landing commit, or if that doesn't exist returns the tip
2252 Returns landing commit, or if that doesn't exist returns the tip
2230 """
2253 """
2231 _rev_type, _rev = self.landing_rev
2254 _rev_type, _rev = self.landing_rev
2232 commit = self.get_commit(_rev)
2255 commit = self.get_commit(_rev)
2233 if isinstance(commit, EmptyCommit):
2256 if isinstance(commit, EmptyCommit):
2234 return self.get_commit()
2257 return self.get_commit()
2235 return commit
2258 return commit
2236
2259
2237 def update_commit_cache(self, cs_cache=None, config=None):
2260 def update_commit_cache(self, cs_cache=None, config=None):
2238 """
2261 """
2239 Update cache of last changeset for repository, keys should be::
2262 Update cache of last changeset for repository, keys should be::
2240
2263
2241 short_id
2264 short_id
2242 raw_id
2265 raw_id
2243 revision
2266 revision
2244 parents
2267 parents
2245 message
2268 message
2246 date
2269 date
2247 author
2270 author
2248
2271
2249 :param cs_cache:
2272 :param cs_cache:
2250 """
2273 """
2251 from rhodecode.lib.vcs.backends.base import BaseChangeset
2274 from rhodecode.lib.vcs.backends.base import BaseChangeset
2252 if cs_cache is None:
2275 if cs_cache is None:
2253 # use no-cache version here
2276 # use no-cache version here
2254 scm_repo = self.scm_instance(cache=False, config=config)
2277 scm_repo = self.scm_instance(cache=False, config=config)
2255
2278
2256 empty = scm_repo.is_empty()
2279 empty = scm_repo.is_empty()
2257 if not empty:
2280 if not empty:
2258 cs_cache = scm_repo.get_commit(
2281 cs_cache = scm_repo.get_commit(
2259 pre_load=["author", "date", "message", "parents"])
2282 pre_load=["author", "date", "message", "parents"])
2260 else:
2283 else:
2261 cs_cache = EmptyCommit()
2284 cs_cache = EmptyCommit()
2262
2285
2263 if isinstance(cs_cache, BaseChangeset):
2286 if isinstance(cs_cache, BaseChangeset):
2264 cs_cache = cs_cache.__json__()
2287 cs_cache = cs_cache.__json__()
2265
2288
2266 def is_outdated(new_cs_cache):
2289 def is_outdated(new_cs_cache):
2267 if (new_cs_cache['raw_id'] != self.changeset_cache['raw_id'] or
2290 if (new_cs_cache['raw_id'] != self.changeset_cache['raw_id'] or
2268 new_cs_cache['revision'] != self.changeset_cache['revision']):
2291 new_cs_cache['revision'] != self.changeset_cache['revision']):
2269 return True
2292 return True
2270 return False
2293 return False
2271
2294
2272 # check if we have maybe already latest cached revision
2295 # check if we have maybe already latest cached revision
2273 if is_outdated(cs_cache) or not self.changeset_cache:
2296 if is_outdated(cs_cache) or not self.changeset_cache:
2274 _default = datetime.datetime.utcnow()
2297 _default = datetime.datetime.utcnow()
2275 last_change = cs_cache.get('date') or _default
2298 last_change = cs_cache.get('date') or _default
2276 if self.updated_on and self.updated_on > last_change:
2299 if self.updated_on and self.updated_on > last_change:
2277 # we check if last update is newer than the new value
2300 # we check if last update is newer than the new value
2278 # if yes, we use the current timestamp instead. Imagine you get
2301 # if yes, we use the current timestamp instead. Imagine you get
2279 # old commit pushed 1y ago, we'd set last update 1y to ago.
2302 # old commit pushed 1y ago, we'd set last update 1y to ago.
2280 last_change = _default
2303 last_change = _default
2281 log.debug('updated repo %s with new cs cache %s',
2304 log.debug('updated repo %s with new cs cache %s',
2282 self.repo_name, cs_cache)
2305 self.repo_name, cs_cache)
2283 self.updated_on = last_change
2306 self.updated_on = last_change
2284 self.changeset_cache = cs_cache
2307 self.changeset_cache = cs_cache
2285 Session().add(self)
2308 Session().add(self)
2286 Session().commit()
2309 Session().commit()
2287 else:
2310 else:
2288 log.debug('Skipping update_commit_cache for repo:`%s` '
2311 log.debug('Skipping update_commit_cache for repo:`%s` '
2289 'commit already with latest changes', self.repo_name)
2312 'commit already with latest changes', self.repo_name)
2290
2313
2291 @property
2314 @property
2292 def tip(self):
2315 def tip(self):
2293 return self.get_commit('tip')
2316 return self.get_commit('tip')
2294
2317
2295 @property
2318 @property
2296 def author(self):
2319 def author(self):
2297 return self.tip.author
2320 return self.tip.author
2298
2321
2299 @property
2322 @property
2300 def last_change(self):
2323 def last_change(self):
2301 return self.scm_instance().last_change
2324 return self.scm_instance().last_change
2302
2325
2303 def get_comments(self, revisions=None):
2326 def get_comments(self, revisions=None):
2304 """
2327 """
2305 Returns comments for this repository grouped by revisions
2328 Returns comments for this repository grouped by revisions
2306
2329
2307 :param revisions: filter query by revisions only
2330 :param revisions: filter query by revisions only
2308 """
2331 """
2309 cmts = ChangesetComment.query()\
2332 cmts = ChangesetComment.query()\
2310 .filter(ChangesetComment.repo == self)
2333 .filter(ChangesetComment.repo == self)
2311 if revisions:
2334 if revisions:
2312 cmts = cmts.filter(ChangesetComment.revision.in_(revisions))
2335 cmts = cmts.filter(ChangesetComment.revision.in_(revisions))
2313 grouped = collections.defaultdict(list)
2336 grouped = collections.defaultdict(list)
2314 for cmt in cmts.all():
2337 for cmt in cmts.all():
2315 grouped[cmt.revision].append(cmt)
2338 grouped[cmt.revision].append(cmt)
2316 return grouped
2339 return grouped
2317
2340
2318 def statuses(self, revisions=None):
2341 def statuses(self, revisions=None):
2319 """
2342 """
2320 Returns statuses for this repository
2343 Returns statuses for this repository
2321
2344
2322 :param revisions: list of revisions to get statuses for
2345 :param revisions: list of revisions to get statuses for
2323 """
2346 """
2324 statuses = ChangesetStatus.query()\
2347 statuses = ChangesetStatus.query()\
2325 .filter(ChangesetStatus.repo == self)\
2348 .filter(ChangesetStatus.repo == self)\
2326 .filter(ChangesetStatus.version == 0)
2349 .filter(ChangesetStatus.version == 0)
2327
2350
2328 if revisions:
2351 if revisions:
2329 # Try doing the filtering in chunks to avoid hitting limits
2352 # Try doing the filtering in chunks to avoid hitting limits
2330 size = 500
2353 size = 500
2331 status_results = []
2354 status_results = []
2332 for chunk in xrange(0, len(revisions), size):
2355 for chunk in xrange(0, len(revisions), size):
2333 status_results += statuses.filter(
2356 status_results += statuses.filter(
2334 ChangesetStatus.revision.in_(
2357 ChangesetStatus.revision.in_(
2335 revisions[chunk: chunk+size])
2358 revisions[chunk: chunk+size])
2336 ).all()
2359 ).all()
2337 else:
2360 else:
2338 status_results = statuses.all()
2361 status_results = statuses.all()
2339
2362
2340 grouped = {}
2363 grouped = {}
2341
2364
2342 # maybe we have open new pullrequest without a status?
2365 # maybe we have open new pullrequest without a status?
2343 stat = ChangesetStatus.STATUS_UNDER_REVIEW
2366 stat = ChangesetStatus.STATUS_UNDER_REVIEW
2344 status_lbl = ChangesetStatus.get_status_lbl(stat)
2367 status_lbl = ChangesetStatus.get_status_lbl(stat)
2345 for pr in PullRequest.query().filter(PullRequest.source_repo == self).all():
2368 for pr in PullRequest.query().filter(PullRequest.source_repo == self).all():
2346 for rev in pr.revisions:
2369 for rev in pr.revisions:
2347 pr_id = pr.pull_request_id
2370 pr_id = pr.pull_request_id
2348 pr_repo = pr.target_repo.repo_name
2371 pr_repo = pr.target_repo.repo_name
2349 grouped[rev] = [stat, status_lbl, pr_id, pr_repo]
2372 grouped[rev] = [stat, status_lbl, pr_id, pr_repo]
2350
2373
2351 for stat in status_results:
2374 for stat in status_results:
2352 pr_id = pr_repo = None
2375 pr_id = pr_repo = None
2353 if stat.pull_request:
2376 if stat.pull_request:
2354 pr_id = stat.pull_request.pull_request_id
2377 pr_id = stat.pull_request.pull_request_id
2355 pr_repo = stat.pull_request.target_repo.repo_name
2378 pr_repo = stat.pull_request.target_repo.repo_name
2356 grouped[stat.revision] = [str(stat.status), stat.status_lbl,
2379 grouped[stat.revision] = [str(stat.status), stat.status_lbl,
2357 pr_id, pr_repo]
2380 pr_id, pr_repo]
2358 return grouped
2381 return grouped
2359
2382
2360 # ==========================================================================
2383 # ==========================================================================
2361 # SCM CACHE INSTANCE
2384 # SCM CACHE INSTANCE
2362 # ==========================================================================
2385 # ==========================================================================
2363
2386
2364 def scm_instance(self, **kwargs):
2387 def scm_instance(self, **kwargs):
2365 import rhodecode
2388 import rhodecode
2366
2389
2367 # Passing a config will not hit the cache currently only used
2390 # Passing a config will not hit the cache currently only used
2368 # for repo2dbmapper
2391 # for repo2dbmapper
2369 config = kwargs.pop('config', None)
2392 config = kwargs.pop('config', None)
2370 cache = kwargs.pop('cache', None)
2393 cache = kwargs.pop('cache', None)
2371 full_cache = str2bool(rhodecode.CONFIG.get('vcs_full_cache'))
2394 full_cache = str2bool(rhodecode.CONFIG.get('vcs_full_cache'))
2372 # if cache is NOT defined use default global, else we have a full
2395 # if cache is NOT defined use default global, else we have a full
2373 # control over cache behaviour
2396 # control over cache behaviour
2374 if cache is None and full_cache and not config:
2397 if cache is None and full_cache and not config:
2375 return self._get_instance_cached()
2398 return self._get_instance_cached()
2376 return self._get_instance(cache=bool(cache), config=config)
2399 return self._get_instance(cache=bool(cache), config=config)
2377
2400
2378 def _get_instance_cached(self):
2401 def _get_instance_cached(self):
2379 from rhodecode.lib import rc_cache
2402 from rhodecode.lib import rc_cache
2380
2403
2381 cache_namespace_uid = 'cache_repo_instance.{}'.format(self.repo_id)
2404 cache_namespace_uid = 'cache_repo_instance.{}'.format(self.repo_id)
2382 invalidation_namespace = CacheKey.REPO_INVALIDATION_NAMESPACE.format(
2405 invalidation_namespace = CacheKey.REPO_INVALIDATION_NAMESPACE.format(
2383 repo_id=self.repo_id)
2406 repo_id=self.repo_id)
2384 region = rc_cache.get_or_create_region('cache_repo_longterm', cache_namespace_uid)
2407 region = rc_cache.get_or_create_region('cache_repo_longterm', cache_namespace_uid)
2385
2408
2386 @region.conditional_cache_on_arguments(namespace=cache_namespace_uid)
2409 @region.conditional_cache_on_arguments(namespace=cache_namespace_uid)
2387 def get_instance_cached(repo_id, context_id):
2410 def get_instance_cached(repo_id, context_id):
2388 return self._get_instance()
2411 return self._get_instance()
2389
2412
2390 # we must use thread scoped cache here,
2413 # we must use thread scoped cache here,
2391 # because each thread of gevent needs it's own not shared connection and cache
2414 # because each thread of gevent needs it's own not shared connection and cache
2392 # we also alter `args` so the cache key is individual for every green thread.
2415 # we also alter `args` so the cache key is individual for every green thread.
2393 inv_context_manager = rc_cache.InvalidationContext(
2416 inv_context_manager = rc_cache.InvalidationContext(
2394 uid=cache_namespace_uid, invalidation_namespace=invalidation_namespace,
2417 uid=cache_namespace_uid, invalidation_namespace=invalidation_namespace,
2395 thread_scoped=True)
2418 thread_scoped=True)
2396 with inv_context_manager as invalidation_context:
2419 with inv_context_manager as invalidation_context:
2397 args = (self.repo_id, inv_context_manager.cache_key)
2420 args = (self.repo_id, inv_context_manager.cache_key)
2398 # re-compute and store cache if we get invalidate signal
2421 # re-compute and store cache if we get invalidate signal
2399 if invalidation_context.should_invalidate():
2422 if invalidation_context.should_invalidate():
2400 instance = get_instance_cached.refresh(*args)
2423 instance = get_instance_cached.refresh(*args)
2401 else:
2424 else:
2402 instance = get_instance_cached(*args)
2425 instance = get_instance_cached(*args)
2403
2426
2404 log.debug(
2427 log.debug(
2405 'Repo instance fetched in %.3fs', inv_context_manager.compute_time)
2428 'Repo instance fetched in %.3fs', inv_context_manager.compute_time)
2406 return instance
2429 return instance
2407
2430
2408 def _get_instance(self, cache=True, config=None):
2431 def _get_instance(self, cache=True, config=None):
2409 config = config or self._config
2432 config = config or self._config
2410 custom_wire = {
2433 custom_wire = {
2411 'cache': cache # controls the vcs.remote cache
2434 'cache': cache # controls the vcs.remote cache
2412 }
2435 }
2413 repo = get_vcs_instance(
2436 repo = get_vcs_instance(
2414 repo_path=safe_str(self.repo_full_path),
2437 repo_path=safe_str(self.repo_full_path),
2415 config=config,
2438 config=config,
2416 with_wire=custom_wire,
2439 with_wire=custom_wire,
2417 create=False,
2440 create=False,
2418 _vcs_alias=self.repo_type)
2441 _vcs_alias=self.repo_type)
2419
2442
2420 return repo
2443 return repo
2421
2444
2422 def __json__(self):
2445 def __json__(self):
2423 return {'landing_rev': self.landing_rev}
2446 return {'landing_rev': self.landing_rev}
2424
2447
2425 def get_dict(self):
2448 def get_dict(self):
2426
2449
2427 # Since we transformed `repo_name` to a hybrid property, we need to
2450 # Since we transformed `repo_name` to a hybrid property, we need to
2428 # keep compatibility with the code which uses `repo_name` field.
2451 # keep compatibility with the code which uses `repo_name` field.
2429
2452
2430 result = super(Repository, self).get_dict()
2453 result = super(Repository, self).get_dict()
2431 result['repo_name'] = result.pop('_repo_name', None)
2454 result['repo_name'] = result.pop('_repo_name', None)
2432 return result
2455 return result
2433
2456
2434
2457
2435 class RepoGroup(Base, BaseModel):
2458 class RepoGroup(Base, BaseModel):
2436 __tablename__ = 'groups'
2459 __tablename__ = 'groups'
2437 __table_args__ = (
2460 __table_args__ = (
2438 UniqueConstraint('group_name', 'group_parent_id'),
2461 UniqueConstraint('group_name', 'group_parent_id'),
2439 CheckConstraint('group_id != group_parent_id'),
2462 CheckConstraint('group_id != group_parent_id'),
2440 base_table_args,
2463 base_table_args,
2441 )
2464 )
2442 __mapper_args__ = {'order_by': 'group_name'}
2465 __mapper_args__ = {'order_by': 'group_name'}
2443
2466
2444 CHOICES_SEPARATOR = '/' # used to generate select2 choices for nested groups
2467 CHOICES_SEPARATOR = '/' # used to generate select2 choices for nested groups
2445
2468
2446 group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2469 group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2447 group_name = Column("group_name", String(255), nullable=False, unique=True, default=None)
2470 group_name = Column("group_name", String(255), nullable=False, unique=True, default=None)
2448 group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
2471 group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
2449 group_description = Column("group_description", String(10000), nullable=True, unique=None, default=None)
2472 group_description = Column("group_description", String(10000), nullable=True, unique=None, default=None)
2450 enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
2473 enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
2451 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
2474 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
2452 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
2475 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
2453 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
2476 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
2454 personal = Column('personal', Boolean(), nullable=True, unique=None, default=None)
2477 personal = Column('personal', Boolean(), nullable=True, unique=None, default=None)
2455
2478
2456 repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id')
2479 repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id')
2457 users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
2480 users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
2458 parent_group = relationship('RepoGroup', remote_side=group_id)
2481 parent_group = relationship('RepoGroup', remote_side=group_id)
2459 user = relationship('User')
2482 user = relationship('User')
2460 integrations = relationship('Integration',
2483 integrations = relationship('Integration',
2461 cascade="all, delete, delete-orphan")
2484 cascade="all, delete, delete-orphan")
2462
2485
2463 def __init__(self, group_name='', parent_group=None):
2486 def __init__(self, group_name='', parent_group=None):
2464 self.group_name = group_name
2487 self.group_name = group_name
2465 self.parent_group = parent_group
2488 self.parent_group = parent_group
2466
2489
2467 def __unicode__(self):
2490 def __unicode__(self):
2468 return u"<%s('id:%s:%s')>" % (
2491 return u"<%s('id:%s:%s')>" % (
2469 self.__class__.__name__, self.group_id, self.group_name)
2492 self.__class__.__name__, self.group_id, self.group_name)
2470
2493
2471 @hybrid_property
2494 @hybrid_property
2472 def description_safe(self):
2495 def description_safe(self):
2473 from rhodecode.lib import helpers as h
2496 from rhodecode.lib import helpers as h
2474 return h.escape(self.group_description)
2497 return h.escape(self.group_description)
2475
2498
2476 @classmethod
2499 @classmethod
2477 def _generate_choice(cls, repo_group):
2500 def _generate_choice(cls, repo_group):
2478 from webhelpers.html import literal as _literal
2501 from webhelpers.html import literal as _literal
2479 _name = lambda k: _literal(cls.CHOICES_SEPARATOR.join(k))
2502 _name = lambda k: _literal(cls.CHOICES_SEPARATOR.join(k))
2480 return repo_group.group_id, _name(repo_group.full_path_splitted)
2503 return repo_group.group_id, _name(repo_group.full_path_splitted)
2481
2504
2482 @classmethod
2505 @classmethod
2483 def groups_choices(cls, groups=None, show_empty_group=True):
2506 def groups_choices(cls, groups=None, show_empty_group=True):
2484 if not groups:
2507 if not groups:
2485 groups = cls.query().all()
2508 groups = cls.query().all()
2486
2509
2487 repo_groups = []
2510 repo_groups = []
2488 if show_empty_group:
2511 if show_empty_group:
2489 repo_groups = [(-1, u'-- %s --' % _('No parent'))]
2512 repo_groups = [(-1, u'-- %s --' % _('No parent'))]
2490
2513
2491 repo_groups.extend([cls._generate_choice(x) for x in groups])
2514 repo_groups.extend([cls._generate_choice(x) for x in groups])
2492
2515
2493 repo_groups = sorted(
2516 repo_groups = sorted(
2494 repo_groups, key=lambda t: t[1].split(cls.CHOICES_SEPARATOR)[0])
2517 repo_groups, key=lambda t: t[1].split(cls.CHOICES_SEPARATOR)[0])
2495 return repo_groups
2518 return repo_groups
2496
2519
2497 @classmethod
2520 @classmethod
2498 def url_sep(cls):
2521 def url_sep(cls):
2499 return URL_SEP
2522 return URL_SEP
2500
2523
2501 @classmethod
2524 @classmethod
2502 def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
2525 def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
2503 if case_insensitive:
2526 if case_insensitive:
2504 gr = cls.query().filter(func.lower(cls.group_name)
2527 gr = cls.query().filter(func.lower(cls.group_name)
2505 == func.lower(group_name))
2528 == func.lower(group_name))
2506 else:
2529 else:
2507 gr = cls.query().filter(cls.group_name == group_name)
2530 gr = cls.query().filter(cls.group_name == group_name)
2508 if cache:
2531 if cache:
2509 name_key = _hash_key(group_name)
2532 name_key = _hash_key(group_name)
2510 gr = gr.options(
2533 gr = gr.options(
2511 FromCache("sql_cache_short", "get_group_%s" % name_key))
2534 FromCache("sql_cache_short", "get_group_%s" % name_key))
2512 return gr.scalar()
2535 return gr.scalar()
2513
2536
2514 @classmethod
2537 @classmethod
2515 def get_user_personal_repo_group(cls, user_id):
2538 def get_user_personal_repo_group(cls, user_id):
2516 user = User.get(user_id)
2539 user = User.get(user_id)
2517 if user.username == User.DEFAULT_USER:
2540 if user.username == User.DEFAULT_USER:
2518 return None
2541 return None
2519
2542
2520 return cls.query()\
2543 return cls.query()\
2521 .filter(cls.personal == true()) \
2544 .filter(cls.personal == true()) \
2522 .filter(cls.user == user) \
2545 .filter(cls.user == user) \
2523 .order_by(cls.group_id.asc()) \
2546 .order_by(cls.group_id.asc()) \
2524 .first()
2547 .first()
2525
2548
2526 @classmethod
2549 @classmethod
2527 def get_all_repo_groups(cls, user_id=Optional(None), group_id=Optional(None),
2550 def get_all_repo_groups(cls, user_id=Optional(None), group_id=Optional(None),
2528 case_insensitive=True):
2551 case_insensitive=True):
2529 q = RepoGroup.query()
2552 q = RepoGroup.query()
2530
2553
2531 if not isinstance(user_id, Optional):
2554 if not isinstance(user_id, Optional):
2532 q = q.filter(RepoGroup.user_id == user_id)
2555 q = q.filter(RepoGroup.user_id == user_id)
2533
2556
2534 if not isinstance(group_id, Optional):
2557 if not isinstance(group_id, Optional):
2535 q = q.filter(RepoGroup.group_parent_id == group_id)
2558 q = q.filter(RepoGroup.group_parent_id == group_id)
2536
2559
2537 if case_insensitive:
2560 if case_insensitive:
2538 q = q.order_by(func.lower(RepoGroup.group_name))
2561 q = q.order_by(func.lower(RepoGroup.group_name))
2539 else:
2562 else:
2540 q = q.order_by(RepoGroup.group_name)
2563 q = q.order_by(RepoGroup.group_name)
2541 return q.all()
2564 return q.all()
2542
2565
2543 @property
2566 @property
2544 def parents(self):
2567 def parents(self):
2545 parents_recursion_limit = 10
2568 parents_recursion_limit = 10
2546 groups = []
2569 groups = []
2547 if self.parent_group is None:
2570 if self.parent_group is None:
2548 return groups
2571 return groups
2549 cur_gr = self.parent_group
2572 cur_gr = self.parent_group
2550 groups.insert(0, cur_gr)
2573 groups.insert(0, cur_gr)
2551 cnt = 0
2574 cnt = 0
2552 while 1:
2575 while 1:
2553 cnt += 1
2576 cnt += 1
2554 gr = getattr(cur_gr, 'parent_group', None)
2577 gr = getattr(cur_gr, 'parent_group', None)
2555 cur_gr = cur_gr.parent_group
2578 cur_gr = cur_gr.parent_group
2556 if gr is None:
2579 if gr is None:
2557 break
2580 break
2558 if cnt == parents_recursion_limit:
2581 if cnt == parents_recursion_limit:
2559 # this will prevent accidental infinit loops
2582 # this will prevent accidental infinit loops
2560 log.error('more than %s parents found for group %s, stopping '
2583 log.error('more than %s parents found for group %s, stopping '
2561 'recursive parent fetching', parents_recursion_limit, self)
2584 'recursive parent fetching', parents_recursion_limit, self)
2562 break
2585 break
2563
2586
2564 groups.insert(0, gr)
2587 groups.insert(0, gr)
2565 return groups
2588 return groups
2566
2589
2567 @property
2590 @property
2568 def last_db_change(self):
2591 def last_db_change(self):
2569 return self.updated_on
2592 return self.updated_on
2570
2593
2571 @property
2594 @property
2572 def children(self):
2595 def children(self):
2573 return RepoGroup.query().filter(RepoGroup.parent_group == self)
2596 return RepoGroup.query().filter(RepoGroup.parent_group == self)
2574
2597
2575 @property
2598 @property
2576 def name(self):
2599 def name(self):
2577 return self.group_name.split(RepoGroup.url_sep())[-1]
2600 return self.group_name.split(RepoGroup.url_sep())[-1]
2578
2601
2579 @property
2602 @property
2580 def full_path(self):
2603 def full_path(self):
2581 return self.group_name
2604 return self.group_name
2582
2605
2583 @property
2606 @property
2584 def full_path_splitted(self):
2607 def full_path_splitted(self):
2585 return self.group_name.split(RepoGroup.url_sep())
2608 return self.group_name.split(RepoGroup.url_sep())
2586
2609
2587 @property
2610 @property
2588 def repositories(self):
2611 def repositories(self):
2589 return Repository.query()\
2612 return Repository.query()\
2590 .filter(Repository.group == self)\
2613 .filter(Repository.group == self)\
2591 .order_by(Repository.repo_name)
2614 .order_by(Repository.repo_name)
2592
2615
2593 @property
2616 @property
2594 def repositories_recursive_count(self):
2617 def repositories_recursive_count(self):
2595 cnt = self.repositories.count()
2618 cnt = self.repositories.count()
2596
2619
2597 def children_count(group):
2620 def children_count(group):
2598 cnt = 0
2621 cnt = 0
2599 for child in group.children:
2622 for child in group.children:
2600 cnt += child.repositories.count()
2623 cnt += child.repositories.count()
2601 cnt += children_count(child)
2624 cnt += children_count(child)
2602 return cnt
2625 return cnt
2603
2626
2604 return cnt + children_count(self)
2627 return cnt + children_count(self)
2605
2628
2606 def _recursive_objects(self, include_repos=True):
2629 def _recursive_objects(self, include_repos=True):
2607 all_ = []
2630 all_ = []
2608
2631
2609 def _get_members(root_gr):
2632 def _get_members(root_gr):
2610 if include_repos:
2633 if include_repos:
2611 for r in root_gr.repositories:
2634 for r in root_gr.repositories:
2612 all_.append(r)
2635 all_.append(r)
2613 childs = root_gr.children.all()
2636 childs = root_gr.children.all()
2614 if childs:
2637 if childs:
2615 for gr in childs:
2638 for gr in childs:
2616 all_.append(gr)
2639 all_.append(gr)
2617 _get_members(gr)
2640 _get_members(gr)
2618
2641
2619 _get_members(self)
2642 _get_members(self)
2620 return [self] + all_
2643 return [self] + all_
2621
2644
2622 def recursive_groups_and_repos(self):
2645 def recursive_groups_and_repos(self):
2623 """
2646 """
2624 Recursive return all groups, with repositories in those groups
2647 Recursive return all groups, with repositories in those groups
2625 """
2648 """
2626 return self._recursive_objects()
2649 return self._recursive_objects()
2627
2650
2628 def recursive_groups(self):
2651 def recursive_groups(self):
2629 """
2652 """
2630 Returns all children groups for this group including children of children
2653 Returns all children groups for this group including children of children
2631 """
2654 """
2632 return self._recursive_objects(include_repos=False)
2655 return self._recursive_objects(include_repos=False)
2633
2656
2634 def get_new_name(self, group_name):
2657 def get_new_name(self, group_name):
2635 """
2658 """
2636 returns new full group name based on parent and new name
2659 returns new full group name based on parent and new name
2637
2660
2638 :param group_name:
2661 :param group_name:
2639 """
2662 """
2640 path_prefix = (self.parent_group.full_path_splitted if
2663 path_prefix = (self.parent_group.full_path_splitted if
2641 self.parent_group else [])
2664 self.parent_group else [])
2642 return RepoGroup.url_sep().join(path_prefix + [group_name])
2665 return RepoGroup.url_sep().join(path_prefix + [group_name])
2643
2666
2644 def permissions(self, with_admins=True, with_owner=True):
2667 def permissions(self, with_admins=True, with_owner=True,
2668 expand_from_user_groups=False):
2645 """
2669 """
2646 Permissions for repository groups
2670 Permissions for repository groups
2647 """
2671 """
2648 _admin_perm = 'group.admin'
2672 _admin_perm = 'group.admin'
2649
2673
2650 owner_row = []
2674 owner_row = []
2651 if with_owner:
2675 if with_owner:
2652 usr = AttributeDict(self.user.get_dict())
2676 usr = AttributeDict(self.user.get_dict())
2653 usr.owner_row = True
2677 usr.owner_row = True
2654 usr.permission = _admin_perm
2678 usr.permission = _admin_perm
2655 owner_row.append(usr)
2679 owner_row.append(usr)
2656
2680
2657 super_admin_ids = []
2681 super_admin_ids = []
2658 super_admin_rows = []
2682 super_admin_rows = []
2659 if with_admins:
2683 if with_admins:
2660 for usr in User.get_all_super_admins():
2684 for usr in User.get_all_super_admins():
2661 super_admin_ids.append(usr.user_id)
2685 super_admin_ids.append(usr.user_id)
2662 # if this admin is also owner, don't double the record
2686 # if this admin is also owner, don't double the record
2663 if usr.user_id == owner_row[0].user_id:
2687 if usr.user_id == owner_row[0].user_id:
2664 owner_row[0].admin_row = True
2688 owner_row[0].admin_row = True
2665 else:
2689 else:
2666 usr = AttributeDict(usr.get_dict())
2690 usr = AttributeDict(usr.get_dict())
2667 usr.admin_row = True
2691 usr.admin_row = True
2668 usr.permission = _admin_perm
2692 usr.permission = _admin_perm
2669 super_admin_rows.append(usr)
2693 super_admin_rows.append(usr)
2670
2694
2671 q = UserRepoGroupToPerm.query().filter(UserRepoGroupToPerm.group == self)
2695 q = UserRepoGroupToPerm.query().filter(UserRepoGroupToPerm.group == self)
2672 q = q.options(joinedload(UserRepoGroupToPerm.group),
2696 q = q.options(joinedload(UserRepoGroupToPerm.group),
2673 joinedload(UserRepoGroupToPerm.user),
2697 joinedload(UserRepoGroupToPerm.user),
2674 joinedload(UserRepoGroupToPerm.permission),)
2698 joinedload(UserRepoGroupToPerm.permission),)
2675
2699
2676 # get owners and admins and permissions. We do a trick of re-writing
2700 # get owners and admins and permissions. We do a trick of re-writing
2677 # objects from sqlalchemy to named-tuples due to sqlalchemy session
2701 # objects from sqlalchemy to named-tuples due to sqlalchemy session
2678 # has a global reference and changing one object propagates to all
2702 # has a global reference and changing one object propagates to all
2679 # others. This means if admin is also an owner admin_row that change
2703 # others. This means if admin is also an owner admin_row that change
2680 # would propagate to both objects
2704 # would propagate to both objects
2681 perm_rows = []
2705 perm_rows = []
2682 for _usr in q.all():
2706 for _usr in q.all():
2683 usr = AttributeDict(_usr.user.get_dict())
2707 usr = AttributeDict(_usr.user.get_dict())
2684 # if this user is also owner/admin, mark as duplicate record
2708 # if this user is also owner/admin, mark as duplicate record
2685 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
2709 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
2686 usr.duplicate_perm = True
2710 usr.duplicate_perm = True
2687 usr.permission = _usr.permission.permission_name
2711 usr.permission = _usr.permission.permission_name
2688 perm_rows.append(usr)
2712 perm_rows.append(usr)
2689
2713
2690 # filter the perm rows by 'default' first and then sort them by
2714 # filter the perm rows by 'default' first and then sort them by
2691 # admin,write,read,none permissions sorted again alphabetically in
2715 # admin,write,read,none permissions sorted again alphabetically in
2692 # each group
2716 # each group
2693 perm_rows = sorted(perm_rows, key=display_user_sort)
2717 perm_rows = sorted(perm_rows, key=display_user_sort)
2694
2718
2695 return super_admin_rows + owner_row + perm_rows
2719 user_groups_rows = []
2696
2720 if expand_from_user_groups:
2697 def permission_user_groups(self):
2721 for ug in self.permission_user_groups(with_members=True):
2698 q = UserGroupRepoGroupToPerm.query().filter(
2722 for user_data in ug.members:
2699 UserGroupRepoGroupToPerm.group == self)
2723 user_groups_rows.append(user_data)
2724
2725 return super_admin_rows + owner_row + perm_rows + user_groups_rows
2726
2727 def permission_user_groups(self, with_members=False):
2728 q = UserGroupRepoGroupToPerm.query()\
2729 .filter(UserGroupRepoGroupToPerm.group == self)
2700 q = q.options(joinedload(UserGroupRepoGroupToPerm.group),
2730 q = q.options(joinedload(UserGroupRepoGroupToPerm.group),
2701 joinedload(UserGroupRepoGroupToPerm.users_group),
2731 joinedload(UserGroupRepoGroupToPerm.users_group),
2702 joinedload(UserGroupRepoGroupToPerm.permission),)
2732 joinedload(UserGroupRepoGroupToPerm.permission),)
2703
2733
2704 perm_rows = []
2734 perm_rows = []
2705 for _user_group in q.all():
2735 for _user_group in q.all():
2706 usr = AttributeDict(_user_group.users_group.get_dict())
2736 entry = AttributeDict(_user_group.users_group.get_dict())
2707 usr.permission = _user_group.permission.permission_name
2737 entry.permission = _user_group.permission.permission_name
2708 perm_rows.append(usr)
2738 if with_members:
2739 entry.members = [x.user.get_dict()
2740 for x in _user_group.users_group.members]
2741 perm_rows.append(entry)
2709
2742
2710 perm_rows = sorted(perm_rows, key=display_user_group_sort)
2743 perm_rows = sorted(perm_rows, key=display_user_group_sort)
2711 return perm_rows
2744 return perm_rows
2712
2745
2713 def get_api_data(self):
2746 def get_api_data(self):
2714 """
2747 """
2715 Common function for generating api data
2748 Common function for generating api data
2716
2749
2717 """
2750 """
2718 group = self
2751 group = self
2719 data = {
2752 data = {
2720 'group_id': group.group_id,
2753 'group_id': group.group_id,
2721 'group_name': group.group_name,
2754 'group_name': group.group_name,
2722 'group_description': group.description_safe,
2755 'group_description': group.description_safe,
2723 'parent_group': group.parent_group.group_name if group.parent_group else None,
2756 'parent_group': group.parent_group.group_name if group.parent_group else None,
2724 'repositories': [x.repo_name for x in group.repositories],
2757 'repositories': [x.repo_name for x in group.repositories],
2725 'owner': group.user.username,
2758 'owner': group.user.username,
2726 }
2759 }
2727 return data
2760 return data
2728
2761
2729
2762
2730 class Permission(Base, BaseModel):
2763 class Permission(Base, BaseModel):
2731 __tablename__ = 'permissions'
2764 __tablename__ = 'permissions'
2732 __table_args__ = (
2765 __table_args__ = (
2733 Index('p_perm_name_idx', 'permission_name'),
2766 Index('p_perm_name_idx', 'permission_name'),
2734 base_table_args,
2767 base_table_args,
2735 )
2768 )
2736
2769
2737 PERMS = [
2770 PERMS = [
2738 ('hg.admin', _('RhodeCode Super Administrator')),
2771 ('hg.admin', _('RhodeCode Super Administrator')),
2739
2772
2740 ('repository.none', _('Repository no access')),
2773 ('repository.none', _('Repository no access')),
2741 ('repository.read', _('Repository read access')),
2774 ('repository.read', _('Repository read access')),
2742 ('repository.write', _('Repository write access')),
2775 ('repository.write', _('Repository write access')),
2743 ('repository.admin', _('Repository admin access')),
2776 ('repository.admin', _('Repository admin access')),
2744
2777
2745 ('group.none', _('Repository group no access')),
2778 ('group.none', _('Repository group no access')),
2746 ('group.read', _('Repository group read access')),
2779 ('group.read', _('Repository group read access')),
2747 ('group.write', _('Repository group write access')),
2780 ('group.write', _('Repository group write access')),
2748 ('group.admin', _('Repository group admin access')),
2781 ('group.admin', _('Repository group admin access')),
2749
2782
2750 ('usergroup.none', _('User group no access')),
2783 ('usergroup.none', _('User group no access')),
2751 ('usergroup.read', _('User group read access')),
2784 ('usergroup.read', _('User group read access')),
2752 ('usergroup.write', _('User group write access')),
2785 ('usergroup.write', _('User group write access')),
2753 ('usergroup.admin', _('User group admin access')),
2786 ('usergroup.admin', _('User group admin access')),
2754
2787
2755 ('branch.none', _('Branch no permissions')),
2788 ('branch.none', _('Branch no permissions')),
2756 ('branch.merge', _('Branch access by web merge')),
2789 ('branch.merge', _('Branch access by web merge')),
2757 ('branch.push', _('Branch access by push')),
2790 ('branch.push', _('Branch access by push')),
2758 ('branch.push_force', _('Branch access by push with force')),
2791 ('branch.push_force', _('Branch access by push with force')),
2759
2792
2760 ('hg.repogroup.create.false', _('Repository Group creation disabled')),
2793 ('hg.repogroup.create.false', _('Repository Group creation disabled')),
2761 ('hg.repogroup.create.true', _('Repository Group creation enabled')),
2794 ('hg.repogroup.create.true', _('Repository Group creation enabled')),
2762
2795
2763 ('hg.usergroup.create.false', _('User Group creation disabled')),
2796 ('hg.usergroup.create.false', _('User Group creation disabled')),
2764 ('hg.usergroup.create.true', _('User Group creation enabled')),
2797 ('hg.usergroup.create.true', _('User Group creation enabled')),
2765
2798
2766 ('hg.create.none', _('Repository creation disabled')),
2799 ('hg.create.none', _('Repository creation disabled')),
2767 ('hg.create.repository', _('Repository creation enabled')),
2800 ('hg.create.repository', _('Repository creation enabled')),
2768 ('hg.create.write_on_repogroup.true', _('Repository creation enabled with write permission to a repository group')),
2801 ('hg.create.write_on_repogroup.true', _('Repository creation enabled with write permission to a repository group')),
2769 ('hg.create.write_on_repogroup.false', _('Repository creation disabled with write permission to a repository group')),
2802 ('hg.create.write_on_repogroup.false', _('Repository creation disabled with write permission to a repository group')),
2770
2803
2771 ('hg.fork.none', _('Repository forking disabled')),
2804 ('hg.fork.none', _('Repository forking disabled')),
2772 ('hg.fork.repository', _('Repository forking enabled')),
2805 ('hg.fork.repository', _('Repository forking enabled')),
2773
2806
2774 ('hg.register.none', _('Registration disabled')),
2807 ('hg.register.none', _('Registration disabled')),
2775 ('hg.register.manual_activate', _('User Registration with manual account activation')),
2808 ('hg.register.manual_activate', _('User Registration with manual account activation')),
2776 ('hg.register.auto_activate', _('User Registration with automatic account activation')),
2809 ('hg.register.auto_activate', _('User Registration with automatic account activation')),
2777
2810
2778 ('hg.password_reset.enabled', _('Password reset enabled')),
2811 ('hg.password_reset.enabled', _('Password reset enabled')),
2779 ('hg.password_reset.hidden', _('Password reset hidden')),
2812 ('hg.password_reset.hidden', _('Password reset hidden')),
2780 ('hg.password_reset.disabled', _('Password reset disabled')),
2813 ('hg.password_reset.disabled', _('Password reset disabled')),
2781
2814
2782 ('hg.extern_activate.manual', _('Manual activation of external account')),
2815 ('hg.extern_activate.manual', _('Manual activation of external account')),
2783 ('hg.extern_activate.auto', _('Automatic activation of external account')),
2816 ('hg.extern_activate.auto', _('Automatic activation of external account')),
2784
2817
2785 ('hg.inherit_default_perms.false', _('Inherit object permissions from default user disabled')),
2818 ('hg.inherit_default_perms.false', _('Inherit object permissions from default user disabled')),
2786 ('hg.inherit_default_perms.true', _('Inherit object permissions from default user enabled')),
2819 ('hg.inherit_default_perms.true', _('Inherit object permissions from default user enabled')),
2787 ]
2820 ]
2788
2821
2789 # definition of system default permissions for DEFAULT user, created on
2822 # definition of system default permissions for DEFAULT user, created on
2790 # system setup
2823 # system setup
2791 DEFAULT_USER_PERMISSIONS = [
2824 DEFAULT_USER_PERMISSIONS = [
2792 # object perms
2825 # object perms
2793 'repository.read',
2826 'repository.read',
2794 'group.read',
2827 'group.read',
2795 'usergroup.read',
2828 'usergroup.read',
2796 # branch, for backward compat we need same value as before so forced pushed
2829 # branch, for backward compat we need same value as before so forced pushed
2797 'branch.push_force',
2830 'branch.push_force',
2798 # global
2831 # global
2799 'hg.create.repository',
2832 'hg.create.repository',
2800 'hg.repogroup.create.false',
2833 'hg.repogroup.create.false',
2801 'hg.usergroup.create.false',
2834 'hg.usergroup.create.false',
2802 'hg.create.write_on_repogroup.true',
2835 'hg.create.write_on_repogroup.true',
2803 'hg.fork.repository',
2836 'hg.fork.repository',
2804 'hg.register.manual_activate',
2837 'hg.register.manual_activate',
2805 'hg.password_reset.enabled',
2838 'hg.password_reset.enabled',
2806 'hg.extern_activate.auto',
2839 'hg.extern_activate.auto',
2807 'hg.inherit_default_perms.true',
2840 'hg.inherit_default_perms.true',
2808 ]
2841 ]
2809
2842
2810 # defines which permissions are more important higher the more important
2843 # defines which permissions are more important higher the more important
2811 # Weight defines which permissions are more important.
2844 # Weight defines which permissions are more important.
2812 # The higher number the more important.
2845 # The higher number the more important.
2813 PERM_WEIGHTS = {
2846 PERM_WEIGHTS = {
2814 'repository.none': 0,
2847 'repository.none': 0,
2815 'repository.read': 1,
2848 'repository.read': 1,
2816 'repository.write': 3,
2849 'repository.write': 3,
2817 'repository.admin': 4,
2850 'repository.admin': 4,
2818
2851
2819 'group.none': 0,
2852 'group.none': 0,
2820 'group.read': 1,
2853 'group.read': 1,
2821 'group.write': 3,
2854 'group.write': 3,
2822 'group.admin': 4,
2855 'group.admin': 4,
2823
2856
2824 'usergroup.none': 0,
2857 'usergroup.none': 0,
2825 'usergroup.read': 1,
2858 'usergroup.read': 1,
2826 'usergroup.write': 3,
2859 'usergroup.write': 3,
2827 'usergroup.admin': 4,
2860 'usergroup.admin': 4,
2828
2861
2829 'branch.none': 0,
2862 'branch.none': 0,
2830 'branch.merge': 1,
2863 'branch.merge': 1,
2831 'branch.push': 3,
2864 'branch.push': 3,
2832 'branch.push_force': 4,
2865 'branch.push_force': 4,
2833
2866
2834 'hg.repogroup.create.false': 0,
2867 'hg.repogroup.create.false': 0,
2835 'hg.repogroup.create.true': 1,
2868 'hg.repogroup.create.true': 1,
2836
2869
2837 'hg.usergroup.create.false': 0,
2870 'hg.usergroup.create.false': 0,
2838 'hg.usergroup.create.true': 1,
2871 'hg.usergroup.create.true': 1,
2839
2872
2840 'hg.fork.none': 0,
2873 'hg.fork.none': 0,
2841 'hg.fork.repository': 1,
2874 'hg.fork.repository': 1,
2842 'hg.create.none': 0,
2875 'hg.create.none': 0,
2843 'hg.create.repository': 1
2876 'hg.create.repository': 1
2844 }
2877 }
2845
2878
2846 permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2879 permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2847 permission_name = Column("permission_name", String(255), nullable=True, unique=None, default=None)
2880 permission_name = Column("permission_name", String(255), nullable=True, unique=None, default=None)
2848 permission_longname = Column("permission_longname", String(255), nullable=True, unique=None, default=None)
2881 permission_longname = Column("permission_longname", String(255), nullable=True, unique=None, default=None)
2849
2882
2850 def __unicode__(self):
2883 def __unicode__(self):
2851 return u"<%s('%s:%s')>" % (
2884 return u"<%s('%s:%s')>" % (
2852 self.__class__.__name__, self.permission_id, self.permission_name
2885 self.__class__.__name__, self.permission_id, self.permission_name
2853 )
2886 )
2854
2887
2855 @classmethod
2888 @classmethod
2856 def get_by_key(cls, key):
2889 def get_by_key(cls, key):
2857 return cls.query().filter(cls.permission_name == key).scalar()
2890 return cls.query().filter(cls.permission_name == key).scalar()
2858
2891
2859 @classmethod
2892 @classmethod
2860 def get_default_repo_perms(cls, user_id, repo_id=None):
2893 def get_default_repo_perms(cls, user_id, repo_id=None):
2861 q = Session().query(UserRepoToPerm, Repository, Permission)\
2894 q = Session().query(UserRepoToPerm, Repository, Permission)\
2862 .join((Permission, UserRepoToPerm.permission_id == Permission.permission_id))\
2895 .join((Permission, UserRepoToPerm.permission_id == Permission.permission_id))\
2863 .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\
2896 .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\
2864 .filter(UserRepoToPerm.user_id == user_id)
2897 .filter(UserRepoToPerm.user_id == user_id)
2865 if repo_id:
2898 if repo_id:
2866 q = q.filter(UserRepoToPerm.repository_id == repo_id)
2899 q = q.filter(UserRepoToPerm.repository_id == repo_id)
2867 return q.all()
2900 return q.all()
2868
2901
2869 @classmethod
2902 @classmethod
2870 def get_default_repo_branch_perms(cls, user_id, repo_id=None):
2903 def get_default_repo_branch_perms(cls, user_id, repo_id=None):
2871 q = Session().query(UserToRepoBranchPermission, UserRepoToPerm, Permission) \
2904 q = Session().query(UserToRepoBranchPermission, UserRepoToPerm, Permission) \
2872 .join(
2905 .join(
2873 Permission,
2906 Permission,
2874 UserToRepoBranchPermission.permission_id == Permission.permission_id) \
2907 UserToRepoBranchPermission.permission_id == Permission.permission_id) \
2875 .join(
2908 .join(
2876 UserRepoToPerm,
2909 UserRepoToPerm,
2877 UserToRepoBranchPermission.rule_to_perm_id == UserRepoToPerm.repo_to_perm_id) \
2910 UserToRepoBranchPermission.rule_to_perm_id == UserRepoToPerm.repo_to_perm_id) \
2878 .filter(UserRepoToPerm.user_id == user_id)
2911 .filter(UserRepoToPerm.user_id == user_id)
2879
2912
2880 if repo_id:
2913 if repo_id:
2881 q = q.filter(UserToRepoBranchPermission.repository_id == repo_id)
2914 q = q.filter(UserToRepoBranchPermission.repository_id == repo_id)
2882 return q.order_by(UserToRepoBranchPermission.rule_order).all()
2915 return q.order_by(UserToRepoBranchPermission.rule_order).all()
2883
2916
2884 @classmethod
2917 @classmethod
2885 def get_default_repo_perms_from_user_group(cls, user_id, repo_id=None):
2918 def get_default_repo_perms_from_user_group(cls, user_id, repo_id=None):
2886 q = Session().query(UserGroupRepoToPerm, Repository, Permission)\
2919 q = Session().query(UserGroupRepoToPerm, Repository, Permission)\
2887 .join(
2920 .join(
2888 Permission,
2921 Permission,
2889 UserGroupRepoToPerm.permission_id == Permission.permission_id)\
2922 UserGroupRepoToPerm.permission_id == Permission.permission_id)\
2890 .join(
2923 .join(
2891 Repository,
2924 Repository,
2892 UserGroupRepoToPerm.repository_id == Repository.repo_id)\
2925 UserGroupRepoToPerm.repository_id == Repository.repo_id)\
2893 .join(
2926 .join(
2894 UserGroup,
2927 UserGroup,
2895 UserGroupRepoToPerm.users_group_id ==
2928 UserGroupRepoToPerm.users_group_id ==
2896 UserGroup.users_group_id)\
2929 UserGroup.users_group_id)\
2897 .join(
2930 .join(
2898 UserGroupMember,
2931 UserGroupMember,
2899 UserGroupRepoToPerm.users_group_id ==
2932 UserGroupRepoToPerm.users_group_id ==
2900 UserGroupMember.users_group_id)\
2933 UserGroupMember.users_group_id)\
2901 .filter(
2934 .filter(
2902 UserGroupMember.user_id == user_id,
2935 UserGroupMember.user_id == user_id,
2903 UserGroup.users_group_active == true())
2936 UserGroup.users_group_active == true())
2904 if repo_id:
2937 if repo_id:
2905 q = q.filter(UserGroupRepoToPerm.repository_id == repo_id)
2938 q = q.filter(UserGroupRepoToPerm.repository_id == repo_id)
2906 return q.all()
2939 return q.all()
2907
2940
2908 @classmethod
2941 @classmethod
2909 def get_default_repo_branch_perms_from_user_group(cls, user_id, repo_id=None):
2942 def get_default_repo_branch_perms_from_user_group(cls, user_id, repo_id=None):
2910 q = Session().query(UserGroupToRepoBranchPermission, UserGroupRepoToPerm, Permission) \
2943 q = Session().query(UserGroupToRepoBranchPermission, UserGroupRepoToPerm, Permission) \
2911 .join(
2944 .join(
2912 Permission,
2945 Permission,
2913 UserGroupToRepoBranchPermission.permission_id == Permission.permission_id) \
2946 UserGroupToRepoBranchPermission.permission_id == Permission.permission_id) \
2914 .join(
2947 .join(
2915 UserGroupRepoToPerm,
2948 UserGroupRepoToPerm,
2916 UserGroupToRepoBranchPermission.rule_to_perm_id == UserGroupRepoToPerm.users_group_to_perm_id) \
2949 UserGroupToRepoBranchPermission.rule_to_perm_id == UserGroupRepoToPerm.users_group_to_perm_id) \
2917 .join(
2950 .join(
2918 UserGroup,
2951 UserGroup,
2919 UserGroupRepoToPerm.users_group_id == UserGroup.users_group_id) \
2952 UserGroupRepoToPerm.users_group_id == UserGroup.users_group_id) \
2920 .join(
2953 .join(
2921 UserGroupMember,
2954 UserGroupMember,
2922 UserGroupRepoToPerm.users_group_id == UserGroupMember.users_group_id) \
2955 UserGroupRepoToPerm.users_group_id == UserGroupMember.users_group_id) \
2923 .filter(
2956 .filter(
2924 UserGroupMember.user_id == user_id,
2957 UserGroupMember.user_id == user_id,
2925 UserGroup.users_group_active == true())
2958 UserGroup.users_group_active == true())
2926
2959
2927 if repo_id:
2960 if repo_id:
2928 q = q.filter(UserGroupToRepoBranchPermission.repository_id == repo_id)
2961 q = q.filter(UserGroupToRepoBranchPermission.repository_id == repo_id)
2929 return q.order_by(UserGroupToRepoBranchPermission.rule_order).all()
2962 return q.order_by(UserGroupToRepoBranchPermission.rule_order).all()
2930
2963
2931 @classmethod
2964 @classmethod
2932 def get_default_group_perms(cls, user_id, repo_group_id=None):
2965 def get_default_group_perms(cls, user_id, repo_group_id=None):
2933 q = Session().query(UserRepoGroupToPerm, RepoGroup, Permission)\
2966 q = Session().query(UserRepoGroupToPerm, RepoGroup, Permission)\
2934 .join(
2967 .join(
2935 Permission,
2968 Permission,
2936 UserRepoGroupToPerm.permission_id == Permission.permission_id)\
2969 UserRepoGroupToPerm.permission_id == Permission.permission_id)\
2937 .join(
2970 .join(
2938 RepoGroup,
2971 RepoGroup,
2939 UserRepoGroupToPerm.group_id == RepoGroup.group_id)\
2972 UserRepoGroupToPerm.group_id == RepoGroup.group_id)\
2940 .filter(UserRepoGroupToPerm.user_id == user_id)
2973 .filter(UserRepoGroupToPerm.user_id == user_id)
2941 if repo_group_id:
2974 if repo_group_id:
2942 q = q.filter(UserRepoGroupToPerm.group_id == repo_group_id)
2975 q = q.filter(UserRepoGroupToPerm.group_id == repo_group_id)
2943 return q.all()
2976 return q.all()
2944
2977
2945 @classmethod
2978 @classmethod
2946 def get_default_group_perms_from_user_group(
2979 def get_default_group_perms_from_user_group(
2947 cls, user_id, repo_group_id=None):
2980 cls, user_id, repo_group_id=None):
2948 q = Session().query(UserGroupRepoGroupToPerm, RepoGroup, Permission)\
2981 q = Session().query(UserGroupRepoGroupToPerm, RepoGroup, Permission)\
2949 .join(
2982 .join(
2950 Permission,
2983 Permission,
2951 UserGroupRepoGroupToPerm.permission_id ==
2984 UserGroupRepoGroupToPerm.permission_id ==
2952 Permission.permission_id)\
2985 Permission.permission_id)\
2953 .join(
2986 .join(
2954 RepoGroup,
2987 RepoGroup,
2955 UserGroupRepoGroupToPerm.group_id == RepoGroup.group_id)\
2988 UserGroupRepoGroupToPerm.group_id == RepoGroup.group_id)\
2956 .join(
2989 .join(
2957 UserGroup,
2990 UserGroup,
2958 UserGroupRepoGroupToPerm.users_group_id ==
2991 UserGroupRepoGroupToPerm.users_group_id ==
2959 UserGroup.users_group_id)\
2992 UserGroup.users_group_id)\
2960 .join(
2993 .join(
2961 UserGroupMember,
2994 UserGroupMember,
2962 UserGroupRepoGroupToPerm.users_group_id ==
2995 UserGroupRepoGroupToPerm.users_group_id ==
2963 UserGroupMember.users_group_id)\
2996 UserGroupMember.users_group_id)\
2964 .filter(
2997 .filter(
2965 UserGroupMember.user_id == user_id,
2998 UserGroupMember.user_id == user_id,
2966 UserGroup.users_group_active == true())
2999 UserGroup.users_group_active == true())
2967 if repo_group_id:
3000 if repo_group_id:
2968 q = q.filter(UserGroupRepoGroupToPerm.group_id == repo_group_id)
3001 q = q.filter(UserGroupRepoGroupToPerm.group_id == repo_group_id)
2969 return q.all()
3002 return q.all()
2970
3003
2971 @classmethod
3004 @classmethod
2972 def get_default_user_group_perms(cls, user_id, user_group_id=None):
3005 def get_default_user_group_perms(cls, user_id, user_group_id=None):
2973 q = Session().query(UserUserGroupToPerm, UserGroup, Permission)\
3006 q = Session().query(UserUserGroupToPerm, UserGroup, Permission)\
2974 .join((Permission, UserUserGroupToPerm.permission_id == Permission.permission_id))\
3007 .join((Permission, UserUserGroupToPerm.permission_id == Permission.permission_id))\
2975 .join((UserGroup, UserUserGroupToPerm.user_group_id == UserGroup.users_group_id))\
3008 .join((UserGroup, UserUserGroupToPerm.user_group_id == UserGroup.users_group_id))\
2976 .filter(UserUserGroupToPerm.user_id == user_id)
3009 .filter(UserUserGroupToPerm.user_id == user_id)
2977 if user_group_id:
3010 if user_group_id:
2978 q = q.filter(UserUserGroupToPerm.user_group_id == user_group_id)
3011 q = q.filter(UserUserGroupToPerm.user_group_id == user_group_id)
2979 return q.all()
3012 return q.all()
2980
3013
2981 @classmethod
3014 @classmethod
2982 def get_default_user_group_perms_from_user_group(
3015 def get_default_user_group_perms_from_user_group(
2983 cls, user_id, user_group_id=None):
3016 cls, user_id, user_group_id=None):
2984 TargetUserGroup = aliased(UserGroup, name='target_user_group')
3017 TargetUserGroup = aliased(UserGroup, name='target_user_group')
2985 q = Session().query(UserGroupUserGroupToPerm, UserGroup, Permission)\
3018 q = Session().query(UserGroupUserGroupToPerm, UserGroup, Permission)\
2986 .join(
3019 .join(
2987 Permission,
3020 Permission,
2988 UserGroupUserGroupToPerm.permission_id ==
3021 UserGroupUserGroupToPerm.permission_id ==
2989 Permission.permission_id)\
3022 Permission.permission_id)\
2990 .join(
3023 .join(
2991 TargetUserGroup,
3024 TargetUserGroup,
2992 UserGroupUserGroupToPerm.target_user_group_id ==
3025 UserGroupUserGroupToPerm.target_user_group_id ==
2993 TargetUserGroup.users_group_id)\
3026 TargetUserGroup.users_group_id)\
2994 .join(
3027 .join(
2995 UserGroup,
3028 UserGroup,
2996 UserGroupUserGroupToPerm.user_group_id ==
3029 UserGroupUserGroupToPerm.user_group_id ==
2997 UserGroup.users_group_id)\
3030 UserGroup.users_group_id)\
2998 .join(
3031 .join(
2999 UserGroupMember,
3032 UserGroupMember,
3000 UserGroupUserGroupToPerm.user_group_id ==
3033 UserGroupUserGroupToPerm.user_group_id ==
3001 UserGroupMember.users_group_id)\
3034 UserGroupMember.users_group_id)\
3002 .filter(
3035 .filter(
3003 UserGroupMember.user_id == user_id,
3036 UserGroupMember.user_id == user_id,
3004 UserGroup.users_group_active == true())
3037 UserGroup.users_group_active == true())
3005 if user_group_id:
3038 if user_group_id:
3006 q = q.filter(
3039 q = q.filter(
3007 UserGroupUserGroupToPerm.user_group_id == user_group_id)
3040 UserGroupUserGroupToPerm.user_group_id == user_group_id)
3008
3041
3009 return q.all()
3042 return q.all()
3010
3043
3011
3044
3012 class UserRepoToPerm(Base, BaseModel):
3045 class UserRepoToPerm(Base, BaseModel):
3013 __tablename__ = 'repo_to_perm'
3046 __tablename__ = 'repo_to_perm'
3014 __table_args__ = (
3047 __table_args__ = (
3015 UniqueConstraint('user_id', 'repository_id', 'permission_id'),
3048 UniqueConstraint('user_id', 'repository_id', 'permission_id'),
3016 base_table_args
3049 base_table_args
3017 )
3050 )
3018
3051
3019 repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3052 repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3020 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3053 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3021 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3054 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3022 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
3055 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
3023
3056
3024 user = relationship('User')
3057 user = relationship('User')
3025 repository = relationship('Repository')
3058 repository = relationship('Repository')
3026 permission = relationship('Permission')
3059 permission = relationship('Permission')
3027
3060
3028 branch_perm_entry = relationship('UserToRepoBranchPermission', cascade="all, delete, delete-orphan", lazy='joined')
3061 branch_perm_entry = relationship('UserToRepoBranchPermission', cascade="all, delete, delete-orphan", lazy='joined')
3029
3062
3030 @classmethod
3063 @classmethod
3031 def create(cls, user, repository, permission):
3064 def create(cls, user, repository, permission):
3032 n = cls()
3065 n = cls()
3033 n.user = user
3066 n.user = user
3034 n.repository = repository
3067 n.repository = repository
3035 n.permission = permission
3068 n.permission = permission
3036 Session().add(n)
3069 Session().add(n)
3037 return n
3070 return n
3038
3071
3039 def __unicode__(self):
3072 def __unicode__(self):
3040 return u'<%s => %s >' % (self.user, self.repository)
3073 return u'<%s => %s >' % (self.user, self.repository)
3041
3074
3042
3075
3043 class UserUserGroupToPerm(Base, BaseModel):
3076 class UserUserGroupToPerm(Base, BaseModel):
3044 __tablename__ = 'user_user_group_to_perm'
3077 __tablename__ = 'user_user_group_to_perm'
3045 __table_args__ = (
3078 __table_args__ = (
3046 UniqueConstraint('user_id', 'user_group_id', 'permission_id'),
3079 UniqueConstraint('user_id', 'user_group_id', 'permission_id'),
3047 base_table_args
3080 base_table_args
3048 )
3081 )
3049
3082
3050 user_user_group_to_perm_id = Column("user_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3083 user_user_group_to_perm_id = Column("user_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3051 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3084 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3052 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3085 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3053 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3086 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3054
3087
3055 user = relationship('User')
3088 user = relationship('User')
3056 user_group = relationship('UserGroup')
3089 user_group = relationship('UserGroup')
3057 permission = relationship('Permission')
3090 permission = relationship('Permission')
3058
3091
3059 @classmethod
3092 @classmethod
3060 def create(cls, user, user_group, permission):
3093 def create(cls, user, user_group, permission):
3061 n = cls()
3094 n = cls()
3062 n.user = user
3095 n.user = user
3063 n.user_group = user_group
3096 n.user_group = user_group
3064 n.permission = permission
3097 n.permission = permission
3065 Session().add(n)
3098 Session().add(n)
3066 return n
3099 return n
3067
3100
3068 def __unicode__(self):
3101 def __unicode__(self):
3069 return u'<%s => %s >' % (self.user, self.user_group)
3102 return u'<%s => %s >' % (self.user, self.user_group)
3070
3103
3071
3104
3072 class UserToPerm(Base, BaseModel):
3105 class UserToPerm(Base, BaseModel):
3073 __tablename__ = 'user_to_perm'
3106 __tablename__ = 'user_to_perm'
3074 __table_args__ = (
3107 __table_args__ = (
3075 UniqueConstraint('user_id', 'permission_id'),
3108 UniqueConstraint('user_id', 'permission_id'),
3076 base_table_args
3109 base_table_args
3077 )
3110 )
3078
3111
3079 user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3112 user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3080 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3113 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3081 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3114 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3082
3115
3083 user = relationship('User')
3116 user = relationship('User')
3084 permission = relationship('Permission', lazy='joined')
3117 permission = relationship('Permission', lazy='joined')
3085
3118
3086 def __unicode__(self):
3119 def __unicode__(self):
3087 return u'<%s => %s >' % (self.user, self.permission)
3120 return u'<%s => %s >' % (self.user, self.permission)
3088
3121
3089
3122
3090 class UserGroupRepoToPerm(Base, BaseModel):
3123 class UserGroupRepoToPerm(Base, BaseModel):
3091 __tablename__ = 'users_group_repo_to_perm'
3124 __tablename__ = 'users_group_repo_to_perm'
3092 __table_args__ = (
3125 __table_args__ = (
3093 UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
3126 UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
3094 base_table_args
3127 base_table_args
3095 )
3128 )
3096
3129
3097 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3130 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3098 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3131 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3099 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3132 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3100 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
3133 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
3101
3134
3102 users_group = relationship('UserGroup')
3135 users_group = relationship('UserGroup')
3103 permission = relationship('Permission')
3136 permission = relationship('Permission')
3104 repository = relationship('Repository')
3137 repository = relationship('Repository')
3105 user_group_branch_perms = relationship('UserGroupToRepoBranchPermission', cascade='all')
3138 user_group_branch_perms = relationship('UserGroupToRepoBranchPermission', cascade='all')
3106
3139
3107 @classmethod
3140 @classmethod
3108 def create(cls, users_group, repository, permission):
3141 def create(cls, users_group, repository, permission):
3109 n = cls()
3142 n = cls()
3110 n.users_group = users_group
3143 n.users_group = users_group
3111 n.repository = repository
3144 n.repository = repository
3112 n.permission = permission
3145 n.permission = permission
3113 Session().add(n)
3146 Session().add(n)
3114 return n
3147 return n
3115
3148
3116 def __unicode__(self):
3149 def __unicode__(self):
3117 return u'<UserGroupRepoToPerm:%s => %s >' % (self.users_group, self.repository)
3150 return u'<UserGroupRepoToPerm:%s => %s >' % (self.users_group, self.repository)
3118
3151
3119
3152
3120 class UserGroupUserGroupToPerm(Base, BaseModel):
3153 class UserGroupUserGroupToPerm(Base, BaseModel):
3121 __tablename__ = 'user_group_user_group_to_perm'
3154 __tablename__ = 'user_group_user_group_to_perm'
3122 __table_args__ = (
3155 __table_args__ = (
3123 UniqueConstraint('target_user_group_id', 'user_group_id', 'permission_id'),
3156 UniqueConstraint('target_user_group_id', 'user_group_id', 'permission_id'),
3124 CheckConstraint('target_user_group_id != user_group_id'),
3157 CheckConstraint('target_user_group_id != user_group_id'),
3125 base_table_args
3158 base_table_args
3126 )
3159 )
3127
3160
3128 user_group_user_group_to_perm_id = Column("user_group_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3161 user_group_user_group_to_perm_id = Column("user_group_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3129 target_user_group_id = Column("target_user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3162 target_user_group_id = Column("target_user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3130 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3163 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3131 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3164 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3132
3165
3133 target_user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id')
3166 target_user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id')
3134 user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.user_group_id==UserGroup.users_group_id')
3167 user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.user_group_id==UserGroup.users_group_id')
3135 permission = relationship('Permission')
3168 permission = relationship('Permission')
3136
3169
3137 @classmethod
3170 @classmethod
3138 def create(cls, target_user_group, user_group, permission):
3171 def create(cls, target_user_group, user_group, permission):
3139 n = cls()
3172 n = cls()
3140 n.target_user_group = target_user_group
3173 n.target_user_group = target_user_group
3141 n.user_group = user_group
3174 n.user_group = user_group
3142 n.permission = permission
3175 n.permission = permission
3143 Session().add(n)
3176 Session().add(n)
3144 return n
3177 return n
3145
3178
3146 def __unicode__(self):
3179 def __unicode__(self):
3147 return u'<UserGroupUserGroup:%s => %s >' % (self.target_user_group, self.user_group)
3180 return u'<UserGroupUserGroup:%s => %s >' % (self.target_user_group, self.user_group)
3148
3181
3149
3182
3150 class UserGroupToPerm(Base, BaseModel):
3183 class UserGroupToPerm(Base, BaseModel):
3151 __tablename__ = 'users_group_to_perm'
3184 __tablename__ = 'users_group_to_perm'
3152 __table_args__ = (
3185 __table_args__ = (
3153 UniqueConstraint('users_group_id', 'permission_id',),
3186 UniqueConstraint('users_group_id', 'permission_id',),
3154 base_table_args
3187 base_table_args
3155 )
3188 )
3156
3189
3157 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3190 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3158 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3191 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3159 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3192 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3160
3193
3161 users_group = relationship('UserGroup')
3194 users_group = relationship('UserGroup')
3162 permission = relationship('Permission')
3195 permission = relationship('Permission')
3163
3196
3164
3197
3165 class UserRepoGroupToPerm(Base, BaseModel):
3198 class UserRepoGroupToPerm(Base, BaseModel):
3166 __tablename__ = 'user_repo_group_to_perm'
3199 __tablename__ = 'user_repo_group_to_perm'
3167 __table_args__ = (
3200 __table_args__ = (
3168 UniqueConstraint('user_id', 'group_id', 'permission_id'),
3201 UniqueConstraint('user_id', 'group_id', 'permission_id'),
3169 base_table_args
3202 base_table_args
3170 )
3203 )
3171
3204
3172 group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3205 group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3173 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3206 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3174 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
3207 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
3175 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3208 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3176
3209
3177 user = relationship('User')
3210 user = relationship('User')
3178 group = relationship('RepoGroup')
3211 group = relationship('RepoGroup')
3179 permission = relationship('Permission')
3212 permission = relationship('Permission')
3180
3213
3181 @classmethod
3214 @classmethod
3182 def create(cls, user, repository_group, permission):
3215 def create(cls, user, repository_group, permission):
3183 n = cls()
3216 n = cls()
3184 n.user = user
3217 n.user = user
3185 n.group = repository_group
3218 n.group = repository_group
3186 n.permission = permission
3219 n.permission = permission
3187 Session().add(n)
3220 Session().add(n)
3188 return n
3221 return n
3189
3222
3190
3223
3191 class UserGroupRepoGroupToPerm(Base, BaseModel):
3224 class UserGroupRepoGroupToPerm(Base, BaseModel):
3192 __tablename__ = 'users_group_repo_group_to_perm'
3225 __tablename__ = 'users_group_repo_group_to_perm'
3193 __table_args__ = (
3226 __table_args__ = (
3194 UniqueConstraint('users_group_id', 'group_id'),
3227 UniqueConstraint('users_group_id', 'group_id'),
3195 base_table_args
3228 base_table_args
3196 )
3229 )
3197
3230
3198 users_group_repo_group_to_perm_id = Column("users_group_repo_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3231 users_group_repo_group_to_perm_id = Column("users_group_repo_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3199 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3232 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3200 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
3233 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
3201 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3234 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3202
3235
3203 users_group = relationship('UserGroup')
3236 users_group = relationship('UserGroup')
3204 permission = relationship('Permission')
3237 permission = relationship('Permission')
3205 group = relationship('RepoGroup')
3238 group = relationship('RepoGroup')
3206
3239
3207 @classmethod
3240 @classmethod
3208 def create(cls, user_group, repository_group, permission):
3241 def create(cls, user_group, repository_group, permission):
3209 n = cls()
3242 n = cls()
3210 n.users_group = user_group
3243 n.users_group = user_group
3211 n.group = repository_group
3244 n.group = repository_group
3212 n.permission = permission
3245 n.permission = permission
3213 Session().add(n)
3246 Session().add(n)
3214 return n
3247 return n
3215
3248
3216 def __unicode__(self):
3249 def __unicode__(self):
3217 return u'<UserGroupRepoGroupToPerm:%s => %s >' % (self.users_group, self.group)
3250 return u'<UserGroupRepoGroupToPerm:%s => %s >' % (self.users_group, self.group)
3218
3251
3219
3252
3220 class Statistics(Base, BaseModel):
3253 class Statistics(Base, BaseModel):
3221 __tablename__ = 'statistics'
3254 __tablename__ = 'statistics'
3222 __table_args__ = (
3255 __table_args__ = (
3223 base_table_args
3256 base_table_args
3224 )
3257 )
3225
3258
3226 stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3259 stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3227 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
3260 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
3228 stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
3261 stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
3229 commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data
3262 commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data
3230 commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data
3263 commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data
3231 languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data
3264 languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data
3232
3265
3233 repository = relationship('Repository', single_parent=True)
3266 repository = relationship('Repository', single_parent=True)
3234
3267
3235
3268
3236 class UserFollowing(Base, BaseModel):
3269 class UserFollowing(Base, BaseModel):
3237 __tablename__ = 'user_followings'
3270 __tablename__ = 'user_followings'
3238 __table_args__ = (
3271 __table_args__ = (
3239 UniqueConstraint('user_id', 'follows_repository_id'),
3272 UniqueConstraint('user_id', 'follows_repository_id'),
3240 UniqueConstraint('user_id', 'follows_user_id'),
3273 UniqueConstraint('user_id', 'follows_user_id'),
3241 base_table_args
3274 base_table_args
3242 )
3275 )
3243
3276
3244 user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3277 user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3245 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3278 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3246 follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
3279 follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
3247 follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
3280 follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
3248 follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
3281 follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
3249
3282
3250 user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id')
3283 user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id')
3251
3284
3252 follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
3285 follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
3253 follows_repository = relationship('Repository', order_by='Repository.repo_name')
3286 follows_repository = relationship('Repository', order_by='Repository.repo_name')
3254
3287
3255 @classmethod
3288 @classmethod
3256 def get_repo_followers(cls, repo_id):
3289 def get_repo_followers(cls, repo_id):
3257 return cls.query().filter(cls.follows_repo_id == repo_id)
3290 return cls.query().filter(cls.follows_repo_id == repo_id)
3258
3291
3259
3292
3260 class CacheKey(Base, BaseModel):
3293 class CacheKey(Base, BaseModel):
3261 __tablename__ = 'cache_invalidation'
3294 __tablename__ = 'cache_invalidation'
3262 __table_args__ = (
3295 __table_args__ = (
3263 UniqueConstraint('cache_key'),
3296 UniqueConstraint('cache_key'),
3264 Index('key_idx', 'cache_key'),
3297 Index('key_idx', 'cache_key'),
3265 base_table_args,
3298 base_table_args,
3266 )
3299 )
3267
3300
3268 CACHE_TYPE_FEED = 'FEED'
3301 CACHE_TYPE_FEED = 'FEED'
3269 CACHE_TYPE_README = 'README'
3302 CACHE_TYPE_README = 'README'
3270 # namespaces used to register process/thread aware caches
3303 # namespaces used to register process/thread aware caches
3271 REPO_INVALIDATION_NAMESPACE = 'repo_cache:{repo_id}'
3304 REPO_INVALIDATION_NAMESPACE = 'repo_cache:{repo_id}'
3272 SETTINGS_INVALIDATION_NAMESPACE = 'system_settings'
3305 SETTINGS_INVALIDATION_NAMESPACE = 'system_settings'
3273
3306
3274 cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3307 cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3275 cache_key = Column("cache_key", String(255), nullable=True, unique=None, default=None)
3308 cache_key = Column("cache_key", String(255), nullable=True, unique=None, default=None)
3276 cache_args = Column("cache_args", String(255), nullable=True, unique=None, default=None)
3309 cache_args = Column("cache_args", String(255), nullable=True, unique=None, default=None)
3277 cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
3310 cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
3278
3311
3279 def __init__(self, cache_key, cache_args=''):
3312 def __init__(self, cache_key, cache_args=''):
3280 self.cache_key = cache_key
3313 self.cache_key = cache_key
3281 self.cache_args = cache_args
3314 self.cache_args = cache_args
3282 self.cache_active = False
3315 self.cache_active = False
3283
3316
3284 def __unicode__(self):
3317 def __unicode__(self):
3285 return u"<%s('%s:%s[%s]')>" % (
3318 return u"<%s('%s:%s[%s]')>" % (
3286 self.__class__.__name__,
3319 self.__class__.__name__,
3287 self.cache_id, self.cache_key, self.cache_active)
3320 self.cache_id, self.cache_key, self.cache_active)
3288
3321
3289 def _cache_key_partition(self):
3322 def _cache_key_partition(self):
3290 prefix, repo_name, suffix = self.cache_key.partition(self.cache_args)
3323 prefix, repo_name, suffix = self.cache_key.partition(self.cache_args)
3291 return prefix, repo_name, suffix
3324 return prefix, repo_name, suffix
3292
3325
3293 def get_prefix(self):
3326 def get_prefix(self):
3294 """
3327 """
3295 Try to extract prefix from existing cache key. The key could consist
3328 Try to extract prefix from existing cache key. The key could consist
3296 of prefix, repo_name, suffix
3329 of prefix, repo_name, suffix
3297 """
3330 """
3298 # this returns prefix, repo_name, suffix
3331 # this returns prefix, repo_name, suffix
3299 return self._cache_key_partition()[0]
3332 return self._cache_key_partition()[0]
3300
3333
3301 def get_suffix(self):
3334 def get_suffix(self):
3302 """
3335 """
3303 get suffix that might have been used in _get_cache_key to
3336 get suffix that might have been used in _get_cache_key to
3304 generate self.cache_key. Only used for informational purposes
3337 generate self.cache_key. Only used for informational purposes
3305 in repo_edit.mako.
3338 in repo_edit.mako.
3306 """
3339 """
3307 # prefix, repo_name, suffix
3340 # prefix, repo_name, suffix
3308 return self._cache_key_partition()[2]
3341 return self._cache_key_partition()[2]
3309
3342
3310 @classmethod
3343 @classmethod
3311 def delete_all_cache(cls):
3344 def delete_all_cache(cls):
3312 """
3345 """
3313 Delete all cache keys from database.
3346 Delete all cache keys from database.
3314 Should only be run when all instances are down and all entries
3347 Should only be run when all instances are down and all entries
3315 thus stale.
3348 thus stale.
3316 """
3349 """
3317 cls.query().delete()
3350 cls.query().delete()
3318 Session().commit()
3351 Session().commit()
3319
3352
3320 @classmethod
3353 @classmethod
3321 def set_invalidate(cls, cache_uid, delete=False):
3354 def set_invalidate(cls, cache_uid, delete=False):
3322 """
3355 """
3323 Mark all caches of a repo as invalid in the database.
3356 Mark all caches of a repo as invalid in the database.
3324 """
3357 """
3325
3358
3326 try:
3359 try:
3327 qry = Session().query(cls).filter(cls.cache_args == cache_uid)
3360 qry = Session().query(cls).filter(cls.cache_args == cache_uid)
3328 if delete:
3361 if delete:
3329 qry.delete()
3362 qry.delete()
3330 log.debug('cache objects deleted for cache args %s',
3363 log.debug('cache objects deleted for cache args %s',
3331 safe_str(cache_uid))
3364 safe_str(cache_uid))
3332 else:
3365 else:
3333 qry.update({"cache_active": False})
3366 qry.update({"cache_active": False})
3334 log.debug('cache objects marked as invalid for cache args %s',
3367 log.debug('cache objects marked as invalid for cache args %s',
3335 safe_str(cache_uid))
3368 safe_str(cache_uid))
3336
3369
3337 Session().commit()
3370 Session().commit()
3338 except Exception:
3371 except Exception:
3339 log.exception(
3372 log.exception(
3340 'Cache key invalidation failed for cache args %s',
3373 'Cache key invalidation failed for cache args %s',
3341 safe_str(cache_uid))
3374 safe_str(cache_uid))
3342 Session().rollback()
3375 Session().rollback()
3343
3376
3344 @classmethod
3377 @classmethod
3345 def get_active_cache(cls, cache_key):
3378 def get_active_cache(cls, cache_key):
3346 inv_obj = cls.query().filter(cls.cache_key == cache_key).scalar()
3379 inv_obj = cls.query().filter(cls.cache_key == cache_key).scalar()
3347 if inv_obj:
3380 if inv_obj:
3348 return inv_obj
3381 return inv_obj
3349 return None
3382 return None
3350
3383
3351
3384
3352 class ChangesetComment(Base, BaseModel):
3385 class ChangesetComment(Base, BaseModel):
3353 __tablename__ = 'changeset_comments'
3386 __tablename__ = 'changeset_comments'
3354 __table_args__ = (
3387 __table_args__ = (
3355 Index('cc_revision_idx', 'revision'),
3388 Index('cc_revision_idx', 'revision'),
3356 base_table_args,
3389 base_table_args,
3357 )
3390 )
3358
3391
3359 COMMENT_OUTDATED = u'comment_outdated'
3392 COMMENT_OUTDATED = u'comment_outdated'
3360 COMMENT_TYPE_NOTE = u'note'
3393 COMMENT_TYPE_NOTE = u'note'
3361 COMMENT_TYPE_TODO = u'todo'
3394 COMMENT_TYPE_TODO = u'todo'
3362 COMMENT_TYPES = [COMMENT_TYPE_NOTE, COMMENT_TYPE_TODO]
3395 COMMENT_TYPES = [COMMENT_TYPE_NOTE, COMMENT_TYPE_TODO]
3363
3396
3364 comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True)
3397 comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True)
3365 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3398 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3366 revision = Column('revision', String(40), nullable=True)
3399 revision = Column('revision', String(40), nullable=True)
3367 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3400 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3368 pull_request_version_id = Column("pull_request_version_id", Integer(), ForeignKey('pull_request_versions.pull_request_version_id'), nullable=True)
3401 pull_request_version_id = Column("pull_request_version_id", Integer(), ForeignKey('pull_request_versions.pull_request_version_id'), nullable=True)
3369 line_no = Column('line_no', Unicode(10), nullable=True)
3402 line_no = Column('line_no', Unicode(10), nullable=True)
3370 hl_lines = Column('hl_lines', Unicode(512), nullable=True)
3403 hl_lines = Column('hl_lines', Unicode(512), nullable=True)
3371 f_path = Column('f_path', Unicode(1000), nullable=True)
3404 f_path = Column('f_path', Unicode(1000), nullable=True)
3372 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
3405 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
3373 text = Column('text', UnicodeText().with_variant(UnicodeText(25000), 'mysql'), nullable=False)
3406 text = Column('text', UnicodeText().with_variant(UnicodeText(25000), 'mysql'), nullable=False)
3374 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3407 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3375 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3408 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3376 renderer = Column('renderer', Unicode(64), nullable=True)
3409 renderer = Column('renderer', Unicode(64), nullable=True)
3377 display_state = Column('display_state', Unicode(128), nullable=True)
3410 display_state = Column('display_state', Unicode(128), nullable=True)
3378
3411
3379 comment_type = Column('comment_type', Unicode(128), nullable=True, default=COMMENT_TYPE_NOTE)
3412 comment_type = Column('comment_type', Unicode(128), nullable=True, default=COMMENT_TYPE_NOTE)
3380 resolved_comment_id = Column('resolved_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'), nullable=True)
3413 resolved_comment_id = Column('resolved_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'), nullable=True)
3381
3414
3382 resolved_comment = relationship('ChangesetComment', remote_side=comment_id, back_populates='resolved_by')
3415 resolved_comment = relationship('ChangesetComment', remote_side=comment_id, back_populates='resolved_by')
3383 resolved_by = relationship('ChangesetComment', back_populates='resolved_comment')
3416 resolved_by = relationship('ChangesetComment', back_populates='resolved_comment')
3384
3417
3385 author = relationship('User', lazy='joined')
3418 author = relationship('User', lazy='joined')
3386 repo = relationship('Repository')
3419 repo = relationship('Repository')
3387 status_change = relationship('ChangesetStatus', cascade="all, delete, delete-orphan", lazy='joined')
3420 status_change = relationship('ChangesetStatus', cascade="all, delete, delete-orphan", lazy='joined')
3388 pull_request = relationship('PullRequest', lazy='joined')
3421 pull_request = relationship('PullRequest', lazy='joined')
3389 pull_request_version = relationship('PullRequestVersion')
3422 pull_request_version = relationship('PullRequestVersion')
3390
3423
3391 @classmethod
3424 @classmethod
3392 def get_users(cls, revision=None, pull_request_id=None):
3425 def get_users(cls, revision=None, pull_request_id=None):
3393 """
3426 """
3394 Returns user associated with this ChangesetComment. ie those
3427 Returns user associated with this ChangesetComment. ie those
3395 who actually commented
3428 who actually commented
3396
3429
3397 :param cls:
3430 :param cls:
3398 :param revision:
3431 :param revision:
3399 """
3432 """
3400 q = Session().query(User)\
3433 q = Session().query(User)\
3401 .join(ChangesetComment.author)
3434 .join(ChangesetComment.author)
3402 if revision:
3435 if revision:
3403 q = q.filter(cls.revision == revision)
3436 q = q.filter(cls.revision == revision)
3404 elif pull_request_id:
3437 elif pull_request_id:
3405 q = q.filter(cls.pull_request_id == pull_request_id)
3438 q = q.filter(cls.pull_request_id == pull_request_id)
3406 return q.all()
3439 return q.all()
3407
3440
3408 @classmethod
3441 @classmethod
3409 def get_index_from_version(cls, pr_version, versions):
3442 def get_index_from_version(cls, pr_version, versions):
3410 num_versions = [x.pull_request_version_id for x in versions]
3443 num_versions = [x.pull_request_version_id for x in versions]
3411 try:
3444 try:
3412 return num_versions.index(pr_version) +1
3445 return num_versions.index(pr_version) +1
3413 except (IndexError, ValueError):
3446 except (IndexError, ValueError):
3414 return
3447 return
3415
3448
3416 @property
3449 @property
3417 def outdated(self):
3450 def outdated(self):
3418 return self.display_state == self.COMMENT_OUTDATED
3451 return self.display_state == self.COMMENT_OUTDATED
3419
3452
3420 def outdated_at_version(self, version):
3453 def outdated_at_version(self, version):
3421 """
3454 """
3422 Checks if comment is outdated for given pull request version
3455 Checks if comment is outdated for given pull request version
3423 """
3456 """
3424 return self.outdated and self.pull_request_version_id != version
3457 return self.outdated and self.pull_request_version_id != version
3425
3458
3426 def older_than_version(self, version):
3459 def older_than_version(self, version):
3427 """
3460 """
3428 Checks if comment is made from previous version than given
3461 Checks if comment is made from previous version than given
3429 """
3462 """
3430 if version is None:
3463 if version is None:
3431 return self.pull_request_version_id is not None
3464 return self.pull_request_version_id is not None
3432
3465
3433 return self.pull_request_version_id < version
3466 return self.pull_request_version_id < version
3434
3467
3435 @property
3468 @property
3436 def resolved(self):
3469 def resolved(self):
3437 return self.resolved_by[0] if self.resolved_by else None
3470 return self.resolved_by[0] if self.resolved_by else None
3438
3471
3439 @property
3472 @property
3440 def is_todo(self):
3473 def is_todo(self):
3441 return self.comment_type == self.COMMENT_TYPE_TODO
3474 return self.comment_type == self.COMMENT_TYPE_TODO
3442
3475
3443 @property
3476 @property
3444 def is_inline(self):
3477 def is_inline(self):
3445 return self.line_no and self.f_path
3478 return self.line_no and self.f_path
3446
3479
3447 def get_index_version(self, versions):
3480 def get_index_version(self, versions):
3448 return self.get_index_from_version(
3481 return self.get_index_from_version(
3449 self.pull_request_version_id, versions)
3482 self.pull_request_version_id, versions)
3450
3483
3451 def __repr__(self):
3484 def __repr__(self):
3452 if self.comment_id:
3485 if self.comment_id:
3453 return '<DB:Comment #%s>' % self.comment_id
3486 return '<DB:Comment #%s>' % self.comment_id
3454 else:
3487 else:
3455 return '<DB:Comment at %#x>' % id(self)
3488 return '<DB:Comment at %#x>' % id(self)
3456
3489
3457 def get_api_data(self):
3490 def get_api_data(self):
3458 comment = self
3491 comment = self
3459 data = {
3492 data = {
3460 'comment_id': comment.comment_id,
3493 'comment_id': comment.comment_id,
3461 'comment_type': comment.comment_type,
3494 'comment_type': comment.comment_type,
3462 'comment_text': comment.text,
3495 'comment_text': comment.text,
3463 'comment_status': comment.status_change,
3496 'comment_status': comment.status_change,
3464 'comment_f_path': comment.f_path,
3497 'comment_f_path': comment.f_path,
3465 'comment_lineno': comment.line_no,
3498 'comment_lineno': comment.line_no,
3466 'comment_author': comment.author,
3499 'comment_author': comment.author,
3467 'comment_created_on': comment.created_on
3500 'comment_created_on': comment.created_on
3468 }
3501 }
3469 return data
3502 return data
3470
3503
3471 def __json__(self):
3504 def __json__(self):
3472 data = dict()
3505 data = dict()
3473 data.update(self.get_api_data())
3506 data.update(self.get_api_data())
3474 return data
3507 return data
3475
3508
3476
3509
3477 class ChangesetStatus(Base, BaseModel):
3510 class ChangesetStatus(Base, BaseModel):
3478 __tablename__ = 'changeset_statuses'
3511 __tablename__ = 'changeset_statuses'
3479 __table_args__ = (
3512 __table_args__ = (
3480 Index('cs_revision_idx', 'revision'),
3513 Index('cs_revision_idx', 'revision'),
3481 Index('cs_version_idx', 'version'),
3514 Index('cs_version_idx', 'version'),
3482 UniqueConstraint('repo_id', 'revision', 'version'),
3515 UniqueConstraint('repo_id', 'revision', 'version'),
3483 base_table_args
3516 base_table_args
3484 )
3517 )
3485
3518
3486 STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed'
3519 STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed'
3487 STATUS_APPROVED = 'approved'
3520 STATUS_APPROVED = 'approved'
3488 STATUS_REJECTED = 'rejected'
3521 STATUS_REJECTED = 'rejected'
3489 STATUS_UNDER_REVIEW = 'under_review'
3522 STATUS_UNDER_REVIEW = 'under_review'
3490
3523
3491 STATUSES = [
3524 STATUSES = [
3492 (STATUS_NOT_REVIEWED, _("Not Reviewed")), # (no icon) and default
3525 (STATUS_NOT_REVIEWED, _("Not Reviewed")), # (no icon) and default
3493 (STATUS_APPROVED, _("Approved")),
3526 (STATUS_APPROVED, _("Approved")),
3494 (STATUS_REJECTED, _("Rejected")),
3527 (STATUS_REJECTED, _("Rejected")),
3495 (STATUS_UNDER_REVIEW, _("Under Review")),
3528 (STATUS_UNDER_REVIEW, _("Under Review")),
3496 ]
3529 ]
3497
3530
3498 changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True)
3531 changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True)
3499 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3532 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3500 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
3533 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
3501 revision = Column('revision', String(40), nullable=False)
3534 revision = Column('revision', String(40), nullable=False)
3502 status = Column('status', String(128), nullable=False, default=DEFAULT)
3535 status = Column('status', String(128), nullable=False, default=DEFAULT)
3503 changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'))
3536 changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'))
3504 modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now)
3537 modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now)
3505 version = Column('version', Integer(), nullable=False, default=0)
3538 version = Column('version', Integer(), nullable=False, default=0)
3506 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3539 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3507
3540
3508 author = relationship('User', lazy='joined')
3541 author = relationship('User', lazy='joined')
3509 repo = relationship('Repository')
3542 repo = relationship('Repository')
3510 comment = relationship('ChangesetComment', lazy='joined')
3543 comment = relationship('ChangesetComment', lazy='joined')
3511 pull_request = relationship('PullRequest', lazy='joined')
3544 pull_request = relationship('PullRequest', lazy='joined')
3512
3545
3513 def __unicode__(self):
3546 def __unicode__(self):
3514 return u"<%s('%s[v%s]:%s')>" % (
3547 return u"<%s('%s[v%s]:%s')>" % (
3515 self.__class__.__name__,
3548 self.__class__.__name__,
3516 self.status, self.version, self.author
3549 self.status, self.version, self.author
3517 )
3550 )
3518
3551
3519 @classmethod
3552 @classmethod
3520 def get_status_lbl(cls, value):
3553 def get_status_lbl(cls, value):
3521 return dict(cls.STATUSES).get(value)
3554 return dict(cls.STATUSES).get(value)
3522
3555
3523 @property
3556 @property
3524 def status_lbl(self):
3557 def status_lbl(self):
3525 return ChangesetStatus.get_status_lbl(self.status)
3558 return ChangesetStatus.get_status_lbl(self.status)
3526
3559
3527 def get_api_data(self):
3560 def get_api_data(self):
3528 status = self
3561 status = self
3529 data = {
3562 data = {
3530 'status_id': status.changeset_status_id,
3563 'status_id': status.changeset_status_id,
3531 'status': status.status,
3564 'status': status.status,
3532 }
3565 }
3533 return data
3566 return data
3534
3567
3535 def __json__(self):
3568 def __json__(self):
3536 data = dict()
3569 data = dict()
3537 data.update(self.get_api_data())
3570 data.update(self.get_api_data())
3538 return data
3571 return data
3539
3572
3540
3573
3541 class _SetState(object):
3574 class _SetState(object):
3542 """
3575 """
3543 Context processor allowing changing state for sensitive operation such as
3576 Context processor allowing changing state for sensitive operation such as
3544 pull request update or merge
3577 pull request update or merge
3545 """
3578 """
3546
3579
3547 def __init__(self, pull_request, pr_state, back_state=None):
3580 def __init__(self, pull_request, pr_state, back_state=None):
3548 self._pr = pull_request
3581 self._pr = pull_request
3549 self._org_state = back_state or pull_request.pull_request_state
3582 self._org_state = back_state or pull_request.pull_request_state
3550 self._pr_state = pr_state
3583 self._pr_state = pr_state
3551
3584
3552 def __enter__(self):
3585 def __enter__(self):
3553 log.debug('StateLock: entering set state context, setting state to: `%s`',
3586 log.debug('StateLock: entering set state context, setting state to: `%s`',
3554 self._pr_state)
3587 self._pr_state)
3555 self._pr.pull_request_state = self._pr_state
3588 self._pr.pull_request_state = self._pr_state
3556 Session().add(self._pr)
3589 Session().add(self._pr)
3557 Session().commit()
3590 Session().commit()
3558
3591
3559 def __exit__(self, exc_type, exc_val, exc_tb):
3592 def __exit__(self, exc_type, exc_val, exc_tb):
3560 log.debug('StateLock: exiting set state context, setting state to: `%s`',
3593 log.debug('StateLock: exiting set state context, setting state to: `%s`',
3561 self._org_state)
3594 self._org_state)
3562 self._pr.pull_request_state = self._org_state
3595 self._pr.pull_request_state = self._org_state
3563 Session().add(self._pr)
3596 Session().add(self._pr)
3564 Session().commit()
3597 Session().commit()
3565
3598
3566
3599
3567 class _PullRequestBase(BaseModel):
3600 class _PullRequestBase(BaseModel):
3568 """
3601 """
3569 Common attributes of pull request and version entries.
3602 Common attributes of pull request and version entries.
3570 """
3603 """
3571
3604
3572 # .status values
3605 # .status values
3573 STATUS_NEW = u'new'
3606 STATUS_NEW = u'new'
3574 STATUS_OPEN = u'open'
3607 STATUS_OPEN = u'open'
3575 STATUS_CLOSED = u'closed'
3608 STATUS_CLOSED = u'closed'
3576
3609
3577 # available states
3610 # available states
3578 STATE_CREATING = u'creating'
3611 STATE_CREATING = u'creating'
3579 STATE_UPDATING = u'updating'
3612 STATE_UPDATING = u'updating'
3580 STATE_MERGING = u'merging'
3613 STATE_MERGING = u'merging'
3581 STATE_CREATED = u'created'
3614 STATE_CREATED = u'created'
3582
3615
3583 title = Column('title', Unicode(255), nullable=True)
3616 title = Column('title', Unicode(255), nullable=True)
3584 description = Column(
3617 description = Column(
3585 'description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'),
3618 'description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'),
3586 nullable=True)
3619 nullable=True)
3587 description_renderer = Column('description_renderer', Unicode(64), nullable=True)
3620 description_renderer = Column('description_renderer', Unicode(64), nullable=True)
3588
3621
3589 # new/open/closed status of pull request (not approve/reject/etc)
3622 # new/open/closed status of pull request (not approve/reject/etc)
3590 status = Column('status', Unicode(255), nullable=False, default=STATUS_NEW)
3623 status = Column('status', Unicode(255), nullable=False, default=STATUS_NEW)
3591 created_on = Column(
3624 created_on = Column(
3592 'created_on', DateTime(timezone=False), nullable=False,
3625 'created_on', DateTime(timezone=False), nullable=False,
3593 default=datetime.datetime.now)
3626 default=datetime.datetime.now)
3594 updated_on = Column(
3627 updated_on = Column(
3595 'updated_on', DateTime(timezone=False), nullable=False,
3628 'updated_on', DateTime(timezone=False), nullable=False,
3596 default=datetime.datetime.now)
3629 default=datetime.datetime.now)
3597
3630
3598 pull_request_state = Column("pull_request_state", String(255), nullable=True)
3631 pull_request_state = Column("pull_request_state", String(255), nullable=True)
3599
3632
3600 @declared_attr
3633 @declared_attr
3601 def user_id(cls):
3634 def user_id(cls):
3602 return Column(
3635 return Column(
3603 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
3636 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
3604 unique=None)
3637 unique=None)
3605
3638
3606 # 500 revisions max
3639 # 500 revisions max
3607 _revisions = Column(
3640 _revisions = Column(
3608 'revisions', UnicodeText().with_variant(UnicodeText(20500), 'mysql'))
3641 'revisions', UnicodeText().with_variant(UnicodeText(20500), 'mysql'))
3609
3642
3610 @declared_attr
3643 @declared_attr
3611 def source_repo_id(cls):
3644 def source_repo_id(cls):
3612 # TODO: dan: rename column to source_repo_id
3645 # TODO: dan: rename column to source_repo_id
3613 return Column(
3646 return Column(
3614 'org_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3647 'org_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3615 nullable=False)
3648 nullable=False)
3616
3649
3617 _source_ref = Column('org_ref', Unicode(255), nullable=False)
3650 _source_ref = Column('org_ref', Unicode(255), nullable=False)
3618
3651
3619 @hybrid_property
3652 @hybrid_property
3620 def source_ref(self):
3653 def source_ref(self):
3621 return self._source_ref
3654 return self._source_ref
3622
3655
3623 @source_ref.setter
3656 @source_ref.setter
3624 def source_ref(self, val):
3657 def source_ref(self, val):
3625 parts = (val or '').split(':')
3658 parts = (val or '').split(':')
3626 if len(parts) != 3:
3659 if len(parts) != 3:
3627 raise ValueError(
3660 raise ValueError(
3628 'Invalid reference format given: {}, expected X:Y:Z'.format(val))
3661 'Invalid reference format given: {}, expected X:Y:Z'.format(val))
3629 self._source_ref = safe_unicode(val)
3662 self._source_ref = safe_unicode(val)
3630
3663
3631 _target_ref = Column('other_ref', Unicode(255), nullable=False)
3664 _target_ref = Column('other_ref', Unicode(255), nullable=False)
3632
3665
3633 @hybrid_property
3666 @hybrid_property
3634 def target_ref(self):
3667 def target_ref(self):
3635 return self._target_ref
3668 return self._target_ref
3636
3669
3637 @target_ref.setter
3670 @target_ref.setter
3638 def target_ref(self, val):
3671 def target_ref(self, val):
3639 parts = (val or '').split(':')
3672 parts = (val or '').split(':')
3640 if len(parts) != 3:
3673 if len(parts) != 3:
3641 raise ValueError(
3674 raise ValueError(
3642 'Invalid reference format given: {}, expected X:Y:Z'.format(val))
3675 'Invalid reference format given: {}, expected X:Y:Z'.format(val))
3643 self._target_ref = safe_unicode(val)
3676 self._target_ref = safe_unicode(val)
3644
3677
3645 @declared_attr
3678 @declared_attr
3646 def target_repo_id(cls):
3679 def target_repo_id(cls):
3647 # TODO: dan: rename column to target_repo_id
3680 # TODO: dan: rename column to target_repo_id
3648 return Column(
3681 return Column(
3649 'other_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3682 'other_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3650 nullable=False)
3683 nullable=False)
3651
3684
3652 _shadow_merge_ref = Column('shadow_merge_ref', Unicode(255), nullable=True)
3685 _shadow_merge_ref = Column('shadow_merge_ref', Unicode(255), nullable=True)
3653
3686
3654 # TODO: dan: rename column to last_merge_source_rev
3687 # TODO: dan: rename column to last_merge_source_rev
3655 _last_merge_source_rev = Column(
3688 _last_merge_source_rev = Column(
3656 'last_merge_org_rev', String(40), nullable=True)
3689 'last_merge_org_rev', String(40), nullable=True)
3657 # TODO: dan: rename column to last_merge_target_rev
3690 # TODO: dan: rename column to last_merge_target_rev
3658 _last_merge_target_rev = Column(
3691 _last_merge_target_rev = Column(
3659 'last_merge_other_rev', String(40), nullable=True)
3692 'last_merge_other_rev', String(40), nullable=True)
3660 _last_merge_status = Column('merge_status', Integer(), nullable=True)
3693 _last_merge_status = Column('merge_status', Integer(), nullable=True)
3661 merge_rev = Column('merge_rev', String(40), nullable=True)
3694 merge_rev = Column('merge_rev', String(40), nullable=True)
3662
3695
3663 reviewer_data = Column(
3696 reviewer_data = Column(
3664 'reviewer_data_json', MutationObj.as_mutable(
3697 'reviewer_data_json', MutationObj.as_mutable(
3665 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
3698 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
3666
3699
3667 @property
3700 @property
3668 def reviewer_data_json(self):
3701 def reviewer_data_json(self):
3669 return json.dumps(self.reviewer_data)
3702 return json.dumps(self.reviewer_data)
3670
3703
3671 @hybrid_property
3704 @hybrid_property
3672 def description_safe(self):
3705 def description_safe(self):
3673 from rhodecode.lib import helpers as h
3706 from rhodecode.lib import helpers as h
3674 return h.escape(self.description)
3707 return h.escape(self.description)
3675
3708
3676 @hybrid_property
3709 @hybrid_property
3677 def revisions(self):
3710 def revisions(self):
3678 return self._revisions.split(':') if self._revisions else []
3711 return self._revisions.split(':') if self._revisions else []
3679
3712
3680 @revisions.setter
3713 @revisions.setter
3681 def revisions(self, val):
3714 def revisions(self, val):
3682 self._revisions = ':'.join(val)
3715 self._revisions = ':'.join(val)
3683
3716
3684 @hybrid_property
3717 @hybrid_property
3685 def last_merge_status(self):
3718 def last_merge_status(self):
3686 return safe_int(self._last_merge_status)
3719 return safe_int(self._last_merge_status)
3687
3720
3688 @last_merge_status.setter
3721 @last_merge_status.setter
3689 def last_merge_status(self, val):
3722 def last_merge_status(self, val):
3690 self._last_merge_status = val
3723 self._last_merge_status = val
3691
3724
3692 @declared_attr
3725 @declared_attr
3693 def author(cls):
3726 def author(cls):
3694 return relationship('User', lazy='joined')
3727 return relationship('User', lazy='joined')
3695
3728
3696 @declared_attr
3729 @declared_attr
3697 def source_repo(cls):
3730 def source_repo(cls):
3698 return relationship(
3731 return relationship(
3699 'Repository',
3732 'Repository',
3700 primaryjoin='%s.source_repo_id==Repository.repo_id' % cls.__name__)
3733 primaryjoin='%s.source_repo_id==Repository.repo_id' % cls.__name__)
3701
3734
3702 @property
3735 @property
3703 def source_ref_parts(self):
3736 def source_ref_parts(self):
3704 return self.unicode_to_reference(self.source_ref)
3737 return self.unicode_to_reference(self.source_ref)
3705
3738
3706 @declared_attr
3739 @declared_attr
3707 def target_repo(cls):
3740 def target_repo(cls):
3708 return relationship(
3741 return relationship(
3709 'Repository',
3742 'Repository',
3710 primaryjoin='%s.target_repo_id==Repository.repo_id' % cls.__name__)
3743 primaryjoin='%s.target_repo_id==Repository.repo_id' % cls.__name__)
3711
3744
3712 @property
3745 @property
3713 def target_ref_parts(self):
3746 def target_ref_parts(self):
3714 return self.unicode_to_reference(self.target_ref)
3747 return self.unicode_to_reference(self.target_ref)
3715
3748
3716 @property
3749 @property
3717 def shadow_merge_ref(self):
3750 def shadow_merge_ref(self):
3718 return self.unicode_to_reference(self._shadow_merge_ref)
3751 return self.unicode_to_reference(self._shadow_merge_ref)
3719
3752
3720 @shadow_merge_ref.setter
3753 @shadow_merge_ref.setter
3721 def shadow_merge_ref(self, ref):
3754 def shadow_merge_ref(self, ref):
3722 self._shadow_merge_ref = self.reference_to_unicode(ref)
3755 self._shadow_merge_ref = self.reference_to_unicode(ref)
3723
3756
3724 @staticmethod
3757 @staticmethod
3725 def unicode_to_reference(raw):
3758 def unicode_to_reference(raw):
3726 """
3759 """
3727 Convert a unicode (or string) to a reference object.
3760 Convert a unicode (or string) to a reference object.
3728 If unicode evaluates to False it returns None.
3761 If unicode evaluates to False it returns None.
3729 """
3762 """
3730 if raw:
3763 if raw:
3731 refs = raw.split(':')
3764 refs = raw.split(':')
3732 return Reference(*refs)
3765 return Reference(*refs)
3733 else:
3766 else:
3734 return None
3767 return None
3735
3768
3736 @staticmethod
3769 @staticmethod
3737 def reference_to_unicode(ref):
3770 def reference_to_unicode(ref):
3738 """
3771 """
3739 Convert a reference object to unicode.
3772 Convert a reference object to unicode.
3740 If reference is None it returns None.
3773 If reference is None it returns None.
3741 """
3774 """
3742 if ref:
3775 if ref:
3743 return u':'.join(ref)
3776 return u':'.join(ref)
3744 else:
3777 else:
3745 return None
3778 return None
3746
3779
3747 def get_api_data(self, with_merge_state=True):
3780 def get_api_data(self, with_merge_state=True):
3748 from rhodecode.model.pull_request import PullRequestModel
3781 from rhodecode.model.pull_request import PullRequestModel
3749
3782
3750 pull_request = self
3783 pull_request = self
3751 if with_merge_state:
3784 if with_merge_state:
3752 merge_status = PullRequestModel().merge_status(pull_request)
3785 merge_status = PullRequestModel().merge_status(pull_request)
3753 merge_state = {
3786 merge_state = {
3754 'status': merge_status[0],
3787 'status': merge_status[0],
3755 'message': safe_unicode(merge_status[1]),
3788 'message': safe_unicode(merge_status[1]),
3756 }
3789 }
3757 else:
3790 else:
3758 merge_state = {'status': 'not_available',
3791 merge_state = {'status': 'not_available',
3759 'message': 'not_available'}
3792 'message': 'not_available'}
3760
3793
3761 merge_data = {
3794 merge_data = {
3762 'clone_url': PullRequestModel().get_shadow_clone_url(pull_request),
3795 'clone_url': PullRequestModel().get_shadow_clone_url(pull_request),
3763 'reference': (
3796 'reference': (
3764 pull_request.shadow_merge_ref._asdict()
3797 pull_request.shadow_merge_ref._asdict()
3765 if pull_request.shadow_merge_ref else None),
3798 if pull_request.shadow_merge_ref else None),
3766 }
3799 }
3767
3800
3768 data = {
3801 data = {
3769 'pull_request_id': pull_request.pull_request_id,
3802 'pull_request_id': pull_request.pull_request_id,
3770 'url': PullRequestModel().get_url(pull_request),
3803 'url': PullRequestModel().get_url(pull_request),
3771 'title': pull_request.title,
3804 'title': pull_request.title,
3772 'description': pull_request.description,
3805 'description': pull_request.description,
3773 'status': pull_request.status,
3806 'status': pull_request.status,
3774 'state': pull_request.pull_request_state,
3807 'state': pull_request.pull_request_state,
3775 'created_on': pull_request.created_on,
3808 'created_on': pull_request.created_on,
3776 'updated_on': pull_request.updated_on,
3809 'updated_on': pull_request.updated_on,
3777 'commit_ids': pull_request.revisions,
3810 'commit_ids': pull_request.revisions,
3778 'review_status': pull_request.calculated_review_status(),
3811 'review_status': pull_request.calculated_review_status(),
3779 'mergeable': merge_state,
3812 'mergeable': merge_state,
3780 'source': {
3813 'source': {
3781 'clone_url': pull_request.source_repo.clone_url(),
3814 'clone_url': pull_request.source_repo.clone_url(),
3782 'repository': pull_request.source_repo.repo_name,
3815 'repository': pull_request.source_repo.repo_name,
3783 'reference': {
3816 'reference': {
3784 'name': pull_request.source_ref_parts.name,
3817 'name': pull_request.source_ref_parts.name,
3785 'type': pull_request.source_ref_parts.type,
3818 'type': pull_request.source_ref_parts.type,
3786 'commit_id': pull_request.source_ref_parts.commit_id,
3819 'commit_id': pull_request.source_ref_parts.commit_id,
3787 },
3820 },
3788 },
3821 },
3789 'target': {
3822 'target': {
3790 'clone_url': pull_request.target_repo.clone_url(),
3823 'clone_url': pull_request.target_repo.clone_url(),
3791 'repository': pull_request.target_repo.repo_name,
3824 'repository': pull_request.target_repo.repo_name,
3792 'reference': {
3825 'reference': {
3793 'name': pull_request.target_ref_parts.name,
3826 'name': pull_request.target_ref_parts.name,
3794 'type': pull_request.target_ref_parts.type,
3827 'type': pull_request.target_ref_parts.type,
3795 'commit_id': pull_request.target_ref_parts.commit_id,
3828 'commit_id': pull_request.target_ref_parts.commit_id,
3796 },
3829 },
3797 },
3830 },
3798 'merge': merge_data,
3831 'merge': merge_data,
3799 'author': pull_request.author.get_api_data(include_secrets=False,
3832 'author': pull_request.author.get_api_data(include_secrets=False,
3800 details='basic'),
3833 details='basic'),
3801 'reviewers': [
3834 'reviewers': [
3802 {
3835 {
3803 'user': reviewer.get_api_data(include_secrets=False,
3836 'user': reviewer.get_api_data(include_secrets=False,
3804 details='basic'),
3837 details='basic'),
3805 'reasons': reasons,
3838 'reasons': reasons,
3806 'review_status': st[0][1].status if st else 'not_reviewed',
3839 'review_status': st[0][1].status if st else 'not_reviewed',
3807 }
3840 }
3808 for obj, reviewer, reasons, mandatory, st in
3841 for obj, reviewer, reasons, mandatory, st in
3809 pull_request.reviewers_statuses()
3842 pull_request.reviewers_statuses()
3810 ]
3843 ]
3811 }
3844 }
3812
3845
3813 return data
3846 return data
3814
3847
3815 def set_state(self, pull_request_state, final_state=None):
3848 def set_state(self, pull_request_state, final_state=None):
3816 """
3849 """
3817 # goes from initial state to updating to initial state.
3850 # goes from initial state to updating to initial state.
3818 # initial state can be changed by specifying back_state=
3851 # initial state can be changed by specifying back_state=
3819 with pull_request_obj.set_state(PullRequest.STATE_UPDATING):
3852 with pull_request_obj.set_state(PullRequest.STATE_UPDATING):
3820 pull_request.merge()
3853 pull_request.merge()
3821
3854
3822 :param pull_request_state:
3855 :param pull_request_state:
3823 :param final_state:
3856 :param final_state:
3824
3857
3825 """
3858 """
3826
3859
3827 return _SetState(self, pull_request_state, back_state=final_state)
3860 return _SetState(self, pull_request_state, back_state=final_state)
3828
3861
3829
3862
3830 class PullRequest(Base, _PullRequestBase):
3863 class PullRequest(Base, _PullRequestBase):
3831 __tablename__ = 'pull_requests'
3864 __tablename__ = 'pull_requests'
3832 __table_args__ = (
3865 __table_args__ = (
3833 base_table_args,
3866 base_table_args,
3834 )
3867 )
3835
3868
3836 pull_request_id = Column(
3869 pull_request_id = Column(
3837 'pull_request_id', Integer(), nullable=False, primary_key=True)
3870 'pull_request_id', Integer(), nullable=False, primary_key=True)
3838
3871
3839 def __repr__(self):
3872 def __repr__(self):
3840 if self.pull_request_id:
3873 if self.pull_request_id:
3841 return '<DB:PullRequest #%s>' % self.pull_request_id
3874 return '<DB:PullRequest #%s>' % self.pull_request_id
3842 else:
3875 else:
3843 return '<DB:PullRequest at %#x>' % id(self)
3876 return '<DB:PullRequest at %#x>' % id(self)
3844
3877
3845 reviewers = relationship('PullRequestReviewers',
3878 reviewers = relationship('PullRequestReviewers',
3846 cascade="all, delete, delete-orphan")
3879 cascade="all, delete, delete-orphan")
3847 statuses = relationship('ChangesetStatus',
3880 statuses = relationship('ChangesetStatus',
3848 cascade="all, delete, delete-orphan")
3881 cascade="all, delete, delete-orphan")
3849 comments = relationship('ChangesetComment',
3882 comments = relationship('ChangesetComment',
3850 cascade="all, delete, delete-orphan")
3883 cascade="all, delete, delete-orphan")
3851 versions = relationship('PullRequestVersion',
3884 versions = relationship('PullRequestVersion',
3852 cascade="all, delete, delete-orphan",
3885 cascade="all, delete, delete-orphan",
3853 lazy='dynamic')
3886 lazy='dynamic')
3854
3887
3855 @classmethod
3888 @classmethod
3856 def get_pr_display_object(cls, pull_request_obj, org_pull_request_obj,
3889 def get_pr_display_object(cls, pull_request_obj, org_pull_request_obj,
3857 internal_methods=None):
3890 internal_methods=None):
3858
3891
3859 class PullRequestDisplay(object):
3892 class PullRequestDisplay(object):
3860 """
3893 """
3861 Special object wrapper for showing PullRequest data via Versions
3894 Special object wrapper for showing PullRequest data via Versions
3862 It mimics PR object as close as possible. This is read only object
3895 It mimics PR object as close as possible. This is read only object
3863 just for display
3896 just for display
3864 """
3897 """
3865
3898
3866 def __init__(self, attrs, internal=None):
3899 def __init__(self, attrs, internal=None):
3867 self.attrs = attrs
3900 self.attrs = attrs
3868 # internal have priority over the given ones via attrs
3901 # internal have priority over the given ones via attrs
3869 self.internal = internal or ['versions']
3902 self.internal = internal or ['versions']
3870
3903
3871 def __getattr__(self, item):
3904 def __getattr__(self, item):
3872 if item in self.internal:
3905 if item in self.internal:
3873 return getattr(self, item)
3906 return getattr(self, item)
3874 try:
3907 try:
3875 return self.attrs[item]
3908 return self.attrs[item]
3876 except KeyError:
3909 except KeyError:
3877 raise AttributeError(
3910 raise AttributeError(
3878 '%s object has no attribute %s' % (self, item))
3911 '%s object has no attribute %s' % (self, item))
3879
3912
3880 def __repr__(self):
3913 def __repr__(self):
3881 return '<DB:PullRequestDisplay #%s>' % self.attrs.get('pull_request_id')
3914 return '<DB:PullRequestDisplay #%s>' % self.attrs.get('pull_request_id')
3882
3915
3883 def versions(self):
3916 def versions(self):
3884 return pull_request_obj.versions.order_by(
3917 return pull_request_obj.versions.order_by(
3885 PullRequestVersion.pull_request_version_id).all()
3918 PullRequestVersion.pull_request_version_id).all()
3886
3919
3887 def is_closed(self):
3920 def is_closed(self):
3888 return pull_request_obj.is_closed()
3921 return pull_request_obj.is_closed()
3889
3922
3890 @property
3923 @property
3891 def pull_request_version_id(self):
3924 def pull_request_version_id(self):
3892 return getattr(pull_request_obj, 'pull_request_version_id', None)
3925 return getattr(pull_request_obj, 'pull_request_version_id', None)
3893
3926
3894 attrs = StrictAttributeDict(pull_request_obj.get_api_data())
3927 attrs = StrictAttributeDict(pull_request_obj.get_api_data())
3895
3928
3896 attrs.author = StrictAttributeDict(
3929 attrs.author = StrictAttributeDict(
3897 pull_request_obj.author.get_api_data())
3930 pull_request_obj.author.get_api_data())
3898 if pull_request_obj.target_repo:
3931 if pull_request_obj.target_repo:
3899 attrs.target_repo = StrictAttributeDict(
3932 attrs.target_repo = StrictAttributeDict(
3900 pull_request_obj.target_repo.get_api_data())
3933 pull_request_obj.target_repo.get_api_data())
3901 attrs.target_repo.clone_url = pull_request_obj.target_repo.clone_url
3934 attrs.target_repo.clone_url = pull_request_obj.target_repo.clone_url
3902
3935
3903 if pull_request_obj.source_repo:
3936 if pull_request_obj.source_repo:
3904 attrs.source_repo = StrictAttributeDict(
3937 attrs.source_repo = StrictAttributeDict(
3905 pull_request_obj.source_repo.get_api_data())
3938 pull_request_obj.source_repo.get_api_data())
3906 attrs.source_repo.clone_url = pull_request_obj.source_repo.clone_url
3939 attrs.source_repo.clone_url = pull_request_obj.source_repo.clone_url
3907
3940
3908 attrs.source_ref_parts = pull_request_obj.source_ref_parts
3941 attrs.source_ref_parts = pull_request_obj.source_ref_parts
3909 attrs.target_ref_parts = pull_request_obj.target_ref_parts
3942 attrs.target_ref_parts = pull_request_obj.target_ref_parts
3910 attrs.revisions = pull_request_obj.revisions
3943 attrs.revisions = pull_request_obj.revisions
3911
3944
3912 attrs.shadow_merge_ref = org_pull_request_obj.shadow_merge_ref
3945 attrs.shadow_merge_ref = org_pull_request_obj.shadow_merge_ref
3913 attrs.reviewer_data = org_pull_request_obj.reviewer_data
3946 attrs.reviewer_data = org_pull_request_obj.reviewer_data
3914 attrs.reviewer_data_json = org_pull_request_obj.reviewer_data_json
3947 attrs.reviewer_data_json = org_pull_request_obj.reviewer_data_json
3915
3948
3916 return PullRequestDisplay(attrs, internal=internal_methods)
3949 return PullRequestDisplay(attrs, internal=internal_methods)
3917
3950
3918 def is_closed(self):
3951 def is_closed(self):
3919 return self.status == self.STATUS_CLOSED
3952 return self.status == self.STATUS_CLOSED
3920
3953
3921 def __json__(self):
3954 def __json__(self):
3922 return {
3955 return {
3923 'revisions': self.revisions,
3956 'revisions': self.revisions,
3924 }
3957 }
3925
3958
3926 def calculated_review_status(self):
3959 def calculated_review_status(self):
3927 from rhodecode.model.changeset_status import ChangesetStatusModel
3960 from rhodecode.model.changeset_status import ChangesetStatusModel
3928 return ChangesetStatusModel().calculated_review_status(self)
3961 return ChangesetStatusModel().calculated_review_status(self)
3929
3962
3930 def reviewers_statuses(self):
3963 def reviewers_statuses(self):
3931 from rhodecode.model.changeset_status import ChangesetStatusModel
3964 from rhodecode.model.changeset_status import ChangesetStatusModel
3932 return ChangesetStatusModel().reviewers_statuses(self)
3965 return ChangesetStatusModel().reviewers_statuses(self)
3933
3966
3934 @property
3967 @property
3935 def workspace_id(self):
3968 def workspace_id(self):
3936 from rhodecode.model.pull_request import PullRequestModel
3969 from rhodecode.model.pull_request import PullRequestModel
3937 return PullRequestModel()._workspace_id(self)
3970 return PullRequestModel()._workspace_id(self)
3938
3971
3939 def get_shadow_repo(self):
3972 def get_shadow_repo(self):
3940 workspace_id = self.workspace_id
3973 workspace_id = self.workspace_id
3941 vcs_obj = self.target_repo.scm_instance()
3974 vcs_obj = self.target_repo.scm_instance()
3942 shadow_repository_path = vcs_obj._get_shadow_repository_path(
3975 shadow_repository_path = vcs_obj._get_shadow_repository_path(
3943 self.target_repo.repo_id, workspace_id)
3976 self.target_repo.repo_id, workspace_id)
3944 if os.path.isdir(shadow_repository_path):
3977 if os.path.isdir(shadow_repository_path):
3945 return vcs_obj._get_shadow_instance(shadow_repository_path)
3978 return vcs_obj._get_shadow_instance(shadow_repository_path)
3946
3979
3947
3980
3948 class PullRequestVersion(Base, _PullRequestBase):
3981 class PullRequestVersion(Base, _PullRequestBase):
3949 __tablename__ = 'pull_request_versions'
3982 __tablename__ = 'pull_request_versions'
3950 __table_args__ = (
3983 __table_args__ = (
3951 base_table_args,
3984 base_table_args,
3952 )
3985 )
3953
3986
3954 pull_request_version_id = Column(
3987 pull_request_version_id = Column(
3955 'pull_request_version_id', Integer(), nullable=False, primary_key=True)
3988 'pull_request_version_id', Integer(), nullable=False, primary_key=True)
3956 pull_request_id = Column(
3989 pull_request_id = Column(
3957 'pull_request_id', Integer(),
3990 'pull_request_id', Integer(),
3958 ForeignKey('pull_requests.pull_request_id'), nullable=False)
3991 ForeignKey('pull_requests.pull_request_id'), nullable=False)
3959 pull_request = relationship('PullRequest')
3992 pull_request = relationship('PullRequest')
3960
3993
3961 def __repr__(self):
3994 def __repr__(self):
3962 if self.pull_request_version_id:
3995 if self.pull_request_version_id:
3963 return '<DB:PullRequestVersion #%s>' % self.pull_request_version_id
3996 return '<DB:PullRequestVersion #%s>' % self.pull_request_version_id
3964 else:
3997 else:
3965 return '<DB:PullRequestVersion at %#x>' % id(self)
3998 return '<DB:PullRequestVersion at %#x>' % id(self)
3966
3999
3967 @property
4000 @property
3968 def reviewers(self):
4001 def reviewers(self):
3969 return self.pull_request.reviewers
4002 return self.pull_request.reviewers
3970
4003
3971 @property
4004 @property
3972 def versions(self):
4005 def versions(self):
3973 return self.pull_request.versions
4006 return self.pull_request.versions
3974
4007
3975 def is_closed(self):
4008 def is_closed(self):
3976 # calculate from original
4009 # calculate from original
3977 return self.pull_request.status == self.STATUS_CLOSED
4010 return self.pull_request.status == self.STATUS_CLOSED
3978
4011
3979 def calculated_review_status(self):
4012 def calculated_review_status(self):
3980 return self.pull_request.calculated_review_status()
4013 return self.pull_request.calculated_review_status()
3981
4014
3982 def reviewers_statuses(self):
4015 def reviewers_statuses(self):
3983 return self.pull_request.reviewers_statuses()
4016 return self.pull_request.reviewers_statuses()
3984
4017
3985
4018
3986 class PullRequestReviewers(Base, BaseModel):
4019 class PullRequestReviewers(Base, BaseModel):
3987 __tablename__ = 'pull_request_reviewers'
4020 __tablename__ = 'pull_request_reviewers'
3988 __table_args__ = (
4021 __table_args__ = (
3989 base_table_args,
4022 base_table_args,
3990 )
4023 )
3991
4024
3992 @hybrid_property
4025 @hybrid_property
3993 def reasons(self):
4026 def reasons(self):
3994 if not self._reasons:
4027 if not self._reasons:
3995 return []
4028 return []
3996 return self._reasons
4029 return self._reasons
3997
4030
3998 @reasons.setter
4031 @reasons.setter
3999 def reasons(self, val):
4032 def reasons(self, val):
4000 val = val or []
4033 val = val or []
4001 if any(not isinstance(x, basestring) for x in val):
4034 if any(not isinstance(x, basestring) for x in val):
4002 raise Exception('invalid reasons type, must be list of strings')
4035 raise Exception('invalid reasons type, must be list of strings')
4003 self._reasons = val
4036 self._reasons = val
4004
4037
4005 pull_requests_reviewers_id = Column(
4038 pull_requests_reviewers_id = Column(
4006 'pull_requests_reviewers_id', Integer(), nullable=False,
4039 'pull_requests_reviewers_id', Integer(), nullable=False,
4007 primary_key=True)
4040 primary_key=True)
4008 pull_request_id = Column(
4041 pull_request_id = Column(
4009 "pull_request_id", Integer(),
4042 "pull_request_id", Integer(),
4010 ForeignKey('pull_requests.pull_request_id'), nullable=False)
4043 ForeignKey('pull_requests.pull_request_id'), nullable=False)
4011 user_id = Column(
4044 user_id = Column(
4012 "user_id", Integer(), ForeignKey('users.user_id'), nullable=True)
4045 "user_id", Integer(), ForeignKey('users.user_id'), nullable=True)
4013 _reasons = Column(
4046 _reasons = Column(
4014 'reason', MutationList.as_mutable(
4047 'reason', MutationList.as_mutable(
4015 JsonType('list', dialect_map=dict(mysql=UnicodeText(16384)))))
4048 JsonType('list', dialect_map=dict(mysql=UnicodeText(16384)))))
4016
4049
4017 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4050 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4018 user = relationship('User')
4051 user = relationship('User')
4019 pull_request = relationship('PullRequest')
4052 pull_request = relationship('PullRequest')
4020
4053
4021 rule_data = Column(
4054 rule_data = Column(
4022 'rule_data_json',
4055 'rule_data_json',
4023 JsonType(dialect_map=dict(mysql=UnicodeText(16384))))
4056 JsonType(dialect_map=dict(mysql=UnicodeText(16384))))
4024
4057
4025 def rule_user_group_data(self):
4058 def rule_user_group_data(self):
4026 """
4059 """
4027 Returns the voting user group rule data for this reviewer
4060 Returns the voting user group rule data for this reviewer
4028 """
4061 """
4029
4062
4030 if self.rule_data and 'vote_rule' in self.rule_data:
4063 if self.rule_data and 'vote_rule' in self.rule_data:
4031 user_group_data = {}
4064 user_group_data = {}
4032 if 'rule_user_group_entry_id' in self.rule_data:
4065 if 'rule_user_group_entry_id' in self.rule_data:
4033 # means a group with voting rules !
4066 # means a group with voting rules !
4034 user_group_data['id'] = self.rule_data['rule_user_group_entry_id']
4067 user_group_data['id'] = self.rule_data['rule_user_group_entry_id']
4035 user_group_data['name'] = self.rule_data['rule_name']
4068 user_group_data['name'] = self.rule_data['rule_name']
4036 user_group_data['vote_rule'] = self.rule_data['vote_rule']
4069 user_group_data['vote_rule'] = self.rule_data['vote_rule']
4037
4070
4038 return user_group_data
4071 return user_group_data
4039
4072
4040 def __unicode__(self):
4073 def __unicode__(self):
4041 return u"<%s('id:%s')>" % (self.__class__.__name__,
4074 return u"<%s('id:%s')>" % (self.__class__.__name__,
4042 self.pull_requests_reviewers_id)
4075 self.pull_requests_reviewers_id)
4043
4076
4044
4077
4045 class Notification(Base, BaseModel):
4078 class Notification(Base, BaseModel):
4046 __tablename__ = 'notifications'
4079 __tablename__ = 'notifications'
4047 __table_args__ = (
4080 __table_args__ = (
4048 Index('notification_type_idx', 'type'),
4081 Index('notification_type_idx', 'type'),
4049 base_table_args,
4082 base_table_args,
4050 )
4083 )
4051
4084
4052 TYPE_CHANGESET_COMMENT = u'cs_comment'
4085 TYPE_CHANGESET_COMMENT = u'cs_comment'
4053 TYPE_MESSAGE = u'message'
4086 TYPE_MESSAGE = u'message'
4054 TYPE_MENTION = u'mention'
4087 TYPE_MENTION = u'mention'
4055 TYPE_REGISTRATION = u'registration'
4088 TYPE_REGISTRATION = u'registration'
4056 TYPE_PULL_REQUEST = u'pull_request'
4089 TYPE_PULL_REQUEST = u'pull_request'
4057 TYPE_PULL_REQUEST_COMMENT = u'pull_request_comment'
4090 TYPE_PULL_REQUEST_COMMENT = u'pull_request_comment'
4058
4091
4059 notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True)
4092 notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True)
4060 subject = Column('subject', Unicode(512), nullable=True)
4093 subject = Column('subject', Unicode(512), nullable=True)
4061 body = Column('body', UnicodeText().with_variant(UnicodeText(50000), 'mysql'), nullable=True)
4094 body = Column('body', UnicodeText().with_variant(UnicodeText(50000), 'mysql'), nullable=True)
4062 created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True)
4095 created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True)
4063 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4096 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4064 type_ = Column('type', Unicode(255))
4097 type_ = Column('type', Unicode(255))
4065
4098
4066 created_by_user = relationship('User')
4099 created_by_user = relationship('User')
4067 notifications_to_users = relationship('UserNotification', lazy='joined',
4100 notifications_to_users = relationship('UserNotification', lazy='joined',
4068 cascade="all, delete, delete-orphan")
4101 cascade="all, delete, delete-orphan")
4069
4102
4070 @property
4103 @property
4071 def recipients(self):
4104 def recipients(self):
4072 return [x.user for x in UserNotification.query()\
4105 return [x.user for x in UserNotification.query()\
4073 .filter(UserNotification.notification == self)\
4106 .filter(UserNotification.notification == self)\
4074 .order_by(UserNotification.user_id.asc()).all()]
4107 .order_by(UserNotification.user_id.asc()).all()]
4075
4108
4076 @classmethod
4109 @classmethod
4077 def create(cls, created_by, subject, body, recipients, type_=None):
4110 def create(cls, created_by, subject, body, recipients, type_=None):
4078 if type_ is None:
4111 if type_ is None:
4079 type_ = Notification.TYPE_MESSAGE
4112 type_ = Notification.TYPE_MESSAGE
4080
4113
4081 notification = cls()
4114 notification = cls()
4082 notification.created_by_user = created_by
4115 notification.created_by_user = created_by
4083 notification.subject = subject
4116 notification.subject = subject
4084 notification.body = body
4117 notification.body = body
4085 notification.type_ = type_
4118 notification.type_ = type_
4086 notification.created_on = datetime.datetime.now()
4119 notification.created_on = datetime.datetime.now()
4087
4120
4088 # For each recipient link the created notification to his account
4121 # For each recipient link the created notification to his account
4089 for u in recipients:
4122 for u in recipients:
4090 assoc = UserNotification()
4123 assoc = UserNotification()
4091 assoc.user_id = u.user_id
4124 assoc.user_id = u.user_id
4092 assoc.notification = notification
4125 assoc.notification = notification
4093
4126
4094 # if created_by is inside recipients mark his notification
4127 # if created_by is inside recipients mark his notification
4095 # as read
4128 # as read
4096 if u.user_id == created_by.user_id:
4129 if u.user_id == created_by.user_id:
4097 assoc.read = True
4130 assoc.read = True
4098 Session().add(assoc)
4131 Session().add(assoc)
4099
4132
4100 Session().add(notification)
4133 Session().add(notification)
4101
4134
4102 return notification
4135 return notification
4103
4136
4104
4137
4105 class UserNotification(Base, BaseModel):
4138 class UserNotification(Base, BaseModel):
4106 __tablename__ = 'user_to_notification'
4139 __tablename__ = 'user_to_notification'
4107 __table_args__ = (
4140 __table_args__ = (
4108 UniqueConstraint('user_id', 'notification_id'),
4141 UniqueConstraint('user_id', 'notification_id'),
4109 base_table_args
4142 base_table_args
4110 )
4143 )
4111
4144
4112 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
4145 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
4113 notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
4146 notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
4114 read = Column('read', Boolean, default=False)
4147 read = Column('read', Boolean, default=False)
4115 sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
4148 sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
4116
4149
4117 user = relationship('User', lazy="joined")
4150 user = relationship('User', lazy="joined")
4118 notification = relationship('Notification', lazy="joined",
4151 notification = relationship('Notification', lazy="joined",
4119 order_by=lambda: Notification.created_on.desc(),)
4152 order_by=lambda: Notification.created_on.desc(),)
4120
4153
4121 def mark_as_read(self):
4154 def mark_as_read(self):
4122 self.read = True
4155 self.read = True
4123 Session().add(self)
4156 Session().add(self)
4124
4157
4125
4158
4126 class Gist(Base, BaseModel):
4159 class Gist(Base, BaseModel):
4127 __tablename__ = 'gists'
4160 __tablename__ = 'gists'
4128 __table_args__ = (
4161 __table_args__ = (
4129 Index('g_gist_access_id_idx', 'gist_access_id'),
4162 Index('g_gist_access_id_idx', 'gist_access_id'),
4130 Index('g_created_on_idx', 'created_on'),
4163 Index('g_created_on_idx', 'created_on'),
4131 base_table_args
4164 base_table_args
4132 )
4165 )
4133
4166
4134 GIST_PUBLIC = u'public'
4167 GIST_PUBLIC = u'public'
4135 GIST_PRIVATE = u'private'
4168 GIST_PRIVATE = u'private'
4136 DEFAULT_FILENAME = u'gistfile1.txt'
4169 DEFAULT_FILENAME = u'gistfile1.txt'
4137
4170
4138 ACL_LEVEL_PUBLIC = u'acl_public'
4171 ACL_LEVEL_PUBLIC = u'acl_public'
4139 ACL_LEVEL_PRIVATE = u'acl_private'
4172 ACL_LEVEL_PRIVATE = u'acl_private'
4140
4173
4141 gist_id = Column('gist_id', Integer(), primary_key=True)
4174 gist_id = Column('gist_id', Integer(), primary_key=True)
4142 gist_access_id = Column('gist_access_id', Unicode(250))
4175 gist_access_id = Column('gist_access_id', Unicode(250))
4143 gist_description = Column('gist_description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
4176 gist_description = Column('gist_description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
4144 gist_owner = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True)
4177 gist_owner = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True)
4145 gist_expires = Column('gist_expires', Float(53), nullable=False)
4178 gist_expires = Column('gist_expires', Float(53), nullable=False)
4146 gist_type = Column('gist_type', Unicode(128), nullable=False)
4179 gist_type = Column('gist_type', Unicode(128), nullable=False)
4147 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4180 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4148 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4181 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4149 acl_level = Column('acl_level', Unicode(128), nullable=True)
4182 acl_level = Column('acl_level', Unicode(128), nullable=True)
4150
4183
4151 owner = relationship('User')
4184 owner = relationship('User')
4152
4185
4153 def __repr__(self):
4186 def __repr__(self):
4154 return '<Gist:[%s]%s>' % (self.gist_type, self.gist_access_id)
4187 return '<Gist:[%s]%s>' % (self.gist_type, self.gist_access_id)
4155
4188
4156 @hybrid_property
4189 @hybrid_property
4157 def description_safe(self):
4190 def description_safe(self):
4158 from rhodecode.lib import helpers as h
4191 from rhodecode.lib import helpers as h
4159 return h.escape(self.gist_description)
4192 return h.escape(self.gist_description)
4160
4193
4161 @classmethod
4194 @classmethod
4162 def get_or_404(cls, id_):
4195 def get_or_404(cls, id_):
4163 from pyramid.httpexceptions import HTTPNotFound
4196 from pyramid.httpexceptions import HTTPNotFound
4164
4197
4165 res = cls.query().filter(cls.gist_access_id == id_).scalar()
4198 res = cls.query().filter(cls.gist_access_id == id_).scalar()
4166 if not res:
4199 if not res:
4167 raise HTTPNotFound()
4200 raise HTTPNotFound()
4168 return res
4201 return res
4169
4202
4170 @classmethod
4203 @classmethod
4171 def get_by_access_id(cls, gist_access_id):
4204 def get_by_access_id(cls, gist_access_id):
4172 return cls.query().filter(cls.gist_access_id == gist_access_id).scalar()
4205 return cls.query().filter(cls.gist_access_id == gist_access_id).scalar()
4173
4206
4174 def gist_url(self):
4207 def gist_url(self):
4175 from rhodecode.model.gist import GistModel
4208 from rhodecode.model.gist import GistModel
4176 return GistModel().get_url(self)
4209 return GistModel().get_url(self)
4177
4210
4178 @classmethod
4211 @classmethod
4179 def base_path(cls):
4212 def base_path(cls):
4180 """
4213 """
4181 Returns base path when all gists are stored
4214 Returns base path when all gists are stored
4182
4215
4183 :param cls:
4216 :param cls:
4184 """
4217 """
4185 from rhodecode.model.gist import GIST_STORE_LOC
4218 from rhodecode.model.gist import GIST_STORE_LOC
4186 q = Session().query(RhodeCodeUi)\
4219 q = Session().query(RhodeCodeUi)\
4187 .filter(RhodeCodeUi.ui_key == URL_SEP)
4220 .filter(RhodeCodeUi.ui_key == URL_SEP)
4188 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
4221 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
4189 return os.path.join(q.one().ui_value, GIST_STORE_LOC)
4222 return os.path.join(q.one().ui_value, GIST_STORE_LOC)
4190
4223
4191 def get_api_data(self):
4224 def get_api_data(self):
4192 """
4225 """
4193 Common function for generating gist related data for API
4226 Common function for generating gist related data for API
4194 """
4227 """
4195 gist = self
4228 gist = self
4196 data = {
4229 data = {
4197 'gist_id': gist.gist_id,
4230 'gist_id': gist.gist_id,
4198 'type': gist.gist_type,
4231 'type': gist.gist_type,
4199 'access_id': gist.gist_access_id,
4232 'access_id': gist.gist_access_id,
4200 'description': gist.gist_description,
4233 'description': gist.gist_description,
4201 'url': gist.gist_url(),
4234 'url': gist.gist_url(),
4202 'expires': gist.gist_expires,
4235 'expires': gist.gist_expires,
4203 'created_on': gist.created_on,
4236 'created_on': gist.created_on,
4204 'modified_at': gist.modified_at,
4237 'modified_at': gist.modified_at,
4205 'content': None,
4238 'content': None,
4206 'acl_level': gist.acl_level,
4239 'acl_level': gist.acl_level,
4207 }
4240 }
4208 return data
4241 return data
4209
4242
4210 def __json__(self):
4243 def __json__(self):
4211 data = dict(
4244 data = dict(
4212 )
4245 )
4213 data.update(self.get_api_data())
4246 data.update(self.get_api_data())
4214 return data
4247 return data
4215 # SCM functions
4248 # SCM functions
4216
4249
4217 def scm_instance(self, **kwargs):
4250 def scm_instance(self, **kwargs):
4218 full_repo_path = os.path.join(self.base_path(), self.gist_access_id)
4251 full_repo_path = os.path.join(self.base_path(), self.gist_access_id)
4219 return get_vcs_instance(
4252 return get_vcs_instance(
4220 repo_path=safe_str(full_repo_path), create=False)
4253 repo_path=safe_str(full_repo_path), create=False)
4221
4254
4222
4255
4223 class ExternalIdentity(Base, BaseModel):
4256 class ExternalIdentity(Base, BaseModel):
4224 __tablename__ = 'external_identities'
4257 __tablename__ = 'external_identities'
4225 __table_args__ = (
4258 __table_args__ = (
4226 Index('local_user_id_idx', 'local_user_id'),
4259 Index('local_user_id_idx', 'local_user_id'),
4227 Index('external_id_idx', 'external_id'),
4260 Index('external_id_idx', 'external_id'),
4228 base_table_args
4261 base_table_args
4229 )
4262 )
4230
4263
4231 external_id = Column('external_id', Unicode(255), default=u'', primary_key=True)
4264 external_id = Column('external_id', Unicode(255), default=u'', primary_key=True)
4232 external_username = Column('external_username', Unicode(1024), default=u'')
4265 external_username = Column('external_username', Unicode(1024), default=u'')
4233 local_user_id = Column('local_user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
4266 local_user_id = Column('local_user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
4234 provider_name = Column('provider_name', Unicode(255), default=u'', primary_key=True)
4267 provider_name = Column('provider_name', Unicode(255), default=u'', primary_key=True)
4235 access_token = Column('access_token', String(1024), default=u'')
4268 access_token = Column('access_token', String(1024), default=u'')
4236 alt_token = Column('alt_token', String(1024), default=u'')
4269 alt_token = Column('alt_token', String(1024), default=u'')
4237 token_secret = Column('token_secret', String(1024), default=u'')
4270 token_secret = Column('token_secret', String(1024), default=u'')
4238
4271
4239 @classmethod
4272 @classmethod
4240 def by_external_id_and_provider(cls, external_id, provider_name, local_user_id=None):
4273 def by_external_id_and_provider(cls, external_id, provider_name, local_user_id=None):
4241 """
4274 """
4242 Returns ExternalIdentity instance based on search params
4275 Returns ExternalIdentity instance based on search params
4243
4276
4244 :param external_id:
4277 :param external_id:
4245 :param provider_name:
4278 :param provider_name:
4246 :return: ExternalIdentity
4279 :return: ExternalIdentity
4247 """
4280 """
4248 query = cls.query()
4281 query = cls.query()
4249 query = query.filter(cls.external_id == external_id)
4282 query = query.filter(cls.external_id == external_id)
4250 query = query.filter(cls.provider_name == provider_name)
4283 query = query.filter(cls.provider_name == provider_name)
4251 if local_user_id:
4284 if local_user_id:
4252 query = query.filter(cls.local_user_id == local_user_id)
4285 query = query.filter(cls.local_user_id == local_user_id)
4253 return query.first()
4286 return query.first()
4254
4287
4255 @classmethod
4288 @classmethod
4256 def user_by_external_id_and_provider(cls, external_id, provider_name):
4289 def user_by_external_id_and_provider(cls, external_id, provider_name):
4257 """
4290 """
4258 Returns User instance based on search params
4291 Returns User instance based on search params
4259
4292
4260 :param external_id:
4293 :param external_id:
4261 :param provider_name:
4294 :param provider_name:
4262 :return: User
4295 :return: User
4263 """
4296 """
4264 query = User.query()
4297 query = User.query()
4265 query = query.filter(cls.external_id == external_id)
4298 query = query.filter(cls.external_id == external_id)
4266 query = query.filter(cls.provider_name == provider_name)
4299 query = query.filter(cls.provider_name == provider_name)
4267 query = query.filter(User.user_id == cls.local_user_id)
4300 query = query.filter(User.user_id == cls.local_user_id)
4268 return query.first()
4301 return query.first()
4269
4302
4270 @classmethod
4303 @classmethod
4271 def by_local_user_id(cls, local_user_id):
4304 def by_local_user_id(cls, local_user_id):
4272 """
4305 """
4273 Returns all tokens for user
4306 Returns all tokens for user
4274
4307
4275 :param local_user_id:
4308 :param local_user_id:
4276 :return: ExternalIdentity
4309 :return: ExternalIdentity
4277 """
4310 """
4278 query = cls.query()
4311 query = cls.query()
4279 query = query.filter(cls.local_user_id == local_user_id)
4312 query = query.filter(cls.local_user_id == local_user_id)
4280 return query
4313 return query
4281
4314
4282 @classmethod
4315 @classmethod
4283 def load_provider_plugin(cls, plugin_id):
4316 def load_provider_plugin(cls, plugin_id):
4284 from rhodecode.authentication.base import loadplugin
4317 from rhodecode.authentication.base import loadplugin
4285 _plugin_id = 'egg:rhodecode-enterprise-ee#{}'.format(plugin_id)
4318 _plugin_id = 'egg:rhodecode-enterprise-ee#{}'.format(plugin_id)
4286 auth_plugin = loadplugin(_plugin_id)
4319 auth_plugin = loadplugin(_plugin_id)
4287 return auth_plugin
4320 return auth_plugin
4288
4321
4289
4322
4290 class Integration(Base, BaseModel):
4323 class Integration(Base, BaseModel):
4291 __tablename__ = 'integrations'
4324 __tablename__ = 'integrations'
4292 __table_args__ = (
4325 __table_args__ = (
4293 base_table_args
4326 base_table_args
4294 )
4327 )
4295
4328
4296 integration_id = Column('integration_id', Integer(), primary_key=True)
4329 integration_id = Column('integration_id', Integer(), primary_key=True)
4297 integration_type = Column('integration_type', String(255))
4330 integration_type = Column('integration_type', String(255))
4298 enabled = Column('enabled', Boolean(), nullable=False)
4331 enabled = Column('enabled', Boolean(), nullable=False)
4299 name = Column('name', String(255), nullable=False)
4332 name = Column('name', String(255), nullable=False)
4300 child_repos_only = Column('child_repos_only', Boolean(), nullable=False,
4333 child_repos_only = Column('child_repos_only', Boolean(), nullable=False,
4301 default=False)
4334 default=False)
4302
4335
4303 settings = Column(
4336 settings = Column(
4304 'settings_json', MutationObj.as_mutable(
4337 'settings_json', MutationObj.as_mutable(
4305 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
4338 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
4306 repo_id = Column(
4339 repo_id = Column(
4307 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
4340 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
4308 nullable=True, unique=None, default=None)
4341 nullable=True, unique=None, default=None)
4309 repo = relationship('Repository', lazy='joined')
4342 repo = relationship('Repository', lazy='joined')
4310
4343
4311 repo_group_id = Column(
4344 repo_group_id = Column(
4312 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
4345 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
4313 nullable=True, unique=None, default=None)
4346 nullable=True, unique=None, default=None)
4314 repo_group = relationship('RepoGroup', lazy='joined')
4347 repo_group = relationship('RepoGroup', lazy='joined')
4315
4348
4316 @property
4349 @property
4317 def scope(self):
4350 def scope(self):
4318 if self.repo:
4351 if self.repo:
4319 return repr(self.repo)
4352 return repr(self.repo)
4320 if self.repo_group:
4353 if self.repo_group:
4321 if self.child_repos_only:
4354 if self.child_repos_only:
4322 return repr(self.repo_group) + ' (child repos only)'
4355 return repr(self.repo_group) + ' (child repos only)'
4323 else:
4356 else:
4324 return repr(self.repo_group) + ' (recursive)'
4357 return repr(self.repo_group) + ' (recursive)'
4325 if self.child_repos_only:
4358 if self.child_repos_only:
4326 return 'root_repos'
4359 return 'root_repos'
4327 return 'global'
4360 return 'global'
4328
4361
4329 def __repr__(self):
4362 def __repr__(self):
4330 return '<Integration(%r, %r)>' % (self.integration_type, self.scope)
4363 return '<Integration(%r, %r)>' % (self.integration_type, self.scope)
4331
4364
4332
4365
4333 class RepoReviewRuleUser(Base, BaseModel):
4366 class RepoReviewRuleUser(Base, BaseModel):
4334 __tablename__ = 'repo_review_rules_users'
4367 __tablename__ = 'repo_review_rules_users'
4335 __table_args__ = (
4368 __table_args__ = (
4336 base_table_args
4369 base_table_args
4337 )
4370 )
4338
4371
4339 repo_review_rule_user_id = Column('repo_review_rule_user_id', Integer(), primary_key=True)
4372 repo_review_rule_user_id = Column('repo_review_rule_user_id', Integer(), primary_key=True)
4340 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
4373 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
4341 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False)
4374 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False)
4342 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4375 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4343 user = relationship('User')
4376 user = relationship('User')
4344
4377
4345 def rule_data(self):
4378 def rule_data(self):
4346 return {
4379 return {
4347 'mandatory': self.mandatory
4380 'mandatory': self.mandatory
4348 }
4381 }
4349
4382
4350
4383
4351 class RepoReviewRuleUserGroup(Base, BaseModel):
4384 class RepoReviewRuleUserGroup(Base, BaseModel):
4352 __tablename__ = 'repo_review_rules_users_groups'
4385 __tablename__ = 'repo_review_rules_users_groups'
4353 __table_args__ = (
4386 __table_args__ = (
4354 base_table_args
4387 base_table_args
4355 )
4388 )
4356
4389
4357 VOTE_RULE_ALL = -1
4390 VOTE_RULE_ALL = -1
4358
4391
4359 repo_review_rule_users_group_id = Column('repo_review_rule_users_group_id', Integer(), primary_key=True)
4392 repo_review_rule_users_group_id = Column('repo_review_rule_users_group_id', Integer(), primary_key=True)
4360 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
4393 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
4361 users_group_id = Column("users_group_id", Integer(),ForeignKey('users_groups.users_group_id'), nullable=False)
4394 users_group_id = Column("users_group_id", Integer(),ForeignKey('users_groups.users_group_id'), nullable=False)
4362 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4395 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4363 vote_rule = Column("vote_rule", Integer(), nullable=True, default=VOTE_RULE_ALL)
4396 vote_rule = Column("vote_rule", Integer(), nullable=True, default=VOTE_RULE_ALL)
4364 users_group = relationship('UserGroup')
4397 users_group = relationship('UserGroup')
4365
4398
4366 def rule_data(self):
4399 def rule_data(self):
4367 return {
4400 return {
4368 'mandatory': self.mandatory,
4401 'mandatory': self.mandatory,
4369 'vote_rule': self.vote_rule
4402 'vote_rule': self.vote_rule
4370 }
4403 }
4371
4404
4372 @property
4405 @property
4373 def vote_rule_label(self):
4406 def vote_rule_label(self):
4374 if not self.vote_rule or self.vote_rule == self.VOTE_RULE_ALL:
4407 if not self.vote_rule or self.vote_rule == self.VOTE_RULE_ALL:
4375 return 'all must vote'
4408 return 'all must vote'
4376 else:
4409 else:
4377 return 'min. vote {}'.format(self.vote_rule)
4410 return 'min. vote {}'.format(self.vote_rule)
4378
4411
4379
4412
4380 class RepoReviewRule(Base, BaseModel):
4413 class RepoReviewRule(Base, BaseModel):
4381 __tablename__ = 'repo_review_rules'
4414 __tablename__ = 'repo_review_rules'
4382 __table_args__ = (
4415 __table_args__ = (
4383 base_table_args
4416 base_table_args
4384 )
4417 )
4385
4418
4386 repo_review_rule_id = Column(
4419 repo_review_rule_id = Column(
4387 'repo_review_rule_id', Integer(), primary_key=True)
4420 'repo_review_rule_id', Integer(), primary_key=True)
4388 repo_id = Column(
4421 repo_id = Column(
4389 "repo_id", Integer(), ForeignKey('repositories.repo_id'))
4422 "repo_id", Integer(), ForeignKey('repositories.repo_id'))
4390 repo = relationship('Repository', backref='review_rules')
4423 repo = relationship('Repository', backref='review_rules')
4391
4424
4392 review_rule_name = Column('review_rule_name', String(255))
4425 review_rule_name = Column('review_rule_name', String(255))
4393 _branch_pattern = Column("branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4426 _branch_pattern = Column("branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4394 _target_branch_pattern = Column("target_branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4427 _target_branch_pattern = Column("target_branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4395 _file_pattern = Column("file_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4428 _file_pattern = Column("file_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4396
4429
4397 use_authors_for_review = Column("use_authors_for_review", Boolean(), nullable=False, default=False)
4430 use_authors_for_review = Column("use_authors_for_review", Boolean(), nullable=False, default=False)
4398 forbid_author_to_review = Column("forbid_author_to_review", Boolean(), nullable=False, default=False)
4431 forbid_author_to_review = Column("forbid_author_to_review", Boolean(), nullable=False, default=False)
4399 forbid_commit_author_to_review = Column("forbid_commit_author_to_review", Boolean(), nullable=False, default=False)
4432 forbid_commit_author_to_review = Column("forbid_commit_author_to_review", Boolean(), nullable=False, default=False)
4400 forbid_adding_reviewers = Column("forbid_adding_reviewers", Boolean(), nullable=False, default=False)
4433 forbid_adding_reviewers = Column("forbid_adding_reviewers", Boolean(), nullable=False, default=False)
4401
4434
4402 rule_users = relationship('RepoReviewRuleUser')
4435 rule_users = relationship('RepoReviewRuleUser')
4403 rule_user_groups = relationship('RepoReviewRuleUserGroup')
4436 rule_user_groups = relationship('RepoReviewRuleUserGroup')
4404
4437
4405 def _validate_pattern(self, value):
4438 def _validate_pattern(self, value):
4406 re.compile('^' + glob2re(value) + '$')
4439 re.compile('^' + glob2re(value) + '$')
4407
4440
4408 @hybrid_property
4441 @hybrid_property
4409 def source_branch_pattern(self):
4442 def source_branch_pattern(self):
4410 return self._branch_pattern or '*'
4443 return self._branch_pattern or '*'
4411
4444
4412 @source_branch_pattern.setter
4445 @source_branch_pattern.setter
4413 def source_branch_pattern(self, value):
4446 def source_branch_pattern(self, value):
4414 self._validate_pattern(value)
4447 self._validate_pattern(value)
4415 self._branch_pattern = value or '*'
4448 self._branch_pattern = value or '*'
4416
4449
4417 @hybrid_property
4450 @hybrid_property
4418 def target_branch_pattern(self):
4451 def target_branch_pattern(self):
4419 return self._target_branch_pattern or '*'
4452 return self._target_branch_pattern or '*'
4420
4453
4421 @target_branch_pattern.setter
4454 @target_branch_pattern.setter
4422 def target_branch_pattern(self, value):
4455 def target_branch_pattern(self, value):
4423 self._validate_pattern(value)
4456 self._validate_pattern(value)
4424 self._target_branch_pattern = value or '*'
4457 self._target_branch_pattern = value or '*'
4425
4458
4426 @hybrid_property
4459 @hybrid_property
4427 def file_pattern(self):
4460 def file_pattern(self):
4428 return self._file_pattern or '*'
4461 return self._file_pattern or '*'
4429
4462
4430 @file_pattern.setter
4463 @file_pattern.setter
4431 def file_pattern(self, value):
4464 def file_pattern(self, value):
4432 self._validate_pattern(value)
4465 self._validate_pattern(value)
4433 self._file_pattern = value or '*'
4466 self._file_pattern = value or '*'
4434
4467
4435 def matches(self, source_branch, target_branch, files_changed):
4468 def matches(self, source_branch, target_branch, files_changed):
4436 """
4469 """
4437 Check if this review rule matches a branch/files in a pull request
4470 Check if this review rule matches a branch/files in a pull request
4438
4471
4439 :param source_branch: source branch name for the commit
4472 :param source_branch: source branch name for the commit
4440 :param target_branch: target branch name for the commit
4473 :param target_branch: target branch name for the commit
4441 :param files_changed: list of file paths changed in the pull request
4474 :param files_changed: list of file paths changed in the pull request
4442 """
4475 """
4443
4476
4444 source_branch = source_branch or ''
4477 source_branch = source_branch or ''
4445 target_branch = target_branch or ''
4478 target_branch = target_branch or ''
4446 files_changed = files_changed or []
4479 files_changed = files_changed or []
4447
4480
4448 branch_matches = True
4481 branch_matches = True
4449 if source_branch or target_branch:
4482 if source_branch or target_branch:
4450 if self.source_branch_pattern == '*':
4483 if self.source_branch_pattern == '*':
4451 source_branch_match = True
4484 source_branch_match = True
4452 else:
4485 else:
4453 if self.source_branch_pattern.startswith('re:'):
4486 if self.source_branch_pattern.startswith('re:'):
4454 source_pattern = self.source_branch_pattern[3:]
4487 source_pattern = self.source_branch_pattern[3:]
4455 else:
4488 else:
4456 source_pattern = '^' + glob2re(self.source_branch_pattern) + '$'
4489 source_pattern = '^' + glob2re(self.source_branch_pattern) + '$'
4457 source_branch_regex = re.compile(source_pattern)
4490 source_branch_regex = re.compile(source_pattern)
4458 source_branch_match = bool(source_branch_regex.search(source_branch))
4491 source_branch_match = bool(source_branch_regex.search(source_branch))
4459 if self.target_branch_pattern == '*':
4492 if self.target_branch_pattern == '*':
4460 target_branch_match = True
4493 target_branch_match = True
4461 else:
4494 else:
4462 if self.target_branch_pattern.startswith('re:'):
4495 if self.target_branch_pattern.startswith('re:'):
4463 target_pattern = self.target_branch_pattern[3:]
4496 target_pattern = self.target_branch_pattern[3:]
4464 else:
4497 else:
4465 target_pattern = '^' + glob2re(self.target_branch_pattern) + '$'
4498 target_pattern = '^' + glob2re(self.target_branch_pattern) + '$'
4466 target_branch_regex = re.compile(target_pattern)
4499 target_branch_regex = re.compile(target_pattern)
4467 target_branch_match = bool(target_branch_regex.search(target_branch))
4500 target_branch_match = bool(target_branch_regex.search(target_branch))
4468
4501
4469 branch_matches = source_branch_match and target_branch_match
4502 branch_matches = source_branch_match and target_branch_match
4470
4503
4471 files_matches = True
4504 files_matches = True
4472 if self.file_pattern != '*':
4505 if self.file_pattern != '*':
4473 files_matches = False
4506 files_matches = False
4474 if self.file_pattern.startswith('re:'):
4507 if self.file_pattern.startswith('re:'):
4475 file_pattern = self.file_pattern[3:]
4508 file_pattern = self.file_pattern[3:]
4476 else:
4509 else:
4477 file_pattern = glob2re(self.file_pattern)
4510 file_pattern = glob2re(self.file_pattern)
4478 file_regex = re.compile(file_pattern)
4511 file_regex = re.compile(file_pattern)
4479 for filename in files_changed:
4512 for filename in files_changed:
4480 if file_regex.search(filename):
4513 if file_regex.search(filename):
4481 files_matches = True
4514 files_matches = True
4482 break
4515 break
4483
4516
4484 return branch_matches and files_matches
4517 return branch_matches and files_matches
4485
4518
4486 @property
4519 @property
4487 def review_users(self):
4520 def review_users(self):
4488 """ Returns the users which this rule applies to """
4521 """ Returns the users which this rule applies to """
4489
4522
4490 users = collections.OrderedDict()
4523 users = collections.OrderedDict()
4491
4524
4492 for rule_user in self.rule_users:
4525 for rule_user in self.rule_users:
4493 if rule_user.user.active:
4526 if rule_user.user.active:
4494 if rule_user.user not in users:
4527 if rule_user.user not in users:
4495 users[rule_user.user.username] = {
4528 users[rule_user.user.username] = {
4496 'user': rule_user.user,
4529 'user': rule_user.user,
4497 'source': 'user',
4530 'source': 'user',
4498 'source_data': {},
4531 'source_data': {},
4499 'data': rule_user.rule_data()
4532 'data': rule_user.rule_data()
4500 }
4533 }
4501
4534
4502 for rule_user_group in self.rule_user_groups:
4535 for rule_user_group in self.rule_user_groups:
4503 source_data = {
4536 source_data = {
4504 'user_group_id': rule_user_group.users_group.users_group_id,
4537 'user_group_id': rule_user_group.users_group.users_group_id,
4505 'name': rule_user_group.users_group.users_group_name,
4538 'name': rule_user_group.users_group.users_group_name,
4506 'members': len(rule_user_group.users_group.members)
4539 'members': len(rule_user_group.users_group.members)
4507 }
4540 }
4508 for member in rule_user_group.users_group.members:
4541 for member in rule_user_group.users_group.members:
4509 if member.user.active:
4542 if member.user.active:
4510 key = member.user.username
4543 key = member.user.username
4511 if key in users:
4544 if key in users:
4512 # skip this member as we have him already
4545 # skip this member as we have him already
4513 # this prevents from override the "first" matched
4546 # this prevents from override the "first" matched
4514 # users with duplicates in multiple groups
4547 # users with duplicates in multiple groups
4515 continue
4548 continue
4516
4549
4517 users[key] = {
4550 users[key] = {
4518 'user': member.user,
4551 'user': member.user,
4519 'source': 'user_group',
4552 'source': 'user_group',
4520 'source_data': source_data,
4553 'source_data': source_data,
4521 'data': rule_user_group.rule_data()
4554 'data': rule_user_group.rule_data()
4522 }
4555 }
4523
4556
4524 return users
4557 return users
4525
4558
4526 def user_group_vote_rule(self, user_id):
4559 def user_group_vote_rule(self, user_id):
4527
4560
4528 rules = []
4561 rules = []
4529 if not self.rule_user_groups:
4562 if not self.rule_user_groups:
4530 return rules
4563 return rules
4531
4564
4532 for user_group in self.rule_user_groups:
4565 for user_group in self.rule_user_groups:
4533 user_group_members = [x.user_id for x in user_group.users_group.members]
4566 user_group_members = [x.user_id for x in user_group.users_group.members]
4534 if user_id in user_group_members:
4567 if user_id in user_group_members:
4535 rules.append(user_group)
4568 rules.append(user_group)
4536 return rules
4569 return rules
4537
4570
4538 def __repr__(self):
4571 def __repr__(self):
4539 return '<RepoReviewerRule(id=%r, repo=%r)>' % (
4572 return '<RepoReviewerRule(id=%r, repo=%r)>' % (
4540 self.repo_review_rule_id, self.repo)
4573 self.repo_review_rule_id, self.repo)
4541
4574
4542
4575
4543 class ScheduleEntry(Base, BaseModel):
4576 class ScheduleEntry(Base, BaseModel):
4544 __tablename__ = 'schedule_entries'
4577 __tablename__ = 'schedule_entries'
4545 __table_args__ = (
4578 __table_args__ = (
4546 UniqueConstraint('schedule_name', name='s_schedule_name_idx'),
4579 UniqueConstraint('schedule_name', name='s_schedule_name_idx'),
4547 UniqueConstraint('task_uid', name='s_task_uid_idx'),
4580 UniqueConstraint('task_uid', name='s_task_uid_idx'),
4548 base_table_args,
4581 base_table_args,
4549 )
4582 )
4550
4583
4551 schedule_types = ['crontab', 'timedelta', 'integer']
4584 schedule_types = ['crontab', 'timedelta', 'integer']
4552 schedule_entry_id = Column('schedule_entry_id', Integer(), primary_key=True)
4585 schedule_entry_id = Column('schedule_entry_id', Integer(), primary_key=True)
4553
4586
4554 schedule_name = Column("schedule_name", String(255), nullable=False, unique=None, default=None)
4587 schedule_name = Column("schedule_name", String(255), nullable=False, unique=None, default=None)
4555 schedule_description = Column("schedule_description", String(10000), nullable=True, unique=None, default=None)
4588 schedule_description = Column("schedule_description", String(10000), nullable=True, unique=None, default=None)
4556 schedule_enabled = Column("schedule_enabled", Boolean(), nullable=False, unique=None, default=True)
4589 schedule_enabled = Column("schedule_enabled", Boolean(), nullable=False, unique=None, default=True)
4557
4590
4558 _schedule_type = Column("schedule_type", String(255), nullable=False, unique=None, default=None)
4591 _schedule_type = Column("schedule_type", String(255), nullable=False, unique=None, default=None)
4559 schedule_definition = Column('schedule_definition_json', MutationObj.as_mutable(JsonType(default=lambda: "", dialect_map=dict(mysql=LONGTEXT()))))
4592 schedule_definition = Column('schedule_definition_json', MutationObj.as_mutable(JsonType(default=lambda: "", dialect_map=dict(mysql=LONGTEXT()))))
4560
4593
4561 schedule_last_run = Column('schedule_last_run', DateTime(timezone=False), nullable=True, unique=None, default=None)
4594 schedule_last_run = Column('schedule_last_run', DateTime(timezone=False), nullable=True, unique=None, default=None)
4562 schedule_total_run_count = Column('schedule_total_run_count', Integer(), nullable=True, unique=None, default=0)
4595 schedule_total_run_count = Column('schedule_total_run_count', Integer(), nullable=True, unique=None, default=0)
4563
4596
4564 # task
4597 # task
4565 task_uid = Column("task_uid", String(255), nullable=False, unique=None, default=None)
4598 task_uid = Column("task_uid", String(255), nullable=False, unique=None, default=None)
4566 task_dot_notation = Column("task_dot_notation", String(4096), nullable=False, unique=None, default=None)
4599 task_dot_notation = Column("task_dot_notation", String(4096), nullable=False, unique=None, default=None)
4567 task_args = Column('task_args_json', MutationObj.as_mutable(JsonType(default=list, dialect_map=dict(mysql=LONGTEXT()))))
4600 task_args = Column('task_args_json', MutationObj.as_mutable(JsonType(default=list, dialect_map=dict(mysql=LONGTEXT()))))
4568 task_kwargs = Column('task_kwargs_json', MutationObj.as_mutable(JsonType(default=dict, dialect_map=dict(mysql=LONGTEXT()))))
4601 task_kwargs = Column('task_kwargs_json', MutationObj.as_mutable(JsonType(default=dict, dialect_map=dict(mysql=LONGTEXT()))))
4569
4602
4570 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4603 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4571 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=None)
4604 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=None)
4572
4605
4573 @hybrid_property
4606 @hybrid_property
4574 def schedule_type(self):
4607 def schedule_type(self):
4575 return self._schedule_type
4608 return self._schedule_type
4576
4609
4577 @schedule_type.setter
4610 @schedule_type.setter
4578 def schedule_type(self, val):
4611 def schedule_type(self, val):
4579 if val not in self.schedule_types:
4612 if val not in self.schedule_types:
4580 raise ValueError('Value must be on of `{}` and got `{}`'.format(
4613 raise ValueError('Value must be on of `{}` and got `{}`'.format(
4581 val, self.schedule_type))
4614 val, self.schedule_type))
4582
4615
4583 self._schedule_type = val
4616 self._schedule_type = val
4584
4617
4585 @classmethod
4618 @classmethod
4586 def get_uid(cls, obj):
4619 def get_uid(cls, obj):
4587 args = obj.task_args
4620 args = obj.task_args
4588 kwargs = obj.task_kwargs
4621 kwargs = obj.task_kwargs
4589 if isinstance(args, JsonRaw):
4622 if isinstance(args, JsonRaw):
4590 try:
4623 try:
4591 args = json.loads(args)
4624 args = json.loads(args)
4592 except ValueError:
4625 except ValueError:
4593 args = tuple()
4626 args = tuple()
4594
4627
4595 if isinstance(kwargs, JsonRaw):
4628 if isinstance(kwargs, JsonRaw):
4596 try:
4629 try:
4597 kwargs = json.loads(kwargs)
4630 kwargs = json.loads(kwargs)
4598 except ValueError:
4631 except ValueError:
4599 kwargs = dict()
4632 kwargs = dict()
4600
4633
4601 dot_notation = obj.task_dot_notation
4634 dot_notation = obj.task_dot_notation
4602 val = '.'.join(map(safe_str, [
4635 val = '.'.join(map(safe_str, [
4603 sorted(dot_notation), args, sorted(kwargs.items())]))
4636 sorted(dot_notation), args, sorted(kwargs.items())]))
4604 return hashlib.sha1(val).hexdigest()
4637 return hashlib.sha1(val).hexdigest()
4605
4638
4606 @classmethod
4639 @classmethod
4607 def get_by_schedule_name(cls, schedule_name):
4640 def get_by_schedule_name(cls, schedule_name):
4608 return cls.query().filter(cls.schedule_name == schedule_name).scalar()
4641 return cls.query().filter(cls.schedule_name == schedule_name).scalar()
4609
4642
4610 @classmethod
4643 @classmethod
4611 def get_by_schedule_id(cls, schedule_id):
4644 def get_by_schedule_id(cls, schedule_id):
4612 return cls.query().filter(cls.schedule_entry_id == schedule_id).scalar()
4645 return cls.query().filter(cls.schedule_entry_id == schedule_id).scalar()
4613
4646
4614 @property
4647 @property
4615 def task(self):
4648 def task(self):
4616 return self.task_dot_notation
4649 return self.task_dot_notation
4617
4650
4618 @property
4651 @property
4619 def schedule(self):
4652 def schedule(self):
4620 from rhodecode.lib.celerylib.utils import raw_2_schedule
4653 from rhodecode.lib.celerylib.utils import raw_2_schedule
4621 schedule = raw_2_schedule(self.schedule_definition, self.schedule_type)
4654 schedule = raw_2_schedule(self.schedule_definition, self.schedule_type)
4622 return schedule
4655 return schedule
4623
4656
4624 @property
4657 @property
4625 def args(self):
4658 def args(self):
4626 try:
4659 try:
4627 return list(self.task_args or [])
4660 return list(self.task_args or [])
4628 except ValueError:
4661 except ValueError:
4629 return list()
4662 return list()
4630
4663
4631 @property
4664 @property
4632 def kwargs(self):
4665 def kwargs(self):
4633 try:
4666 try:
4634 return dict(self.task_kwargs or {})
4667 return dict(self.task_kwargs or {})
4635 except ValueError:
4668 except ValueError:
4636 return dict()
4669 return dict()
4637
4670
4638 def _as_raw(self, val):
4671 def _as_raw(self, val):
4639 if hasattr(val, 'de_coerce'):
4672 if hasattr(val, 'de_coerce'):
4640 val = val.de_coerce()
4673 val = val.de_coerce()
4641 if val:
4674 if val:
4642 val = json.dumps(val)
4675 val = json.dumps(val)
4643
4676
4644 return val
4677 return val
4645
4678
4646 @property
4679 @property
4647 def schedule_definition_raw(self):
4680 def schedule_definition_raw(self):
4648 return self._as_raw(self.schedule_definition)
4681 return self._as_raw(self.schedule_definition)
4649
4682
4650 @property
4683 @property
4651 def args_raw(self):
4684 def args_raw(self):
4652 return self._as_raw(self.task_args)
4685 return self._as_raw(self.task_args)
4653
4686
4654 @property
4687 @property
4655 def kwargs_raw(self):
4688 def kwargs_raw(self):
4656 return self._as_raw(self.task_kwargs)
4689 return self._as_raw(self.task_kwargs)
4657
4690
4658 def __repr__(self):
4691 def __repr__(self):
4659 return '<DB:ScheduleEntry({}:{})>'.format(
4692 return '<DB:ScheduleEntry({}:{})>'.format(
4660 self.schedule_entry_id, self.schedule_name)
4693 self.schedule_entry_id, self.schedule_name)
4661
4694
4662
4695
4663 @event.listens_for(ScheduleEntry, 'before_update')
4696 @event.listens_for(ScheduleEntry, 'before_update')
4664 def update_task_uid(mapper, connection, target):
4697 def update_task_uid(mapper, connection, target):
4665 target.task_uid = ScheduleEntry.get_uid(target)
4698 target.task_uid = ScheduleEntry.get_uid(target)
4666
4699
4667
4700
4668 @event.listens_for(ScheduleEntry, 'before_insert')
4701 @event.listens_for(ScheduleEntry, 'before_insert')
4669 def set_task_uid(mapper, connection, target):
4702 def set_task_uid(mapper, connection, target):
4670 target.task_uid = ScheduleEntry.get_uid(target)
4703 target.task_uid = ScheduleEntry.get_uid(target)
4671
4704
4672
4705
4673 class _BaseBranchPerms(BaseModel):
4706 class _BaseBranchPerms(BaseModel):
4674 @classmethod
4707 @classmethod
4675 def compute_hash(cls, value):
4708 def compute_hash(cls, value):
4676 return sha1_safe(value)
4709 return sha1_safe(value)
4677
4710
4678 @hybrid_property
4711 @hybrid_property
4679 def branch_pattern(self):
4712 def branch_pattern(self):
4680 return self._branch_pattern or '*'
4713 return self._branch_pattern or '*'
4681
4714
4682 @hybrid_property
4715 @hybrid_property
4683 def branch_hash(self):
4716 def branch_hash(self):
4684 return self._branch_hash
4717 return self._branch_hash
4685
4718
4686 def _validate_glob(self, value):
4719 def _validate_glob(self, value):
4687 re.compile('^' + glob2re(value) + '$')
4720 re.compile('^' + glob2re(value) + '$')
4688
4721
4689 @branch_pattern.setter
4722 @branch_pattern.setter
4690 def branch_pattern(self, value):
4723 def branch_pattern(self, value):
4691 self._validate_glob(value)
4724 self._validate_glob(value)
4692 self._branch_pattern = value or '*'
4725 self._branch_pattern = value or '*'
4693 # set the Hash when setting the branch pattern
4726 # set the Hash when setting the branch pattern
4694 self._branch_hash = self.compute_hash(self._branch_pattern)
4727 self._branch_hash = self.compute_hash(self._branch_pattern)
4695
4728
4696 def matches(self, branch):
4729 def matches(self, branch):
4697 """
4730 """
4698 Check if this the branch matches entry
4731 Check if this the branch matches entry
4699
4732
4700 :param branch: branch name for the commit
4733 :param branch: branch name for the commit
4701 """
4734 """
4702
4735
4703 branch = branch or ''
4736 branch = branch or ''
4704
4737
4705 branch_matches = True
4738 branch_matches = True
4706 if branch:
4739 if branch:
4707 branch_regex = re.compile('^' + glob2re(self.branch_pattern) + '$')
4740 branch_regex = re.compile('^' + glob2re(self.branch_pattern) + '$')
4708 branch_matches = bool(branch_regex.search(branch))
4741 branch_matches = bool(branch_regex.search(branch))
4709
4742
4710 return branch_matches
4743 return branch_matches
4711
4744
4712
4745
4713 class UserToRepoBranchPermission(Base, _BaseBranchPerms):
4746 class UserToRepoBranchPermission(Base, _BaseBranchPerms):
4714 __tablename__ = 'user_to_repo_branch_permissions'
4747 __tablename__ = 'user_to_repo_branch_permissions'
4715 __table_args__ = (
4748 __table_args__ = (
4716 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4749 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4717 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
4750 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
4718 )
4751 )
4719
4752
4720 branch_rule_id = Column('branch_rule_id', Integer(), primary_key=True)
4753 branch_rule_id = Column('branch_rule_id', Integer(), primary_key=True)
4721
4754
4722 repository_id = Column('repository_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
4755 repository_id = Column('repository_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
4723 repo = relationship('Repository', backref='user_branch_perms')
4756 repo = relationship('Repository', backref='user_branch_perms')
4724
4757
4725 permission_id = Column('permission_id', Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
4758 permission_id = Column('permission_id', Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
4726 permission = relationship('Permission')
4759 permission = relationship('Permission')
4727
4760
4728 rule_to_perm_id = Column('rule_to_perm_id', Integer(), ForeignKey('repo_to_perm.repo_to_perm_id'), nullable=False, unique=None, default=None)
4761 rule_to_perm_id = Column('rule_to_perm_id', Integer(), ForeignKey('repo_to_perm.repo_to_perm_id'), nullable=False, unique=None, default=None)
4729 user_repo_to_perm = relationship('UserRepoToPerm')
4762 user_repo_to_perm = relationship('UserRepoToPerm')
4730
4763
4731 rule_order = Column('rule_order', Integer(), nullable=False)
4764 rule_order = Column('rule_order', Integer(), nullable=False)
4732 _branch_pattern = Column('branch_pattern', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), default=u'*') # glob
4765 _branch_pattern = Column('branch_pattern', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), default=u'*') # glob
4733 _branch_hash = Column('branch_hash', UnicodeText().with_variant(UnicodeText(2048), 'mysql'))
4766 _branch_hash = Column('branch_hash', UnicodeText().with_variant(UnicodeText(2048), 'mysql'))
4734
4767
4735 def __unicode__(self):
4768 def __unicode__(self):
4736 return u'<UserBranchPermission(%s => %r)>' % (
4769 return u'<UserBranchPermission(%s => %r)>' % (
4737 self.user_repo_to_perm, self.branch_pattern)
4770 self.user_repo_to_perm, self.branch_pattern)
4738
4771
4739
4772
4740 class UserGroupToRepoBranchPermission(Base, _BaseBranchPerms):
4773 class UserGroupToRepoBranchPermission(Base, _BaseBranchPerms):
4741 __tablename__ = 'user_group_to_repo_branch_permissions'
4774 __tablename__ = 'user_group_to_repo_branch_permissions'
4742 __table_args__ = (
4775 __table_args__ = (
4743 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4776 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4744 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
4777 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
4745 )
4778 )
4746
4779
4747 branch_rule_id = Column('branch_rule_id', Integer(), primary_key=True)
4780 branch_rule_id = Column('branch_rule_id', Integer(), primary_key=True)
4748
4781
4749 repository_id = Column('repository_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
4782 repository_id = Column('repository_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
4750 repo = relationship('Repository', backref='user_group_branch_perms')
4783 repo = relationship('Repository', backref='user_group_branch_perms')
4751
4784
4752 permission_id = Column('permission_id', Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
4785 permission_id = Column('permission_id', Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
4753 permission = relationship('Permission')
4786 permission = relationship('Permission')
4754
4787
4755 rule_to_perm_id = Column('rule_to_perm_id', Integer(), ForeignKey('users_group_repo_to_perm.users_group_to_perm_id'), nullable=False, unique=None, default=None)
4788 rule_to_perm_id = Column('rule_to_perm_id', Integer(), ForeignKey('users_group_repo_to_perm.users_group_to_perm_id'), nullable=False, unique=None, default=None)
4756 user_group_repo_to_perm = relationship('UserGroupRepoToPerm')
4789 user_group_repo_to_perm = relationship('UserGroupRepoToPerm')
4757
4790
4758 rule_order = Column('rule_order', Integer(), nullable=False)
4791 rule_order = Column('rule_order', Integer(), nullable=False)
4759 _branch_pattern = Column('branch_pattern', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), default=u'*') # glob
4792 _branch_pattern = Column('branch_pattern', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), default=u'*') # glob
4760 _branch_hash = Column('branch_hash', UnicodeText().with_variant(UnicodeText(2048), 'mysql'))
4793 _branch_hash = Column('branch_hash', UnicodeText().with_variant(UnicodeText(2048), 'mysql'))
4761
4794
4762 def __unicode__(self):
4795 def __unicode__(self):
4763 return u'<UserBranchPermission(%s => %r)>' % (
4796 return u'<UserBranchPermission(%s => %r)>' % (
4764 self.user_group_repo_to_perm, self.branch_pattern)
4797 self.user_group_repo_to_perm, self.branch_pattern)
4765
4798
4766
4799
4767 class DbMigrateVersion(Base, BaseModel):
4800 class DbMigrateVersion(Base, BaseModel):
4768 __tablename__ = 'db_migrate_version'
4801 __tablename__ = 'db_migrate_version'
4769 __table_args__ = (
4802 __table_args__ = (
4770 base_table_args,
4803 base_table_args,
4771 )
4804 )
4772
4805
4773 repository_id = Column('repository_id', String(250), primary_key=True)
4806 repository_id = Column('repository_id', String(250), primary_key=True)
4774 repository_path = Column('repository_path', Text)
4807 repository_path = Column('repository_path', Text)
4775 version = Column('version', Integer)
4808 version = Column('version', Integer)
4776
4809
4777 @classmethod
4810 @classmethod
4778 def set_version(cls, version):
4811 def set_version(cls, version):
4779 """
4812 """
4780 Helper for forcing a different version, usually for debugging purposes via ishell.
4813 Helper for forcing a different version, usually for debugging purposes via ishell.
4781 """
4814 """
4782 ver = DbMigrateVersion.query().first()
4815 ver = DbMigrateVersion.query().first()
4783 ver.version = version
4816 ver.version = version
4784 Session().commit()
4817 Session().commit()
4785
4818
4786
4819
4787 class DbSession(Base, BaseModel):
4820 class DbSession(Base, BaseModel):
4788 __tablename__ = 'db_session'
4821 __tablename__ = 'db_session'
4789 __table_args__ = (
4822 __table_args__ = (
4790 base_table_args,
4823 base_table_args,
4791 )
4824 )
4792
4825
4793 def __repr__(self):
4826 def __repr__(self):
4794 return '<DB:DbSession({})>'.format(self.id)
4827 return '<DB:DbSession({})>'.format(self.id)
4795
4828
4796 id = Column('id', Integer())
4829 id = Column('id', Integer())
4797 namespace = Column('namespace', String(255), primary_key=True)
4830 namespace = Column('namespace', String(255), primary_key=True)
4798 accessed = Column('accessed', DateTime, nullable=False)
4831 accessed = Column('accessed', DateTime, nullable=False)
4799 created = Column('created', DateTime, nullable=False)
4832 created = Column('created', DateTime, nullable=False)
4800 data = Column('data', PickleType, nullable=False)
4833 data = Column('data', PickleType, nullable=False)
General Comments 0
You need to be logged in to leave comments. Login now