##// END OF EJS Templates
permissions: handle more cases for invalidating permission caches...
marcink -
r3411:2e06ebce stable
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-2018 RhodeCode GmbH
3 # Copyright (C) 2016-2018 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 import 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-2018 RhodeCode GmbH
3 # Copyright (C) 2016-2018 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 import 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,1242 +1,1247 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2016-2018 RhodeCode GmbH
3 # Copyright (C) 2016-2018 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 import 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_force_password_reset', request_method='POST',
607 route_name='user_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_force_password_reset(self):
609 def user_force_password_reset(self):
605 """
610 """
606 toggle reset password flag for this user
611 toggle reset password flag for this user
607 """
612 """
608 _ = self.request.translate
613 _ = self.request.translate
609 c = self.load_default_context()
614 c = self.load_default_context()
610
615
611 user_id = self.db_user_id
616 user_id = self.db_user_id
612 c.user = self.db_user
617 c.user = self.db_user
613
618
614 try:
619 try:
615 old_value = c.user.user_data.get('force_password_change')
620 old_value = c.user.user_data.get('force_password_change')
616 c.user.update_userdata(force_password_change=not old_value)
621 c.user.update_userdata(force_password_change=not old_value)
617
622
618 if old_value:
623 if old_value:
619 msg = _('Force password change disabled for user')
624 msg = _('Force password change disabled for user')
620 audit_logger.store_web(
625 audit_logger.store_web(
621 'user.edit.password_reset.disabled',
626 'user.edit.password_reset.disabled',
622 user=c.rhodecode_user)
627 user=c.rhodecode_user)
623 else:
628 else:
624 msg = _('Force password change enabled for user')
629 msg = _('Force password change enabled for user')
625 audit_logger.store_web(
630 audit_logger.store_web(
626 'user.edit.password_reset.enabled',
631 'user.edit.password_reset.enabled',
627 user=c.rhodecode_user)
632 user=c.rhodecode_user)
628
633
629 Session().commit()
634 Session().commit()
630 h.flash(msg, category='success')
635 h.flash(msg, category='success')
631 except Exception:
636 except Exception:
632 log.exception("Exception during password reset for user")
637 log.exception("Exception during password reset for user")
633 h.flash(_('An error occurred during password reset for user'),
638 h.flash(_('An error occurred during password reset for user'),
634 category='error')
639 category='error')
635
640
636 raise HTTPFound(h.route_path('user_edit_advanced', user_id=user_id))
641 raise HTTPFound(h.route_path('user_edit_advanced', user_id=user_id))
637
642
638 @LoginRequired()
643 @LoginRequired()
639 @HasPermissionAllDecorator('hg.admin')
644 @HasPermissionAllDecorator('hg.admin')
640 @CSRFRequired()
645 @CSRFRequired()
641 @view_config(
646 @view_config(
642 route_name='user_create_personal_repo_group', request_method='POST',
647 route_name='user_create_personal_repo_group', request_method='POST',
643 renderer='rhodecode:templates/admin/users/user_edit.mako')
648 renderer='rhodecode:templates/admin/users/user_edit.mako')
644 def user_create_personal_repo_group(self):
649 def user_create_personal_repo_group(self):
645 """
650 """
646 Create personal repository group for this user
651 Create personal repository group for this user
647 """
652 """
648 from rhodecode.model.repo_group import RepoGroupModel
653 from rhodecode.model.repo_group import RepoGroupModel
649
654
650 _ = self.request.translate
655 _ = self.request.translate
651 c = self.load_default_context()
656 c = self.load_default_context()
652
657
653 user_id = self.db_user_id
658 user_id = self.db_user_id
654 c.user = self.db_user
659 c.user = self.db_user
655
660
656 personal_repo_group = RepoGroup.get_user_personal_repo_group(
661 personal_repo_group = RepoGroup.get_user_personal_repo_group(
657 c.user.user_id)
662 c.user.user_id)
658 if personal_repo_group:
663 if personal_repo_group:
659 raise HTTPFound(h.route_path('user_edit_advanced', user_id=user_id))
664 raise HTTPFound(h.route_path('user_edit_advanced', user_id=user_id))
660
665
661 personal_repo_group_name = RepoGroupModel().get_personal_group_name(
666 personal_repo_group_name = RepoGroupModel().get_personal_group_name(
662 c.user)
667 c.user)
663 named_personal_group = RepoGroup.get_by_group_name(
668 named_personal_group = RepoGroup.get_by_group_name(
664 personal_repo_group_name)
669 personal_repo_group_name)
665 try:
670 try:
666
671
667 if named_personal_group and named_personal_group.user_id == c.user.user_id:
672 if named_personal_group and named_personal_group.user_id == c.user.user_id:
668 # migrate the same named group, and mark it as personal
673 # migrate the same named group, and mark it as personal
669 named_personal_group.personal = True
674 named_personal_group.personal = True
670 Session().add(named_personal_group)
675 Session().add(named_personal_group)
671 Session().commit()
676 Session().commit()
672 msg = _('Linked repository group `%s` as personal' % (
677 msg = _('Linked repository group `%s` as personal' % (
673 personal_repo_group_name,))
678 personal_repo_group_name,))
674 h.flash(msg, category='success')
679 h.flash(msg, category='success')
675 elif not named_personal_group:
680 elif not named_personal_group:
676 RepoGroupModel().create_personal_repo_group(c.user)
681 RepoGroupModel().create_personal_repo_group(c.user)
677
682
678 msg = _('Created repository group `%s`' % (
683 msg = _('Created repository group `%s`' % (
679 personal_repo_group_name,))
684 personal_repo_group_name,))
680 h.flash(msg, category='success')
685 h.flash(msg, category='success')
681 else:
686 else:
682 msg = _('Repository group `%s` is already taken' % (
687 msg = _('Repository group `%s` is already taken' % (
683 personal_repo_group_name,))
688 personal_repo_group_name,))
684 h.flash(msg, category='warning')
689 h.flash(msg, category='warning')
685 except Exception:
690 except Exception:
686 log.exception("Exception during repository group creation")
691 log.exception("Exception during repository group creation")
687 msg = _(
692 msg = _(
688 'An error occurred during repository group creation for user')
693 'An error occurred during repository group creation for user')
689 h.flash(msg, category='error')
694 h.flash(msg, category='error')
690 Session().rollback()
695 Session().rollback()
691
696
692 raise HTTPFound(h.route_path('user_edit_advanced', user_id=user_id))
697 raise HTTPFound(h.route_path('user_edit_advanced', user_id=user_id))
693
698
694 @LoginRequired()
699 @LoginRequired()
695 @HasPermissionAllDecorator('hg.admin')
700 @HasPermissionAllDecorator('hg.admin')
696 @view_config(
701 @view_config(
697 route_name='edit_user_auth_tokens', request_method='GET',
702 route_name='edit_user_auth_tokens', request_method='GET',
698 renderer='rhodecode:templates/admin/users/user_edit.mako')
703 renderer='rhodecode:templates/admin/users/user_edit.mako')
699 def auth_tokens(self):
704 def auth_tokens(self):
700 _ = self.request.translate
705 _ = self.request.translate
701 c = self.load_default_context()
706 c = self.load_default_context()
702 c.user = self.db_user
707 c.user = self.db_user
703
708
704 c.active = 'auth_tokens'
709 c.active = 'auth_tokens'
705
710
706 c.lifetime_values = AuthTokenModel.get_lifetime_values(translator=_)
711 c.lifetime_values = AuthTokenModel.get_lifetime_values(translator=_)
707 c.role_values = [
712 c.role_values = [
708 (x, AuthTokenModel.cls._get_role_name(x))
713 (x, AuthTokenModel.cls._get_role_name(x))
709 for x in AuthTokenModel.cls.ROLES]
714 for x in AuthTokenModel.cls.ROLES]
710 c.role_options = [(c.role_values, _("Role"))]
715 c.role_options = [(c.role_values, _("Role"))]
711 c.user_auth_tokens = AuthTokenModel().get_auth_tokens(
716 c.user_auth_tokens = AuthTokenModel().get_auth_tokens(
712 c.user.user_id, show_expired=True)
717 c.user.user_id, show_expired=True)
713 c.role_vcs = AuthTokenModel.cls.ROLE_VCS
718 c.role_vcs = AuthTokenModel.cls.ROLE_VCS
714 return self._get_template_context(c)
719 return self._get_template_context(c)
715
720
716 def maybe_attach_token_scope(self, token):
721 def maybe_attach_token_scope(self, token):
717 # implemented in EE edition
722 # implemented in EE edition
718 pass
723 pass
719
724
720 @LoginRequired()
725 @LoginRequired()
721 @HasPermissionAllDecorator('hg.admin')
726 @HasPermissionAllDecorator('hg.admin')
722 @CSRFRequired()
727 @CSRFRequired()
723 @view_config(
728 @view_config(
724 route_name='edit_user_auth_tokens_add', request_method='POST')
729 route_name='edit_user_auth_tokens_add', request_method='POST')
725 def auth_tokens_add(self):
730 def auth_tokens_add(self):
726 _ = self.request.translate
731 _ = self.request.translate
727 c = self.load_default_context()
732 c = self.load_default_context()
728
733
729 user_id = self.db_user_id
734 user_id = self.db_user_id
730 c.user = self.db_user
735 c.user = self.db_user
731
736
732 user_data = c.user.get_api_data()
737 user_data = c.user.get_api_data()
733 lifetime = safe_int(self.request.POST.get('lifetime'), -1)
738 lifetime = safe_int(self.request.POST.get('lifetime'), -1)
734 description = self.request.POST.get('description')
739 description = self.request.POST.get('description')
735 role = self.request.POST.get('role')
740 role = self.request.POST.get('role')
736
741
737 token = UserModel().add_auth_token(
742 token = UserModel().add_auth_token(
738 user=c.user.user_id,
743 user=c.user.user_id,
739 lifetime_minutes=lifetime, role=role, description=description,
744 lifetime_minutes=lifetime, role=role, description=description,
740 scope_callback=self.maybe_attach_token_scope)
745 scope_callback=self.maybe_attach_token_scope)
741 token_data = token.get_api_data()
746 token_data = token.get_api_data()
742
747
743 audit_logger.store_web(
748 audit_logger.store_web(
744 'user.edit.token.add', action_data={
749 'user.edit.token.add', action_data={
745 'data': {'token': token_data, 'user': user_data}},
750 'data': {'token': token_data, 'user': user_data}},
746 user=self._rhodecode_user, )
751 user=self._rhodecode_user, )
747 Session().commit()
752 Session().commit()
748
753
749 h.flash(_("Auth token successfully created"), category='success')
754 h.flash(_("Auth token successfully created"), category='success')
750 return HTTPFound(h.route_path('edit_user_auth_tokens', user_id=user_id))
755 return HTTPFound(h.route_path('edit_user_auth_tokens', user_id=user_id))
751
756
752 @LoginRequired()
757 @LoginRequired()
753 @HasPermissionAllDecorator('hg.admin')
758 @HasPermissionAllDecorator('hg.admin')
754 @CSRFRequired()
759 @CSRFRequired()
755 @view_config(
760 @view_config(
756 route_name='edit_user_auth_tokens_delete', request_method='POST')
761 route_name='edit_user_auth_tokens_delete', request_method='POST')
757 def auth_tokens_delete(self):
762 def auth_tokens_delete(self):
758 _ = self.request.translate
763 _ = self.request.translate
759 c = self.load_default_context()
764 c = self.load_default_context()
760
765
761 user_id = self.db_user_id
766 user_id = self.db_user_id
762 c.user = self.db_user
767 c.user = self.db_user
763
768
764 user_data = c.user.get_api_data()
769 user_data = c.user.get_api_data()
765
770
766 del_auth_token = self.request.POST.get('del_auth_token')
771 del_auth_token = self.request.POST.get('del_auth_token')
767
772
768 if del_auth_token:
773 if del_auth_token:
769 token = UserApiKeys.get_or_404(del_auth_token)
774 token = UserApiKeys.get_or_404(del_auth_token)
770 token_data = token.get_api_data()
775 token_data = token.get_api_data()
771
776
772 AuthTokenModel().delete(del_auth_token, c.user.user_id)
777 AuthTokenModel().delete(del_auth_token, c.user.user_id)
773 audit_logger.store_web(
778 audit_logger.store_web(
774 'user.edit.token.delete', action_data={
779 'user.edit.token.delete', action_data={
775 'data': {'token': token_data, 'user': user_data}},
780 'data': {'token': token_data, 'user': user_data}},
776 user=self._rhodecode_user,)
781 user=self._rhodecode_user,)
777 Session().commit()
782 Session().commit()
778 h.flash(_("Auth token successfully deleted"), category='success')
783 h.flash(_("Auth token successfully deleted"), category='success')
779
784
780 return HTTPFound(h.route_path('edit_user_auth_tokens', user_id=user_id))
785 return HTTPFound(h.route_path('edit_user_auth_tokens', user_id=user_id))
781
786
782 @LoginRequired()
787 @LoginRequired()
783 @HasPermissionAllDecorator('hg.admin')
788 @HasPermissionAllDecorator('hg.admin')
784 @view_config(
789 @view_config(
785 route_name='edit_user_ssh_keys', request_method='GET',
790 route_name='edit_user_ssh_keys', request_method='GET',
786 renderer='rhodecode:templates/admin/users/user_edit.mako')
791 renderer='rhodecode:templates/admin/users/user_edit.mako')
787 def ssh_keys(self):
792 def ssh_keys(self):
788 _ = self.request.translate
793 _ = self.request.translate
789 c = self.load_default_context()
794 c = self.load_default_context()
790 c.user = self.db_user
795 c.user = self.db_user
791
796
792 c.active = 'ssh_keys'
797 c.active = 'ssh_keys'
793 c.default_key = self.request.GET.get('default_key')
798 c.default_key = self.request.GET.get('default_key')
794 c.user_ssh_keys = SshKeyModel().get_ssh_keys(c.user.user_id)
799 c.user_ssh_keys = SshKeyModel().get_ssh_keys(c.user.user_id)
795 return self._get_template_context(c)
800 return self._get_template_context(c)
796
801
797 @LoginRequired()
802 @LoginRequired()
798 @HasPermissionAllDecorator('hg.admin')
803 @HasPermissionAllDecorator('hg.admin')
799 @view_config(
804 @view_config(
800 route_name='edit_user_ssh_keys_generate_keypair', request_method='GET',
805 route_name='edit_user_ssh_keys_generate_keypair', request_method='GET',
801 renderer='rhodecode:templates/admin/users/user_edit.mako')
806 renderer='rhodecode:templates/admin/users/user_edit.mako')
802 def ssh_keys_generate_keypair(self):
807 def ssh_keys_generate_keypair(self):
803 _ = self.request.translate
808 _ = self.request.translate
804 c = self.load_default_context()
809 c = self.load_default_context()
805
810
806 c.user = self.db_user
811 c.user = self.db_user
807
812
808 c.active = 'ssh_keys_generate'
813 c.active = 'ssh_keys_generate'
809 comment = 'RhodeCode-SSH {}'.format(c.user.email or '')
814 comment = 'RhodeCode-SSH {}'.format(c.user.email or '')
810 c.private, c.public = SshKeyModel().generate_keypair(comment=comment)
815 c.private, c.public = SshKeyModel().generate_keypair(comment=comment)
811
816
812 return self._get_template_context(c)
817 return self._get_template_context(c)
813
818
814 @LoginRequired()
819 @LoginRequired()
815 @HasPermissionAllDecorator('hg.admin')
820 @HasPermissionAllDecorator('hg.admin')
816 @CSRFRequired()
821 @CSRFRequired()
817 @view_config(
822 @view_config(
818 route_name='edit_user_ssh_keys_add', request_method='POST')
823 route_name='edit_user_ssh_keys_add', request_method='POST')
819 def ssh_keys_add(self):
824 def ssh_keys_add(self):
820 _ = self.request.translate
825 _ = self.request.translate
821 c = self.load_default_context()
826 c = self.load_default_context()
822
827
823 user_id = self.db_user_id
828 user_id = self.db_user_id
824 c.user = self.db_user
829 c.user = self.db_user
825
830
826 user_data = c.user.get_api_data()
831 user_data = c.user.get_api_data()
827 key_data = self.request.POST.get('key_data')
832 key_data = self.request.POST.get('key_data')
828 description = self.request.POST.get('description')
833 description = self.request.POST.get('description')
829
834
830 fingerprint = 'unknown'
835 fingerprint = 'unknown'
831 try:
836 try:
832 if not key_data:
837 if not key_data:
833 raise ValueError('Please add a valid public key')
838 raise ValueError('Please add a valid public key')
834
839
835 key = SshKeyModel().parse_key(key_data.strip())
840 key = SshKeyModel().parse_key(key_data.strip())
836 fingerprint = key.hash_md5()
841 fingerprint = key.hash_md5()
837
842
838 ssh_key = SshKeyModel().create(
843 ssh_key = SshKeyModel().create(
839 c.user.user_id, fingerprint, key.keydata, description)
844 c.user.user_id, fingerprint, key.keydata, description)
840 ssh_key_data = ssh_key.get_api_data()
845 ssh_key_data = ssh_key.get_api_data()
841
846
842 audit_logger.store_web(
847 audit_logger.store_web(
843 'user.edit.ssh_key.add', action_data={
848 'user.edit.ssh_key.add', action_data={
844 'data': {'ssh_key': ssh_key_data, 'user': user_data}},
849 'data': {'ssh_key': ssh_key_data, 'user': user_data}},
845 user=self._rhodecode_user, )
850 user=self._rhodecode_user, )
846 Session().commit()
851 Session().commit()
847
852
848 # Trigger an event on change of keys.
853 # Trigger an event on change of keys.
849 trigger(SshKeyFileChangeEvent(), self.request.registry)
854 trigger(SshKeyFileChangeEvent(), self.request.registry)
850
855
851 h.flash(_("Ssh Key successfully created"), category='success')
856 h.flash(_("Ssh Key successfully created"), category='success')
852
857
853 except IntegrityError:
858 except IntegrityError:
854 log.exception("Exception during ssh key saving")
859 log.exception("Exception during ssh key saving")
855 err = 'Such key with fingerprint `{}` already exists, ' \
860 err = 'Such key with fingerprint `{}` already exists, ' \
856 'please use a different one'.format(fingerprint)
861 'please use a different one'.format(fingerprint)
857 h.flash(_('An error occurred during ssh key saving: {}').format(err),
862 h.flash(_('An error occurred during ssh key saving: {}').format(err),
858 category='error')
863 category='error')
859 except Exception as e:
864 except Exception as e:
860 log.exception("Exception during ssh key saving")
865 log.exception("Exception during ssh key saving")
861 h.flash(_('An error occurred during ssh key saving: {}').format(e),
866 h.flash(_('An error occurred during ssh key saving: {}').format(e),
862 category='error')
867 category='error')
863
868
864 return HTTPFound(
869 return HTTPFound(
865 h.route_path('edit_user_ssh_keys', user_id=user_id))
870 h.route_path('edit_user_ssh_keys', user_id=user_id))
866
871
867 @LoginRequired()
872 @LoginRequired()
868 @HasPermissionAllDecorator('hg.admin')
873 @HasPermissionAllDecorator('hg.admin')
869 @CSRFRequired()
874 @CSRFRequired()
870 @view_config(
875 @view_config(
871 route_name='edit_user_ssh_keys_delete', request_method='POST')
876 route_name='edit_user_ssh_keys_delete', request_method='POST')
872 def ssh_keys_delete(self):
877 def ssh_keys_delete(self):
873 _ = self.request.translate
878 _ = self.request.translate
874 c = self.load_default_context()
879 c = self.load_default_context()
875
880
876 user_id = self.db_user_id
881 user_id = self.db_user_id
877 c.user = self.db_user
882 c.user = self.db_user
878
883
879 user_data = c.user.get_api_data()
884 user_data = c.user.get_api_data()
880
885
881 del_ssh_key = self.request.POST.get('del_ssh_key')
886 del_ssh_key = self.request.POST.get('del_ssh_key')
882
887
883 if del_ssh_key:
888 if del_ssh_key:
884 ssh_key = UserSshKeys.get_or_404(del_ssh_key)
889 ssh_key = UserSshKeys.get_or_404(del_ssh_key)
885 ssh_key_data = ssh_key.get_api_data()
890 ssh_key_data = ssh_key.get_api_data()
886
891
887 SshKeyModel().delete(del_ssh_key, c.user.user_id)
892 SshKeyModel().delete(del_ssh_key, c.user.user_id)
888 audit_logger.store_web(
893 audit_logger.store_web(
889 'user.edit.ssh_key.delete', action_data={
894 'user.edit.ssh_key.delete', action_data={
890 'data': {'ssh_key': ssh_key_data, 'user': user_data}},
895 'data': {'ssh_key': ssh_key_data, 'user': user_data}},
891 user=self._rhodecode_user,)
896 user=self._rhodecode_user,)
892 Session().commit()
897 Session().commit()
893 # Trigger an event on change of keys.
898 # Trigger an event on change of keys.
894 trigger(SshKeyFileChangeEvent(), self.request.registry)
899 trigger(SshKeyFileChangeEvent(), self.request.registry)
895 h.flash(_("Ssh key successfully deleted"), category='success')
900 h.flash(_("Ssh key successfully deleted"), category='success')
896
901
897 return HTTPFound(h.route_path('edit_user_ssh_keys', user_id=user_id))
902 return HTTPFound(h.route_path('edit_user_ssh_keys', user_id=user_id))
898
903
899 @LoginRequired()
904 @LoginRequired()
900 @HasPermissionAllDecorator('hg.admin')
905 @HasPermissionAllDecorator('hg.admin')
901 @view_config(
906 @view_config(
902 route_name='edit_user_emails', request_method='GET',
907 route_name='edit_user_emails', request_method='GET',
903 renderer='rhodecode:templates/admin/users/user_edit.mako')
908 renderer='rhodecode:templates/admin/users/user_edit.mako')
904 def emails(self):
909 def emails(self):
905 _ = self.request.translate
910 _ = self.request.translate
906 c = self.load_default_context()
911 c = self.load_default_context()
907 c.user = self.db_user
912 c.user = self.db_user
908
913
909 c.active = 'emails'
914 c.active = 'emails'
910 c.user_email_map = UserEmailMap.query() \
915 c.user_email_map = UserEmailMap.query() \
911 .filter(UserEmailMap.user == c.user).all()
916 .filter(UserEmailMap.user == c.user).all()
912
917
913 return self._get_template_context(c)
918 return self._get_template_context(c)
914
919
915 @LoginRequired()
920 @LoginRequired()
916 @HasPermissionAllDecorator('hg.admin')
921 @HasPermissionAllDecorator('hg.admin')
917 @CSRFRequired()
922 @CSRFRequired()
918 @view_config(
923 @view_config(
919 route_name='edit_user_emails_add', request_method='POST')
924 route_name='edit_user_emails_add', request_method='POST')
920 def emails_add(self):
925 def emails_add(self):
921 _ = self.request.translate
926 _ = self.request.translate
922 c = self.load_default_context()
927 c = self.load_default_context()
923
928
924 user_id = self.db_user_id
929 user_id = self.db_user_id
925 c.user = self.db_user
930 c.user = self.db_user
926
931
927 email = self.request.POST.get('new_email')
932 email = self.request.POST.get('new_email')
928 user_data = c.user.get_api_data()
933 user_data = c.user.get_api_data()
929 try:
934 try:
930
935
931 form = UserExtraEmailForm(self.request.translate)()
936 form = UserExtraEmailForm(self.request.translate)()
932 data = form.to_python({'email': email})
937 data = form.to_python({'email': email})
933 email = data['email']
938 email = data['email']
934
939
935 UserModel().add_extra_email(c.user.user_id, email)
940 UserModel().add_extra_email(c.user.user_id, email)
936 audit_logger.store_web(
941 audit_logger.store_web(
937 'user.edit.email.add',
942 'user.edit.email.add',
938 action_data={'email': email, 'user': user_data},
943 action_data={'email': email, 'user': user_data},
939 user=self._rhodecode_user)
944 user=self._rhodecode_user)
940 Session().commit()
945 Session().commit()
941 h.flash(_("Added new email address `%s` for user account") % email,
946 h.flash(_("Added new email address `%s` for user account") % email,
942 category='success')
947 category='success')
943 except formencode.Invalid as error:
948 except formencode.Invalid as error:
944 h.flash(h.escape(error.error_dict['email']), category='error')
949 h.flash(h.escape(error.error_dict['email']), category='error')
945 except IntegrityError:
950 except IntegrityError:
946 log.warning("Email %s already exists", email)
951 log.warning("Email %s already exists", email)
947 h.flash(_('Email `{}` is already registered for another user.').format(email),
952 h.flash(_('Email `{}` is already registered for another user.').format(email),
948 category='error')
953 category='error')
949 except Exception:
954 except Exception:
950 log.exception("Exception during email saving")
955 log.exception("Exception during email saving")
951 h.flash(_('An error occurred during email saving'),
956 h.flash(_('An error occurred during email saving'),
952 category='error')
957 category='error')
953 raise HTTPFound(h.route_path('edit_user_emails', user_id=user_id))
958 raise HTTPFound(h.route_path('edit_user_emails', user_id=user_id))
954
959
955 @LoginRequired()
960 @LoginRequired()
956 @HasPermissionAllDecorator('hg.admin')
961 @HasPermissionAllDecorator('hg.admin')
957 @CSRFRequired()
962 @CSRFRequired()
958 @view_config(
963 @view_config(
959 route_name='edit_user_emails_delete', request_method='POST')
964 route_name='edit_user_emails_delete', request_method='POST')
960 def emails_delete(self):
965 def emails_delete(self):
961 _ = self.request.translate
966 _ = self.request.translate
962 c = self.load_default_context()
967 c = self.load_default_context()
963
968
964 user_id = self.db_user_id
969 user_id = self.db_user_id
965 c.user = self.db_user
970 c.user = self.db_user
966
971
967 email_id = self.request.POST.get('del_email_id')
972 email_id = self.request.POST.get('del_email_id')
968 user_model = UserModel()
973 user_model = UserModel()
969
974
970 email = UserEmailMap.query().get(email_id).email
975 email = UserEmailMap.query().get(email_id).email
971 user_data = c.user.get_api_data()
976 user_data = c.user.get_api_data()
972 user_model.delete_extra_email(c.user.user_id, email_id)
977 user_model.delete_extra_email(c.user.user_id, email_id)
973 audit_logger.store_web(
978 audit_logger.store_web(
974 'user.edit.email.delete',
979 'user.edit.email.delete',
975 action_data={'email': email, 'user': user_data},
980 action_data={'email': email, 'user': user_data},
976 user=self._rhodecode_user)
981 user=self._rhodecode_user)
977 Session().commit()
982 Session().commit()
978 h.flash(_("Removed email address from user account"),
983 h.flash(_("Removed email address from user account"),
979 category='success')
984 category='success')
980 raise HTTPFound(h.route_path('edit_user_emails', user_id=user_id))
985 raise HTTPFound(h.route_path('edit_user_emails', user_id=user_id))
981
986
982 @LoginRequired()
987 @LoginRequired()
983 @HasPermissionAllDecorator('hg.admin')
988 @HasPermissionAllDecorator('hg.admin')
984 @view_config(
989 @view_config(
985 route_name='edit_user_ips', request_method='GET',
990 route_name='edit_user_ips', request_method='GET',
986 renderer='rhodecode:templates/admin/users/user_edit.mako')
991 renderer='rhodecode:templates/admin/users/user_edit.mako')
987 def ips(self):
992 def ips(self):
988 _ = self.request.translate
993 _ = self.request.translate
989 c = self.load_default_context()
994 c = self.load_default_context()
990 c.user = self.db_user
995 c.user = self.db_user
991
996
992 c.active = 'ips'
997 c.active = 'ips'
993 c.user_ip_map = UserIpMap.query() \
998 c.user_ip_map = UserIpMap.query() \
994 .filter(UserIpMap.user == c.user).all()
999 .filter(UserIpMap.user == c.user).all()
995
1000
996 c.inherit_default_ips = c.user.inherit_default_permissions
1001 c.inherit_default_ips = c.user.inherit_default_permissions
997 c.default_user_ip_map = UserIpMap.query() \
1002 c.default_user_ip_map = UserIpMap.query() \
998 .filter(UserIpMap.user == User.get_default_user()).all()
1003 .filter(UserIpMap.user == User.get_default_user()).all()
999
1004
1000 return self._get_template_context(c)
1005 return self._get_template_context(c)
1001
1006
1002 @LoginRequired()
1007 @LoginRequired()
1003 @HasPermissionAllDecorator('hg.admin')
1008 @HasPermissionAllDecorator('hg.admin')
1004 @CSRFRequired()
1009 @CSRFRequired()
1005 @view_config(
1010 @view_config(
1006 route_name='edit_user_ips_add', request_method='POST')
1011 route_name='edit_user_ips_add', request_method='POST')
1007 # NOTE(marcink): this view is allowed for default users, as we can
1012 # NOTE(marcink): this view is allowed for default users, as we can
1008 # edit their IP white list
1013 # edit their IP white list
1009 def ips_add(self):
1014 def ips_add(self):
1010 _ = self.request.translate
1015 _ = self.request.translate
1011 c = self.load_default_context()
1016 c = self.load_default_context()
1012
1017
1013 user_id = self.db_user_id
1018 user_id = self.db_user_id
1014 c.user = self.db_user
1019 c.user = self.db_user
1015
1020
1016 user_model = UserModel()
1021 user_model = UserModel()
1017 desc = self.request.POST.get('description')
1022 desc = self.request.POST.get('description')
1018 try:
1023 try:
1019 ip_list = user_model.parse_ip_range(
1024 ip_list = user_model.parse_ip_range(
1020 self.request.POST.get('new_ip'))
1025 self.request.POST.get('new_ip'))
1021 except Exception as e:
1026 except Exception as e:
1022 ip_list = []
1027 ip_list = []
1023 log.exception("Exception during ip saving")
1028 log.exception("Exception during ip saving")
1024 h.flash(_('An error occurred during ip saving:%s' % (e,)),
1029 h.flash(_('An error occurred during ip saving:%s' % (e,)),
1025 category='error')
1030 category='error')
1026 added = []
1031 added = []
1027 user_data = c.user.get_api_data()
1032 user_data = c.user.get_api_data()
1028 for ip in ip_list:
1033 for ip in ip_list:
1029 try:
1034 try:
1030 form = UserExtraIpForm(self.request.translate)()
1035 form = UserExtraIpForm(self.request.translate)()
1031 data = form.to_python({'ip': ip})
1036 data = form.to_python({'ip': ip})
1032 ip = data['ip']
1037 ip = data['ip']
1033
1038
1034 user_model.add_extra_ip(c.user.user_id, ip, desc)
1039 user_model.add_extra_ip(c.user.user_id, ip, desc)
1035 audit_logger.store_web(
1040 audit_logger.store_web(
1036 'user.edit.ip.add',
1041 'user.edit.ip.add',
1037 action_data={'ip': ip, 'user': user_data},
1042 action_data={'ip': ip, 'user': user_data},
1038 user=self._rhodecode_user)
1043 user=self._rhodecode_user)
1039 Session().commit()
1044 Session().commit()
1040 added.append(ip)
1045 added.append(ip)
1041 except formencode.Invalid as error:
1046 except formencode.Invalid as error:
1042 msg = error.error_dict['ip']
1047 msg = error.error_dict['ip']
1043 h.flash(msg, category='error')
1048 h.flash(msg, category='error')
1044 except Exception:
1049 except Exception:
1045 log.exception("Exception during ip saving")
1050 log.exception("Exception during ip saving")
1046 h.flash(_('An error occurred during ip saving'),
1051 h.flash(_('An error occurred during ip saving'),
1047 category='error')
1052 category='error')
1048 if added:
1053 if added:
1049 h.flash(
1054 h.flash(
1050 _("Added ips %s to user whitelist") % (', '.join(ip_list), ),
1055 _("Added ips %s to user whitelist") % (', '.join(ip_list), ),
1051 category='success')
1056 category='success')
1052 if 'default_user' in self.request.POST:
1057 if 'default_user' in self.request.POST:
1053 # case for editing global IP list we do it for 'DEFAULT' user
1058 # case for editing global IP list we do it for 'DEFAULT' user
1054 raise HTTPFound(h.route_path('admin_permissions_ips'))
1059 raise HTTPFound(h.route_path('admin_permissions_ips'))
1055 raise HTTPFound(h.route_path('edit_user_ips', user_id=user_id))
1060 raise HTTPFound(h.route_path('edit_user_ips', user_id=user_id))
1056
1061
1057 @LoginRequired()
1062 @LoginRequired()
1058 @HasPermissionAllDecorator('hg.admin')
1063 @HasPermissionAllDecorator('hg.admin')
1059 @CSRFRequired()
1064 @CSRFRequired()
1060 @view_config(
1065 @view_config(
1061 route_name='edit_user_ips_delete', request_method='POST')
1066 route_name='edit_user_ips_delete', request_method='POST')
1062 # NOTE(marcink): this view is allowed for default users, as we can
1067 # NOTE(marcink): this view is allowed for default users, as we can
1063 # edit their IP white list
1068 # edit their IP white list
1064 def ips_delete(self):
1069 def ips_delete(self):
1065 _ = self.request.translate
1070 _ = self.request.translate
1066 c = self.load_default_context()
1071 c = self.load_default_context()
1067
1072
1068 user_id = self.db_user_id
1073 user_id = self.db_user_id
1069 c.user = self.db_user
1074 c.user = self.db_user
1070
1075
1071 ip_id = self.request.POST.get('del_ip_id')
1076 ip_id = self.request.POST.get('del_ip_id')
1072 user_model = UserModel()
1077 user_model = UserModel()
1073 user_data = c.user.get_api_data()
1078 user_data = c.user.get_api_data()
1074 ip = UserIpMap.query().get(ip_id).ip_addr
1079 ip = UserIpMap.query().get(ip_id).ip_addr
1075 user_model.delete_extra_ip(c.user.user_id, ip_id)
1080 user_model.delete_extra_ip(c.user.user_id, ip_id)
1076 audit_logger.store_web(
1081 audit_logger.store_web(
1077 'user.edit.ip.delete', action_data={'ip': ip, 'user': user_data},
1082 'user.edit.ip.delete', action_data={'ip': ip, 'user': user_data},
1078 user=self._rhodecode_user)
1083 user=self._rhodecode_user)
1079 Session().commit()
1084 Session().commit()
1080 h.flash(_("Removed ip address from user whitelist"), category='success')
1085 h.flash(_("Removed ip address from user whitelist"), category='success')
1081
1086
1082 if 'default_user' in self.request.POST:
1087 if 'default_user' in self.request.POST:
1083 # case for editing global IP list we do it for 'DEFAULT' user
1088 # case for editing global IP list we do it for 'DEFAULT' user
1084 raise HTTPFound(h.route_path('admin_permissions_ips'))
1089 raise HTTPFound(h.route_path('admin_permissions_ips'))
1085 raise HTTPFound(h.route_path('edit_user_ips', user_id=user_id))
1090 raise HTTPFound(h.route_path('edit_user_ips', user_id=user_id))
1086
1091
1087 @LoginRequired()
1092 @LoginRequired()
1088 @HasPermissionAllDecorator('hg.admin')
1093 @HasPermissionAllDecorator('hg.admin')
1089 @view_config(
1094 @view_config(
1090 route_name='edit_user_groups_management', request_method='GET',
1095 route_name='edit_user_groups_management', request_method='GET',
1091 renderer='rhodecode:templates/admin/users/user_edit.mako')
1096 renderer='rhodecode:templates/admin/users/user_edit.mako')
1092 def groups_management(self):
1097 def groups_management(self):
1093 c = self.load_default_context()
1098 c = self.load_default_context()
1094 c.user = self.db_user
1099 c.user = self.db_user
1095 c.data = c.user.group_member
1100 c.data = c.user.group_member
1096
1101
1097 groups = [UserGroupModel.get_user_groups_as_dict(group.users_group)
1102 groups = [UserGroupModel.get_user_groups_as_dict(group.users_group)
1098 for group in c.user.group_member]
1103 for group in c.user.group_member]
1099 c.groups = json.dumps(groups)
1104 c.groups = json.dumps(groups)
1100 c.active = 'groups'
1105 c.active = 'groups'
1101
1106
1102 return self._get_template_context(c)
1107 return self._get_template_context(c)
1103
1108
1104 @LoginRequired()
1109 @LoginRequired()
1105 @HasPermissionAllDecorator('hg.admin')
1110 @HasPermissionAllDecorator('hg.admin')
1106 @CSRFRequired()
1111 @CSRFRequired()
1107 @view_config(
1112 @view_config(
1108 route_name='edit_user_groups_management_updates', request_method='POST')
1113 route_name='edit_user_groups_management_updates', request_method='POST')
1109 def groups_management_updates(self):
1114 def groups_management_updates(self):
1110 _ = self.request.translate
1115 _ = self.request.translate
1111 c = self.load_default_context()
1116 c = self.load_default_context()
1112
1117
1113 user_id = self.db_user_id
1118 user_id = self.db_user_id
1114 c.user = self.db_user
1119 c.user = self.db_user
1115
1120
1116 user_groups = set(self.request.POST.getall('users_group_id'))
1121 user_groups = set(self.request.POST.getall('users_group_id'))
1117 user_groups_objects = []
1122 user_groups_objects = []
1118
1123
1119 for ugid in user_groups:
1124 for ugid in user_groups:
1120 user_groups_objects.append(
1125 user_groups_objects.append(
1121 UserGroupModel().get_group(safe_int(ugid)))
1126 UserGroupModel().get_group(safe_int(ugid)))
1122 user_group_model = UserGroupModel()
1127 user_group_model = UserGroupModel()
1123 added_to_groups, removed_from_groups = \
1128 added_to_groups, removed_from_groups = \
1124 user_group_model.change_groups(c.user, user_groups_objects)
1129 user_group_model.change_groups(c.user, user_groups_objects)
1125
1130
1126 user_data = c.user.get_api_data()
1131 user_data = c.user.get_api_data()
1127 for user_group_id in added_to_groups:
1132 for user_group_id in added_to_groups:
1128 user_group = UserGroup.get(user_group_id)
1133 user_group = UserGroup.get(user_group_id)
1129 old_values = user_group.get_api_data()
1134 old_values = user_group.get_api_data()
1130 audit_logger.store_web(
1135 audit_logger.store_web(
1131 'user_group.edit.member.add',
1136 'user_group.edit.member.add',
1132 action_data={'user': user_data, 'old_data': old_values},
1137 action_data={'user': user_data, 'old_data': old_values},
1133 user=self._rhodecode_user)
1138 user=self._rhodecode_user)
1134
1139
1135 for user_group_id in removed_from_groups:
1140 for user_group_id in removed_from_groups:
1136 user_group = UserGroup.get(user_group_id)
1141 user_group = UserGroup.get(user_group_id)
1137 old_values = user_group.get_api_data()
1142 old_values = user_group.get_api_data()
1138 audit_logger.store_web(
1143 audit_logger.store_web(
1139 'user_group.edit.member.delete',
1144 'user_group.edit.member.delete',
1140 action_data={'user': user_data, 'old_data': old_values},
1145 action_data={'user': user_data, 'old_data': old_values},
1141 user=self._rhodecode_user)
1146 user=self._rhodecode_user)
1142
1147
1143 Session().commit()
1148 Session().commit()
1144 c.active = 'user_groups_management'
1149 c.active = 'user_groups_management'
1145 h.flash(_("Groups successfully changed"), category='success')
1150 h.flash(_("Groups successfully changed"), category='success')
1146
1151
1147 return HTTPFound(h.route_path(
1152 return HTTPFound(h.route_path(
1148 'edit_user_groups_management', user_id=user_id))
1153 'edit_user_groups_management', user_id=user_id))
1149
1154
1150 @LoginRequired()
1155 @LoginRequired()
1151 @HasPermissionAllDecorator('hg.admin')
1156 @HasPermissionAllDecorator('hg.admin')
1152 @view_config(
1157 @view_config(
1153 route_name='edit_user_audit_logs', request_method='GET',
1158 route_name='edit_user_audit_logs', request_method='GET',
1154 renderer='rhodecode:templates/admin/users/user_edit.mako')
1159 renderer='rhodecode:templates/admin/users/user_edit.mako')
1155 def user_audit_logs(self):
1160 def user_audit_logs(self):
1156 _ = self.request.translate
1161 _ = self.request.translate
1157 c = self.load_default_context()
1162 c = self.load_default_context()
1158 c.user = self.db_user
1163 c.user = self.db_user
1159
1164
1160 c.active = 'audit'
1165 c.active = 'audit'
1161
1166
1162 p = safe_int(self.request.GET.get('page', 1), 1)
1167 p = safe_int(self.request.GET.get('page', 1), 1)
1163
1168
1164 filter_term = self.request.GET.get('filter')
1169 filter_term = self.request.GET.get('filter')
1165 user_log = UserModel().get_user_log(c.user, filter_term)
1170 user_log = UserModel().get_user_log(c.user, filter_term)
1166
1171
1167 def url_generator(**kw):
1172 def url_generator(**kw):
1168 if filter_term:
1173 if filter_term:
1169 kw['filter'] = filter_term
1174 kw['filter'] = filter_term
1170 return self.request.current_route_path(_query=kw)
1175 return self.request.current_route_path(_query=kw)
1171
1176
1172 c.audit_logs = h.Page(
1177 c.audit_logs = h.Page(
1173 user_log, page=p, items_per_page=10, url=url_generator)
1178 user_log, page=p, items_per_page=10, url=url_generator)
1174 c.filter_term = filter_term
1179 c.filter_term = filter_term
1175 return self._get_template_context(c)
1180 return self._get_template_context(c)
1176
1181
1177 @LoginRequired()
1182 @LoginRequired()
1178 @HasPermissionAllDecorator('hg.admin')
1183 @HasPermissionAllDecorator('hg.admin')
1179 @view_config(
1184 @view_config(
1180 route_name='edit_user_perms_summary', request_method='GET',
1185 route_name='edit_user_perms_summary', request_method='GET',
1181 renderer='rhodecode:templates/admin/users/user_edit.mako')
1186 renderer='rhodecode:templates/admin/users/user_edit.mako')
1182 def user_perms_summary(self):
1187 def user_perms_summary(self):
1183 _ = self.request.translate
1188 _ = self.request.translate
1184 c = self.load_default_context()
1189 c = self.load_default_context()
1185 c.user = self.db_user
1190 c.user = self.db_user
1186
1191
1187 c.active = 'perms_summary'
1192 c.active = 'perms_summary'
1188 c.perm_user = c.user.AuthUser(ip_addr=self.request.remote_addr)
1193 c.perm_user = c.user.AuthUser(ip_addr=self.request.remote_addr)
1189
1194
1190 return self._get_template_context(c)
1195 return self._get_template_context(c)
1191
1196
1192 @LoginRequired()
1197 @LoginRequired()
1193 @HasPermissionAllDecorator('hg.admin')
1198 @HasPermissionAllDecorator('hg.admin')
1194 @view_config(
1199 @view_config(
1195 route_name='edit_user_perms_summary_json', request_method='GET',
1200 route_name='edit_user_perms_summary_json', request_method='GET',
1196 renderer='json_ext')
1201 renderer='json_ext')
1197 def user_perms_summary_json(self):
1202 def user_perms_summary_json(self):
1198 self.load_default_context()
1203 self.load_default_context()
1199 perm_user = self.db_user.AuthUser(ip_addr=self.request.remote_addr)
1204 perm_user = self.db_user.AuthUser(ip_addr=self.request.remote_addr)
1200
1205
1201 return perm_user.permissions
1206 return perm_user.permissions
1202
1207
1203 @LoginRequired()
1208 @LoginRequired()
1204 @HasPermissionAllDecorator('hg.admin')
1209 @HasPermissionAllDecorator('hg.admin')
1205 @view_config(
1210 @view_config(
1206 route_name='edit_user_caches', request_method='GET',
1211 route_name='edit_user_caches', request_method='GET',
1207 renderer='rhodecode:templates/admin/users/user_edit.mako')
1212 renderer='rhodecode:templates/admin/users/user_edit.mako')
1208 def user_caches(self):
1213 def user_caches(self):
1209 _ = self.request.translate
1214 _ = self.request.translate
1210 c = self.load_default_context()
1215 c = self.load_default_context()
1211 c.user = self.db_user
1216 c.user = self.db_user
1212
1217
1213 c.active = 'caches'
1218 c.active = 'caches'
1214 c.perm_user = c.user.AuthUser(ip_addr=self.request.remote_addr)
1219 c.perm_user = c.user.AuthUser(ip_addr=self.request.remote_addr)
1215
1220
1216 cache_namespace_uid = 'cache_user_auth.{}'.format(self.db_user.user_id)
1221 cache_namespace_uid = 'cache_user_auth.{}'.format(self.db_user.user_id)
1217 c.region = rc_cache.get_or_create_region('cache_perms', cache_namespace_uid)
1222 c.region = rc_cache.get_or_create_region('cache_perms', cache_namespace_uid)
1218 c.backend = c.region.backend
1223 c.backend = c.region.backend
1219 c.user_keys = sorted(c.region.backend.list_keys(prefix=cache_namespace_uid))
1224 c.user_keys = sorted(c.region.backend.list_keys(prefix=cache_namespace_uid))
1220
1225
1221 return self._get_template_context(c)
1226 return self._get_template_context(c)
1222
1227
1223 @LoginRequired()
1228 @LoginRequired()
1224 @HasPermissionAllDecorator('hg.admin')
1229 @HasPermissionAllDecorator('hg.admin')
1225 @CSRFRequired()
1230 @CSRFRequired()
1226 @view_config(
1231 @view_config(
1227 route_name='edit_user_caches_update', request_method='POST')
1232 route_name='edit_user_caches_update', request_method='POST')
1228 def user_caches_update(self):
1233 def user_caches_update(self):
1229 _ = self.request.translate
1234 _ = self.request.translate
1230 c = self.load_default_context()
1235 c = self.load_default_context()
1231 c.user = self.db_user
1236 c.user = self.db_user
1232
1237
1233 c.active = 'caches'
1238 c.active = 'caches'
1234 c.perm_user = c.user.AuthUser(ip_addr=self.request.remote_addr)
1239 c.perm_user = c.user.AuthUser(ip_addr=self.request.remote_addr)
1235
1240
1236 cache_namespace_uid = 'cache_user_auth.{}'.format(self.db_user.user_id)
1241 cache_namespace_uid = 'cache_user_auth.{}'.format(self.db_user.user_id)
1237 del_keys = rc_cache.clear_cache_namespace('cache_perms', cache_namespace_uid)
1242 del_keys = rc_cache.clear_cache_namespace('cache_perms', cache_namespace_uid)
1238
1243
1239 h.flash(_("Deleted {} cache keys").format(del_keys), category='success')
1244 h.flash(_("Deleted {} cache keys").format(del_keys), category='success')
1240
1245
1241 return HTTPFound(h.route_path(
1246 return HTTPFound(h.route_path(
1242 'edit_user_caches', user_id=c.user.user_id))
1247 '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-2018 RhodeCode GmbH
3 # Copyright (C) 2011-2018 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 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-2018 RhodeCode GmbH
3 # Copyright (C) 2011-2018 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 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-2018 RhodeCode GmbH
3 # Copyright (C) 2011-2018 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 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,4721 +1,4754 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2010-2018 RhodeCode GmbH
3 # Copyright (C) 2010-2018 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 """
21 """
22 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 resolved_comment = relationship('ChangesetComment', remote_side=comment_id, backref='resolved_by')
3414 resolved_comment = relationship('ChangesetComment', remote_side=comment_id, backref='resolved_by')
3382 author = relationship('User', lazy='joined')
3415 author = relationship('User', lazy='joined')
3383 repo = relationship('Repository')
3416 repo = relationship('Repository')
3384 status_change = relationship('ChangesetStatus', cascade="all, delete, delete-orphan", lazy='joined')
3417 status_change = relationship('ChangesetStatus', cascade="all, delete, delete-orphan", lazy='joined')
3385 pull_request = relationship('PullRequest', lazy='joined')
3418 pull_request = relationship('PullRequest', lazy='joined')
3386 pull_request_version = relationship('PullRequestVersion')
3419 pull_request_version = relationship('PullRequestVersion')
3387
3420
3388 @classmethod
3421 @classmethod
3389 def get_users(cls, revision=None, pull_request_id=None):
3422 def get_users(cls, revision=None, pull_request_id=None):
3390 """
3423 """
3391 Returns user associated with this ChangesetComment. ie those
3424 Returns user associated with this ChangesetComment. ie those
3392 who actually commented
3425 who actually commented
3393
3426
3394 :param cls:
3427 :param cls:
3395 :param revision:
3428 :param revision:
3396 """
3429 """
3397 q = Session().query(User)\
3430 q = Session().query(User)\
3398 .join(ChangesetComment.author)
3431 .join(ChangesetComment.author)
3399 if revision:
3432 if revision:
3400 q = q.filter(cls.revision == revision)
3433 q = q.filter(cls.revision == revision)
3401 elif pull_request_id:
3434 elif pull_request_id:
3402 q = q.filter(cls.pull_request_id == pull_request_id)
3435 q = q.filter(cls.pull_request_id == pull_request_id)
3403 return q.all()
3436 return q.all()
3404
3437
3405 @classmethod
3438 @classmethod
3406 def get_index_from_version(cls, pr_version, versions):
3439 def get_index_from_version(cls, pr_version, versions):
3407 num_versions = [x.pull_request_version_id for x in versions]
3440 num_versions = [x.pull_request_version_id for x in versions]
3408 try:
3441 try:
3409 return num_versions.index(pr_version) +1
3442 return num_versions.index(pr_version) +1
3410 except (IndexError, ValueError):
3443 except (IndexError, ValueError):
3411 return
3444 return
3412
3445
3413 @property
3446 @property
3414 def outdated(self):
3447 def outdated(self):
3415 return self.display_state == self.COMMENT_OUTDATED
3448 return self.display_state == self.COMMENT_OUTDATED
3416
3449
3417 def outdated_at_version(self, version):
3450 def outdated_at_version(self, version):
3418 """
3451 """
3419 Checks if comment is outdated for given pull request version
3452 Checks if comment is outdated for given pull request version
3420 """
3453 """
3421 return self.outdated and self.pull_request_version_id != version
3454 return self.outdated and self.pull_request_version_id != version
3422
3455
3423 def older_than_version(self, version):
3456 def older_than_version(self, version):
3424 """
3457 """
3425 Checks if comment is made from previous version than given
3458 Checks if comment is made from previous version than given
3426 """
3459 """
3427 if version is None:
3460 if version is None:
3428 return self.pull_request_version_id is not None
3461 return self.pull_request_version_id is not None
3429
3462
3430 return self.pull_request_version_id < version
3463 return self.pull_request_version_id < version
3431
3464
3432 @property
3465 @property
3433 def resolved(self):
3466 def resolved(self):
3434 return self.resolved_by[0] if self.resolved_by else None
3467 return self.resolved_by[0] if self.resolved_by else None
3435
3468
3436 @property
3469 @property
3437 def is_todo(self):
3470 def is_todo(self):
3438 return self.comment_type == self.COMMENT_TYPE_TODO
3471 return self.comment_type == self.COMMENT_TYPE_TODO
3439
3472
3440 @property
3473 @property
3441 def is_inline(self):
3474 def is_inline(self):
3442 return self.line_no and self.f_path
3475 return self.line_no and self.f_path
3443
3476
3444 def get_index_version(self, versions):
3477 def get_index_version(self, versions):
3445 return self.get_index_from_version(
3478 return self.get_index_from_version(
3446 self.pull_request_version_id, versions)
3479 self.pull_request_version_id, versions)
3447
3480
3448 def __repr__(self):
3481 def __repr__(self):
3449 if self.comment_id:
3482 if self.comment_id:
3450 return '<DB:Comment #%s>' % self.comment_id
3483 return '<DB:Comment #%s>' % self.comment_id
3451 else:
3484 else:
3452 return '<DB:Comment at %#x>' % id(self)
3485 return '<DB:Comment at %#x>' % id(self)
3453
3486
3454 def get_api_data(self):
3487 def get_api_data(self):
3455 comment = self
3488 comment = self
3456 data = {
3489 data = {
3457 'comment_id': comment.comment_id,
3490 'comment_id': comment.comment_id,
3458 'comment_type': comment.comment_type,
3491 'comment_type': comment.comment_type,
3459 'comment_text': comment.text,
3492 'comment_text': comment.text,
3460 'comment_status': comment.status_change,
3493 'comment_status': comment.status_change,
3461 'comment_f_path': comment.f_path,
3494 'comment_f_path': comment.f_path,
3462 'comment_lineno': comment.line_no,
3495 'comment_lineno': comment.line_no,
3463 'comment_author': comment.author,
3496 'comment_author': comment.author,
3464 'comment_created_on': comment.created_on
3497 'comment_created_on': comment.created_on
3465 }
3498 }
3466 return data
3499 return data
3467
3500
3468 def __json__(self):
3501 def __json__(self):
3469 data = dict()
3502 data = dict()
3470 data.update(self.get_api_data())
3503 data.update(self.get_api_data())
3471 return data
3504 return data
3472
3505
3473
3506
3474 class ChangesetStatus(Base, BaseModel):
3507 class ChangesetStatus(Base, BaseModel):
3475 __tablename__ = 'changeset_statuses'
3508 __tablename__ = 'changeset_statuses'
3476 __table_args__ = (
3509 __table_args__ = (
3477 Index('cs_revision_idx', 'revision'),
3510 Index('cs_revision_idx', 'revision'),
3478 Index('cs_version_idx', 'version'),
3511 Index('cs_version_idx', 'version'),
3479 UniqueConstraint('repo_id', 'revision', 'version'),
3512 UniqueConstraint('repo_id', 'revision', 'version'),
3480 base_table_args
3513 base_table_args
3481 )
3514 )
3482
3515
3483 STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed'
3516 STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed'
3484 STATUS_APPROVED = 'approved'
3517 STATUS_APPROVED = 'approved'
3485 STATUS_REJECTED = 'rejected'
3518 STATUS_REJECTED = 'rejected'
3486 STATUS_UNDER_REVIEW = 'under_review'
3519 STATUS_UNDER_REVIEW = 'under_review'
3487
3520
3488 STATUSES = [
3521 STATUSES = [
3489 (STATUS_NOT_REVIEWED, _("Not Reviewed")), # (no icon) and default
3522 (STATUS_NOT_REVIEWED, _("Not Reviewed")), # (no icon) and default
3490 (STATUS_APPROVED, _("Approved")),
3523 (STATUS_APPROVED, _("Approved")),
3491 (STATUS_REJECTED, _("Rejected")),
3524 (STATUS_REJECTED, _("Rejected")),
3492 (STATUS_UNDER_REVIEW, _("Under Review")),
3525 (STATUS_UNDER_REVIEW, _("Under Review")),
3493 ]
3526 ]
3494
3527
3495 changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True)
3528 changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True)
3496 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3529 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3497 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
3530 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
3498 revision = Column('revision', String(40), nullable=False)
3531 revision = Column('revision', String(40), nullable=False)
3499 status = Column('status', String(128), nullable=False, default=DEFAULT)
3532 status = Column('status', String(128), nullable=False, default=DEFAULT)
3500 changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'))
3533 changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'))
3501 modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now)
3534 modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now)
3502 version = Column('version', Integer(), nullable=False, default=0)
3535 version = Column('version', Integer(), nullable=False, default=0)
3503 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3536 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3504
3537
3505 author = relationship('User', lazy='joined')
3538 author = relationship('User', lazy='joined')
3506 repo = relationship('Repository')
3539 repo = relationship('Repository')
3507 comment = relationship('ChangesetComment', lazy='joined')
3540 comment = relationship('ChangesetComment', lazy='joined')
3508 pull_request = relationship('PullRequest', lazy='joined')
3541 pull_request = relationship('PullRequest', lazy='joined')
3509
3542
3510 def __unicode__(self):
3543 def __unicode__(self):
3511 return u"<%s('%s[v%s]:%s')>" % (
3544 return u"<%s('%s[v%s]:%s')>" % (
3512 self.__class__.__name__,
3545 self.__class__.__name__,
3513 self.status, self.version, self.author
3546 self.status, self.version, self.author
3514 )
3547 )
3515
3548
3516 @classmethod
3549 @classmethod
3517 def get_status_lbl(cls, value):
3550 def get_status_lbl(cls, value):
3518 return dict(cls.STATUSES).get(value)
3551 return dict(cls.STATUSES).get(value)
3519
3552
3520 @property
3553 @property
3521 def status_lbl(self):
3554 def status_lbl(self):
3522 return ChangesetStatus.get_status_lbl(self.status)
3555 return ChangesetStatus.get_status_lbl(self.status)
3523
3556
3524 def get_api_data(self):
3557 def get_api_data(self):
3525 status = self
3558 status = self
3526 data = {
3559 data = {
3527 'status_id': status.changeset_status_id,
3560 'status_id': status.changeset_status_id,
3528 'status': status.status,
3561 'status': status.status,
3529 }
3562 }
3530 return data
3563 return data
3531
3564
3532 def __json__(self):
3565 def __json__(self):
3533 data = dict()
3566 data = dict()
3534 data.update(self.get_api_data())
3567 data.update(self.get_api_data())
3535 return data
3568 return data
3536
3569
3537
3570
3538 class _PullRequestBase(BaseModel):
3571 class _PullRequestBase(BaseModel):
3539 """
3572 """
3540 Common attributes of pull request and version entries.
3573 Common attributes of pull request and version entries.
3541 """
3574 """
3542
3575
3543 # .status values
3576 # .status values
3544 STATUS_NEW = u'new'
3577 STATUS_NEW = u'new'
3545 STATUS_OPEN = u'open'
3578 STATUS_OPEN = u'open'
3546 STATUS_CLOSED = u'closed'
3579 STATUS_CLOSED = u'closed'
3547
3580
3548 title = Column('title', Unicode(255), nullable=True)
3581 title = Column('title', Unicode(255), nullable=True)
3549 description = Column(
3582 description = Column(
3550 'description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'),
3583 'description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'),
3551 nullable=True)
3584 nullable=True)
3552 description_renderer = Column('description_renderer', Unicode(64), nullable=True)
3585 description_renderer = Column('description_renderer', Unicode(64), nullable=True)
3553
3586
3554 # new/open/closed status of pull request (not approve/reject/etc)
3587 # new/open/closed status of pull request (not approve/reject/etc)
3555 status = Column('status', Unicode(255), nullable=False, default=STATUS_NEW)
3588 status = Column('status', Unicode(255), nullable=False, default=STATUS_NEW)
3556 created_on = Column(
3589 created_on = Column(
3557 'created_on', DateTime(timezone=False), nullable=False,
3590 'created_on', DateTime(timezone=False), nullable=False,
3558 default=datetime.datetime.now)
3591 default=datetime.datetime.now)
3559 updated_on = Column(
3592 updated_on = Column(
3560 'updated_on', DateTime(timezone=False), nullable=False,
3593 'updated_on', DateTime(timezone=False), nullable=False,
3561 default=datetime.datetime.now)
3594 default=datetime.datetime.now)
3562
3595
3563 @declared_attr
3596 @declared_attr
3564 def user_id(cls):
3597 def user_id(cls):
3565 return Column(
3598 return Column(
3566 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
3599 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
3567 unique=None)
3600 unique=None)
3568
3601
3569 # 500 revisions max
3602 # 500 revisions max
3570 _revisions = Column(
3603 _revisions = Column(
3571 'revisions', UnicodeText().with_variant(UnicodeText(20500), 'mysql'))
3604 'revisions', UnicodeText().with_variant(UnicodeText(20500), 'mysql'))
3572
3605
3573 @declared_attr
3606 @declared_attr
3574 def source_repo_id(cls):
3607 def source_repo_id(cls):
3575 # TODO: dan: rename column to source_repo_id
3608 # TODO: dan: rename column to source_repo_id
3576 return Column(
3609 return Column(
3577 'org_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3610 'org_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3578 nullable=False)
3611 nullable=False)
3579
3612
3580 source_ref = Column('org_ref', Unicode(255), nullable=False)
3613 source_ref = Column('org_ref', Unicode(255), nullable=False)
3581
3614
3582 @declared_attr
3615 @declared_attr
3583 def target_repo_id(cls):
3616 def target_repo_id(cls):
3584 # TODO: dan: rename column to target_repo_id
3617 # TODO: dan: rename column to target_repo_id
3585 return Column(
3618 return Column(
3586 'other_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3619 'other_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3587 nullable=False)
3620 nullable=False)
3588
3621
3589 target_ref = Column('other_ref', Unicode(255), nullable=False)
3622 target_ref = Column('other_ref', Unicode(255), nullable=False)
3590 _shadow_merge_ref = Column('shadow_merge_ref', Unicode(255), nullable=True)
3623 _shadow_merge_ref = Column('shadow_merge_ref', Unicode(255), nullable=True)
3591
3624
3592 # TODO: dan: rename column to last_merge_source_rev
3625 # TODO: dan: rename column to last_merge_source_rev
3593 _last_merge_source_rev = Column(
3626 _last_merge_source_rev = Column(
3594 'last_merge_org_rev', String(40), nullable=True)
3627 'last_merge_org_rev', String(40), nullable=True)
3595 # TODO: dan: rename column to last_merge_target_rev
3628 # TODO: dan: rename column to last_merge_target_rev
3596 _last_merge_target_rev = Column(
3629 _last_merge_target_rev = Column(
3597 'last_merge_other_rev', String(40), nullable=True)
3630 'last_merge_other_rev', String(40), nullable=True)
3598 _last_merge_status = Column('merge_status', Integer(), nullable=True)
3631 _last_merge_status = Column('merge_status', Integer(), nullable=True)
3599 merge_rev = Column('merge_rev', String(40), nullable=True)
3632 merge_rev = Column('merge_rev', String(40), nullable=True)
3600
3633
3601 reviewer_data = Column(
3634 reviewer_data = Column(
3602 'reviewer_data_json', MutationObj.as_mutable(
3635 'reviewer_data_json', MutationObj.as_mutable(
3603 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
3636 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
3604
3637
3605 @property
3638 @property
3606 def reviewer_data_json(self):
3639 def reviewer_data_json(self):
3607 return json.dumps(self.reviewer_data)
3640 return json.dumps(self.reviewer_data)
3608
3641
3609 @hybrid_property
3642 @hybrid_property
3610 def description_safe(self):
3643 def description_safe(self):
3611 from rhodecode.lib import helpers as h
3644 from rhodecode.lib import helpers as h
3612 return h.escape(self.description)
3645 return h.escape(self.description)
3613
3646
3614 @hybrid_property
3647 @hybrid_property
3615 def revisions(self):
3648 def revisions(self):
3616 return self._revisions.split(':') if self._revisions else []
3649 return self._revisions.split(':') if self._revisions else []
3617
3650
3618 @revisions.setter
3651 @revisions.setter
3619 def revisions(self, val):
3652 def revisions(self, val):
3620 self._revisions = ':'.join(val)
3653 self._revisions = ':'.join(val)
3621
3654
3622 @hybrid_property
3655 @hybrid_property
3623 def last_merge_status(self):
3656 def last_merge_status(self):
3624 return safe_int(self._last_merge_status)
3657 return safe_int(self._last_merge_status)
3625
3658
3626 @last_merge_status.setter
3659 @last_merge_status.setter
3627 def last_merge_status(self, val):
3660 def last_merge_status(self, val):
3628 self._last_merge_status = val
3661 self._last_merge_status = val
3629
3662
3630 @declared_attr
3663 @declared_attr
3631 def author(cls):
3664 def author(cls):
3632 return relationship('User', lazy='joined')
3665 return relationship('User', lazy='joined')
3633
3666
3634 @declared_attr
3667 @declared_attr
3635 def source_repo(cls):
3668 def source_repo(cls):
3636 return relationship(
3669 return relationship(
3637 'Repository',
3670 'Repository',
3638 primaryjoin='%s.source_repo_id==Repository.repo_id' % cls.__name__)
3671 primaryjoin='%s.source_repo_id==Repository.repo_id' % cls.__name__)
3639
3672
3640 @property
3673 @property
3641 def source_ref_parts(self):
3674 def source_ref_parts(self):
3642 return self.unicode_to_reference(self.source_ref)
3675 return self.unicode_to_reference(self.source_ref)
3643
3676
3644 @declared_attr
3677 @declared_attr
3645 def target_repo(cls):
3678 def target_repo(cls):
3646 return relationship(
3679 return relationship(
3647 'Repository',
3680 'Repository',
3648 primaryjoin='%s.target_repo_id==Repository.repo_id' % cls.__name__)
3681 primaryjoin='%s.target_repo_id==Repository.repo_id' % cls.__name__)
3649
3682
3650 @property
3683 @property
3651 def target_ref_parts(self):
3684 def target_ref_parts(self):
3652 return self.unicode_to_reference(self.target_ref)
3685 return self.unicode_to_reference(self.target_ref)
3653
3686
3654 @property
3687 @property
3655 def shadow_merge_ref(self):
3688 def shadow_merge_ref(self):
3656 return self.unicode_to_reference(self._shadow_merge_ref)
3689 return self.unicode_to_reference(self._shadow_merge_ref)
3657
3690
3658 @shadow_merge_ref.setter
3691 @shadow_merge_ref.setter
3659 def shadow_merge_ref(self, ref):
3692 def shadow_merge_ref(self, ref):
3660 self._shadow_merge_ref = self.reference_to_unicode(ref)
3693 self._shadow_merge_ref = self.reference_to_unicode(ref)
3661
3694
3662 def unicode_to_reference(self, raw):
3695 def unicode_to_reference(self, raw):
3663 """
3696 """
3664 Convert a unicode (or string) to a reference object.
3697 Convert a unicode (or string) to a reference object.
3665 If unicode evaluates to False it returns None.
3698 If unicode evaluates to False it returns None.
3666 """
3699 """
3667 if raw:
3700 if raw:
3668 refs = raw.split(':')
3701 refs = raw.split(':')
3669 return Reference(*refs)
3702 return Reference(*refs)
3670 else:
3703 else:
3671 return None
3704 return None
3672
3705
3673 def reference_to_unicode(self, ref):
3706 def reference_to_unicode(self, ref):
3674 """
3707 """
3675 Convert a reference object to unicode.
3708 Convert a reference object to unicode.
3676 If reference is None it returns None.
3709 If reference is None it returns None.
3677 """
3710 """
3678 if ref:
3711 if ref:
3679 return u':'.join(ref)
3712 return u':'.join(ref)
3680 else:
3713 else:
3681 return None
3714 return None
3682
3715
3683 def get_api_data(self, with_merge_state=True):
3716 def get_api_data(self, with_merge_state=True):
3684 from rhodecode.model.pull_request import PullRequestModel
3717 from rhodecode.model.pull_request import PullRequestModel
3685
3718
3686 pull_request = self
3719 pull_request = self
3687 if with_merge_state:
3720 if with_merge_state:
3688 merge_status = PullRequestModel().merge_status(pull_request)
3721 merge_status = PullRequestModel().merge_status(pull_request)
3689 merge_state = {
3722 merge_state = {
3690 'status': merge_status[0],
3723 'status': merge_status[0],
3691 'message': safe_unicode(merge_status[1]),
3724 'message': safe_unicode(merge_status[1]),
3692 }
3725 }
3693 else:
3726 else:
3694 merge_state = {'status': 'not_available',
3727 merge_state = {'status': 'not_available',
3695 'message': 'not_available'}
3728 'message': 'not_available'}
3696
3729
3697 merge_data = {
3730 merge_data = {
3698 'clone_url': PullRequestModel().get_shadow_clone_url(pull_request),
3731 'clone_url': PullRequestModel().get_shadow_clone_url(pull_request),
3699 'reference': (
3732 'reference': (
3700 pull_request.shadow_merge_ref._asdict()
3733 pull_request.shadow_merge_ref._asdict()
3701 if pull_request.shadow_merge_ref else None),
3734 if pull_request.shadow_merge_ref else None),
3702 }
3735 }
3703
3736
3704 data = {
3737 data = {
3705 'pull_request_id': pull_request.pull_request_id,
3738 'pull_request_id': pull_request.pull_request_id,
3706 'url': PullRequestModel().get_url(pull_request),
3739 'url': PullRequestModel().get_url(pull_request),
3707 'title': pull_request.title,
3740 'title': pull_request.title,
3708 'description': pull_request.description,
3741 'description': pull_request.description,
3709 'status': pull_request.status,
3742 'status': pull_request.status,
3710 'created_on': pull_request.created_on,
3743 'created_on': pull_request.created_on,
3711 'updated_on': pull_request.updated_on,
3744 'updated_on': pull_request.updated_on,
3712 'commit_ids': pull_request.revisions,
3745 'commit_ids': pull_request.revisions,
3713 'review_status': pull_request.calculated_review_status(),
3746 'review_status': pull_request.calculated_review_status(),
3714 'mergeable': merge_state,
3747 'mergeable': merge_state,
3715 'source': {
3748 'source': {
3716 'clone_url': pull_request.source_repo.clone_url(),
3749 'clone_url': pull_request.source_repo.clone_url(),
3717 'repository': pull_request.source_repo.repo_name,
3750 'repository': pull_request.source_repo.repo_name,
3718 'reference': {
3751 'reference': {
3719 'name': pull_request.source_ref_parts.name,
3752 'name': pull_request.source_ref_parts.name,
3720 'type': pull_request.source_ref_parts.type,
3753 'type': pull_request.source_ref_parts.type,
3721 'commit_id': pull_request.source_ref_parts.commit_id,
3754 'commit_id': pull_request.source_ref_parts.commit_id,
3722 },
3755 },
3723 },
3756 },
3724 'target': {
3757 'target': {
3725 'clone_url': pull_request.target_repo.clone_url(),
3758 'clone_url': pull_request.target_repo.clone_url(),
3726 'repository': pull_request.target_repo.repo_name,
3759 'repository': pull_request.target_repo.repo_name,
3727 'reference': {
3760 'reference': {
3728 'name': pull_request.target_ref_parts.name,
3761 'name': pull_request.target_ref_parts.name,
3729 'type': pull_request.target_ref_parts.type,
3762 'type': pull_request.target_ref_parts.type,
3730 'commit_id': pull_request.target_ref_parts.commit_id,
3763 'commit_id': pull_request.target_ref_parts.commit_id,
3731 },
3764 },
3732 },
3765 },
3733 'merge': merge_data,
3766 'merge': merge_data,
3734 'author': pull_request.author.get_api_data(include_secrets=False,
3767 'author': pull_request.author.get_api_data(include_secrets=False,
3735 details='basic'),
3768 details='basic'),
3736 'reviewers': [
3769 'reviewers': [
3737 {
3770 {
3738 'user': reviewer.get_api_data(include_secrets=False,
3771 'user': reviewer.get_api_data(include_secrets=False,
3739 details='basic'),
3772 details='basic'),
3740 'reasons': reasons,
3773 'reasons': reasons,
3741 'review_status': st[0][1].status if st else 'not_reviewed',
3774 'review_status': st[0][1].status if st else 'not_reviewed',
3742 }
3775 }
3743 for obj, reviewer, reasons, mandatory, st in
3776 for obj, reviewer, reasons, mandatory, st in
3744 pull_request.reviewers_statuses()
3777 pull_request.reviewers_statuses()
3745 ]
3778 ]
3746 }
3779 }
3747
3780
3748 return data
3781 return data
3749
3782
3750
3783
3751 class PullRequest(Base, _PullRequestBase):
3784 class PullRequest(Base, _PullRequestBase):
3752 __tablename__ = 'pull_requests'
3785 __tablename__ = 'pull_requests'
3753 __table_args__ = (
3786 __table_args__ = (
3754 base_table_args,
3787 base_table_args,
3755 )
3788 )
3756
3789
3757 pull_request_id = Column(
3790 pull_request_id = Column(
3758 'pull_request_id', Integer(), nullable=False, primary_key=True)
3791 'pull_request_id', Integer(), nullable=False, primary_key=True)
3759
3792
3760 def __repr__(self):
3793 def __repr__(self):
3761 if self.pull_request_id:
3794 if self.pull_request_id:
3762 return '<DB:PullRequest #%s>' % self.pull_request_id
3795 return '<DB:PullRequest #%s>' % self.pull_request_id
3763 else:
3796 else:
3764 return '<DB:PullRequest at %#x>' % id(self)
3797 return '<DB:PullRequest at %#x>' % id(self)
3765
3798
3766 reviewers = relationship('PullRequestReviewers',
3799 reviewers = relationship('PullRequestReviewers',
3767 cascade="all, delete, delete-orphan")
3800 cascade="all, delete, delete-orphan")
3768 statuses = relationship('ChangesetStatus',
3801 statuses = relationship('ChangesetStatus',
3769 cascade="all, delete, delete-orphan")
3802 cascade="all, delete, delete-orphan")
3770 comments = relationship('ChangesetComment',
3803 comments = relationship('ChangesetComment',
3771 cascade="all, delete, delete-orphan")
3804 cascade="all, delete, delete-orphan")
3772 versions = relationship('PullRequestVersion',
3805 versions = relationship('PullRequestVersion',
3773 cascade="all, delete, delete-orphan",
3806 cascade="all, delete, delete-orphan",
3774 lazy='dynamic')
3807 lazy='dynamic')
3775
3808
3776 @classmethod
3809 @classmethod
3777 def get_pr_display_object(cls, pull_request_obj, org_pull_request_obj,
3810 def get_pr_display_object(cls, pull_request_obj, org_pull_request_obj,
3778 internal_methods=None):
3811 internal_methods=None):
3779
3812
3780 class PullRequestDisplay(object):
3813 class PullRequestDisplay(object):
3781 """
3814 """
3782 Special object wrapper for showing PullRequest data via Versions
3815 Special object wrapper for showing PullRequest data via Versions
3783 It mimics PR object as close as possible. This is read only object
3816 It mimics PR object as close as possible. This is read only object
3784 just for display
3817 just for display
3785 """
3818 """
3786
3819
3787 def __init__(self, attrs, internal=None):
3820 def __init__(self, attrs, internal=None):
3788 self.attrs = attrs
3821 self.attrs = attrs
3789 # internal have priority over the given ones via attrs
3822 # internal have priority over the given ones via attrs
3790 self.internal = internal or ['versions']
3823 self.internal = internal or ['versions']
3791
3824
3792 def __getattr__(self, item):
3825 def __getattr__(self, item):
3793 if item in self.internal:
3826 if item in self.internal:
3794 return getattr(self, item)
3827 return getattr(self, item)
3795 try:
3828 try:
3796 return self.attrs[item]
3829 return self.attrs[item]
3797 except KeyError:
3830 except KeyError:
3798 raise AttributeError(
3831 raise AttributeError(
3799 '%s object has no attribute %s' % (self, item))
3832 '%s object has no attribute %s' % (self, item))
3800
3833
3801 def __repr__(self):
3834 def __repr__(self):
3802 return '<DB:PullRequestDisplay #%s>' % self.attrs.get('pull_request_id')
3835 return '<DB:PullRequestDisplay #%s>' % self.attrs.get('pull_request_id')
3803
3836
3804 def versions(self):
3837 def versions(self):
3805 return pull_request_obj.versions.order_by(
3838 return pull_request_obj.versions.order_by(
3806 PullRequestVersion.pull_request_version_id).all()
3839 PullRequestVersion.pull_request_version_id).all()
3807
3840
3808 def is_closed(self):
3841 def is_closed(self):
3809 return pull_request_obj.is_closed()
3842 return pull_request_obj.is_closed()
3810
3843
3811 @property
3844 @property
3812 def pull_request_version_id(self):
3845 def pull_request_version_id(self):
3813 return getattr(pull_request_obj, 'pull_request_version_id', None)
3846 return getattr(pull_request_obj, 'pull_request_version_id', None)
3814
3847
3815 attrs = StrictAttributeDict(pull_request_obj.get_api_data())
3848 attrs = StrictAttributeDict(pull_request_obj.get_api_data())
3816
3849
3817 attrs.author = StrictAttributeDict(
3850 attrs.author = StrictAttributeDict(
3818 pull_request_obj.author.get_api_data())
3851 pull_request_obj.author.get_api_data())
3819 if pull_request_obj.target_repo:
3852 if pull_request_obj.target_repo:
3820 attrs.target_repo = StrictAttributeDict(
3853 attrs.target_repo = StrictAttributeDict(
3821 pull_request_obj.target_repo.get_api_data())
3854 pull_request_obj.target_repo.get_api_data())
3822 attrs.target_repo.clone_url = pull_request_obj.target_repo.clone_url
3855 attrs.target_repo.clone_url = pull_request_obj.target_repo.clone_url
3823
3856
3824 if pull_request_obj.source_repo:
3857 if pull_request_obj.source_repo:
3825 attrs.source_repo = StrictAttributeDict(
3858 attrs.source_repo = StrictAttributeDict(
3826 pull_request_obj.source_repo.get_api_data())
3859 pull_request_obj.source_repo.get_api_data())
3827 attrs.source_repo.clone_url = pull_request_obj.source_repo.clone_url
3860 attrs.source_repo.clone_url = pull_request_obj.source_repo.clone_url
3828
3861
3829 attrs.source_ref_parts = pull_request_obj.source_ref_parts
3862 attrs.source_ref_parts = pull_request_obj.source_ref_parts
3830 attrs.target_ref_parts = pull_request_obj.target_ref_parts
3863 attrs.target_ref_parts = pull_request_obj.target_ref_parts
3831 attrs.revisions = pull_request_obj.revisions
3864 attrs.revisions = pull_request_obj.revisions
3832
3865
3833 attrs.shadow_merge_ref = org_pull_request_obj.shadow_merge_ref
3866 attrs.shadow_merge_ref = org_pull_request_obj.shadow_merge_ref
3834 attrs.reviewer_data = org_pull_request_obj.reviewer_data
3867 attrs.reviewer_data = org_pull_request_obj.reviewer_data
3835 attrs.reviewer_data_json = org_pull_request_obj.reviewer_data_json
3868 attrs.reviewer_data_json = org_pull_request_obj.reviewer_data_json
3836
3869
3837 return PullRequestDisplay(attrs, internal=internal_methods)
3870 return PullRequestDisplay(attrs, internal=internal_methods)
3838
3871
3839 def is_closed(self):
3872 def is_closed(self):
3840 return self.status == self.STATUS_CLOSED
3873 return self.status == self.STATUS_CLOSED
3841
3874
3842 def __json__(self):
3875 def __json__(self):
3843 return {
3876 return {
3844 'revisions': self.revisions,
3877 'revisions': self.revisions,
3845 }
3878 }
3846
3879
3847 def calculated_review_status(self):
3880 def calculated_review_status(self):
3848 from rhodecode.model.changeset_status import ChangesetStatusModel
3881 from rhodecode.model.changeset_status import ChangesetStatusModel
3849 return ChangesetStatusModel().calculated_review_status(self)
3882 return ChangesetStatusModel().calculated_review_status(self)
3850
3883
3851 def reviewers_statuses(self):
3884 def reviewers_statuses(self):
3852 from rhodecode.model.changeset_status import ChangesetStatusModel
3885 from rhodecode.model.changeset_status import ChangesetStatusModel
3853 return ChangesetStatusModel().reviewers_statuses(self)
3886 return ChangesetStatusModel().reviewers_statuses(self)
3854
3887
3855 @property
3888 @property
3856 def workspace_id(self):
3889 def workspace_id(self):
3857 from rhodecode.model.pull_request import PullRequestModel
3890 from rhodecode.model.pull_request import PullRequestModel
3858 return PullRequestModel()._workspace_id(self)
3891 return PullRequestModel()._workspace_id(self)
3859
3892
3860 def get_shadow_repo(self):
3893 def get_shadow_repo(self):
3861 workspace_id = self.workspace_id
3894 workspace_id = self.workspace_id
3862 vcs_obj = self.target_repo.scm_instance()
3895 vcs_obj = self.target_repo.scm_instance()
3863 shadow_repository_path = vcs_obj._get_shadow_repository_path(
3896 shadow_repository_path = vcs_obj._get_shadow_repository_path(
3864 self.target_repo.repo_id, workspace_id)
3897 self.target_repo.repo_id, workspace_id)
3865 if os.path.isdir(shadow_repository_path):
3898 if os.path.isdir(shadow_repository_path):
3866 return vcs_obj._get_shadow_instance(shadow_repository_path)
3899 return vcs_obj._get_shadow_instance(shadow_repository_path)
3867
3900
3868
3901
3869 class PullRequestVersion(Base, _PullRequestBase):
3902 class PullRequestVersion(Base, _PullRequestBase):
3870 __tablename__ = 'pull_request_versions'
3903 __tablename__ = 'pull_request_versions'
3871 __table_args__ = (
3904 __table_args__ = (
3872 base_table_args,
3905 base_table_args,
3873 )
3906 )
3874
3907
3875 pull_request_version_id = Column(
3908 pull_request_version_id = Column(
3876 'pull_request_version_id', Integer(), nullable=False, primary_key=True)
3909 'pull_request_version_id', Integer(), nullable=False, primary_key=True)
3877 pull_request_id = Column(
3910 pull_request_id = Column(
3878 'pull_request_id', Integer(),
3911 'pull_request_id', Integer(),
3879 ForeignKey('pull_requests.pull_request_id'), nullable=False)
3912 ForeignKey('pull_requests.pull_request_id'), nullable=False)
3880 pull_request = relationship('PullRequest')
3913 pull_request = relationship('PullRequest')
3881
3914
3882 def __repr__(self):
3915 def __repr__(self):
3883 if self.pull_request_version_id:
3916 if self.pull_request_version_id:
3884 return '<DB:PullRequestVersion #%s>' % self.pull_request_version_id
3917 return '<DB:PullRequestVersion #%s>' % self.pull_request_version_id
3885 else:
3918 else:
3886 return '<DB:PullRequestVersion at %#x>' % id(self)
3919 return '<DB:PullRequestVersion at %#x>' % id(self)
3887
3920
3888 @property
3921 @property
3889 def reviewers(self):
3922 def reviewers(self):
3890 return self.pull_request.reviewers
3923 return self.pull_request.reviewers
3891
3924
3892 @property
3925 @property
3893 def versions(self):
3926 def versions(self):
3894 return self.pull_request.versions
3927 return self.pull_request.versions
3895
3928
3896 def is_closed(self):
3929 def is_closed(self):
3897 # calculate from original
3930 # calculate from original
3898 return self.pull_request.status == self.STATUS_CLOSED
3931 return self.pull_request.status == self.STATUS_CLOSED
3899
3932
3900 def calculated_review_status(self):
3933 def calculated_review_status(self):
3901 return self.pull_request.calculated_review_status()
3934 return self.pull_request.calculated_review_status()
3902
3935
3903 def reviewers_statuses(self):
3936 def reviewers_statuses(self):
3904 return self.pull_request.reviewers_statuses()
3937 return self.pull_request.reviewers_statuses()
3905
3938
3906
3939
3907 class PullRequestReviewers(Base, BaseModel):
3940 class PullRequestReviewers(Base, BaseModel):
3908 __tablename__ = 'pull_request_reviewers'
3941 __tablename__ = 'pull_request_reviewers'
3909 __table_args__ = (
3942 __table_args__ = (
3910 base_table_args,
3943 base_table_args,
3911 )
3944 )
3912
3945
3913 @hybrid_property
3946 @hybrid_property
3914 def reasons(self):
3947 def reasons(self):
3915 if not self._reasons:
3948 if not self._reasons:
3916 return []
3949 return []
3917 return self._reasons
3950 return self._reasons
3918
3951
3919 @reasons.setter
3952 @reasons.setter
3920 def reasons(self, val):
3953 def reasons(self, val):
3921 val = val or []
3954 val = val or []
3922 if any(not isinstance(x, basestring) for x in val):
3955 if any(not isinstance(x, basestring) for x in val):
3923 raise Exception('invalid reasons type, must be list of strings')
3956 raise Exception('invalid reasons type, must be list of strings')
3924 self._reasons = val
3957 self._reasons = val
3925
3958
3926 pull_requests_reviewers_id = Column(
3959 pull_requests_reviewers_id = Column(
3927 'pull_requests_reviewers_id', Integer(), nullable=False,
3960 'pull_requests_reviewers_id', Integer(), nullable=False,
3928 primary_key=True)
3961 primary_key=True)
3929 pull_request_id = Column(
3962 pull_request_id = Column(
3930 "pull_request_id", Integer(),
3963 "pull_request_id", Integer(),
3931 ForeignKey('pull_requests.pull_request_id'), nullable=False)
3964 ForeignKey('pull_requests.pull_request_id'), nullable=False)
3932 user_id = Column(
3965 user_id = Column(
3933 "user_id", Integer(), ForeignKey('users.user_id'), nullable=True)
3966 "user_id", Integer(), ForeignKey('users.user_id'), nullable=True)
3934 _reasons = Column(
3967 _reasons = Column(
3935 'reason', MutationList.as_mutable(
3968 'reason', MutationList.as_mutable(
3936 JsonType('list', dialect_map=dict(mysql=UnicodeText(16384)))))
3969 JsonType('list', dialect_map=dict(mysql=UnicodeText(16384)))))
3937
3970
3938 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
3971 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
3939 user = relationship('User')
3972 user = relationship('User')
3940 pull_request = relationship('PullRequest')
3973 pull_request = relationship('PullRequest')
3941
3974
3942 rule_data = Column(
3975 rule_data = Column(
3943 'rule_data_json',
3976 'rule_data_json',
3944 JsonType(dialect_map=dict(mysql=UnicodeText(16384))))
3977 JsonType(dialect_map=dict(mysql=UnicodeText(16384))))
3945
3978
3946 def rule_user_group_data(self):
3979 def rule_user_group_data(self):
3947 """
3980 """
3948 Returns the voting user group rule data for this reviewer
3981 Returns the voting user group rule data for this reviewer
3949 """
3982 """
3950
3983
3951 if self.rule_data and 'vote_rule' in self.rule_data:
3984 if self.rule_data and 'vote_rule' in self.rule_data:
3952 user_group_data = {}
3985 user_group_data = {}
3953 if 'rule_user_group_entry_id' in self.rule_data:
3986 if 'rule_user_group_entry_id' in self.rule_data:
3954 # means a group with voting rules !
3987 # means a group with voting rules !
3955 user_group_data['id'] = self.rule_data['rule_user_group_entry_id']
3988 user_group_data['id'] = self.rule_data['rule_user_group_entry_id']
3956 user_group_data['name'] = self.rule_data['rule_name']
3989 user_group_data['name'] = self.rule_data['rule_name']
3957 user_group_data['vote_rule'] = self.rule_data['vote_rule']
3990 user_group_data['vote_rule'] = self.rule_data['vote_rule']
3958
3991
3959 return user_group_data
3992 return user_group_data
3960
3993
3961 def __unicode__(self):
3994 def __unicode__(self):
3962 return u"<%s('id:%s')>" % (self.__class__.__name__,
3995 return u"<%s('id:%s')>" % (self.__class__.__name__,
3963 self.pull_requests_reviewers_id)
3996 self.pull_requests_reviewers_id)
3964
3997
3965
3998
3966 class Notification(Base, BaseModel):
3999 class Notification(Base, BaseModel):
3967 __tablename__ = 'notifications'
4000 __tablename__ = 'notifications'
3968 __table_args__ = (
4001 __table_args__ = (
3969 Index('notification_type_idx', 'type'),
4002 Index('notification_type_idx', 'type'),
3970 base_table_args,
4003 base_table_args,
3971 )
4004 )
3972
4005
3973 TYPE_CHANGESET_COMMENT = u'cs_comment'
4006 TYPE_CHANGESET_COMMENT = u'cs_comment'
3974 TYPE_MESSAGE = u'message'
4007 TYPE_MESSAGE = u'message'
3975 TYPE_MENTION = u'mention'
4008 TYPE_MENTION = u'mention'
3976 TYPE_REGISTRATION = u'registration'
4009 TYPE_REGISTRATION = u'registration'
3977 TYPE_PULL_REQUEST = u'pull_request'
4010 TYPE_PULL_REQUEST = u'pull_request'
3978 TYPE_PULL_REQUEST_COMMENT = u'pull_request_comment'
4011 TYPE_PULL_REQUEST_COMMENT = u'pull_request_comment'
3979
4012
3980 notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True)
4013 notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True)
3981 subject = Column('subject', Unicode(512), nullable=True)
4014 subject = Column('subject', Unicode(512), nullable=True)
3982 body = Column('body', UnicodeText().with_variant(UnicodeText(50000), 'mysql'), nullable=True)
4015 body = Column('body', UnicodeText().with_variant(UnicodeText(50000), 'mysql'), nullable=True)
3983 created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True)
4016 created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True)
3984 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4017 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3985 type_ = Column('type', Unicode(255))
4018 type_ = Column('type', Unicode(255))
3986
4019
3987 created_by_user = relationship('User')
4020 created_by_user = relationship('User')
3988 notifications_to_users = relationship('UserNotification', lazy='joined',
4021 notifications_to_users = relationship('UserNotification', lazy='joined',
3989 cascade="all, delete, delete-orphan")
4022 cascade="all, delete, delete-orphan")
3990
4023
3991 @property
4024 @property
3992 def recipients(self):
4025 def recipients(self):
3993 return [x.user for x in UserNotification.query()\
4026 return [x.user for x in UserNotification.query()\
3994 .filter(UserNotification.notification == self)\
4027 .filter(UserNotification.notification == self)\
3995 .order_by(UserNotification.user_id.asc()).all()]
4028 .order_by(UserNotification.user_id.asc()).all()]
3996
4029
3997 @classmethod
4030 @classmethod
3998 def create(cls, created_by, subject, body, recipients, type_=None):
4031 def create(cls, created_by, subject, body, recipients, type_=None):
3999 if type_ is None:
4032 if type_ is None:
4000 type_ = Notification.TYPE_MESSAGE
4033 type_ = Notification.TYPE_MESSAGE
4001
4034
4002 notification = cls()
4035 notification = cls()
4003 notification.created_by_user = created_by
4036 notification.created_by_user = created_by
4004 notification.subject = subject
4037 notification.subject = subject
4005 notification.body = body
4038 notification.body = body
4006 notification.type_ = type_
4039 notification.type_ = type_
4007 notification.created_on = datetime.datetime.now()
4040 notification.created_on = datetime.datetime.now()
4008
4041
4009 # For each recipient link the created notification to his account
4042 # For each recipient link the created notification to his account
4010 for u in recipients:
4043 for u in recipients:
4011 assoc = UserNotification()
4044 assoc = UserNotification()
4012 assoc.user_id = u.user_id
4045 assoc.user_id = u.user_id
4013 assoc.notification = notification
4046 assoc.notification = notification
4014
4047
4015 # if created_by is inside recipients mark his notification
4048 # if created_by is inside recipients mark his notification
4016 # as read
4049 # as read
4017 if u.user_id == created_by.user_id:
4050 if u.user_id == created_by.user_id:
4018 assoc.read = True
4051 assoc.read = True
4019 Session().add(assoc)
4052 Session().add(assoc)
4020
4053
4021 Session().add(notification)
4054 Session().add(notification)
4022
4055
4023 return notification
4056 return notification
4024
4057
4025
4058
4026 class UserNotification(Base, BaseModel):
4059 class UserNotification(Base, BaseModel):
4027 __tablename__ = 'user_to_notification'
4060 __tablename__ = 'user_to_notification'
4028 __table_args__ = (
4061 __table_args__ = (
4029 UniqueConstraint('user_id', 'notification_id'),
4062 UniqueConstraint('user_id', 'notification_id'),
4030 base_table_args
4063 base_table_args
4031 )
4064 )
4032
4065
4033 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
4066 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
4034 notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
4067 notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
4035 read = Column('read', Boolean, default=False)
4068 read = Column('read', Boolean, default=False)
4036 sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
4069 sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
4037
4070
4038 user = relationship('User', lazy="joined")
4071 user = relationship('User', lazy="joined")
4039 notification = relationship('Notification', lazy="joined",
4072 notification = relationship('Notification', lazy="joined",
4040 order_by=lambda: Notification.created_on.desc(),)
4073 order_by=lambda: Notification.created_on.desc(),)
4041
4074
4042 def mark_as_read(self):
4075 def mark_as_read(self):
4043 self.read = True
4076 self.read = True
4044 Session().add(self)
4077 Session().add(self)
4045
4078
4046
4079
4047 class Gist(Base, BaseModel):
4080 class Gist(Base, BaseModel):
4048 __tablename__ = 'gists'
4081 __tablename__ = 'gists'
4049 __table_args__ = (
4082 __table_args__ = (
4050 Index('g_gist_access_id_idx', 'gist_access_id'),
4083 Index('g_gist_access_id_idx', 'gist_access_id'),
4051 Index('g_created_on_idx', 'created_on'),
4084 Index('g_created_on_idx', 'created_on'),
4052 base_table_args
4085 base_table_args
4053 )
4086 )
4054
4087
4055 GIST_PUBLIC = u'public'
4088 GIST_PUBLIC = u'public'
4056 GIST_PRIVATE = u'private'
4089 GIST_PRIVATE = u'private'
4057 DEFAULT_FILENAME = u'gistfile1.txt'
4090 DEFAULT_FILENAME = u'gistfile1.txt'
4058
4091
4059 ACL_LEVEL_PUBLIC = u'acl_public'
4092 ACL_LEVEL_PUBLIC = u'acl_public'
4060 ACL_LEVEL_PRIVATE = u'acl_private'
4093 ACL_LEVEL_PRIVATE = u'acl_private'
4061
4094
4062 gist_id = Column('gist_id', Integer(), primary_key=True)
4095 gist_id = Column('gist_id', Integer(), primary_key=True)
4063 gist_access_id = Column('gist_access_id', Unicode(250))
4096 gist_access_id = Column('gist_access_id', Unicode(250))
4064 gist_description = Column('gist_description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
4097 gist_description = Column('gist_description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
4065 gist_owner = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True)
4098 gist_owner = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True)
4066 gist_expires = Column('gist_expires', Float(53), nullable=False)
4099 gist_expires = Column('gist_expires', Float(53), nullable=False)
4067 gist_type = Column('gist_type', Unicode(128), nullable=False)
4100 gist_type = Column('gist_type', Unicode(128), nullable=False)
4068 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4101 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4069 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4102 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4070 acl_level = Column('acl_level', Unicode(128), nullable=True)
4103 acl_level = Column('acl_level', Unicode(128), nullable=True)
4071
4104
4072 owner = relationship('User')
4105 owner = relationship('User')
4073
4106
4074 def __repr__(self):
4107 def __repr__(self):
4075 return '<Gist:[%s]%s>' % (self.gist_type, self.gist_access_id)
4108 return '<Gist:[%s]%s>' % (self.gist_type, self.gist_access_id)
4076
4109
4077 @hybrid_property
4110 @hybrid_property
4078 def description_safe(self):
4111 def description_safe(self):
4079 from rhodecode.lib import helpers as h
4112 from rhodecode.lib import helpers as h
4080 return h.escape(self.gist_description)
4113 return h.escape(self.gist_description)
4081
4114
4082 @classmethod
4115 @classmethod
4083 def get_or_404(cls, id_):
4116 def get_or_404(cls, id_):
4084 from pyramid.httpexceptions import HTTPNotFound
4117 from pyramid.httpexceptions import HTTPNotFound
4085
4118
4086 res = cls.query().filter(cls.gist_access_id == id_).scalar()
4119 res = cls.query().filter(cls.gist_access_id == id_).scalar()
4087 if not res:
4120 if not res:
4088 raise HTTPNotFound()
4121 raise HTTPNotFound()
4089 return res
4122 return res
4090
4123
4091 @classmethod
4124 @classmethod
4092 def get_by_access_id(cls, gist_access_id):
4125 def get_by_access_id(cls, gist_access_id):
4093 return cls.query().filter(cls.gist_access_id == gist_access_id).scalar()
4126 return cls.query().filter(cls.gist_access_id == gist_access_id).scalar()
4094
4127
4095 def gist_url(self):
4128 def gist_url(self):
4096 from rhodecode.model.gist import GistModel
4129 from rhodecode.model.gist import GistModel
4097 return GistModel().get_url(self)
4130 return GistModel().get_url(self)
4098
4131
4099 @classmethod
4132 @classmethod
4100 def base_path(cls):
4133 def base_path(cls):
4101 """
4134 """
4102 Returns base path when all gists are stored
4135 Returns base path when all gists are stored
4103
4136
4104 :param cls:
4137 :param cls:
4105 """
4138 """
4106 from rhodecode.model.gist import GIST_STORE_LOC
4139 from rhodecode.model.gist import GIST_STORE_LOC
4107 q = Session().query(RhodeCodeUi)\
4140 q = Session().query(RhodeCodeUi)\
4108 .filter(RhodeCodeUi.ui_key == URL_SEP)
4141 .filter(RhodeCodeUi.ui_key == URL_SEP)
4109 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
4142 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
4110 return os.path.join(q.one().ui_value, GIST_STORE_LOC)
4143 return os.path.join(q.one().ui_value, GIST_STORE_LOC)
4111
4144
4112 def get_api_data(self):
4145 def get_api_data(self):
4113 """
4146 """
4114 Common function for generating gist related data for API
4147 Common function for generating gist related data for API
4115 """
4148 """
4116 gist = self
4149 gist = self
4117 data = {
4150 data = {
4118 'gist_id': gist.gist_id,
4151 'gist_id': gist.gist_id,
4119 'type': gist.gist_type,
4152 'type': gist.gist_type,
4120 'access_id': gist.gist_access_id,
4153 'access_id': gist.gist_access_id,
4121 'description': gist.gist_description,
4154 'description': gist.gist_description,
4122 'url': gist.gist_url(),
4155 'url': gist.gist_url(),
4123 'expires': gist.gist_expires,
4156 'expires': gist.gist_expires,
4124 'created_on': gist.created_on,
4157 'created_on': gist.created_on,
4125 'modified_at': gist.modified_at,
4158 'modified_at': gist.modified_at,
4126 'content': None,
4159 'content': None,
4127 'acl_level': gist.acl_level,
4160 'acl_level': gist.acl_level,
4128 }
4161 }
4129 return data
4162 return data
4130
4163
4131 def __json__(self):
4164 def __json__(self):
4132 data = dict(
4165 data = dict(
4133 )
4166 )
4134 data.update(self.get_api_data())
4167 data.update(self.get_api_data())
4135 return data
4168 return data
4136 # SCM functions
4169 # SCM functions
4137
4170
4138 def scm_instance(self, **kwargs):
4171 def scm_instance(self, **kwargs):
4139 full_repo_path = os.path.join(self.base_path(), self.gist_access_id)
4172 full_repo_path = os.path.join(self.base_path(), self.gist_access_id)
4140 return get_vcs_instance(
4173 return get_vcs_instance(
4141 repo_path=safe_str(full_repo_path), create=False)
4174 repo_path=safe_str(full_repo_path), create=False)
4142
4175
4143
4176
4144 class ExternalIdentity(Base, BaseModel):
4177 class ExternalIdentity(Base, BaseModel):
4145 __tablename__ = 'external_identities'
4178 __tablename__ = 'external_identities'
4146 __table_args__ = (
4179 __table_args__ = (
4147 Index('local_user_id_idx', 'local_user_id'),
4180 Index('local_user_id_idx', 'local_user_id'),
4148 Index('external_id_idx', 'external_id'),
4181 Index('external_id_idx', 'external_id'),
4149 base_table_args
4182 base_table_args
4150 )
4183 )
4151
4184
4152 external_id = Column('external_id', Unicode(255), default=u'', primary_key=True)
4185 external_id = Column('external_id', Unicode(255), default=u'', primary_key=True)
4153 external_username = Column('external_username', Unicode(1024), default=u'')
4186 external_username = Column('external_username', Unicode(1024), default=u'')
4154 local_user_id = Column('local_user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
4187 local_user_id = Column('local_user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
4155 provider_name = Column('provider_name', Unicode(255), default=u'', primary_key=True)
4188 provider_name = Column('provider_name', Unicode(255), default=u'', primary_key=True)
4156 access_token = Column('access_token', String(1024), default=u'')
4189 access_token = Column('access_token', String(1024), default=u'')
4157 alt_token = Column('alt_token', String(1024), default=u'')
4190 alt_token = Column('alt_token', String(1024), default=u'')
4158 token_secret = Column('token_secret', String(1024), default=u'')
4191 token_secret = Column('token_secret', String(1024), default=u'')
4159
4192
4160 @classmethod
4193 @classmethod
4161 def by_external_id_and_provider(cls, external_id, provider_name, local_user_id=None):
4194 def by_external_id_and_provider(cls, external_id, provider_name, local_user_id=None):
4162 """
4195 """
4163 Returns ExternalIdentity instance based on search params
4196 Returns ExternalIdentity instance based on search params
4164
4197
4165 :param external_id:
4198 :param external_id:
4166 :param provider_name:
4199 :param provider_name:
4167 :return: ExternalIdentity
4200 :return: ExternalIdentity
4168 """
4201 """
4169 query = cls.query()
4202 query = cls.query()
4170 query = query.filter(cls.external_id == external_id)
4203 query = query.filter(cls.external_id == external_id)
4171 query = query.filter(cls.provider_name == provider_name)
4204 query = query.filter(cls.provider_name == provider_name)
4172 if local_user_id:
4205 if local_user_id:
4173 query = query.filter(cls.local_user_id == local_user_id)
4206 query = query.filter(cls.local_user_id == local_user_id)
4174 return query.first()
4207 return query.first()
4175
4208
4176 @classmethod
4209 @classmethod
4177 def user_by_external_id_and_provider(cls, external_id, provider_name):
4210 def user_by_external_id_and_provider(cls, external_id, provider_name):
4178 """
4211 """
4179 Returns User instance based on search params
4212 Returns User instance based on search params
4180
4213
4181 :param external_id:
4214 :param external_id:
4182 :param provider_name:
4215 :param provider_name:
4183 :return: User
4216 :return: User
4184 """
4217 """
4185 query = User.query()
4218 query = User.query()
4186 query = query.filter(cls.external_id == external_id)
4219 query = query.filter(cls.external_id == external_id)
4187 query = query.filter(cls.provider_name == provider_name)
4220 query = query.filter(cls.provider_name == provider_name)
4188 query = query.filter(User.user_id == cls.local_user_id)
4221 query = query.filter(User.user_id == cls.local_user_id)
4189 return query.first()
4222 return query.first()
4190
4223
4191 @classmethod
4224 @classmethod
4192 def by_local_user_id(cls, local_user_id):
4225 def by_local_user_id(cls, local_user_id):
4193 """
4226 """
4194 Returns all tokens for user
4227 Returns all tokens for user
4195
4228
4196 :param local_user_id:
4229 :param local_user_id:
4197 :return: ExternalIdentity
4230 :return: ExternalIdentity
4198 """
4231 """
4199 query = cls.query()
4232 query = cls.query()
4200 query = query.filter(cls.local_user_id == local_user_id)
4233 query = query.filter(cls.local_user_id == local_user_id)
4201 return query
4234 return query
4202
4235
4203 @classmethod
4236 @classmethod
4204 def load_provider_plugin(cls, plugin_id):
4237 def load_provider_plugin(cls, plugin_id):
4205 from rhodecode.authentication.base import loadplugin
4238 from rhodecode.authentication.base import loadplugin
4206 _plugin_id = 'egg:rhodecode-enterprise-ee#{}'.format(plugin_id)
4239 _plugin_id = 'egg:rhodecode-enterprise-ee#{}'.format(plugin_id)
4207 auth_plugin = loadplugin(_plugin_id)
4240 auth_plugin = loadplugin(_plugin_id)
4208 return auth_plugin
4241 return auth_plugin
4209
4242
4210
4243
4211 class Integration(Base, BaseModel):
4244 class Integration(Base, BaseModel):
4212 __tablename__ = 'integrations'
4245 __tablename__ = 'integrations'
4213 __table_args__ = (
4246 __table_args__ = (
4214 base_table_args
4247 base_table_args
4215 )
4248 )
4216
4249
4217 integration_id = Column('integration_id', Integer(), primary_key=True)
4250 integration_id = Column('integration_id', Integer(), primary_key=True)
4218 integration_type = Column('integration_type', String(255))
4251 integration_type = Column('integration_type', String(255))
4219 enabled = Column('enabled', Boolean(), nullable=False)
4252 enabled = Column('enabled', Boolean(), nullable=False)
4220 name = Column('name', String(255), nullable=False)
4253 name = Column('name', String(255), nullable=False)
4221 child_repos_only = Column('child_repos_only', Boolean(), nullable=False,
4254 child_repos_only = Column('child_repos_only', Boolean(), nullable=False,
4222 default=False)
4255 default=False)
4223
4256
4224 settings = Column(
4257 settings = Column(
4225 'settings_json', MutationObj.as_mutable(
4258 'settings_json', MutationObj.as_mutable(
4226 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
4259 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
4227 repo_id = Column(
4260 repo_id = Column(
4228 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
4261 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
4229 nullable=True, unique=None, default=None)
4262 nullable=True, unique=None, default=None)
4230 repo = relationship('Repository', lazy='joined')
4263 repo = relationship('Repository', lazy='joined')
4231
4264
4232 repo_group_id = Column(
4265 repo_group_id = Column(
4233 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
4266 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
4234 nullable=True, unique=None, default=None)
4267 nullable=True, unique=None, default=None)
4235 repo_group = relationship('RepoGroup', lazy='joined')
4268 repo_group = relationship('RepoGroup', lazy='joined')
4236
4269
4237 @property
4270 @property
4238 def scope(self):
4271 def scope(self):
4239 if self.repo:
4272 if self.repo:
4240 return repr(self.repo)
4273 return repr(self.repo)
4241 if self.repo_group:
4274 if self.repo_group:
4242 if self.child_repos_only:
4275 if self.child_repos_only:
4243 return repr(self.repo_group) + ' (child repos only)'
4276 return repr(self.repo_group) + ' (child repos only)'
4244 else:
4277 else:
4245 return repr(self.repo_group) + ' (recursive)'
4278 return repr(self.repo_group) + ' (recursive)'
4246 if self.child_repos_only:
4279 if self.child_repos_only:
4247 return 'root_repos'
4280 return 'root_repos'
4248 return 'global'
4281 return 'global'
4249
4282
4250 def __repr__(self):
4283 def __repr__(self):
4251 return '<Integration(%r, %r)>' % (self.integration_type, self.scope)
4284 return '<Integration(%r, %r)>' % (self.integration_type, self.scope)
4252
4285
4253
4286
4254 class RepoReviewRuleUser(Base, BaseModel):
4287 class RepoReviewRuleUser(Base, BaseModel):
4255 __tablename__ = 'repo_review_rules_users'
4288 __tablename__ = 'repo_review_rules_users'
4256 __table_args__ = (
4289 __table_args__ = (
4257 base_table_args
4290 base_table_args
4258 )
4291 )
4259
4292
4260 repo_review_rule_user_id = Column('repo_review_rule_user_id', Integer(), primary_key=True)
4293 repo_review_rule_user_id = Column('repo_review_rule_user_id', Integer(), primary_key=True)
4261 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
4294 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
4262 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False)
4295 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False)
4263 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4296 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4264 user = relationship('User')
4297 user = relationship('User')
4265
4298
4266 def rule_data(self):
4299 def rule_data(self):
4267 return {
4300 return {
4268 'mandatory': self.mandatory
4301 'mandatory': self.mandatory
4269 }
4302 }
4270
4303
4271
4304
4272 class RepoReviewRuleUserGroup(Base, BaseModel):
4305 class RepoReviewRuleUserGroup(Base, BaseModel):
4273 __tablename__ = 'repo_review_rules_users_groups'
4306 __tablename__ = 'repo_review_rules_users_groups'
4274 __table_args__ = (
4307 __table_args__ = (
4275 base_table_args
4308 base_table_args
4276 )
4309 )
4277
4310
4278 VOTE_RULE_ALL = -1
4311 VOTE_RULE_ALL = -1
4279
4312
4280 repo_review_rule_users_group_id = Column('repo_review_rule_users_group_id', Integer(), primary_key=True)
4313 repo_review_rule_users_group_id = Column('repo_review_rule_users_group_id', Integer(), primary_key=True)
4281 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
4314 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
4282 users_group_id = Column("users_group_id", Integer(),ForeignKey('users_groups.users_group_id'), nullable=False)
4315 users_group_id = Column("users_group_id", Integer(),ForeignKey('users_groups.users_group_id'), nullable=False)
4283 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4316 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4284 vote_rule = Column("vote_rule", Integer(), nullable=True, default=VOTE_RULE_ALL)
4317 vote_rule = Column("vote_rule", Integer(), nullable=True, default=VOTE_RULE_ALL)
4285 users_group = relationship('UserGroup')
4318 users_group = relationship('UserGroup')
4286
4319
4287 def rule_data(self):
4320 def rule_data(self):
4288 return {
4321 return {
4289 'mandatory': self.mandatory,
4322 'mandatory': self.mandatory,
4290 'vote_rule': self.vote_rule
4323 'vote_rule': self.vote_rule
4291 }
4324 }
4292
4325
4293 @property
4326 @property
4294 def vote_rule_label(self):
4327 def vote_rule_label(self):
4295 if not self.vote_rule or self.vote_rule == self.VOTE_RULE_ALL:
4328 if not self.vote_rule or self.vote_rule == self.VOTE_RULE_ALL:
4296 return 'all must vote'
4329 return 'all must vote'
4297 else:
4330 else:
4298 return 'min. vote {}'.format(self.vote_rule)
4331 return 'min. vote {}'.format(self.vote_rule)
4299
4332
4300
4333
4301 class RepoReviewRule(Base, BaseModel):
4334 class RepoReviewRule(Base, BaseModel):
4302 __tablename__ = 'repo_review_rules'
4335 __tablename__ = 'repo_review_rules'
4303 __table_args__ = (
4336 __table_args__ = (
4304 base_table_args
4337 base_table_args
4305 )
4338 )
4306
4339
4307 repo_review_rule_id = Column(
4340 repo_review_rule_id = Column(
4308 'repo_review_rule_id', Integer(), primary_key=True)
4341 'repo_review_rule_id', Integer(), primary_key=True)
4309 repo_id = Column(
4342 repo_id = Column(
4310 "repo_id", Integer(), ForeignKey('repositories.repo_id'))
4343 "repo_id", Integer(), ForeignKey('repositories.repo_id'))
4311 repo = relationship('Repository', backref='review_rules')
4344 repo = relationship('Repository', backref='review_rules')
4312
4345
4313 review_rule_name = Column('review_rule_name', String(255))
4346 review_rule_name = Column('review_rule_name', String(255))
4314 _branch_pattern = Column("branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4347 _branch_pattern = Column("branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4315 _target_branch_pattern = Column("target_branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4348 _target_branch_pattern = Column("target_branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4316 _file_pattern = Column("file_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4349 _file_pattern = Column("file_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4317
4350
4318 use_authors_for_review = Column("use_authors_for_review", Boolean(), nullable=False, default=False)
4351 use_authors_for_review = Column("use_authors_for_review", Boolean(), nullable=False, default=False)
4319 forbid_author_to_review = Column("forbid_author_to_review", Boolean(), nullable=False, default=False)
4352 forbid_author_to_review = Column("forbid_author_to_review", Boolean(), nullable=False, default=False)
4320 forbid_commit_author_to_review = Column("forbid_commit_author_to_review", Boolean(), nullable=False, default=False)
4353 forbid_commit_author_to_review = Column("forbid_commit_author_to_review", Boolean(), nullable=False, default=False)
4321 forbid_adding_reviewers = Column("forbid_adding_reviewers", Boolean(), nullable=False, default=False)
4354 forbid_adding_reviewers = Column("forbid_adding_reviewers", Boolean(), nullable=False, default=False)
4322
4355
4323 rule_users = relationship('RepoReviewRuleUser')
4356 rule_users = relationship('RepoReviewRuleUser')
4324 rule_user_groups = relationship('RepoReviewRuleUserGroup')
4357 rule_user_groups = relationship('RepoReviewRuleUserGroup')
4325
4358
4326 def _validate_pattern(self, value):
4359 def _validate_pattern(self, value):
4327 re.compile('^' + glob2re(value) + '$')
4360 re.compile('^' + glob2re(value) + '$')
4328
4361
4329 @hybrid_property
4362 @hybrid_property
4330 def source_branch_pattern(self):
4363 def source_branch_pattern(self):
4331 return self._branch_pattern or '*'
4364 return self._branch_pattern or '*'
4332
4365
4333 @source_branch_pattern.setter
4366 @source_branch_pattern.setter
4334 def source_branch_pattern(self, value):
4367 def source_branch_pattern(self, value):
4335 self._validate_pattern(value)
4368 self._validate_pattern(value)
4336 self._branch_pattern = value or '*'
4369 self._branch_pattern = value or '*'
4337
4370
4338 @hybrid_property
4371 @hybrid_property
4339 def target_branch_pattern(self):
4372 def target_branch_pattern(self):
4340 return self._target_branch_pattern or '*'
4373 return self._target_branch_pattern or '*'
4341
4374
4342 @target_branch_pattern.setter
4375 @target_branch_pattern.setter
4343 def target_branch_pattern(self, value):
4376 def target_branch_pattern(self, value):
4344 self._validate_pattern(value)
4377 self._validate_pattern(value)
4345 self._target_branch_pattern = value or '*'
4378 self._target_branch_pattern = value or '*'
4346
4379
4347 @hybrid_property
4380 @hybrid_property
4348 def file_pattern(self):
4381 def file_pattern(self):
4349 return self._file_pattern or '*'
4382 return self._file_pattern or '*'
4350
4383
4351 @file_pattern.setter
4384 @file_pattern.setter
4352 def file_pattern(self, value):
4385 def file_pattern(self, value):
4353 self._validate_pattern(value)
4386 self._validate_pattern(value)
4354 self._file_pattern = value or '*'
4387 self._file_pattern = value or '*'
4355
4388
4356 def matches(self, source_branch, target_branch, files_changed):
4389 def matches(self, source_branch, target_branch, files_changed):
4357 """
4390 """
4358 Check if this review rule matches a branch/files in a pull request
4391 Check if this review rule matches a branch/files in a pull request
4359
4392
4360 :param source_branch: source branch name for the commit
4393 :param source_branch: source branch name for the commit
4361 :param target_branch: target branch name for the commit
4394 :param target_branch: target branch name for the commit
4362 :param files_changed: list of file paths changed in the pull request
4395 :param files_changed: list of file paths changed in the pull request
4363 """
4396 """
4364
4397
4365 source_branch = source_branch or ''
4398 source_branch = source_branch or ''
4366 target_branch = target_branch or ''
4399 target_branch = target_branch or ''
4367 files_changed = files_changed or []
4400 files_changed = files_changed or []
4368
4401
4369 branch_matches = True
4402 branch_matches = True
4370 if source_branch or target_branch:
4403 if source_branch or target_branch:
4371 if self.source_branch_pattern == '*':
4404 if self.source_branch_pattern == '*':
4372 source_branch_match = True
4405 source_branch_match = True
4373 else:
4406 else:
4374 if self.source_branch_pattern.startswith('re:'):
4407 if self.source_branch_pattern.startswith('re:'):
4375 source_pattern = self.source_branch_pattern[3:]
4408 source_pattern = self.source_branch_pattern[3:]
4376 else:
4409 else:
4377 source_pattern = '^' + glob2re(self.source_branch_pattern) + '$'
4410 source_pattern = '^' + glob2re(self.source_branch_pattern) + '$'
4378 source_branch_regex = re.compile(source_pattern)
4411 source_branch_regex = re.compile(source_pattern)
4379 source_branch_match = bool(source_branch_regex.search(source_branch))
4412 source_branch_match = bool(source_branch_regex.search(source_branch))
4380 if self.target_branch_pattern == '*':
4413 if self.target_branch_pattern == '*':
4381 target_branch_match = True
4414 target_branch_match = True
4382 else:
4415 else:
4383 if self.target_branch_pattern.startswith('re:'):
4416 if self.target_branch_pattern.startswith('re:'):
4384 target_pattern = self.target_branch_pattern[3:]
4417 target_pattern = self.target_branch_pattern[3:]
4385 else:
4418 else:
4386 target_pattern = '^' + glob2re(self.target_branch_pattern) + '$'
4419 target_pattern = '^' + glob2re(self.target_branch_pattern) + '$'
4387 target_branch_regex = re.compile(target_pattern)
4420 target_branch_regex = re.compile(target_pattern)
4388 target_branch_match = bool(target_branch_regex.search(target_branch))
4421 target_branch_match = bool(target_branch_regex.search(target_branch))
4389
4422
4390 branch_matches = source_branch_match and target_branch_match
4423 branch_matches = source_branch_match and target_branch_match
4391
4424
4392 files_matches = True
4425 files_matches = True
4393 if self.file_pattern != '*':
4426 if self.file_pattern != '*':
4394 files_matches = False
4427 files_matches = False
4395 if self.file_pattern.startswith('re:'):
4428 if self.file_pattern.startswith('re:'):
4396 file_pattern = self.file_pattern[3:]
4429 file_pattern = self.file_pattern[3:]
4397 else:
4430 else:
4398 file_pattern = glob2re(self.file_pattern)
4431 file_pattern = glob2re(self.file_pattern)
4399 file_regex = re.compile(file_pattern)
4432 file_regex = re.compile(file_pattern)
4400 for filename in files_changed:
4433 for filename in files_changed:
4401 if file_regex.search(filename):
4434 if file_regex.search(filename):
4402 files_matches = True
4435 files_matches = True
4403 break
4436 break
4404
4437
4405 return branch_matches and files_matches
4438 return branch_matches and files_matches
4406
4439
4407 @property
4440 @property
4408 def review_users(self):
4441 def review_users(self):
4409 """ Returns the users which this rule applies to """
4442 """ Returns the users which this rule applies to """
4410
4443
4411 users = collections.OrderedDict()
4444 users = collections.OrderedDict()
4412
4445
4413 for rule_user in self.rule_users:
4446 for rule_user in self.rule_users:
4414 if rule_user.user.active:
4447 if rule_user.user.active:
4415 if rule_user.user not in users:
4448 if rule_user.user not in users:
4416 users[rule_user.user.username] = {
4449 users[rule_user.user.username] = {
4417 'user': rule_user.user,
4450 'user': rule_user.user,
4418 'source': 'user',
4451 'source': 'user',
4419 'source_data': {},
4452 'source_data': {},
4420 'data': rule_user.rule_data()
4453 'data': rule_user.rule_data()
4421 }
4454 }
4422
4455
4423 for rule_user_group in self.rule_user_groups:
4456 for rule_user_group in self.rule_user_groups:
4424 source_data = {
4457 source_data = {
4425 'user_group_id': rule_user_group.users_group.users_group_id,
4458 'user_group_id': rule_user_group.users_group.users_group_id,
4426 'name': rule_user_group.users_group.users_group_name,
4459 'name': rule_user_group.users_group.users_group_name,
4427 'members': len(rule_user_group.users_group.members)
4460 'members': len(rule_user_group.users_group.members)
4428 }
4461 }
4429 for member in rule_user_group.users_group.members:
4462 for member in rule_user_group.users_group.members:
4430 if member.user.active:
4463 if member.user.active:
4431 key = member.user.username
4464 key = member.user.username
4432 if key in users:
4465 if key in users:
4433 # skip this member as we have him already
4466 # skip this member as we have him already
4434 # this prevents from override the "first" matched
4467 # this prevents from override the "first" matched
4435 # users with duplicates in multiple groups
4468 # users with duplicates in multiple groups
4436 continue
4469 continue
4437
4470
4438 users[key] = {
4471 users[key] = {
4439 'user': member.user,
4472 'user': member.user,
4440 'source': 'user_group',
4473 'source': 'user_group',
4441 'source_data': source_data,
4474 'source_data': source_data,
4442 'data': rule_user_group.rule_data()
4475 'data': rule_user_group.rule_data()
4443 }
4476 }
4444
4477
4445 return users
4478 return users
4446
4479
4447 def user_group_vote_rule(self, user_id):
4480 def user_group_vote_rule(self, user_id):
4448
4481
4449 rules = []
4482 rules = []
4450 if not self.rule_user_groups:
4483 if not self.rule_user_groups:
4451 return rules
4484 return rules
4452
4485
4453 for user_group in self.rule_user_groups:
4486 for user_group in self.rule_user_groups:
4454 user_group_members = [x.user_id for x in user_group.users_group.members]
4487 user_group_members = [x.user_id for x in user_group.users_group.members]
4455 if user_id in user_group_members:
4488 if user_id in user_group_members:
4456 rules.append(user_group)
4489 rules.append(user_group)
4457 return rules
4490 return rules
4458
4491
4459 def __repr__(self):
4492 def __repr__(self):
4460 return '<RepoReviewerRule(id=%r, repo=%r)>' % (
4493 return '<RepoReviewerRule(id=%r, repo=%r)>' % (
4461 self.repo_review_rule_id, self.repo)
4494 self.repo_review_rule_id, self.repo)
4462
4495
4463
4496
4464 class ScheduleEntry(Base, BaseModel):
4497 class ScheduleEntry(Base, BaseModel):
4465 __tablename__ = 'schedule_entries'
4498 __tablename__ = 'schedule_entries'
4466 __table_args__ = (
4499 __table_args__ = (
4467 UniqueConstraint('schedule_name', name='s_schedule_name_idx'),
4500 UniqueConstraint('schedule_name', name='s_schedule_name_idx'),
4468 UniqueConstraint('task_uid', name='s_task_uid_idx'),
4501 UniqueConstraint('task_uid', name='s_task_uid_idx'),
4469 base_table_args,
4502 base_table_args,
4470 )
4503 )
4471
4504
4472 schedule_types = ['crontab', 'timedelta', 'integer']
4505 schedule_types = ['crontab', 'timedelta', 'integer']
4473 schedule_entry_id = Column('schedule_entry_id', Integer(), primary_key=True)
4506 schedule_entry_id = Column('schedule_entry_id', Integer(), primary_key=True)
4474
4507
4475 schedule_name = Column("schedule_name", String(255), nullable=False, unique=None, default=None)
4508 schedule_name = Column("schedule_name", String(255), nullable=False, unique=None, default=None)
4476 schedule_description = Column("schedule_description", String(10000), nullable=True, unique=None, default=None)
4509 schedule_description = Column("schedule_description", String(10000), nullable=True, unique=None, default=None)
4477 schedule_enabled = Column("schedule_enabled", Boolean(), nullable=False, unique=None, default=True)
4510 schedule_enabled = Column("schedule_enabled", Boolean(), nullable=False, unique=None, default=True)
4478
4511
4479 _schedule_type = Column("schedule_type", String(255), nullable=False, unique=None, default=None)
4512 _schedule_type = Column("schedule_type", String(255), nullable=False, unique=None, default=None)
4480 schedule_definition = Column('schedule_definition_json', MutationObj.as_mutable(JsonType(default=lambda: "", dialect_map=dict(mysql=LONGTEXT()))))
4513 schedule_definition = Column('schedule_definition_json', MutationObj.as_mutable(JsonType(default=lambda: "", dialect_map=dict(mysql=LONGTEXT()))))
4481
4514
4482 schedule_last_run = Column('schedule_last_run', DateTime(timezone=False), nullable=True, unique=None, default=None)
4515 schedule_last_run = Column('schedule_last_run', DateTime(timezone=False), nullable=True, unique=None, default=None)
4483 schedule_total_run_count = Column('schedule_total_run_count', Integer(), nullable=True, unique=None, default=0)
4516 schedule_total_run_count = Column('schedule_total_run_count', Integer(), nullable=True, unique=None, default=0)
4484
4517
4485 # task
4518 # task
4486 task_uid = Column("task_uid", String(255), nullable=False, unique=None, default=None)
4519 task_uid = Column("task_uid", String(255), nullable=False, unique=None, default=None)
4487 task_dot_notation = Column("task_dot_notation", String(4096), nullable=False, unique=None, default=None)
4520 task_dot_notation = Column("task_dot_notation", String(4096), nullable=False, unique=None, default=None)
4488 task_args = Column('task_args_json', MutationObj.as_mutable(JsonType(default=list, dialect_map=dict(mysql=LONGTEXT()))))
4521 task_args = Column('task_args_json', MutationObj.as_mutable(JsonType(default=list, dialect_map=dict(mysql=LONGTEXT()))))
4489 task_kwargs = Column('task_kwargs_json', MutationObj.as_mutable(JsonType(default=dict, dialect_map=dict(mysql=LONGTEXT()))))
4522 task_kwargs = Column('task_kwargs_json', MutationObj.as_mutable(JsonType(default=dict, dialect_map=dict(mysql=LONGTEXT()))))
4490
4523
4491 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4524 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4492 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=None)
4525 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=None)
4493
4526
4494 @hybrid_property
4527 @hybrid_property
4495 def schedule_type(self):
4528 def schedule_type(self):
4496 return self._schedule_type
4529 return self._schedule_type
4497
4530
4498 @schedule_type.setter
4531 @schedule_type.setter
4499 def schedule_type(self, val):
4532 def schedule_type(self, val):
4500 if val not in self.schedule_types:
4533 if val not in self.schedule_types:
4501 raise ValueError('Value must be on of `{}` and got `{}`'.format(
4534 raise ValueError('Value must be on of `{}` and got `{}`'.format(
4502 val, self.schedule_type))
4535 val, self.schedule_type))
4503
4536
4504 self._schedule_type = val
4537 self._schedule_type = val
4505
4538
4506 @classmethod
4539 @classmethod
4507 def get_uid(cls, obj):
4540 def get_uid(cls, obj):
4508 args = obj.task_args
4541 args = obj.task_args
4509 kwargs = obj.task_kwargs
4542 kwargs = obj.task_kwargs
4510 if isinstance(args, JsonRaw):
4543 if isinstance(args, JsonRaw):
4511 try:
4544 try:
4512 args = json.loads(args)
4545 args = json.loads(args)
4513 except ValueError:
4546 except ValueError:
4514 args = tuple()
4547 args = tuple()
4515
4548
4516 if isinstance(kwargs, JsonRaw):
4549 if isinstance(kwargs, JsonRaw):
4517 try:
4550 try:
4518 kwargs = json.loads(kwargs)
4551 kwargs = json.loads(kwargs)
4519 except ValueError:
4552 except ValueError:
4520 kwargs = dict()
4553 kwargs = dict()
4521
4554
4522 dot_notation = obj.task_dot_notation
4555 dot_notation = obj.task_dot_notation
4523 val = '.'.join(map(safe_str, [
4556 val = '.'.join(map(safe_str, [
4524 sorted(dot_notation), args, sorted(kwargs.items())]))
4557 sorted(dot_notation), args, sorted(kwargs.items())]))
4525 return hashlib.sha1(val).hexdigest()
4558 return hashlib.sha1(val).hexdigest()
4526
4559
4527 @classmethod
4560 @classmethod
4528 def get_by_schedule_name(cls, schedule_name):
4561 def get_by_schedule_name(cls, schedule_name):
4529 return cls.query().filter(cls.schedule_name == schedule_name).scalar()
4562 return cls.query().filter(cls.schedule_name == schedule_name).scalar()
4530
4563
4531 @classmethod
4564 @classmethod
4532 def get_by_schedule_id(cls, schedule_id):
4565 def get_by_schedule_id(cls, schedule_id):
4533 return cls.query().filter(cls.schedule_entry_id == schedule_id).scalar()
4566 return cls.query().filter(cls.schedule_entry_id == schedule_id).scalar()
4534
4567
4535 @property
4568 @property
4536 def task(self):
4569 def task(self):
4537 return self.task_dot_notation
4570 return self.task_dot_notation
4538
4571
4539 @property
4572 @property
4540 def schedule(self):
4573 def schedule(self):
4541 from rhodecode.lib.celerylib.utils import raw_2_schedule
4574 from rhodecode.lib.celerylib.utils import raw_2_schedule
4542 schedule = raw_2_schedule(self.schedule_definition, self.schedule_type)
4575 schedule = raw_2_schedule(self.schedule_definition, self.schedule_type)
4543 return schedule
4576 return schedule
4544
4577
4545 @property
4578 @property
4546 def args(self):
4579 def args(self):
4547 try:
4580 try:
4548 return list(self.task_args or [])
4581 return list(self.task_args or [])
4549 except ValueError:
4582 except ValueError:
4550 return list()
4583 return list()
4551
4584
4552 @property
4585 @property
4553 def kwargs(self):
4586 def kwargs(self):
4554 try:
4587 try:
4555 return dict(self.task_kwargs or {})
4588 return dict(self.task_kwargs or {})
4556 except ValueError:
4589 except ValueError:
4557 return dict()
4590 return dict()
4558
4591
4559 def _as_raw(self, val):
4592 def _as_raw(self, val):
4560 if hasattr(val, 'de_coerce'):
4593 if hasattr(val, 'de_coerce'):
4561 val = val.de_coerce()
4594 val = val.de_coerce()
4562 if val:
4595 if val:
4563 val = json.dumps(val)
4596 val = json.dumps(val)
4564
4597
4565 return val
4598 return val
4566
4599
4567 @property
4600 @property
4568 def schedule_definition_raw(self):
4601 def schedule_definition_raw(self):
4569 return self._as_raw(self.schedule_definition)
4602 return self._as_raw(self.schedule_definition)
4570
4603
4571 @property
4604 @property
4572 def args_raw(self):
4605 def args_raw(self):
4573 return self._as_raw(self.task_args)
4606 return self._as_raw(self.task_args)
4574
4607
4575 @property
4608 @property
4576 def kwargs_raw(self):
4609 def kwargs_raw(self):
4577 return self._as_raw(self.task_kwargs)
4610 return self._as_raw(self.task_kwargs)
4578
4611
4579 def __repr__(self):
4612 def __repr__(self):
4580 return '<DB:ScheduleEntry({}:{})>'.format(
4613 return '<DB:ScheduleEntry({}:{})>'.format(
4581 self.schedule_entry_id, self.schedule_name)
4614 self.schedule_entry_id, self.schedule_name)
4582
4615
4583
4616
4584 @event.listens_for(ScheduleEntry, 'before_update')
4617 @event.listens_for(ScheduleEntry, 'before_update')
4585 def update_task_uid(mapper, connection, target):
4618 def update_task_uid(mapper, connection, target):
4586 target.task_uid = ScheduleEntry.get_uid(target)
4619 target.task_uid = ScheduleEntry.get_uid(target)
4587
4620
4588
4621
4589 @event.listens_for(ScheduleEntry, 'before_insert')
4622 @event.listens_for(ScheduleEntry, 'before_insert')
4590 def set_task_uid(mapper, connection, target):
4623 def set_task_uid(mapper, connection, target):
4591 target.task_uid = ScheduleEntry.get_uid(target)
4624 target.task_uid = ScheduleEntry.get_uid(target)
4592
4625
4593
4626
4594 class _BaseBranchPerms(BaseModel):
4627 class _BaseBranchPerms(BaseModel):
4595 @classmethod
4628 @classmethod
4596 def compute_hash(cls, value):
4629 def compute_hash(cls, value):
4597 return sha1_safe(value)
4630 return sha1_safe(value)
4598
4631
4599 @hybrid_property
4632 @hybrid_property
4600 def branch_pattern(self):
4633 def branch_pattern(self):
4601 return self._branch_pattern or '*'
4634 return self._branch_pattern or '*'
4602
4635
4603 @hybrid_property
4636 @hybrid_property
4604 def branch_hash(self):
4637 def branch_hash(self):
4605 return self._branch_hash
4638 return self._branch_hash
4606
4639
4607 def _validate_glob(self, value):
4640 def _validate_glob(self, value):
4608 re.compile('^' + glob2re(value) + '$')
4641 re.compile('^' + glob2re(value) + '$')
4609
4642
4610 @branch_pattern.setter
4643 @branch_pattern.setter
4611 def branch_pattern(self, value):
4644 def branch_pattern(self, value):
4612 self._validate_glob(value)
4645 self._validate_glob(value)
4613 self._branch_pattern = value or '*'
4646 self._branch_pattern = value or '*'
4614 # set the Hash when setting the branch pattern
4647 # set the Hash when setting the branch pattern
4615 self._branch_hash = self.compute_hash(self._branch_pattern)
4648 self._branch_hash = self.compute_hash(self._branch_pattern)
4616
4649
4617 def matches(self, branch):
4650 def matches(self, branch):
4618 """
4651 """
4619 Check if this the branch matches entry
4652 Check if this the branch matches entry
4620
4653
4621 :param branch: branch name for the commit
4654 :param branch: branch name for the commit
4622 """
4655 """
4623
4656
4624 branch = branch or ''
4657 branch = branch or ''
4625
4658
4626 branch_matches = True
4659 branch_matches = True
4627 if branch:
4660 if branch:
4628 branch_regex = re.compile('^' + glob2re(self.branch_pattern) + '$')
4661 branch_regex = re.compile('^' + glob2re(self.branch_pattern) + '$')
4629 branch_matches = bool(branch_regex.search(branch))
4662 branch_matches = bool(branch_regex.search(branch))
4630
4663
4631 return branch_matches
4664 return branch_matches
4632
4665
4633
4666
4634 class UserToRepoBranchPermission(Base, _BaseBranchPerms):
4667 class UserToRepoBranchPermission(Base, _BaseBranchPerms):
4635 __tablename__ = 'user_to_repo_branch_permissions'
4668 __tablename__ = 'user_to_repo_branch_permissions'
4636 __table_args__ = (
4669 __table_args__ = (
4637 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4670 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4638 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
4671 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
4639 )
4672 )
4640
4673
4641 branch_rule_id = Column('branch_rule_id', Integer(), primary_key=True)
4674 branch_rule_id = Column('branch_rule_id', Integer(), primary_key=True)
4642
4675
4643 repository_id = Column('repository_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
4676 repository_id = Column('repository_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
4644 repo = relationship('Repository', backref='user_branch_perms')
4677 repo = relationship('Repository', backref='user_branch_perms')
4645
4678
4646 permission_id = Column('permission_id', Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
4679 permission_id = Column('permission_id', Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
4647 permission = relationship('Permission')
4680 permission = relationship('Permission')
4648
4681
4649 rule_to_perm_id = Column('rule_to_perm_id', Integer(), ForeignKey('repo_to_perm.repo_to_perm_id'), nullable=False, unique=None, default=None)
4682 rule_to_perm_id = Column('rule_to_perm_id', Integer(), ForeignKey('repo_to_perm.repo_to_perm_id'), nullable=False, unique=None, default=None)
4650 user_repo_to_perm = relationship('UserRepoToPerm')
4683 user_repo_to_perm = relationship('UserRepoToPerm')
4651
4684
4652 rule_order = Column('rule_order', Integer(), nullable=False)
4685 rule_order = Column('rule_order', Integer(), nullable=False)
4653 _branch_pattern = Column('branch_pattern', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), default=u'*') # glob
4686 _branch_pattern = Column('branch_pattern', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), default=u'*') # glob
4654 _branch_hash = Column('branch_hash', UnicodeText().with_variant(UnicodeText(2048), 'mysql'))
4687 _branch_hash = Column('branch_hash', UnicodeText().with_variant(UnicodeText(2048), 'mysql'))
4655
4688
4656 def __unicode__(self):
4689 def __unicode__(self):
4657 return u'<UserBranchPermission(%s => %r)>' % (
4690 return u'<UserBranchPermission(%s => %r)>' % (
4658 self.user_repo_to_perm, self.branch_pattern)
4691 self.user_repo_to_perm, self.branch_pattern)
4659
4692
4660
4693
4661 class UserGroupToRepoBranchPermission(Base, _BaseBranchPerms):
4694 class UserGroupToRepoBranchPermission(Base, _BaseBranchPerms):
4662 __tablename__ = 'user_group_to_repo_branch_permissions'
4695 __tablename__ = 'user_group_to_repo_branch_permissions'
4663 __table_args__ = (
4696 __table_args__ = (
4664 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4697 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4665 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
4698 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
4666 )
4699 )
4667
4700
4668 branch_rule_id = Column('branch_rule_id', Integer(), primary_key=True)
4701 branch_rule_id = Column('branch_rule_id', Integer(), primary_key=True)
4669
4702
4670 repository_id = Column('repository_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
4703 repository_id = Column('repository_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
4671 repo = relationship('Repository', backref='user_group_branch_perms')
4704 repo = relationship('Repository', backref='user_group_branch_perms')
4672
4705
4673 permission_id = Column('permission_id', Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
4706 permission_id = Column('permission_id', Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
4674 permission = relationship('Permission')
4707 permission = relationship('Permission')
4675
4708
4676 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)
4709 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)
4677 user_group_repo_to_perm = relationship('UserGroupRepoToPerm')
4710 user_group_repo_to_perm = relationship('UserGroupRepoToPerm')
4678
4711
4679 rule_order = Column('rule_order', Integer(), nullable=False)
4712 rule_order = Column('rule_order', Integer(), nullable=False)
4680 _branch_pattern = Column('branch_pattern', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), default=u'*') # glob
4713 _branch_pattern = Column('branch_pattern', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), default=u'*') # glob
4681 _branch_hash = Column('branch_hash', UnicodeText().with_variant(UnicodeText(2048), 'mysql'))
4714 _branch_hash = Column('branch_hash', UnicodeText().with_variant(UnicodeText(2048), 'mysql'))
4682
4715
4683 def __unicode__(self):
4716 def __unicode__(self):
4684 return u'<UserBranchPermission(%s => %r)>' % (
4717 return u'<UserBranchPermission(%s => %r)>' % (
4685 self.user_group_repo_to_perm, self.branch_pattern)
4718 self.user_group_repo_to_perm, self.branch_pattern)
4686
4719
4687
4720
4688 class DbMigrateVersion(Base, BaseModel):
4721 class DbMigrateVersion(Base, BaseModel):
4689 __tablename__ = 'db_migrate_version'
4722 __tablename__ = 'db_migrate_version'
4690 __table_args__ = (
4723 __table_args__ = (
4691 base_table_args,
4724 base_table_args,
4692 )
4725 )
4693
4726
4694 repository_id = Column('repository_id', String(250), primary_key=True)
4727 repository_id = Column('repository_id', String(250), primary_key=True)
4695 repository_path = Column('repository_path', Text)
4728 repository_path = Column('repository_path', Text)
4696 version = Column('version', Integer)
4729 version = Column('version', Integer)
4697
4730
4698 @classmethod
4731 @classmethod
4699 def set_version(cls, version):
4732 def set_version(cls, version):
4700 """
4733 """
4701 Helper for forcing a different version, usually for debugging purposes via ishell.
4734 Helper for forcing a different version, usually for debugging purposes via ishell.
4702 """
4735 """
4703 ver = DbMigrateVersion.query().first()
4736 ver = DbMigrateVersion.query().first()
4704 ver.version = version
4737 ver.version = version
4705 Session().commit()
4738 Session().commit()
4706
4739
4707
4740
4708 class DbSession(Base, BaseModel):
4741 class DbSession(Base, BaseModel):
4709 __tablename__ = 'db_session'
4742 __tablename__ = 'db_session'
4710 __table_args__ = (
4743 __table_args__ = (
4711 base_table_args,
4744 base_table_args,
4712 )
4745 )
4713
4746
4714 def __repr__(self):
4747 def __repr__(self):
4715 return '<DB:DbSession({})>'.format(self.id)
4748 return '<DB:DbSession({})>'.format(self.id)
4716
4749
4717 id = Column('id', Integer())
4750 id = Column('id', Integer())
4718 namespace = Column('namespace', String(255), primary_key=True)
4751 namespace = Column('namespace', String(255), primary_key=True)
4719 accessed = Column('accessed', DateTime, nullable=False)
4752 accessed = Column('accessed', DateTime, nullable=False)
4720 created = Column('created', DateTime, nullable=False)
4753 created = Column('created', DateTime, nullable=False)
4721 data = Column('data', PickleType, nullable=False)
4754 data = Column('data', PickleType, nullable=False)
General Comments 0
You need to be logged in to leave comments. Login now