##// 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 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2016-2018 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 21 import logging
22 22 import formencode
23 23 import formencode.htmlfill
24 24
25 25 from pyramid.httpexceptions import HTTPFound, HTTPForbidden
26 26 from pyramid.view import view_config
27 27 from pyramid.renderers import render
28 28 from pyramid.response import Response
29 29
30 30 from rhodecode import events
31 31 from rhodecode.apps._base import BaseAppView, DataGridAppView
32 32
33 33 from rhodecode.lib.ext_json import json
34 34 from rhodecode.lib.auth import (
35 35 LoginRequired, CSRFRequired, NotAnonymous,
36 36 HasPermissionAny, HasRepoGroupPermissionAny)
37 37 from rhodecode.lib import helpers as h, audit_logger
38 38 from rhodecode.lib.utils2 import safe_int, safe_unicode
39 39 from rhodecode.model.forms import RepoGroupForm
40 40 from rhodecode.model.repo_group import RepoGroupModel
41 41 from rhodecode.model.scm import RepoGroupList
42 42 from rhodecode.model.db import Session, RepoGroup
43 43
44 44 log = logging.getLogger(__name__)
45 45
46 46
47 47 class AdminRepoGroupsView(BaseAppView, DataGridAppView):
48 48
49 49 def load_default_context(self):
50 50 c = self._get_local_tmpl_context()
51 51
52 52 return c
53 53
54 54 def _load_form_data(self, c):
55 55 allow_empty_group = False
56 56
57 57 if self._can_create_repo_group():
58 58 # we're global admin, we're ok and we can create TOP level groups
59 59 allow_empty_group = True
60 60
61 61 # override the choices for this form, we need to filter choices
62 62 # and display only those we have ADMIN right
63 63 groups_with_admin_rights = RepoGroupList(
64 64 RepoGroup.query().all(),
65 65 perm_set=['group.admin'])
66 66 c.repo_groups = RepoGroup.groups_choices(
67 67 groups=groups_with_admin_rights,
68 68 show_empty_group=allow_empty_group)
69 69
70 70 def _can_create_repo_group(self, parent_group_id=None):
71 71 is_admin = HasPermissionAny('hg.admin')('group create controller')
72 72 create_repo_group = HasPermissionAny(
73 73 'hg.repogroup.create.true')('group create controller')
74 74 if is_admin or (create_repo_group and not parent_group_id):
75 75 # we're global admin, or we have global repo group create
76 76 # permission
77 77 # we're ok and we can create TOP level groups
78 78 return True
79 79 elif parent_group_id:
80 80 # we check the permission if we can write to parent group
81 81 group = RepoGroup.get(parent_group_id)
82 82 group_name = group.group_name if group else None
83 83 if HasRepoGroupPermissionAny('group.admin')(
84 84 group_name, 'check if user is an admin of group'):
85 85 # we're an admin of passed in group, we're ok.
86 86 return True
87 87 else:
88 88 return False
89 89 return False
90 90
91 91 @LoginRequired()
92 92 @NotAnonymous()
93 93 # perms check inside
94 94 @view_config(
95 95 route_name='repo_groups', request_method='GET',
96 96 renderer='rhodecode:templates/admin/repo_groups/repo_groups.mako')
97 97 def repo_group_list(self):
98 98 c = self.load_default_context()
99 99
100 100 repo_group_list = RepoGroup.get_all_repo_groups()
101 101 repo_group_list_acl = RepoGroupList(
102 102 repo_group_list, perm_set=['group.admin'])
103 103 repo_group_data = RepoGroupModel().get_repo_groups_as_dict(
104 104 repo_group_list=repo_group_list_acl, admin=True)
105 105 c.data = json.dumps(repo_group_data)
106 106 return self._get_template_context(c)
107 107
108 108 @LoginRequired()
109 109 @NotAnonymous()
110 110 # perm checks inside
111 111 @view_config(
112 112 route_name='repo_group_new', request_method='GET',
113 113 renderer='rhodecode:templates/admin/repo_groups/repo_group_add.mako')
114 114 def repo_group_new(self):
115 115 c = self.load_default_context()
116 116
117 117 # perm check for admin, create_group perm or admin of parent_group
118 118 parent_group_id = safe_int(self.request.GET.get('parent_group'))
119 119 if not self._can_create_repo_group(parent_group_id):
120 120 raise HTTPForbidden()
121 121
122 122 self._load_form_data(c)
123 123
124 124 defaults = {} # Future proof for default of repo group
125 125 data = render(
126 126 'rhodecode:templates/admin/repo_groups/repo_group_add.mako',
127 127 self._get_template_context(c), self.request)
128 128 html = formencode.htmlfill.render(
129 129 data,
130 130 defaults=defaults,
131 131 encoding="UTF-8",
132 132 force_defaults=False
133 133 )
134 134 return Response(html)
135 135
136 136 @LoginRequired()
137 137 @NotAnonymous()
138 138 @CSRFRequired()
139 139 # perm checks inside
140 140 @view_config(
141 141 route_name='repo_group_create', request_method='POST',
142 142 renderer='rhodecode:templates/admin/repo_groups/repo_group_add.mako')
143 143 def repo_group_create(self):
144 144 c = self.load_default_context()
145 145 _ = self.request.translate
146 146
147 147 parent_group_id = safe_int(self.request.POST.get('group_parent_id'))
148 148 can_create = self._can_create_repo_group(parent_group_id)
149 149
150 150 self._load_form_data(c)
151 151 # permissions for can create group based on parent_id are checked
152 152 # here in the Form
153 153 available_groups = map(lambda k: safe_unicode(k[0]), c.repo_groups)
154 154 repo_group_form = RepoGroupForm(
155 155 self.request.translate, available_groups=available_groups,
156 156 can_create_in_root=can_create)()
157 157
158 158 repo_group_name = self.request.POST.get('group_name')
159 159 try:
160 160 owner = self._rhodecode_user
161 161 form_result = repo_group_form.to_python(dict(self.request.POST))
162 copy_permissions = form_result.get('group_copy_permissions')
162 163 repo_group = RepoGroupModel().create(
163 164 group_name=form_result['group_name_full'],
164 165 group_description=form_result['group_description'],
165 166 owner=owner.user_id,
166 167 copy_permissions=form_result['group_copy_permissions']
167 168 )
168 169 Session().flush()
169 170
170 171 repo_group_data = repo_group.get_api_data()
171 172 audit_logger.store_web(
172 173 'repo_group.create', action_data={'data': repo_group_data},
173 174 user=self._rhodecode_user)
174 175
175 176 Session().commit()
176 177
177 178 _new_group_name = form_result['group_name_full']
178 179
179 180 repo_group_url = h.link_to(
180 181 _new_group_name,
181 182 h.route_path('repo_group_home', repo_group_name=_new_group_name))
182 183 h.flash(h.literal(_('Created repository group %s')
183 184 % repo_group_url), category='success')
184 185
185 186 except formencode.Invalid as errors:
186 187 data = render(
187 188 'rhodecode:templates/admin/repo_groups/repo_group_add.mako',
188 189 self._get_template_context(c), self.request)
189 190 html = formencode.htmlfill.render(
190 191 data,
191 192 defaults=errors.value,
192 193 errors=errors.error_dict or {},
193 194 prefix_error=False,
194 195 encoding="UTF-8",
195 196 force_defaults=False
196 197 )
197 198 return Response(html)
198 199 except Exception:
199 200 log.exception("Exception during creation of repository group")
200 201 h.flash(_('Error occurred during creation of repository group %s')
201 202 % repo_group_name, category='error')
202 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 213 raise HTTPFound(
206 214 h.route_path('repo_group_home',
207 215 repo_group_name=form_result['group_name_full']))
@@ -1,184 +1,194 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2016-2018 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 21 import logging
22 22 import formencode
23 23 import formencode.htmlfill
24 24
25 25 from pyramid.httpexceptions import HTTPFound, HTTPForbidden
26 26 from pyramid.view import view_config
27 27 from pyramid.renderers import render
28 28 from pyramid.response import Response
29 29
30 30 from rhodecode import events
31 31 from rhodecode.apps._base import BaseAppView, DataGridAppView
32 32 from rhodecode.lib.celerylib.utils import get_task_id
33 33
34 34 from rhodecode.lib.ext_json import json
35 35 from rhodecode.lib.auth import (
36 36 LoginRequired, CSRFRequired, NotAnonymous,
37 37 HasPermissionAny, HasRepoGroupPermissionAny)
38 38 from rhodecode.lib import helpers as h
39 39 from rhodecode.lib.utils import repo_name_slug
40 40 from rhodecode.lib.utils2 import safe_int, safe_unicode
41 41 from rhodecode.model.forms import RepoForm
42 42 from rhodecode.model.repo import RepoModel
43 43 from rhodecode.model.scm import RepoList, RepoGroupList, ScmModel
44 44 from rhodecode.model.settings import SettingsModel
45 45 from rhodecode.model.db import Repository, RepoGroup
46 46
47 47 log = logging.getLogger(__name__)
48 48
49 49
50 50 class AdminReposView(BaseAppView, DataGridAppView):
51 51
52 52 def load_default_context(self):
53 53 c = self._get_local_tmpl_context()
54 54
55 55 return c
56 56
57 57 def _load_form_data(self, c):
58 58 acl_groups = RepoGroupList(RepoGroup.query().all(),
59 59 perm_set=['group.write', 'group.admin'])
60 60 c.repo_groups = RepoGroup.groups_choices(groups=acl_groups)
61 61 c.repo_groups_choices = map(lambda k: safe_unicode(k[0]), c.repo_groups)
62 62 c.landing_revs_choices, c.landing_revs = \
63 63 ScmModel().get_repo_landing_revs(self.request.translate)
64 64 c.personal_repo_group = self._rhodecode_user.personal_repo_group
65 65
66 66 @LoginRequired()
67 67 @NotAnonymous()
68 68 # perms check inside
69 69 @view_config(
70 70 route_name='repos', request_method='GET',
71 71 renderer='rhodecode:templates/admin/repos/repos.mako')
72 72 def repository_list(self):
73 73 c = self.load_default_context()
74 74
75 75 repo_list = Repository.get_all_repos()
76 76 c.repo_list = RepoList(repo_list, perm_set=['repository.admin'])
77 77 repos_data = RepoModel().get_repos_as_dict(
78 78 repo_list=c.repo_list, admin=True, super_user_actions=True)
79 79 # json used to render the grid
80 80 c.data = json.dumps(repos_data)
81 81
82 82 return self._get_template_context(c)
83 83
84 84 @LoginRequired()
85 85 @NotAnonymous()
86 86 # perms check inside
87 87 @view_config(
88 88 route_name='repo_new', request_method='GET',
89 89 renderer='rhodecode:templates/admin/repos/repo_add.mako')
90 90 def repository_new(self):
91 91 c = self.load_default_context()
92 92
93 93 new_repo = self.request.GET.get('repo', '')
94 94 parent_group = safe_int(self.request.GET.get('parent_group'))
95 95 _gr = RepoGroup.get(parent_group)
96 96
97 97 if not HasPermissionAny('hg.admin', 'hg.create.repository')():
98 98 # you're not super admin nor have global create permissions,
99 99 # but maybe you have at least write permission to a parent group ?
100 100
101 101 gr_name = _gr.group_name if _gr else None
102 102 # create repositories with write permission on group is set to true
103 103 create_on_write = HasPermissionAny('hg.create.write_on_repogroup.true')()
104 104 group_admin = HasRepoGroupPermissionAny('group.admin')(group_name=gr_name)
105 105 group_write = HasRepoGroupPermissionAny('group.write')(group_name=gr_name)
106 106 if not (group_admin or (group_write and create_on_write)):
107 107 raise HTTPForbidden()
108 108
109 109 self._load_form_data(c)
110 110 c.new_repo = repo_name_slug(new_repo)
111 111
112 112 # apply the defaults from defaults page
113 113 defaults = SettingsModel().get_default_repo_settings(strip_prefix=True)
114 114 # set checkbox to autochecked
115 115 defaults['repo_copy_permissions'] = True
116 116
117 117 parent_group_choice = '-1'
118 118 if not self._rhodecode_user.is_admin and self._rhodecode_user.personal_repo_group:
119 119 parent_group_choice = self._rhodecode_user.personal_repo_group
120 120
121 121 if parent_group and _gr:
122 122 if parent_group in [x[0] for x in c.repo_groups]:
123 123 parent_group_choice = safe_unicode(parent_group)
124 124
125 125 defaults.update({'repo_group': parent_group_choice})
126 126
127 127 data = render('rhodecode:templates/admin/repos/repo_add.mako',
128 128 self._get_template_context(c), self.request)
129 129 html = formencode.htmlfill.render(
130 130 data,
131 131 defaults=defaults,
132 132 encoding="UTF-8",
133 133 force_defaults=False
134 134 )
135 135 return Response(html)
136 136
137 137 @LoginRequired()
138 138 @NotAnonymous()
139 139 @CSRFRequired()
140 140 # perms check inside
141 141 @view_config(
142 142 route_name='repo_create', request_method='POST',
143 143 renderer='rhodecode:templates/admin/repos/repos.mako')
144 144 def repository_create(self):
145 145 c = self.load_default_context()
146 146
147 147 form_result = {}
148 148 self._load_form_data(c)
149 task_id = None
149
150 150 try:
151 151 # CanWriteToGroup validators checks permissions of this POST
152 152 form = RepoForm(
153 153 self.request.translate, repo_groups=c.repo_groups_choices,
154 154 landing_revs=c.landing_revs_choices)()
155 155 form_result = form.to_python(dict(self.request.POST))
156
156 copy_permissions = form_result.get('repo_copy_permissions')
157 157 # create is done sometimes async on celery, db transaction
158 158 # management is handled there.
159 159 task = RepoModel().create(form_result, self._rhodecode_user.user_id)
160 160 task_id = get_task_id(task)
161 161 except formencode.Invalid as errors:
162 162 data = render('rhodecode:templates/admin/repos/repo_add.mako',
163 163 self._get_template_context(c), self.request)
164 164 html = formencode.htmlfill.render(
165 165 data,
166 166 defaults=errors.value,
167 167 errors=errors.error_dict or {},
168 168 prefix_error=False,
169 169 encoding="UTF-8",
170 170 force_defaults=False
171 171 )
172 172 return Response(html)
173 173
174 174 except Exception as e:
175 175 msg = self._log_creation_exception(e, form_result.get('repo_name'))
176 176 h.flash(msg, category='error')
177 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 192 raise HTTPFound(
182 h.route_path('repo_creating',
183 repo_name=form_result['repo_name_full'],
193 h.route_path('repo_creating', repo_name=repo_name,
184 194 _query=dict(task_id=task_id)))
@@ -1,1242 +1,1247 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2016-2018 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 21 import logging
22 22 import datetime
23 23 import formencode
24 24 import formencode.htmlfill
25 25
26 26 from pyramid.httpexceptions import HTTPFound
27 27 from pyramid.view import view_config
28 28 from pyramid.renderers import render
29 29 from pyramid.response import Response
30 30
31 from rhodecode import events
31 32 from rhodecode.apps._base import BaseAppView, DataGridAppView, UserAppView
32 33 from rhodecode.apps.ssh_support import SshKeyFileChangeEvent
33 34 from rhodecode.authentication.plugins import auth_rhodecode
34 35 from rhodecode.events import trigger
35 36 from rhodecode.model.db import true
36 37
37 38 from rhodecode.lib import audit_logger, rc_cache
38 39 from rhodecode.lib.exceptions import (
39 40 UserCreationError, UserOwnsReposException, UserOwnsRepoGroupsException,
40 41 UserOwnsUserGroupsException, DefaultUserException)
41 42 from rhodecode.lib.ext_json import json
42 43 from rhodecode.lib.auth import (
43 44 LoginRequired, HasPermissionAllDecorator, CSRFRequired)
44 45 from rhodecode.lib import helpers as h
45 46 from rhodecode.lib.utils2 import safe_int, safe_unicode, AttributeDict
46 47 from rhodecode.model.auth_token import AuthTokenModel
47 48 from rhodecode.model.forms import (
48 49 UserForm, UserIndividualPermissionsForm, UserPermissionsForm,
49 50 UserExtraEmailForm, UserExtraIpForm)
50 51 from rhodecode.model.permission import PermissionModel
51 52 from rhodecode.model.repo_group import RepoGroupModel
52 53 from rhodecode.model.ssh_key import SshKeyModel
53 54 from rhodecode.model.user import UserModel
54 55 from rhodecode.model.user_group import UserGroupModel
55 56 from rhodecode.model.db import (
56 57 or_, coalesce,IntegrityError, User, UserGroup, UserIpMap, UserEmailMap,
57 58 UserApiKeys, UserSshKeys, RepoGroup)
58 59 from rhodecode.model.meta import Session
59 60
60 61 log = logging.getLogger(__name__)
61 62
62 63
63 64 class AdminUsersView(BaseAppView, DataGridAppView):
64 65
65 66 def load_default_context(self):
66 67 c = self._get_local_tmpl_context()
67 68 return c
68 69
69 70 @LoginRequired()
70 71 @HasPermissionAllDecorator('hg.admin')
71 72 @view_config(
72 73 route_name='users', request_method='GET',
73 74 renderer='rhodecode:templates/admin/users/users.mako')
74 75 def users_list(self):
75 76 c = self.load_default_context()
76 77 return self._get_template_context(c)
77 78
78 79 @LoginRequired()
79 80 @HasPermissionAllDecorator('hg.admin')
80 81 @view_config(
81 82 # renderer defined below
82 83 route_name='users_data', request_method='GET',
83 84 renderer='json_ext', xhr=True)
84 85 def users_list_data(self):
85 86 self.load_default_context()
86 87 column_map = {
87 88 'first_name': 'name',
88 89 'last_name': 'lastname',
89 90 }
90 91 draw, start, limit = self._extract_chunk(self.request)
91 92 search_q, order_by, order_dir = self._extract_ordering(
92 93 self.request, column_map=column_map)
93 94 _render = self.request.get_partial_renderer(
94 95 'rhodecode:templates/data_table/_dt_elements.mako')
95 96
96 97 def user_actions(user_id, username):
97 98 return _render("user_actions", user_id, username)
98 99
99 100 users_data_total_count = User.query()\
100 101 .filter(User.username != User.DEFAULT_USER) \
101 102 .count()
102 103
103 104 users_data_total_inactive_count = User.query()\
104 105 .filter(User.username != User.DEFAULT_USER) \
105 106 .filter(User.active != true())\
106 107 .count()
107 108
108 109 # json generate
109 110 base_q = User.query().filter(User.username != User.DEFAULT_USER)
110 111 base_inactive_q = base_q.filter(User.active != true())
111 112
112 113 if search_q:
113 114 like_expression = u'%{}%'.format(safe_unicode(search_q))
114 115 base_q = base_q.filter(or_(
115 116 User.username.ilike(like_expression),
116 117 User._email.ilike(like_expression),
117 118 User.name.ilike(like_expression),
118 119 User.lastname.ilike(like_expression),
119 120 ))
120 121 base_inactive_q = base_q.filter(User.active != true())
121 122
122 123 users_data_total_filtered_count = base_q.count()
123 124 users_data_total_filtered_inactive_count = base_inactive_q.count()
124 125
125 126 sort_col = getattr(User, order_by, None)
126 127 if sort_col:
127 128 if order_dir == 'asc':
128 129 # handle null values properly to order by NULL last
129 130 if order_by in ['last_activity']:
130 131 sort_col = coalesce(sort_col, datetime.date.max)
131 132 sort_col = sort_col.asc()
132 133 else:
133 134 # handle null values properly to order by NULL last
134 135 if order_by in ['last_activity']:
135 136 sort_col = coalesce(sort_col, datetime.date.min)
136 137 sort_col = sort_col.desc()
137 138
138 139 base_q = base_q.order_by(sort_col)
139 140 base_q = base_q.offset(start).limit(limit)
140 141
141 142 users_list = base_q.all()
142 143
143 144 users_data = []
144 145 for user in users_list:
145 146 users_data.append({
146 147 "username": h.gravatar_with_user(self.request, user.username),
147 148 "email": user.email,
148 149 "first_name": user.first_name,
149 150 "last_name": user.last_name,
150 151 "last_login": h.format_date(user.last_login),
151 152 "last_activity": h.format_date(user.last_activity),
152 153 "active": h.bool2icon(user.active),
153 154 "active_raw": user.active,
154 155 "admin": h.bool2icon(user.admin),
155 156 "extern_type": user.extern_type,
156 157 "extern_name": user.extern_name,
157 158 "action": user_actions(user.user_id, user.username),
158 159 })
159 160 data = ({
160 161 'draw': draw,
161 162 'data': users_data,
162 163 'recordsTotal': users_data_total_count,
163 164 'recordsFiltered': users_data_total_filtered_count,
164 165 'recordsTotalInactive': users_data_total_inactive_count,
165 166 'recordsFilteredInactive': users_data_total_filtered_inactive_count
166 167 })
167 168
168 169 return data
169 170
170 171 def _set_personal_repo_group_template_vars(self, c_obj):
171 172 DummyUser = AttributeDict({
172 173 'username': '${username}',
173 174 'user_id': '${user_id}',
174 175 })
175 176 c_obj.default_create_repo_group = RepoGroupModel() \
176 177 .get_default_create_personal_repo_group()
177 178 c_obj.personal_repo_group_name = RepoGroupModel() \
178 179 .get_personal_group_name(DummyUser)
179 180
180 181 @LoginRequired()
181 182 @HasPermissionAllDecorator('hg.admin')
182 183 @view_config(
183 184 route_name='users_new', request_method='GET',
184 185 renderer='rhodecode:templates/admin/users/user_add.mako')
185 186 def users_new(self):
186 187 _ = self.request.translate
187 188 c = self.load_default_context()
188 189 c.default_extern_type = auth_rhodecode.RhodeCodeAuthPlugin.uid
189 190 self._set_personal_repo_group_template_vars(c)
190 191 return self._get_template_context(c)
191 192
192 193 @LoginRequired()
193 194 @HasPermissionAllDecorator('hg.admin')
194 195 @CSRFRequired()
195 196 @view_config(
196 197 route_name='users_create', request_method='POST',
197 198 renderer='rhodecode:templates/admin/users/user_add.mako')
198 199 def users_create(self):
199 200 _ = self.request.translate
200 201 c = self.load_default_context()
201 202 c.default_extern_type = auth_rhodecode.RhodeCodeAuthPlugin.uid
202 203 user_model = UserModel()
203 204 user_form = UserForm(self.request.translate)()
204 205 try:
205 206 form_result = user_form.to_python(dict(self.request.POST))
206 207 user = user_model.create(form_result)
207 208 Session().flush()
208 209 creation_data = user.get_api_data()
209 210 username = form_result['username']
210 211
211 212 audit_logger.store_web(
212 213 'user.create', action_data={'data': creation_data},
213 214 user=c.rhodecode_user)
214 215
215 216 user_link = h.link_to(
216 217 h.escape(username),
217 218 h.route_path('user_edit', user_id=user.user_id))
218 219 h.flash(h.literal(_('Created user %(user_link)s')
219 220 % {'user_link': user_link}), category='success')
220 221 Session().commit()
221 222 except formencode.Invalid as errors:
222 223 self._set_personal_repo_group_template_vars(c)
223 224 data = render(
224 225 'rhodecode:templates/admin/users/user_add.mako',
225 226 self._get_template_context(c), self.request)
226 227 html = formencode.htmlfill.render(
227 228 data,
228 229 defaults=errors.value,
229 230 errors=errors.error_dict or {},
230 231 prefix_error=False,
231 232 encoding="UTF-8",
232 233 force_defaults=False
233 234 )
234 235 return Response(html)
235 236 except UserCreationError as e:
236 237 h.flash(e, 'error')
237 238 except Exception:
238 239 log.exception("Exception creation of user")
239 240 h.flash(_('Error occurred during creation of user %s')
240 241 % self.request.POST.get('username'), category='error')
241 242 raise HTTPFound(h.route_path('users'))
242 243
243 244
244 245 class UsersView(UserAppView):
245 246 ALLOW_SCOPED_TOKENS = False
246 247 """
247 248 This view has alternative version inside EE, if modified please take a look
248 249 in there as well.
249 250 """
250 251
251 252 def load_default_context(self):
252 253 c = self._get_local_tmpl_context()
253 254 c.allow_scoped_tokens = self.ALLOW_SCOPED_TOKENS
254 255 c.allowed_languages = [
255 256 ('en', 'English (en)'),
256 257 ('de', 'German (de)'),
257 258 ('fr', 'French (fr)'),
258 259 ('it', 'Italian (it)'),
259 260 ('ja', 'Japanese (ja)'),
260 261 ('pl', 'Polish (pl)'),
261 262 ('pt', 'Portuguese (pt)'),
262 263 ('ru', 'Russian (ru)'),
263 264 ('zh', 'Chinese (zh)'),
264 265 ]
265 266 req = self.request
266 267
267 268 c.available_permissions = req.registry.settings['available_permissions']
268 269 PermissionModel().set_global_permission_choices(
269 270 c, gettext_translator=req.translate)
270 271
271 272 return c
272 273
273 274 @LoginRequired()
274 275 @HasPermissionAllDecorator('hg.admin')
275 276 @CSRFRequired()
276 277 @view_config(
277 278 route_name='user_update', request_method='POST',
278 279 renderer='rhodecode:templates/admin/users/user_edit.mako')
279 280 def user_update(self):
280 281 _ = self.request.translate
281 282 c = self.load_default_context()
282 283
283 284 user_id = self.db_user_id
284 285 c.user = self.db_user
285 286
286 287 c.active = 'profile'
287 288 c.extern_type = c.user.extern_type
288 289 c.extern_name = c.user.extern_name
289 290 c.perm_user = c.user.AuthUser(ip_addr=self.request.remote_addr)
290 291 available_languages = [x[0] for x in c.allowed_languages]
291 292 _form = UserForm(self.request.translate, edit=True,
292 293 available_languages=available_languages,
293 294 old_data={'user_id': user_id,
294 295 'email': c.user.email})()
295 296 form_result = {}
296 297 old_values = c.user.get_api_data()
297 298 try:
298 299 form_result = _form.to_python(dict(self.request.POST))
299 300 skip_attrs = ['extern_type', 'extern_name']
300 301 # TODO: plugin should define if username can be updated
301 302 if c.extern_type != "rhodecode":
302 303 # forbid updating username for external accounts
303 304 skip_attrs.append('username')
304 305
305 306 UserModel().update_user(
306 307 user_id, skip_attrs=skip_attrs, **form_result)
307 308
308 309 audit_logger.store_web(
309 310 'user.edit', action_data={'old_data': old_values},
310 311 user=c.rhodecode_user)
311 312
312 313 Session().commit()
313 314 h.flash(_('User updated successfully'), category='success')
314 315 except formencode.Invalid as errors:
315 316 data = render(
316 317 'rhodecode:templates/admin/users/user_edit.mako',
317 318 self._get_template_context(c), self.request)
318 319 html = formencode.htmlfill.render(
319 320 data,
320 321 defaults=errors.value,
321 322 errors=errors.error_dict or {},
322 323 prefix_error=False,
323 324 encoding="UTF-8",
324 325 force_defaults=False
325 326 )
326 327 return Response(html)
327 328 except UserCreationError as e:
328 329 h.flash(e, 'error')
329 330 except Exception:
330 331 log.exception("Exception updating user")
331 332 h.flash(_('Error occurred during update of user %s')
332 333 % form_result.get('username'), category='error')
333 334 raise HTTPFound(h.route_path('user_edit', user_id=user_id))
334 335
335 336 @LoginRequired()
336 337 @HasPermissionAllDecorator('hg.admin')
337 338 @CSRFRequired()
338 339 @view_config(
339 340 route_name='user_delete', request_method='POST',
340 341 renderer='rhodecode:templates/admin/users/user_edit.mako')
341 342 def user_delete(self):
342 343 _ = self.request.translate
343 344 c = self.load_default_context()
344 345 c.user = self.db_user
345 346
346 347 _repos = c.user.repositories
347 348 _repo_groups = c.user.repository_groups
348 349 _user_groups = c.user.user_groups
349 350
350 351 handle_repos = None
351 352 handle_repo_groups = None
352 353 handle_user_groups = None
353 354 # dummy call for flash of handle
354 355 set_handle_flash_repos = lambda: None
355 356 set_handle_flash_repo_groups = lambda: None
356 357 set_handle_flash_user_groups = lambda: None
357 358
358 359 if _repos and self.request.POST.get('user_repos'):
359 360 do = self.request.POST['user_repos']
360 361 if do == 'detach':
361 362 handle_repos = 'detach'
362 363 set_handle_flash_repos = lambda: h.flash(
363 364 _('Detached %s repositories') % len(_repos),
364 365 category='success')
365 366 elif do == 'delete':
366 367 handle_repos = 'delete'
367 368 set_handle_flash_repos = lambda: h.flash(
368 369 _('Deleted %s repositories') % len(_repos),
369 370 category='success')
370 371
371 372 if _repo_groups and self.request.POST.get('user_repo_groups'):
372 373 do = self.request.POST['user_repo_groups']
373 374 if do == 'detach':
374 375 handle_repo_groups = 'detach'
375 376 set_handle_flash_repo_groups = lambda: h.flash(
376 377 _('Detached %s repository groups') % len(_repo_groups),
377 378 category='success')
378 379 elif do == 'delete':
379 380 handle_repo_groups = 'delete'
380 381 set_handle_flash_repo_groups = lambda: h.flash(
381 382 _('Deleted %s repository groups') % len(_repo_groups),
382 383 category='success')
383 384
384 385 if _user_groups and self.request.POST.get('user_user_groups'):
385 386 do = self.request.POST['user_user_groups']
386 387 if do == 'detach':
387 388 handle_user_groups = 'detach'
388 389 set_handle_flash_user_groups = lambda: h.flash(
389 390 _('Detached %s user groups') % len(_user_groups),
390 391 category='success')
391 392 elif do == 'delete':
392 393 handle_user_groups = 'delete'
393 394 set_handle_flash_user_groups = lambda: h.flash(
394 395 _('Deleted %s user groups') % len(_user_groups),
395 396 category='success')
396 397
397 398 old_values = c.user.get_api_data()
398 399 try:
399 400 UserModel().delete(c.user, handle_repos=handle_repos,
400 401 handle_repo_groups=handle_repo_groups,
401 402 handle_user_groups=handle_user_groups)
402 403
403 404 audit_logger.store_web(
404 405 'user.delete', action_data={'old_data': old_values},
405 406 user=c.rhodecode_user)
406 407
407 408 Session().commit()
408 409 set_handle_flash_repos()
409 410 set_handle_flash_repo_groups()
410 411 set_handle_flash_user_groups()
411 412 h.flash(_('Successfully deleted user'), category='success')
412 413 except (UserOwnsReposException, UserOwnsRepoGroupsException,
413 414 UserOwnsUserGroupsException, DefaultUserException) as e:
414 415 h.flash(e, category='warning')
415 416 except Exception:
416 417 log.exception("Exception during deletion of user")
417 418 h.flash(_('An error occurred during deletion of user'),
418 419 category='error')
419 420 raise HTTPFound(h.route_path('users'))
420 421
421 422 @LoginRequired()
422 423 @HasPermissionAllDecorator('hg.admin')
423 424 @view_config(
424 425 route_name='user_edit', request_method='GET',
425 426 renderer='rhodecode:templates/admin/users/user_edit.mako')
426 427 def user_edit(self):
427 428 _ = self.request.translate
428 429 c = self.load_default_context()
429 430 c.user = self.db_user
430 431
431 432 c.active = 'profile'
432 433 c.extern_type = c.user.extern_type
433 434 c.extern_name = c.user.extern_name
434 435 c.perm_user = c.user.AuthUser(ip_addr=self.request.remote_addr)
435 436
436 437 defaults = c.user.get_dict()
437 438 defaults.update({'language': c.user.user_data.get('language')})
438 439
439 440 data = render(
440 441 'rhodecode:templates/admin/users/user_edit.mako',
441 442 self._get_template_context(c), self.request)
442 443 html = formencode.htmlfill.render(
443 444 data,
444 445 defaults=defaults,
445 446 encoding="UTF-8",
446 447 force_defaults=False
447 448 )
448 449 return Response(html)
449 450
450 451 @LoginRequired()
451 452 @HasPermissionAllDecorator('hg.admin')
452 453 @view_config(
453 454 route_name='user_edit_advanced', request_method='GET',
454 455 renderer='rhodecode:templates/admin/users/user_edit.mako')
455 456 def user_edit_advanced(self):
456 457 _ = self.request.translate
457 458 c = self.load_default_context()
458 459
459 460 user_id = self.db_user_id
460 461 c.user = self.db_user
461 462
462 463 c.active = 'advanced'
463 464 c.personal_repo_group = RepoGroup.get_user_personal_repo_group(user_id)
464 465 c.personal_repo_group_name = RepoGroupModel()\
465 466 .get_personal_group_name(c.user)
466 467
467 468 c.user_to_review_rules = sorted(
468 469 (x.user for x in c.user.user_review_rules),
469 470 key=lambda u: u.username.lower())
470 471
471 472 c.first_admin = User.get_first_super_admin()
472 473 defaults = c.user.get_dict()
473 474
474 475 # Interim workaround if the user participated on any pull requests as a
475 476 # reviewer.
476 477 has_review = len(c.user.reviewer_pull_requests)
477 478 c.can_delete_user = not has_review
478 479 c.can_delete_user_message = ''
479 480 inactive_link = h.link_to(
480 481 'inactive', h.route_path('user_edit', user_id=user_id, _anchor='active'))
481 482 if has_review == 1:
482 483 c.can_delete_user_message = h.literal(_(
483 484 'The user participates as reviewer in {} pull request and '
484 485 'cannot be deleted. \nYou can set the user to '
485 486 '"{}" instead of deleting it.').format(
486 487 has_review, inactive_link))
487 488 elif has_review:
488 489 c.can_delete_user_message = h.literal(_(
489 490 'The user participates as reviewer in {} pull requests and '
490 491 'cannot be deleted. \nYou can set the user to '
491 492 '"{}" instead of deleting it.').format(
492 493 has_review, inactive_link))
493 494
494 495 data = render(
495 496 'rhodecode:templates/admin/users/user_edit.mako',
496 497 self._get_template_context(c), self.request)
497 498 html = formencode.htmlfill.render(
498 499 data,
499 500 defaults=defaults,
500 501 encoding="UTF-8",
501 502 force_defaults=False
502 503 )
503 504 return Response(html)
504 505
505 506 @LoginRequired()
506 507 @HasPermissionAllDecorator('hg.admin')
507 508 @view_config(
508 509 route_name='user_edit_global_perms', request_method='GET',
509 510 renderer='rhodecode:templates/admin/users/user_edit.mako')
510 511 def user_edit_global_perms(self):
511 512 _ = self.request.translate
512 513 c = self.load_default_context()
513 514 c.user = self.db_user
514 515
515 516 c.active = 'global_perms'
516 517
517 518 c.default_user = User.get_default_user()
518 519 defaults = c.user.get_dict()
519 520 defaults.update(c.default_user.get_default_perms(suffix='_inherited'))
520 521 defaults.update(c.default_user.get_default_perms())
521 522 defaults.update(c.user.get_default_perms())
522 523
523 524 data = render(
524 525 'rhodecode:templates/admin/users/user_edit.mako',
525 526 self._get_template_context(c), self.request)
526 527 html = formencode.htmlfill.render(
527 528 data,
528 529 defaults=defaults,
529 530 encoding="UTF-8",
530 531 force_defaults=False
531 532 )
532 533 return Response(html)
533 534
534 535 @LoginRequired()
535 536 @HasPermissionAllDecorator('hg.admin')
536 537 @CSRFRequired()
537 538 @view_config(
538 539 route_name='user_edit_global_perms_update', request_method='POST',
539 540 renderer='rhodecode:templates/admin/users/user_edit.mako')
540 541 def user_edit_global_perms_update(self):
541 542 _ = self.request.translate
542 543 c = self.load_default_context()
543 544
544 545 user_id = self.db_user_id
545 546 c.user = self.db_user
546 547
547 548 c.active = 'global_perms'
548 549 try:
549 550 # first stage that verifies the checkbox
550 551 _form = UserIndividualPermissionsForm(self.request.translate)
551 552 form_result = _form.to_python(dict(self.request.POST))
552 553 inherit_perms = form_result['inherit_default_permissions']
553 554 c.user.inherit_default_permissions = inherit_perms
554 555 Session().add(c.user)
555 556
556 557 if not inherit_perms:
557 558 # only update the individual ones if we un check the flag
558 559 _form = UserPermissionsForm(
559 560 self.request.translate,
560 561 [x[0] for x in c.repo_create_choices],
561 562 [x[0] for x in c.repo_create_on_write_choices],
562 563 [x[0] for x in c.repo_group_create_choices],
563 564 [x[0] for x in c.user_group_create_choices],
564 565 [x[0] for x in c.fork_choices],
565 566 [x[0] for x in c.inherit_default_permission_choices])()
566 567
567 568 form_result = _form.to_python(dict(self.request.POST))
568 569 form_result.update({'perm_user_id': c.user.user_id})
569 570
570 571 PermissionModel().update_user_permissions(form_result)
571 572
572 573 # TODO(marcink): implement global permissions
573 574 # audit_log.store_web('user.edit.permissions')
574 575
575 576 Session().commit()
577
576 578 h.flash(_('User global permissions updated successfully'),
577 579 category='success')
578 580
579 581 except formencode.Invalid as errors:
580 582 data = render(
581 583 'rhodecode:templates/admin/users/user_edit.mako',
582 584 self._get_template_context(c), self.request)
583 585 html = formencode.htmlfill.render(
584 586 data,
585 587 defaults=errors.value,
586 588 errors=errors.error_dict or {},
587 589 prefix_error=False,
588 590 encoding="UTF-8",
589 591 force_defaults=False
590 592 )
591 593 return Response(html)
592 594 except Exception:
593 595 log.exception("Exception during permissions saving")
594 596 h.flash(_('An error occurred during permissions saving'),
595 597 category='error')
598
599 affected_user_ids = [user_id]
600 events.trigger(events.UserPermissionsChange(affected_user_ids))
596 601 raise HTTPFound(h.route_path('user_edit_global_perms', user_id=user_id))
597 602
598 603 @LoginRequired()
599 604 @HasPermissionAllDecorator('hg.admin')
600 605 @CSRFRequired()
601 606 @view_config(
602 607 route_name='user_force_password_reset', request_method='POST',
603 608 renderer='rhodecode:templates/admin/users/user_edit.mako')
604 609 def user_force_password_reset(self):
605 610 """
606 611 toggle reset password flag for this user
607 612 """
608 613 _ = self.request.translate
609 614 c = self.load_default_context()
610 615
611 616 user_id = self.db_user_id
612 617 c.user = self.db_user
613 618
614 619 try:
615 620 old_value = c.user.user_data.get('force_password_change')
616 621 c.user.update_userdata(force_password_change=not old_value)
617 622
618 623 if old_value:
619 624 msg = _('Force password change disabled for user')
620 625 audit_logger.store_web(
621 626 'user.edit.password_reset.disabled',
622 627 user=c.rhodecode_user)
623 628 else:
624 629 msg = _('Force password change enabled for user')
625 630 audit_logger.store_web(
626 631 'user.edit.password_reset.enabled',
627 632 user=c.rhodecode_user)
628 633
629 634 Session().commit()
630 635 h.flash(msg, category='success')
631 636 except Exception:
632 637 log.exception("Exception during password reset for user")
633 638 h.flash(_('An error occurred during password reset for user'),
634 639 category='error')
635 640
636 641 raise HTTPFound(h.route_path('user_edit_advanced', user_id=user_id))
637 642
638 643 @LoginRequired()
639 644 @HasPermissionAllDecorator('hg.admin')
640 645 @CSRFRequired()
641 646 @view_config(
642 647 route_name='user_create_personal_repo_group', request_method='POST',
643 648 renderer='rhodecode:templates/admin/users/user_edit.mako')
644 649 def user_create_personal_repo_group(self):
645 650 """
646 651 Create personal repository group for this user
647 652 """
648 653 from rhodecode.model.repo_group import RepoGroupModel
649 654
650 655 _ = self.request.translate
651 656 c = self.load_default_context()
652 657
653 658 user_id = self.db_user_id
654 659 c.user = self.db_user
655 660
656 661 personal_repo_group = RepoGroup.get_user_personal_repo_group(
657 662 c.user.user_id)
658 663 if personal_repo_group:
659 664 raise HTTPFound(h.route_path('user_edit_advanced', user_id=user_id))
660 665
661 666 personal_repo_group_name = RepoGroupModel().get_personal_group_name(
662 667 c.user)
663 668 named_personal_group = RepoGroup.get_by_group_name(
664 669 personal_repo_group_name)
665 670 try:
666 671
667 672 if named_personal_group and named_personal_group.user_id == c.user.user_id:
668 673 # migrate the same named group, and mark it as personal
669 674 named_personal_group.personal = True
670 675 Session().add(named_personal_group)
671 676 Session().commit()
672 677 msg = _('Linked repository group `%s` as personal' % (
673 678 personal_repo_group_name,))
674 679 h.flash(msg, category='success')
675 680 elif not named_personal_group:
676 681 RepoGroupModel().create_personal_repo_group(c.user)
677 682
678 683 msg = _('Created repository group `%s`' % (
679 684 personal_repo_group_name,))
680 685 h.flash(msg, category='success')
681 686 else:
682 687 msg = _('Repository group `%s` is already taken' % (
683 688 personal_repo_group_name,))
684 689 h.flash(msg, category='warning')
685 690 except Exception:
686 691 log.exception("Exception during repository group creation")
687 692 msg = _(
688 693 'An error occurred during repository group creation for user')
689 694 h.flash(msg, category='error')
690 695 Session().rollback()
691 696
692 697 raise HTTPFound(h.route_path('user_edit_advanced', user_id=user_id))
693 698
694 699 @LoginRequired()
695 700 @HasPermissionAllDecorator('hg.admin')
696 701 @view_config(
697 702 route_name='edit_user_auth_tokens', request_method='GET',
698 703 renderer='rhodecode:templates/admin/users/user_edit.mako')
699 704 def auth_tokens(self):
700 705 _ = self.request.translate
701 706 c = self.load_default_context()
702 707 c.user = self.db_user
703 708
704 709 c.active = 'auth_tokens'
705 710
706 711 c.lifetime_values = AuthTokenModel.get_lifetime_values(translator=_)
707 712 c.role_values = [
708 713 (x, AuthTokenModel.cls._get_role_name(x))
709 714 for x in AuthTokenModel.cls.ROLES]
710 715 c.role_options = [(c.role_values, _("Role"))]
711 716 c.user_auth_tokens = AuthTokenModel().get_auth_tokens(
712 717 c.user.user_id, show_expired=True)
713 718 c.role_vcs = AuthTokenModel.cls.ROLE_VCS
714 719 return self._get_template_context(c)
715 720
716 721 def maybe_attach_token_scope(self, token):
717 722 # implemented in EE edition
718 723 pass
719 724
720 725 @LoginRequired()
721 726 @HasPermissionAllDecorator('hg.admin')
722 727 @CSRFRequired()
723 728 @view_config(
724 729 route_name='edit_user_auth_tokens_add', request_method='POST')
725 730 def auth_tokens_add(self):
726 731 _ = self.request.translate
727 732 c = self.load_default_context()
728 733
729 734 user_id = self.db_user_id
730 735 c.user = self.db_user
731 736
732 737 user_data = c.user.get_api_data()
733 738 lifetime = safe_int(self.request.POST.get('lifetime'), -1)
734 739 description = self.request.POST.get('description')
735 740 role = self.request.POST.get('role')
736 741
737 742 token = UserModel().add_auth_token(
738 743 user=c.user.user_id,
739 744 lifetime_minutes=lifetime, role=role, description=description,
740 745 scope_callback=self.maybe_attach_token_scope)
741 746 token_data = token.get_api_data()
742 747
743 748 audit_logger.store_web(
744 749 'user.edit.token.add', action_data={
745 750 'data': {'token': token_data, 'user': user_data}},
746 751 user=self._rhodecode_user, )
747 752 Session().commit()
748 753
749 754 h.flash(_("Auth token successfully created"), category='success')
750 755 return HTTPFound(h.route_path('edit_user_auth_tokens', user_id=user_id))
751 756
752 757 @LoginRequired()
753 758 @HasPermissionAllDecorator('hg.admin')
754 759 @CSRFRequired()
755 760 @view_config(
756 761 route_name='edit_user_auth_tokens_delete', request_method='POST')
757 762 def auth_tokens_delete(self):
758 763 _ = self.request.translate
759 764 c = self.load_default_context()
760 765
761 766 user_id = self.db_user_id
762 767 c.user = self.db_user
763 768
764 769 user_data = c.user.get_api_data()
765 770
766 771 del_auth_token = self.request.POST.get('del_auth_token')
767 772
768 773 if del_auth_token:
769 774 token = UserApiKeys.get_or_404(del_auth_token)
770 775 token_data = token.get_api_data()
771 776
772 777 AuthTokenModel().delete(del_auth_token, c.user.user_id)
773 778 audit_logger.store_web(
774 779 'user.edit.token.delete', action_data={
775 780 'data': {'token': token_data, 'user': user_data}},
776 781 user=self._rhodecode_user,)
777 782 Session().commit()
778 783 h.flash(_("Auth token successfully deleted"), category='success')
779 784
780 785 return HTTPFound(h.route_path('edit_user_auth_tokens', user_id=user_id))
781 786
782 787 @LoginRequired()
783 788 @HasPermissionAllDecorator('hg.admin')
784 789 @view_config(
785 790 route_name='edit_user_ssh_keys', request_method='GET',
786 791 renderer='rhodecode:templates/admin/users/user_edit.mako')
787 792 def ssh_keys(self):
788 793 _ = self.request.translate
789 794 c = self.load_default_context()
790 795 c.user = self.db_user
791 796
792 797 c.active = 'ssh_keys'
793 798 c.default_key = self.request.GET.get('default_key')
794 799 c.user_ssh_keys = SshKeyModel().get_ssh_keys(c.user.user_id)
795 800 return self._get_template_context(c)
796 801
797 802 @LoginRequired()
798 803 @HasPermissionAllDecorator('hg.admin')
799 804 @view_config(
800 805 route_name='edit_user_ssh_keys_generate_keypair', request_method='GET',
801 806 renderer='rhodecode:templates/admin/users/user_edit.mako')
802 807 def ssh_keys_generate_keypair(self):
803 808 _ = self.request.translate
804 809 c = self.load_default_context()
805 810
806 811 c.user = self.db_user
807 812
808 813 c.active = 'ssh_keys_generate'
809 814 comment = 'RhodeCode-SSH {}'.format(c.user.email or '')
810 815 c.private, c.public = SshKeyModel().generate_keypair(comment=comment)
811 816
812 817 return self._get_template_context(c)
813 818
814 819 @LoginRequired()
815 820 @HasPermissionAllDecorator('hg.admin')
816 821 @CSRFRequired()
817 822 @view_config(
818 823 route_name='edit_user_ssh_keys_add', request_method='POST')
819 824 def ssh_keys_add(self):
820 825 _ = self.request.translate
821 826 c = self.load_default_context()
822 827
823 828 user_id = self.db_user_id
824 829 c.user = self.db_user
825 830
826 831 user_data = c.user.get_api_data()
827 832 key_data = self.request.POST.get('key_data')
828 833 description = self.request.POST.get('description')
829 834
830 835 fingerprint = 'unknown'
831 836 try:
832 837 if not key_data:
833 838 raise ValueError('Please add a valid public key')
834 839
835 840 key = SshKeyModel().parse_key(key_data.strip())
836 841 fingerprint = key.hash_md5()
837 842
838 843 ssh_key = SshKeyModel().create(
839 844 c.user.user_id, fingerprint, key.keydata, description)
840 845 ssh_key_data = ssh_key.get_api_data()
841 846
842 847 audit_logger.store_web(
843 848 'user.edit.ssh_key.add', action_data={
844 849 'data': {'ssh_key': ssh_key_data, 'user': user_data}},
845 850 user=self._rhodecode_user, )
846 851 Session().commit()
847 852
848 853 # Trigger an event on change of keys.
849 854 trigger(SshKeyFileChangeEvent(), self.request.registry)
850 855
851 856 h.flash(_("Ssh Key successfully created"), category='success')
852 857
853 858 except IntegrityError:
854 859 log.exception("Exception during ssh key saving")
855 860 err = 'Such key with fingerprint `{}` already exists, ' \
856 861 'please use a different one'.format(fingerprint)
857 862 h.flash(_('An error occurred during ssh key saving: {}').format(err),
858 863 category='error')
859 864 except Exception as e:
860 865 log.exception("Exception during ssh key saving")
861 866 h.flash(_('An error occurred during ssh key saving: {}').format(e),
862 867 category='error')
863 868
864 869 return HTTPFound(
865 870 h.route_path('edit_user_ssh_keys', user_id=user_id))
866 871
867 872 @LoginRequired()
868 873 @HasPermissionAllDecorator('hg.admin')
869 874 @CSRFRequired()
870 875 @view_config(
871 876 route_name='edit_user_ssh_keys_delete', request_method='POST')
872 877 def ssh_keys_delete(self):
873 878 _ = self.request.translate
874 879 c = self.load_default_context()
875 880
876 881 user_id = self.db_user_id
877 882 c.user = self.db_user
878 883
879 884 user_data = c.user.get_api_data()
880 885
881 886 del_ssh_key = self.request.POST.get('del_ssh_key')
882 887
883 888 if del_ssh_key:
884 889 ssh_key = UserSshKeys.get_or_404(del_ssh_key)
885 890 ssh_key_data = ssh_key.get_api_data()
886 891
887 892 SshKeyModel().delete(del_ssh_key, c.user.user_id)
888 893 audit_logger.store_web(
889 894 'user.edit.ssh_key.delete', action_data={
890 895 'data': {'ssh_key': ssh_key_data, 'user': user_data}},
891 896 user=self._rhodecode_user,)
892 897 Session().commit()
893 898 # Trigger an event on change of keys.
894 899 trigger(SshKeyFileChangeEvent(), self.request.registry)
895 900 h.flash(_("Ssh key successfully deleted"), category='success')
896 901
897 902 return HTTPFound(h.route_path('edit_user_ssh_keys', user_id=user_id))
898 903
899 904 @LoginRequired()
900 905 @HasPermissionAllDecorator('hg.admin')
901 906 @view_config(
902 907 route_name='edit_user_emails', request_method='GET',
903 908 renderer='rhodecode:templates/admin/users/user_edit.mako')
904 909 def emails(self):
905 910 _ = self.request.translate
906 911 c = self.load_default_context()
907 912 c.user = self.db_user
908 913
909 914 c.active = 'emails'
910 915 c.user_email_map = UserEmailMap.query() \
911 916 .filter(UserEmailMap.user == c.user).all()
912 917
913 918 return self._get_template_context(c)
914 919
915 920 @LoginRequired()
916 921 @HasPermissionAllDecorator('hg.admin')
917 922 @CSRFRequired()
918 923 @view_config(
919 924 route_name='edit_user_emails_add', request_method='POST')
920 925 def emails_add(self):
921 926 _ = self.request.translate
922 927 c = self.load_default_context()
923 928
924 929 user_id = self.db_user_id
925 930 c.user = self.db_user
926 931
927 932 email = self.request.POST.get('new_email')
928 933 user_data = c.user.get_api_data()
929 934 try:
930 935
931 936 form = UserExtraEmailForm(self.request.translate)()
932 937 data = form.to_python({'email': email})
933 938 email = data['email']
934 939
935 940 UserModel().add_extra_email(c.user.user_id, email)
936 941 audit_logger.store_web(
937 942 'user.edit.email.add',
938 943 action_data={'email': email, 'user': user_data},
939 944 user=self._rhodecode_user)
940 945 Session().commit()
941 946 h.flash(_("Added new email address `%s` for user account") % email,
942 947 category='success')
943 948 except formencode.Invalid as error:
944 949 h.flash(h.escape(error.error_dict['email']), category='error')
945 950 except IntegrityError:
946 951 log.warning("Email %s already exists", email)
947 952 h.flash(_('Email `{}` is already registered for another user.').format(email),
948 953 category='error')
949 954 except Exception:
950 955 log.exception("Exception during email saving")
951 956 h.flash(_('An error occurred during email saving'),
952 957 category='error')
953 958 raise HTTPFound(h.route_path('edit_user_emails', user_id=user_id))
954 959
955 960 @LoginRequired()
956 961 @HasPermissionAllDecorator('hg.admin')
957 962 @CSRFRequired()
958 963 @view_config(
959 964 route_name='edit_user_emails_delete', request_method='POST')
960 965 def emails_delete(self):
961 966 _ = self.request.translate
962 967 c = self.load_default_context()
963 968
964 969 user_id = self.db_user_id
965 970 c.user = self.db_user
966 971
967 972 email_id = self.request.POST.get('del_email_id')
968 973 user_model = UserModel()
969 974
970 975 email = UserEmailMap.query().get(email_id).email
971 976 user_data = c.user.get_api_data()
972 977 user_model.delete_extra_email(c.user.user_id, email_id)
973 978 audit_logger.store_web(
974 979 'user.edit.email.delete',
975 980 action_data={'email': email, 'user': user_data},
976 981 user=self._rhodecode_user)
977 982 Session().commit()
978 983 h.flash(_("Removed email address from user account"),
979 984 category='success')
980 985 raise HTTPFound(h.route_path('edit_user_emails', user_id=user_id))
981 986
982 987 @LoginRequired()
983 988 @HasPermissionAllDecorator('hg.admin')
984 989 @view_config(
985 990 route_name='edit_user_ips', request_method='GET',
986 991 renderer='rhodecode:templates/admin/users/user_edit.mako')
987 992 def ips(self):
988 993 _ = self.request.translate
989 994 c = self.load_default_context()
990 995 c.user = self.db_user
991 996
992 997 c.active = 'ips'
993 998 c.user_ip_map = UserIpMap.query() \
994 999 .filter(UserIpMap.user == c.user).all()
995 1000
996 1001 c.inherit_default_ips = c.user.inherit_default_permissions
997 1002 c.default_user_ip_map = UserIpMap.query() \
998 1003 .filter(UserIpMap.user == User.get_default_user()).all()
999 1004
1000 1005 return self._get_template_context(c)
1001 1006
1002 1007 @LoginRequired()
1003 1008 @HasPermissionAllDecorator('hg.admin')
1004 1009 @CSRFRequired()
1005 1010 @view_config(
1006 1011 route_name='edit_user_ips_add', request_method='POST')
1007 1012 # NOTE(marcink): this view is allowed for default users, as we can
1008 1013 # edit their IP white list
1009 1014 def ips_add(self):
1010 1015 _ = self.request.translate
1011 1016 c = self.load_default_context()
1012 1017
1013 1018 user_id = self.db_user_id
1014 1019 c.user = self.db_user
1015 1020
1016 1021 user_model = UserModel()
1017 1022 desc = self.request.POST.get('description')
1018 1023 try:
1019 1024 ip_list = user_model.parse_ip_range(
1020 1025 self.request.POST.get('new_ip'))
1021 1026 except Exception as e:
1022 1027 ip_list = []
1023 1028 log.exception("Exception during ip saving")
1024 1029 h.flash(_('An error occurred during ip saving:%s' % (e,)),
1025 1030 category='error')
1026 1031 added = []
1027 1032 user_data = c.user.get_api_data()
1028 1033 for ip in ip_list:
1029 1034 try:
1030 1035 form = UserExtraIpForm(self.request.translate)()
1031 1036 data = form.to_python({'ip': ip})
1032 1037 ip = data['ip']
1033 1038
1034 1039 user_model.add_extra_ip(c.user.user_id, ip, desc)
1035 1040 audit_logger.store_web(
1036 1041 'user.edit.ip.add',
1037 1042 action_data={'ip': ip, 'user': user_data},
1038 1043 user=self._rhodecode_user)
1039 1044 Session().commit()
1040 1045 added.append(ip)
1041 1046 except formencode.Invalid as error:
1042 1047 msg = error.error_dict['ip']
1043 1048 h.flash(msg, category='error')
1044 1049 except Exception:
1045 1050 log.exception("Exception during ip saving")
1046 1051 h.flash(_('An error occurred during ip saving'),
1047 1052 category='error')
1048 1053 if added:
1049 1054 h.flash(
1050 1055 _("Added ips %s to user whitelist") % (', '.join(ip_list), ),
1051 1056 category='success')
1052 1057 if 'default_user' in self.request.POST:
1053 1058 # case for editing global IP list we do it for 'DEFAULT' user
1054 1059 raise HTTPFound(h.route_path('admin_permissions_ips'))
1055 1060 raise HTTPFound(h.route_path('edit_user_ips', user_id=user_id))
1056 1061
1057 1062 @LoginRequired()
1058 1063 @HasPermissionAllDecorator('hg.admin')
1059 1064 @CSRFRequired()
1060 1065 @view_config(
1061 1066 route_name='edit_user_ips_delete', request_method='POST')
1062 1067 # NOTE(marcink): this view is allowed for default users, as we can
1063 1068 # edit their IP white list
1064 1069 def ips_delete(self):
1065 1070 _ = self.request.translate
1066 1071 c = self.load_default_context()
1067 1072
1068 1073 user_id = self.db_user_id
1069 1074 c.user = self.db_user
1070 1075
1071 1076 ip_id = self.request.POST.get('del_ip_id')
1072 1077 user_model = UserModel()
1073 1078 user_data = c.user.get_api_data()
1074 1079 ip = UserIpMap.query().get(ip_id).ip_addr
1075 1080 user_model.delete_extra_ip(c.user.user_id, ip_id)
1076 1081 audit_logger.store_web(
1077 1082 'user.edit.ip.delete', action_data={'ip': ip, 'user': user_data},
1078 1083 user=self._rhodecode_user)
1079 1084 Session().commit()
1080 1085 h.flash(_("Removed ip address from user whitelist"), category='success')
1081 1086
1082 1087 if 'default_user' in self.request.POST:
1083 1088 # case for editing global IP list we do it for 'DEFAULT' user
1084 1089 raise HTTPFound(h.route_path('admin_permissions_ips'))
1085 1090 raise HTTPFound(h.route_path('edit_user_ips', user_id=user_id))
1086 1091
1087 1092 @LoginRequired()
1088 1093 @HasPermissionAllDecorator('hg.admin')
1089 1094 @view_config(
1090 1095 route_name='edit_user_groups_management', request_method='GET',
1091 1096 renderer='rhodecode:templates/admin/users/user_edit.mako')
1092 1097 def groups_management(self):
1093 1098 c = self.load_default_context()
1094 1099 c.user = self.db_user
1095 1100 c.data = c.user.group_member
1096 1101
1097 1102 groups = [UserGroupModel.get_user_groups_as_dict(group.users_group)
1098 1103 for group in c.user.group_member]
1099 1104 c.groups = json.dumps(groups)
1100 1105 c.active = 'groups'
1101 1106
1102 1107 return self._get_template_context(c)
1103 1108
1104 1109 @LoginRequired()
1105 1110 @HasPermissionAllDecorator('hg.admin')
1106 1111 @CSRFRequired()
1107 1112 @view_config(
1108 1113 route_name='edit_user_groups_management_updates', request_method='POST')
1109 1114 def groups_management_updates(self):
1110 1115 _ = self.request.translate
1111 1116 c = self.load_default_context()
1112 1117
1113 1118 user_id = self.db_user_id
1114 1119 c.user = self.db_user
1115 1120
1116 1121 user_groups = set(self.request.POST.getall('users_group_id'))
1117 1122 user_groups_objects = []
1118 1123
1119 1124 for ugid in user_groups:
1120 1125 user_groups_objects.append(
1121 1126 UserGroupModel().get_group(safe_int(ugid)))
1122 1127 user_group_model = UserGroupModel()
1123 1128 added_to_groups, removed_from_groups = \
1124 1129 user_group_model.change_groups(c.user, user_groups_objects)
1125 1130
1126 1131 user_data = c.user.get_api_data()
1127 1132 for user_group_id in added_to_groups:
1128 1133 user_group = UserGroup.get(user_group_id)
1129 1134 old_values = user_group.get_api_data()
1130 1135 audit_logger.store_web(
1131 1136 'user_group.edit.member.add',
1132 1137 action_data={'user': user_data, 'old_data': old_values},
1133 1138 user=self._rhodecode_user)
1134 1139
1135 1140 for user_group_id in removed_from_groups:
1136 1141 user_group = UserGroup.get(user_group_id)
1137 1142 old_values = user_group.get_api_data()
1138 1143 audit_logger.store_web(
1139 1144 'user_group.edit.member.delete',
1140 1145 action_data={'user': user_data, 'old_data': old_values},
1141 1146 user=self._rhodecode_user)
1142 1147
1143 1148 Session().commit()
1144 1149 c.active = 'user_groups_management'
1145 1150 h.flash(_("Groups successfully changed"), category='success')
1146 1151
1147 1152 return HTTPFound(h.route_path(
1148 1153 'edit_user_groups_management', user_id=user_id))
1149 1154
1150 1155 @LoginRequired()
1151 1156 @HasPermissionAllDecorator('hg.admin')
1152 1157 @view_config(
1153 1158 route_name='edit_user_audit_logs', request_method='GET',
1154 1159 renderer='rhodecode:templates/admin/users/user_edit.mako')
1155 1160 def user_audit_logs(self):
1156 1161 _ = self.request.translate
1157 1162 c = self.load_default_context()
1158 1163 c.user = self.db_user
1159 1164
1160 1165 c.active = 'audit'
1161 1166
1162 1167 p = safe_int(self.request.GET.get('page', 1), 1)
1163 1168
1164 1169 filter_term = self.request.GET.get('filter')
1165 1170 user_log = UserModel().get_user_log(c.user, filter_term)
1166 1171
1167 1172 def url_generator(**kw):
1168 1173 if filter_term:
1169 1174 kw['filter'] = filter_term
1170 1175 return self.request.current_route_path(_query=kw)
1171 1176
1172 1177 c.audit_logs = h.Page(
1173 1178 user_log, page=p, items_per_page=10, url=url_generator)
1174 1179 c.filter_term = filter_term
1175 1180 return self._get_template_context(c)
1176 1181
1177 1182 @LoginRequired()
1178 1183 @HasPermissionAllDecorator('hg.admin')
1179 1184 @view_config(
1180 1185 route_name='edit_user_perms_summary', request_method='GET',
1181 1186 renderer='rhodecode:templates/admin/users/user_edit.mako')
1182 1187 def user_perms_summary(self):
1183 1188 _ = self.request.translate
1184 1189 c = self.load_default_context()
1185 1190 c.user = self.db_user
1186 1191
1187 1192 c.active = 'perms_summary'
1188 1193 c.perm_user = c.user.AuthUser(ip_addr=self.request.remote_addr)
1189 1194
1190 1195 return self._get_template_context(c)
1191 1196
1192 1197 @LoginRequired()
1193 1198 @HasPermissionAllDecorator('hg.admin')
1194 1199 @view_config(
1195 1200 route_name='edit_user_perms_summary_json', request_method='GET',
1196 1201 renderer='json_ext')
1197 1202 def user_perms_summary_json(self):
1198 1203 self.load_default_context()
1199 1204 perm_user = self.db_user.AuthUser(ip_addr=self.request.remote_addr)
1200 1205
1201 1206 return perm_user.permissions
1202 1207
1203 1208 @LoginRequired()
1204 1209 @HasPermissionAllDecorator('hg.admin')
1205 1210 @view_config(
1206 1211 route_name='edit_user_caches', request_method='GET',
1207 1212 renderer='rhodecode:templates/admin/users/user_edit.mako')
1208 1213 def user_caches(self):
1209 1214 _ = self.request.translate
1210 1215 c = self.load_default_context()
1211 1216 c.user = self.db_user
1212 1217
1213 1218 c.active = 'caches'
1214 1219 c.perm_user = c.user.AuthUser(ip_addr=self.request.remote_addr)
1215 1220
1216 1221 cache_namespace_uid = 'cache_user_auth.{}'.format(self.db_user.user_id)
1217 1222 c.region = rc_cache.get_or_create_region('cache_perms', cache_namespace_uid)
1218 1223 c.backend = c.region.backend
1219 1224 c.user_keys = sorted(c.region.backend.list_keys(prefix=cache_namespace_uid))
1220 1225
1221 1226 return self._get_template_context(c)
1222 1227
1223 1228 @LoginRequired()
1224 1229 @HasPermissionAllDecorator('hg.admin')
1225 1230 @CSRFRequired()
1226 1231 @view_config(
1227 1232 route_name='edit_user_caches_update', request_method='POST')
1228 1233 def user_caches_update(self):
1229 1234 _ = self.request.translate
1230 1235 c = self.load_default_context()
1231 1236 c.user = self.db_user
1232 1237
1233 1238 c.active = 'caches'
1234 1239 c.perm_user = c.user.AuthUser(ip_addr=self.request.remote_addr)
1235 1240
1236 1241 cache_namespace_uid = 'cache_user_auth.{}'.format(self.db_user.user_id)
1237 1242 del_keys = rc_cache.clear_cache_namespace('cache_perms', cache_namespace_uid)
1238 1243
1239 1244 h.flash(_("Deleted {} cache keys").format(del_keys), category='success')
1240 1245
1241 1246 return HTTPFound(h.route_path(
1242 1247 'edit_user_caches', user_id=c.user.user_id))
@@ -1,189 +1,193 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2011-2018 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 21 import logging
22 22 import deform
23 23
24 24 from pyramid.view import view_config
25 25 from pyramid.httpexceptions import HTTPFound
26 26
27 27 from rhodecode import events
28 28 from rhodecode.apps._base import RepoGroupAppView
29 29 from rhodecode.forms import RcForm
30 30 from rhodecode.lib import helpers as h
31 31 from rhodecode.lib import audit_logger
32 32 from rhodecode.lib.auth import (
33 33 LoginRequired, HasPermissionAll,
34 34 HasRepoGroupPermissionAny, HasRepoGroupPermissionAnyDecorator, CSRFRequired)
35 35 from rhodecode.model.db import Session, RepoGroup, User
36 36 from rhodecode.model.scm import RepoGroupList
37 37 from rhodecode.model.repo_group import RepoGroupModel
38 38 from rhodecode.model.validation_schema.schemas import repo_group_schema
39 39
40 40 log = logging.getLogger(__name__)
41 41
42 42
43 43 class RepoGroupSettingsView(RepoGroupAppView):
44 44 def load_default_context(self):
45 45 c = self._get_local_tmpl_context()
46 46 c.repo_group = self.db_repo_group
47 47 no_parrent = not c.repo_group.parent_group
48 48 can_create_in_root = self._can_create_repo_group()
49 49
50 50 show_root_location = False
51 51 if no_parrent or can_create_in_root:
52 52 # we're global admin, we're ok and we can create TOP level groups
53 53 # or in case this group is already at top-level we also allow
54 54 # creation in root
55 55 show_root_location = True
56 56
57 57 acl_groups = RepoGroupList(
58 58 RepoGroup.query().all(),
59 59 perm_set=['group.admin'])
60 60 c.repo_groups = RepoGroup.groups_choices(
61 61 groups=acl_groups,
62 62 show_empty_group=show_root_location)
63 63 # filter out current repo group
64 64 exclude_group_ids = [c.repo_group.group_id]
65 65 c.repo_groups = filter(lambda x: x[0] not in exclude_group_ids,
66 66 c.repo_groups)
67 67 c.repo_groups_choices = map(lambda k: k[0], c.repo_groups)
68 68
69 69 parent_group = c.repo_group.parent_group
70 70
71 71 add_parent_group = (parent_group and (
72 72 parent_group.group_id not in c.repo_groups_choices))
73 73 if add_parent_group:
74 74 c.repo_groups_choices.append(parent_group.group_id)
75 75 c.repo_groups.append(RepoGroup._generate_choice(parent_group))
76 76 return c
77 77
78 78 def _can_create_repo_group(self, parent_group_id=None):
79 79 is_admin = HasPermissionAll('hg.admin')('group create controller')
80 80 create_repo_group = HasPermissionAll(
81 81 'hg.repogroup.create.true')('group create controller')
82 82 if is_admin or (create_repo_group and not parent_group_id):
83 83 # we're global admin, or we have global repo group create
84 84 # permission
85 85 # we're ok and we can create TOP level groups
86 86 return True
87 87 elif parent_group_id:
88 88 # we check the permission if we can write to parent group
89 89 group = RepoGroup.get(parent_group_id)
90 90 group_name = group.group_name if group else None
91 91 if HasRepoGroupPermissionAny('group.admin')(
92 92 group_name, 'check if user is an admin of group'):
93 93 # we're an admin of passed in group, we're ok.
94 94 return True
95 95 else:
96 96 return False
97 97 return False
98 98
99 99 def _get_schema(self, c, old_values=None):
100 100 return repo_group_schema.RepoGroupSettingsSchema().bind(
101 101 repo_group_repo_group_options=c.repo_groups_choices,
102 102 repo_group_repo_group_items=c.repo_groups,
103 103
104 104 # user caller
105 105 user=self._rhodecode_user,
106 106 old_values=old_values
107 107 )
108 108
109 109 @LoginRequired()
110 110 @HasRepoGroupPermissionAnyDecorator('group.admin')
111 111 @view_config(
112 112 route_name='edit_repo_group', request_method='GET',
113 113 renderer='rhodecode:templates/admin/repo_groups/repo_group_edit.mako')
114 114 def edit_settings(self):
115 115 c = self.load_default_context()
116 116 c.active = 'settings'
117 117
118 118 defaults = RepoGroupModel()._get_defaults(self.db_repo_group_name)
119 119 defaults['repo_group_owner'] = defaults['user']
120 120
121 121 schema = self._get_schema(c)
122 122 c.form = RcForm(schema, appstruct=defaults)
123 123 return self._get_template_context(c)
124 124
125 125 @LoginRequired()
126 126 @HasRepoGroupPermissionAnyDecorator('group.admin')
127 127 @CSRFRequired()
128 128 @view_config(
129 129 route_name='edit_repo_group', request_method='POST',
130 130 renderer='rhodecode:templates/admin/repo_groups/repo_group_edit.mako')
131 131 def edit_settings_update(self):
132 132 _ = self.request.translate
133 133 c = self.load_default_context()
134 134 c.active = 'settings'
135 135
136 136 old_repo_group_name = self.db_repo_group_name
137 137 new_repo_group_name = old_repo_group_name
138 138
139 139 old_values = RepoGroupModel()._get_defaults(self.db_repo_group_name)
140 140 schema = self._get_schema(c, old_values=old_values)
141 141
142 142 c.form = RcForm(schema)
143 143 pstruct = self.request.POST.items()
144 144
145 145 try:
146 146 schema_data = c.form.validate(pstruct)
147 147 except deform.ValidationFailure as err_form:
148 148 return self._get_template_context(c)
149 149
150 150 # data is now VALID, proceed with updates
151 151 # save validated data back into the updates dict
152 152 validated_updates = dict(
153 153 group_name=schema_data['repo_group']['repo_group_name_without_group'],
154 154 group_parent_id=schema_data['repo_group']['repo_group_id'],
155 155 user=schema_data['repo_group_owner'],
156 156 group_description=schema_data['repo_group_description'],
157 157 enable_locking=schema_data['repo_group_enable_locking'],
158 158 )
159 159
160 160 try:
161 161 RepoGroupModel().update(self.db_repo_group, validated_updates)
162 162
163 163 audit_logger.store_web(
164 164 'repo_group.edit', action_data={'old_data': old_values},
165 165 user=c.rhodecode_user)
166 166
167 167 Session().commit()
168 168
169 169 # use the new full name for redirect once we know we updated
170 170 # the name on filesystem and in DB
171 171 new_repo_group_name = schema_data['repo_group']['repo_group_name_with_group']
172 172
173 173 h.flash(_('Repository Group `{}` updated successfully').format(
174 174 old_repo_group_name), category='success')
175 175
176 176 except Exception:
177 177 log.exception("Exception during update or repository group")
178 178 h.flash(_('Error occurred during update of repository group %s')
179 179 % old_repo_group_name, category='error')
180 180
181 181 name_changed = old_repo_group_name != new_repo_group_name
182 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 187 owner = User.get_by_username(schema_data['repo_group_owner'])
184 188 owner_id = owner.user_id if owner else self._rhodecode_user.user_id
185 events.trigger(events.UserPermissionsChange([
186 self._rhodecode_user.user_id, owner_id]))
189 affected_user_ids.extend([self._rhodecode_user.user_id, owner_id])
190 events.trigger(events.UserPermissionsChange(affected_user_ids))
187 191
188 192 raise HTTPFound(
189 193 h.route_path('edit_repo_group', repo_group_name=new_repo_group_name))
@@ -1,263 +1,270 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2011-2018 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 21 import logging
22 22 import datetime
23 23 import formencode
24 24 import formencode.htmlfill
25 25
26 26 from pyramid.httpexceptions import HTTPFound
27 27 from pyramid.view import view_config
28 28 from pyramid.renderers import render
29 29 from pyramid.response import Response
30 30
31 31 from rhodecode import events
32 32 from rhodecode.apps._base import RepoAppView, DataGridAppView
33 33 from rhodecode.lib.auth import (
34 34 LoginRequired, HasRepoPermissionAnyDecorator, NotAnonymous,
35 35 HasRepoPermissionAny, HasPermissionAnyDecorator, CSRFRequired)
36 36 import rhodecode.lib.helpers as h
37 37 from rhodecode.lib.celerylib.utils import get_task_id
38 38 from rhodecode.model.db import coalesce, or_, Repository, RepoGroup
39 39 from rhodecode.model.repo import RepoModel
40 40 from rhodecode.model.forms import RepoForkForm
41 41 from rhodecode.model.scm import ScmModel, RepoGroupList
42 42 from rhodecode.lib.utils2 import safe_int, safe_unicode
43 43
44 44 log = logging.getLogger(__name__)
45 45
46 46
47 47 class RepoForksView(RepoAppView, DataGridAppView):
48 48
49 49 def load_default_context(self):
50 50 c = self._get_local_tmpl_context(include_app_defaults=True)
51 51 c.rhodecode_repo = self.rhodecode_vcs_repo
52 52
53 53 acl_groups = RepoGroupList(
54 54 RepoGroup.query().all(),
55 55 perm_set=['group.write', 'group.admin'])
56 56 c.repo_groups = RepoGroup.groups_choices(groups=acl_groups)
57 57 c.repo_groups_choices = map(lambda k: safe_unicode(k[0]), c.repo_groups)
58 58 choices, c.landing_revs = ScmModel().get_repo_landing_revs(
59 59 self.request.translate)
60 60 c.landing_revs_choices = choices
61 61 c.personal_repo_group = c.rhodecode_user.personal_repo_group
62 62
63 63 return c
64 64
65 65 @LoginRequired()
66 66 @HasRepoPermissionAnyDecorator(
67 67 'repository.read', 'repository.write', 'repository.admin')
68 68 @view_config(
69 69 route_name='repo_forks_show_all', request_method='GET',
70 70 renderer='rhodecode:templates/forks/forks.mako')
71 71 def repo_forks_show_all(self):
72 72 c = self.load_default_context()
73 73 return self._get_template_context(c)
74 74
75 75 @LoginRequired()
76 76 @HasRepoPermissionAnyDecorator(
77 77 'repository.read', 'repository.write', 'repository.admin')
78 78 @view_config(
79 79 route_name='repo_forks_data', request_method='GET',
80 80 renderer='json_ext', xhr=True)
81 81 def repo_forks_data(self):
82 82 _ = self.request.translate
83 83 self.load_default_context()
84 84 column_map = {
85 85 'fork_name': 'repo_name',
86 86 'fork_date': 'created_on',
87 87 'last_activity': 'updated_on'
88 88 }
89 89 draw, start, limit = self._extract_chunk(self.request)
90 90 search_q, order_by, order_dir = self._extract_ordering(
91 91 self.request, column_map=column_map)
92 92
93 93 acl_check = HasRepoPermissionAny(
94 94 'repository.read', 'repository.write', 'repository.admin')
95 95 repo_id = self.db_repo.repo_id
96 96 allowed_ids = [-1]
97 97 for f in Repository.query().filter(Repository.fork_id == repo_id):
98 98 if acl_check(f.repo_name, 'get forks check'):
99 99 allowed_ids.append(f.repo_id)
100 100
101 101 forks_data_total_count = Repository.query()\
102 102 .filter(Repository.fork_id == repo_id)\
103 103 .filter(Repository.repo_id.in_(allowed_ids))\
104 104 .count()
105 105
106 106 # json generate
107 107 base_q = Repository.query()\
108 108 .filter(Repository.fork_id == repo_id)\
109 109 .filter(Repository.repo_id.in_(allowed_ids))\
110 110
111 111 if search_q:
112 112 like_expression = u'%{}%'.format(safe_unicode(search_q))
113 113 base_q = base_q.filter(or_(
114 114 Repository.repo_name.ilike(like_expression),
115 115 Repository.description.ilike(like_expression),
116 116 ))
117 117
118 118 forks_data_total_filtered_count = base_q.count()
119 119
120 120 sort_col = getattr(Repository, order_by, None)
121 121 if sort_col:
122 122 if order_dir == 'asc':
123 123 # handle null values properly to order by NULL last
124 124 if order_by in ['last_activity']:
125 125 sort_col = coalesce(sort_col, datetime.date.max)
126 126 sort_col = sort_col.asc()
127 127 else:
128 128 # handle null values properly to order by NULL last
129 129 if order_by in ['last_activity']:
130 130 sort_col = coalesce(sort_col, datetime.date.min)
131 131 sort_col = sort_col.desc()
132 132
133 133 base_q = base_q.order_by(sort_col)
134 134 base_q = base_q.offset(start).limit(limit)
135 135
136 136 fork_list = base_q.all()
137 137
138 138 def fork_actions(fork):
139 139 url_link = h.route_path(
140 140 'repo_compare',
141 141 repo_name=fork.repo_name,
142 142 source_ref_type=self.db_repo.landing_rev[0],
143 143 source_ref=self.db_repo.landing_rev[1],
144 144 target_ref_type=self.db_repo.landing_rev[0],
145 145 target_ref=self.db_repo.landing_rev[1],
146 146 _query=dict(merge=1, target_repo=f.repo_name))
147 147 return h.link_to(_('Compare fork'), url_link, class_='btn-link')
148 148
149 149 def fork_name(fork):
150 150 return h.link_to(fork.repo_name,
151 151 h.route_path('repo_summary', repo_name=fork.repo_name))
152 152
153 153 forks_data = []
154 154 for fork in fork_list:
155 155 forks_data.append({
156 156 "username": h.gravatar_with_user(self.request, fork.user.username),
157 157 "fork_name": fork_name(fork),
158 158 "description": fork.description_safe,
159 159 "fork_date": h.age_component(fork.created_on, time_is_local=True),
160 160 "last_activity": h.format_date(fork.updated_on),
161 161 "action": fork_actions(fork),
162 162 })
163 163
164 164 data = ({
165 165 'draw': draw,
166 166 'data': forks_data,
167 167 'recordsTotal': forks_data_total_count,
168 168 'recordsFiltered': forks_data_total_filtered_count,
169 169 })
170 170
171 171 return data
172 172
173 173 @LoginRequired()
174 174 @NotAnonymous()
175 175 @HasPermissionAnyDecorator('hg.admin', 'hg.fork.repository')
176 176 @HasRepoPermissionAnyDecorator(
177 177 'repository.read', 'repository.write', 'repository.admin')
178 178 @view_config(
179 179 route_name='repo_fork_new', request_method='GET',
180 180 renderer='rhodecode:templates/forks/forks.mako')
181 181 def repo_fork_new(self):
182 182 c = self.load_default_context()
183 183
184 184 defaults = RepoModel()._get_defaults(self.db_repo_name)
185 185 # alter the description to indicate a fork
186 186 defaults['description'] = (
187 187 'fork of repository: %s \n%s' % (
188 188 defaults['repo_name'], defaults['description']))
189 189 # add suffix to fork
190 190 defaults['repo_name'] = '%s-fork' % defaults['repo_name']
191 191
192 192 data = render('rhodecode:templates/forks/fork.mako',
193 193 self._get_template_context(c), self.request)
194 194 html = formencode.htmlfill.render(
195 195 data,
196 196 defaults=defaults,
197 197 encoding="UTF-8",
198 198 force_defaults=False
199 199 )
200 200 return Response(html)
201 201
202 202 @LoginRequired()
203 203 @NotAnonymous()
204 204 @HasPermissionAnyDecorator('hg.admin', 'hg.fork.repository')
205 205 @HasRepoPermissionAnyDecorator(
206 206 'repository.read', 'repository.write', 'repository.admin')
207 207 @CSRFRequired()
208 208 @view_config(
209 209 route_name='repo_fork_create', request_method='POST',
210 210 renderer='rhodecode:templates/forks/fork.mako')
211 211 def repo_fork_create(self):
212 212 _ = self.request.translate
213 213 c = self.load_default_context()
214 214
215 215 _form = RepoForkForm(self.request.translate, old_data={'repo_type': self.db_repo.repo_type},
216 216 repo_groups=c.repo_groups_choices,
217 217 landing_revs=c.landing_revs_choices)()
218 218 post_data = dict(self.request.POST)
219 219
220 220 # forbid injecting other repo by forging a request
221 221 post_data['fork_parent_id'] = self.db_repo.repo_id
222 222
223 223 form_result = {}
224 224 task_id = None
225 225 try:
226 226 form_result = _form.to_python(post_data)
227 copy_permissions = form_result.get('copy_permissions')
227 228 # create fork is done sometimes async on celery, db transaction
228 229 # management is handled there.
229 230 task = RepoModel().create_fork(
230 231 form_result, c.rhodecode_user.user_id)
231 232
232 233 task_id = get_task_id(task)
233 234 except formencode.Invalid as errors:
234 235 c.rhodecode_db_repo = self.db_repo
235 236
236 237 data = render('rhodecode:templates/forks/fork.mako',
237 238 self._get_template_context(c), self.request)
238 239 html = formencode.htmlfill.render(
239 240 data,
240 241 defaults=errors.value,
241 242 errors=errors.error_dict or {},
242 243 prefix_error=False,
243 244 encoding="UTF-8",
244 245 force_defaults=False
245 246 )
246 247 return Response(html)
247 248 except Exception:
248 249 log.exception(
249 u'Exception while trying to fork the repository %s',
250 self.db_repo_name)
251 msg = (
252 _('An error occurred during repository forking %s') % (
253 self.db_repo_name, ))
250 u'Exception while trying to fork the repository %s', self.db_repo_name)
251 msg = _('An error occurred during repository forking %s') % (self.db_repo_name, )
254 252 h.flash(msg, category='error')
253 raise HTTPFound(h.route_path('home'))
255 254
256 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 268 raise HTTPFound(
261 h.route_path('repo_creating',
262 repo_name=repo_name,
269 h.route_path('repo_creating', repo_name=repo_name,
263 270 _query=dict(task_id=task_id)))
@@ -1,262 +1,266 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2011-2018 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 21 import logging
22 22
23 23 import deform
24 24 from pyramid.httpexceptions import HTTPFound
25 25 from pyramid.view import view_config
26 26
27 27 from rhodecode import events
28 28 from rhodecode.apps._base import RepoAppView
29 29 from rhodecode.forms import RcForm
30 30 from rhodecode.lib import helpers as h
31 31 from rhodecode.lib import audit_logger
32 32 from rhodecode.lib.auth import (
33 33 LoginRequired, HasRepoPermissionAnyDecorator, CSRFRequired)
34 34 from rhodecode.model.db import RepositoryField, RepoGroup, Repository, User
35 35 from rhodecode.model.meta import Session
36 36 from rhodecode.model.repo import RepoModel
37 37 from rhodecode.model.scm import RepoGroupList, ScmModel
38 38 from rhodecode.model.validation_schema.schemas import repo_schema
39 39
40 40 log = logging.getLogger(__name__)
41 41
42 42
43 43 class RepoSettingsView(RepoAppView):
44 44
45 45 def load_default_context(self):
46 46 c = self._get_local_tmpl_context()
47 47
48 48 acl_groups = RepoGroupList(
49 49 RepoGroup.query().all(),
50 50 perm_set=['group.write', 'group.admin'])
51 51 c.repo_groups = RepoGroup.groups_choices(groups=acl_groups)
52 52 c.repo_groups_choices = map(lambda k: k[0], c.repo_groups)
53 53
54 54 # in case someone no longer have a group.write access to a repository
55 55 # pre fill the list with this entry, we don't care if this is the same
56 56 # but it will allow saving repo data properly.
57 57 repo_group = self.db_repo.group
58 58 if repo_group and repo_group.group_id not in c.repo_groups_choices:
59 59 c.repo_groups_choices.append(repo_group.group_id)
60 60 c.repo_groups.append(RepoGroup._generate_choice(repo_group))
61 61
62 62 if c.repository_requirements_missing or self.rhodecode_vcs_repo is None:
63 63 # we might be in missing requirement state, so we load things
64 64 # without touching scm_instance()
65 65 c.landing_revs_choices, c.landing_revs = \
66 66 ScmModel().get_repo_landing_revs(self.request.translate)
67 67 else:
68 68 c.landing_revs_choices, c.landing_revs = \
69 69 ScmModel().get_repo_landing_revs(
70 70 self.request.translate, self.db_repo)
71 71
72 72 c.personal_repo_group = c.auth_user.personal_repo_group
73 73 c.repo_fields = RepositoryField.query()\
74 74 .filter(RepositoryField.repository == self.db_repo).all()
75 75 return c
76 76
77 77 def _get_schema(self, c, old_values=None):
78 78 return repo_schema.RepoSettingsSchema().bind(
79 79 repo_type=self.db_repo.repo_type,
80 80 repo_type_options=[self.db_repo.repo_type],
81 81 repo_ref_options=c.landing_revs_choices,
82 82 repo_ref_items=c.landing_revs,
83 83 repo_repo_group_options=c.repo_groups_choices,
84 84 repo_repo_group_items=c.repo_groups,
85 85 # user caller
86 86 user=self._rhodecode_user,
87 87 old_values=old_values
88 88 )
89 89
90 90 @LoginRequired()
91 91 @HasRepoPermissionAnyDecorator('repository.admin')
92 92 @view_config(
93 93 route_name='edit_repo', request_method='GET',
94 94 renderer='rhodecode:templates/admin/repos/repo_edit.mako')
95 95 def edit_settings(self):
96 96 c = self.load_default_context()
97 97 c.active = 'settings'
98 98
99 99 defaults = RepoModel()._get_defaults(self.db_repo_name)
100 100 defaults['repo_owner'] = defaults['user']
101 101 defaults['repo_landing_commit_ref'] = defaults['repo_landing_rev']
102 102
103 103 schema = self._get_schema(c)
104 104 c.form = RcForm(schema, appstruct=defaults)
105 105 return self._get_template_context(c)
106 106
107 107 @LoginRequired()
108 108 @HasRepoPermissionAnyDecorator('repository.admin')
109 109 @CSRFRequired()
110 110 @view_config(
111 111 route_name='edit_repo', request_method='POST',
112 112 renderer='rhodecode:templates/admin/repos/repo_edit.mako')
113 113 def edit_settings_update(self):
114 114 _ = self.request.translate
115 115 c = self.load_default_context()
116 116 c.active = 'settings'
117 117 old_repo_name = self.db_repo_name
118 118
119 119 old_values = self.db_repo.get_api_data()
120 120 schema = self._get_schema(c, old_values=old_values)
121 121
122 122 c.form = RcForm(schema)
123 123 pstruct = self.request.POST.items()
124 124 pstruct.append(('repo_type', self.db_repo.repo_type))
125 125 try:
126 126 schema_data = c.form.validate(pstruct)
127 127 except deform.ValidationFailure as err_form:
128 128 return self._get_template_context(c)
129 129
130 130 # data is now VALID, proceed with updates
131 131 # save validated data back into the updates dict
132 132 validated_updates = dict(
133 133 repo_name=schema_data['repo_group']['repo_name_without_group'],
134 134 repo_group=schema_data['repo_group']['repo_group_id'],
135 135
136 136 user=schema_data['repo_owner'],
137 137 repo_description=schema_data['repo_description'],
138 138 repo_private=schema_data['repo_private'],
139 139 clone_uri=schema_data['repo_clone_uri'],
140 140 push_uri=schema_data['repo_push_uri'],
141 141 repo_landing_rev=schema_data['repo_landing_commit_ref'],
142 142 repo_enable_statistics=schema_data['repo_enable_statistics'],
143 143 repo_enable_locking=schema_data['repo_enable_locking'],
144 144 repo_enable_downloads=schema_data['repo_enable_downloads'],
145 145 )
146 146 # detect if SYNC URI changed, if we get OLD means we keep old values
147 147 if schema_data['repo_clone_uri_change'] == 'OLD':
148 148 validated_updates['clone_uri'] = self.db_repo.clone_uri
149 149
150 150 if schema_data['repo_push_uri_change'] == 'OLD':
151 151 validated_updates['push_uri'] = self.db_repo.push_uri
152 152
153 153 # use the new full name for redirect
154 154 new_repo_name = schema_data['repo_group']['repo_name_with_group']
155 155
156 156 # save extra fields into our validated data
157 157 for key, value in pstruct:
158 158 if key.startswith(RepositoryField.PREFIX):
159 159 validated_updates[key] = value
160 160
161 161 try:
162 162 RepoModel().update(self.db_repo, **validated_updates)
163 163 ScmModel().mark_for_invalidation(new_repo_name)
164 164
165 165 audit_logger.store_web(
166 166 'repo.edit', action_data={'old_data': old_values},
167 167 user=self._rhodecode_user, repo=self.db_repo)
168 168
169 169 Session().commit()
170 170
171 h.flash(_('Repository `{}` updated successfully').format(
172 old_repo_name), category='success')
171 h.flash(_('Repository `{}` updated successfully').format(old_repo_name),
172 category='success')
173 173 except Exception:
174 174 log.exception("Exception during update of repository")
175 175 h.flash(_('Error occurred during update of repository {}').format(
176 176 old_repo_name), category='error')
177 177
178 178 name_changed = old_repo_name != new_repo_name
179 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 184 owner = User.get_by_username(schema_data['repo_owner'])
181 185 owner_id = owner.user_id if owner else self._rhodecode_user.user_id
182 events.trigger(events.UserPermissionsChange([
183 self._rhodecode_user.user_id, owner_id]))
186 affected_user_ids.extend([self._rhodecode_user.user_id, owner_id])
187 events.trigger(events.UserPermissionsChange(affected_user_ids))
184 188
185 189 raise HTTPFound(
186 190 h.route_path('edit_repo', repo_name=new_repo_name))
187 191
188 192 @LoginRequired()
189 193 @HasRepoPermissionAnyDecorator('repository.write', 'repository.admin')
190 194 @view_config(
191 195 route_name='repo_edit_toggle_locking', request_method='GET',
192 196 renderer='rhodecode:templates/admin/repos/repo_edit.mako')
193 197 def toggle_locking(self):
194 198 """
195 199 Toggle locking of repository by simple GET call to url
196 200 """
197 201 _ = self.request.translate
198 202 repo = self.db_repo
199 203
200 204 try:
201 205 if repo.enable_locking:
202 206 if repo.locked[0]:
203 207 Repository.unlock(repo)
204 208 action = _('Unlocked')
205 209 else:
206 210 Repository.lock(
207 211 repo, self._rhodecode_user.user_id,
208 212 lock_reason=Repository.LOCK_WEB)
209 213 action = _('Locked')
210 214
211 215 h.flash(_('Repository has been %s') % action,
212 216 category='success')
213 217 except Exception:
214 218 log.exception("Exception during unlocking")
215 219 h.flash(_('An error occurred during unlocking'),
216 220 category='error')
217 221 raise HTTPFound(
218 222 h.route_path('repo_summary', repo_name=self.db_repo_name))
219 223
220 224 @LoginRequired()
221 225 @HasRepoPermissionAnyDecorator('repository.admin')
222 226 @view_config(
223 227 route_name='edit_repo_statistics', request_method='GET',
224 228 renderer='rhodecode:templates/admin/repos/repo_edit.mako')
225 229 def edit_statistics_form(self):
226 230 c = self.load_default_context()
227 231
228 232 if self.db_repo.stats:
229 233 # this is on what revision we ended up so we add +1 for count
230 234 last_rev = self.db_repo.stats.stat_on_revision + 1
231 235 else:
232 236 last_rev = 0
233 237
234 238 c.active = 'statistics'
235 239 c.stats_revision = last_rev
236 240 c.repo_last_rev = self.rhodecode_vcs_repo.count()
237 241
238 242 if last_rev == 0 or c.repo_last_rev == 0:
239 243 c.stats_percentage = 0
240 244 else:
241 245 c.stats_percentage = '%.2f' % (
242 246 (float((last_rev)) / c.repo_last_rev) * 100)
243 247 return self._get_template_context(c)
244 248
245 249 @LoginRequired()
246 250 @HasRepoPermissionAnyDecorator('repository.admin')
247 251 @CSRFRequired()
248 252 @view_config(
249 253 route_name='edit_repo_statistics_reset', request_method='POST',
250 254 renderer='rhodecode:templates/admin/repos/repo_edit.mako')
251 255 def repo_statistics_reset(self):
252 256 _ = self.request.translate
253 257
254 258 try:
255 259 RepoModel().delete_stats(self.db_repo_name)
256 260 Session().commit()
257 261 except Exception:
258 262 log.exception('Edit statistics failure')
259 263 h.flash(_('An error occurred during deletion of repository stats'),
260 264 category='error')
261 265 raise HTTPFound(
262 266 h.route_path('edit_repo_statistics', repo_name=self.db_repo_name))
@@ -1,4721 +1,4754 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2010-2018 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 21 """
22 22 Database Models for RhodeCode Enterprise
23 23 """
24 24
25 25 import re
26 26 import os
27 27 import time
28 28 import hashlib
29 29 import logging
30 30 import datetime
31 31 import warnings
32 32 import ipaddress
33 33 import functools
34 34 import traceback
35 35 import collections
36 36
37 37 from sqlalchemy import (
38 38 or_, and_, not_, func, TypeDecorator, event,
39 39 Index, Sequence, UniqueConstraint, ForeignKey, CheckConstraint, Column,
40 40 Boolean, String, Unicode, UnicodeText, DateTime, Integer, LargeBinary,
41 41 Text, Float, PickleType)
42 42 from sqlalchemy.sql.expression import true, false
43 43 from sqlalchemy.sql.functions import coalesce, count # pragma: no cover
44 44 from sqlalchemy.orm import (
45 45 relationship, joinedload, class_mapper, validates, aliased)
46 46 from sqlalchemy.ext.declarative import declared_attr
47 47 from sqlalchemy.ext.hybrid import hybrid_property
48 48 from sqlalchemy.exc import IntegrityError # pragma: no cover
49 49 from sqlalchemy.dialects.mysql import LONGTEXT
50 50 from zope.cachedescriptors.property import Lazy as LazyProperty
51 51
52 52 from pyramid.threadlocal import get_current_request
53 53
54 54 from rhodecode.translation import _
55 55 from rhodecode.lib.vcs import get_vcs_instance
56 56 from rhodecode.lib.vcs.backends.base import EmptyCommit, Reference
57 57 from rhodecode.lib.utils2 import (
58 58 str2bool, safe_str, get_commit_safe, safe_unicode, sha1_safe,
59 59 time_to_datetime, aslist, Optional, safe_int, get_clone_url, AttributeDict,
60 60 glob2re, StrictAttributeDict, cleaned_uri)
61 61 from rhodecode.lib.jsonalchemy import MutationObj, MutationList, JsonType, \
62 62 JsonRaw
63 63 from rhodecode.lib.ext_json import json
64 64 from rhodecode.lib.caching_query import FromCache
65 65 from rhodecode.lib.encrypt import AESCipher
66 66
67 67 from rhodecode.model.meta import Base, Session
68 68
69 69 URL_SEP = '/'
70 70 log = logging.getLogger(__name__)
71 71
72 72 # =============================================================================
73 73 # BASE CLASSES
74 74 # =============================================================================
75 75
76 76 # this is propagated from .ini file rhodecode.encrypted_values.secret or
77 77 # beaker.session.secret if first is not set.
78 78 # and initialized at environment.py
79 79 ENCRYPTION_KEY = None
80 80
81 81 # used to sort permissions by types, '#' used here is not allowed to be in
82 82 # usernames, and it's very early in sorted string.printable table.
83 83 PERMISSION_TYPE_SORT = {
84 84 'admin': '####',
85 85 'write': '###',
86 86 'read': '##',
87 87 'none': '#',
88 88 }
89 89
90 90
91 91 def display_user_sort(obj):
92 92 """
93 93 Sort function used to sort permissions in .permissions() function of
94 94 Repository, RepoGroup, UserGroup. Also it put the default user in front
95 95 of all other resources
96 96 """
97 97
98 98 if obj.username == User.DEFAULT_USER:
99 99 return '#####'
100 100 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
101 101 return prefix + obj.username
102 102
103 103
104 104 def display_user_group_sort(obj):
105 105 """
106 106 Sort function used to sort permissions in .permissions() function of
107 107 Repository, RepoGroup, UserGroup. Also it put the default user in front
108 108 of all other resources
109 109 """
110 110
111 111 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
112 112 return prefix + obj.users_group_name
113 113
114 114
115 115 def _hash_key(k):
116 116 return sha1_safe(k)
117 117
118 118
119 119 def in_filter_generator(qry, items, limit=500):
120 120 """
121 121 Splits IN() into multiple with OR
122 122 e.g.::
123 123 cnt = Repository.query().filter(
124 124 or_(
125 125 *in_filter_generator(Repository.repo_id, range(100000))
126 126 )).count()
127 127 """
128 128 if not items:
129 129 # empty list will cause empty query which might cause security issues
130 130 # this can lead to hidden unpleasant results
131 131 items = [-1]
132 132
133 133 parts = []
134 134 for chunk in xrange(0, len(items), limit):
135 135 parts.append(
136 136 qry.in_(items[chunk: chunk + limit])
137 137 )
138 138
139 139 return parts
140 140
141 141
142 142 base_table_args = {
143 143 'extend_existing': True,
144 144 'mysql_engine': 'InnoDB',
145 145 'mysql_charset': 'utf8',
146 146 'sqlite_autoincrement': True
147 147 }
148 148
149 149
150 150 class EncryptedTextValue(TypeDecorator):
151 151 """
152 152 Special column for encrypted long text data, use like::
153 153
154 154 value = Column("encrypted_value", EncryptedValue(), nullable=False)
155 155
156 156 This column is intelligent so if value is in unencrypted form it return
157 157 unencrypted form, but on save it always encrypts
158 158 """
159 159 impl = Text
160 160
161 161 def process_bind_param(self, value, dialect):
162 162 if not value:
163 163 return value
164 164 if value.startswith('enc$aes$') or value.startswith('enc$aes_hmac$'):
165 165 # protect against double encrypting if someone manually starts
166 166 # doing
167 167 raise ValueError('value needs to be in unencrypted format, ie. '
168 168 'not starting with enc$aes')
169 169 return 'enc$aes_hmac$%s' % AESCipher(
170 170 ENCRYPTION_KEY, hmac=True).encrypt(value)
171 171
172 172 def process_result_value(self, value, dialect):
173 173 import rhodecode
174 174
175 175 if not value:
176 176 return value
177 177
178 178 parts = value.split('$', 3)
179 179 if not len(parts) == 3:
180 180 # probably not encrypted values
181 181 return value
182 182 else:
183 183 if parts[0] != 'enc':
184 184 # parts ok but without our header ?
185 185 return value
186 186 enc_strict_mode = str2bool(rhodecode.CONFIG.get(
187 187 'rhodecode.encrypted_values.strict') or True)
188 188 # at that stage we know it's our encryption
189 189 if parts[1] == 'aes':
190 190 decrypted_data = AESCipher(ENCRYPTION_KEY).decrypt(parts[2])
191 191 elif parts[1] == 'aes_hmac':
192 192 decrypted_data = AESCipher(
193 193 ENCRYPTION_KEY, hmac=True,
194 194 strict_verification=enc_strict_mode).decrypt(parts[2])
195 195 else:
196 196 raise ValueError(
197 197 'Encryption type part is wrong, must be `aes` '
198 198 'or `aes_hmac`, got `%s` instead' % (parts[1]))
199 199 return decrypted_data
200 200
201 201
202 202 class BaseModel(object):
203 203 """
204 204 Base Model for all classes
205 205 """
206 206
207 207 @classmethod
208 208 def _get_keys(cls):
209 209 """return column names for this model """
210 210 return class_mapper(cls).c.keys()
211 211
212 212 def get_dict(self):
213 213 """
214 214 return dict with keys and values corresponding
215 215 to this model data """
216 216
217 217 d = {}
218 218 for k in self._get_keys():
219 219 d[k] = getattr(self, k)
220 220
221 221 # also use __json__() if present to get additional fields
222 222 _json_attr = getattr(self, '__json__', None)
223 223 if _json_attr:
224 224 # update with attributes from __json__
225 225 if callable(_json_attr):
226 226 _json_attr = _json_attr()
227 227 for k, val in _json_attr.iteritems():
228 228 d[k] = val
229 229 return d
230 230
231 231 def get_appstruct(self):
232 232 """return list with keys and values tuples corresponding
233 233 to this model data """
234 234
235 235 lst = []
236 236 for k in self._get_keys():
237 237 lst.append((k, getattr(self, k),))
238 238 return lst
239 239
240 240 def populate_obj(self, populate_dict):
241 241 """populate model with data from given populate_dict"""
242 242
243 243 for k in self._get_keys():
244 244 if k in populate_dict:
245 245 setattr(self, k, populate_dict[k])
246 246
247 247 @classmethod
248 248 def query(cls):
249 249 return Session().query(cls)
250 250
251 251 @classmethod
252 252 def get(cls, id_):
253 253 if id_:
254 254 return cls.query().get(id_)
255 255
256 256 @classmethod
257 257 def get_or_404(cls, id_):
258 258 from pyramid.httpexceptions import HTTPNotFound
259 259
260 260 try:
261 261 id_ = int(id_)
262 262 except (TypeError, ValueError):
263 263 raise HTTPNotFound()
264 264
265 265 res = cls.query().get(id_)
266 266 if not res:
267 267 raise HTTPNotFound()
268 268 return res
269 269
270 270 @classmethod
271 271 def getAll(cls):
272 272 # deprecated and left for backward compatibility
273 273 return cls.get_all()
274 274
275 275 @classmethod
276 276 def get_all(cls):
277 277 return cls.query().all()
278 278
279 279 @classmethod
280 280 def delete(cls, id_):
281 281 obj = cls.query().get(id_)
282 282 Session().delete(obj)
283 283
284 284 @classmethod
285 285 def identity_cache(cls, session, attr_name, value):
286 286 exist_in_session = []
287 287 for (item_cls, pkey), instance in session.identity_map.items():
288 288 if cls == item_cls and getattr(instance, attr_name) == value:
289 289 exist_in_session.append(instance)
290 290 if exist_in_session:
291 291 if len(exist_in_session) == 1:
292 292 return exist_in_session[0]
293 293 log.exception(
294 294 'multiple objects with attr %s and '
295 295 'value %s found with same name: %r',
296 296 attr_name, value, exist_in_session)
297 297
298 298 def __repr__(self):
299 299 if hasattr(self, '__unicode__'):
300 300 # python repr needs to return str
301 301 try:
302 302 return safe_str(self.__unicode__())
303 303 except UnicodeDecodeError:
304 304 pass
305 305 return '<DB:%s>' % (self.__class__.__name__)
306 306
307 307
308 308 class RhodeCodeSetting(Base, BaseModel):
309 309 __tablename__ = 'rhodecode_settings'
310 310 __table_args__ = (
311 311 UniqueConstraint('app_settings_name'),
312 312 base_table_args
313 313 )
314 314
315 315 SETTINGS_TYPES = {
316 316 'str': safe_str,
317 317 'int': safe_int,
318 318 'unicode': safe_unicode,
319 319 'bool': str2bool,
320 320 'list': functools.partial(aslist, sep=',')
321 321 }
322 322 DEFAULT_UPDATE_URL = 'https://rhodecode.com/api/v1/info/versions'
323 323 GLOBAL_CONF_KEY = 'app_settings'
324 324
325 325 app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
326 326 app_settings_name = Column("app_settings_name", String(255), nullable=True, unique=None, default=None)
327 327 _app_settings_value = Column("app_settings_value", String(4096), nullable=True, unique=None, default=None)
328 328 _app_settings_type = Column("app_settings_type", String(255), nullable=True, unique=None, default=None)
329 329
330 330 def __init__(self, key='', val='', type='unicode'):
331 331 self.app_settings_name = key
332 332 self.app_settings_type = type
333 333 self.app_settings_value = val
334 334
335 335 @validates('_app_settings_value')
336 336 def validate_settings_value(self, key, val):
337 337 assert type(val) == unicode
338 338 return val
339 339
340 340 @hybrid_property
341 341 def app_settings_value(self):
342 342 v = self._app_settings_value
343 343 _type = self.app_settings_type
344 344 if _type:
345 345 _type = self.app_settings_type.split('.')[0]
346 346 # decode the encrypted value
347 347 if 'encrypted' in self.app_settings_type:
348 348 cipher = EncryptedTextValue()
349 349 v = safe_unicode(cipher.process_result_value(v, None))
350 350
351 351 converter = self.SETTINGS_TYPES.get(_type) or \
352 352 self.SETTINGS_TYPES['unicode']
353 353 return converter(v)
354 354
355 355 @app_settings_value.setter
356 356 def app_settings_value(self, val):
357 357 """
358 358 Setter that will always make sure we use unicode in app_settings_value
359 359
360 360 :param val:
361 361 """
362 362 val = safe_unicode(val)
363 363 # encode the encrypted value
364 364 if 'encrypted' in self.app_settings_type:
365 365 cipher = EncryptedTextValue()
366 366 val = safe_unicode(cipher.process_bind_param(val, None))
367 367 self._app_settings_value = val
368 368
369 369 @hybrid_property
370 370 def app_settings_type(self):
371 371 return self._app_settings_type
372 372
373 373 @app_settings_type.setter
374 374 def app_settings_type(self, val):
375 375 if val.split('.')[0] not in self.SETTINGS_TYPES:
376 376 raise Exception('type must be one of %s got %s'
377 377 % (self.SETTINGS_TYPES.keys(), val))
378 378 self._app_settings_type = val
379 379
380 380 @classmethod
381 381 def get_by_prefix(cls, prefix):
382 382 return RhodeCodeSetting.query()\
383 383 .filter(RhodeCodeSetting.app_settings_name.startswith(prefix))\
384 384 .all()
385 385
386 386 def __unicode__(self):
387 387 return u"<%s('%s:%s[%s]')>" % (
388 388 self.__class__.__name__,
389 389 self.app_settings_name, self.app_settings_value,
390 390 self.app_settings_type
391 391 )
392 392
393 393
394 394 class RhodeCodeUi(Base, BaseModel):
395 395 __tablename__ = 'rhodecode_ui'
396 396 __table_args__ = (
397 397 UniqueConstraint('ui_key'),
398 398 base_table_args
399 399 )
400 400
401 401 HOOK_REPO_SIZE = 'changegroup.repo_size'
402 402 # HG
403 403 HOOK_PRE_PULL = 'preoutgoing.pre_pull'
404 404 HOOK_PULL = 'outgoing.pull_logger'
405 405 HOOK_PRE_PUSH = 'prechangegroup.pre_push'
406 406 HOOK_PRETX_PUSH = 'pretxnchangegroup.pre_push'
407 407 HOOK_PUSH = 'changegroup.push_logger'
408 408 HOOK_PUSH_KEY = 'pushkey.key_push'
409 409
410 410 # TODO: johbo: Unify way how hooks are configured for git and hg,
411 411 # git part is currently hardcoded.
412 412
413 413 # SVN PATTERNS
414 414 SVN_BRANCH_ID = 'vcs_svn_branch'
415 415 SVN_TAG_ID = 'vcs_svn_tag'
416 416
417 417 ui_id = Column(
418 418 "ui_id", Integer(), nullable=False, unique=True, default=None,
419 419 primary_key=True)
420 420 ui_section = Column(
421 421 "ui_section", String(255), nullable=True, unique=None, default=None)
422 422 ui_key = Column(
423 423 "ui_key", String(255), nullable=True, unique=None, default=None)
424 424 ui_value = Column(
425 425 "ui_value", String(255), nullable=True, unique=None, default=None)
426 426 ui_active = Column(
427 427 "ui_active", Boolean(), nullable=True, unique=None, default=True)
428 428
429 429 def __repr__(self):
430 430 return '<%s[%s]%s=>%s]>' % (self.__class__.__name__, self.ui_section,
431 431 self.ui_key, self.ui_value)
432 432
433 433
434 434 class RepoRhodeCodeSetting(Base, BaseModel):
435 435 __tablename__ = 'repo_rhodecode_settings'
436 436 __table_args__ = (
437 437 UniqueConstraint(
438 438 'app_settings_name', 'repository_id',
439 439 name='uq_repo_rhodecode_setting_name_repo_id'),
440 440 base_table_args
441 441 )
442 442
443 443 repository_id = Column(
444 444 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
445 445 nullable=False)
446 446 app_settings_id = Column(
447 447 "app_settings_id", Integer(), nullable=False, unique=True,
448 448 default=None, primary_key=True)
449 449 app_settings_name = Column(
450 450 "app_settings_name", String(255), nullable=True, unique=None,
451 451 default=None)
452 452 _app_settings_value = Column(
453 453 "app_settings_value", String(4096), nullable=True, unique=None,
454 454 default=None)
455 455 _app_settings_type = Column(
456 456 "app_settings_type", String(255), nullable=True, unique=None,
457 457 default=None)
458 458
459 459 repository = relationship('Repository')
460 460
461 461 def __init__(self, repository_id, key='', val='', type='unicode'):
462 462 self.repository_id = repository_id
463 463 self.app_settings_name = key
464 464 self.app_settings_type = type
465 465 self.app_settings_value = val
466 466
467 467 @validates('_app_settings_value')
468 468 def validate_settings_value(self, key, val):
469 469 assert type(val) == unicode
470 470 return val
471 471
472 472 @hybrid_property
473 473 def app_settings_value(self):
474 474 v = self._app_settings_value
475 475 type_ = self.app_settings_type
476 476 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
477 477 converter = SETTINGS_TYPES.get(type_) or SETTINGS_TYPES['unicode']
478 478 return converter(v)
479 479
480 480 @app_settings_value.setter
481 481 def app_settings_value(self, val):
482 482 """
483 483 Setter that will always make sure we use unicode in app_settings_value
484 484
485 485 :param val:
486 486 """
487 487 self._app_settings_value = safe_unicode(val)
488 488
489 489 @hybrid_property
490 490 def app_settings_type(self):
491 491 return self._app_settings_type
492 492
493 493 @app_settings_type.setter
494 494 def app_settings_type(self, val):
495 495 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
496 496 if val not in SETTINGS_TYPES:
497 497 raise Exception('type must be one of %s got %s'
498 498 % (SETTINGS_TYPES.keys(), val))
499 499 self._app_settings_type = val
500 500
501 501 def __unicode__(self):
502 502 return u"<%s('%s:%s:%s[%s]')>" % (
503 503 self.__class__.__name__, self.repository.repo_name,
504 504 self.app_settings_name, self.app_settings_value,
505 505 self.app_settings_type
506 506 )
507 507
508 508
509 509 class RepoRhodeCodeUi(Base, BaseModel):
510 510 __tablename__ = 'repo_rhodecode_ui'
511 511 __table_args__ = (
512 512 UniqueConstraint(
513 513 'repository_id', 'ui_section', 'ui_key',
514 514 name='uq_repo_rhodecode_ui_repository_id_section_key'),
515 515 base_table_args
516 516 )
517 517
518 518 repository_id = Column(
519 519 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
520 520 nullable=False)
521 521 ui_id = Column(
522 522 "ui_id", Integer(), nullable=False, unique=True, default=None,
523 523 primary_key=True)
524 524 ui_section = Column(
525 525 "ui_section", String(255), nullable=True, unique=None, default=None)
526 526 ui_key = Column(
527 527 "ui_key", String(255), nullable=True, unique=None, default=None)
528 528 ui_value = Column(
529 529 "ui_value", String(255), nullable=True, unique=None, default=None)
530 530 ui_active = Column(
531 531 "ui_active", Boolean(), nullable=True, unique=None, default=True)
532 532
533 533 repository = relationship('Repository')
534 534
535 535 def __repr__(self):
536 536 return '<%s[%s:%s]%s=>%s]>' % (
537 537 self.__class__.__name__, self.repository.repo_name,
538 538 self.ui_section, self.ui_key, self.ui_value)
539 539
540 540
541 541 class User(Base, BaseModel):
542 542 __tablename__ = 'users'
543 543 __table_args__ = (
544 544 UniqueConstraint('username'), UniqueConstraint('email'),
545 545 Index('u_username_idx', 'username'),
546 546 Index('u_email_idx', 'email'),
547 547 base_table_args
548 548 )
549 549
550 550 DEFAULT_USER = 'default'
551 551 DEFAULT_USER_EMAIL = 'anonymous@rhodecode.org'
552 552 DEFAULT_GRAVATAR_URL = 'https://secure.gravatar.com/avatar/{md5email}?d=identicon&s={size}'
553 553
554 554 user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
555 555 username = Column("username", String(255), nullable=True, unique=None, default=None)
556 556 password = Column("password", String(255), nullable=True, unique=None, default=None)
557 557 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
558 558 admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
559 559 name = Column("firstname", String(255), nullable=True, unique=None, default=None)
560 560 lastname = Column("lastname", String(255), nullable=True, unique=None, default=None)
561 561 _email = Column("email", String(255), nullable=True, unique=None, default=None)
562 562 last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
563 563 last_activity = Column('last_activity', DateTime(timezone=False), nullable=True, unique=None, default=None)
564 564
565 565 extern_type = Column("extern_type", String(255), nullable=True, unique=None, default=None)
566 566 extern_name = Column("extern_name", String(255), nullable=True, unique=None, default=None)
567 567 _api_key = Column("api_key", String(255), nullable=True, unique=None, default=None)
568 568 inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
569 569 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
570 570 _user_data = Column("user_data", LargeBinary(), nullable=True) # JSON data
571 571
572 572 user_log = relationship('UserLog')
573 573 user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
574 574
575 575 repositories = relationship('Repository')
576 576 repository_groups = relationship('RepoGroup')
577 577 user_groups = relationship('UserGroup')
578 578
579 579 user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
580 580 followings = relationship('UserFollowing', primaryjoin='UserFollowing.user_id==User.user_id', cascade='all')
581 581
582 582 repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all')
583 583 repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all')
584 584 user_group_to_perm = relationship('UserUserGroupToPerm', primaryjoin='UserUserGroupToPerm.user_id==User.user_id', cascade='all')
585 585
586 586 group_member = relationship('UserGroupMember', cascade='all')
587 587
588 588 notifications = relationship('UserNotification', cascade='all')
589 589 # notifications assigned to this user
590 590 user_created_notifications = relationship('Notification', cascade='all')
591 591 # comments created by this user
592 592 user_comments = relationship('ChangesetComment', cascade='all')
593 593 # user profile extra info
594 594 user_emails = relationship('UserEmailMap', cascade='all')
595 595 user_ip_map = relationship('UserIpMap', cascade='all')
596 596 user_auth_tokens = relationship('UserApiKeys', cascade='all')
597 597 user_ssh_keys = relationship('UserSshKeys', cascade='all')
598 598
599 599 # gists
600 600 user_gists = relationship('Gist', cascade='all')
601 601 # user pull requests
602 602 user_pull_requests = relationship('PullRequest', cascade='all')
603 603 # external identities
604 604 extenal_identities = relationship(
605 605 'ExternalIdentity',
606 606 primaryjoin="User.user_id==ExternalIdentity.local_user_id",
607 607 cascade='all')
608 608 # review rules
609 609 user_review_rules = relationship('RepoReviewRuleUser', cascade='all')
610 610
611 611 def __unicode__(self):
612 612 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
613 613 self.user_id, self.username)
614 614
615 615 @hybrid_property
616 616 def email(self):
617 617 return self._email
618 618
619 619 @email.setter
620 620 def email(self, val):
621 621 self._email = val.lower() if val else None
622 622
623 623 @hybrid_property
624 624 def first_name(self):
625 625 from rhodecode.lib import helpers as h
626 626 if self.name:
627 627 return h.escape(self.name)
628 628 return self.name
629 629
630 630 @hybrid_property
631 631 def last_name(self):
632 632 from rhodecode.lib import helpers as h
633 633 if self.lastname:
634 634 return h.escape(self.lastname)
635 635 return self.lastname
636 636
637 637 @hybrid_property
638 638 def api_key(self):
639 639 """
640 640 Fetch if exist an auth-token with role ALL connected to this user
641 641 """
642 642 user_auth_token = UserApiKeys.query()\
643 643 .filter(UserApiKeys.user_id == self.user_id)\
644 644 .filter(or_(UserApiKeys.expires == -1,
645 645 UserApiKeys.expires >= time.time()))\
646 646 .filter(UserApiKeys.role == UserApiKeys.ROLE_ALL).first()
647 647 if user_auth_token:
648 648 user_auth_token = user_auth_token.api_key
649 649
650 650 return user_auth_token
651 651
652 652 @api_key.setter
653 653 def api_key(self, val):
654 654 # don't allow to set API key this is deprecated for now
655 655 self._api_key = None
656 656
657 657 @property
658 658 def reviewer_pull_requests(self):
659 659 return PullRequestReviewers.query() \
660 660 .options(joinedload(PullRequestReviewers.pull_request)) \
661 661 .filter(PullRequestReviewers.user_id == self.user_id) \
662 662 .all()
663 663
664 664 @property
665 665 def firstname(self):
666 666 # alias for future
667 667 return self.name
668 668
669 669 @property
670 670 def emails(self):
671 671 other = UserEmailMap.query()\
672 672 .filter(UserEmailMap.user == self) \
673 673 .order_by(UserEmailMap.email_id.asc()) \
674 674 .all()
675 675 return [self.email] + [x.email for x in other]
676 676
677 677 @property
678 678 def auth_tokens(self):
679 679 auth_tokens = self.get_auth_tokens()
680 680 return [x.api_key for x in auth_tokens]
681 681
682 682 def get_auth_tokens(self):
683 683 return UserApiKeys.query()\
684 684 .filter(UserApiKeys.user == self)\
685 685 .order_by(UserApiKeys.user_api_key_id.asc())\
686 686 .all()
687 687
688 688 @LazyProperty
689 689 def feed_token(self):
690 690 return self.get_feed_token()
691 691
692 692 def get_feed_token(self, cache=True):
693 693 feed_tokens = UserApiKeys.query()\
694 694 .filter(UserApiKeys.user == self)\
695 695 .filter(UserApiKeys.role == UserApiKeys.ROLE_FEED)
696 696 if cache:
697 697 feed_tokens = feed_tokens.options(
698 698 FromCache("sql_cache_short", "get_user_feed_token_%s" % self.user_id))
699 699
700 700 feed_tokens = feed_tokens.all()
701 701 if feed_tokens:
702 702 return feed_tokens[0].api_key
703 703 return 'NO_FEED_TOKEN_AVAILABLE'
704 704
705 705 @classmethod
706 706 def get(cls, user_id, cache=False):
707 707 if not user_id:
708 708 return
709 709
710 710 user = cls.query()
711 711 if cache:
712 712 user = user.options(
713 713 FromCache("sql_cache_short", "get_users_%s" % user_id))
714 714 return user.get(user_id)
715 715
716 716 @classmethod
717 717 def extra_valid_auth_tokens(cls, user, role=None):
718 718 tokens = UserApiKeys.query().filter(UserApiKeys.user == user)\
719 719 .filter(or_(UserApiKeys.expires == -1,
720 720 UserApiKeys.expires >= time.time()))
721 721 if role:
722 722 tokens = tokens.filter(or_(UserApiKeys.role == role,
723 723 UserApiKeys.role == UserApiKeys.ROLE_ALL))
724 724 return tokens.all()
725 725
726 726 def authenticate_by_token(self, auth_token, roles=None, scope_repo_id=None):
727 727 from rhodecode.lib import auth
728 728
729 729 log.debug('Trying to authenticate user: %s via auth-token, '
730 730 'and roles: %s', self, roles)
731 731
732 732 if not auth_token:
733 733 return False
734 734
735 735 crypto_backend = auth.crypto_backend()
736 736
737 737 roles = (roles or []) + [UserApiKeys.ROLE_ALL]
738 738 tokens_q = UserApiKeys.query()\
739 739 .filter(UserApiKeys.user_id == self.user_id)\
740 740 .filter(or_(UserApiKeys.expires == -1,
741 741 UserApiKeys.expires >= time.time()))
742 742
743 743 tokens_q = tokens_q.filter(UserApiKeys.role.in_(roles))
744 744
745 745 plain_tokens = []
746 746 hash_tokens = []
747 747
748 748 user_tokens = tokens_q.all()
749 749 log.debug('Found %s user tokens to check for authentication', len(user_tokens))
750 750 for token in user_tokens:
751 751 log.debug('AUTH_TOKEN: checking if user token with id `%s` matches',
752 752 token.user_api_key_id)
753 753 # verify scope first, since it's way faster than hash calculation of
754 754 # encrypted tokens
755 755 if token.repo_id:
756 756 # token has a scope, we need to verify it
757 757 if scope_repo_id != token.repo_id:
758 758 log.debug(
759 759 'AUTH_TOKEN: scope mismatch, token has a set repo scope: %s, '
760 760 'and calling scope is:%s, skipping further checks',
761 761 token.repo, scope_repo_id)
762 762 # token has a scope, and it doesn't match, skip token
763 763 continue
764 764
765 765 if token.api_key.startswith(crypto_backend.ENC_PREF):
766 766 hash_tokens.append(token.api_key)
767 767 else:
768 768 plain_tokens.append(token.api_key)
769 769
770 770 is_plain_match = auth_token in plain_tokens
771 771 if is_plain_match:
772 772 return True
773 773
774 774 for hashed in hash_tokens:
775 775 # NOTE(marcink): this is expensive to calculate, but most secure
776 776 match = crypto_backend.hash_check(auth_token, hashed)
777 777 if match:
778 778 return True
779 779
780 780 return False
781 781
782 782 @property
783 783 def ip_addresses(self):
784 784 ret = UserIpMap.query().filter(UserIpMap.user == self).all()
785 785 return [x.ip_addr for x in ret]
786 786
787 787 @property
788 788 def username_and_name(self):
789 789 return '%s (%s %s)' % (self.username, self.first_name, self.last_name)
790 790
791 791 @property
792 792 def username_or_name_or_email(self):
793 793 full_name = self.full_name if self.full_name is not ' ' else None
794 794 return self.username or full_name or self.email
795 795
796 796 @property
797 797 def full_name(self):
798 798 return '%s %s' % (self.first_name, self.last_name)
799 799
800 800 @property
801 801 def full_name_or_username(self):
802 802 return ('%s %s' % (self.first_name, self.last_name)
803 803 if (self.first_name and self.last_name) else self.username)
804 804
805 805 @property
806 806 def full_contact(self):
807 807 return '%s %s <%s>' % (self.first_name, self.last_name, self.email)
808 808
809 809 @property
810 810 def short_contact(self):
811 811 return '%s %s' % (self.first_name, self.last_name)
812 812
813 813 @property
814 814 def is_admin(self):
815 815 return self.admin
816 816
817 817 def AuthUser(self, **kwargs):
818 818 """
819 819 Returns instance of AuthUser for this user
820 820 """
821 821 from rhodecode.lib.auth import AuthUser
822 822 return AuthUser(user_id=self.user_id, username=self.username, **kwargs)
823 823
824 824 @hybrid_property
825 825 def user_data(self):
826 826 if not self._user_data:
827 827 return {}
828 828
829 829 try:
830 830 return json.loads(self._user_data)
831 831 except TypeError:
832 832 return {}
833 833
834 834 @user_data.setter
835 835 def user_data(self, val):
836 836 if not isinstance(val, dict):
837 837 raise Exception('user_data must be dict, got %s' % type(val))
838 838 try:
839 839 self._user_data = json.dumps(val)
840 840 except Exception:
841 841 log.error(traceback.format_exc())
842 842
843 843 @classmethod
844 844 def get_by_username(cls, username, case_insensitive=False,
845 845 cache=False, identity_cache=False):
846 846 session = Session()
847 847
848 848 if case_insensitive:
849 849 q = cls.query().filter(
850 850 func.lower(cls.username) == func.lower(username))
851 851 else:
852 852 q = cls.query().filter(cls.username == username)
853 853
854 854 if cache:
855 855 if identity_cache:
856 856 val = cls.identity_cache(session, 'username', username)
857 857 if val:
858 858 return val
859 859 else:
860 860 cache_key = "get_user_by_name_%s" % _hash_key(username)
861 861 q = q.options(
862 862 FromCache("sql_cache_short", cache_key))
863 863
864 864 return q.scalar()
865 865
866 866 @classmethod
867 867 def get_by_auth_token(cls, auth_token, cache=False):
868 868 q = UserApiKeys.query()\
869 869 .filter(UserApiKeys.api_key == auth_token)\
870 870 .filter(or_(UserApiKeys.expires == -1,
871 871 UserApiKeys.expires >= time.time()))
872 872 if cache:
873 873 q = q.options(
874 874 FromCache("sql_cache_short", "get_auth_token_%s" % auth_token))
875 875
876 876 match = q.first()
877 877 if match:
878 878 return match.user
879 879
880 880 @classmethod
881 881 def get_by_email(cls, email, case_insensitive=False, cache=False):
882 882
883 883 if case_insensitive:
884 884 q = cls.query().filter(func.lower(cls.email) == func.lower(email))
885 885
886 886 else:
887 887 q = cls.query().filter(cls.email == email)
888 888
889 889 email_key = _hash_key(email)
890 890 if cache:
891 891 q = q.options(
892 892 FromCache("sql_cache_short", "get_email_key_%s" % email_key))
893 893
894 894 ret = q.scalar()
895 895 if ret is None:
896 896 q = UserEmailMap.query()
897 897 # try fetching in alternate email map
898 898 if case_insensitive:
899 899 q = q.filter(func.lower(UserEmailMap.email) == func.lower(email))
900 900 else:
901 901 q = q.filter(UserEmailMap.email == email)
902 902 q = q.options(joinedload(UserEmailMap.user))
903 903 if cache:
904 904 q = q.options(
905 905 FromCache("sql_cache_short", "get_email_map_key_%s" % email_key))
906 906 ret = getattr(q.scalar(), 'user', None)
907 907
908 908 return ret
909 909
910 910 @classmethod
911 911 def get_from_cs_author(cls, author):
912 912 """
913 913 Tries to get User objects out of commit author string
914 914
915 915 :param author:
916 916 """
917 917 from rhodecode.lib.helpers import email, author_name
918 918 # Valid email in the attribute passed, see if they're in the system
919 919 _email = email(author)
920 920 if _email:
921 921 user = cls.get_by_email(_email, case_insensitive=True)
922 922 if user:
923 923 return user
924 924 # Maybe we can match by username?
925 925 _author = author_name(author)
926 926 user = cls.get_by_username(_author, case_insensitive=True)
927 927 if user:
928 928 return user
929 929
930 930 def update_userdata(self, **kwargs):
931 931 usr = self
932 932 old = usr.user_data
933 933 old.update(**kwargs)
934 934 usr.user_data = old
935 935 Session().add(usr)
936 936 log.debug('updated userdata with ', kwargs)
937 937
938 938 def update_lastlogin(self):
939 939 """Update user lastlogin"""
940 940 self.last_login = datetime.datetime.now()
941 941 Session().add(self)
942 942 log.debug('updated user %s lastlogin', self.username)
943 943
944 944 def update_password(self, new_password):
945 945 from rhodecode.lib.auth import get_crypt_password
946 946
947 947 self.password = get_crypt_password(new_password)
948 948 Session().add(self)
949 949
950 950 @classmethod
951 951 def get_first_super_admin(cls):
952 952 user = User.query()\
953 953 .filter(User.admin == true()) \
954 954 .order_by(User.user_id.asc()) \
955 955 .first()
956 956
957 957 if user is None:
958 958 raise Exception('FATAL: Missing administrative account!')
959 959 return user
960 960
961 961 @classmethod
962 def get_all_super_admins(cls):
962 def get_all_super_admins(cls, only_active=False):
963 963 """
964 964 Returns all admin accounts sorted by username
965 965 """
966 return User.query().filter(User.admin == true())\
967 .order_by(User.username.asc()).all()
966 qry = User.query().filter(User.admin == true()).order_by(User.username.asc())
967 if only_active:
968 qry = qry.filter(User.active == true())
969 return qry.all()
968 970
969 971 @classmethod
970 972 def get_default_user(cls, cache=False, refresh=False):
971 973 user = User.get_by_username(User.DEFAULT_USER, cache=cache)
972 974 if user is None:
973 975 raise Exception('FATAL: Missing default account!')
974 976 if refresh:
975 977 # The default user might be based on outdated state which
976 978 # has been loaded from the cache.
977 979 # A call to refresh() ensures that the
978 980 # latest state from the database is used.
979 981 Session().refresh(user)
980 982 return user
981 983
982 984 def _get_default_perms(self, user, suffix=''):
983 985 from rhodecode.model.permission import PermissionModel
984 986 return PermissionModel().get_default_perms(user.user_perms, suffix)
985 987
986 988 def get_default_perms(self, suffix=''):
987 989 return self._get_default_perms(self, suffix)
988 990
989 991 def get_api_data(self, include_secrets=False, details='full'):
990 992 """
991 993 Common function for generating user related data for API
992 994
993 995 :param include_secrets: By default secrets in the API data will be replaced
994 996 by a placeholder value to prevent exposing this data by accident. In case
995 997 this data shall be exposed, set this flag to ``True``.
996 998
997 999 :param details: details can be 'basic|full' basic gives only a subset of
998 1000 the available user information that includes user_id, name and emails.
999 1001 """
1000 1002 user = self
1001 1003 user_data = self.user_data
1002 1004 data = {
1003 1005 'user_id': user.user_id,
1004 1006 'username': user.username,
1005 1007 'firstname': user.name,
1006 1008 'lastname': user.lastname,
1007 1009 'email': user.email,
1008 1010 'emails': user.emails,
1009 1011 }
1010 1012 if details == 'basic':
1011 1013 return data
1012 1014
1013 1015 auth_token_length = 40
1014 1016 auth_token_replacement = '*' * auth_token_length
1015 1017
1016 1018 extras = {
1017 1019 'auth_tokens': [auth_token_replacement],
1018 1020 'active': user.active,
1019 1021 'admin': user.admin,
1020 1022 'extern_type': user.extern_type,
1021 1023 'extern_name': user.extern_name,
1022 1024 'last_login': user.last_login,
1023 1025 'last_activity': user.last_activity,
1024 1026 'ip_addresses': user.ip_addresses,
1025 1027 'language': user_data.get('language')
1026 1028 }
1027 1029 data.update(extras)
1028 1030
1029 1031 if include_secrets:
1030 1032 data['auth_tokens'] = user.auth_tokens
1031 1033 return data
1032 1034
1033 1035 def __json__(self):
1034 1036 data = {
1035 1037 'full_name': self.full_name,
1036 1038 'full_name_or_username': self.full_name_or_username,
1037 1039 'short_contact': self.short_contact,
1038 1040 'full_contact': self.full_contact,
1039 1041 }
1040 1042 data.update(self.get_api_data())
1041 1043 return data
1042 1044
1043 1045
1044 1046 class UserApiKeys(Base, BaseModel):
1045 1047 __tablename__ = 'user_api_keys'
1046 1048 __table_args__ = (
1047 1049 Index('uak_api_key_idx', 'api_key', unique=True),
1048 1050 Index('uak_api_key_expires_idx', 'api_key', 'expires'),
1049 1051 base_table_args
1050 1052 )
1051 1053 __mapper_args__ = {}
1052 1054
1053 1055 # ApiKey role
1054 1056 ROLE_ALL = 'token_role_all'
1055 1057 ROLE_HTTP = 'token_role_http'
1056 1058 ROLE_VCS = 'token_role_vcs'
1057 1059 ROLE_API = 'token_role_api'
1058 1060 ROLE_FEED = 'token_role_feed'
1059 1061 ROLE_PASSWORD_RESET = 'token_password_reset'
1060 1062
1061 1063 ROLES = [ROLE_ALL, ROLE_HTTP, ROLE_VCS, ROLE_API, ROLE_FEED]
1062 1064
1063 1065 user_api_key_id = Column("user_api_key_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1064 1066 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1065 1067 api_key = Column("api_key", String(255), nullable=False, unique=True)
1066 1068 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1067 1069 expires = Column('expires', Float(53), nullable=False)
1068 1070 role = Column('role', String(255), nullable=True)
1069 1071 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1070 1072
1071 1073 # scope columns
1072 1074 repo_id = Column(
1073 1075 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
1074 1076 nullable=True, unique=None, default=None)
1075 1077 repo = relationship('Repository', lazy='joined')
1076 1078
1077 1079 repo_group_id = Column(
1078 1080 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
1079 1081 nullable=True, unique=None, default=None)
1080 1082 repo_group = relationship('RepoGroup', lazy='joined')
1081 1083
1082 1084 user = relationship('User', lazy='joined')
1083 1085
1084 1086 def __unicode__(self):
1085 1087 return u"<%s('%s')>" % (self.__class__.__name__, self.role)
1086 1088
1087 1089 def __json__(self):
1088 1090 data = {
1089 1091 'auth_token': self.api_key,
1090 1092 'role': self.role,
1091 1093 'scope': self.scope_humanized,
1092 1094 'expired': self.expired
1093 1095 }
1094 1096 return data
1095 1097
1096 1098 def get_api_data(self, include_secrets=False):
1097 1099 data = self.__json__()
1098 1100 if include_secrets:
1099 1101 return data
1100 1102 else:
1101 1103 data['auth_token'] = self.token_obfuscated
1102 1104 return data
1103 1105
1104 1106 @hybrid_property
1105 1107 def description_safe(self):
1106 1108 from rhodecode.lib import helpers as h
1107 1109 return h.escape(self.description)
1108 1110
1109 1111 @property
1110 1112 def expired(self):
1111 1113 if self.expires == -1:
1112 1114 return False
1113 1115 return time.time() > self.expires
1114 1116
1115 1117 @classmethod
1116 1118 def _get_role_name(cls, role):
1117 1119 return {
1118 1120 cls.ROLE_ALL: _('all'),
1119 1121 cls.ROLE_HTTP: _('http/web interface'),
1120 1122 cls.ROLE_VCS: _('vcs (git/hg/svn protocol)'),
1121 1123 cls.ROLE_API: _('api calls'),
1122 1124 cls.ROLE_FEED: _('feed access'),
1123 1125 }.get(role, role)
1124 1126
1125 1127 @property
1126 1128 def role_humanized(self):
1127 1129 return self._get_role_name(self.role)
1128 1130
1129 1131 def _get_scope(self):
1130 1132 if self.repo:
1131 1133 return repr(self.repo)
1132 1134 if self.repo_group:
1133 1135 return repr(self.repo_group) + ' (recursive)'
1134 1136 return 'global'
1135 1137
1136 1138 @property
1137 1139 def scope_humanized(self):
1138 1140 return self._get_scope()
1139 1141
1140 1142 @property
1141 1143 def token_obfuscated(self):
1142 1144 if self.api_key:
1143 1145 return self.api_key[:4] + "****"
1144 1146
1145 1147
1146 1148 class UserEmailMap(Base, BaseModel):
1147 1149 __tablename__ = 'user_email_map'
1148 1150 __table_args__ = (
1149 1151 Index('uem_email_idx', 'email'),
1150 1152 UniqueConstraint('email'),
1151 1153 base_table_args
1152 1154 )
1153 1155 __mapper_args__ = {}
1154 1156
1155 1157 email_id = Column("email_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1156 1158 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1157 1159 _email = Column("email", String(255), nullable=True, unique=False, default=None)
1158 1160 user = relationship('User', lazy='joined')
1159 1161
1160 1162 @validates('_email')
1161 1163 def validate_email(self, key, email):
1162 1164 # check if this email is not main one
1163 1165 main_email = Session().query(User).filter(User.email == email).scalar()
1164 1166 if main_email is not None:
1165 1167 raise AttributeError('email %s is present is user table' % email)
1166 1168 return email
1167 1169
1168 1170 @hybrid_property
1169 1171 def email(self):
1170 1172 return self._email
1171 1173
1172 1174 @email.setter
1173 1175 def email(self, val):
1174 1176 self._email = val.lower() if val else None
1175 1177
1176 1178
1177 1179 class UserIpMap(Base, BaseModel):
1178 1180 __tablename__ = 'user_ip_map'
1179 1181 __table_args__ = (
1180 1182 UniqueConstraint('user_id', 'ip_addr'),
1181 1183 base_table_args
1182 1184 )
1183 1185 __mapper_args__ = {}
1184 1186
1185 1187 ip_id = Column("ip_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1186 1188 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1187 1189 ip_addr = Column("ip_addr", String(255), nullable=True, unique=False, default=None)
1188 1190 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
1189 1191 description = Column("description", String(10000), nullable=True, unique=None, default=None)
1190 1192 user = relationship('User', lazy='joined')
1191 1193
1192 1194 @hybrid_property
1193 1195 def description_safe(self):
1194 1196 from rhodecode.lib import helpers as h
1195 1197 return h.escape(self.description)
1196 1198
1197 1199 @classmethod
1198 1200 def _get_ip_range(cls, ip_addr):
1199 1201 net = ipaddress.ip_network(safe_unicode(ip_addr), strict=False)
1200 1202 return [str(net.network_address), str(net.broadcast_address)]
1201 1203
1202 1204 def __json__(self):
1203 1205 return {
1204 1206 'ip_addr': self.ip_addr,
1205 1207 'ip_range': self._get_ip_range(self.ip_addr),
1206 1208 }
1207 1209
1208 1210 def __unicode__(self):
1209 1211 return u"<%s('user_id:%s=>%s')>" % (self.__class__.__name__,
1210 1212 self.user_id, self.ip_addr)
1211 1213
1212 1214
1213 1215 class UserSshKeys(Base, BaseModel):
1214 1216 __tablename__ = 'user_ssh_keys'
1215 1217 __table_args__ = (
1216 1218 Index('usk_ssh_key_fingerprint_idx', 'ssh_key_fingerprint'),
1217 1219
1218 1220 UniqueConstraint('ssh_key_fingerprint'),
1219 1221
1220 1222 base_table_args
1221 1223 )
1222 1224 __mapper_args__ = {}
1223 1225
1224 1226 ssh_key_id = Column('ssh_key_id', Integer(), nullable=False, unique=True, default=None, primary_key=True)
1225 1227 ssh_key_data = Column('ssh_key_data', String(10240), nullable=False, unique=None, default=None)
1226 1228 ssh_key_fingerprint = Column('ssh_key_fingerprint', String(255), nullable=False, unique=None, default=None)
1227 1229
1228 1230 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1229 1231
1230 1232 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1231 1233 accessed_on = Column('accessed_on', DateTime(timezone=False), nullable=True, default=None)
1232 1234 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1233 1235
1234 1236 user = relationship('User', lazy='joined')
1235 1237
1236 1238 def __json__(self):
1237 1239 data = {
1238 1240 'ssh_fingerprint': self.ssh_key_fingerprint,
1239 1241 'description': self.description,
1240 1242 'created_on': self.created_on
1241 1243 }
1242 1244 return data
1243 1245
1244 1246 def get_api_data(self):
1245 1247 data = self.__json__()
1246 1248 return data
1247 1249
1248 1250
1249 1251 class UserLog(Base, BaseModel):
1250 1252 __tablename__ = 'user_logs'
1251 1253 __table_args__ = (
1252 1254 base_table_args,
1253 1255 )
1254 1256
1255 1257 VERSION_1 = 'v1'
1256 1258 VERSION_2 = 'v2'
1257 1259 VERSIONS = [VERSION_1, VERSION_2]
1258 1260
1259 1261 user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1260 1262 user_id = Column("user_id", Integer(), ForeignKey('users.user_id',ondelete='SET NULL'), nullable=True, unique=None, default=None)
1261 1263 username = Column("username", String(255), nullable=True, unique=None, default=None)
1262 1264 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id', ondelete='SET NULL'), nullable=True, unique=None, default=None)
1263 1265 repository_name = Column("repository_name", String(255), nullable=True, unique=None, default=None)
1264 1266 user_ip = Column("user_ip", String(255), nullable=True, unique=None, default=None)
1265 1267 action = Column("action", Text().with_variant(Text(1200000), 'mysql'), nullable=True, unique=None, default=None)
1266 1268 action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
1267 1269
1268 1270 version = Column("version", String(255), nullable=True, default=VERSION_1)
1269 1271 user_data = Column('user_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1270 1272 action_data = Column('action_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1271 1273
1272 1274 def __unicode__(self):
1273 1275 return u"<%s('id:%s:%s')>" % (
1274 1276 self.__class__.__name__, self.repository_name, self.action)
1275 1277
1276 1278 def __json__(self):
1277 1279 return {
1278 1280 'user_id': self.user_id,
1279 1281 'username': self.username,
1280 1282 'repository_id': self.repository_id,
1281 1283 'repository_name': self.repository_name,
1282 1284 'user_ip': self.user_ip,
1283 1285 'action_date': self.action_date,
1284 1286 'action': self.action,
1285 1287 }
1286 1288
1287 1289 @hybrid_property
1288 1290 def entry_id(self):
1289 1291 return self.user_log_id
1290 1292
1291 1293 @property
1292 1294 def action_as_day(self):
1293 1295 return datetime.date(*self.action_date.timetuple()[:3])
1294 1296
1295 1297 user = relationship('User')
1296 1298 repository = relationship('Repository', cascade='')
1297 1299
1298 1300
1299 1301 class UserGroup(Base, BaseModel):
1300 1302 __tablename__ = 'users_groups'
1301 1303 __table_args__ = (
1302 1304 base_table_args,
1303 1305 )
1304 1306
1305 1307 users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1306 1308 users_group_name = Column("users_group_name", String(255), nullable=False, unique=True, default=None)
1307 1309 user_group_description = Column("user_group_description", String(10000), nullable=True, unique=None, default=None)
1308 1310 users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
1309 1311 inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
1310 1312 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
1311 1313 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1312 1314 _group_data = Column("group_data", LargeBinary(), nullable=True) # JSON data
1313 1315
1314 1316 members = relationship('UserGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
1315 1317 users_group_to_perm = relationship('UserGroupToPerm', cascade='all')
1316 1318 users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1317 1319 users_group_repo_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
1318 1320 user_user_group_to_perm = relationship('UserUserGroupToPerm', cascade='all')
1319 1321 user_group_user_group_to_perm = relationship('UserGroupUserGroupToPerm ', primaryjoin="UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id", cascade='all')
1320 1322
1321 1323 user_group_review_rules = relationship('RepoReviewRuleUserGroup', cascade='all')
1322 1324 user = relationship('User', primaryjoin="User.user_id==UserGroup.user_id")
1323 1325
1324 1326 @classmethod
1325 1327 def _load_group_data(cls, column):
1326 1328 if not column:
1327 1329 return {}
1328 1330
1329 1331 try:
1330 1332 return json.loads(column) or {}
1331 1333 except TypeError:
1332 1334 return {}
1333 1335
1334 1336 @hybrid_property
1335 1337 def description_safe(self):
1336 1338 from rhodecode.lib import helpers as h
1337 1339 return h.escape(self.user_group_description)
1338 1340
1339 1341 @hybrid_property
1340 1342 def group_data(self):
1341 1343 return self._load_group_data(self._group_data)
1342 1344
1343 1345 @group_data.expression
1344 1346 def group_data(self, **kwargs):
1345 1347 return self._group_data
1346 1348
1347 1349 @group_data.setter
1348 1350 def group_data(self, val):
1349 1351 try:
1350 1352 self._group_data = json.dumps(val)
1351 1353 except Exception:
1352 1354 log.error(traceback.format_exc())
1353 1355
1354 1356 @classmethod
1355 1357 def _load_sync(cls, group_data):
1356 1358 if group_data:
1357 1359 return group_data.get('extern_type')
1358 1360
1359 1361 @property
1360 1362 def sync(self):
1361 1363 return self._load_sync(self.group_data)
1362 1364
1363 1365 def __unicode__(self):
1364 1366 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
1365 1367 self.users_group_id,
1366 1368 self.users_group_name)
1367 1369
1368 1370 @classmethod
1369 1371 def get_by_group_name(cls, group_name, cache=False,
1370 1372 case_insensitive=False):
1371 1373 if case_insensitive:
1372 1374 q = cls.query().filter(func.lower(cls.users_group_name) ==
1373 1375 func.lower(group_name))
1374 1376
1375 1377 else:
1376 1378 q = cls.query().filter(cls.users_group_name == group_name)
1377 1379 if cache:
1378 1380 q = q.options(
1379 1381 FromCache("sql_cache_short", "get_group_%s" % _hash_key(group_name)))
1380 1382 return q.scalar()
1381 1383
1382 1384 @classmethod
1383 1385 def get(cls, user_group_id, cache=False):
1384 1386 if not user_group_id:
1385 1387 return
1386 1388
1387 1389 user_group = cls.query()
1388 1390 if cache:
1389 1391 user_group = user_group.options(
1390 1392 FromCache("sql_cache_short", "get_users_group_%s" % user_group_id))
1391 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 1398 Permissions for user groups
1396 1399 """
1397 1400 _admin_perm = 'usergroup.admin'
1398 1401
1399 1402 owner_row = []
1400 1403 if with_owner:
1401 1404 usr = AttributeDict(self.user.get_dict())
1402 1405 usr.owner_row = True
1403 1406 usr.permission = _admin_perm
1404 1407 owner_row.append(usr)
1405 1408
1406 1409 super_admin_ids = []
1407 1410 super_admin_rows = []
1408 1411 if with_admins:
1409 1412 for usr in User.get_all_super_admins():
1410 1413 super_admin_ids.append(usr.user_id)
1411 1414 # if this admin is also owner, don't double the record
1412 1415 if usr.user_id == owner_row[0].user_id:
1413 1416 owner_row[0].admin_row = True
1414 1417 else:
1415 1418 usr = AttributeDict(usr.get_dict())
1416 1419 usr.admin_row = True
1417 1420 usr.permission = _admin_perm
1418 1421 super_admin_rows.append(usr)
1419 1422
1420 1423 q = UserUserGroupToPerm.query().filter(UserUserGroupToPerm.user_group == self)
1421 1424 q = q.options(joinedload(UserUserGroupToPerm.user_group),
1422 1425 joinedload(UserUserGroupToPerm.user),
1423 1426 joinedload(UserUserGroupToPerm.permission),)
1424 1427
1425 1428 # get owners and admins and permissions. We do a trick of re-writing
1426 1429 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1427 1430 # has a global reference and changing one object propagates to all
1428 1431 # others. This means if admin is also an owner admin_row that change
1429 1432 # would propagate to both objects
1430 1433 perm_rows = []
1431 1434 for _usr in q.all():
1432 1435 usr = AttributeDict(_usr.user.get_dict())
1433 1436 # if this user is also owner/admin, mark as duplicate record
1434 1437 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
1435 1438 usr.duplicate_perm = True
1436 1439 usr.permission = _usr.permission.permission_name
1437 1440 perm_rows.append(usr)
1438 1441
1439 1442 # filter the perm rows by 'default' first and then sort them by
1440 1443 # admin,write,read,none permissions sorted again alphabetically in
1441 1444 # each group
1442 1445 perm_rows = sorted(perm_rows, key=display_user_sort)
1443 1446
1444 return super_admin_rows + owner_row + perm_rows
1445
1446 def permission_user_groups(self):
1447 q = UserGroupUserGroupToPerm.query().filter(UserGroupUserGroupToPerm.target_user_group == self)
1447 user_groups_rows = []
1448 if expand_from_user_groups:
1449 for ug in self.permission_user_groups(with_members=True):
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 1458 q = q.options(joinedload(UserGroupUserGroupToPerm.user_group),
1449 1459 joinedload(UserGroupUserGroupToPerm.target_user_group),
1450 1460 joinedload(UserGroupUserGroupToPerm.permission),)
1451 1461
1452 1462 perm_rows = []
1453 1463 for _user_group in q.all():
1454 usr = AttributeDict(_user_group.user_group.get_dict())
1455 usr.permission = _user_group.permission.permission_name
1456 perm_rows.append(usr)
1464 entry = AttributeDict(_user_group.user_group.get_dict())
1465 entry.permission = _user_group.permission.permission_name
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 1471 perm_rows = sorted(perm_rows, key=display_user_group_sort)
1459 1472 return perm_rows
1460 1473
1461 1474 def _get_default_perms(self, user_group, suffix=''):
1462 1475 from rhodecode.model.permission import PermissionModel
1463 1476 return PermissionModel().get_default_perms(user_group.users_group_to_perm, suffix)
1464 1477
1465 1478 def get_default_perms(self, suffix=''):
1466 1479 return self._get_default_perms(self, suffix)
1467 1480
1468 1481 def get_api_data(self, with_group_members=True, include_secrets=False):
1469 1482 """
1470 1483 :param include_secrets: See :meth:`User.get_api_data`, this parameter is
1471 1484 basically forwarded.
1472 1485
1473 1486 """
1474 1487 user_group = self
1475 1488 data = {
1476 1489 'users_group_id': user_group.users_group_id,
1477 1490 'group_name': user_group.users_group_name,
1478 1491 'group_description': user_group.user_group_description,
1479 1492 'active': user_group.users_group_active,
1480 1493 'owner': user_group.user.username,
1481 1494 'sync': user_group.sync,
1482 1495 'owner_email': user_group.user.email,
1483 1496 }
1484 1497
1485 1498 if with_group_members:
1486 1499 users = []
1487 1500 for user in user_group.members:
1488 1501 user = user.user
1489 1502 users.append(user.get_api_data(include_secrets=include_secrets))
1490 1503 data['users'] = users
1491 1504
1492 1505 return data
1493 1506
1494 1507
1495 1508 class UserGroupMember(Base, BaseModel):
1496 1509 __tablename__ = 'users_groups_members'
1497 1510 __table_args__ = (
1498 1511 base_table_args,
1499 1512 )
1500 1513
1501 1514 users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1502 1515 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
1503 1516 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
1504 1517
1505 1518 user = relationship('User', lazy='joined')
1506 1519 users_group = relationship('UserGroup')
1507 1520
1508 1521 def __init__(self, gr_id='', u_id=''):
1509 1522 self.users_group_id = gr_id
1510 1523 self.user_id = u_id
1511 1524
1512 1525
1513 1526 class RepositoryField(Base, BaseModel):
1514 1527 __tablename__ = 'repositories_fields'
1515 1528 __table_args__ = (
1516 1529 UniqueConstraint('repository_id', 'field_key'), # no-multi field
1517 1530 base_table_args,
1518 1531 )
1519 1532
1520 1533 PREFIX = 'ex_' # prefix used in form to not conflict with already existing fields
1521 1534
1522 1535 repo_field_id = Column("repo_field_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1523 1536 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
1524 1537 field_key = Column("field_key", String(250))
1525 1538 field_label = Column("field_label", String(1024), nullable=False)
1526 1539 field_value = Column("field_value", String(10000), nullable=False)
1527 1540 field_desc = Column("field_desc", String(1024), nullable=False)
1528 1541 field_type = Column("field_type", String(255), nullable=False, unique=None)
1529 1542 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1530 1543
1531 1544 repository = relationship('Repository')
1532 1545
1533 1546 @property
1534 1547 def field_key_prefixed(self):
1535 1548 return 'ex_%s' % self.field_key
1536 1549
1537 1550 @classmethod
1538 1551 def un_prefix_key(cls, key):
1539 1552 if key.startswith(cls.PREFIX):
1540 1553 return key[len(cls.PREFIX):]
1541 1554 return key
1542 1555
1543 1556 @classmethod
1544 1557 def get_by_key_name(cls, key, repo):
1545 1558 row = cls.query()\
1546 1559 .filter(cls.repository == repo)\
1547 1560 .filter(cls.field_key == key).scalar()
1548 1561 return row
1549 1562
1550 1563
1551 1564 class Repository(Base, BaseModel):
1552 1565 __tablename__ = 'repositories'
1553 1566 __table_args__ = (
1554 1567 Index('r_repo_name_idx', 'repo_name', mysql_length=255),
1555 1568 base_table_args,
1556 1569 )
1557 1570 DEFAULT_CLONE_URI = '{scheme}://{user}@{netloc}/{repo}'
1558 1571 DEFAULT_CLONE_URI_ID = '{scheme}://{user}@{netloc}/_{repoid}'
1559 1572 DEFAULT_CLONE_URI_SSH = 'ssh://{sys_user}@{hostname}/{repo}'
1560 1573
1561 1574 STATE_CREATED = 'repo_state_created'
1562 1575 STATE_PENDING = 'repo_state_pending'
1563 1576 STATE_ERROR = 'repo_state_error'
1564 1577
1565 1578 LOCK_AUTOMATIC = 'lock_auto'
1566 1579 LOCK_API = 'lock_api'
1567 1580 LOCK_WEB = 'lock_web'
1568 1581 LOCK_PULL = 'lock_pull'
1569 1582
1570 1583 NAME_SEP = URL_SEP
1571 1584
1572 1585 repo_id = Column(
1573 1586 "repo_id", Integer(), nullable=False, unique=True, default=None,
1574 1587 primary_key=True)
1575 1588 _repo_name = Column(
1576 1589 "repo_name", Text(), nullable=False, default=None)
1577 1590 _repo_name_hash = Column(
1578 1591 "repo_name_hash", String(255), nullable=False, unique=True)
1579 1592 repo_state = Column("repo_state", String(255), nullable=True)
1580 1593
1581 1594 clone_uri = Column(
1582 1595 "clone_uri", EncryptedTextValue(), nullable=True, unique=False,
1583 1596 default=None)
1584 1597 push_uri = Column(
1585 1598 "push_uri", EncryptedTextValue(), nullable=True, unique=False,
1586 1599 default=None)
1587 1600 repo_type = Column(
1588 1601 "repo_type", String(255), nullable=False, unique=False, default=None)
1589 1602 user_id = Column(
1590 1603 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
1591 1604 unique=False, default=None)
1592 1605 private = Column(
1593 1606 "private", Boolean(), nullable=True, unique=None, default=None)
1594 1607 archived = Column(
1595 1608 "archived", Boolean(), nullable=True, unique=None, default=None)
1596 1609 enable_statistics = Column(
1597 1610 "statistics", Boolean(), nullable=True, unique=None, default=True)
1598 1611 enable_downloads = Column(
1599 1612 "downloads", Boolean(), nullable=True, unique=None, default=True)
1600 1613 description = Column(
1601 1614 "description", String(10000), nullable=True, unique=None, default=None)
1602 1615 created_on = Column(
1603 1616 'created_on', DateTime(timezone=False), nullable=True, unique=None,
1604 1617 default=datetime.datetime.now)
1605 1618 updated_on = Column(
1606 1619 'updated_on', DateTime(timezone=False), nullable=True, unique=None,
1607 1620 default=datetime.datetime.now)
1608 1621 _landing_revision = Column(
1609 1622 "landing_revision", String(255), nullable=False, unique=False,
1610 1623 default=None)
1611 1624 enable_locking = Column(
1612 1625 "enable_locking", Boolean(), nullable=False, unique=None,
1613 1626 default=False)
1614 1627 _locked = Column(
1615 1628 "locked", String(255), nullable=True, unique=False, default=None)
1616 1629 _changeset_cache = Column(
1617 1630 "changeset_cache", LargeBinary(), nullable=True) # JSON data
1618 1631
1619 1632 fork_id = Column(
1620 1633 "fork_id", Integer(), ForeignKey('repositories.repo_id'),
1621 1634 nullable=True, unique=False, default=None)
1622 1635 group_id = Column(
1623 1636 "group_id", Integer(), ForeignKey('groups.group_id'), nullable=True,
1624 1637 unique=False, default=None)
1625 1638
1626 1639 user = relationship('User', lazy='joined')
1627 1640 fork = relationship('Repository', remote_side=repo_id, lazy='joined')
1628 1641 group = relationship('RepoGroup', lazy='joined')
1629 1642 repo_to_perm = relationship(
1630 1643 'UserRepoToPerm', cascade='all',
1631 1644 order_by='UserRepoToPerm.repo_to_perm_id')
1632 1645 users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1633 1646 stats = relationship('Statistics', cascade='all', uselist=False)
1634 1647
1635 1648 followers = relationship(
1636 1649 'UserFollowing',
1637 1650 primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id',
1638 1651 cascade='all')
1639 1652 extra_fields = relationship(
1640 1653 'RepositoryField', cascade="all, delete, delete-orphan")
1641 1654 logs = relationship('UserLog')
1642 1655 comments = relationship(
1643 1656 'ChangesetComment', cascade="all, delete, delete-orphan")
1644 1657 pull_requests_source = relationship(
1645 1658 'PullRequest',
1646 1659 primaryjoin='PullRequest.source_repo_id==Repository.repo_id',
1647 1660 cascade="all, delete, delete-orphan")
1648 1661 pull_requests_target = relationship(
1649 1662 'PullRequest',
1650 1663 primaryjoin='PullRequest.target_repo_id==Repository.repo_id',
1651 1664 cascade="all, delete, delete-orphan")
1652 1665 ui = relationship('RepoRhodeCodeUi', cascade="all")
1653 1666 settings = relationship('RepoRhodeCodeSetting', cascade="all")
1654 1667 integrations = relationship('Integration',
1655 1668 cascade="all, delete, delete-orphan")
1656 1669
1657 1670 scoped_tokens = relationship('UserApiKeys', cascade="all")
1658 1671
1659 1672 def __unicode__(self):
1660 1673 return u"<%s('%s:%s')>" % (self.__class__.__name__, self.repo_id,
1661 1674 safe_unicode(self.repo_name))
1662 1675
1663 1676 @hybrid_property
1664 1677 def description_safe(self):
1665 1678 from rhodecode.lib import helpers as h
1666 1679 return h.escape(self.description)
1667 1680
1668 1681 @hybrid_property
1669 1682 def landing_rev(self):
1670 1683 # always should return [rev_type, rev]
1671 1684 if self._landing_revision:
1672 1685 _rev_info = self._landing_revision.split(':')
1673 1686 if len(_rev_info) < 2:
1674 1687 _rev_info.insert(0, 'rev')
1675 1688 return [_rev_info[0], _rev_info[1]]
1676 1689 return [None, None]
1677 1690
1678 1691 @landing_rev.setter
1679 1692 def landing_rev(self, val):
1680 1693 if ':' not in val:
1681 1694 raise ValueError('value must be delimited with `:` and consist '
1682 1695 'of <rev_type>:<rev>, got %s instead' % val)
1683 1696 self._landing_revision = val
1684 1697
1685 1698 @hybrid_property
1686 1699 def locked(self):
1687 1700 if self._locked:
1688 1701 user_id, timelocked, reason = self._locked.split(':')
1689 1702 lock_values = int(user_id), timelocked, reason
1690 1703 else:
1691 1704 lock_values = [None, None, None]
1692 1705 return lock_values
1693 1706
1694 1707 @locked.setter
1695 1708 def locked(self, val):
1696 1709 if val and isinstance(val, (list, tuple)):
1697 1710 self._locked = ':'.join(map(str, val))
1698 1711 else:
1699 1712 self._locked = None
1700 1713
1701 1714 @hybrid_property
1702 1715 def changeset_cache(self):
1703 1716 from rhodecode.lib.vcs.backends.base import EmptyCommit
1704 1717 dummy = EmptyCommit().__json__()
1705 1718 if not self._changeset_cache:
1706 1719 return dummy
1707 1720 try:
1708 1721 return json.loads(self._changeset_cache)
1709 1722 except TypeError:
1710 1723 return dummy
1711 1724 except Exception:
1712 1725 log.error(traceback.format_exc())
1713 1726 return dummy
1714 1727
1715 1728 @changeset_cache.setter
1716 1729 def changeset_cache(self, val):
1717 1730 try:
1718 1731 self._changeset_cache = json.dumps(val)
1719 1732 except Exception:
1720 1733 log.error(traceback.format_exc())
1721 1734
1722 1735 @hybrid_property
1723 1736 def repo_name(self):
1724 1737 return self._repo_name
1725 1738
1726 1739 @repo_name.setter
1727 1740 def repo_name(self, value):
1728 1741 self._repo_name = value
1729 1742 self._repo_name_hash = hashlib.sha1(safe_str(value)).hexdigest()
1730 1743
1731 1744 @classmethod
1732 1745 def normalize_repo_name(cls, repo_name):
1733 1746 """
1734 1747 Normalizes os specific repo_name to the format internally stored inside
1735 1748 database using URL_SEP
1736 1749
1737 1750 :param cls:
1738 1751 :param repo_name:
1739 1752 """
1740 1753 return cls.NAME_SEP.join(repo_name.split(os.sep))
1741 1754
1742 1755 @classmethod
1743 1756 def get_by_repo_name(cls, repo_name, cache=False, identity_cache=False):
1744 1757 session = Session()
1745 1758 q = session.query(cls).filter(cls.repo_name == repo_name)
1746 1759
1747 1760 if cache:
1748 1761 if identity_cache:
1749 1762 val = cls.identity_cache(session, 'repo_name', repo_name)
1750 1763 if val:
1751 1764 return val
1752 1765 else:
1753 1766 cache_key = "get_repo_by_name_%s" % _hash_key(repo_name)
1754 1767 q = q.options(
1755 1768 FromCache("sql_cache_short", cache_key))
1756 1769
1757 1770 return q.scalar()
1758 1771
1759 1772 @classmethod
1760 1773 def get_by_id_or_repo_name(cls, repoid):
1761 1774 if isinstance(repoid, (int, long)):
1762 1775 try:
1763 1776 repo = cls.get(repoid)
1764 1777 except ValueError:
1765 1778 repo = None
1766 1779 else:
1767 1780 repo = cls.get_by_repo_name(repoid)
1768 1781 return repo
1769 1782
1770 1783 @classmethod
1771 1784 def get_by_full_path(cls, repo_full_path):
1772 1785 repo_name = repo_full_path.split(cls.base_path(), 1)[-1]
1773 1786 repo_name = cls.normalize_repo_name(repo_name)
1774 1787 return cls.get_by_repo_name(repo_name.strip(URL_SEP))
1775 1788
1776 1789 @classmethod
1777 1790 def get_repo_forks(cls, repo_id):
1778 1791 return cls.query().filter(Repository.fork_id == repo_id)
1779 1792
1780 1793 @classmethod
1781 1794 def base_path(cls):
1782 1795 """
1783 1796 Returns base path when all repos are stored
1784 1797
1785 1798 :param cls:
1786 1799 """
1787 1800 q = Session().query(RhodeCodeUi)\
1788 1801 .filter(RhodeCodeUi.ui_key == cls.NAME_SEP)
1789 1802 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1790 1803 return q.one().ui_value
1791 1804
1792 1805 @classmethod
1793 1806 def get_all_repos(cls, user_id=Optional(None), group_id=Optional(None),
1794 1807 case_insensitive=True, archived=False):
1795 1808 q = Repository.query()
1796 1809
1797 1810 if not archived:
1798 1811 q = q.filter(Repository.archived.isnot(true()))
1799 1812
1800 1813 if not isinstance(user_id, Optional):
1801 1814 q = q.filter(Repository.user_id == user_id)
1802 1815
1803 1816 if not isinstance(group_id, Optional):
1804 1817 q = q.filter(Repository.group_id == group_id)
1805 1818
1806 1819 if case_insensitive:
1807 1820 q = q.order_by(func.lower(Repository.repo_name))
1808 1821 else:
1809 1822 q = q.order_by(Repository.repo_name)
1810 1823
1811 1824 return q.all()
1812 1825
1813 1826 @property
1814 1827 def forks(self):
1815 1828 """
1816 1829 Return forks of this repo
1817 1830 """
1818 1831 return Repository.get_repo_forks(self.repo_id)
1819 1832
1820 1833 @property
1821 1834 def parent(self):
1822 1835 """
1823 1836 Returns fork parent
1824 1837 """
1825 1838 return self.fork
1826 1839
1827 1840 @property
1828 1841 def just_name(self):
1829 1842 return self.repo_name.split(self.NAME_SEP)[-1]
1830 1843
1831 1844 @property
1832 1845 def groups_with_parents(self):
1833 1846 groups = []
1834 1847 if self.group is None:
1835 1848 return groups
1836 1849
1837 1850 cur_gr = self.group
1838 1851 groups.insert(0, cur_gr)
1839 1852 while 1:
1840 1853 gr = getattr(cur_gr, 'parent_group', None)
1841 1854 cur_gr = cur_gr.parent_group
1842 1855 if gr is None:
1843 1856 break
1844 1857 groups.insert(0, gr)
1845 1858
1846 1859 return groups
1847 1860
1848 1861 @property
1849 1862 def groups_and_repo(self):
1850 1863 return self.groups_with_parents, self
1851 1864
1852 1865 @LazyProperty
1853 1866 def repo_path(self):
1854 1867 """
1855 1868 Returns base full path for that repository means where it actually
1856 1869 exists on a filesystem
1857 1870 """
1858 1871 q = Session().query(RhodeCodeUi).filter(
1859 1872 RhodeCodeUi.ui_key == self.NAME_SEP)
1860 1873 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1861 1874 return q.one().ui_value
1862 1875
1863 1876 @property
1864 1877 def repo_full_path(self):
1865 1878 p = [self.repo_path]
1866 1879 # we need to split the name by / since this is how we store the
1867 1880 # names in the database, but that eventually needs to be converted
1868 1881 # into a valid system path
1869 1882 p += self.repo_name.split(self.NAME_SEP)
1870 1883 return os.path.join(*map(safe_unicode, p))
1871 1884
1872 1885 @property
1873 1886 def cache_keys(self):
1874 1887 """
1875 1888 Returns associated cache keys for that repo
1876 1889 """
1877 1890 invalidation_namespace = CacheKey.REPO_INVALIDATION_NAMESPACE.format(
1878 1891 repo_id=self.repo_id)
1879 1892 return CacheKey.query()\
1880 1893 .filter(CacheKey.cache_args == invalidation_namespace)\
1881 1894 .order_by(CacheKey.cache_key)\
1882 1895 .all()
1883 1896
1884 1897 @property
1885 1898 def cached_diffs_relative_dir(self):
1886 1899 """
1887 1900 Return a relative to the repository store path of cached diffs
1888 1901 used for safe display for users, who shouldn't know the absolute store
1889 1902 path
1890 1903 """
1891 1904 return os.path.join(
1892 1905 os.path.dirname(self.repo_name),
1893 1906 self.cached_diffs_dir.split(os.path.sep)[-1])
1894 1907
1895 1908 @property
1896 1909 def cached_diffs_dir(self):
1897 1910 path = self.repo_full_path
1898 1911 return os.path.join(
1899 1912 os.path.dirname(path),
1900 1913 '.__shadow_diff_cache_repo_{}'.format(self.repo_id))
1901 1914
1902 1915 def cached_diffs(self):
1903 1916 diff_cache_dir = self.cached_diffs_dir
1904 1917 if os.path.isdir(diff_cache_dir):
1905 1918 return os.listdir(diff_cache_dir)
1906 1919 return []
1907 1920
1908 1921 def shadow_repos(self):
1909 1922 shadow_repos_pattern = '.__shadow_repo_{}'.format(self.repo_id)
1910 1923 return [
1911 1924 x for x in os.listdir(os.path.dirname(self.repo_full_path))
1912 1925 if x.startswith(shadow_repos_pattern)]
1913 1926
1914 1927 def get_new_name(self, repo_name):
1915 1928 """
1916 1929 returns new full repository name based on assigned group and new new
1917 1930
1918 1931 :param group_name:
1919 1932 """
1920 1933 path_prefix = self.group.full_path_splitted if self.group else []
1921 1934 return self.NAME_SEP.join(path_prefix + [repo_name])
1922 1935
1923 1936 @property
1924 1937 def _config(self):
1925 1938 """
1926 1939 Returns db based config object.
1927 1940 """
1928 1941 from rhodecode.lib.utils import make_db_config
1929 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 1947 Permissions for repositories
1934 1948 """
1935 1949 _admin_perm = 'repository.admin'
1936 1950
1937 1951 owner_row = []
1938 1952 if with_owner:
1939 1953 usr = AttributeDict(self.user.get_dict())
1940 1954 usr.owner_row = True
1941 1955 usr.permission = _admin_perm
1942 1956 usr.permission_id = None
1943 1957 owner_row.append(usr)
1944 1958
1945 1959 super_admin_ids = []
1946 1960 super_admin_rows = []
1947 1961 if with_admins:
1948 1962 for usr in User.get_all_super_admins():
1949 1963 super_admin_ids.append(usr.user_id)
1950 1964 # if this admin is also owner, don't double the record
1951 1965 if usr.user_id == owner_row[0].user_id:
1952 1966 owner_row[0].admin_row = True
1953 1967 else:
1954 1968 usr = AttributeDict(usr.get_dict())
1955 1969 usr.admin_row = True
1956 1970 usr.permission = _admin_perm
1957 1971 usr.permission_id = None
1958 1972 super_admin_rows.append(usr)
1959 1973
1960 1974 q = UserRepoToPerm.query().filter(UserRepoToPerm.repository == self)
1961 1975 q = q.options(joinedload(UserRepoToPerm.repository),
1962 1976 joinedload(UserRepoToPerm.user),
1963 1977 joinedload(UserRepoToPerm.permission),)
1964 1978
1965 1979 # get owners and admins and permissions. We do a trick of re-writing
1966 1980 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1967 1981 # has a global reference and changing one object propagates to all
1968 1982 # others. This means if admin is also an owner admin_row that change
1969 1983 # would propagate to both objects
1970 1984 perm_rows = []
1971 1985 for _usr in q.all():
1972 1986 usr = AttributeDict(_usr.user.get_dict())
1973 1987 # if this user is also owner/admin, mark as duplicate record
1974 1988 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
1975 1989 usr.duplicate_perm = True
1976 1990 # also check if this permission is maybe used by branch_permissions
1977 1991 if _usr.branch_perm_entry:
1978 1992 usr.branch_rules = [x.branch_rule_id for x in _usr.branch_perm_entry]
1979 1993
1980 1994 usr.permission = _usr.permission.permission_name
1981 1995 usr.permission_id = _usr.repo_to_perm_id
1982 1996 perm_rows.append(usr)
1983 1997
1984 1998 # filter the perm rows by 'default' first and then sort them by
1985 1999 # admin,write,read,none permissions sorted again alphabetically in
1986 2000 # each group
1987 2001 perm_rows = sorted(perm_rows, key=display_user_sort)
1988 2002
1989 return super_admin_rows + owner_row + perm_rows
1990
1991 def permission_user_groups(self):
1992 q = UserGroupRepoToPerm.query().filter(
1993 UserGroupRepoToPerm.repository == self)
2003 user_groups_rows = []
2004 if expand_from_user_groups:
2005 for ug in self.permission_user_groups(with_members=True):
2006 for user_data in ug.members:
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 2014 q = q.options(joinedload(UserGroupRepoToPerm.repository),
1995 2015 joinedload(UserGroupRepoToPerm.users_group),
1996 2016 joinedload(UserGroupRepoToPerm.permission),)
1997 2017
1998 2018 perm_rows = []
1999 2019 for _user_group in q.all():
2000 usr = AttributeDict(_user_group.users_group.get_dict())
2001 usr.permission = _user_group.permission.permission_name
2002 perm_rows.append(usr)
2020 entry = AttributeDict(_user_group.users_group.get_dict())
2021 entry.permission = _user_group.permission.permission_name
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 2027 perm_rows = sorted(perm_rows, key=display_user_group_sort)
2005 2028 return perm_rows
2006 2029
2007 2030 def get_api_data(self, include_secrets=False):
2008 2031 """
2009 2032 Common function for generating repo api data
2010 2033
2011 2034 :param include_secrets: See :meth:`User.get_api_data`.
2012 2035
2013 2036 """
2014 2037 # TODO: mikhail: Here there is an anti-pattern, we probably need to
2015 2038 # move this methods on models level.
2016 2039 from rhodecode.model.settings import SettingsModel
2017 2040 from rhodecode.model.repo import RepoModel
2018 2041
2019 2042 repo = self
2020 2043 _user_id, _time, _reason = self.locked
2021 2044
2022 2045 data = {
2023 2046 'repo_id': repo.repo_id,
2024 2047 'repo_name': repo.repo_name,
2025 2048 'repo_type': repo.repo_type,
2026 2049 'clone_uri': repo.clone_uri or '',
2027 2050 'push_uri': repo.push_uri or '',
2028 2051 'url': RepoModel().get_url(self),
2029 2052 'private': repo.private,
2030 2053 'created_on': repo.created_on,
2031 2054 'description': repo.description_safe,
2032 2055 'landing_rev': repo.landing_rev,
2033 2056 'owner': repo.user.username,
2034 2057 'fork_of': repo.fork.repo_name if repo.fork else None,
2035 2058 'fork_of_id': repo.fork.repo_id if repo.fork else None,
2036 2059 'enable_statistics': repo.enable_statistics,
2037 2060 'enable_locking': repo.enable_locking,
2038 2061 'enable_downloads': repo.enable_downloads,
2039 2062 'last_changeset': repo.changeset_cache,
2040 2063 'locked_by': User.get(_user_id).get_api_data(
2041 2064 include_secrets=include_secrets) if _user_id else None,
2042 2065 'locked_date': time_to_datetime(_time) if _time else None,
2043 2066 'lock_reason': _reason if _reason else None,
2044 2067 }
2045 2068
2046 2069 # TODO: mikhail: should be per-repo settings here
2047 2070 rc_config = SettingsModel().get_all_settings()
2048 2071 repository_fields = str2bool(
2049 2072 rc_config.get('rhodecode_repository_fields'))
2050 2073 if repository_fields:
2051 2074 for f in self.extra_fields:
2052 2075 data[f.field_key_prefixed] = f.field_value
2053 2076
2054 2077 return data
2055 2078
2056 2079 @classmethod
2057 2080 def lock(cls, repo, user_id, lock_time=None, lock_reason=None):
2058 2081 if not lock_time:
2059 2082 lock_time = time.time()
2060 2083 if not lock_reason:
2061 2084 lock_reason = cls.LOCK_AUTOMATIC
2062 2085 repo.locked = [user_id, lock_time, lock_reason]
2063 2086 Session().add(repo)
2064 2087 Session().commit()
2065 2088
2066 2089 @classmethod
2067 2090 def unlock(cls, repo):
2068 2091 repo.locked = None
2069 2092 Session().add(repo)
2070 2093 Session().commit()
2071 2094
2072 2095 @classmethod
2073 2096 def getlock(cls, repo):
2074 2097 return repo.locked
2075 2098
2076 2099 def is_user_lock(self, user_id):
2077 2100 if self.lock[0]:
2078 2101 lock_user_id = safe_int(self.lock[0])
2079 2102 user_id = safe_int(user_id)
2080 2103 # both are ints, and they are equal
2081 2104 return all([lock_user_id, user_id]) and lock_user_id == user_id
2082 2105
2083 2106 return False
2084 2107
2085 2108 def get_locking_state(self, action, user_id, only_when_enabled=True):
2086 2109 """
2087 2110 Checks locking on this repository, if locking is enabled and lock is
2088 2111 present returns a tuple of make_lock, locked, locked_by.
2089 2112 make_lock can have 3 states None (do nothing) True, make lock
2090 2113 False release lock, This value is later propagated to hooks, which
2091 2114 do the locking. Think about this as signals passed to hooks what to do.
2092 2115
2093 2116 """
2094 2117 # TODO: johbo: This is part of the business logic and should be moved
2095 2118 # into the RepositoryModel.
2096 2119
2097 2120 if action not in ('push', 'pull'):
2098 2121 raise ValueError("Invalid action value: %s" % repr(action))
2099 2122
2100 2123 # defines if locked error should be thrown to user
2101 2124 currently_locked = False
2102 2125 # defines if new lock should be made, tri-state
2103 2126 make_lock = None
2104 2127 repo = self
2105 2128 user = User.get(user_id)
2106 2129
2107 2130 lock_info = repo.locked
2108 2131
2109 2132 if repo and (repo.enable_locking or not only_when_enabled):
2110 2133 if action == 'push':
2111 2134 # check if it's already locked !, if it is compare users
2112 2135 locked_by_user_id = lock_info[0]
2113 2136 if user.user_id == locked_by_user_id:
2114 2137 log.debug(
2115 2138 'Got `push` action from user %s, now unlocking', user)
2116 2139 # unlock if we have push from user who locked
2117 2140 make_lock = False
2118 2141 else:
2119 2142 # we're not the same user who locked, ban with
2120 2143 # code defined in settings (default is 423 HTTP Locked) !
2121 2144 log.debug('Repo %s is currently locked by %s', repo, user)
2122 2145 currently_locked = True
2123 2146 elif action == 'pull':
2124 2147 # [0] user [1] date
2125 2148 if lock_info[0] and lock_info[1]:
2126 2149 log.debug('Repo %s is currently locked by %s', repo, user)
2127 2150 currently_locked = True
2128 2151 else:
2129 2152 log.debug('Setting lock on repo %s by %s', repo, user)
2130 2153 make_lock = True
2131 2154
2132 2155 else:
2133 2156 log.debug('Repository %s do not have locking enabled', repo)
2134 2157
2135 2158 log.debug('FINAL locking values make_lock:%s,locked:%s,locked_by:%s',
2136 2159 make_lock, currently_locked, lock_info)
2137 2160
2138 2161 from rhodecode.lib.auth import HasRepoPermissionAny
2139 2162 perm_check = HasRepoPermissionAny('repository.write', 'repository.admin')
2140 2163 if make_lock and not perm_check(repo_name=repo.repo_name, user=user):
2141 2164 # if we don't have at least write permission we cannot make a lock
2142 2165 log.debug('lock state reset back to FALSE due to lack '
2143 2166 'of at least read permission')
2144 2167 make_lock = False
2145 2168
2146 2169 return make_lock, currently_locked, lock_info
2147 2170
2148 2171 @property
2149 2172 def last_db_change(self):
2150 2173 return self.updated_on
2151 2174
2152 2175 @property
2153 2176 def clone_uri_hidden(self):
2154 2177 clone_uri = self.clone_uri
2155 2178 if clone_uri:
2156 2179 import urlobject
2157 2180 url_obj = urlobject.URLObject(cleaned_uri(clone_uri))
2158 2181 if url_obj.password:
2159 2182 clone_uri = url_obj.with_password('*****')
2160 2183 return clone_uri
2161 2184
2162 2185 @property
2163 2186 def push_uri_hidden(self):
2164 2187 push_uri = self.push_uri
2165 2188 if push_uri:
2166 2189 import urlobject
2167 2190 url_obj = urlobject.URLObject(cleaned_uri(push_uri))
2168 2191 if url_obj.password:
2169 2192 push_uri = url_obj.with_password('*****')
2170 2193 return push_uri
2171 2194
2172 2195 def clone_url(self, **override):
2173 2196 from rhodecode.model.settings import SettingsModel
2174 2197
2175 2198 uri_tmpl = None
2176 2199 if 'with_id' in override:
2177 2200 uri_tmpl = self.DEFAULT_CLONE_URI_ID
2178 2201 del override['with_id']
2179 2202
2180 2203 if 'uri_tmpl' in override:
2181 2204 uri_tmpl = override['uri_tmpl']
2182 2205 del override['uri_tmpl']
2183 2206
2184 2207 ssh = False
2185 2208 if 'ssh' in override:
2186 2209 ssh = True
2187 2210 del override['ssh']
2188 2211
2189 2212 # we didn't override our tmpl from **overrides
2190 2213 if not uri_tmpl:
2191 2214 rc_config = SettingsModel().get_all_settings(cache=True)
2192 2215 if ssh:
2193 2216 uri_tmpl = rc_config.get(
2194 2217 'rhodecode_clone_uri_ssh_tmpl') or self.DEFAULT_CLONE_URI_SSH
2195 2218 else:
2196 2219 uri_tmpl = rc_config.get(
2197 2220 'rhodecode_clone_uri_tmpl') or self.DEFAULT_CLONE_URI
2198 2221
2199 2222 request = get_current_request()
2200 2223 return get_clone_url(request=request,
2201 2224 uri_tmpl=uri_tmpl,
2202 2225 repo_name=self.repo_name,
2203 2226 repo_id=self.repo_id, **override)
2204 2227
2205 2228 def set_state(self, state):
2206 2229 self.repo_state = state
2207 2230 Session().add(self)
2208 2231 #==========================================================================
2209 2232 # SCM PROPERTIES
2210 2233 #==========================================================================
2211 2234
2212 2235 def get_commit(self, commit_id=None, commit_idx=None, pre_load=None):
2213 2236 return get_commit_safe(
2214 2237 self.scm_instance(), commit_id, commit_idx, pre_load=pre_load)
2215 2238
2216 2239 def get_changeset(self, rev=None, pre_load=None):
2217 2240 warnings.warn("Use get_commit", DeprecationWarning)
2218 2241 commit_id = None
2219 2242 commit_idx = None
2220 2243 if isinstance(rev, basestring):
2221 2244 commit_id = rev
2222 2245 else:
2223 2246 commit_idx = rev
2224 2247 return self.get_commit(commit_id=commit_id, commit_idx=commit_idx,
2225 2248 pre_load=pre_load)
2226 2249
2227 2250 def get_landing_commit(self):
2228 2251 """
2229 2252 Returns landing commit, or if that doesn't exist returns the tip
2230 2253 """
2231 2254 _rev_type, _rev = self.landing_rev
2232 2255 commit = self.get_commit(_rev)
2233 2256 if isinstance(commit, EmptyCommit):
2234 2257 return self.get_commit()
2235 2258 return commit
2236 2259
2237 2260 def update_commit_cache(self, cs_cache=None, config=None):
2238 2261 """
2239 2262 Update cache of last changeset for repository, keys should be::
2240 2263
2241 2264 short_id
2242 2265 raw_id
2243 2266 revision
2244 2267 parents
2245 2268 message
2246 2269 date
2247 2270 author
2248 2271
2249 2272 :param cs_cache:
2250 2273 """
2251 2274 from rhodecode.lib.vcs.backends.base import BaseChangeset
2252 2275 if cs_cache is None:
2253 2276 # use no-cache version here
2254 2277 scm_repo = self.scm_instance(cache=False, config=config)
2255 2278
2256 2279 empty = scm_repo.is_empty()
2257 2280 if not empty:
2258 2281 cs_cache = scm_repo.get_commit(
2259 2282 pre_load=["author", "date", "message", "parents"])
2260 2283 else:
2261 2284 cs_cache = EmptyCommit()
2262 2285
2263 2286 if isinstance(cs_cache, BaseChangeset):
2264 2287 cs_cache = cs_cache.__json__()
2265 2288
2266 2289 def is_outdated(new_cs_cache):
2267 2290 if (new_cs_cache['raw_id'] != self.changeset_cache['raw_id'] or
2268 2291 new_cs_cache['revision'] != self.changeset_cache['revision']):
2269 2292 return True
2270 2293 return False
2271 2294
2272 2295 # check if we have maybe already latest cached revision
2273 2296 if is_outdated(cs_cache) or not self.changeset_cache:
2274 2297 _default = datetime.datetime.utcnow()
2275 2298 last_change = cs_cache.get('date') or _default
2276 2299 if self.updated_on and self.updated_on > last_change:
2277 2300 # we check if last update is newer than the new value
2278 2301 # if yes, we use the current timestamp instead. Imagine you get
2279 2302 # old commit pushed 1y ago, we'd set last update 1y to ago.
2280 2303 last_change = _default
2281 2304 log.debug('updated repo %s with new cs cache %s',
2282 2305 self.repo_name, cs_cache)
2283 2306 self.updated_on = last_change
2284 2307 self.changeset_cache = cs_cache
2285 2308 Session().add(self)
2286 2309 Session().commit()
2287 2310 else:
2288 2311 log.debug('Skipping update_commit_cache for repo:`%s` '
2289 2312 'commit already with latest changes', self.repo_name)
2290 2313
2291 2314 @property
2292 2315 def tip(self):
2293 2316 return self.get_commit('tip')
2294 2317
2295 2318 @property
2296 2319 def author(self):
2297 2320 return self.tip.author
2298 2321
2299 2322 @property
2300 2323 def last_change(self):
2301 2324 return self.scm_instance().last_change
2302 2325
2303 2326 def get_comments(self, revisions=None):
2304 2327 """
2305 2328 Returns comments for this repository grouped by revisions
2306 2329
2307 2330 :param revisions: filter query by revisions only
2308 2331 """
2309 2332 cmts = ChangesetComment.query()\
2310 2333 .filter(ChangesetComment.repo == self)
2311 2334 if revisions:
2312 2335 cmts = cmts.filter(ChangesetComment.revision.in_(revisions))
2313 2336 grouped = collections.defaultdict(list)
2314 2337 for cmt in cmts.all():
2315 2338 grouped[cmt.revision].append(cmt)
2316 2339 return grouped
2317 2340
2318 2341 def statuses(self, revisions=None):
2319 2342 """
2320 2343 Returns statuses for this repository
2321 2344
2322 2345 :param revisions: list of revisions to get statuses for
2323 2346 """
2324 2347 statuses = ChangesetStatus.query()\
2325 2348 .filter(ChangesetStatus.repo == self)\
2326 2349 .filter(ChangesetStatus.version == 0)
2327 2350
2328 2351 if revisions:
2329 2352 # Try doing the filtering in chunks to avoid hitting limits
2330 2353 size = 500
2331 2354 status_results = []
2332 2355 for chunk in xrange(0, len(revisions), size):
2333 2356 status_results += statuses.filter(
2334 2357 ChangesetStatus.revision.in_(
2335 2358 revisions[chunk: chunk+size])
2336 2359 ).all()
2337 2360 else:
2338 2361 status_results = statuses.all()
2339 2362
2340 2363 grouped = {}
2341 2364
2342 2365 # maybe we have open new pullrequest without a status?
2343 2366 stat = ChangesetStatus.STATUS_UNDER_REVIEW
2344 2367 status_lbl = ChangesetStatus.get_status_lbl(stat)
2345 2368 for pr in PullRequest.query().filter(PullRequest.source_repo == self).all():
2346 2369 for rev in pr.revisions:
2347 2370 pr_id = pr.pull_request_id
2348 2371 pr_repo = pr.target_repo.repo_name
2349 2372 grouped[rev] = [stat, status_lbl, pr_id, pr_repo]
2350 2373
2351 2374 for stat in status_results:
2352 2375 pr_id = pr_repo = None
2353 2376 if stat.pull_request:
2354 2377 pr_id = stat.pull_request.pull_request_id
2355 2378 pr_repo = stat.pull_request.target_repo.repo_name
2356 2379 grouped[stat.revision] = [str(stat.status), stat.status_lbl,
2357 2380 pr_id, pr_repo]
2358 2381 return grouped
2359 2382
2360 2383 # ==========================================================================
2361 2384 # SCM CACHE INSTANCE
2362 2385 # ==========================================================================
2363 2386
2364 2387 def scm_instance(self, **kwargs):
2365 2388 import rhodecode
2366 2389
2367 2390 # Passing a config will not hit the cache currently only used
2368 2391 # for repo2dbmapper
2369 2392 config = kwargs.pop('config', None)
2370 2393 cache = kwargs.pop('cache', None)
2371 2394 full_cache = str2bool(rhodecode.CONFIG.get('vcs_full_cache'))
2372 2395 # if cache is NOT defined use default global, else we have a full
2373 2396 # control over cache behaviour
2374 2397 if cache is None and full_cache and not config:
2375 2398 return self._get_instance_cached()
2376 2399 return self._get_instance(cache=bool(cache), config=config)
2377 2400
2378 2401 def _get_instance_cached(self):
2379 2402 from rhodecode.lib import rc_cache
2380 2403
2381 2404 cache_namespace_uid = 'cache_repo_instance.{}'.format(self.repo_id)
2382 2405 invalidation_namespace = CacheKey.REPO_INVALIDATION_NAMESPACE.format(
2383 2406 repo_id=self.repo_id)
2384 2407 region = rc_cache.get_or_create_region('cache_repo_longterm', cache_namespace_uid)
2385 2408
2386 2409 @region.conditional_cache_on_arguments(namespace=cache_namespace_uid)
2387 2410 def get_instance_cached(repo_id, context_id):
2388 2411 return self._get_instance()
2389 2412
2390 2413 # we must use thread scoped cache here,
2391 2414 # because each thread of gevent needs it's own not shared connection and cache
2392 2415 # we also alter `args` so the cache key is individual for every green thread.
2393 2416 inv_context_manager = rc_cache.InvalidationContext(
2394 2417 uid=cache_namespace_uid, invalidation_namespace=invalidation_namespace,
2395 2418 thread_scoped=True)
2396 2419 with inv_context_manager as invalidation_context:
2397 2420 args = (self.repo_id, inv_context_manager.cache_key)
2398 2421 # re-compute and store cache if we get invalidate signal
2399 2422 if invalidation_context.should_invalidate():
2400 2423 instance = get_instance_cached.refresh(*args)
2401 2424 else:
2402 2425 instance = get_instance_cached(*args)
2403 2426
2404 2427 log.debug(
2405 2428 'Repo instance fetched in %.3fs', inv_context_manager.compute_time)
2406 2429 return instance
2407 2430
2408 2431 def _get_instance(self, cache=True, config=None):
2409 2432 config = config or self._config
2410 2433 custom_wire = {
2411 2434 'cache': cache # controls the vcs.remote cache
2412 2435 }
2413 2436 repo = get_vcs_instance(
2414 2437 repo_path=safe_str(self.repo_full_path),
2415 2438 config=config,
2416 2439 with_wire=custom_wire,
2417 2440 create=False,
2418 2441 _vcs_alias=self.repo_type)
2419 2442
2420 2443 return repo
2421 2444
2422 2445 def __json__(self):
2423 2446 return {'landing_rev': self.landing_rev}
2424 2447
2425 2448 def get_dict(self):
2426 2449
2427 2450 # Since we transformed `repo_name` to a hybrid property, we need to
2428 2451 # keep compatibility with the code which uses `repo_name` field.
2429 2452
2430 2453 result = super(Repository, self).get_dict()
2431 2454 result['repo_name'] = result.pop('_repo_name', None)
2432 2455 return result
2433 2456
2434 2457
2435 2458 class RepoGroup(Base, BaseModel):
2436 2459 __tablename__ = 'groups'
2437 2460 __table_args__ = (
2438 2461 UniqueConstraint('group_name', 'group_parent_id'),
2439 2462 CheckConstraint('group_id != group_parent_id'),
2440 2463 base_table_args,
2441 2464 )
2442 2465 __mapper_args__ = {'order_by': 'group_name'}
2443 2466
2444 2467 CHOICES_SEPARATOR = '/' # used to generate select2 choices for nested groups
2445 2468
2446 2469 group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2447 2470 group_name = Column("group_name", String(255), nullable=False, unique=True, default=None)
2448 2471 group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
2449 2472 group_description = Column("group_description", String(10000), nullable=True, unique=None, default=None)
2450 2473 enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
2451 2474 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
2452 2475 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
2453 2476 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
2454 2477 personal = Column('personal', Boolean(), nullable=True, unique=None, default=None)
2455 2478
2456 2479 repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id')
2457 2480 users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
2458 2481 parent_group = relationship('RepoGroup', remote_side=group_id)
2459 2482 user = relationship('User')
2460 2483 integrations = relationship('Integration',
2461 2484 cascade="all, delete, delete-orphan")
2462 2485
2463 2486 def __init__(self, group_name='', parent_group=None):
2464 2487 self.group_name = group_name
2465 2488 self.parent_group = parent_group
2466 2489
2467 2490 def __unicode__(self):
2468 2491 return u"<%s('id:%s:%s')>" % (
2469 2492 self.__class__.__name__, self.group_id, self.group_name)
2470 2493
2471 2494 @hybrid_property
2472 2495 def description_safe(self):
2473 2496 from rhodecode.lib import helpers as h
2474 2497 return h.escape(self.group_description)
2475 2498
2476 2499 @classmethod
2477 2500 def _generate_choice(cls, repo_group):
2478 2501 from webhelpers.html import literal as _literal
2479 2502 _name = lambda k: _literal(cls.CHOICES_SEPARATOR.join(k))
2480 2503 return repo_group.group_id, _name(repo_group.full_path_splitted)
2481 2504
2482 2505 @classmethod
2483 2506 def groups_choices(cls, groups=None, show_empty_group=True):
2484 2507 if not groups:
2485 2508 groups = cls.query().all()
2486 2509
2487 2510 repo_groups = []
2488 2511 if show_empty_group:
2489 2512 repo_groups = [(-1, u'-- %s --' % _('No parent'))]
2490 2513
2491 2514 repo_groups.extend([cls._generate_choice(x) for x in groups])
2492 2515
2493 2516 repo_groups = sorted(
2494 2517 repo_groups, key=lambda t: t[1].split(cls.CHOICES_SEPARATOR)[0])
2495 2518 return repo_groups
2496 2519
2497 2520 @classmethod
2498 2521 def url_sep(cls):
2499 2522 return URL_SEP
2500 2523
2501 2524 @classmethod
2502 2525 def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
2503 2526 if case_insensitive:
2504 2527 gr = cls.query().filter(func.lower(cls.group_name)
2505 2528 == func.lower(group_name))
2506 2529 else:
2507 2530 gr = cls.query().filter(cls.group_name == group_name)
2508 2531 if cache:
2509 2532 name_key = _hash_key(group_name)
2510 2533 gr = gr.options(
2511 2534 FromCache("sql_cache_short", "get_group_%s" % name_key))
2512 2535 return gr.scalar()
2513 2536
2514 2537 @classmethod
2515 2538 def get_user_personal_repo_group(cls, user_id):
2516 2539 user = User.get(user_id)
2517 2540 if user.username == User.DEFAULT_USER:
2518 2541 return None
2519 2542
2520 2543 return cls.query()\
2521 2544 .filter(cls.personal == true()) \
2522 2545 .filter(cls.user == user) \
2523 2546 .order_by(cls.group_id.asc()) \
2524 2547 .first()
2525 2548
2526 2549 @classmethod
2527 2550 def get_all_repo_groups(cls, user_id=Optional(None), group_id=Optional(None),
2528 2551 case_insensitive=True):
2529 2552 q = RepoGroup.query()
2530 2553
2531 2554 if not isinstance(user_id, Optional):
2532 2555 q = q.filter(RepoGroup.user_id == user_id)
2533 2556
2534 2557 if not isinstance(group_id, Optional):
2535 2558 q = q.filter(RepoGroup.group_parent_id == group_id)
2536 2559
2537 2560 if case_insensitive:
2538 2561 q = q.order_by(func.lower(RepoGroup.group_name))
2539 2562 else:
2540 2563 q = q.order_by(RepoGroup.group_name)
2541 2564 return q.all()
2542 2565
2543 2566 @property
2544 2567 def parents(self):
2545 2568 parents_recursion_limit = 10
2546 2569 groups = []
2547 2570 if self.parent_group is None:
2548 2571 return groups
2549 2572 cur_gr = self.parent_group
2550 2573 groups.insert(0, cur_gr)
2551 2574 cnt = 0
2552 2575 while 1:
2553 2576 cnt += 1
2554 2577 gr = getattr(cur_gr, 'parent_group', None)
2555 2578 cur_gr = cur_gr.parent_group
2556 2579 if gr is None:
2557 2580 break
2558 2581 if cnt == parents_recursion_limit:
2559 2582 # this will prevent accidental infinit loops
2560 2583 log.error('more than %s parents found for group %s, stopping '
2561 2584 'recursive parent fetching', parents_recursion_limit, self)
2562 2585 break
2563 2586
2564 2587 groups.insert(0, gr)
2565 2588 return groups
2566 2589
2567 2590 @property
2568 2591 def last_db_change(self):
2569 2592 return self.updated_on
2570 2593
2571 2594 @property
2572 2595 def children(self):
2573 2596 return RepoGroup.query().filter(RepoGroup.parent_group == self)
2574 2597
2575 2598 @property
2576 2599 def name(self):
2577 2600 return self.group_name.split(RepoGroup.url_sep())[-1]
2578 2601
2579 2602 @property
2580 2603 def full_path(self):
2581 2604 return self.group_name
2582 2605
2583 2606 @property
2584 2607 def full_path_splitted(self):
2585 2608 return self.group_name.split(RepoGroup.url_sep())
2586 2609
2587 2610 @property
2588 2611 def repositories(self):
2589 2612 return Repository.query()\
2590 2613 .filter(Repository.group == self)\
2591 2614 .order_by(Repository.repo_name)
2592 2615
2593 2616 @property
2594 2617 def repositories_recursive_count(self):
2595 2618 cnt = self.repositories.count()
2596 2619
2597 2620 def children_count(group):
2598 2621 cnt = 0
2599 2622 for child in group.children:
2600 2623 cnt += child.repositories.count()
2601 2624 cnt += children_count(child)
2602 2625 return cnt
2603 2626
2604 2627 return cnt + children_count(self)
2605 2628
2606 2629 def _recursive_objects(self, include_repos=True):
2607 2630 all_ = []
2608 2631
2609 2632 def _get_members(root_gr):
2610 2633 if include_repos:
2611 2634 for r in root_gr.repositories:
2612 2635 all_.append(r)
2613 2636 childs = root_gr.children.all()
2614 2637 if childs:
2615 2638 for gr in childs:
2616 2639 all_.append(gr)
2617 2640 _get_members(gr)
2618 2641
2619 2642 _get_members(self)
2620 2643 return [self] + all_
2621 2644
2622 2645 def recursive_groups_and_repos(self):
2623 2646 """
2624 2647 Recursive return all groups, with repositories in those groups
2625 2648 """
2626 2649 return self._recursive_objects()
2627 2650
2628 2651 def recursive_groups(self):
2629 2652 """
2630 2653 Returns all children groups for this group including children of children
2631 2654 """
2632 2655 return self._recursive_objects(include_repos=False)
2633 2656
2634 2657 def get_new_name(self, group_name):
2635 2658 """
2636 2659 returns new full group name based on parent and new name
2637 2660
2638 2661 :param group_name:
2639 2662 """
2640 2663 path_prefix = (self.parent_group.full_path_splitted if
2641 2664 self.parent_group else [])
2642 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 2670 Permissions for repository groups
2647 2671 """
2648 2672 _admin_perm = 'group.admin'
2649 2673
2650 2674 owner_row = []
2651 2675 if with_owner:
2652 2676 usr = AttributeDict(self.user.get_dict())
2653 2677 usr.owner_row = True
2654 2678 usr.permission = _admin_perm
2655 2679 owner_row.append(usr)
2656 2680
2657 2681 super_admin_ids = []
2658 2682 super_admin_rows = []
2659 2683 if with_admins:
2660 2684 for usr in User.get_all_super_admins():
2661 2685 super_admin_ids.append(usr.user_id)
2662 2686 # if this admin is also owner, don't double the record
2663 2687 if usr.user_id == owner_row[0].user_id:
2664 2688 owner_row[0].admin_row = True
2665 2689 else:
2666 2690 usr = AttributeDict(usr.get_dict())
2667 2691 usr.admin_row = True
2668 2692 usr.permission = _admin_perm
2669 2693 super_admin_rows.append(usr)
2670 2694
2671 2695 q = UserRepoGroupToPerm.query().filter(UserRepoGroupToPerm.group == self)
2672 2696 q = q.options(joinedload(UserRepoGroupToPerm.group),
2673 2697 joinedload(UserRepoGroupToPerm.user),
2674 2698 joinedload(UserRepoGroupToPerm.permission),)
2675 2699
2676 2700 # get owners and admins and permissions. We do a trick of re-writing
2677 2701 # objects from sqlalchemy to named-tuples due to sqlalchemy session
2678 2702 # has a global reference and changing one object propagates to all
2679 2703 # others. This means if admin is also an owner admin_row that change
2680 2704 # would propagate to both objects
2681 2705 perm_rows = []
2682 2706 for _usr in q.all():
2683 2707 usr = AttributeDict(_usr.user.get_dict())
2684 2708 # if this user is also owner/admin, mark as duplicate record
2685 2709 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
2686 2710 usr.duplicate_perm = True
2687 2711 usr.permission = _usr.permission.permission_name
2688 2712 perm_rows.append(usr)
2689 2713
2690 2714 # filter the perm rows by 'default' first and then sort them by
2691 2715 # admin,write,read,none permissions sorted again alphabetically in
2692 2716 # each group
2693 2717 perm_rows = sorted(perm_rows, key=display_user_sort)
2694 2718
2695 return super_admin_rows + owner_row + perm_rows
2696
2697 def permission_user_groups(self):
2698 q = UserGroupRepoGroupToPerm.query().filter(
2699 UserGroupRepoGroupToPerm.group == self)
2719 user_groups_rows = []
2720 if expand_from_user_groups:
2721 for ug in self.permission_user_groups(with_members=True):
2722 for user_data in ug.members:
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 2730 q = q.options(joinedload(UserGroupRepoGroupToPerm.group),
2701 2731 joinedload(UserGroupRepoGroupToPerm.users_group),
2702 2732 joinedload(UserGroupRepoGroupToPerm.permission),)
2703 2733
2704 2734 perm_rows = []
2705 2735 for _user_group in q.all():
2706 usr = AttributeDict(_user_group.users_group.get_dict())
2707 usr.permission = _user_group.permission.permission_name
2708 perm_rows.append(usr)
2736 entry = AttributeDict(_user_group.users_group.get_dict())
2737 entry.permission = _user_group.permission.permission_name
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 2743 perm_rows = sorted(perm_rows, key=display_user_group_sort)
2711 2744 return perm_rows
2712 2745
2713 2746 def get_api_data(self):
2714 2747 """
2715 2748 Common function for generating api data
2716 2749
2717 2750 """
2718 2751 group = self
2719 2752 data = {
2720 2753 'group_id': group.group_id,
2721 2754 'group_name': group.group_name,
2722 2755 'group_description': group.description_safe,
2723 2756 'parent_group': group.parent_group.group_name if group.parent_group else None,
2724 2757 'repositories': [x.repo_name for x in group.repositories],
2725 2758 'owner': group.user.username,
2726 2759 }
2727 2760 return data
2728 2761
2729 2762
2730 2763 class Permission(Base, BaseModel):
2731 2764 __tablename__ = 'permissions'
2732 2765 __table_args__ = (
2733 2766 Index('p_perm_name_idx', 'permission_name'),
2734 2767 base_table_args,
2735 2768 )
2736 2769
2737 2770 PERMS = [
2738 2771 ('hg.admin', _('RhodeCode Super Administrator')),
2739 2772
2740 2773 ('repository.none', _('Repository no access')),
2741 2774 ('repository.read', _('Repository read access')),
2742 2775 ('repository.write', _('Repository write access')),
2743 2776 ('repository.admin', _('Repository admin access')),
2744 2777
2745 2778 ('group.none', _('Repository group no access')),
2746 2779 ('group.read', _('Repository group read access')),
2747 2780 ('group.write', _('Repository group write access')),
2748 2781 ('group.admin', _('Repository group admin access')),
2749 2782
2750 2783 ('usergroup.none', _('User group no access')),
2751 2784 ('usergroup.read', _('User group read access')),
2752 2785 ('usergroup.write', _('User group write access')),
2753 2786 ('usergroup.admin', _('User group admin access')),
2754 2787
2755 2788 ('branch.none', _('Branch no permissions')),
2756 2789 ('branch.merge', _('Branch access by web merge')),
2757 2790 ('branch.push', _('Branch access by push')),
2758 2791 ('branch.push_force', _('Branch access by push with force')),
2759 2792
2760 2793 ('hg.repogroup.create.false', _('Repository Group creation disabled')),
2761 2794 ('hg.repogroup.create.true', _('Repository Group creation enabled')),
2762 2795
2763 2796 ('hg.usergroup.create.false', _('User Group creation disabled')),
2764 2797 ('hg.usergroup.create.true', _('User Group creation enabled')),
2765 2798
2766 2799 ('hg.create.none', _('Repository creation disabled')),
2767 2800 ('hg.create.repository', _('Repository creation enabled')),
2768 2801 ('hg.create.write_on_repogroup.true', _('Repository creation enabled with write permission to a repository group')),
2769 2802 ('hg.create.write_on_repogroup.false', _('Repository creation disabled with write permission to a repository group')),
2770 2803
2771 2804 ('hg.fork.none', _('Repository forking disabled')),
2772 2805 ('hg.fork.repository', _('Repository forking enabled')),
2773 2806
2774 2807 ('hg.register.none', _('Registration disabled')),
2775 2808 ('hg.register.manual_activate', _('User Registration with manual account activation')),
2776 2809 ('hg.register.auto_activate', _('User Registration with automatic account activation')),
2777 2810
2778 2811 ('hg.password_reset.enabled', _('Password reset enabled')),
2779 2812 ('hg.password_reset.hidden', _('Password reset hidden')),
2780 2813 ('hg.password_reset.disabled', _('Password reset disabled')),
2781 2814
2782 2815 ('hg.extern_activate.manual', _('Manual activation of external account')),
2783 2816 ('hg.extern_activate.auto', _('Automatic activation of external account')),
2784 2817
2785 2818 ('hg.inherit_default_perms.false', _('Inherit object permissions from default user disabled')),
2786 2819 ('hg.inherit_default_perms.true', _('Inherit object permissions from default user enabled')),
2787 2820 ]
2788 2821
2789 2822 # definition of system default permissions for DEFAULT user, created on
2790 2823 # system setup
2791 2824 DEFAULT_USER_PERMISSIONS = [
2792 2825 # object perms
2793 2826 'repository.read',
2794 2827 'group.read',
2795 2828 'usergroup.read',
2796 2829 # branch, for backward compat we need same value as before so forced pushed
2797 2830 'branch.push_force',
2798 2831 # global
2799 2832 'hg.create.repository',
2800 2833 'hg.repogroup.create.false',
2801 2834 'hg.usergroup.create.false',
2802 2835 'hg.create.write_on_repogroup.true',
2803 2836 'hg.fork.repository',
2804 2837 'hg.register.manual_activate',
2805 2838 'hg.password_reset.enabled',
2806 2839 'hg.extern_activate.auto',
2807 2840 'hg.inherit_default_perms.true',
2808 2841 ]
2809 2842
2810 2843 # defines which permissions are more important higher the more important
2811 2844 # Weight defines which permissions are more important.
2812 2845 # The higher number the more important.
2813 2846 PERM_WEIGHTS = {
2814 2847 'repository.none': 0,
2815 2848 'repository.read': 1,
2816 2849 'repository.write': 3,
2817 2850 'repository.admin': 4,
2818 2851
2819 2852 'group.none': 0,
2820 2853 'group.read': 1,
2821 2854 'group.write': 3,
2822 2855 'group.admin': 4,
2823 2856
2824 2857 'usergroup.none': 0,
2825 2858 'usergroup.read': 1,
2826 2859 'usergroup.write': 3,
2827 2860 'usergroup.admin': 4,
2828 2861
2829 2862 'branch.none': 0,
2830 2863 'branch.merge': 1,
2831 2864 'branch.push': 3,
2832 2865 'branch.push_force': 4,
2833 2866
2834 2867 'hg.repogroup.create.false': 0,
2835 2868 'hg.repogroup.create.true': 1,
2836 2869
2837 2870 'hg.usergroup.create.false': 0,
2838 2871 'hg.usergroup.create.true': 1,
2839 2872
2840 2873 'hg.fork.none': 0,
2841 2874 'hg.fork.repository': 1,
2842 2875 'hg.create.none': 0,
2843 2876 'hg.create.repository': 1
2844 2877 }
2845 2878
2846 2879 permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2847 2880 permission_name = Column("permission_name", String(255), nullable=True, unique=None, default=None)
2848 2881 permission_longname = Column("permission_longname", String(255), nullable=True, unique=None, default=None)
2849 2882
2850 2883 def __unicode__(self):
2851 2884 return u"<%s('%s:%s')>" % (
2852 2885 self.__class__.__name__, self.permission_id, self.permission_name
2853 2886 )
2854 2887
2855 2888 @classmethod
2856 2889 def get_by_key(cls, key):
2857 2890 return cls.query().filter(cls.permission_name == key).scalar()
2858 2891
2859 2892 @classmethod
2860 2893 def get_default_repo_perms(cls, user_id, repo_id=None):
2861 2894 q = Session().query(UserRepoToPerm, Repository, Permission)\
2862 2895 .join((Permission, UserRepoToPerm.permission_id == Permission.permission_id))\
2863 2896 .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\
2864 2897 .filter(UserRepoToPerm.user_id == user_id)
2865 2898 if repo_id:
2866 2899 q = q.filter(UserRepoToPerm.repository_id == repo_id)
2867 2900 return q.all()
2868 2901
2869 2902 @classmethod
2870 2903 def get_default_repo_branch_perms(cls, user_id, repo_id=None):
2871 2904 q = Session().query(UserToRepoBranchPermission, UserRepoToPerm, Permission) \
2872 2905 .join(
2873 2906 Permission,
2874 2907 UserToRepoBranchPermission.permission_id == Permission.permission_id) \
2875 2908 .join(
2876 2909 UserRepoToPerm,
2877 2910 UserToRepoBranchPermission.rule_to_perm_id == UserRepoToPerm.repo_to_perm_id) \
2878 2911 .filter(UserRepoToPerm.user_id == user_id)
2879 2912
2880 2913 if repo_id:
2881 2914 q = q.filter(UserToRepoBranchPermission.repository_id == repo_id)
2882 2915 return q.order_by(UserToRepoBranchPermission.rule_order).all()
2883 2916
2884 2917 @classmethod
2885 2918 def get_default_repo_perms_from_user_group(cls, user_id, repo_id=None):
2886 2919 q = Session().query(UserGroupRepoToPerm, Repository, Permission)\
2887 2920 .join(
2888 2921 Permission,
2889 2922 UserGroupRepoToPerm.permission_id == Permission.permission_id)\
2890 2923 .join(
2891 2924 Repository,
2892 2925 UserGroupRepoToPerm.repository_id == Repository.repo_id)\
2893 2926 .join(
2894 2927 UserGroup,
2895 2928 UserGroupRepoToPerm.users_group_id ==
2896 2929 UserGroup.users_group_id)\
2897 2930 .join(
2898 2931 UserGroupMember,
2899 2932 UserGroupRepoToPerm.users_group_id ==
2900 2933 UserGroupMember.users_group_id)\
2901 2934 .filter(
2902 2935 UserGroupMember.user_id == user_id,
2903 2936 UserGroup.users_group_active == true())
2904 2937 if repo_id:
2905 2938 q = q.filter(UserGroupRepoToPerm.repository_id == repo_id)
2906 2939 return q.all()
2907 2940
2908 2941 @classmethod
2909 2942 def get_default_repo_branch_perms_from_user_group(cls, user_id, repo_id=None):
2910 2943 q = Session().query(UserGroupToRepoBranchPermission, UserGroupRepoToPerm, Permission) \
2911 2944 .join(
2912 2945 Permission,
2913 2946 UserGroupToRepoBranchPermission.permission_id == Permission.permission_id) \
2914 2947 .join(
2915 2948 UserGroupRepoToPerm,
2916 2949 UserGroupToRepoBranchPermission.rule_to_perm_id == UserGroupRepoToPerm.users_group_to_perm_id) \
2917 2950 .join(
2918 2951 UserGroup,
2919 2952 UserGroupRepoToPerm.users_group_id == UserGroup.users_group_id) \
2920 2953 .join(
2921 2954 UserGroupMember,
2922 2955 UserGroupRepoToPerm.users_group_id == UserGroupMember.users_group_id) \
2923 2956 .filter(
2924 2957 UserGroupMember.user_id == user_id,
2925 2958 UserGroup.users_group_active == true())
2926 2959
2927 2960 if repo_id:
2928 2961 q = q.filter(UserGroupToRepoBranchPermission.repository_id == repo_id)
2929 2962 return q.order_by(UserGroupToRepoBranchPermission.rule_order).all()
2930 2963
2931 2964 @classmethod
2932 2965 def get_default_group_perms(cls, user_id, repo_group_id=None):
2933 2966 q = Session().query(UserRepoGroupToPerm, RepoGroup, Permission)\
2934 2967 .join(
2935 2968 Permission,
2936 2969 UserRepoGroupToPerm.permission_id == Permission.permission_id)\
2937 2970 .join(
2938 2971 RepoGroup,
2939 2972 UserRepoGroupToPerm.group_id == RepoGroup.group_id)\
2940 2973 .filter(UserRepoGroupToPerm.user_id == user_id)
2941 2974 if repo_group_id:
2942 2975 q = q.filter(UserRepoGroupToPerm.group_id == repo_group_id)
2943 2976 return q.all()
2944 2977
2945 2978 @classmethod
2946 2979 def get_default_group_perms_from_user_group(
2947 2980 cls, user_id, repo_group_id=None):
2948 2981 q = Session().query(UserGroupRepoGroupToPerm, RepoGroup, Permission)\
2949 2982 .join(
2950 2983 Permission,
2951 2984 UserGroupRepoGroupToPerm.permission_id ==
2952 2985 Permission.permission_id)\
2953 2986 .join(
2954 2987 RepoGroup,
2955 2988 UserGroupRepoGroupToPerm.group_id == RepoGroup.group_id)\
2956 2989 .join(
2957 2990 UserGroup,
2958 2991 UserGroupRepoGroupToPerm.users_group_id ==
2959 2992 UserGroup.users_group_id)\
2960 2993 .join(
2961 2994 UserGroupMember,
2962 2995 UserGroupRepoGroupToPerm.users_group_id ==
2963 2996 UserGroupMember.users_group_id)\
2964 2997 .filter(
2965 2998 UserGroupMember.user_id == user_id,
2966 2999 UserGroup.users_group_active == true())
2967 3000 if repo_group_id:
2968 3001 q = q.filter(UserGroupRepoGroupToPerm.group_id == repo_group_id)
2969 3002 return q.all()
2970 3003
2971 3004 @classmethod
2972 3005 def get_default_user_group_perms(cls, user_id, user_group_id=None):
2973 3006 q = Session().query(UserUserGroupToPerm, UserGroup, Permission)\
2974 3007 .join((Permission, UserUserGroupToPerm.permission_id == Permission.permission_id))\
2975 3008 .join((UserGroup, UserUserGroupToPerm.user_group_id == UserGroup.users_group_id))\
2976 3009 .filter(UserUserGroupToPerm.user_id == user_id)
2977 3010 if user_group_id:
2978 3011 q = q.filter(UserUserGroupToPerm.user_group_id == user_group_id)
2979 3012 return q.all()
2980 3013
2981 3014 @classmethod
2982 3015 def get_default_user_group_perms_from_user_group(
2983 3016 cls, user_id, user_group_id=None):
2984 3017 TargetUserGroup = aliased(UserGroup, name='target_user_group')
2985 3018 q = Session().query(UserGroupUserGroupToPerm, UserGroup, Permission)\
2986 3019 .join(
2987 3020 Permission,
2988 3021 UserGroupUserGroupToPerm.permission_id ==
2989 3022 Permission.permission_id)\
2990 3023 .join(
2991 3024 TargetUserGroup,
2992 3025 UserGroupUserGroupToPerm.target_user_group_id ==
2993 3026 TargetUserGroup.users_group_id)\
2994 3027 .join(
2995 3028 UserGroup,
2996 3029 UserGroupUserGroupToPerm.user_group_id ==
2997 3030 UserGroup.users_group_id)\
2998 3031 .join(
2999 3032 UserGroupMember,
3000 3033 UserGroupUserGroupToPerm.user_group_id ==
3001 3034 UserGroupMember.users_group_id)\
3002 3035 .filter(
3003 3036 UserGroupMember.user_id == user_id,
3004 3037 UserGroup.users_group_active == true())
3005 3038 if user_group_id:
3006 3039 q = q.filter(
3007 3040 UserGroupUserGroupToPerm.user_group_id == user_group_id)
3008 3041
3009 3042 return q.all()
3010 3043
3011 3044
3012 3045 class UserRepoToPerm(Base, BaseModel):
3013 3046 __tablename__ = 'repo_to_perm'
3014 3047 __table_args__ = (
3015 3048 UniqueConstraint('user_id', 'repository_id', 'permission_id'),
3016 3049 base_table_args
3017 3050 )
3018 3051
3019 3052 repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3020 3053 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3021 3054 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3022 3055 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
3023 3056
3024 3057 user = relationship('User')
3025 3058 repository = relationship('Repository')
3026 3059 permission = relationship('Permission')
3027 3060
3028 3061 branch_perm_entry = relationship('UserToRepoBranchPermission', cascade="all, delete, delete-orphan", lazy='joined')
3029 3062
3030 3063 @classmethod
3031 3064 def create(cls, user, repository, permission):
3032 3065 n = cls()
3033 3066 n.user = user
3034 3067 n.repository = repository
3035 3068 n.permission = permission
3036 3069 Session().add(n)
3037 3070 return n
3038 3071
3039 3072 def __unicode__(self):
3040 3073 return u'<%s => %s >' % (self.user, self.repository)
3041 3074
3042 3075
3043 3076 class UserUserGroupToPerm(Base, BaseModel):
3044 3077 __tablename__ = 'user_user_group_to_perm'
3045 3078 __table_args__ = (
3046 3079 UniqueConstraint('user_id', 'user_group_id', 'permission_id'),
3047 3080 base_table_args
3048 3081 )
3049 3082
3050 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 3084 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3052 3085 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3053 3086 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3054 3087
3055 3088 user = relationship('User')
3056 3089 user_group = relationship('UserGroup')
3057 3090 permission = relationship('Permission')
3058 3091
3059 3092 @classmethod
3060 3093 def create(cls, user, user_group, permission):
3061 3094 n = cls()
3062 3095 n.user = user
3063 3096 n.user_group = user_group
3064 3097 n.permission = permission
3065 3098 Session().add(n)
3066 3099 return n
3067 3100
3068 3101 def __unicode__(self):
3069 3102 return u'<%s => %s >' % (self.user, self.user_group)
3070 3103
3071 3104
3072 3105 class UserToPerm(Base, BaseModel):
3073 3106 __tablename__ = 'user_to_perm'
3074 3107 __table_args__ = (
3075 3108 UniqueConstraint('user_id', 'permission_id'),
3076 3109 base_table_args
3077 3110 )
3078 3111
3079 3112 user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3080 3113 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3081 3114 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3082 3115
3083 3116 user = relationship('User')
3084 3117 permission = relationship('Permission', lazy='joined')
3085 3118
3086 3119 def __unicode__(self):
3087 3120 return u'<%s => %s >' % (self.user, self.permission)
3088 3121
3089 3122
3090 3123 class UserGroupRepoToPerm(Base, BaseModel):
3091 3124 __tablename__ = 'users_group_repo_to_perm'
3092 3125 __table_args__ = (
3093 3126 UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
3094 3127 base_table_args
3095 3128 )
3096 3129
3097 3130 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3098 3131 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3099 3132 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3100 3133 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
3101 3134
3102 3135 users_group = relationship('UserGroup')
3103 3136 permission = relationship('Permission')
3104 3137 repository = relationship('Repository')
3105 3138 user_group_branch_perms = relationship('UserGroupToRepoBranchPermission', cascade='all')
3106 3139
3107 3140 @classmethod
3108 3141 def create(cls, users_group, repository, permission):
3109 3142 n = cls()
3110 3143 n.users_group = users_group
3111 3144 n.repository = repository
3112 3145 n.permission = permission
3113 3146 Session().add(n)
3114 3147 return n
3115 3148
3116 3149 def __unicode__(self):
3117 3150 return u'<UserGroupRepoToPerm:%s => %s >' % (self.users_group, self.repository)
3118 3151
3119 3152
3120 3153 class UserGroupUserGroupToPerm(Base, BaseModel):
3121 3154 __tablename__ = 'user_group_user_group_to_perm'
3122 3155 __table_args__ = (
3123 3156 UniqueConstraint('target_user_group_id', 'user_group_id', 'permission_id'),
3124 3157 CheckConstraint('target_user_group_id != user_group_id'),
3125 3158 base_table_args
3126 3159 )
3127 3160
3128 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 3162 target_user_group_id = Column("target_user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3130 3163 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3131 3164 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3132 3165
3133 3166 target_user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id')
3134 3167 user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.user_group_id==UserGroup.users_group_id')
3135 3168 permission = relationship('Permission')
3136 3169
3137 3170 @classmethod
3138 3171 def create(cls, target_user_group, user_group, permission):
3139 3172 n = cls()
3140 3173 n.target_user_group = target_user_group
3141 3174 n.user_group = user_group
3142 3175 n.permission = permission
3143 3176 Session().add(n)
3144 3177 return n
3145 3178
3146 3179 def __unicode__(self):
3147 3180 return u'<UserGroupUserGroup:%s => %s >' % (self.target_user_group, self.user_group)
3148 3181
3149 3182
3150 3183 class UserGroupToPerm(Base, BaseModel):
3151 3184 __tablename__ = 'users_group_to_perm'
3152 3185 __table_args__ = (
3153 3186 UniqueConstraint('users_group_id', 'permission_id',),
3154 3187 base_table_args
3155 3188 )
3156 3189
3157 3190 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3158 3191 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3159 3192 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3160 3193
3161 3194 users_group = relationship('UserGroup')
3162 3195 permission = relationship('Permission')
3163 3196
3164 3197
3165 3198 class UserRepoGroupToPerm(Base, BaseModel):
3166 3199 __tablename__ = 'user_repo_group_to_perm'
3167 3200 __table_args__ = (
3168 3201 UniqueConstraint('user_id', 'group_id', 'permission_id'),
3169 3202 base_table_args
3170 3203 )
3171 3204
3172 3205 group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3173 3206 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3174 3207 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
3175 3208 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3176 3209
3177 3210 user = relationship('User')
3178 3211 group = relationship('RepoGroup')
3179 3212 permission = relationship('Permission')
3180 3213
3181 3214 @classmethod
3182 3215 def create(cls, user, repository_group, permission):
3183 3216 n = cls()
3184 3217 n.user = user
3185 3218 n.group = repository_group
3186 3219 n.permission = permission
3187 3220 Session().add(n)
3188 3221 return n
3189 3222
3190 3223
3191 3224 class UserGroupRepoGroupToPerm(Base, BaseModel):
3192 3225 __tablename__ = 'users_group_repo_group_to_perm'
3193 3226 __table_args__ = (
3194 3227 UniqueConstraint('users_group_id', 'group_id'),
3195 3228 base_table_args
3196 3229 )
3197 3230
3198 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 3232 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3200 3233 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
3201 3234 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3202 3235
3203 3236 users_group = relationship('UserGroup')
3204 3237 permission = relationship('Permission')
3205 3238 group = relationship('RepoGroup')
3206 3239
3207 3240 @classmethod
3208 3241 def create(cls, user_group, repository_group, permission):
3209 3242 n = cls()
3210 3243 n.users_group = user_group
3211 3244 n.group = repository_group
3212 3245 n.permission = permission
3213 3246 Session().add(n)
3214 3247 return n
3215 3248
3216 3249 def __unicode__(self):
3217 3250 return u'<UserGroupRepoGroupToPerm:%s => %s >' % (self.users_group, self.group)
3218 3251
3219 3252
3220 3253 class Statistics(Base, BaseModel):
3221 3254 __tablename__ = 'statistics'
3222 3255 __table_args__ = (
3223 3256 base_table_args
3224 3257 )
3225 3258
3226 3259 stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3227 3260 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
3228 3261 stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
3229 3262 commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data
3230 3263 commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data
3231 3264 languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data
3232 3265
3233 3266 repository = relationship('Repository', single_parent=True)
3234 3267
3235 3268
3236 3269 class UserFollowing(Base, BaseModel):
3237 3270 __tablename__ = 'user_followings'
3238 3271 __table_args__ = (
3239 3272 UniqueConstraint('user_id', 'follows_repository_id'),
3240 3273 UniqueConstraint('user_id', 'follows_user_id'),
3241 3274 base_table_args
3242 3275 )
3243 3276
3244 3277 user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3245 3278 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3246 3279 follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
3247 3280 follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
3248 3281 follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
3249 3282
3250 3283 user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id')
3251 3284
3252 3285 follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
3253 3286 follows_repository = relationship('Repository', order_by='Repository.repo_name')
3254 3287
3255 3288 @classmethod
3256 3289 def get_repo_followers(cls, repo_id):
3257 3290 return cls.query().filter(cls.follows_repo_id == repo_id)
3258 3291
3259 3292
3260 3293 class CacheKey(Base, BaseModel):
3261 3294 __tablename__ = 'cache_invalidation'
3262 3295 __table_args__ = (
3263 3296 UniqueConstraint('cache_key'),
3264 3297 Index('key_idx', 'cache_key'),
3265 3298 base_table_args,
3266 3299 )
3267 3300
3268 3301 CACHE_TYPE_FEED = 'FEED'
3269 3302 CACHE_TYPE_README = 'README'
3270 3303 # namespaces used to register process/thread aware caches
3271 3304 REPO_INVALIDATION_NAMESPACE = 'repo_cache:{repo_id}'
3272 3305 SETTINGS_INVALIDATION_NAMESPACE = 'system_settings'
3273 3306
3274 3307 cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3275 3308 cache_key = Column("cache_key", String(255), nullable=True, unique=None, default=None)
3276 3309 cache_args = Column("cache_args", String(255), nullable=True, unique=None, default=None)
3277 3310 cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
3278 3311
3279 3312 def __init__(self, cache_key, cache_args=''):
3280 3313 self.cache_key = cache_key
3281 3314 self.cache_args = cache_args
3282 3315 self.cache_active = False
3283 3316
3284 3317 def __unicode__(self):
3285 3318 return u"<%s('%s:%s[%s]')>" % (
3286 3319 self.__class__.__name__,
3287 3320 self.cache_id, self.cache_key, self.cache_active)
3288 3321
3289 3322 def _cache_key_partition(self):
3290 3323 prefix, repo_name, suffix = self.cache_key.partition(self.cache_args)
3291 3324 return prefix, repo_name, suffix
3292 3325
3293 3326 def get_prefix(self):
3294 3327 """
3295 3328 Try to extract prefix from existing cache key. The key could consist
3296 3329 of prefix, repo_name, suffix
3297 3330 """
3298 3331 # this returns prefix, repo_name, suffix
3299 3332 return self._cache_key_partition()[0]
3300 3333
3301 3334 def get_suffix(self):
3302 3335 """
3303 3336 get suffix that might have been used in _get_cache_key to
3304 3337 generate self.cache_key. Only used for informational purposes
3305 3338 in repo_edit.mako.
3306 3339 """
3307 3340 # prefix, repo_name, suffix
3308 3341 return self._cache_key_partition()[2]
3309 3342
3310 3343 @classmethod
3311 3344 def delete_all_cache(cls):
3312 3345 """
3313 3346 Delete all cache keys from database.
3314 3347 Should only be run when all instances are down and all entries
3315 3348 thus stale.
3316 3349 """
3317 3350 cls.query().delete()
3318 3351 Session().commit()
3319 3352
3320 3353 @classmethod
3321 3354 def set_invalidate(cls, cache_uid, delete=False):
3322 3355 """
3323 3356 Mark all caches of a repo as invalid in the database.
3324 3357 """
3325 3358
3326 3359 try:
3327 3360 qry = Session().query(cls).filter(cls.cache_args == cache_uid)
3328 3361 if delete:
3329 3362 qry.delete()
3330 3363 log.debug('cache objects deleted for cache args %s',
3331 3364 safe_str(cache_uid))
3332 3365 else:
3333 3366 qry.update({"cache_active": False})
3334 3367 log.debug('cache objects marked as invalid for cache args %s',
3335 3368 safe_str(cache_uid))
3336 3369
3337 3370 Session().commit()
3338 3371 except Exception:
3339 3372 log.exception(
3340 3373 'Cache key invalidation failed for cache args %s',
3341 3374 safe_str(cache_uid))
3342 3375 Session().rollback()
3343 3376
3344 3377 @classmethod
3345 3378 def get_active_cache(cls, cache_key):
3346 3379 inv_obj = cls.query().filter(cls.cache_key == cache_key).scalar()
3347 3380 if inv_obj:
3348 3381 return inv_obj
3349 3382 return None
3350 3383
3351 3384
3352 3385 class ChangesetComment(Base, BaseModel):
3353 3386 __tablename__ = 'changeset_comments'
3354 3387 __table_args__ = (
3355 3388 Index('cc_revision_idx', 'revision'),
3356 3389 base_table_args,
3357 3390 )
3358 3391
3359 3392 COMMENT_OUTDATED = u'comment_outdated'
3360 3393 COMMENT_TYPE_NOTE = u'note'
3361 3394 COMMENT_TYPE_TODO = u'todo'
3362 3395 COMMENT_TYPES = [COMMENT_TYPE_NOTE, COMMENT_TYPE_TODO]
3363 3396
3364 3397 comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True)
3365 3398 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3366 3399 revision = Column('revision', String(40), nullable=True)
3367 3400 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3368 3401 pull_request_version_id = Column("pull_request_version_id", Integer(), ForeignKey('pull_request_versions.pull_request_version_id'), nullable=True)
3369 3402 line_no = Column('line_no', Unicode(10), nullable=True)
3370 3403 hl_lines = Column('hl_lines', Unicode(512), nullable=True)
3371 3404 f_path = Column('f_path', Unicode(1000), nullable=True)
3372 3405 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
3373 3406 text = Column('text', UnicodeText().with_variant(UnicodeText(25000), 'mysql'), nullable=False)
3374 3407 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3375 3408 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3376 3409 renderer = Column('renderer', Unicode(64), nullable=True)
3377 3410 display_state = Column('display_state', Unicode(128), nullable=True)
3378 3411
3379 3412 comment_type = Column('comment_type', Unicode(128), nullable=True, default=COMMENT_TYPE_NOTE)
3380 3413 resolved_comment_id = Column('resolved_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'), nullable=True)
3381 3414 resolved_comment = relationship('ChangesetComment', remote_side=comment_id, backref='resolved_by')
3382 3415 author = relationship('User', lazy='joined')
3383 3416 repo = relationship('Repository')
3384 3417 status_change = relationship('ChangesetStatus', cascade="all, delete, delete-orphan", lazy='joined')
3385 3418 pull_request = relationship('PullRequest', lazy='joined')
3386 3419 pull_request_version = relationship('PullRequestVersion')
3387 3420
3388 3421 @classmethod
3389 3422 def get_users(cls, revision=None, pull_request_id=None):
3390 3423 """
3391 3424 Returns user associated with this ChangesetComment. ie those
3392 3425 who actually commented
3393 3426
3394 3427 :param cls:
3395 3428 :param revision:
3396 3429 """
3397 3430 q = Session().query(User)\
3398 3431 .join(ChangesetComment.author)
3399 3432 if revision:
3400 3433 q = q.filter(cls.revision == revision)
3401 3434 elif pull_request_id:
3402 3435 q = q.filter(cls.pull_request_id == pull_request_id)
3403 3436 return q.all()
3404 3437
3405 3438 @classmethod
3406 3439 def get_index_from_version(cls, pr_version, versions):
3407 3440 num_versions = [x.pull_request_version_id for x in versions]
3408 3441 try:
3409 3442 return num_versions.index(pr_version) +1
3410 3443 except (IndexError, ValueError):
3411 3444 return
3412 3445
3413 3446 @property
3414 3447 def outdated(self):
3415 3448 return self.display_state == self.COMMENT_OUTDATED
3416 3449
3417 3450 def outdated_at_version(self, version):
3418 3451 """
3419 3452 Checks if comment is outdated for given pull request version
3420 3453 """
3421 3454 return self.outdated and self.pull_request_version_id != version
3422 3455
3423 3456 def older_than_version(self, version):
3424 3457 """
3425 3458 Checks if comment is made from previous version than given
3426 3459 """
3427 3460 if version is None:
3428 3461 return self.pull_request_version_id is not None
3429 3462
3430 3463 return self.pull_request_version_id < version
3431 3464
3432 3465 @property
3433 3466 def resolved(self):
3434 3467 return self.resolved_by[0] if self.resolved_by else None
3435 3468
3436 3469 @property
3437 3470 def is_todo(self):
3438 3471 return self.comment_type == self.COMMENT_TYPE_TODO
3439 3472
3440 3473 @property
3441 3474 def is_inline(self):
3442 3475 return self.line_no and self.f_path
3443 3476
3444 3477 def get_index_version(self, versions):
3445 3478 return self.get_index_from_version(
3446 3479 self.pull_request_version_id, versions)
3447 3480
3448 3481 def __repr__(self):
3449 3482 if self.comment_id:
3450 3483 return '<DB:Comment #%s>' % self.comment_id
3451 3484 else:
3452 3485 return '<DB:Comment at %#x>' % id(self)
3453 3486
3454 3487 def get_api_data(self):
3455 3488 comment = self
3456 3489 data = {
3457 3490 'comment_id': comment.comment_id,
3458 3491 'comment_type': comment.comment_type,
3459 3492 'comment_text': comment.text,
3460 3493 'comment_status': comment.status_change,
3461 3494 'comment_f_path': comment.f_path,
3462 3495 'comment_lineno': comment.line_no,
3463 3496 'comment_author': comment.author,
3464 3497 'comment_created_on': comment.created_on
3465 3498 }
3466 3499 return data
3467 3500
3468 3501 def __json__(self):
3469 3502 data = dict()
3470 3503 data.update(self.get_api_data())
3471 3504 return data
3472 3505
3473 3506
3474 3507 class ChangesetStatus(Base, BaseModel):
3475 3508 __tablename__ = 'changeset_statuses'
3476 3509 __table_args__ = (
3477 3510 Index('cs_revision_idx', 'revision'),
3478 3511 Index('cs_version_idx', 'version'),
3479 3512 UniqueConstraint('repo_id', 'revision', 'version'),
3480 3513 base_table_args
3481 3514 )
3482 3515
3483 3516 STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed'
3484 3517 STATUS_APPROVED = 'approved'
3485 3518 STATUS_REJECTED = 'rejected'
3486 3519 STATUS_UNDER_REVIEW = 'under_review'
3487 3520
3488 3521 STATUSES = [
3489 3522 (STATUS_NOT_REVIEWED, _("Not Reviewed")), # (no icon) and default
3490 3523 (STATUS_APPROVED, _("Approved")),
3491 3524 (STATUS_REJECTED, _("Rejected")),
3492 3525 (STATUS_UNDER_REVIEW, _("Under Review")),
3493 3526 ]
3494 3527
3495 3528 changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True)
3496 3529 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3497 3530 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
3498 3531 revision = Column('revision', String(40), nullable=False)
3499 3532 status = Column('status', String(128), nullable=False, default=DEFAULT)
3500 3533 changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'))
3501 3534 modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now)
3502 3535 version = Column('version', Integer(), nullable=False, default=0)
3503 3536 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3504 3537
3505 3538 author = relationship('User', lazy='joined')
3506 3539 repo = relationship('Repository')
3507 3540 comment = relationship('ChangesetComment', lazy='joined')
3508 3541 pull_request = relationship('PullRequest', lazy='joined')
3509 3542
3510 3543 def __unicode__(self):
3511 3544 return u"<%s('%s[v%s]:%s')>" % (
3512 3545 self.__class__.__name__,
3513 3546 self.status, self.version, self.author
3514 3547 )
3515 3548
3516 3549 @classmethod
3517 3550 def get_status_lbl(cls, value):
3518 3551 return dict(cls.STATUSES).get(value)
3519 3552
3520 3553 @property
3521 3554 def status_lbl(self):
3522 3555 return ChangesetStatus.get_status_lbl(self.status)
3523 3556
3524 3557 def get_api_data(self):
3525 3558 status = self
3526 3559 data = {
3527 3560 'status_id': status.changeset_status_id,
3528 3561 'status': status.status,
3529 3562 }
3530 3563 return data
3531 3564
3532 3565 def __json__(self):
3533 3566 data = dict()
3534 3567 data.update(self.get_api_data())
3535 3568 return data
3536 3569
3537 3570
3538 3571 class _PullRequestBase(BaseModel):
3539 3572 """
3540 3573 Common attributes of pull request and version entries.
3541 3574 """
3542 3575
3543 3576 # .status values
3544 3577 STATUS_NEW = u'new'
3545 3578 STATUS_OPEN = u'open'
3546 3579 STATUS_CLOSED = u'closed'
3547 3580
3548 3581 title = Column('title', Unicode(255), nullable=True)
3549 3582 description = Column(
3550 3583 'description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'),
3551 3584 nullable=True)
3552 3585 description_renderer = Column('description_renderer', Unicode(64), nullable=True)
3553 3586
3554 3587 # new/open/closed status of pull request (not approve/reject/etc)
3555 3588 status = Column('status', Unicode(255), nullable=False, default=STATUS_NEW)
3556 3589 created_on = Column(
3557 3590 'created_on', DateTime(timezone=False), nullable=False,
3558 3591 default=datetime.datetime.now)
3559 3592 updated_on = Column(
3560 3593 'updated_on', DateTime(timezone=False), nullable=False,
3561 3594 default=datetime.datetime.now)
3562 3595
3563 3596 @declared_attr
3564 3597 def user_id(cls):
3565 3598 return Column(
3566 3599 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
3567 3600 unique=None)
3568 3601
3569 3602 # 500 revisions max
3570 3603 _revisions = Column(
3571 3604 'revisions', UnicodeText().with_variant(UnicodeText(20500), 'mysql'))
3572 3605
3573 3606 @declared_attr
3574 3607 def source_repo_id(cls):
3575 3608 # TODO: dan: rename column to source_repo_id
3576 3609 return Column(
3577 3610 'org_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3578 3611 nullable=False)
3579 3612
3580 3613 source_ref = Column('org_ref', Unicode(255), nullable=False)
3581 3614
3582 3615 @declared_attr
3583 3616 def target_repo_id(cls):
3584 3617 # TODO: dan: rename column to target_repo_id
3585 3618 return Column(
3586 3619 'other_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3587 3620 nullable=False)
3588 3621
3589 3622 target_ref = Column('other_ref', Unicode(255), nullable=False)
3590 3623 _shadow_merge_ref = Column('shadow_merge_ref', Unicode(255), nullable=True)
3591 3624
3592 3625 # TODO: dan: rename column to last_merge_source_rev
3593 3626 _last_merge_source_rev = Column(
3594 3627 'last_merge_org_rev', String(40), nullable=True)
3595 3628 # TODO: dan: rename column to last_merge_target_rev
3596 3629 _last_merge_target_rev = Column(
3597 3630 'last_merge_other_rev', String(40), nullable=True)
3598 3631 _last_merge_status = Column('merge_status', Integer(), nullable=True)
3599 3632 merge_rev = Column('merge_rev', String(40), nullable=True)
3600 3633
3601 3634 reviewer_data = Column(
3602 3635 'reviewer_data_json', MutationObj.as_mutable(
3603 3636 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
3604 3637
3605 3638 @property
3606 3639 def reviewer_data_json(self):
3607 3640 return json.dumps(self.reviewer_data)
3608 3641
3609 3642 @hybrid_property
3610 3643 def description_safe(self):
3611 3644 from rhodecode.lib import helpers as h
3612 3645 return h.escape(self.description)
3613 3646
3614 3647 @hybrid_property
3615 3648 def revisions(self):
3616 3649 return self._revisions.split(':') if self._revisions else []
3617 3650
3618 3651 @revisions.setter
3619 3652 def revisions(self, val):
3620 3653 self._revisions = ':'.join(val)
3621 3654
3622 3655 @hybrid_property
3623 3656 def last_merge_status(self):
3624 3657 return safe_int(self._last_merge_status)
3625 3658
3626 3659 @last_merge_status.setter
3627 3660 def last_merge_status(self, val):
3628 3661 self._last_merge_status = val
3629 3662
3630 3663 @declared_attr
3631 3664 def author(cls):
3632 3665 return relationship('User', lazy='joined')
3633 3666
3634 3667 @declared_attr
3635 3668 def source_repo(cls):
3636 3669 return relationship(
3637 3670 'Repository',
3638 3671 primaryjoin='%s.source_repo_id==Repository.repo_id' % cls.__name__)
3639 3672
3640 3673 @property
3641 3674 def source_ref_parts(self):
3642 3675 return self.unicode_to_reference(self.source_ref)
3643 3676
3644 3677 @declared_attr
3645 3678 def target_repo(cls):
3646 3679 return relationship(
3647 3680 'Repository',
3648 3681 primaryjoin='%s.target_repo_id==Repository.repo_id' % cls.__name__)
3649 3682
3650 3683 @property
3651 3684 def target_ref_parts(self):
3652 3685 return self.unicode_to_reference(self.target_ref)
3653 3686
3654 3687 @property
3655 3688 def shadow_merge_ref(self):
3656 3689 return self.unicode_to_reference(self._shadow_merge_ref)
3657 3690
3658 3691 @shadow_merge_ref.setter
3659 3692 def shadow_merge_ref(self, ref):
3660 3693 self._shadow_merge_ref = self.reference_to_unicode(ref)
3661 3694
3662 3695 def unicode_to_reference(self, raw):
3663 3696 """
3664 3697 Convert a unicode (or string) to a reference object.
3665 3698 If unicode evaluates to False it returns None.
3666 3699 """
3667 3700 if raw:
3668 3701 refs = raw.split(':')
3669 3702 return Reference(*refs)
3670 3703 else:
3671 3704 return None
3672 3705
3673 3706 def reference_to_unicode(self, ref):
3674 3707 """
3675 3708 Convert a reference object to unicode.
3676 3709 If reference is None it returns None.
3677 3710 """
3678 3711 if ref:
3679 3712 return u':'.join(ref)
3680 3713 else:
3681 3714 return None
3682 3715
3683 3716 def get_api_data(self, with_merge_state=True):
3684 3717 from rhodecode.model.pull_request import PullRequestModel
3685 3718
3686 3719 pull_request = self
3687 3720 if with_merge_state:
3688 3721 merge_status = PullRequestModel().merge_status(pull_request)
3689 3722 merge_state = {
3690 3723 'status': merge_status[0],
3691 3724 'message': safe_unicode(merge_status[1]),
3692 3725 }
3693 3726 else:
3694 3727 merge_state = {'status': 'not_available',
3695 3728 'message': 'not_available'}
3696 3729
3697 3730 merge_data = {
3698 3731 'clone_url': PullRequestModel().get_shadow_clone_url(pull_request),
3699 3732 'reference': (
3700 3733 pull_request.shadow_merge_ref._asdict()
3701 3734 if pull_request.shadow_merge_ref else None),
3702 3735 }
3703 3736
3704 3737 data = {
3705 3738 'pull_request_id': pull_request.pull_request_id,
3706 3739 'url': PullRequestModel().get_url(pull_request),
3707 3740 'title': pull_request.title,
3708 3741 'description': pull_request.description,
3709 3742 'status': pull_request.status,
3710 3743 'created_on': pull_request.created_on,
3711 3744 'updated_on': pull_request.updated_on,
3712 3745 'commit_ids': pull_request.revisions,
3713 3746 'review_status': pull_request.calculated_review_status(),
3714 3747 'mergeable': merge_state,
3715 3748 'source': {
3716 3749 'clone_url': pull_request.source_repo.clone_url(),
3717 3750 'repository': pull_request.source_repo.repo_name,
3718 3751 'reference': {
3719 3752 'name': pull_request.source_ref_parts.name,
3720 3753 'type': pull_request.source_ref_parts.type,
3721 3754 'commit_id': pull_request.source_ref_parts.commit_id,
3722 3755 },
3723 3756 },
3724 3757 'target': {
3725 3758 'clone_url': pull_request.target_repo.clone_url(),
3726 3759 'repository': pull_request.target_repo.repo_name,
3727 3760 'reference': {
3728 3761 'name': pull_request.target_ref_parts.name,
3729 3762 'type': pull_request.target_ref_parts.type,
3730 3763 'commit_id': pull_request.target_ref_parts.commit_id,
3731 3764 },
3732 3765 },
3733 3766 'merge': merge_data,
3734 3767 'author': pull_request.author.get_api_data(include_secrets=False,
3735 3768 details='basic'),
3736 3769 'reviewers': [
3737 3770 {
3738 3771 'user': reviewer.get_api_data(include_secrets=False,
3739 3772 details='basic'),
3740 3773 'reasons': reasons,
3741 3774 'review_status': st[0][1].status if st else 'not_reviewed',
3742 3775 }
3743 3776 for obj, reviewer, reasons, mandatory, st in
3744 3777 pull_request.reviewers_statuses()
3745 3778 ]
3746 3779 }
3747 3780
3748 3781 return data
3749 3782
3750 3783
3751 3784 class PullRequest(Base, _PullRequestBase):
3752 3785 __tablename__ = 'pull_requests'
3753 3786 __table_args__ = (
3754 3787 base_table_args,
3755 3788 )
3756 3789
3757 3790 pull_request_id = Column(
3758 3791 'pull_request_id', Integer(), nullable=False, primary_key=True)
3759 3792
3760 3793 def __repr__(self):
3761 3794 if self.pull_request_id:
3762 3795 return '<DB:PullRequest #%s>' % self.pull_request_id
3763 3796 else:
3764 3797 return '<DB:PullRequest at %#x>' % id(self)
3765 3798
3766 3799 reviewers = relationship('PullRequestReviewers',
3767 3800 cascade="all, delete, delete-orphan")
3768 3801 statuses = relationship('ChangesetStatus',
3769 3802 cascade="all, delete, delete-orphan")
3770 3803 comments = relationship('ChangesetComment',
3771 3804 cascade="all, delete, delete-orphan")
3772 3805 versions = relationship('PullRequestVersion',
3773 3806 cascade="all, delete, delete-orphan",
3774 3807 lazy='dynamic')
3775 3808
3776 3809 @classmethod
3777 3810 def get_pr_display_object(cls, pull_request_obj, org_pull_request_obj,
3778 3811 internal_methods=None):
3779 3812
3780 3813 class PullRequestDisplay(object):
3781 3814 """
3782 3815 Special object wrapper for showing PullRequest data via Versions
3783 3816 It mimics PR object as close as possible. This is read only object
3784 3817 just for display
3785 3818 """
3786 3819
3787 3820 def __init__(self, attrs, internal=None):
3788 3821 self.attrs = attrs
3789 3822 # internal have priority over the given ones via attrs
3790 3823 self.internal = internal or ['versions']
3791 3824
3792 3825 def __getattr__(self, item):
3793 3826 if item in self.internal:
3794 3827 return getattr(self, item)
3795 3828 try:
3796 3829 return self.attrs[item]
3797 3830 except KeyError:
3798 3831 raise AttributeError(
3799 3832 '%s object has no attribute %s' % (self, item))
3800 3833
3801 3834 def __repr__(self):
3802 3835 return '<DB:PullRequestDisplay #%s>' % self.attrs.get('pull_request_id')
3803 3836
3804 3837 def versions(self):
3805 3838 return pull_request_obj.versions.order_by(
3806 3839 PullRequestVersion.pull_request_version_id).all()
3807 3840
3808 3841 def is_closed(self):
3809 3842 return pull_request_obj.is_closed()
3810 3843
3811 3844 @property
3812 3845 def pull_request_version_id(self):
3813 3846 return getattr(pull_request_obj, 'pull_request_version_id', None)
3814 3847
3815 3848 attrs = StrictAttributeDict(pull_request_obj.get_api_data())
3816 3849
3817 3850 attrs.author = StrictAttributeDict(
3818 3851 pull_request_obj.author.get_api_data())
3819 3852 if pull_request_obj.target_repo:
3820 3853 attrs.target_repo = StrictAttributeDict(
3821 3854 pull_request_obj.target_repo.get_api_data())
3822 3855 attrs.target_repo.clone_url = pull_request_obj.target_repo.clone_url
3823 3856
3824 3857 if pull_request_obj.source_repo:
3825 3858 attrs.source_repo = StrictAttributeDict(
3826 3859 pull_request_obj.source_repo.get_api_data())
3827 3860 attrs.source_repo.clone_url = pull_request_obj.source_repo.clone_url
3828 3861
3829 3862 attrs.source_ref_parts = pull_request_obj.source_ref_parts
3830 3863 attrs.target_ref_parts = pull_request_obj.target_ref_parts
3831 3864 attrs.revisions = pull_request_obj.revisions
3832 3865
3833 3866 attrs.shadow_merge_ref = org_pull_request_obj.shadow_merge_ref
3834 3867 attrs.reviewer_data = org_pull_request_obj.reviewer_data
3835 3868 attrs.reviewer_data_json = org_pull_request_obj.reviewer_data_json
3836 3869
3837 3870 return PullRequestDisplay(attrs, internal=internal_methods)
3838 3871
3839 3872 def is_closed(self):
3840 3873 return self.status == self.STATUS_CLOSED
3841 3874
3842 3875 def __json__(self):
3843 3876 return {
3844 3877 'revisions': self.revisions,
3845 3878 }
3846 3879
3847 3880 def calculated_review_status(self):
3848 3881 from rhodecode.model.changeset_status import ChangesetStatusModel
3849 3882 return ChangesetStatusModel().calculated_review_status(self)
3850 3883
3851 3884 def reviewers_statuses(self):
3852 3885 from rhodecode.model.changeset_status import ChangesetStatusModel
3853 3886 return ChangesetStatusModel().reviewers_statuses(self)
3854 3887
3855 3888 @property
3856 3889 def workspace_id(self):
3857 3890 from rhodecode.model.pull_request import PullRequestModel
3858 3891 return PullRequestModel()._workspace_id(self)
3859 3892
3860 3893 def get_shadow_repo(self):
3861 3894 workspace_id = self.workspace_id
3862 3895 vcs_obj = self.target_repo.scm_instance()
3863 3896 shadow_repository_path = vcs_obj._get_shadow_repository_path(
3864 3897 self.target_repo.repo_id, workspace_id)
3865 3898 if os.path.isdir(shadow_repository_path):
3866 3899 return vcs_obj._get_shadow_instance(shadow_repository_path)
3867 3900
3868 3901
3869 3902 class PullRequestVersion(Base, _PullRequestBase):
3870 3903 __tablename__ = 'pull_request_versions'
3871 3904 __table_args__ = (
3872 3905 base_table_args,
3873 3906 )
3874 3907
3875 3908 pull_request_version_id = Column(
3876 3909 'pull_request_version_id', Integer(), nullable=False, primary_key=True)
3877 3910 pull_request_id = Column(
3878 3911 'pull_request_id', Integer(),
3879 3912 ForeignKey('pull_requests.pull_request_id'), nullable=False)
3880 3913 pull_request = relationship('PullRequest')
3881 3914
3882 3915 def __repr__(self):
3883 3916 if self.pull_request_version_id:
3884 3917 return '<DB:PullRequestVersion #%s>' % self.pull_request_version_id
3885 3918 else:
3886 3919 return '<DB:PullRequestVersion at %#x>' % id(self)
3887 3920
3888 3921 @property
3889 3922 def reviewers(self):
3890 3923 return self.pull_request.reviewers
3891 3924
3892 3925 @property
3893 3926 def versions(self):
3894 3927 return self.pull_request.versions
3895 3928
3896 3929 def is_closed(self):
3897 3930 # calculate from original
3898 3931 return self.pull_request.status == self.STATUS_CLOSED
3899 3932
3900 3933 def calculated_review_status(self):
3901 3934 return self.pull_request.calculated_review_status()
3902 3935
3903 3936 def reviewers_statuses(self):
3904 3937 return self.pull_request.reviewers_statuses()
3905 3938
3906 3939
3907 3940 class PullRequestReviewers(Base, BaseModel):
3908 3941 __tablename__ = 'pull_request_reviewers'
3909 3942 __table_args__ = (
3910 3943 base_table_args,
3911 3944 )
3912 3945
3913 3946 @hybrid_property
3914 3947 def reasons(self):
3915 3948 if not self._reasons:
3916 3949 return []
3917 3950 return self._reasons
3918 3951
3919 3952 @reasons.setter
3920 3953 def reasons(self, val):
3921 3954 val = val or []
3922 3955 if any(not isinstance(x, basestring) for x in val):
3923 3956 raise Exception('invalid reasons type, must be list of strings')
3924 3957 self._reasons = val
3925 3958
3926 3959 pull_requests_reviewers_id = Column(
3927 3960 'pull_requests_reviewers_id', Integer(), nullable=False,
3928 3961 primary_key=True)
3929 3962 pull_request_id = Column(
3930 3963 "pull_request_id", Integer(),
3931 3964 ForeignKey('pull_requests.pull_request_id'), nullable=False)
3932 3965 user_id = Column(
3933 3966 "user_id", Integer(), ForeignKey('users.user_id'), nullable=True)
3934 3967 _reasons = Column(
3935 3968 'reason', MutationList.as_mutable(
3936 3969 JsonType('list', dialect_map=dict(mysql=UnicodeText(16384)))))
3937 3970
3938 3971 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
3939 3972 user = relationship('User')
3940 3973 pull_request = relationship('PullRequest')
3941 3974
3942 3975 rule_data = Column(
3943 3976 'rule_data_json',
3944 3977 JsonType(dialect_map=dict(mysql=UnicodeText(16384))))
3945 3978
3946 3979 def rule_user_group_data(self):
3947 3980 """
3948 3981 Returns the voting user group rule data for this reviewer
3949 3982 """
3950 3983
3951 3984 if self.rule_data and 'vote_rule' in self.rule_data:
3952 3985 user_group_data = {}
3953 3986 if 'rule_user_group_entry_id' in self.rule_data:
3954 3987 # means a group with voting rules !
3955 3988 user_group_data['id'] = self.rule_data['rule_user_group_entry_id']
3956 3989 user_group_data['name'] = self.rule_data['rule_name']
3957 3990 user_group_data['vote_rule'] = self.rule_data['vote_rule']
3958 3991
3959 3992 return user_group_data
3960 3993
3961 3994 def __unicode__(self):
3962 3995 return u"<%s('id:%s')>" % (self.__class__.__name__,
3963 3996 self.pull_requests_reviewers_id)
3964 3997
3965 3998
3966 3999 class Notification(Base, BaseModel):
3967 4000 __tablename__ = 'notifications'
3968 4001 __table_args__ = (
3969 4002 Index('notification_type_idx', 'type'),
3970 4003 base_table_args,
3971 4004 )
3972 4005
3973 4006 TYPE_CHANGESET_COMMENT = u'cs_comment'
3974 4007 TYPE_MESSAGE = u'message'
3975 4008 TYPE_MENTION = u'mention'
3976 4009 TYPE_REGISTRATION = u'registration'
3977 4010 TYPE_PULL_REQUEST = u'pull_request'
3978 4011 TYPE_PULL_REQUEST_COMMENT = u'pull_request_comment'
3979 4012
3980 4013 notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True)
3981 4014 subject = Column('subject', Unicode(512), nullable=True)
3982 4015 body = Column('body', UnicodeText().with_variant(UnicodeText(50000), 'mysql'), nullable=True)
3983 4016 created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True)
3984 4017 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3985 4018 type_ = Column('type', Unicode(255))
3986 4019
3987 4020 created_by_user = relationship('User')
3988 4021 notifications_to_users = relationship('UserNotification', lazy='joined',
3989 4022 cascade="all, delete, delete-orphan")
3990 4023
3991 4024 @property
3992 4025 def recipients(self):
3993 4026 return [x.user for x in UserNotification.query()\
3994 4027 .filter(UserNotification.notification == self)\
3995 4028 .order_by(UserNotification.user_id.asc()).all()]
3996 4029
3997 4030 @classmethod
3998 4031 def create(cls, created_by, subject, body, recipients, type_=None):
3999 4032 if type_ is None:
4000 4033 type_ = Notification.TYPE_MESSAGE
4001 4034
4002 4035 notification = cls()
4003 4036 notification.created_by_user = created_by
4004 4037 notification.subject = subject
4005 4038 notification.body = body
4006 4039 notification.type_ = type_
4007 4040 notification.created_on = datetime.datetime.now()
4008 4041
4009 4042 # For each recipient link the created notification to his account
4010 4043 for u in recipients:
4011 4044 assoc = UserNotification()
4012 4045 assoc.user_id = u.user_id
4013 4046 assoc.notification = notification
4014 4047
4015 4048 # if created_by is inside recipients mark his notification
4016 4049 # as read
4017 4050 if u.user_id == created_by.user_id:
4018 4051 assoc.read = True
4019 4052 Session().add(assoc)
4020 4053
4021 4054 Session().add(notification)
4022 4055
4023 4056 return notification
4024 4057
4025 4058
4026 4059 class UserNotification(Base, BaseModel):
4027 4060 __tablename__ = 'user_to_notification'
4028 4061 __table_args__ = (
4029 4062 UniqueConstraint('user_id', 'notification_id'),
4030 4063 base_table_args
4031 4064 )
4032 4065
4033 4066 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
4034 4067 notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
4035 4068 read = Column('read', Boolean, default=False)
4036 4069 sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
4037 4070
4038 4071 user = relationship('User', lazy="joined")
4039 4072 notification = relationship('Notification', lazy="joined",
4040 4073 order_by=lambda: Notification.created_on.desc(),)
4041 4074
4042 4075 def mark_as_read(self):
4043 4076 self.read = True
4044 4077 Session().add(self)
4045 4078
4046 4079
4047 4080 class Gist(Base, BaseModel):
4048 4081 __tablename__ = 'gists'
4049 4082 __table_args__ = (
4050 4083 Index('g_gist_access_id_idx', 'gist_access_id'),
4051 4084 Index('g_created_on_idx', 'created_on'),
4052 4085 base_table_args
4053 4086 )
4054 4087
4055 4088 GIST_PUBLIC = u'public'
4056 4089 GIST_PRIVATE = u'private'
4057 4090 DEFAULT_FILENAME = u'gistfile1.txt'
4058 4091
4059 4092 ACL_LEVEL_PUBLIC = u'acl_public'
4060 4093 ACL_LEVEL_PRIVATE = u'acl_private'
4061 4094
4062 4095 gist_id = Column('gist_id', Integer(), primary_key=True)
4063 4096 gist_access_id = Column('gist_access_id', Unicode(250))
4064 4097 gist_description = Column('gist_description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
4065 4098 gist_owner = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True)
4066 4099 gist_expires = Column('gist_expires', Float(53), nullable=False)
4067 4100 gist_type = Column('gist_type', Unicode(128), nullable=False)
4068 4101 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4069 4102 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4070 4103 acl_level = Column('acl_level', Unicode(128), nullable=True)
4071 4104
4072 4105 owner = relationship('User')
4073 4106
4074 4107 def __repr__(self):
4075 4108 return '<Gist:[%s]%s>' % (self.gist_type, self.gist_access_id)
4076 4109
4077 4110 @hybrid_property
4078 4111 def description_safe(self):
4079 4112 from rhodecode.lib import helpers as h
4080 4113 return h.escape(self.gist_description)
4081 4114
4082 4115 @classmethod
4083 4116 def get_or_404(cls, id_):
4084 4117 from pyramid.httpexceptions import HTTPNotFound
4085 4118
4086 4119 res = cls.query().filter(cls.gist_access_id == id_).scalar()
4087 4120 if not res:
4088 4121 raise HTTPNotFound()
4089 4122 return res
4090 4123
4091 4124 @classmethod
4092 4125 def get_by_access_id(cls, gist_access_id):
4093 4126 return cls.query().filter(cls.gist_access_id == gist_access_id).scalar()
4094 4127
4095 4128 def gist_url(self):
4096 4129 from rhodecode.model.gist import GistModel
4097 4130 return GistModel().get_url(self)
4098 4131
4099 4132 @classmethod
4100 4133 def base_path(cls):
4101 4134 """
4102 4135 Returns base path when all gists are stored
4103 4136
4104 4137 :param cls:
4105 4138 """
4106 4139 from rhodecode.model.gist import GIST_STORE_LOC
4107 4140 q = Session().query(RhodeCodeUi)\
4108 4141 .filter(RhodeCodeUi.ui_key == URL_SEP)
4109 4142 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
4110 4143 return os.path.join(q.one().ui_value, GIST_STORE_LOC)
4111 4144
4112 4145 def get_api_data(self):
4113 4146 """
4114 4147 Common function for generating gist related data for API
4115 4148 """
4116 4149 gist = self
4117 4150 data = {
4118 4151 'gist_id': gist.gist_id,
4119 4152 'type': gist.gist_type,
4120 4153 'access_id': gist.gist_access_id,
4121 4154 'description': gist.gist_description,
4122 4155 'url': gist.gist_url(),
4123 4156 'expires': gist.gist_expires,
4124 4157 'created_on': gist.created_on,
4125 4158 'modified_at': gist.modified_at,
4126 4159 'content': None,
4127 4160 'acl_level': gist.acl_level,
4128 4161 }
4129 4162 return data
4130 4163
4131 4164 def __json__(self):
4132 4165 data = dict(
4133 4166 )
4134 4167 data.update(self.get_api_data())
4135 4168 return data
4136 4169 # SCM functions
4137 4170
4138 4171 def scm_instance(self, **kwargs):
4139 4172 full_repo_path = os.path.join(self.base_path(), self.gist_access_id)
4140 4173 return get_vcs_instance(
4141 4174 repo_path=safe_str(full_repo_path), create=False)
4142 4175
4143 4176
4144 4177 class ExternalIdentity(Base, BaseModel):
4145 4178 __tablename__ = 'external_identities'
4146 4179 __table_args__ = (
4147 4180 Index('local_user_id_idx', 'local_user_id'),
4148 4181 Index('external_id_idx', 'external_id'),
4149 4182 base_table_args
4150 4183 )
4151 4184
4152 4185 external_id = Column('external_id', Unicode(255), default=u'', primary_key=True)
4153 4186 external_username = Column('external_username', Unicode(1024), default=u'')
4154 4187 local_user_id = Column('local_user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
4155 4188 provider_name = Column('provider_name', Unicode(255), default=u'', primary_key=True)
4156 4189 access_token = Column('access_token', String(1024), default=u'')
4157 4190 alt_token = Column('alt_token', String(1024), default=u'')
4158 4191 token_secret = Column('token_secret', String(1024), default=u'')
4159 4192
4160 4193 @classmethod
4161 4194 def by_external_id_and_provider(cls, external_id, provider_name, local_user_id=None):
4162 4195 """
4163 4196 Returns ExternalIdentity instance based on search params
4164 4197
4165 4198 :param external_id:
4166 4199 :param provider_name:
4167 4200 :return: ExternalIdentity
4168 4201 """
4169 4202 query = cls.query()
4170 4203 query = query.filter(cls.external_id == external_id)
4171 4204 query = query.filter(cls.provider_name == provider_name)
4172 4205 if local_user_id:
4173 4206 query = query.filter(cls.local_user_id == local_user_id)
4174 4207 return query.first()
4175 4208
4176 4209 @classmethod
4177 4210 def user_by_external_id_and_provider(cls, external_id, provider_name):
4178 4211 """
4179 4212 Returns User instance based on search params
4180 4213
4181 4214 :param external_id:
4182 4215 :param provider_name:
4183 4216 :return: User
4184 4217 """
4185 4218 query = User.query()
4186 4219 query = query.filter(cls.external_id == external_id)
4187 4220 query = query.filter(cls.provider_name == provider_name)
4188 4221 query = query.filter(User.user_id == cls.local_user_id)
4189 4222 return query.first()
4190 4223
4191 4224 @classmethod
4192 4225 def by_local_user_id(cls, local_user_id):
4193 4226 """
4194 4227 Returns all tokens for user
4195 4228
4196 4229 :param local_user_id:
4197 4230 :return: ExternalIdentity
4198 4231 """
4199 4232 query = cls.query()
4200 4233 query = query.filter(cls.local_user_id == local_user_id)
4201 4234 return query
4202 4235
4203 4236 @classmethod
4204 4237 def load_provider_plugin(cls, plugin_id):
4205 4238 from rhodecode.authentication.base import loadplugin
4206 4239 _plugin_id = 'egg:rhodecode-enterprise-ee#{}'.format(plugin_id)
4207 4240 auth_plugin = loadplugin(_plugin_id)
4208 4241 return auth_plugin
4209 4242
4210 4243
4211 4244 class Integration(Base, BaseModel):
4212 4245 __tablename__ = 'integrations'
4213 4246 __table_args__ = (
4214 4247 base_table_args
4215 4248 )
4216 4249
4217 4250 integration_id = Column('integration_id', Integer(), primary_key=True)
4218 4251 integration_type = Column('integration_type', String(255))
4219 4252 enabled = Column('enabled', Boolean(), nullable=False)
4220 4253 name = Column('name', String(255), nullable=False)
4221 4254 child_repos_only = Column('child_repos_only', Boolean(), nullable=False,
4222 4255 default=False)
4223 4256
4224 4257 settings = Column(
4225 4258 'settings_json', MutationObj.as_mutable(
4226 4259 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
4227 4260 repo_id = Column(
4228 4261 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
4229 4262 nullable=True, unique=None, default=None)
4230 4263 repo = relationship('Repository', lazy='joined')
4231 4264
4232 4265 repo_group_id = Column(
4233 4266 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
4234 4267 nullable=True, unique=None, default=None)
4235 4268 repo_group = relationship('RepoGroup', lazy='joined')
4236 4269
4237 4270 @property
4238 4271 def scope(self):
4239 4272 if self.repo:
4240 4273 return repr(self.repo)
4241 4274 if self.repo_group:
4242 4275 if self.child_repos_only:
4243 4276 return repr(self.repo_group) + ' (child repos only)'
4244 4277 else:
4245 4278 return repr(self.repo_group) + ' (recursive)'
4246 4279 if self.child_repos_only:
4247 4280 return 'root_repos'
4248 4281 return 'global'
4249 4282
4250 4283 def __repr__(self):
4251 4284 return '<Integration(%r, %r)>' % (self.integration_type, self.scope)
4252 4285
4253 4286
4254 4287 class RepoReviewRuleUser(Base, BaseModel):
4255 4288 __tablename__ = 'repo_review_rules_users'
4256 4289 __table_args__ = (
4257 4290 base_table_args
4258 4291 )
4259 4292
4260 4293 repo_review_rule_user_id = Column('repo_review_rule_user_id', Integer(), primary_key=True)
4261 4294 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
4262 4295 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False)
4263 4296 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4264 4297 user = relationship('User')
4265 4298
4266 4299 def rule_data(self):
4267 4300 return {
4268 4301 'mandatory': self.mandatory
4269 4302 }
4270 4303
4271 4304
4272 4305 class RepoReviewRuleUserGroup(Base, BaseModel):
4273 4306 __tablename__ = 'repo_review_rules_users_groups'
4274 4307 __table_args__ = (
4275 4308 base_table_args
4276 4309 )
4277 4310
4278 4311 VOTE_RULE_ALL = -1
4279 4312
4280 4313 repo_review_rule_users_group_id = Column('repo_review_rule_users_group_id', Integer(), primary_key=True)
4281 4314 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
4282 4315 users_group_id = Column("users_group_id", Integer(),ForeignKey('users_groups.users_group_id'), nullable=False)
4283 4316 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4284 4317 vote_rule = Column("vote_rule", Integer(), nullable=True, default=VOTE_RULE_ALL)
4285 4318 users_group = relationship('UserGroup')
4286 4319
4287 4320 def rule_data(self):
4288 4321 return {
4289 4322 'mandatory': self.mandatory,
4290 4323 'vote_rule': self.vote_rule
4291 4324 }
4292 4325
4293 4326 @property
4294 4327 def vote_rule_label(self):
4295 4328 if not self.vote_rule or self.vote_rule == self.VOTE_RULE_ALL:
4296 4329 return 'all must vote'
4297 4330 else:
4298 4331 return 'min. vote {}'.format(self.vote_rule)
4299 4332
4300 4333
4301 4334 class RepoReviewRule(Base, BaseModel):
4302 4335 __tablename__ = 'repo_review_rules'
4303 4336 __table_args__ = (
4304 4337 base_table_args
4305 4338 )
4306 4339
4307 4340 repo_review_rule_id = Column(
4308 4341 'repo_review_rule_id', Integer(), primary_key=True)
4309 4342 repo_id = Column(
4310 4343 "repo_id", Integer(), ForeignKey('repositories.repo_id'))
4311 4344 repo = relationship('Repository', backref='review_rules')
4312 4345
4313 4346 review_rule_name = Column('review_rule_name', String(255))
4314 4347 _branch_pattern = Column("branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4315 4348 _target_branch_pattern = Column("target_branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4316 4349 _file_pattern = Column("file_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4317 4350
4318 4351 use_authors_for_review = Column("use_authors_for_review", Boolean(), nullable=False, default=False)
4319 4352 forbid_author_to_review = Column("forbid_author_to_review", Boolean(), nullable=False, default=False)
4320 4353 forbid_commit_author_to_review = Column("forbid_commit_author_to_review", Boolean(), nullable=False, default=False)
4321 4354 forbid_adding_reviewers = Column("forbid_adding_reviewers", Boolean(), nullable=False, default=False)
4322 4355
4323 4356 rule_users = relationship('RepoReviewRuleUser')
4324 4357 rule_user_groups = relationship('RepoReviewRuleUserGroup')
4325 4358
4326 4359 def _validate_pattern(self, value):
4327 4360 re.compile('^' + glob2re(value) + '$')
4328 4361
4329 4362 @hybrid_property
4330 4363 def source_branch_pattern(self):
4331 4364 return self._branch_pattern or '*'
4332 4365
4333 4366 @source_branch_pattern.setter
4334 4367 def source_branch_pattern(self, value):
4335 4368 self._validate_pattern(value)
4336 4369 self._branch_pattern = value or '*'
4337 4370
4338 4371 @hybrid_property
4339 4372 def target_branch_pattern(self):
4340 4373 return self._target_branch_pattern or '*'
4341 4374
4342 4375 @target_branch_pattern.setter
4343 4376 def target_branch_pattern(self, value):
4344 4377 self._validate_pattern(value)
4345 4378 self._target_branch_pattern = value or '*'
4346 4379
4347 4380 @hybrid_property
4348 4381 def file_pattern(self):
4349 4382 return self._file_pattern or '*'
4350 4383
4351 4384 @file_pattern.setter
4352 4385 def file_pattern(self, value):
4353 4386 self._validate_pattern(value)
4354 4387 self._file_pattern = value or '*'
4355 4388
4356 4389 def matches(self, source_branch, target_branch, files_changed):
4357 4390 """
4358 4391 Check if this review rule matches a branch/files in a pull request
4359 4392
4360 4393 :param source_branch: source branch name for the commit
4361 4394 :param target_branch: target branch name for the commit
4362 4395 :param files_changed: list of file paths changed in the pull request
4363 4396 """
4364 4397
4365 4398 source_branch = source_branch or ''
4366 4399 target_branch = target_branch or ''
4367 4400 files_changed = files_changed or []
4368 4401
4369 4402 branch_matches = True
4370 4403 if source_branch or target_branch:
4371 4404 if self.source_branch_pattern == '*':
4372 4405 source_branch_match = True
4373 4406 else:
4374 4407 if self.source_branch_pattern.startswith('re:'):
4375 4408 source_pattern = self.source_branch_pattern[3:]
4376 4409 else:
4377 4410 source_pattern = '^' + glob2re(self.source_branch_pattern) + '$'
4378 4411 source_branch_regex = re.compile(source_pattern)
4379 4412 source_branch_match = bool(source_branch_regex.search(source_branch))
4380 4413 if self.target_branch_pattern == '*':
4381 4414 target_branch_match = True
4382 4415 else:
4383 4416 if self.target_branch_pattern.startswith('re:'):
4384 4417 target_pattern = self.target_branch_pattern[3:]
4385 4418 else:
4386 4419 target_pattern = '^' + glob2re(self.target_branch_pattern) + '$'
4387 4420 target_branch_regex = re.compile(target_pattern)
4388 4421 target_branch_match = bool(target_branch_regex.search(target_branch))
4389 4422
4390 4423 branch_matches = source_branch_match and target_branch_match
4391 4424
4392 4425 files_matches = True
4393 4426 if self.file_pattern != '*':
4394 4427 files_matches = False
4395 4428 if self.file_pattern.startswith('re:'):
4396 4429 file_pattern = self.file_pattern[3:]
4397 4430 else:
4398 4431 file_pattern = glob2re(self.file_pattern)
4399 4432 file_regex = re.compile(file_pattern)
4400 4433 for filename in files_changed:
4401 4434 if file_regex.search(filename):
4402 4435 files_matches = True
4403 4436 break
4404 4437
4405 4438 return branch_matches and files_matches
4406 4439
4407 4440 @property
4408 4441 def review_users(self):
4409 4442 """ Returns the users which this rule applies to """
4410 4443
4411 4444 users = collections.OrderedDict()
4412 4445
4413 4446 for rule_user in self.rule_users:
4414 4447 if rule_user.user.active:
4415 4448 if rule_user.user not in users:
4416 4449 users[rule_user.user.username] = {
4417 4450 'user': rule_user.user,
4418 4451 'source': 'user',
4419 4452 'source_data': {},
4420 4453 'data': rule_user.rule_data()
4421 4454 }
4422 4455
4423 4456 for rule_user_group in self.rule_user_groups:
4424 4457 source_data = {
4425 4458 'user_group_id': rule_user_group.users_group.users_group_id,
4426 4459 'name': rule_user_group.users_group.users_group_name,
4427 4460 'members': len(rule_user_group.users_group.members)
4428 4461 }
4429 4462 for member in rule_user_group.users_group.members:
4430 4463 if member.user.active:
4431 4464 key = member.user.username
4432 4465 if key in users:
4433 4466 # skip this member as we have him already
4434 4467 # this prevents from override the "first" matched
4435 4468 # users with duplicates in multiple groups
4436 4469 continue
4437 4470
4438 4471 users[key] = {
4439 4472 'user': member.user,
4440 4473 'source': 'user_group',
4441 4474 'source_data': source_data,
4442 4475 'data': rule_user_group.rule_data()
4443 4476 }
4444 4477
4445 4478 return users
4446 4479
4447 4480 def user_group_vote_rule(self, user_id):
4448 4481
4449 4482 rules = []
4450 4483 if not self.rule_user_groups:
4451 4484 return rules
4452 4485
4453 4486 for user_group in self.rule_user_groups:
4454 4487 user_group_members = [x.user_id for x in user_group.users_group.members]
4455 4488 if user_id in user_group_members:
4456 4489 rules.append(user_group)
4457 4490 return rules
4458 4491
4459 4492 def __repr__(self):
4460 4493 return '<RepoReviewerRule(id=%r, repo=%r)>' % (
4461 4494 self.repo_review_rule_id, self.repo)
4462 4495
4463 4496
4464 4497 class ScheduleEntry(Base, BaseModel):
4465 4498 __tablename__ = 'schedule_entries'
4466 4499 __table_args__ = (
4467 4500 UniqueConstraint('schedule_name', name='s_schedule_name_idx'),
4468 4501 UniqueConstraint('task_uid', name='s_task_uid_idx'),
4469 4502 base_table_args,
4470 4503 )
4471 4504
4472 4505 schedule_types = ['crontab', 'timedelta', 'integer']
4473 4506 schedule_entry_id = Column('schedule_entry_id', Integer(), primary_key=True)
4474 4507
4475 4508 schedule_name = Column("schedule_name", String(255), nullable=False, unique=None, default=None)
4476 4509 schedule_description = Column("schedule_description", String(10000), nullable=True, unique=None, default=None)
4477 4510 schedule_enabled = Column("schedule_enabled", Boolean(), nullable=False, unique=None, default=True)
4478 4511
4479 4512 _schedule_type = Column("schedule_type", String(255), nullable=False, unique=None, default=None)
4480 4513 schedule_definition = Column('schedule_definition_json', MutationObj.as_mutable(JsonType(default=lambda: "", dialect_map=dict(mysql=LONGTEXT()))))
4481 4514
4482 4515 schedule_last_run = Column('schedule_last_run', DateTime(timezone=False), nullable=True, unique=None, default=None)
4483 4516 schedule_total_run_count = Column('schedule_total_run_count', Integer(), nullable=True, unique=None, default=0)
4484 4517
4485 4518 # task
4486 4519 task_uid = Column("task_uid", String(255), nullable=False, unique=None, default=None)
4487 4520 task_dot_notation = Column("task_dot_notation", String(4096), nullable=False, unique=None, default=None)
4488 4521 task_args = Column('task_args_json', MutationObj.as_mutable(JsonType(default=list, dialect_map=dict(mysql=LONGTEXT()))))
4489 4522 task_kwargs = Column('task_kwargs_json', MutationObj.as_mutable(JsonType(default=dict, dialect_map=dict(mysql=LONGTEXT()))))
4490 4523
4491 4524 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4492 4525 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=None)
4493 4526
4494 4527 @hybrid_property
4495 4528 def schedule_type(self):
4496 4529 return self._schedule_type
4497 4530
4498 4531 @schedule_type.setter
4499 4532 def schedule_type(self, val):
4500 4533 if val not in self.schedule_types:
4501 4534 raise ValueError('Value must be on of `{}` and got `{}`'.format(
4502 4535 val, self.schedule_type))
4503 4536
4504 4537 self._schedule_type = val
4505 4538
4506 4539 @classmethod
4507 4540 def get_uid(cls, obj):
4508 4541 args = obj.task_args
4509 4542 kwargs = obj.task_kwargs
4510 4543 if isinstance(args, JsonRaw):
4511 4544 try:
4512 4545 args = json.loads(args)
4513 4546 except ValueError:
4514 4547 args = tuple()
4515 4548
4516 4549 if isinstance(kwargs, JsonRaw):
4517 4550 try:
4518 4551 kwargs = json.loads(kwargs)
4519 4552 except ValueError:
4520 4553 kwargs = dict()
4521 4554
4522 4555 dot_notation = obj.task_dot_notation
4523 4556 val = '.'.join(map(safe_str, [
4524 4557 sorted(dot_notation), args, sorted(kwargs.items())]))
4525 4558 return hashlib.sha1(val).hexdigest()
4526 4559
4527 4560 @classmethod
4528 4561 def get_by_schedule_name(cls, schedule_name):
4529 4562 return cls.query().filter(cls.schedule_name == schedule_name).scalar()
4530 4563
4531 4564 @classmethod
4532 4565 def get_by_schedule_id(cls, schedule_id):
4533 4566 return cls.query().filter(cls.schedule_entry_id == schedule_id).scalar()
4534 4567
4535 4568 @property
4536 4569 def task(self):
4537 4570 return self.task_dot_notation
4538 4571
4539 4572 @property
4540 4573 def schedule(self):
4541 4574 from rhodecode.lib.celerylib.utils import raw_2_schedule
4542 4575 schedule = raw_2_schedule(self.schedule_definition, self.schedule_type)
4543 4576 return schedule
4544 4577
4545 4578 @property
4546 4579 def args(self):
4547 4580 try:
4548 4581 return list(self.task_args or [])
4549 4582 except ValueError:
4550 4583 return list()
4551 4584
4552 4585 @property
4553 4586 def kwargs(self):
4554 4587 try:
4555 4588 return dict(self.task_kwargs or {})
4556 4589 except ValueError:
4557 4590 return dict()
4558 4591
4559 4592 def _as_raw(self, val):
4560 4593 if hasattr(val, 'de_coerce'):
4561 4594 val = val.de_coerce()
4562 4595 if val:
4563 4596 val = json.dumps(val)
4564 4597
4565 4598 return val
4566 4599
4567 4600 @property
4568 4601 def schedule_definition_raw(self):
4569 4602 return self._as_raw(self.schedule_definition)
4570 4603
4571 4604 @property
4572 4605 def args_raw(self):
4573 4606 return self._as_raw(self.task_args)
4574 4607
4575 4608 @property
4576 4609 def kwargs_raw(self):
4577 4610 return self._as_raw(self.task_kwargs)
4578 4611
4579 4612 def __repr__(self):
4580 4613 return '<DB:ScheduleEntry({}:{})>'.format(
4581 4614 self.schedule_entry_id, self.schedule_name)
4582 4615
4583 4616
4584 4617 @event.listens_for(ScheduleEntry, 'before_update')
4585 4618 def update_task_uid(mapper, connection, target):
4586 4619 target.task_uid = ScheduleEntry.get_uid(target)
4587 4620
4588 4621
4589 4622 @event.listens_for(ScheduleEntry, 'before_insert')
4590 4623 def set_task_uid(mapper, connection, target):
4591 4624 target.task_uid = ScheduleEntry.get_uid(target)
4592 4625
4593 4626
4594 4627 class _BaseBranchPerms(BaseModel):
4595 4628 @classmethod
4596 4629 def compute_hash(cls, value):
4597 4630 return sha1_safe(value)
4598 4631
4599 4632 @hybrid_property
4600 4633 def branch_pattern(self):
4601 4634 return self._branch_pattern or '*'
4602 4635
4603 4636 @hybrid_property
4604 4637 def branch_hash(self):
4605 4638 return self._branch_hash
4606 4639
4607 4640 def _validate_glob(self, value):
4608 4641 re.compile('^' + glob2re(value) + '$')
4609 4642
4610 4643 @branch_pattern.setter
4611 4644 def branch_pattern(self, value):
4612 4645 self._validate_glob(value)
4613 4646 self._branch_pattern = value or '*'
4614 4647 # set the Hash when setting the branch pattern
4615 4648 self._branch_hash = self.compute_hash(self._branch_pattern)
4616 4649
4617 4650 def matches(self, branch):
4618 4651 """
4619 4652 Check if this the branch matches entry
4620 4653
4621 4654 :param branch: branch name for the commit
4622 4655 """
4623 4656
4624 4657 branch = branch or ''
4625 4658
4626 4659 branch_matches = True
4627 4660 if branch:
4628 4661 branch_regex = re.compile('^' + glob2re(self.branch_pattern) + '$')
4629 4662 branch_matches = bool(branch_regex.search(branch))
4630 4663
4631 4664 return branch_matches
4632 4665
4633 4666
4634 4667 class UserToRepoBranchPermission(Base, _BaseBranchPerms):
4635 4668 __tablename__ = 'user_to_repo_branch_permissions'
4636 4669 __table_args__ = (
4637 4670 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4638 4671 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
4639 4672 )
4640 4673
4641 4674 branch_rule_id = Column('branch_rule_id', Integer(), primary_key=True)
4642 4675
4643 4676 repository_id = Column('repository_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
4644 4677 repo = relationship('Repository', backref='user_branch_perms')
4645 4678
4646 4679 permission_id = Column('permission_id', Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
4647 4680 permission = relationship('Permission')
4648 4681
4649 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 4683 user_repo_to_perm = relationship('UserRepoToPerm')
4651 4684
4652 4685 rule_order = Column('rule_order', Integer(), nullable=False)
4653 4686 _branch_pattern = Column('branch_pattern', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), default=u'*') # glob
4654 4687 _branch_hash = Column('branch_hash', UnicodeText().with_variant(UnicodeText(2048), 'mysql'))
4655 4688
4656 4689 def __unicode__(self):
4657 4690 return u'<UserBranchPermission(%s => %r)>' % (
4658 4691 self.user_repo_to_perm, self.branch_pattern)
4659 4692
4660 4693
4661 4694 class UserGroupToRepoBranchPermission(Base, _BaseBranchPerms):
4662 4695 __tablename__ = 'user_group_to_repo_branch_permissions'
4663 4696 __table_args__ = (
4664 4697 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4665 4698 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
4666 4699 )
4667 4700
4668 4701 branch_rule_id = Column('branch_rule_id', Integer(), primary_key=True)
4669 4702
4670 4703 repository_id = Column('repository_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
4671 4704 repo = relationship('Repository', backref='user_group_branch_perms')
4672 4705
4673 4706 permission_id = Column('permission_id', Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
4674 4707 permission = relationship('Permission')
4675 4708
4676 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 4710 user_group_repo_to_perm = relationship('UserGroupRepoToPerm')
4678 4711
4679 4712 rule_order = Column('rule_order', Integer(), nullable=False)
4680 4713 _branch_pattern = Column('branch_pattern', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), default=u'*') # glob
4681 4714 _branch_hash = Column('branch_hash', UnicodeText().with_variant(UnicodeText(2048), 'mysql'))
4682 4715
4683 4716 def __unicode__(self):
4684 4717 return u'<UserBranchPermission(%s => %r)>' % (
4685 4718 self.user_group_repo_to_perm, self.branch_pattern)
4686 4719
4687 4720
4688 4721 class DbMigrateVersion(Base, BaseModel):
4689 4722 __tablename__ = 'db_migrate_version'
4690 4723 __table_args__ = (
4691 4724 base_table_args,
4692 4725 )
4693 4726
4694 4727 repository_id = Column('repository_id', String(250), primary_key=True)
4695 4728 repository_path = Column('repository_path', Text)
4696 4729 version = Column('version', Integer)
4697 4730
4698 4731 @classmethod
4699 4732 def set_version(cls, version):
4700 4733 """
4701 4734 Helper for forcing a different version, usually for debugging purposes via ishell.
4702 4735 """
4703 4736 ver = DbMigrateVersion.query().first()
4704 4737 ver.version = version
4705 4738 Session().commit()
4706 4739
4707 4740
4708 4741 class DbSession(Base, BaseModel):
4709 4742 __tablename__ = 'db_session'
4710 4743 __table_args__ = (
4711 4744 base_table_args,
4712 4745 )
4713 4746
4714 4747 def __repr__(self):
4715 4748 return '<DB:DbSession({})>'.format(self.id)
4716 4749
4717 4750 id = Column('id', Integer())
4718 4751 namespace = Column('namespace', String(255), primary_key=True)
4719 4752 accessed = Column('accessed', DateTime, nullable=False)
4720 4753 created = Column('created', DateTime, nullable=False)
4721 4754 data = Column('data', PickleType, nullable=False)
General Comments 0
You need to be logged in to leave comments. Login now