##// END OF EJS Templates
fix(forced 2fa): fixed forced 2fa functionality. Fixes: RCCE-68
ilin.s -
r5398:6efbb976 default
parent child Browse files
Show More
@@ -1,984 +1,986 b''
1 # Copyright (C) 2016-2023 RhodeCode GmbH
1 # Copyright (C) 2016-2023 RhodeCode GmbH
2 #
2 #
3 # This program is free software: you can redistribute it and/or modify
3 # This program is free software: you can redistribute it and/or modify
4 # it under the terms of the GNU Affero General Public License, version 3
4 # it under the terms of the GNU Affero General Public License, version 3
5 # (only), as published by the Free Software Foundation.
5 # (only), as published by the Free Software Foundation.
6 #
6 #
7 # This program is distributed in the hope that it will be useful,
7 # This program is distributed in the hope that it will be useful,
8 # but WITHOUT ANY WARRANTY; without even the implied warranty of
8 # but WITHOUT ANY WARRANTY; without even the implied warranty of
9 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
9 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 # GNU General Public License for more details.
10 # GNU General Public License for more details.
11 #
11 #
12 # You should have received a copy of the GNU Affero General Public License
12 # You should have received a copy of the GNU Affero General Public License
13 # along with this program. If not, see <http://www.gnu.org/licenses/>.
13 # along with this program. If not, see <http://www.gnu.org/licenses/>.
14 #
14 #
15 # This program is dual-licensed. If you wish to learn more about the
15 # This program is dual-licensed. If you wish to learn more about the
16 # RhodeCode Enterprise Edition, including its added features, Support services,
16 # RhodeCode Enterprise Edition, including its added features, Support services,
17 # and proprietary license terms, please see https://rhodecode.com/licenses/
17 # and proprietary license terms, please see https://rhodecode.com/licenses/
18
18
19 import time
19 import time
20 import logging
20 import logging
21 import operator
21 import operator
22
22
23 from pyramid.httpexceptions import HTTPFound, HTTPForbidden, HTTPBadRequest
23 from pyramid.httpexceptions import HTTPFound, HTTPForbidden, HTTPBadRequest
24
24
25 from rhodecode.lib import helpers as h, diffs, rc_cache
25 from rhodecode.lib import helpers as h, diffs, rc_cache
26 from rhodecode.lib.str_utils import safe_str
26 from rhodecode.lib.str_utils import safe_str
27 from rhodecode.lib.utils import repo_name_slug
27 from rhodecode.lib.utils import repo_name_slug
28 from rhodecode.lib.utils2 import (
28 from rhodecode.lib.utils2 import (
29 StrictAttributeDict,
29 StrictAttributeDict,
30 str2bool,
30 str2bool,
31 safe_int,
31 safe_int,
32 datetime_to_time,
32 datetime_to_time,
33 )
33 )
34 from rhodecode.lib.markup_renderer import MarkupRenderer, relative_links
34 from rhodecode.lib.markup_renderer import MarkupRenderer, relative_links
35 from rhodecode.lib.vcs.backends.base import EmptyCommit
35 from rhodecode.lib.vcs.backends.base import EmptyCommit
36 from rhodecode.lib.vcs.exceptions import RepositoryRequirementError
36 from rhodecode.lib.vcs.exceptions import RepositoryRequirementError
37 from rhodecode.model import repo
37 from rhodecode.model import repo
38 from rhodecode.model import repo_group
38 from rhodecode.model import repo_group
39 from rhodecode.model import user_group
39 from rhodecode.model import user_group
40 from rhodecode.model import user
40 from rhodecode.model import user
41 from rhodecode.model.db import User
41 from rhodecode.model.db import User
42 from rhodecode.model.scm import ScmModel
42 from rhodecode.model.scm import ScmModel
43 from rhodecode.model.settings import VcsSettingsModel, IssueTrackerSettingsModel
43 from rhodecode.model.settings import VcsSettingsModel, IssueTrackerSettingsModel
44 from rhodecode.model.repo import ReadmeFinder
44 from rhodecode.model.repo import ReadmeFinder
45
45
46 log = logging.getLogger(__name__)
46 log = logging.getLogger(__name__)
47
47
48
48
49 ADMIN_PREFIX: str = "/_admin"
49 ADMIN_PREFIX: str = "/_admin"
50 STATIC_FILE_PREFIX: str = "/_static"
50 STATIC_FILE_PREFIX: str = "/_static"
51
51
52 URL_NAME_REQUIREMENTS = {
52 URL_NAME_REQUIREMENTS = {
53 # group name can have a slash in them, but they must not end with a slash
53 # group name can have a slash in them, but they must not end with a slash
54 "group_name": r".*?[^/]",
54 "group_name": r".*?[^/]",
55 "repo_group_name": r".*?[^/]",
55 "repo_group_name": r".*?[^/]",
56 # repo names can have a slash in them, but they must not end with a slash
56 # repo names can have a slash in them, but they must not end with a slash
57 "repo_name": r".*?[^/]",
57 "repo_name": r".*?[^/]",
58 # file path eats up everything at the end
58 # file path eats up everything at the end
59 "f_path": r".*",
59 "f_path": r".*",
60 # reference types
60 # reference types
61 "source_ref_type": r"(branch|book|tag|rev|\%\(source_ref_type\)s)",
61 "source_ref_type": r"(branch|book|tag|rev|\%\(source_ref_type\)s)",
62 "target_ref_type": r"(branch|book|tag|rev|\%\(target_ref_type\)s)",
62 "target_ref_type": r"(branch|book|tag|rev|\%\(target_ref_type\)s)",
63 }
63 }
64
64
65
65
66 def add_route_with_slash(config, name, pattern, **kw):
66 def add_route_with_slash(config, name, pattern, **kw):
67 config.add_route(name, pattern, **kw)
67 config.add_route(name, pattern, **kw)
68 if not pattern.endswith("/"):
68 if not pattern.endswith("/"):
69 config.add_route(name + "_slash", pattern + "/", **kw)
69 config.add_route(name + "_slash", pattern + "/", **kw)
70
70
71
71
72 def add_route_requirements(route_path, requirements=None):
72 def add_route_requirements(route_path, requirements=None):
73 """
73 """
74 Adds regex requirements to pyramid routes using a mapping dict
74 Adds regex requirements to pyramid routes using a mapping dict
75 e.g::
75 e.g::
76 add_route_requirements('{repo_name}/settings')
76 add_route_requirements('{repo_name}/settings')
77 """
77 """
78 requirements = requirements or URL_NAME_REQUIREMENTS
78 requirements = requirements or URL_NAME_REQUIREMENTS
79 for key, regex in list(requirements.items()):
79 for key, regex in list(requirements.items()):
80 route_path = route_path.replace("{%s}" % key, "{%s:%s}" % (key, regex))
80 route_path = route_path.replace("{%s}" % key, "{%s:%s}" % (key, regex))
81 return route_path
81 return route_path
82
82
83
83
84 def get_format_ref_id(repo):
84 def get_format_ref_id(repo):
85 """Returns a `repo` specific reference formatter function"""
85 """Returns a `repo` specific reference formatter function"""
86 if h.is_svn(repo):
86 if h.is_svn(repo):
87 return _format_ref_id_svn
87 return _format_ref_id_svn
88 else:
88 else:
89 return _format_ref_id
89 return _format_ref_id
90
90
91
91
92 def _format_ref_id(name, raw_id):
92 def _format_ref_id(name, raw_id):
93 """Default formatting of a given reference `name`"""
93 """Default formatting of a given reference `name`"""
94 return name
94 return name
95
95
96
96
97 def _format_ref_id_svn(name, raw_id):
97 def _format_ref_id_svn(name, raw_id):
98 """Special way of formatting a reference for Subversion including path"""
98 """Special way of formatting a reference for Subversion including path"""
99 return f"{name}@{raw_id}"
99 return f"{name}@{raw_id}"
100
100
101
101
102 class TemplateArgs(StrictAttributeDict):
102 class TemplateArgs(StrictAttributeDict):
103 pass
103 pass
104
104
105
105
106 class BaseAppView(object):
106 class BaseAppView(object):
107 DONT_CHECKOUT_VIEWS = ["channelstream_connect", "ops_ping"]
107 DONT_CHECKOUT_VIEWS = ["channelstream_connect", "ops_ping"]
108 EXTRA_VIEWS_TO_IGNORE = ['login', 'register', 'logout']
108 EXTRA_VIEWS_TO_IGNORE = ['login', 'register', 'logout']
109 SETUP_2FA_VIEW = 'setup_2fa'
109 SETUP_2FA_VIEW = 'setup_2fa'
110 VERIFY_2FA_VIEW = 'check_2fa'
110 VERIFY_2FA_VIEW = 'check_2fa'
111
111
112 def __init__(self, context, request):
112 def __init__(self, context, request):
113 self.request = request
113 self.request = request
114 self.context = context
114 self.context = context
115 self.session = request.session
115 self.session = request.session
116 if not hasattr(request, "user"):
116 if not hasattr(request, "user"):
117 # NOTE(marcink): edge case, we ended up in matched route
117 # NOTE(marcink): edge case, we ended up in matched route
118 # but probably of web-app context, e.g API CALL/VCS CALL
118 # but probably of web-app context, e.g API CALL/VCS CALL
119 if hasattr(request, "vcs_call") or hasattr(request, "rpc_method"):
119 if hasattr(request, "vcs_call") or hasattr(request, "rpc_method"):
120 log.warning("Unable to process request `%s` in this scope", request)
120 log.warning("Unable to process request `%s` in this scope", request)
121 raise HTTPBadRequest()
121 raise HTTPBadRequest()
122
122
123 self._rhodecode_user = request.user # auth user
123 self._rhodecode_user = request.user # auth user
124 self._rhodecode_db_user = self._rhodecode_user.get_instance()
124 self._rhodecode_db_user = self._rhodecode_user.get_instance()
125 self.user_data = self._rhodecode_db_user.user_data if self._rhodecode_db_user else {}
125 self.user_data = self._rhodecode_db_user.user_data if self._rhodecode_db_user else {}
126 self._maybe_needs_password_change(
126 self._maybe_needs_password_change(
127 request.matched_route.name, self._rhodecode_db_user
127 request.matched_route.name, self._rhodecode_db_user
128 )
128 )
129 self._maybe_needs_2fa_configuration(
129 self._maybe_needs_2fa_configuration(
130 request.matched_route.name, self._rhodecode_db_user
130 request.matched_route.name, self._rhodecode_db_user
131 )
131 )
132 self._maybe_needs_2fa_check(
132 self._maybe_needs_2fa_check(
133 request.matched_route.name, self._rhodecode_db_user
133 request.matched_route.name, self._rhodecode_db_user
134 )
134 )
135
135
136 def _maybe_needs_password_change(self, view_name, user_obj):
136 def _maybe_needs_password_change(self, view_name, user_obj):
137 if view_name in self.DONT_CHECKOUT_VIEWS:
137 if view_name in self.DONT_CHECKOUT_VIEWS:
138 return
138 return
139
139
140 log.debug(
140 log.debug(
141 "Checking if user %s needs password change on view %s", user_obj, view_name
141 "Checking if user %s needs password change on view %s", user_obj, view_name
142 )
142 )
143
143
144 skip_user_views = [
144 skip_user_views = [
145 "logout",
145 "logout",
146 "login",
146 "login",
147 "check_2fa",
147 "check_2fa",
148 "my_account_password",
148 "my_account_password",
149 "my_account_password_update",
149 "my_account_password_update",
150 ]
150 ]
151
151
152 if not user_obj:
152 if not user_obj:
153 return
153 return
154
154
155 if user_obj.username == User.DEFAULT_USER:
155 if user_obj.username == User.DEFAULT_USER:
156 return
156 return
157
157
158 now = time.time()
158 now = time.time()
159 should_change = self.user_data.get("force_password_change")
159 should_change = self.user_data.get("force_password_change")
160 change_after = safe_int(should_change) or 0
160 change_after = safe_int(should_change) or 0
161 if should_change and now > change_after:
161 if should_change and now > change_after:
162 log.debug("User %s requires password change", user_obj)
162 log.debug("User %s requires password change", user_obj)
163 h.flash(
163 h.flash(
164 "You are required to change your password",
164 "You are required to change your password",
165 "warning",
165 "warning",
166 ignore_duplicate=True,
166 ignore_duplicate=True,
167 )
167 )
168
168
169 if view_name not in skip_user_views:
169 if view_name not in skip_user_views:
170 raise HTTPFound(self.request.route_path("my_account_password"))
170 raise HTTPFound(self.request.route_path("my_account_password"))
171
171
172 def _maybe_needs_2fa_configuration(self, view_name, user_obj):
172 def _maybe_needs_2fa_configuration(self, view_name, user_obj):
173 if view_name in self.DONT_CHECKOUT_VIEWS + self.EXTRA_VIEWS_TO_IGNORE:
173 if view_name in self.DONT_CHECKOUT_VIEWS + self.EXTRA_VIEWS_TO_IGNORE:
174 return
174 return
175
175
176 if not user_obj:
176 if not user_obj:
177 return
177 return
178
178
179 if user_obj.needs_2fa_configure and view_name != self.SETUP_2FA_VIEW:
179 if user_obj.needs_2fa_configure and view_name != self.SETUP_2FA_VIEW:
180 h.flash(
180 h.flash(
181 "You are required to configure 2FA",
181 "You are required to configure 2FA",
182 "warning",
182 "warning",
183 ignore_duplicate=False,
183 ignore_duplicate=False,
184 )
184 )
185 # Special case for users created "on the fly" (ldap case for new user)
186 user_obj.check_2fa_required = False
185 raise HTTPFound(self.request.route_path(self.SETUP_2FA_VIEW))
187 raise HTTPFound(self.request.route_path(self.SETUP_2FA_VIEW))
186
188
187 def _maybe_needs_2fa_check(self, view_name, user_obj):
189 def _maybe_needs_2fa_check(self, view_name, user_obj):
188 if view_name in self.DONT_CHECKOUT_VIEWS + self.EXTRA_VIEWS_TO_IGNORE:
190 if view_name in self.DONT_CHECKOUT_VIEWS + self.EXTRA_VIEWS_TO_IGNORE:
189 return
191 return
190
192
191 if not user_obj:
193 if not user_obj:
192 return
194 return
193
195
194 if user_obj.check_2fa_required and view_name != self.VERIFY_2FA_VIEW:
196 if user_obj.check_2fa_required and view_name != self.VERIFY_2FA_VIEW:
195 raise HTTPFound(self.request.route_path(self.VERIFY_2FA_VIEW))
197 raise HTTPFound(self.request.route_path(self.VERIFY_2FA_VIEW))
196
198
197 def _log_creation_exception(self, e, repo_name):
199 def _log_creation_exception(self, e, repo_name):
198 _ = self.request.translate
200 _ = self.request.translate
199 reason = None
201 reason = None
200 if len(e.args) == 2:
202 if len(e.args) == 2:
201 reason = e.args[1]
203 reason = e.args[1]
202
204
203 if reason == "INVALID_CERTIFICATE":
205 if reason == "INVALID_CERTIFICATE":
204 log.exception("Exception creating a repository: invalid certificate")
206 log.exception("Exception creating a repository: invalid certificate")
205 msg = _("Error creating repository %s: invalid certificate") % repo_name
207 msg = _("Error creating repository %s: invalid certificate") % repo_name
206 else:
208 else:
207 log.exception("Exception creating a repository")
209 log.exception("Exception creating a repository")
208 msg = _("Error creating repository %s") % repo_name
210 msg = _("Error creating repository %s") % repo_name
209 return msg
211 return msg
210
212
211 def _get_local_tmpl_context(self, include_app_defaults=True):
213 def _get_local_tmpl_context(self, include_app_defaults=True):
212 c = TemplateArgs()
214 c = TemplateArgs()
213 c.auth_user = self.request.user
215 c.auth_user = self.request.user
214 # TODO(marcink): migrate the usage of c.rhodecode_user to c.auth_user
216 # TODO(marcink): migrate the usage of c.rhodecode_user to c.auth_user
215 c.rhodecode_user = self.request.user
217 c.rhodecode_user = self.request.user
216
218
217 if include_app_defaults:
219 if include_app_defaults:
218 from rhodecode.lib.base import attach_context_attributes
220 from rhodecode.lib.base import attach_context_attributes
219
221
220 attach_context_attributes(c, self.request, self.request.user.user_id)
222 attach_context_attributes(c, self.request, self.request.user.user_id)
221
223
222 c.is_super_admin = c.auth_user.is_admin
224 c.is_super_admin = c.auth_user.is_admin
223
225
224 c.can_create_repo = c.is_super_admin
226 c.can_create_repo = c.is_super_admin
225 c.can_create_repo_group = c.is_super_admin
227 c.can_create_repo_group = c.is_super_admin
226 c.can_create_user_group = c.is_super_admin
228 c.can_create_user_group = c.is_super_admin
227
229
228 c.is_delegated_admin = False
230 c.is_delegated_admin = False
229
231
230 if not c.auth_user.is_default and not c.is_super_admin:
232 if not c.auth_user.is_default and not c.is_super_admin:
231 c.can_create_repo = h.HasPermissionAny("hg.create.repository")(
233 c.can_create_repo = h.HasPermissionAny("hg.create.repository")(
232 user=self.request.user
234 user=self.request.user
233 )
235 )
234 repositories = c.auth_user.repositories_admin or c.can_create_repo
236 repositories = c.auth_user.repositories_admin or c.can_create_repo
235
237
236 c.can_create_repo_group = h.HasPermissionAny("hg.repogroup.create.true")(
238 c.can_create_repo_group = h.HasPermissionAny("hg.repogroup.create.true")(
237 user=self.request.user
239 user=self.request.user
238 )
240 )
239 repository_groups = (
241 repository_groups = (
240 c.auth_user.repository_groups_admin or c.can_create_repo_group
242 c.auth_user.repository_groups_admin or c.can_create_repo_group
241 )
243 )
242
244
243 c.can_create_user_group = h.HasPermissionAny("hg.usergroup.create.true")(
245 c.can_create_user_group = h.HasPermissionAny("hg.usergroup.create.true")(
244 user=self.request.user
246 user=self.request.user
245 )
247 )
246 user_groups = c.auth_user.user_groups_admin or c.can_create_user_group
248 user_groups = c.auth_user.user_groups_admin or c.can_create_user_group
247 # delegated admin can create, or manage some objects
249 # delegated admin can create, or manage some objects
248 c.is_delegated_admin = repositories or repository_groups or user_groups
250 c.is_delegated_admin = repositories or repository_groups or user_groups
249 return c
251 return c
250
252
251 def _get_template_context(self, tmpl_args, **kwargs):
253 def _get_template_context(self, tmpl_args, **kwargs):
252 local_tmpl_args = {"defaults": {}, "errors": {}, "c": tmpl_args}
254 local_tmpl_args = {"defaults": {}, "errors": {}, "c": tmpl_args}
253 local_tmpl_args.update(kwargs)
255 local_tmpl_args.update(kwargs)
254 return local_tmpl_args
256 return local_tmpl_args
255
257
256 def load_default_context(self):
258 def load_default_context(self):
257 """
259 """
258 example:
260 example:
259
261
260 def load_default_context(self):
262 def load_default_context(self):
261 c = self._get_local_tmpl_context()
263 c = self._get_local_tmpl_context()
262 c.custom_var = 'foobar'
264 c.custom_var = 'foobar'
263
265
264 return c
266 return c
265 """
267 """
266 raise NotImplementedError("Needs implementation in view class")
268 raise NotImplementedError("Needs implementation in view class")
267
269
268
270
269 class RepoAppView(BaseAppView):
271 class RepoAppView(BaseAppView):
270 def __init__(self, context, request):
272 def __init__(self, context, request):
271 super().__init__(context, request)
273 super().__init__(context, request)
272 self.db_repo = request.db_repo
274 self.db_repo = request.db_repo
273 self.db_repo_name = self.db_repo.repo_name
275 self.db_repo_name = self.db_repo.repo_name
274 self.db_repo_pull_requests = ScmModel().get_pull_requests(self.db_repo)
276 self.db_repo_pull_requests = ScmModel().get_pull_requests(self.db_repo)
275 self.db_repo_artifacts = ScmModel().get_artifacts(self.db_repo)
277 self.db_repo_artifacts = ScmModel().get_artifacts(self.db_repo)
276 self.db_repo_patterns = IssueTrackerSettingsModel(repo=self.db_repo)
278 self.db_repo_patterns = IssueTrackerSettingsModel(repo=self.db_repo)
277
279
278 def _handle_missing_requirements(self, error):
280 def _handle_missing_requirements(self, error):
279 log.error(
281 log.error(
280 "Requirements are missing for repository %s: %s",
282 "Requirements are missing for repository %s: %s",
281 self.db_repo_name,
283 self.db_repo_name,
282 safe_str(error),
284 safe_str(error),
283 )
285 )
284
286
285 def _prepare_and_set_clone_url(self, c):
287 def _prepare_and_set_clone_url(self, c):
286 username = ""
288 username = ""
287 if self._rhodecode_user.username != User.DEFAULT_USER:
289 if self._rhodecode_user.username != User.DEFAULT_USER:
288 username = self._rhodecode_user.username
290 username = self._rhodecode_user.username
289
291
290 _def_clone_uri = c.clone_uri_tmpl
292 _def_clone_uri = c.clone_uri_tmpl
291 _def_clone_uri_id = c.clone_uri_id_tmpl
293 _def_clone_uri_id = c.clone_uri_id_tmpl
292 _def_clone_uri_ssh = c.clone_uri_ssh_tmpl
294 _def_clone_uri_ssh = c.clone_uri_ssh_tmpl
293
295
294 c.clone_repo_url = self.db_repo.clone_url(
296 c.clone_repo_url = self.db_repo.clone_url(
295 user=username, uri_tmpl=_def_clone_uri
297 user=username, uri_tmpl=_def_clone_uri
296 )
298 )
297 c.clone_repo_url_id = self.db_repo.clone_url(
299 c.clone_repo_url_id = self.db_repo.clone_url(
298 user=username, uri_tmpl=_def_clone_uri_id
300 user=username, uri_tmpl=_def_clone_uri_id
299 )
301 )
300 c.clone_repo_url_ssh = self.db_repo.clone_url(
302 c.clone_repo_url_ssh = self.db_repo.clone_url(
301 uri_tmpl=_def_clone_uri_ssh, ssh=True
303 uri_tmpl=_def_clone_uri_ssh, ssh=True
302 )
304 )
303
305
304 def _get_local_tmpl_context(self, include_app_defaults=True):
306 def _get_local_tmpl_context(self, include_app_defaults=True):
305 _ = self.request.translate
307 _ = self.request.translate
306 c = super()._get_local_tmpl_context(include_app_defaults=include_app_defaults)
308 c = super()._get_local_tmpl_context(include_app_defaults=include_app_defaults)
307
309
308 # register common vars for this type of view
310 # register common vars for this type of view
309 c.rhodecode_db_repo = self.db_repo
311 c.rhodecode_db_repo = self.db_repo
310 c.repo_name = self.db_repo_name
312 c.repo_name = self.db_repo_name
311 c.repository_pull_requests = self.db_repo_pull_requests
313 c.repository_pull_requests = self.db_repo_pull_requests
312 c.repository_artifacts = self.db_repo_artifacts
314 c.repository_artifacts = self.db_repo_artifacts
313 c.repository_is_user_following = ScmModel().is_following_repo(
315 c.repository_is_user_following = ScmModel().is_following_repo(
314 self.db_repo_name, self._rhodecode_user.user_id
316 self.db_repo_name, self._rhodecode_user.user_id
315 )
317 )
316 self.path_filter = PathFilter(None)
318 self.path_filter = PathFilter(None)
317
319
318 c.repository_requirements_missing = {}
320 c.repository_requirements_missing = {}
319 try:
321 try:
320 self.rhodecode_vcs_repo = self.db_repo.scm_instance()
322 self.rhodecode_vcs_repo = self.db_repo.scm_instance()
321 # NOTE(marcink):
323 # NOTE(marcink):
322 # comparison to None since if it's an object __bool__ is expensive to
324 # comparison to None since if it's an object __bool__ is expensive to
323 # calculate
325 # calculate
324 if self.rhodecode_vcs_repo is not None:
326 if self.rhodecode_vcs_repo is not None:
325 path_perms = self.rhodecode_vcs_repo.get_path_permissions(
327 path_perms = self.rhodecode_vcs_repo.get_path_permissions(
326 c.auth_user.username
328 c.auth_user.username
327 )
329 )
328 self.path_filter = PathFilter(path_perms)
330 self.path_filter = PathFilter(path_perms)
329 except RepositoryRequirementError as e:
331 except RepositoryRequirementError as e:
330 c.repository_requirements_missing = {"error": str(e)}
332 c.repository_requirements_missing = {"error": str(e)}
331 self._handle_missing_requirements(e)
333 self._handle_missing_requirements(e)
332 self.rhodecode_vcs_repo = None
334 self.rhodecode_vcs_repo = None
333
335
334 c.path_filter = self.path_filter # used by atom_feed_entry.mako
336 c.path_filter = self.path_filter # used by atom_feed_entry.mako
335
337
336 if self.rhodecode_vcs_repo is None:
338 if self.rhodecode_vcs_repo is None:
337 # unable to fetch this repo as vcs instance, report back to user
339 # unable to fetch this repo as vcs instance, report back to user
338 log.debug(
340 log.debug(
339 "Repository was not found on filesystem, check if it exists or is not damaged"
341 "Repository was not found on filesystem, check if it exists or is not damaged"
340 )
342 )
341 h.flash(
343 h.flash(
342 _(
344 _(
343 "The repository `%(repo_name)s` cannot be loaded in filesystem. "
345 "The repository `%(repo_name)s` cannot be loaded in filesystem. "
344 "Please check if it exist, or is not damaged."
346 "Please check if it exist, or is not damaged."
345 )
347 )
346 % {"repo_name": c.repo_name},
348 % {"repo_name": c.repo_name},
347 category="error",
349 category="error",
348 ignore_duplicate=True,
350 ignore_duplicate=True,
349 )
351 )
350 if c.repository_requirements_missing:
352 if c.repository_requirements_missing:
351 route = self.request.matched_route.name
353 route = self.request.matched_route.name
352 if route.startswith(("edit_repo", "repo_summary")):
354 if route.startswith(("edit_repo", "repo_summary")):
353 # allow summary and edit repo on missing requirements
355 # allow summary and edit repo on missing requirements
354 return c
356 return c
355
357
356 raise HTTPFound(
358 raise HTTPFound(
357 h.route_path("repo_summary", repo_name=self.db_repo_name)
359 h.route_path("repo_summary", repo_name=self.db_repo_name)
358 )
360 )
359
361
360 else: # redirect if we don't show missing requirements
362 else: # redirect if we don't show missing requirements
361 raise HTTPFound(h.route_path("home"))
363 raise HTTPFound(h.route_path("home"))
362
364
363 c.has_origin_repo_read_perm = False
365 c.has_origin_repo_read_perm = False
364 if self.db_repo.fork:
366 if self.db_repo.fork:
365 c.has_origin_repo_read_perm = h.HasRepoPermissionAny(
367 c.has_origin_repo_read_perm = h.HasRepoPermissionAny(
366 "repository.write", "repository.read", "repository.admin"
368 "repository.write", "repository.read", "repository.admin"
367 )(self.db_repo.fork.repo_name, "summary fork link")
369 )(self.db_repo.fork.repo_name, "summary fork link")
368
370
369 return c
371 return c
370
372
371 def _get_f_path_unchecked(self, matchdict, default=None):
373 def _get_f_path_unchecked(self, matchdict, default=None):
372 """
374 """
373 Should only be used by redirects, everything else should call _get_f_path
375 Should only be used by redirects, everything else should call _get_f_path
374 """
376 """
375 f_path = matchdict.get("f_path")
377 f_path = matchdict.get("f_path")
376 if f_path:
378 if f_path:
377 # fix for multiple initial slashes that causes errors for GIT
379 # fix for multiple initial slashes that causes errors for GIT
378 return f_path.lstrip("/")
380 return f_path.lstrip("/")
379
381
380 return default
382 return default
381
383
382 def _get_f_path(self, matchdict, default=None):
384 def _get_f_path(self, matchdict, default=None):
383 f_path_match = self._get_f_path_unchecked(matchdict, default)
385 f_path_match = self._get_f_path_unchecked(matchdict, default)
384 return self.path_filter.assert_path_permissions(f_path_match)
386 return self.path_filter.assert_path_permissions(f_path_match)
385
387
386 def _get_general_setting(self, target_repo, settings_key, default=False):
388 def _get_general_setting(self, target_repo, settings_key, default=False):
387 settings_model = VcsSettingsModel(repo=target_repo)
389 settings_model = VcsSettingsModel(repo=target_repo)
388 settings = settings_model.get_general_settings()
390 settings = settings_model.get_general_settings()
389 return settings.get(settings_key, default)
391 return settings.get(settings_key, default)
390
392
391 def _get_repo_setting(self, target_repo, settings_key, default=False):
393 def _get_repo_setting(self, target_repo, settings_key, default=False):
392 settings_model = VcsSettingsModel(repo=target_repo)
394 settings_model = VcsSettingsModel(repo=target_repo)
393 settings = settings_model.get_repo_settings_inherited()
395 settings = settings_model.get_repo_settings_inherited()
394 return settings.get(settings_key, default)
396 return settings.get(settings_key, default)
395
397
396 def _get_readme_data(self, db_repo, renderer_type, commit_id=None, path="/"):
398 def _get_readme_data(self, db_repo, renderer_type, commit_id=None, path="/"):
397 log.debug("Looking for README file at path %s", path)
399 log.debug("Looking for README file at path %s", path)
398 if commit_id:
400 if commit_id:
399 landing_commit_id = commit_id
401 landing_commit_id = commit_id
400 else:
402 else:
401 landing_commit = db_repo.get_landing_commit()
403 landing_commit = db_repo.get_landing_commit()
402 if isinstance(landing_commit, EmptyCommit):
404 if isinstance(landing_commit, EmptyCommit):
403 return None, None
405 return None, None
404 landing_commit_id = landing_commit.raw_id
406 landing_commit_id = landing_commit.raw_id
405
407
406 cache_namespace_uid = f"repo.{db_repo.repo_id}"
408 cache_namespace_uid = f"repo.{db_repo.repo_id}"
407 region = rc_cache.get_or_create_region(
409 region = rc_cache.get_or_create_region(
408 "cache_repo", cache_namespace_uid, use_async_runner=False
410 "cache_repo", cache_namespace_uid, use_async_runner=False
409 )
411 )
410 start = time.time()
412 start = time.time()
411
413
412 @region.conditional_cache_on_arguments(namespace=cache_namespace_uid)
414 @region.conditional_cache_on_arguments(namespace=cache_namespace_uid)
413 def generate_repo_readme(
415 def generate_repo_readme(
414 repo_id, _commit_id, _repo_name, _readme_search_path, _renderer_type
416 repo_id, _commit_id, _repo_name, _readme_search_path, _renderer_type
415 ):
417 ):
416 readme_data = None
418 readme_data = None
417 readme_filename = None
419 readme_filename = None
418
420
419 commit = db_repo.get_commit(_commit_id)
421 commit = db_repo.get_commit(_commit_id)
420 log.debug("Searching for a README file at commit %s.", _commit_id)
422 log.debug("Searching for a README file at commit %s.", _commit_id)
421 readme_node = ReadmeFinder(_renderer_type).search(
423 readme_node = ReadmeFinder(_renderer_type).search(
422 commit, path=_readme_search_path
424 commit, path=_readme_search_path
423 )
425 )
424
426
425 if readme_node:
427 if readme_node:
426 log.debug("Found README node: %s", readme_node)
428 log.debug("Found README node: %s", readme_node)
427
429
428 relative_urls = {
430 relative_urls = {
429 "raw": h.route_path(
431 "raw": h.route_path(
430 "repo_file_raw",
432 "repo_file_raw",
431 repo_name=_repo_name,
433 repo_name=_repo_name,
432 commit_id=commit.raw_id,
434 commit_id=commit.raw_id,
433 f_path=readme_node.path,
435 f_path=readme_node.path,
434 ),
436 ),
435 "standard": h.route_path(
437 "standard": h.route_path(
436 "repo_files",
438 "repo_files",
437 repo_name=_repo_name,
439 repo_name=_repo_name,
438 commit_id=commit.raw_id,
440 commit_id=commit.raw_id,
439 f_path=readme_node.path,
441 f_path=readme_node.path,
440 ),
442 ),
441 }
443 }
442
444
443 readme_data = self._render_readme_or_none(
445 readme_data = self._render_readme_or_none(
444 commit, readme_node, relative_urls
446 commit, readme_node, relative_urls
445 )
447 )
446 readme_filename = readme_node.str_path
448 readme_filename = readme_node.str_path
447
449
448 return readme_data, readme_filename
450 return readme_data, readme_filename
449
451
450 readme_data, readme_filename = generate_repo_readme(
452 readme_data, readme_filename = generate_repo_readme(
451 db_repo.repo_id,
453 db_repo.repo_id,
452 landing_commit_id,
454 landing_commit_id,
453 db_repo.repo_name,
455 db_repo.repo_name,
454 path,
456 path,
455 renderer_type,
457 renderer_type,
456 )
458 )
457
459
458 compute_time = time.time() - start
460 compute_time = time.time() - start
459 log.debug(
461 log.debug(
460 "Repo README for path %s generated and computed in %.4fs",
462 "Repo README for path %s generated and computed in %.4fs",
461 path,
463 path,
462 compute_time,
464 compute_time,
463 )
465 )
464 return readme_data, readme_filename
466 return readme_data, readme_filename
465
467
466 def _render_readme_or_none(self, commit, readme_node, relative_urls):
468 def _render_readme_or_none(self, commit, readme_node, relative_urls):
467 log.debug("Found README file `%s` rendering...", readme_node.path)
469 log.debug("Found README file `%s` rendering...", readme_node.path)
468 renderer = MarkupRenderer()
470 renderer = MarkupRenderer()
469 try:
471 try:
470 html_source = renderer.render(
472 html_source = renderer.render(
471 readme_node.str_content, filename=readme_node.path
473 readme_node.str_content, filename=readme_node.path
472 )
474 )
473 if relative_urls:
475 if relative_urls:
474 return relative_links(html_source, relative_urls)
476 return relative_links(html_source, relative_urls)
475 return html_source
477 return html_source
476 except Exception:
478 except Exception:
477 log.exception("Exception while trying to render the README")
479 log.exception("Exception while trying to render the README")
478
480
479 def get_recache_flag(self):
481 def get_recache_flag(self):
480 for flag_name in ["force_recache", "force-recache", "no-cache"]:
482 for flag_name in ["force_recache", "force-recache", "no-cache"]:
481 flag_val = self.request.GET.get(flag_name)
483 flag_val = self.request.GET.get(flag_name)
482 if str2bool(flag_val):
484 if str2bool(flag_val):
483 return True
485 return True
484 return False
486 return False
485
487
486 def get_commit_preload_attrs(cls):
488 def get_commit_preload_attrs(cls):
487 pre_load = [
489 pre_load = [
488 "author",
490 "author",
489 "branch",
491 "branch",
490 "date",
492 "date",
491 "message",
493 "message",
492 "parents",
494 "parents",
493 "obsolete",
495 "obsolete",
494 "phase",
496 "phase",
495 "hidden",
497 "hidden",
496 ]
498 ]
497 return pre_load
499 return pre_load
498
500
499
501
500 class PathFilter(object):
502 class PathFilter(object):
501 # Expects and instance of BasePathPermissionChecker or None
503 # Expects and instance of BasePathPermissionChecker or None
502 def __init__(self, permission_checker):
504 def __init__(self, permission_checker):
503 self.permission_checker = permission_checker
505 self.permission_checker = permission_checker
504
506
505 def assert_path_permissions(self, path):
507 def assert_path_permissions(self, path):
506 if self.path_access_allowed(path):
508 if self.path_access_allowed(path):
507 return path
509 return path
508 raise HTTPForbidden()
510 raise HTTPForbidden()
509
511
510 def path_access_allowed(self, path):
512 def path_access_allowed(self, path):
511 log.debug("Checking ACL permissions for PathFilter for `%s`", path)
513 log.debug("Checking ACL permissions for PathFilter for `%s`", path)
512 if self.permission_checker:
514 if self.permission_checker:
513 has_access = path and self.permission_checker.has_access(path)
515 has_access = path and self.permission_checker.has_access(path)
514 log.debug(
516 log.debug(
515 "ACL Permissions checker enabled, ACL Check has_access: %s", has_access
517 "ACL Permissions checker enabled, ACL Check has_access: %s", has_access
516 )
518 )
517 return has_access
519 return has_access
518
520
519 log.debug("ACL permissions checker not enabled, skipping...")
521 log.debug("ACL permissions checker not enabled, skipping...")
520 return True
522 return True
521
523
522 def filter_patchset(self, patchset):
524 def filter_patchset(self, patchset):
523 if not self.permission_checker or not patchset:
525 if not self.permission_checker or not patchset:
524 return patchset, False
526 return patchset, False
525 had_filtered = False
527 had_filtered = False
526 filtered_patchset = []
528 filtered_patchset = []
527 for patch in patchset:
529 for patch in patchset:
528 filename = patch.get("filename", None)
530 filename = patch.get("filename", None)
529 if not filename or self.permission_checker.has_access(filename):
531 if not filename or self.permission_checker.has_access(filename):
530 filtered_patchset.append(patch)
532 filtered_patchset.append(patch)
531 else:
533 else:
532 had_filtered = True
534 had_filtered = True
533 if had_filtered:
535 if had_filtered:
534 if isinstance(patchset, diffs.LimitedDiffContainer):
536 if isinstance(patchset, diffs.LimitedDiffContainer):
535 filtered_patchset = diffs.LimitedDiffContainer(
537 filtered_patchset = diffs.LimitedDiffContainer(
536 patchset.diff_limit, patchset.cur_diff_size, filtered_patchset
538 patchset.diff_limit, patchset.cur_diff_size, filtered_patchset
537 )
539 )
538 return filtered_patchset, True
540 return filtered_patchset, True
539 else:
541 else:
540 return patchset, False
542 return patchset, False
541
543
542 def render_patchset_filtered(
544 def render_patchset_filtered(
543 self, diffset, patchset, source_ref=None, target_ref=None
545 self, diffset, patchset, source_ref=None, target_ref=None
544 ):
546 ):
545 filtered_patchset, has_hidden_changes = self.filter_patchset(patchset)
547 filtered_patchset, has_hidden_changes = self.filter_patchset(patchset)
546 result = diffset.render_patchset(
548 result = diffset.render_patchset(
547 filtered_patchset, source_ref=source_ref, target_ref=target_ref
549 filtered_patchset, source_ref=source_ref, target_ref=target_ref
548 )
550 )
549 result.has_hidden_changes = has_hidden_changes
551 result.has_hidden_changes = has_hidden_changes
550 return result
552 return result
551
553
552 def get_raw_patch(self, diff_processor):
554 def get_raw_patch(self, diff_processor):
553 if self.permission_checker is None:
555 if self.permission_checker is None:
554 return diff_processor.as_raw()
556 return diff_processor.as_raw()
555 elif self.permission_checker.has_full_access:
557 elif self.permission_checker.has_full_access:
556 return diff_processor.as_raw()
558 return diff_processor.as_raw()
557 else:
559 else:
558 return "# Repository has user-specific filters, raw patch generation is disabled."
560 return "# Repository has user-specific filters, raw patch generation is disabled."
559
561
560 @property
562 @property
561 def is_enabled(self):
563 def is_enabled(self):
562 return self.permission_checker is not None
564 return self.permission_checker is not None
563
565
564
566
565 class RepoGroupAppView(BaseAppView):
567 class RepoGroupAppView(BaseAppView):
566 def __init__(self, context, request):
568 def __init__(self, context, request):
567 super().__init__(context, request)
569 super().__init__(context, request)
568 self.db_repo_group = request.db_repo_group
570 self.db_repo_group = request.db_repo_group
569 self.db_repo_group_name = self.db_repo_group.group_name
571 self.db_repo_group_name = self.db_repo_group.group_name
570
572
571 def _get_local_tmpl_context(self, include_app_defaults=True):
573 def _get_local_tmpl_context(self, include_app_defaults=True):
572 _ = self.request.translate
574 _ = self.request.translate
573 c = super()._get_local_tmpl_context(include_app_defaults=include_app_defaults)
575 c = super()._get_local_tmpl_context(include_app_defaults=include_app_defaults)
574 c.repo_group = self.db_repo_group
576 c.repo_group = self.db_repo_group
575 return c
577 return c
576
578
577 def _revoke_perms_on_yourself(self, form_result):
579 def _revoke_perms_on_yourself(self, form_result):
578 _updates = [
580 _updates = [
579 u
581 u
580 for u in form_result["perm_updates"]
582 for u in form_result["perm_updates"]
581 if self._rhodecode_user.user_id == int(u[0])
583 if self._rhodecode_user.user_id == int(u[0])
582 ]
584 ]
583 _additions = [
585 _additions = [
584 u
586 u
585 for u in form_result["perm_additions"]
587 for u in form_result["perm_additions"]
586 if self._rhodecode_user.user_id == int(u[0])
588 if self._rhodecode_user.user_id == int(u[0])
587 ]
589 ]
588 _deletions = [
590 _deletions = [
589 u
591 u
590 for u in form_result["perm_deletions"]
592 for u in form_result["perm_deletions"]
591 if self._rhodecode_user.user_id == int(u[0])
593 if self._rhodecode_user.user_id == int(u[0])
592 ]
594 ]
593 admin_perm = "group.admin"
595 admin_perm = "group.admin"
594 if (
596 if (
595 _updates
597 _updates
596 and _updates[0][1] != admin_perm
598 and _updates[0][1] != admin_perm
597 or _additions
599 or _additions
598 and _additions[0][1] != admin_perm
600 and _additions[0][1] != admin_perm
599 or _deletions
601 or _deletions
600 and _deletions[0][1] != admin_perm
602 and _deletions[0][1] != admin_perm
601 ):
603 ):
602 return True
604 return True
603 return False
605 return False
604
606
605
607
606 class UserGroupAppView(BaseAppView):
608 class UserGroupAppView(BaseAppView):
607 def __init__(self, context, request):
609 def __init__(self, context, request):
608 super().__init__(context, request)
610 super().__init__(context, request)
609 self.db_user_group = request.db_user_group
611 self.db_user_group = request.db_user_group
610 self.db_user_group_name = self.db_user_group.users_group_name
612 self.db_user_group_name = self.db_user_group.users_group_name
611
613
612
614
613 class UserAppView(BaseAppView):
615 class UserAppView(BaseAppView):
614 def __init__(self, context, request):
616 def __init__(self, context, request):
615 super().__init__(context, request)
617 super().__init__(context, request)
616 self.db_user = request.db_user
618 self.db_user = request.db_user
617 self.db_user_id = self.db_user.user_id
619 self.db_user_id = self.db_user.user_id
618
620
619 _ = self.request.translate
621 _ = self.request.translate
620 if not request.db_user_supports_default:
622 if not request.db_user_supports_default:
621 if self.db_user.username == User.DEFAULT_USER:
623 if self.db_user.username == User.DEFAULT_USER:
622 h.flash(
624 h.flash(
623 _("Editing user `{}` is disabled.".format(User.DEFAULT_USER)),
625 _("Editing user `{}` is disabled.".format(User.DEFAULT_USER)),
624 category="warning",
626 category="warning",
625 )
627 )
626 raise HTTPFound(h.route_path("users"))
628 raise HTTPFound(h.route_path("users"))
627
629
628
630
629 class DataGridAppView(object):
631 class DataGridAppView(object):
630 """
632 """
631 Common class to have re-usable grid rendering components
633 Common class to have re-usable grid rendering components
632 """
634 """
633
635
634 def _extract_ordering(self, request, column_map=None):
636 def _extract_ordering(self, request, column_map=None):
635 column_map = column_map or {}
637 column_map = column_map or {}
636 column_index = safe_int(request.GET.get("order[0][column]"))
638 column_index = safe_int(request.GET.get("order[0][column]"))
637 order_dir = request.GET.get("order[0][dir]", "desc")
639 order_dir = request.GET.get("order[0][dir]", "desc")
638 order_by = request.GET.get("columns[%s][data][sort]" % column_index, "name_raw")
640 order_by = request.GET.get("columns[%s][data][sort]" % column_index, "name_raw")
639
641
640 # translate datatable to DB columns
642 # translate datatable to DB columns
641 order_by = column_map.get(order_by) or order_by
643 order_by = column_map.get(order_by) or order_by
642
644
643 search_q = request.GET.get("search[value]")
645 search_q = request.GET.get("search[value]")
644 return search_q, order_by, order_dir
646 return search_q, order_by, order_dir
645
647
646 def _extract_chunk(self, request):
648 def _extract_chunk(self, request):
647 start = safe_int(request.GET.get("start"), 0)
649 start = safe_int(request.GET.get("start"), 0)
648 length = safe_int(request.GET.get("length"), 25)
650 length = safe_int(request.GET.get("length"), 25)
649 draw = safe_int(request.GET.get("draw"))
651 draw = safe_int(request.GET.get("draw"))
650 return draw, start, length
652 return draw, start, length
651
653
652 def _get_order_col(self, order_by, model):
654 def _get_order_col(self, order_by, model):
653 if isinstance(order_by, str):
655 if isinstance(order_by, str):
654 try:
656 try:
655 return operator.attrgetter(order_by)(model)
657 return operator.attrgetter(order_by)(model)
656 except AttributeError:
658 except AttributeError:
657 return None
659 return None
658 else:
660 else:
659 return order_by
661 return order_by
660
662
661
663
662 class BaseReferencesView(RepoAppView):
664 class BaseReferencesView(RepoAppView):
663 """
665 """
664 Base for reference view for branches, tags and bookmarks.
666 Base for reference view for branches, tags and bookmarks.
665 """
667 """
666
668
667 def load_default_context(self):
669 def load_default_context(self):
668 c = self._get_local_tmpl_context()
670 c = self._get_local_tmpl_context()
669 return c
671 return c
670
672
671 def load_refs_context(self, ref_items, partials_template):
673 def load_refs_context(self, ref_items, partials_template):
672 _render = self.request.get_partial_renderer(partials_template)
674 _render = self.request.get_partial_renderer(partials_template)
673 pre_load = ["author", "date", "message", "parents"]
675 pre_load = ["author", "date", "message", "parents"]
674
676
675 is_svn = h.is_svn(self.rhodecode_vcs_repo)
677 is_svn = h.is_svn(self.rhodecode_vcs_repo)
676 is_hg = h.is_hg(self.rhodecode_vcs_repo)
678 is_hg = h.is_hg(self.rhodecode_vcs_repo)
677
679
678 format_ref_id = get_format_ref_id(self.rhodecode_vcs_repo)
680 format_ref_id = get_format_ref_id(self.rhodecode_vcs_repo)
679
681
680 closed_refs = {}
682 closed_refs = {}
681 if is_hg:
683 if is_hg:
682 closed_refs = self.rhodecode_vcs_repo.branches_closed
684 closed_refs = self.rhodecode_vcs_repo.branches_closed
683
685
684 data = []
686 data = []
685 for ref_name, commit_id in ref_items:
687 for ref_name, commit_id in ref_items:
686 commit = self.rhodecode_vcs_repo.get_commit(
688 commit = self.rhodecode_vcs_repo.get_commit(
687 commit_id=commit_id, pre_load=pre_load
689 commit_id=commit_id, pre_load=pre_load
688 )
690 )
689 closed = ref_name in closed_refs
691 closed = ref_name in closed_refs
690
692
691 # TODO: johbo: Unify generation of reference links
693 # TODO: johbo: Unify generation of reference links
692 use_commit_id = "/" in ref_name or is_svn
694 use_commit_id = "/" in ref_name or is_svn
693
695
694 if use_commit_id:
696 if use_commit_id:
695 files_url = h.route_path(
697 files_url = h.route_path(
696 "repo_files",
698 "repo_files",
697 repo_name=self.db_repo_name,
699 repo_name=self.db_repo_name,
698 f_path=ref_name if is_svn else "",
700 f_path=ref_name if is_svn else "",
699 commit_id=commit_id,
701 commit_id=commit_id,
700 _query=dict(at=ref_name),
702 _query=dict(at=ref_name),
701 )
703 )
702
704
703 else:
705 else:
704 files_url = h.route_path(
706 files_url = h.route_path(
705 "repo_files",
707 "repo_files",
706 repo_name=self.db_repo_name,
708 repo_name=self.db_repo_name,
707 f_path=ref_name if is_svn else "",
709 f_path=ref_name if is_svn else "",
708 commit_id=ref_name,
710 commit_id=ref_name,
709 _query=dict(at=ref_name),
711 _query=dict(at=ref_name),
710 )
712 )
711
713
712 data.append(
714 data.append(
713 {
715 {
714 "name": _render("name", ref_name, files_url, closed),
716 "name": _render("name", ref_name, files_url, closed),
715 "name_raw": ref_name,
717 "name_raw": ref_name,
716 "date": _render("date", commit.date),
718 "date": _render("date", commit.date),
717 "date_raw": datetime_to_time(commit.date),
719 "date_raw": datetime_to_time(commit.date),
718 "author": _render("author", commit.author),
720 "author": _render("author", commit.author),
719 "commit": _render(
721 "commit": _render(
720 "commit", commit.message, commit.raw_id, commit.idx
722 "commit", commit.message, commit.raw_id, commit.idx
721 ),
723 ),
722 "commit_raw": commit.idx,
724 "commit_raw": commit.idx,
723 "compare": _render(
725 "compare": _render(
724 "compare", format_ref_id(ref_name, commit.raw_id)
726 "compare", format_ref_id(ref_name, commit.raw_id)
725 ),
727 ),
726 }
728 }
727 )
729 )
728
730
729 return data
731 return data
730
732
731
733
732 class RepoRoutePredicate(object):
734 class RepoRoutePredicate(object):
733 def __init__(self, val, config):
735 def __init__(self, val, config):
734 self.val = val
736 self.val = val
735
737
736 def text(self):
738 def text(self):
737 return f"repo_route = {self.val}"
739 return f"repo_route = {self.val}"
738
740
739 phash = text
741 phash = text
740
742
741 def __call__(self, info, request):
743 def __call__(self, info, request):
742 if hasattr(request, "vcs_call"):
744 if hasattr(request, "vcs_call"):
743 # skip vcs calls
745 # skip vcs calls
744 return
746 return
745
747
746 repo_name = info["match"]["repo_name"]
748 repo_name = info["match"]["repo_name"]
747
749
748 repo_name_parts = repo_name.split("/")
750 repo_name_parts = repo_name.split("/")
749 repo_slugs = [x for x in (repo_name_slug(x) for x in repo_name_parts)]
751 repo_slugs = [x for x in (repo_name_slug(x) for x in repo_name_parts)]
750
752
751 if repo_name_parts != repo_slugs:
753 if repo_name_parts != repo_slugs:
752 # short-skip if the repo-name doesn't follow slug rule
754 # short-skip if the repo-name doesn't follow slug rule
753 log.warning(
755 log.warning(
754 "repo_name: %s is different than slug %s", repo_name_parts, repo_slugs
756 "repo_name: %s is different than slug %s", repo_name_parts, repo_slugs
755 )
757 )
756 return False
758 return False
757
759
758 repo_model = repo.RepoModel()
760 repo_model = repo.RepoModel()
759
761
760 by_name_match = repo_model.get_by_repo_name(repo_name, cache=False)
762 by_name_match = repo_model.get_by_repo_name(repo_name, cache=False)
761
763
762 def redirect_if_creating(route_info, db_repo):
764 def redirect_if_creating(route_info, db_repo):
763 skip_views = ["edit_repo_advanced_delete"]
765 skip_views = ["edit_repo_advanced_delete"]
764 route = route_info["route"]
766 route = route_info["route"]
765 # we should skip delete view so we can actually "remove" repositories
767 # we should skip delete view so we can actually "remove" repositories
766 # if they get stuck in creating state.
768 # if they get stuck in creating state.
767 if route.name in skip_views:
769 if route.name in skip_views:
768 return
770 return
769
771
770 if db_repo.repo_state in [repo.Repository.STATE_PENDING]:
772 if db_repo.repo_state in [repo.Repository.STATE_PENDING]:
771 repo_creating_url = request.route_path(
773 repo_creating_url = request.route_path(
772 "repo_creating", repo_name=db_repo.repo_name
774 "repo_creating", repo_name=db_repo.repo_name
773 )
775 )
774 raise HTTPFound(repo_creating_url)
776 raise HTTPFound(repo_creating_url)
775
777
776 if by_name_match:
778 if by_name_match:
777 # register this as request object we can re-use later
779 # register this as request object we can re-use later
778 request.db_repo = by_name_match
780 request.db_repo = by_name_match
779 request.db_repo_name = request.db_repo.repo_name
781 request.db_repo_name = request.db_repo.repo_name
780
782
781 redirect_if_creating(info, by_name_match)
783 redirect_if_creating(info, by_name_match)
782 return True
784 return True
783
785
784 by_id_match = repo_model.get_repo_by_id(repo_name)
786 by_id_match = repo_model.get_repo_by_id(repo_name)
785 if by_id_match:
787 if by_id_match:
786 request.db_repo = by_id_match
788 request.db_repo = by_id_match
787 request.db_repo_name = request.db_repo.repo_name
789 request.db_repo_name = request.db_repo.repo_name
788 redirect_if_creating(info, by_id_match)
790 redirect_if_creating(info, by_id_match)
789 return True
791 return True
790
792
791 return False
793 return False
792
794
793
795
794 class RepoForbidArchivedRoutePredicate(object):
796 class RepoForbidArchivedRoutePredicate(object):
795 def __init__(self, val, config):
797 def __init__(self, val, config):
796 self.val = val
798 self.val = val
797
799
798 def text(self):
800 def text(self):
799 return f"repo_forbid_archived = {self.val}"
801 return f"repo_forbid_archived = {self.val}"
800
802
801 phash = text
803 phash = text
802
804
803 def __call__(self, info, request):
805 def __call__(self, info, request):
804 _ = request.translate
806 _ = request.translate
805 rhodecode_db_repo = request.db_repo
807 rhodecode_db_repo = request.db_repo
806
808
807 log.debug(
809 log.debug(
808 "%s checking if archived flag for repo for %s",
810 "%s checking if archived flag for repo for %s",
809 self.__class__.__name__,
811 self.__class__.__name__,
810 rhodecode_db_repo.repo_name,
812 rhodecode_db_repo.repo_name,
811 )
813 )
812
814
813 if rhodecode_db_repo.archived:
815 if rhodecode_db_repo.archived:
814 log.warning(
816 log.warning(
815 "Current view is not supported for archived repo:%s",
817 "Current view is not supported for archived repo:%s",
816 rhodecode_db_repo.repo_name,
818 rhodecode_db_repo.repo_name,
817 )
819 )
818
820
819 h.flash(
821 h.flash(
820 h.literal(_("Action not supported for archived repository.")),
822 h.literal(_("Action not supported for archived repository.")),
821 category="warning",
823 category="warning",
822 )
824 )
823 summary_url = request.route_path(
825 summary_url = request.route_path(
824 "repo_summary", repo_name=rhodecode_db_repo.repo_name
826 "repo_summary", repo_name=rhodecode_db_repo.repo_name
825 )
827 )
826 raise HTTPFound(summary_url)
828 raise HTTPFound(summary_url)
827 return True
829 return True
828
830
829
831
830 class RepoTypeRoutePredicate(object):
832 class RepoTypeRoutePredicate(object):
831 def __init__(self, val, config):
833 def __init__(self, val, config):
832 self.val = val or ["hg", "git", "svn"]
834 self.val = val or ["hg", "git", "svn"]
833
835
834 def text(self):
836 def text(self):
835 return f"repo_accepted_type = {self.val}"
837 return f"repo_accepted_type = {self.val}"
836
838
837 phash = text
839 phash = text
838
840
839 def __call__(self, info, request):
841 def __call__(self, info, request):
840 if hasattr(request, "vcs_call"):
842 if hasattr(request, "vcs_call"):
841 # skip vcs calls
843 # skip vcs calls
842 return
844 return
843
845
844 rhodecode_db_repo = request.db_repo
846 rhodecode_db_repo = request.db_repo
845
847
846 log.debug(
848 log.debug(
847 "%s checking repo type for %s in %s",
849 "%s checking repo type for %s in %s",
848 self.__class__.__name__,
850 self.__class__.__name__,
849 rhodecode_db_repo.repo_type,
851 rhodecode_db_repo.repo_type,
850 self.val,
852 self.val,
851 )
853 )
852
854
853 if rhodecode_db_repo.repo_type in self.val:
855 if rhodecode_db_repo.repo_type in self.val:
854 return True
856 return True
855 else:
857 else:
856 log.warning(
858 log.warning(
857 "Current view is not supported for repo type:%s",
859 "Current view is not supported for repo type:%s",
858 rhodecode_db_repo.repo_type,
860 rhodecode_db_repo.repo_type,
859 )
861 )
860 return False
862 return False
861
863
862
864
863 class RepoGroupRoutePredicate(object):
865 class RepoGroupRoutePredicate(object):
864 def __init__(self, val, config):
866 def __init__(self, val, config):
865 self.val = val
867 self.val = val
866
868
867 def text(self):
869 def text(self):
868 return f"repo_group_route = {self.val}"
870 return f"repo_group_route = {self.val}"
869
871
870 phash = text
872 phash = text
871
873
872 def __call__(self, info, request):
874 def __call__(self, info, request):
873 if hasattr(request, "vcs_call"):
875 if hasattr(request, "vcs_call"):
874 # skip vcs calls
876 # skip vcs calls
875 return
877 return
876
878
877 repo_group_name = info["match"]["repo_group_name"]
879 repo_group_name = info["match"]["repo_group_name"]
878
880
879 repo_group_name_parts = repo_group_name.split("/")
881 repo_group_name_parts = repo_group_name.split("/")
880 repo_group_slugs = [
882 repo_group_slugs = [
881 x for x in [repo_name_slug(x) for x in repo_group_name_parts]
883 x for x in [repo_name_slug(x) for x in repo_group_name_parts]
882 ]
884 ]
883 if repo_group_name_parts != repo_group_slugs:
885 if repo_group_name_parts != repo_group_slugs:
884 # short-skip if the repo-name doesn't follow slug rule
886 # short-skip if the repo-name doesn't follow slug rule
885 log.warning(
887 log.warning(
886 "repo_group_name: %s is different than slug %s",
888 "repo_group_name: %s is different than slug %s",
887 repo_group_name_parts,
889 repo_group_name_parts,
888 repo_group_slugs,
890 repo_group_slugs,
889 )
891 )
890 return False
892 return False
891
893
892 repo_group_model = repo_group.RepoGroupModel()
894 repo_group_model = repo_group.RepoGroupModel()
893 by_name_match = repo_group_model.get_by_group_name(repo_group_name, cache=False)
895 by_name_match = repo_group_model.get_by_group_name(repo_group_name, cache=False)
894
896
895 if by_name_match:
897 if by_name_match:
896 # register this as request object we can re-use later
898 # register this as request object we can re-use later
897 request.db_repo_group = by_name_match
899 request.db_repo_group = by_name_match
898 request.db_repo_group_name = request.db_repo_group.group_name
900 request.db_repo_group_name = request.db_repo_group.group_name
899 return True
901 return True
900
902
901 return False
903 return False
902
904
903
905
904 class UserGroupRoutePredicate(object):
906 class UserGroupRoutePredicate(object):
905 def __init__(self, val, config):
907 def __init__(self, val, config):
906 self.val = val
908 self.val = val
907
909
908 def text(self):
910 def text(self):
909 return f"user_group_route = {self.val}"
911 return f"user_group_route = {self.val}"
910
912
911 phash = text
913 phash = text
912
914
913 def __call__(self, info, request):
915 def __call__(self, info, request):
914 if hasattr(request, "vcs_call"):
916 if hasattr(request, "vcs_call"):
915 # skip vcs calls
917 # skip vcs calls
916 return
918 return
917
919
918 user_group_id = info["match"]["user_group_id"]
920 user_group_id = info["match"]["user_group_id"]
919 user_group_model = user_group.UserGroup()
921 user_group_model = user_group.UserGroup()
920 by_id_match = user_group_model.get(user_group_id, cache=False)
922 by_id_match = user_group_model.get(user_group_id, cache=False)
921
923
922 if by_id_match:
924 if by_id_match:
923 # register this as request object we can re-use later
925 # register this as request object we can re-use later
924 request.db_user_group = by_id_match
926 request.db_user_group = by_id_match
925 return True
927 return True
926
928
927 return False
929 return False
928
930
929
931
930 class UserRoutePredicateBase(object):
932 class UserRoutePredicateBase(object):
931 supports_default = None
933 supports_default = None
932
934
933 def __init__(self, val, config):
935 def __init__(self, val, config):
934 self.val = val
936 self.val = val
935
937
936 def text(self):
938 def text(self):
937 raise NotImplementedError()
939 raise NotImplementedError()
938
940
939 def __call__(self, info, request):
941 def __call__(self, info, request):
940 if hasattr(request, "vcs_call"):
942 if hasattr(request, "vcs_call"):
941 # skip vcs calls
943 # skip vcs calls
942 return
944 return
943
945
944 user_id = info["match"]["user_id"]
946 user_id = info["match"]["user_id"]
945 user_model = user.User()
947 user_model = user.User()
946 by_id_match = user_model.get(user_id, cache=False)
948 by_id_match = user_model.get(user_id, cache=False)
947
949
948 if by_id_match:
950 if by_id_match:
949 # register this as request object we can re-use later
951 # register this as request object we can re-use later
950 request.db_user = by_id_match
952 request.db_user = by_id_match
951 request.db_user_supports_default = self.supports_default
953 request.db_user_supports_default = self.supports_default
952 return True
954 return True
953
955
954 return False
956 return False
955
957
956
958
957 class UserRoutePredicate(UserRoutePredicateBase):
959 class UserRoutePredicate(UserRoutePredicateBase):
958 supports_default = False
960 supports_default = False
959
961
960 def text(self):
962 def text(self):
961 return f"user_route = {self.val}"
963 return f"user_route = {self.val}"
962
964
963 phash = text
965 phash = text
964
966
965
967
966 class UserRouteWithDefaultPredicate(UserRoutePredicateBase):
968 class UserRouteWithDefaultPredicate(UserRoutePredicateBase):
967 supports_default = True
969 supports_default = True
968
970
969 def text(self):
971 def text(self):
970 return f"user_with_default_route = {self.val}"
972 return f"user_with_default_route = {self.val}"
971
973
972 phash = text
974 phash = text
973
975
974
976
975 def includeme(config):
977 def includeme(config):
976 config.add_route_predicate("repo_route", RepoRoutePredicate)
978 config.add_route_predicate("repo_route", RepoRoutePredicate)
977 config.add_route_predicate("repo_accepted_types", RepoTypeRoutePredicate)
979 config.add_route_predicate("repo_accepted_types", RepoTypeRoutePredicate)
978 config.add_route_predicate(
980 config.add_route_predicate(
979 "repo_forbid_when_archived", RepoForbidArchivedRoutePredicate
981 "repo_forbid_when_archived", RepoForbidArchivedRoutePredicate
980 )
982 )
981 config.add_route_predicate("repo_group_route", RepoGroupRoutePredicate)
983 config.add_route_predicate("repo_group_route", RepoGroupRoutePredicate)
982 config.add_route_predicate("user_group_route", UserGroupRoutePredicate)
984 config.add_route_predicate("user_group_route", UserGroupRoutePredicate)
983 config.add_route_predicate("user_route_with_default", UserRouteWithDefaultPredicate)
985 config.add_route_predicate("user_route_with_default", UserRouteWithDefaultPredicate)
984 config.add_route_predicate("user_route", UserRoutePredicate)
986 config.add_route_predicate("user_route", UserRoutePredicate)
@@ -1,6037 +1,6037 b''
1 # Copyright (C) 2010-2023 RhodeCode GmbH
1 # Copyright (C) 2010-2023 RhodeCode GmbH
2 #
2 #
3 # This program is free software: you can redistribute it and/or modify
3 # This program is free software: you can redistribute it and/or modify
4 # it under the terms of the GNU Affero General Public License, version 3
4 # it under the terms of the GNU Affero General Public License, version 3
5 # (only), as published by the Free Software Foundation.
5 # (only), as published by the Free Software Foundation.
6 #
6 #
7 # This program is distributed in the hope that it will be useful,
7 # This program is distributed in the hope that it will be useful,
8 # but WITHOUT ANY WARRANTY; without even the implied warranty of
8 # but WITHOUT ANY WARRANTY; without even the implied warranty of
9 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
9 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 # GNU General Public License for more details.
10 # GNU General Public License for more details.
11 #
11 #
12 # You should have received a copy of the GNU Affero General Public License
12 # You should have received a copy of the GNU Affero General Public License
13 # along with this program. If not, see <http://www.gnu.org/licenses/>.
13 # along with this program. If not, see <http://www.gnu.org/licenses/>.
14 #
14 #
15 # This program is dual-licensed. If you wish to learn more about the
15 # This program is dual-licensed. If you wish to learn more about the
16 # RhodeCode Enterprise Edition, including its added features, Support services,
16 # RhodeCode Enterprise Edition, including its added features, Support services,
17 # and proprietary license terms, please see https://rhodecode.com/licenses/
17 # and proprietary license terms, please see https://rhodecode.com/licenses/
18
18
19 """
19 """
20 Database Models for RhodeCode Enterprise
20 Database Models for RhodeCode Enterprise
21 """
21 """
22
22
23 import re
23 import re
24 import os
24 import os
25 import time
25 import time
26 import string
26 import string
27 import logging
27 import logging
28 import datetime
28 import datetime
29 import uuid
29 import uuid
30 import warnings
30 import warnings
31 import ipaddress
31 import ipaddress
32 import functools
32 import functools
33 import traceback
33 import traceback
34 import collections
34 import collections
35
35
36 import pyotp
36 import pyotp
37 from sqlalchemy import (
37 from sqlalchemy import (
38 or_, and_, not_, func, cast, TypeDecorator, event, select,
38 or_, and_, not_, func, cast, TypeDecorator, event, select,
39 true, false, null, union_all,
39 true, false, null, union_all,
40 Index, Sequence, UniqueConstraint, ForeignKey, CheckConstraint, Column,
40 Index, Sequence, UniqueConstraint, ForeignKey, CheckConstraint, Column,
41 Boolean, String, Unicode, UnicodeText, DateTime, Integer, LargeBinary,
41 Boolean, String, Unicode, UnicodeText, DateTime, Integer, LargeBinary,
42 Text, Float, PickleType, BigInteger)
42 Text, Float, PickleType, BigInteger)
43 from sqlalchemy.sql.expression import case
43 from sqlalchemy.sql.expression import case
44 from sqlalchemy.sql.functions import coalesce, count # pragma: no cover
44 from sqlalchemy.sql.functions import coalesce, count # pragma: no cover
45 from sqlalchemy.orm import (
45 from sqlalchemy.orm import (
46 relationship, lazyload, joinedload, class_mapper, validates, aliased, load_only)
46 relationship, lazyload, joinedload, class_mapper, validates, aliased, load_only)
47 from sqlalchemy.ext.declarative import declared_attr
47 from sqlalchemy.ext.declarative import declared_attr
48 from sqlalchemy.ext.hybrid import hybrid_property
48 from sqlalchemy.ext.hybrid import hybrid_property
49 from sqlalchemy.exc import IntegrityError # pragma: no cover
49 from sqlalchemy.exc import IntegrityError # pragma: no cover
50 from sqlalchemy.dialects.mysql import LONGTEXT
50 from sqlalchemy.dialects.mysql import LONGTEXT
51 from zope.cachedescriptors.property import Lazy as LazyProperty
51 from zope.cachedescriptors.property import Lazy as LazyProperty
52 from pyramid.threadlocal import get_current_request
52 from pyramid.threadlocal import get_current_request
53 from webhelpers2.text import remove_formatting
53 from webhelpers2.text import remove_formatting
54
54
55 from rhodecode import ConfigGet
55 from rhodecode import ConfigGet
56 from rhodecode.lib.str_utils import safe_bytes
56 from rhodecode.lib.str_utils import safe_bytes
57 from rhodecode.translation import _
57 from rhodecode.translation import _
58 from rhodecode.lib.vcs import get_vcs_instance, VCSError
58 from rhodecode.lib.vcs import get_vcs_instance, VCSError
59 from rhodecode.lib.vcs.backends.base import (
59 from rhodecode.lib.vcs.backends.base import (
60 EmptyCommit, Reference, unicode_to_reference, reference_to_unicode)
60 EmptyCommit, Reference, unicode_to_reference, reference_to_unicode)
61 from rhodecode.lib.utils2 import (
61 from rhodecode.lib.utils2 import (
62 str2bool, safe_str, get_commit_safe, sha1_safe,
62 str2bool, safe_str, get_commit_safe, sha1_safe,
63 time_to_datetime, aslist, Optional, safe_int, get_clone_url, AttributeDict,
63 time_to_datetime, aslist, Optional, safe_int, get_clone_url, AttributeDict,
64 glob2re, StrictAttributeDict, cleaned_uri, datetime_to_time)
64 glob2re, StrictAttributeDict, cleaned_uri, datetime_to_time)
65 from rhodecode.lib.jsonalchemy import (
65 from rhodecode.lib.jsonalchemy import (
66 MutationObj, MutationList, JsonType, JsonRaw)
66 MutationObj, MutationList, JsonType, JsonRaw)
67 from rhodecode.lib.hash_utils import sha1
67 from rhodecode.lib.hash_utils import sha1
68 from rhodecode.lib import ext_json
68 from rhodecode.lib import ext_json
69 from rhodecode.lib import enc_utils
69 from rhodecode.lib import enc_utils
70 from rhodecode.lib.ext_json import json, str_json
70 from rhodecode.lib.ext_json import json, str_json
71 from rhodecode.lib.caching_query import FromCache
71 from rhodecode.lib.caching_query import FromCache
72 from rhodecode.lib.exceptions import (
72 from rhodecode.lib.exceptions import (
73 ArtifactMetadataDuplicate, ArtifactMetadataBadValueType)
73 ArtifactMetadataDuplicate, ArtifactMetadataBadValueType)
74 from rhodecode.model.meta import Base, Session
74 from rhodecode.model.meta import Base, Session
75
75
76 URL_SEP = '/'
76 URL_SEP = '/'
77 log = logging.getLogger(__name__)
77 log = logging.getLogger(__name__)
78
78
79 # =============================================================================
79 # =============================================================================
80 # BASE CLASSES
80 # BASE CLASSES
81 # =============================================================================
81 # =============================================================================
82
82
83 # this is propagated from .ini file rhodecode.encrypted_values.secret or
83 # this is propagated from .ini file rhodecode.encrypted_values.secret or
84 # beaker.session.secret if first is not set.
84 # beaker.session.secret if first is not set.
85 # and initialized at environment.py
85 # and initialized at environment.py
86 ENCRYPTION_KEY: bytes = b''
86 ENCRYPTION_KEY: bytes = b''
87
87
88 # used to sort permissions by types, '#' used here is not allowed to be in
88 # used to sort permissions by types, '#' used here is not allowed to be in
89 # usernames, and it's very early in sorted string.printable table.
89 # usernames, and it's very early in sorted string.printable table.
90 PERMISSION_TYPE_SORT = {
90 PERMISSION_TYPE_SORT = {
91 'admin': '####',
91 'admin': '####',
92 'write': '###',
92 'write': '###',
93 'read': '##',
93 'read': '##',
94 'none': '#',
94 'none': '#',
95 }
95 }
96
96
97
97
98 def display_user_sort(obj):
98 def display_user_sort(obj):
99 """
99 """
100 Sort function used to sort permissions in .permissions() function of
100 Sort function used to sort permissions in .permissions() function of
101 Repository, RepoGroup, UserGroup. Also it put the default user in front
101 Repository, RepoGroup, UserGroup. Also it put the default user in front
102 of all other resources
102 of all other resources
103 """
103 """
104
104
105 if obj.username == User.DEFAULT_USER:
105 if obj.username == User.DEFAULT_USER:
106 return '#####'
106 return '#####'
107 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
107 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
108 extra_sort_num = '1' # default
108 extra_sort_num = '1' # default
109
109
110 # NOTE(dan): inactive duplicates goes last
110 # NOTE(dan): inactive duplicates goes last
111 if getattr(obj, 'duplicate_perm', None):
111 if getattr(obj, 'duplicate_perm', None):
112 extra_sort_num = '9'
112 extra_sort_num = '9'
113 return prefix + extra_sort_num + obj.username
113 return prefix + extra_sort_num + obj.username
114
114
115
115
116 def display_user_group_sort(obj):
116 def display_user_group_sort(obj):
117 """
117 """
118 Sort function used to sort permissions in .permissions() function of
118 Sort function used to sort permissions in .permissions() function of
119 Repository, RepoGroup, UserGroup. Also it put the default user in front
119 Repository, RepoGroup, UserGroup. Also it put the default user in front
120 of all other resources
120 of all other resources
121 """
121 """
122
122
123 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
123 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
124 return prefix + obj.users_group_name
124 return prefix + obj.users_group_name
125
125
126
126
127 def _hash_key(k):
127 def _hash_key(k):
128 return sha1_safe(k)
128 return sha1_safe(k)
129
129
130
130
131 def in_filter_generator(qry, items, limit=500):
131 def in_filter_generator(qry, items, limit=500):
132 """
132 """
133 Splits IN() into multiple with OR
133 Splits IN() into multiple with OR
134 e.g.::
134 e.g.::
135 cnt = Repository.query().filter(
135 cnt = Repository.query().filter(
136 or_(
136 or_(
137 *in_filter_generator(Repository.repo_id, range(100000))
137 *in_filter_generator(Repository.repo_id, range(100000))
138 )).count()
138 )).count()
139 """
139 """
140 if not items:
140 if not items:
141 # empty list will cause empty query which might cause security issues
141 # empty list will cause empty query which might cause security issues
142 # this can lead to hidden unpleasant results
142 # this can lead to hidden unpleasant results
143 items = [-1]
143 items = [-1]
144
144
145 parts = []
145 parts = []
146 for chunk in range(0, len(items), limit):
146 for chunk in range(0, len(items), limit):
147 parts.append(
147 parts.append(
148 qry.in_(items[chunk: chunk + limit])
148 qry.in_(items[chunk: chunk + limit])
149 )
149 )
150
150
151 return parts
151 return parts
152
152
153
153
154 base_table_args = {
154 base_table_args = {
155 'extend_existing': True,
155 'extend_existing': True,
156 'mysql_engine': 'InnoDB',
156 'mysql_engine': 'InnoDB',
157 'mysql_charset': 'utf8',
157 'mysql_charset': 'utf8',
158 'sqlite_autoincrement': True
158 'sqlite_autoincrement': True
159 }
159 }
160
160
161
161
162 class EncryptedTextValue(TypeDecorator):
162 class EncryptedTextValue(TypeDecorator):
163 """
163 """
164 Special column for encrypted long text data, use like::
164 Special column for encrypted long text data, use like::
165
165
166 value = Column("encrypted_value", EncryptedValue(), nullable=False)
166 value = Column("encrypted_value", EncryptedValue(), nullable=False)
167
167
168 This column is intelligent so if value is in unencrypted form it return
168 This column is intelligent so if value is in unencrypted form it return
169 unencrypted form, but on save it always encrypts
169 unencrypted form, but on save it always encrypts
170 """
170 """
171 cache_ok = True
171 cache_ok = True
172 impl = Text
172 impl = Text
173
173
174 def process_bind_param(self, value, dialect):
174 def process_bind_param(self, value, dialect):
175 """
175 """
176 Setter for storing value
176 Setter for storing value
177 """
177 """
178 import rhodecode
178 import rhodecode
179 if not value:
179 if not value:
180 return value
180 return value
181
181
182 # protect against double encrypting if values is already encrypted
182 # protect against double encrypting if values is already encrypted
183 if value.startswith('enc$aes$') \
183 if value.startswith('enc$aes$') \
184 or value.startswith('enc$aes_hmac$') \
184 or value.startswith('enc$aes_hmac$') \
185 or value.startswith('enc2$'):
185 or value.startswith('enc2$'):
186 raise ValueError('value needs to be in unencrypted format, '
186 raise ValueError('value needs to be in unencrypted format, '
187 'ie. not starting with enc$ or enc2$')
187 'ie. not starting with enc$ or enc2$')
188
188
189 algo = rhodecode.CONFIG.get('rhodecode.encrypted_values.algorithm') or 'aes'
189 algo = rhodecode.CONFIG.get('rhodecode.encrypted_values.algorithm') or 'aes'
190 bytes_val = enc_utils.encrypt_value(value, enc_key=ENCRYPTION_KEY, algo=algo)
190 bytes_val = enc_utils.encrypt_value(value, enc_key=ENCRYPTION_KEY, algo=algo)
191 return safe_str(bytes_val)
191 return safe_str(bytes_val)
192
192
193 def process_result_value(self, value, dialect):
193 def process_result_value(self, value, dialect):
194 """
194 """
195 Getter for retrieving value
195 Getter for retrieving value
196 """
196 """
197
197
198 import rhodecode
198 import rhodecode
199 if not value:
199 if not value:
200 return value
200 return value
201
201
202 bytes_val = enc_utils.decrypt_value(value, enc_key=ENCRYPTION_KEY)
202 bytes_val = enc_utils.decrypt_value(value, enc_key=ENCRYPTION_KEY)
203
203
204 return safe_str(bytes_val)
204 return safe_str(bytes_val)
205
205
206
206
207 class BaseModel(object):
207 class BaseModel(object):
208 """
208 """
209 Base Model for all classes
209 Base Model for all classes
210 """
210 """
211
211
212 @classmethod
212 @classmethod
213 def _get_keys(cls):
213 def _get_keys(cls):
214 """return column names for this model """
214 """return column names for this model """
215 return class_mapper(cls).c.keys()
215 return class_mapper(cls).c.keys()
216
216
217 def get_dict(self):
217 def get_dict(self):
218 """
218 """
219 return dict with keys and values corresponding
219 return dict with keys and values corresponding
220 to this model data """
220 to this model data """
221
221
222 d = {}
222 d = {}
223 for k in self._get_keys():
223 for k in self._get_keys():
224 d[k] = getattr(self, k)
224 d[k] = getattr(self, k)
225
225
226 # also use __json__() if present to get additional fields
226 # also use __json__() if present to get additional fields
227 _json_attr = getattr(self, '__json__', None)
227 _json_attr = getattr(self, '__json__', None)
228 if _json_attr:
228 if _json_attr:
229 # update with attributes from __json__
229 # update with attributes from __json__
230 if callable(_json_attr):
230 if callable(_json_attr):
231 _json_attr = _json_attr()
231 _json_attr = _json_attr()
232 for k, val in _json_attr.items():
232 for k, val in _json_attr.items():
233 d[k] = val
233 d[k] = val
234 return d
234 return d
235
235
236 def get_appstruct(self):
236 def get_appstruct(self):
237 """return list with keys and values tuples corresponding
237 """return list with keys and values tuples corresponding
238 to this model data """
238 to this model data """
239
239
240 lst = []
240 lst = []
241 for k in self._get_keys():
241 for k in self._get_keys():
242 lst.append((k, getattr(self, k),))
242 lst.append((k, getattr(self, k),))
243 return lst
243 return lst
244
244
245 def populate_obj(self, populate_dict):
245 def populate_obj(self, populate_dict):
246 """populate model with data from given populate_dict"""
246 """populate model with data from given populate_dict"""
247
247
248 for k in self._get_keys():
248 for k in self._get_keys():
249 if k in populate_dict:
249 if k in populate_dict:
250 setattr(self, k, populate_dict[k])
250 setattr(self, k, populate_dict[k])
251
251
252 @classmethod
252 @classmethod
253 def query(cls):
253 def query(cls):
254 return Session().query(cls)
254 return Session().query(cls)
255
255
256 @classmethod
256 @classmethod
257 def select(cls, custom_cls=None):
257 def select(cls, custom_cls=None):
258 """
258 """
259 stmt = cls.select().where(cls.user_id==1)
259 stmt = cls.select().where(cls.user_id==1)
260 # optionally
260 # optionally
261 stmt = cls.select(User.user_id).where(cls.user_id==1)
261 stmt = cls.select(User.user_id).where(cls.user_id==1)
262 result = cls.execute(stmt) | cls.scalars(stmt)
262 result = cls.execute(stmt) | cls.scalars(stmt)
263 """
263 """
264
264
265 if custom_cls:
265 if custom_cls:
266 stmt = select(custom_cls)
266 stmt = select(custom_cls)
267 else:
267 else:
268 stmt = select(cls)
268 stmt = select(cls)
269 return stmt
269 return stmt
270
270
271 @classmethod
271 @classmethod
272 def execute(cls, stmt):
272 def execute(cls, stmt):
273 return Session().execute(stmt)
273 return Session().execute(stmt)
274
274
275 @classmethod
275 @classmethod
276 def scalars(cls, stmt):
276 def scalars(cls, stmt):
277 return Session().scalars(stmt)
277 return Session().scalars(stmt)
278
278
279 @classmethod
279 @classmethod
280 def get(cls, id_):
280 def get(cls, id_):
281 if id_:
281 if id_:
282 return cls.query().get(id_)
282 return cls.query().get(id_)
283
283
284 @classmethod
284 @classmethod
285 def get_or_404(cls, id_):
285 def get_or_404(cls, id_):
286 from pyramid.httpexceptions import HTTPNotFound
286 from pyramid.httpexceptions import HTTPNotFound
287
287
288 try:
288 try:
289 id_ = int(id_)
289 id_ = int(id_)
290 except (TypeError, ValueError):
290 except (TypeError, ValueError):
291 raise HTTPNotFound()
291 raise HTTPNotFound()
292
292
293 res = cls.query().get(id_)
293 res = cls.query().get(id_)
294 if not res:
294 if not res:
295 raise HTTPNotFound()
295 raise HTTPNotFound()
296 return res
296 return res
297
297
298 @classmethod
298 @classmethod
299 def getAll(cls):
299 def getAll(cls):
300 # deprecated and left for backward compatibility
300 # deprecated and left for backward compatibility
301 return cls.get_all()
301 return cls.get_all()
302
302
303 @classmethod
303 @classmethod
304 def get_all(cls):
304 def get_all(cls):
305 return cls.query().all()
305 return cls.query().all()
306
306
307 @classmethod
307 @classmethod
308 def delete(cls, id_):
308 def delete(cls, id_):
309 obj = cls.query().get(id_)
309 obj = cls.query().get(id_)
310 Session().delete(obj)
310 Session().delete(obj)
311
311
312 @classmethod
312 @classmethod
313 def identity_cache(cls, session, attr_name, value):
313 def identity_cache(cls, session, attr_name, value):
314 exist_in_session = []
314 exist_in_session = []
315 for (item_cls, pkey), instance in session.identity_map.items():
315 for (item_cls, pkey), instance in session.identity_map.items():
316 if cls == item_cls and getattr(instance, attr_name) == value:
316 if cls == item_cls and getattr(instance, attr_name) == value:
317 exist_in_session.append(instance)
317 exist_in_session.append(instance)
318 if exist_in_session:
318 if exist_in_session:
319 if len(exist_in_session) == 1:
319 if len(exist_in_session) == 1:
320 return exist_in_session[0]
320 return exist_in_session[0]
321 log.exception(
321 log.exception(
322 'multiple objects with attr %s and '
322 'multiple objects with attr %s and '
323 'value %s found with same name: %r',
323 'value %s found with same name: %r',
324 attr_name, value, exist_in_session)
324 attr_name, value, exist_in_session)
325
325
326 @property
326 @property
327 def cls_name(self):
327 def cls_name(self):
328 return self.__class__.__name__
328 return self.__class__.__name__
329
329
330 def __repr__(self):
330 def __repr__(self):
331 return f'<DB:{self.cls_name}>'
331 return f'<DB:{self.cls_name}>'
332
332
333
333
334 class RhodeCodeSetting(Base, BaseModel):
334 class RhodeCodeSetting(Base, BaseModel):
335 __tablename__ = 'rhodecode_settings'
335 __tablename__ = 'rhodecode_settings'
336 __table_args__ = (
336 __table_args__ = (
337 UniqueConstraint('app_settings_name'),
337 UniqueConstraint('app_settings_name'),
338 base_table_args
338 base_table_args
339 )
339 )
340
340
341 SETTINGS_TYPES = {
341 SETTINGS_TYPES = {
342 'str': safe_str,
342 'str': safe_str,
343 'int': safe_int,
343 'int': safe_int,
344 'unicode': safe_str,
344 'unicode': safe_str,
345 'bool': str2bool,
345 'bool': str2bool,
346 'list': functools.partial(aslist, sep=',')
346 'list': functools.partial(aslist, sep=',')
347 }
347 }
348 DEFAULT_UPDATE_URL = 'https://rhodecode.com/api/v1/info/versions'
348 DEFAULT_UPDATE_URL = 'https://rhodecode.com/api/v1/info/versions'
349 GLOBAL_CONF_KEY = 'app_settings'
349 GLOBAL_CONF_KEY = 'app_settings'
350
350
351 app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
351 app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
352 app_settings_name = Column("app_settings_name", String(255), nullable=True, unique=None, default=None)
352 app_settings_name = Column("app_settings_name", String(255), nullable=True, unique=None, default=None)
353 _app_settings_value = Column("app_settings_value", String(4096), nullable=True, unique=None, default=None)
353 _app_settings_value = Column("app_settings_value", String(4096), nullable=True, unique=None, default=None)
354 _app_settings_type = Column("app_settings_type", String(255), nullable=True, unique=None, default=None)
354 _app_settings_type = Column("app_settings_type", String(255), nullable=True, unique=None, default=None)
355
355
356 def __init__(self, key='', val='', type='unicode'):
356 def __init__(self, key='', val='', type='unicode'):
357 self.app_settings_name = key
357 self.app_settings_name = key
358 self.app_settings_type = type
358 self.app_settings_type = type
359 self.app_settings_value = val
359 self.app_settings_value = val
360
360
361 @validates('_app_settings_value')
361 @validates('_app_settings_value')
362 def validate_settings_value(self, key, val):
362 def validate_settings_value(self, key, val):
363 assert type(val) == str
363 assert type(val) == str
364 return val
364 return val
365
365
366 @hybrid_property
366 @hybrid_property
367 def app_settings_value(self):
367 def app_settings_value(self):
368 v = self._app_settings_value
368 v = self._app_settings_value
369 _type = self.app_settings_type
369 _type = self.app_settings_type
370 if _type:
370 if _type:
371 _type = self.app_settings_type.split('.')[0]
371 _type = self.app_settings_type.split('.')[0]
372 # decode the encrypted value
372 # decode the encrypted value
373 if 'encrypted' in self.app_settings_type:
373 if 'encrypted' in self.app_settings_type:
374 cipher = EncryptedTextValue()
374 cipher = EncryptedTextValue()
375 v = safe_str(cipher.process_result_value(v, None))
375 v = safe_str(cipher.process_result_value(v, None))
376
376
377 converter = self.SETTINGS_TYPES.get(_type) or \
377 converter = self.SETTINGS_TYPES.get(_type) or \
378 self.SETTINGS_TYPES['unicode']
378 self.SETTINGS_TYPES['unicode']
379 return converter(v)
379 return converter(v)
380
380
381 @app_settings_value.setter
381 @app_settings_value.setter
382 def app_settings_value(self, val):
382 def app_settings_value(self, val):
383 """
383 """
384 Setter that will always make sure we use unicode in app_settings_value
384 Setter that will always make sure we use unicode in app_settings_value
385
385
386 :param val:
386 :param val:
387 """
387 """
388 val = safe_str(val)
388 val = safe_str(val)
389 # encode the encrypted value
389 # encode the encrypted value
390 if 'encrypted' in self.app_settings_type:
390 if 'encrypted' in self.app_settings_type:
391 cipher = EncryptedTextValue()
391 cipher = EncryptedTextValue()
392 val = safe_str(cipher.process_bind_param(val, None))
392 val = safe_str(cipher.process_bind_param(val, None))
393 self._app_settings_value = val
393 self._app_settings_value = val
394
394
395 @hybrid_property
395 @hybrid_property
396 def app_settings_type(self):
396 def app_settings_type(self):
397 return self._app_settings_type
397 return self._app_settings_type
398
398
399 @app_settings_type.setter
399 @app_settings_type.setter
400 def app_settings_type(self, val):
400 def app_settings_type(self, val):
401 if val.split('.')[0] not in self.SETTINGS_TYPES:
401 if val.split('.')[0] not in self.SETTINGS_TYPES:
402 raise Exception('type must be one of %s got %s'
402 raise Exception('type must be one of %s got %s'
403 % (self.SETTINGS_TYPES.keys(), val))
403 % (self.SETTINGS_TYPES.keys(), val))
404 self._app_settings_type = val
404 self._app_settings_type = val
405
405
406 @classmethod
406 @classmethod
407 def get_by_prefix(cls, prefix):
407 def get_by_prefix(cls, prefix):
408 return RhodeCodeSetting.query()\
408 return RhodeCodeSetting.query()\
409 .filter(RhodeCodeSetting.app_settings_name.startswith(prefix))\
409 .filter(RhodeCodeSetting.app_settings_name.startswith(prefix))\
410 .all()
410 .all()
411
411
412 def __repr__(self):
412 def __repr__(self):
413 return "<%s('%s:%s[%s]')>" % (
413 return "<%s('%s:%s[%s]')>" % (
414 self.cls_name,
414 self.cls_name,
415 self.app_settings_name, self.app_settings_value,
415 self.app_settings_name, self.app_settings_value,
416 self.app_settings_type
416 self.app_settings_type
417 )
417 )
418
418
419
419
420 class RhodeCodeUi(Base, BaseModel):
420 class RhodeCodeUi(Base, BaseModel):
421 __tablename__ = 'rhodecode_ui'
421 __tablename__ = 'rhodecode_ui'
422 __table_args__ = (
422 __table_args__ = (
423 UniqueConstraint('ui_key'),
423 UniqueConstraint('ui_key'),
424 base_table_args
424 base_table_args
425 )
425 )
426 # Sync those values with vcsserver.config.hooks
426 # Sync those values with vcsserver.config.hooks
427
427
428 HOOK_REPO_SIZE = 'changegroup.repo_size'
428 HOOK_REPO_SIZE = 'changegroup.repo_size'
429 # HG
429 # HG
430 HOOK_PRE_PULL = 'preoutgoing.pre_pull'
430 HOOK_PRE_PULL = 'preoutgoing.pre_pull'
431 HOOK_PULL = 'outgoing.pull_logger'
431 HOOK_PULL = 'outgoing.pull_logger'
432 HOOK_PRE_PUSH = 'prechangegroup.pre_push'
432 HOOK_PRE_PUSH = 'prechangegroup.pre_push'
433 HOOK_PRETX_PUSH = 'pretxnchangegroup.pre_push'
433 HOOK_PRETX_PUSH = 'pretxnchangegroup.pre_push'
434 HOOK_PUSH = 'changegroup.push_logger'
434 HOOK_PUSH = 'changegroup.push_logger'
435 HOOK_PUSH_KEY = 'pushkey.key_push'
435 HOOK_PUSH_KEY = 'pushkey.key_push'
436
436
437 HOOKS_BUILTIN = [
437 HOOKS_BUILTIN = [
438 HOOK_PRE_PULL,
438 HOOK_PRE_PULL,
439 HOOK_PULL,
439 HOOK_PULL,
440 HOOK_PRE_PUSH,
440 HOOK_PRE_PUSH,
441 HOOK_PRETX_PUSH,
441 HOOK_PRETX_PUSH,
442 HOOK_PUSH,
442 HOOK_PUSH,
443 HOOK_PUSH_KEY,
443 HOOK_PUSH_KEY,
444 ]
444 ]
445
445
446 # TODO: johbo: Unify way how hooks are configured for git and hg,
446 # TODO: johbo: Unify way how hooks are configured for git and hg,
447 # git part is currently hardcoded.
447 # git part is currently hardcoded.
448
448
449 # SVN PATTERNS
449 # SVN PATTERNS
450 SVN_BRANCH_ID = 'vcs_svn_branch'
450 SVN_BRANCH_ID = 'vcs_svn_branch'
451 SVN_TAG_ID = 'vcs_svn_tag'
451 SVN_TAG_ID = 'vcs_svn_tag'
452
452
453 ui_id = Column(
453 ui_id = Column(
454 "ui_id", Integer(), nullable=False, unique=True, default=None,
454 "ui_id", Integer(), nullable=False, unique=True, default=None,
455 primary_key=True)
455 primary_key=True)
456 ui_section = Column(
456 ui_section = Column(
457 "ui_section", String(255), nullable=True, unique=None, default=None)
457 "ui_section", String(255), nullable=True, unique=None, default=None)
458 ui_key = Column(
458 ui_key = Column(
459 "ui_key", String(255), nullable=True, unique=None, default=None)
459 "ui_key", String(255), nullable=True, unique=None, default=None)
460 ui_value = Column(
460 ui_value = Column(
461 "ui_value", String(255), nullable=True, unique=None, default=None)
461 "ui_value", String(255), nullable=True, unique=None, default=None)
462 ui_active = Column(
462 ui_active = Column(
463 "ui_active", Boolean(), nullable=True, unique=None, default=True)
463 "ui_active", Boolean(), nullable=True, unique=None, default=True)
464
464
465 def __repr__(self):
465 def __repr__(self):
466 return '<%s[%s]%s=>%s]>' % (self.cls_name, self.ui_section,
466 return '<%s[%s]%s=>%s]>' % (self.cls_name, self.ui_section,
467 self.ui_key, self.ui_value)
467 self.ui_key, self.ui_value)
468
468
469
469
470 class RepoRhodeCodeSetting(Base, BaseModel):
470 class RepoRhodeCodeSetting(Base, BaseModel):
471 __tablename__ = 'repo_rhodecode_settings'
471 __tablename__ = 'repo_rhodecode_settings'
472 __table_args__ = (
472 __table_args__ = (
473 UniqueConstraint(
473 UniqueConstraint(
474 'app_settings_name', 'repository_id',
474 'app_settings_name', 'repository_id',
475 name='uq_repo_rhodecode_setting_name_repo_id'),
475 name='uq_repo_rhodecode_setting_name_repo_id'),
476 base_table_args
476 base_table_args
477 )
477 )
478
478
479 repository_id = Column(
479 repository_id = Column(
480 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
480 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
481 nullable=False)
481 nullable=False)
482 app_settings_id = Column(
482 app_settings_id = Column(
483 "app_settings_id", Integer(), nullable=False, unique=True,
483 "app_settings_id", Integer(), nullable=False, unique=True,
484 default=None, primary_key=True)
484 default=None, primary_key=True)
485 app_settings_name = Column(
485 app_settings_name = Column(
486 "app_settings_name", String(255), nullable=True, unique=None,
486 "app_settings_name", String(255), nullable=True, unique=None,
487 default=None)
487 default=None)
488 _app_settings_value = Column(
488 _app_settings_value = Column(
489 "app_settings_value", String(4096), nullable=True, unique=None,
489 "app_settings_value", String(4096), nullable=True, unique=None,
490 default=None)
490 default=None)
491 _app_settings_type = Column(
491 _app_settings_type = Column(
492 "app_settings_type", String(255), nullable=True, unique=None,
492 "app_settings_type", String(255), nullable=True, unique=None,
493 default=None)
493 default=None)
494
494
495 repository = relationship('Repository', viewonly=True)
495 repository = relationship('Repository', viewonly=True)
496
496
497 def __init__(self, repository_id, key='', val='', type='unicode'):
497 def __init__(self, repository_id, key='', val='', type='unicode'):
498 self.repository_id = repository_id
498 self.repository_id = repository_id
499 self.app_settings_name = key
499 self.app_settings_name = key
500 self.app_settings_type = type
500 self.app_settings_type = type
501 self.app_settings_value = val
501 self.app_settings_value = val
502
502
503 @validates('_app_settings_value')
503 @validates('_app_settings_value')
504 def validate_settings_value(self, key, val):
504 def validate_settings_value(self, key, val):
505 assert type(val) == str
505 assert type(val) == str
506 return val
506 return val
507
507
508 @hybrid_property
508 @hybrid_property
509 def app_settings_value(self):
509 def app_settings_value(self):
510 v = self._app_settings_value
510 v = self._app_settings_value
511 type_ = self.app_settings_type
511 type_ = self.app_settings_type
512 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
512 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
513 converter = SETTINGS_TYPES.get(type_) or SETTINGS_TYPES['unicode']
513 converter = SETTINGS_TYPES.get(type_) or SETTINGS_TYPES['unicode']
514 return converter(v)
514 return converter(v)
515
515
516 @app_settings_value.setter
516 @app_settings_value.setter
517 def app_settings_value(self, val):
517 def app_settings_value(self, val):
518 """
518 """
519 Setter that will always make sure we use unicode in app_settings_value
519 Setter that will always make sure we use unicode in app_settings_value
520
520
521 :param val:
521 :param val:
522 """
522 """
523 self._app_settings_value = safe_str(val)
523 self._app_settings_value = safe_str(val)
524
524
525 @hybrid_property
525 @hybrid_property
526 def app_settings_type(self):
526 def app_settings_type(self):
527 return self._app_settings_type
527 return self._app_settings_type
528
528
529 @app_settings_type.setter
529 @app_settings_type.setter
530 def app_settings_type(self, val):
530 def app_settings_type(self, val):
531 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
531 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
532 if val not in SETTINGS_TYPES:
532 if val not in SETTINGS_TYPES:
533 raise Exception('type must be one of %s got %s'
533 raise Exception('type must be one of %s got %s'
534 % (SETTINGS_TYPES.keys(), val))
534 % (SETTINGS_TYPES.keys(), val))
535 self._app_settings_type = val
535 self._app_settings_type = val
536
536
537 def __repr__(self):
537 def __repr__(self):
538 return "<%s('%s:%s:%s[%s]')>" % (
538 return "<%s('%s:%s:%s[%s]')>" % (
539 self.cls_name, self.repository.repo_name,
539 self.cls_name, self.repository.repo_name,
540 self.app_settings_name, self.app_settings_value,
540 self.app_settings_name, self.app_settings_value,
541 self.app_settings_type
541 self.app_settings_type
542 )
542 )
543
543
544
544
545 class RepoRhodeCodeUi(Base, BaseModel):
545 class RepoRhodeCodeUi(Base, BaseModel):
546 __tablename__ = 'repo_rhodecode_ui'
546 __tablename__ = 'repo_rhodecode_ui'
547 __table_args__ = (
547 __table_args__ = (
548 UniqueConstraint(
548 UniqueConstraint(
549 'repository_id', 'ui_section', 'ui_key',
549 'repository_id', 'ui_section', 'ui_key',
550 name='uq_repo_rhodecode_ui_repository_id_section_key'),
550 name='uq_repo_rhodecode_ui_repository_id_section_key'),
551 base_table_args
551 base_table_args
552 )
552 )
553
553
554 repository_id = Column(
554 repository_id = Column(
555 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
555 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
556 nullable=False)
556 nullable=False)
557 ui_id = Column(
557 ui_id = Column(
558 "ui_id", Integer(), nullable=False, unique=True, default=None,
558 "ui_id", Integer(), nullable=False, unique=True, default=None,
559 primary_key=True)
559 primary_key=True)
560 ui_section = Column(
560 ui_section = Column(
561 "ui_section", String(255), nullable=True, unique=None, default=None)
561 "ui_section", String(255), nullable=True, unique=None, default=None)
562 ui_key = Column(
562 ui_key = Column(
563 "ui_key", String(255), nullable=True, unique=None, default=None)
563 "ui_key", String(255), nullable=True, unique=None, default=None)
564 ui_value = Column(
564 ui_value = Column(
565 "ui_value", String(255), nullable=True, unique=None, default=None)
565 "ui_value", String(255), nullable=True, unique=None, default=None)
566 ui_active = Column(
566 ui_active = Column(
567 "ui_active", Boolean(), nullable=True, unique=None, default=True)
567 "ui_active", Boolean(), nullable=True, unique=None, default=True)
568
568
569 repository = relationship('Repository', viewonly=True)
569 repository = relationship('Repository', viewonly=True)
570
570
571 def __repr__(self):
571 def __repr__(self):
572 return '<%s[%s:%s]%s=>%s]>' % (
572 return '<%s[%s:%s]%s=>%s]>' % (
573 self.cls_name, self.repository.repo_name,
573 self.cls_name, self.repository.repo_name,
574 self.ui_section, self.ui_key, self.ui_value)
574 self.ui_section, self.ui_key, self.ui_value)
575
575
576
576
577 class User(Base, BaseModel):
577 class User(Base, BaseModel):
578 __tablename__ = 'users'
578 __tablename__ = 'users'
579 __table_args__ = (
579 __table_args__ = (
580 UniqueConstraint('username'), UniqueConstraint('email'),
580 UniqueConstraint('username'), UniqueConstraint('email'),
581 Index('u_username_idx', 'username'),
581 Index('u_username_idx', 'username'),
582 Index('u_email_idx', 'email'),
582 Index('u_email_idx', 'email'),
583 base_table_args
583 base_table_args
584 )
584 )
585
585
586 DEFAULT_USER = 'default'
586 DEFAULT_USER = 'default'
587 DEFAULT_USER_EMAIL = 'anonymous@rhodecode.org'
587 DEFAULT_USER_EMAIL = 'anonymous@rhodecode.org'
588 DEFAULT_GRAVATAR_URL = 'https://secure.gravatar.com/avatar/{md5email}?d=identicon&s={size}'
588 DEFAULT_GRAVATAR_URL = 'https://secure.gravatar.com/avatar/{md5email}?d=identicon&s={size}'
589 RECOVERY_CODES_COUNT = 10
589 RECOVERY_CODES_COUNT = 10
590
590
591 user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
591 user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
592 username = Column("username", String(255), nullable=True, unique=None, default=None)
592 username = Column("username", String(255), nullable=True, unique=None, default=None)
593 password = Column("password", String(255), nullable=True, unique=None, default=None)
593 password = Column("password", String(255), nullable=True, unique=None, default=None)
594 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
594 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
595 admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
595 admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
596 name = Column("firstname", String(255), nullable=True, unique=None, default=None)
596 name = Column("firstname", String(255), nullable=True, unique=None, default=None)
597 lastname = Column("lastname", String(255), nullable=True, unique=None, default=None)
597 lastname = Column("lastname", String(255), nullable=True, unique=None, default=None)
598 _email = Column("email", String(255), nullable=True, unique=None, default=None)
598 _email = Column("email", String(255), nullable=True, unique=None, default=None)
599 last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
599 last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
600 last_activity = Column('last_activity', DateTime(timezone=False), nullable=True, unique=None, default=None)
600 last_activity = Column('last_activity', DateTime(timezone=False), nullable=True, unique=None, default=None)
601 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
601 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
602
602
603 extern_type = Column("extern_type", String(255), nullable=True, unique=None, default=None)
603 extern_type = Column("extern_type", String(255), nullable=True, unique=None, default=None)
604 extern_name = Column("extern_name", String(255), nullable=True, unique=None, default=None)
604 extern_name = Column("extern_name", String(255), nullable=True, unique=None, default=None)
605 _api_key = Column("api_key", String(255), nullable=True, unique=None, default=None)
605 _api_key = Column("api_key", String(255), nullable=True, unique=None, default=None)
606 inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
606 inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
607 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
607 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
608 _user_data = Column("user_data", LargeBinary(), nullable=True) # JSON data
608 _user_data = Column("user_data", LargeBinary(), nullable=True) # JSON data
609
609
610 user_log = relationship('UserLog', back_populates='user')
610 user_log = relationship('UserLog', back_populates='user')
611 user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all, delete-orphan')
611 user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all, delete-orphan')
612
612
613 repositories = relationship('Repository', back_populates='user')
613 repositories = relationship('Repository', back_populates='user')
614 repository_groups = relationship('RepoGroup', back_populates='user')
614 repository_groups = relationship('RepoGroup', back_populates='user')
615 user_groups = relationship('UserGroup', back_populates='user')
615 user_groups = relationship('UserGroup', back_populates='user')
616
616
617 user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all', back_populates='follows_user')
617 user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all', back_populates='follows_user')
618 followings = relationship('UserFollowing', primaryjoin='UserFollowing.user_id==User.user_id', cascade='all', back_populates='user')
618 followings = relationship('UserFollowing', primaryjoin='UserFollowing.user_id==User.user_id', cascade='all', back_populates='user')
619
619
620 repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all, delete-orphan')
620 repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all, delete-orphan')
621 repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all, delete-orphan', back_populates='user')
621 repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all, delete-orphan', back_populates='user')
622 user_group_to_perm = relationship('UserUserGroupToPerm', primaryjoin='UserUserGroupToPerm.user_id==User.user_id', cascade='all, delete-orphan', back_populates='user')
622 user_group_to_perm = relationship('UserUserGroupToPerm', primaryjoin='UserUserGroupToPerm.user_id==User.user_id', cascade='all, delete-orphan', back_populates='user')
623
623
624 group_member = relationship('UserGroupMember', cascade='all', back_populates='user')
624 group_member = relationship('UserGroupMember', cascade='all', back_populates='user')
625
625
626 notifications = relationship('UserNotification', cascade='all', back_populates='user')
626 notifications = relationship('UserNotification', cascade='all', back_populates='user')
627 # notifications assigned to this user
627 # notifications assigned to this user
628 user_created_notifications = relationship('Notification', cascade='all', back_populates='created_by_user')
628 user_created_notifications = relationship('Notification', cascade='all', back_populates='created_by_user')
629 # comments created by this user
629 # comments created by this user
630 user_comments = relationship('ChangesetComment', cascade='all', back_populates='author')
630 user_comments = relationship('ChangesetComment', cascade='all', back_populates='author')
631 # user profile extra info
631 # user profile extra info
632 user_emails = relationship('UserEmailMap', cascade='all', back_populates='user')
632 user_emails = relationship('UserEmailMap', cascade='all', back_populates='user')
633 user_ip_map = relationship('UserIpMap', cascade='all', back_populates='user')
633 user_ip_map = relationship('UserIpMap', cascade='all', back_populates='user')
634 user_auth_tokens = relationship('UserApiKeys', cascade='all', back_populates='user')
634 user_auth_tokens = relationship('UserApiKeys', cascade='all', back_populates='user')
635 user_ssh_keys = relationship('UserSshKeys', cascade='all', back_populates='user')
635 user_ssh_keys = relationship('UserSshKeys', cascade='all', back_populates='user')
636
636
637 # gists
637 # gists
638 user_gists = relationship('Gist', cascade='all', back_populates='owner')
638 user_gists = relationship('Gist', cascade='all', back_populates='owner')
639 # user pull requests
639 # user pull requests
640 user_pull_requests = relationship('PullRequest', cascade='all', back_populates='author')
640 user_pull_requests = relationship('PullRequest', cascade='all', back_populates='author')
641
641
642 # external identities
642 # external identities
643 external_identities = relationship('ExternalIdentity', primaryjoin="User.user_id==ExternalIdentity.local_user_id", cascade='all')
643 external_identities = relationship('ExternalIdentity', primaryjoin="User.user_id==ExternalIdentity.local_user_id", cascade='all')
644 # review rules
644 # review rules
645 user_review_rules = relationship('RepoReviewRuleUser', cascade='all', back_populates='user')
645 user_review_rules = relationship('RepoReviewRuleUser', cascade='all', back_populates='user')
646
646
647 # artifacts owned
647 # artifacts owned
648 artifacts = relationship('FileStore', primaryjoin='FileStore.user_id==User.user_id', back_populates='upload_user')
648 artifacts = relationship('FileStore', primaryjoin='FileStore.user_id==User.user_id', back_populates='upload_user')
649
649
650 # no cascade, set NULL
650 # no cascade, set NULL
651 scope_artifacts = relationship('FileStore', primaryjoin='FileStore.scope_user_id==User.user_id', cascade='', back_populates='user')
651 scope_artifacts = relationship('FileStore', primaryjoin='FileStore.scope_user_id==User.user_id', cascade='', back_populates='user')
652
652
653 def __repr__(self):
653 def __repr__(self):
654 return f"<{self.cls_name}('id={self.user_id}, username={self.username}')>"
654 return f"<{self.cls_name}('id={self.user_id}, username={self.username}')>"
655
655
656 @hybrid_property
656 @hybrid_property
657 def email(self):
657 def email(self):
658 return self._email
658 return self._email
659
659
660 @email.setter
660 @email.setter
661 def email(self, val):
661 def email(self, val):
662 self._email = val.lower() if val else None
662 self._email = val.lower() if val else None
663
663
664 @hybrid_property
664 @hybrid_property
665 def first_name(self):
665 def first_name(self):
666 from rhodecode.lib import helpers as h
666 from rhodecode.lib import helpers as h
667 if self.name:
667 if self.name:
668 return h.escape(self.name)
668 return h.escape(self.name)
669 return self.name
669 return self.name
670
670
671 @hybrid_property
671 @hybrid_property
672 def last_name(self):
672 def last_name(self):
673 from rhodecode.lib import helpers as h
673 from rhodecode.lib import helpers as h
674 if self.lastname:
674 if self.lastname:
675 return h.escape(self.lastname)
675 return h.escape(self.lastname)
676 return self.lastname
676 return self.lastname
677
677
678 @hybrid_property
678 @hybrid_property
679 def api_key(self):
679 def api_key(self):
680 """
680 """
681 Fetch if exist an auth-token with role ALL connected to this user
681 Fetch if exist an auth-token with role ALL connected to this user
682 """
682 """
683 user_auth_token = UserApiKeys.query()\
683 user_auth_token = UserApiKeys.query()\
684 .filter(UserApiKeys.user_id == self.user_id)\
684 .filter(UserApiKeys.user_id == self.user_id)\
685 .filter(or_(UserApiKeys.expires == -1,
685 .filter(or_(UserApiKeys.expires == -1,
686 UserApiKeys.expires >= time.time()))\
686 UserApiKeys.expires >= time.time()))\
687 .filter(UserApiKeys.role == UserApiKeys.ROLE_ALL).first()
687 .filter(UserApiKeys.role == UserApiKeys.ROLE_ALL).first()
688 if user_auth_token:
688 if user_auth_token:
689 user_auth_token = user_auth_token.api_key
689 user_auth_token = user_auth_token.api_key
690
690
691 return user_auth_token
691 return user_auth_token
692
692
693 @api_key.setter
693 @api_key.setter
694 def api_key(self, val):
694 def api_key(self, val):
695 # don't allow to set API key this is deprecated for now
695 # don't allow to set API key this is deprecated for now
696 self._api_key = None
696 self._api_key = None
697
697
698 @property
698 @property
699 def reviewer_pull_requests(self):
699 def reviewer_pull_requests(self):
700 return PullRequestReviewers.query() \
700 return PullRequestReviewers.query() \
701 .options(joinedload(PullRequestReviewers.pull_request)) \
701 .options(joinedload(PullRequestReviewers.pull_request)) \
702 .filter(PullRequestReviewers.user_id == self.user_id) \
702 .filter(PullRequestReviewers.user_id == self.user_id) \
703 .all()
703 .all()
704
704
705 @property
705 @property
706 def firstname(self):
706 def firstname(self):
707 # alias for future
707 # alias for future
708 return self.name
708 return self.name
709
709
710 @property
710 @property
711 def emails(self):
711 def emails(self):
712 other = UserEmailMap.query()\
712 other = UserEmailMap.query()\
713 .filter(UserEmailMap.user == self) \
713 .filter(UserEmailMap.user == self) \
714 .order_by(UserEmailMap.email_id.asc()) \
714 .order_by(UserEmailMap.email_id.asc()) \
715 .all()
715 .all()
716 return [self.email] + [x.email for x in other]
716 return [self.email] + [x.email for x in other]
717
717
718 def emails_cached(self):
718 def emails_cached(self):
719 emails = []
719 emails = []
720 if self.user_id != self.get_default_user_id():
720 if self.user_id != self.get_default_user_id():
721 emails = UserEmailMap.query()\
721 emails = UserEmailMap.query()\
722 .filter(UserEmailMap.user == self) \
722 .filter(UserEmailMap.user == self) \
723 .order_by(UserEmailMap.email_id.asc())
723 .order_by(UserEmailMap.email_id.asc())
724
724
725 emails = emails.options(
725 emails = emails.options(
726 FromCache("sql_cache_short", f"get_user_{self.user_id}_emails")
726 FromCache("sql_cache_short", f"get_user_{self.user_id}_emails")
727 )
727 )
728
728
729 return [self.email] + [x.email for x in emails]
729 return [self.email] + [x.email for x in emails]
730
730
731 @property
731 @property
732 def auth_tokens(self):
732 def auth_tokens(self):
733 auth_tokens = self.get_auth_tokens()
733 auth_tokens = self.get_auth_tokens()
734 return [x.api_key for x in auth_tokens]
734 return [x.api_key for x in auth_tokens]
735
735
736 def get_auth_tokens(self):
736 def get_auth_tokens(self):
737 return UserApiKeys.query()\
737 return UserApiKeys.query()\
738 .filter(UserApiKeys.user == self)\
738 .filter(UserApiKeys.user == self)\
739 .order_by(UserApiKeys.user_api_key_id.asc())\
739 .order_by(UserApiKeys.user_api_key_id.asc())\
740 .all()
740 .all()
741
741
742 @LazyProperty
742 @LazyProperty
743 def feed_token(self):
743 def feed_token(self):
744 return self.get_feed_token()
744 return self.get_feed_token()
745
745
746 def get_feed_token(self, cache=True):
746 def get_feed_token(self, cache=True):
747 feed_tokens = UserApiKeys.query()\
747 feed_tokens = UserApiKeys.query()\
748 .filter(UserApiKeys.user == self)\
748 .filter(UserApiKeys.user == self)\
749 .filter(UserApiKeys.role == UserApiKeys.ROLE_FEED)
749 .filter(UserApiKeys.role == UserApiKeys.ROLE_FEED)
750 if cache:
750 if cache:
751 feed_tokens = feed_tokens.options(
751 feed_tokens = feed_tokens.options(
752 FromCache("sql_cache_short", f"get_user_feed_token_{self.user_id}"))
752 FromCache("sql_cache_short", f"get_user_feed_token_{self.user_id}"))
753
753
754 feed_tokens = feed_tokens.all()
754 feed_tokens = feed_tokens.all()
755 if feed_tokens:
755 if feed_tokens:
756 return feed_tokens[0].api_key
756 return feed_tokens[0].api_key
757 return 'NO_FEED_TOKEN_AVAILABLE'
757 return 'NO_FEED_TOKEN_AVAILABLE'
758
758
759 @LazyProperty
759 @LazyProperty
760 def artifact_token(self):
760 def artifact_token(self):
761 return self.get_artifact_token()
761 return self.get_artifact_token()
762
762
763 def get_artifact_token(self, cache=True):
763 def get_artifact_token(self, cache=True):
764 artifacts_tokens = UserApiKeys.query()\
764 artifacts_tokens = UserApiKeys.query()\
765 .filter(UserApiKeys.user == self) \
765 .filter(UserApiKeys.user == self) \
766 .filter(or_(UserApiKeys.expires == -1,
766 .filter(or_(UserApiKeys.expires == -1,
767 UserApiKeys.expires >= time.time())) \
767 UserApiKeys.expires >= time.time())) \
768 .filter(UserApiKeys.role == UserApiKeys.ROLE_ARTIFACT_DOWNLOAD)
768 .filter(UserApiKeys.role == UserApiKeys.ROLE_ARTIFACT_DOWNLOAD)
769
769
770 if cache:
770 if cache:
771 artifacts_tokens = artifacts_tokens.options(
771 artifacts_tokens = artifacts_tokens.options(
772 FromCache("sql_cache_short", f"get_user_artifact_token_{self.user_id}"))
772 FromCache("sql_cache_short", f"get_user_artifact_token_{self.user_id}"))
773
773
774 artifacts_tokens = artifacts_tokens.all()
774 artifacts_tokens = artifacts_tokens.all()
775 if artifacts_tokens:
775 if artifacts_tokens:
776 return artifacts_tokens[0].api_key
776 return artifacts_tokens[0].api_key
777 return 'NO_ARTIFACT_TOKEN_AVAILABLE'
777 return 'NO_ARTIFACT_TOKEN_AVAILABLE'
778
778
779 def get_or_create_artifact_token(self):
779 def get_or_create_artifact_token(self):
780 artifacts_tokens = UserApiKeys.query()\
780 artifacts_tokens = UserApiKeys.query()\
781 .filter(UserApiKeys.user == self) \
781 .filter(UserApiKeys.user == self) \
782 .filter(or_(UserApiKeys.expires == -1,
782 .filter(or_(UserApiKeys.expires == -1,
783 UserApiKeys.expires >= time.time())) \
783 UserApiKeys.expires >= time.time())) \
784 .filter(UserApiKeys.role == UserApiKeys.ROLE_ARTIFACT_DOWNLOAD)
784 .filter(UserApiKeys.role == UserApiKeys.ROLE_ARTIFACT_DOWNLOAD)
785
785
786 artifacts_tokens = artifacts_tokens.all()
786 artifacts_tokens = artifacts_tokens.all()
787 if artifacts_tokens:
787 if artifacts_tokens:
788 return artifacts_tokens[0].api_key
788 return artifacts_tokens[0].api_key
789 else:
789 else:
790 from rhodecode.model.auth_token import AuthTokenModel
790 from rhodecode.model.auth_token import AuthTokenModel
791 artifact_token = AuthTokenModel().create(
791 artifact_token = AuthTokenModel().create(
792 self, 'auto-generated-artifact-token',
792 self, 'auto-generated-artifact-token',
793 lifetime=-1, role=UserApiKeys.ROLE_ARTIFACT_DOWNLOAD)
793 lifetime=-1, role=UserApiKeys.ROLE_ARTIFACT_DOWNLOAD)
794 Session.commit()
794 Session.commit()
795 return artifact_token.api_key
795 return artifact_token.api_key
796
796
797 def is_totp_valid(self, received_code, secret):
797 def is_totp_valid(self, received_code, secret):
798 totp = pyotp.TOTP(secret)
798 totp = pyotp.TOTP(secret)
799 return totp.verify(received_code)
799 return totp.verify(received_code)
800
800
801 def is_2fa_recovery_code_valid(self, received_code, secret):
801 def is_2fa_recovery_code_valid(self, received_code, secret):
802 encrypted_recovery_codes = self.user_data.get('recovery_codes_2fa', [])
802 encrypted_recovery_codes = self.user_data.get('recovery_codes_2fa', [])
803 recovery_codes = self.get_2fa_recovery_codes()
803 recovery_codes = self.get_2fa_recovery_codes()
804 if received_code in recovery_codes:
804 if received_code in recovery_codes:
805 encrypted_recovery_codes.pop(recovery_codes.index(received_code))
805 encrypted_recovery_codes.pop(recovery_codes.index(received_code))
806 self.update_userdata(recovery_codes_2fa=encrypted_recovery_codes)
806 self.update_userdata(recovery_codes_2fa=encrypted_recovery_codes)
807 return True
807 return True
808 return False
808 return False
809
809
810 @hybrid_property
810 @hybrid_property
811 def has_forced_2fa(self):
811 def has_forced_2fa(self):
812 """
812 """
813 Checks if 2fa was forced for current user
813 Checks if 2fa was forced for current user
814 """
814 """
815 from rhodecode.model.settings import SettingsModel
815 from rhodecode.model.settings import SettingsModel
816 if value := SettingsModel().get_setting_by_name(f'{self.extern_type}_global_2fa'):
816 if value := SettingsModel().get_setting_by_name(f'auth_{self.extern_type}_global_2fa'):
817 return value.app_settings_value
817 return value.app_settings_value
818 return False
818 return False
819
819
820 @hybrid_property
820 @hybrid_property
821 def has_enabled_2fa(self):
821 def has_enabled_2fa(self):
822 """
822 """
823 Checks if user enabled 2fa
823 Checks if user enabled 2fa
824 """
824 """
825 if value := self.has_forced_2fa:
825 if value := self.has_forced_2fa:
826 return value
826 return value
827 return self.user_data.get('enabled_2fa', False)
827 return self.user_data.get('enabled_2fa', False)
828
828
829 @has_enabled_2fa.setter
829 @has_enabled_2fa.setter
830 def has_enabled_2fa(self, val):
830 def has_enabled_2fa(self, val):
831 val = str2bool(val)
831 val = str2bool(val)
832 self.update_userdata(enabled_2fa=val)
832 self.update_userdata(enabled_2fa=val)
833 if not val:
833 if not val:
834 # NOTE: setting to false we clear the user_data to not store any 2fa artifacts
834 # NOTE: setting to false we clear the user_data to not store any 2fa artifacts
835 self.update_userdata(secret_2fa=None, recovery_codes_2fa=[], check_2fa=False)
835 self.update_userdata(secret_2fa=None, recovery_codes_2fa=[], check_2fa=False)
836 Session().commit()
836 Session().commit()
837
837
838 @hybrid_property
838 @hybrid_property
839 def check_2fa_required(self):
839 def check_2fa_required(self):
840 """
840 """
841 Check if check 2fa flag is set for this user
841 Check if check 2fa flag is set for this user
842 """
842 """
843 value = self.user_data.get('check_2fa', False)
843 value = self.user_data.get('check_2fa', False)
844 return value
844 return value
845
845
846 @check_2fa_required.setter
846 @check_2fa_required.setter
847 def check_2fa_required(self, val):
847 def check_2fa_required(self, val):
848 val = str2bool(val)
848 val = str2bool(val)
849 self.update_userdata(check_2fa=val)
849 self.update_userdata(check_2fa=val)
850 Session().commit()
850 Session().commit()
851
851
852 @hybrid_property
852 @hybrid_property
853 def has_seen_2fa_codes(self):
853 def has_seen_2fa_codes(self):
854 """
854 """
855 get the flag about if user has seen 2fa recovery codes
855 get the flag about if user has seen 2fa recovery codes
856 """
856 """
857 value = self.user_data.get('recovery_codes_2fa_seen', False)
857 value = self.user_data.get('recovery_codes_2fa_seen', False)
858 return value
858 return value
859
859
860 @has_seen_2fa_codes.setter
860 @has_seen_2fa_codes.setter
861 def has_seen_2fa_codes(self, val):
861 def has_seen_2fa_codes(self, val):
862 val = str2bool(val)
862 val = str2bool(val)
863 self.update_userdata(recovery_codes_2fa_seen=val)
863 self.update_userdata(recovery_codes_2fa_seen=val)
864 Session().commit()
864 Session().commit()
865
865
866 @hybrid_property
866 @hybrid_property
867 def needs_2fa_configure(self):
867 def needs_2fa_configure(self):
868 """
868 """
869 Determines if setup2fa has completed for this user. Means he has all needed data for 2fa to work.
869 Determines if setup2fa has completed for this user. Means he has all needed data for 2fa to work.
870
870
871 Currently this is 2fa enabled and secret exists
871 Currently this is 2fa enabled and secret exists
872 """
872 """
873 if self.has_enabled_2fa:
873 if self.has_enabled_2fa:
874 return not self.user_data.get('secret_2fa')
874 return not self.user_data.get('secret_2fa')
875 return False
875 return False
876
876
877 def init_2fa_recovery_codes(self, persist=True, force=False):
877 def init_2fa_recovery_codes(self, persist=True, force=False):
878 """
878 """
879 Creates 2fa recovery codes
879 Creates 2fa recovery codes
880 """
880 """
881 recovery_codes = self.user_data.get('recovery_codes_2fa', [])
881 recovery_codes = self.user_data.get('recovery_codes_2fa', [])
882 encrypted_codes = []
882 encrypted_codes = []
883 if not recovery_codes or force:
883 if not recovery_codes or force:
884 for _ in range(self.RECOVERY_CODES_COUNT):
884 for _ in range(self.RECOVERY_CODES_COUNT):
885 recovery_code = pyotp.random_base32()
885 recovery_code = pyotp.random_base32()
886 recovery_codes.append(recovery_code)
886 recovery_codes.append(recovery_code)
887 encrypted_code = enc_utils.encrypt_value(safe_bytes(recovery_code), enc_key=ENCRYPTION_KEY)
887 encrypted_code = enc_utils.encrypt_value(safe_bytes(recovery_code), enc_key=ENCRYPTION_KEY)
888 encrypted_codes.append(safe_str(encrypted_code))
888 encrypted_codes.append(safe_str(encrypted_code))
889 if persist:
889 if persist:
890 self.update_userdata(recovery_codes_2fa=encrypted_codes, recovery_codes_2fa_seen=False)
890 self.update_userdata(recovery_codes_2fa=encrypted_codes, recovery_codes_2fa_seen=False)
891 return recovery_codes
891 return recovery_codes
892 # User should not check the same recovery codes more than once
892 # User should not check the same recovery codes more than once
893 return []
893 return []
894
894
895 def get_2fa_recovery_codes(self):
895 def get_2fa_recovery_codes(self):
896 encrypted_recovery_codes = self.user_data.get('recovery_codes_2fa', [])
896 encrypted_recovery_codes = self.user_data.get('recovery_codes_2fa', [])
897
897
898 recovery_codes = list(map(
898 recovery_codes = list(map(
899 lambda val: safe_str(
899 lambda val: safe_str(
900 enc_utils.decrypt_value(
900 enc_utils.decrypt_value(
901 val,
901 val,
902 enc_key=ENCRYPTION_KEY
902 enc_key=ENCRYPTION_KEY
903 )),
903 )),
904 encrypted_recovery_codes))
904 encrypted_recovery_codes))
905 return recovery_codes
905 return recovery_codes
906
906
907 def init_secret_2fa(self, persist=True, force=False):
907 def init_secret_2fa(self, persist=True, force=False):
908 secret_2fa = self.user_data.get('secret_2fa')
908 secret_2fa = self.user_data.get('secret_2fa')
909 if not secret_2fa or force:
909 if not secret_2fa or force:
910 secret = pyotp.random_base32()
910 secret = pyotp.random_base32()
911 if persist:
911 if persist:
912 self.update_userdata(secret_2fa=safe_str(enc_utils.encrypt_value(safe_bytes(secret), enc_key=ENCRYPTION_KEY)))
912 self.update_userdata(secret_2fa=safe_str(enc_utils.encrypt_value(safe_bytes(secret), enc_key=ENCRYPTION_KEY)))
913 return secret
913 return secret
914 return ''
914 return ''
915
915
916 @hybrid_property
916 @hybrid_property
917 def secret_2fa(self) -> str:
917 def secret_2fa(self) -> str:
918 """
918 """
919 get stored secret for 2fa
919 get stored secret for 2fa
920 """
920 """
921 secret_2fa = self.user_data.get('secret_2fa')
921 secret_2fa = self.user_data.get('secret_2fa')
922 if secret_2fa:
922 if secret_2fa:
923 return safe_str(
923 return safe_str(
924 enc_utils.decrypt_value(secret_2fa, enc_key=ENCRYPTION_KEY))
924 enc_utils.decrypt_value(secret_2fa, enc_key=ENCRYPTION_KEY))
925 return ''
925 return ''
926
926
927 @secret_2fa.setter
927 @secret_2fa.setter
928 def secret_2fa(self, value: str) -> None:
928 def secret_2fa(self, value: str) -> None:
929 encrypted_value = enc_utils.encrypt_value(safe_bytes(value), enc_key=ENCRYPTION_KEY)
929 encrypted_value = enc_utils.encrypt_value(safe_bytes(value), enc_key=ENCRYPTION_KEY)
930 self.update_userdata(secret_2fa=safe_str(encrypted_value))
930 self.update_userdata(secret_2fa=safe_str(encrypted_value))
931
931
932 def regenerate_2fa_recovery_codes(self):
932 def regenerate_2fa_recovery_codes(self):
933 """
933 """
934 Regenerates 2fa recovery codes upon request
934 Regenerates 2fa recovery codes upon request
935 """
935 """
936 new_recovery_codes = self.init_2fa_recovery_codes(force=True)
936 new_recovery_codes = self.init_2fa_recovery_codes(force=True)
937 Session().commit()
937 Session().commit()
938 return new_recovery_codes
938 return new_recovery_codes
939
939
940 @classmethod
940 @classmethod
941 def extra_valid_auth_tokens(cls, user, role=None):
941 def extra_valid_auth_tokens(cls, user, role=None):
942 tokens = UserApiKeys.query().filter(UserApiKeys.user == user)\
942 tokens = UserApiKeys.query().filter(UserApiKeys.user == user)\
943 .filter(or_(UserApiKeys.expires == -1,
943 .filter(or_(UserApiKeys.expires == -1,
944 UserApiKeys.expires >= time.time()))
944 UserApiKeys.expires >= time.time()))
945 if role:
945 if role:
946 tokens = tokens.filter(or_(UserApiKeys.role == role,
946 tokens = tokens.filter(or_(UserApiKeys.role == role,
947 UserApiKeys.role == UserApiKeys.ROLE_ALL))
947 UserApiKeys.role == UserApiKeys.ROLE_ALL))
948 return tokens.all()
948 return tokens.all()
949
949
950 def authenticate_by_token(self, auth_token, roles=None, scope_repo_id=None):
950 def authenticate_by_token(self, auth_token, roles=None, scope_repo_id=None):
951 from rhodecode.lib import auth
951 from rhodecode.lib import auth
952
952
953 log.debug('Trying to authenticate user: %s via auth-token, '
953 log.debug('Trying to authenticate user: %s via auth-token, '
954 'and roles: %s', self, roles)
954 'and roles: %s', self, roles)
955
955
956 if not auth_token:
956 if not auth_token:
957 return False
957 return False
958
958
959 roles = (roles or []) + [UserApiKeys.ROLE_ALL]
959 roles = (roles or []) + [UserApiKeys.ROLE_ALL]
960 tokens_q = UserApiKeys.query()\
960 tokens_q = UserApiKeys.query()\
961 .filter(UserApiKeys.user_id == self.user_id)\
961 .filter(UserApiKeys.user_id == self.user_id)\
962 .filter(or_(UserApiKeys.expires == -1,
962 .filter(or_(UserApiKeys.expires == -1,
963 UserApiKeys.expires >= time.time()))
963 UserApiKeys.expires >= time.time()))
964
964
965 tokens_q = tokens_q.filter(UserApiKeys.role.in_(roles))
965 tokens_q = tokens_q.filter(UserApiKeys.role.in_(roles))
966
966
967 crypto_backend = auth.crypto_backend()
967 crypto_backend = auth.crypto_backend()
968 enc_token_map = {}
968 enc_token_map = {}
969 plain_token_map = {}
969 plain_token_map = {}
970 for token in tokens_q:
970 for token in tokens_q:
971 if token.api_key.startswith(crypto_backend.ENC_PREF):
971 if token.api_key.startswith(crypto_backend.ENC_PREF):
972 enc_token_map[token.api_key] = token
972 enc_token_map[token.api_key] = token
973 else:
973 else:
974 plain_token_map[token.api_key] = token
974 plain_token_map[token.api_key] = token
975 log.debug(
975 log.debug(
976 'Found %s plain and %s encrypted tokens to check for authentication for this user',
976 'Found %s plain and %s encrypted tokens to check for authentication for this user',
977 len(plain_token_map), len(enc_token_map))
977 len(plain_token_map), len(enc_token_map))
978
978
979 # plain token match comes first
979 # plain token match comes first
980 match = plain_token_map.get(auth_token)
980 match = plain_token_map.get(auth_token)
981
981
982 # check encrypted tokens now
982 # check encrypted tokens now
983 if not match:
983 if not match:
984 for token_hash, token in enc_token_map.items():
984 for token_hash, token in enc_token_map.items():
985 # NOTE(marcink): this is expensive to calculate, but most secure
985 # NOTE(marcink): this is expensive to calculate, but most secure
986 if crypto_backend.hash_check(auth_token, token_hash):
986 if crypto_backend.hash_check(auth_token, token_hash):
987 match = token
987 match = token
988 break
988 break
989
989
990 if match:
990 if match:
991 log.debug('Found matching token %s', match)
991 log.debug('Found matching token %s', match)
992 if match.repo_id:
992 if match.repo_id:
993 log.debug('Found scope, checking for scope match of token %s', match)
993 log.debug('Found scope, checking for scope match of token %s', match)
994 if match.repo_id == scope_repo_id:
994 if match.repo_id == scope_repo_id:
995 return True
995 return True
996 else:
996 else:
997 log.debug(
997 log.debug(
998 'AUTH_TOKEN: scope mismatch, token has a set repo scope: %s, '
998 'AUTH_TOKEN: scope mismatch, token has a set repo scope: %s, '
999 'and calling scope is:%s, skipping further checks',
999 'and calling scope is:%s, skipping further checks',
1000 match.repo, scope_repo_id)
1000 match.repo, scope_repo_id)
1001 return False
1001 return False
1002 else:
1002 else:
1003 return True
1003 return True
1004
1004
1005 return False
1005 return False
1006
1006
1007 @property
1007 @property
1008 def ip_addresses(self):
1008 def ip_addresses(self):
1009 ret = UserIpMap.query().filter(UserIpMap.user == self).all()
1009 ret = UserIpMap.query().filter(UserIpMap.user == self).all()
1010 return [x.ip_addr for x in ret]
1010 return [x.ip_addr for x in ret]
1011
1011
1012 @property
1012 @property
1013 def username_and_name(self):
1013 def username_and_name(self):
1014 return f'{self.username} ({self.first_name} {self.last_name})'
1014 return f'{self.username} ({self.first_name} {self.last_name})'
1015
1015
1016 @property
1016 @property
1017 def username_or_name_or_email(self):
1017 def username_or_name_or_email(self):
1018 full_name = self.full_name if self.full_name != ' ' else None
1018 full_name = self.full_name if self.full_name != ' ' else None
1019 return self.username or full_name or self.email
1019 return self.username or full_name or self.email
1020
1020
1021 @property
1021 @property
1022 def full_name(self):
1022 def full_name(self):
1023 return f'{self.first_name} {self.last_name}'
1023 return f'{self.first_name} {self.last_name}'
1024
1024
1025 @property
1025 @property
1026 def full_name_or_username(self):
1026 def full_name_or_username(self):
1027 return (f'{self.first_name} {self.last_name}'
1027 return (f'{self.first_name} {self.last_name}'
1028 if (self.first_name and self.last_name) else self.username)
1028 if (self.first_name and self.last_name) else self.username)
1029
1029
1030 @property
1030 @property
1031 def full_contact(self):
1031 def full_contact(self):
1032 return f'{self.first_name} {self.last_name} <{self.email}>'
1032 return f'{self.first_name} {self.last_name} <{self.email}>'
1033
1033
1034 @property
1034 @property
1035 def short_contact(self):
1035 def short_contact(self):
1036 return f'{self.first_name} {self.last_name}'
1036 return f'{self.first_name} {self.last_name}'
1037
1037
1038 @property
1038 @property
1039 def is_admin(self):
1039 def is_admin(self):
1040 return self.admin
1040 return self.admin
1041
1041
1042 @property
1042 @property
1043 def language(self):
1043 def language(self):
1044 return self.user_data.get('language')
1044 return self.user_data.get('language')
1045
1045
1046 def AuthUser(self, **kwargs):
1046 def AuthUser(self, **kwargs):
1047 """
1047 """
1048 Returns instance of AuthUser for this user
1048 Returns instance of AuthUser for this user
1049 """
1049 """
1050 from rhodecode.lib.auth import AuthUser
1050 from rhodecode.lib.auth import AuthUser
1051 return AuthUser(user_id=self.user_id, username=self.username, **kwargs)
1051 return AuthUser(user_id=self.user_id, username=self.username, **kwargs)
1052
1052
1053 @hybrid_property
1053 @hybrid_property
1054 def user_data(self):
1054 def user_data(self):
1055 if not self._user_data:
1055 if not self._user_data:
1056 return {}
1056 return {}
1057
1057
1058 try:
1058 try:
1059 return json.loads(self._user_data) or {}
1059 return json.loads(self._user_data) or {}
1060 except TypeError:
1060 except TypeError:
1061 return {}
1061 return {}
1062
1062
1063 @user_data.setter
1063 @user_data.setter
1064 def user_data(self, val):
1064 def user_data(self, val):
1065 if not isinstance(val, dict):
1065 if not isinstance(val, dict):
1066 raise Exception(f'user_data must be dict, got {type(val)}')
1066 raise Exception(f'user_data must be dict, got {type(val)}')
1067 try:
1067 try:
1068 self._user_data = safe_bytes(json.dumps(val))
1068 self._user_data = safe_bytes(json.dumps(val))
1069 except Exception:
1069 except Exception:
1070 log.error(traceback.format_exc())
1070 log.error(traceback.format_exc())
1071
1071
1072 @classmethod
1072 @classmethod
1073 def get(cls, user_id, cache=False):
1073 def get(cls, user_id, cache=False):
1074 if not user_id:
1074 if not user_id:
1075 return
1075 return
1076
1076
1077 user = cls.query()
1077 user = cls.query()
1078 if cache:
1078 if cache:
1079 user = user.options(
1079 user = user.options(
1080 FromCache("sql_cache_short", f"get_users_{user_id}"))
1080 FromCache("sql_cache_short", f"get_users_{user_id}"))
1081 return user.get(user_id)
1081 return user.get(user_id)
1082
1082
1083 @classmethod
1083 @classmethod
1084 def get_by_username(cls, username, case_insensitive=False,
1084 def get_by_username(cls, username, case_insensitive=False,
1085 cache=False):
1085 cache=False):
1086
1086
1087 if case_insensitive:
1087 if case_insensitive:
1088 q = cls.select().where(
1088 q = cls.select().where(
1089 func.lower(cls.username) == func.lower(username))
1089 func.lower(cls.username) == func.lower(username))
1090 else:
1090 else:
1091 q = cls.select().where(cls.username == username)
1091 q = cls.select().where(cls.username == username)
1092
1092
1093 if cache:
1093 if cache:
1094 hash_key = _hash_key(username)
1094 hash_key = _hash_key(username)
1095 q = q.options(
1095 q = q.options(
1096 FromCache("sql_cache_short", f"get_user_by_name_{hash_key}"))
1096 FromCache("sql_cache_short", f"get_user_by_name_{hash_key}"))
1097
1097
1098 return cls.execute(q).scalar_one_or_none()
1098 return cls.execute(q).scalar_one_or_none()
1099
1099
1100 @classmethod
1100 @classmethod
1101 def get_by_username_or_primary_email(cls, user_identifier):
1101 def get_by_username_or_primary_email(cls, user_identifier):
1102 qs = union_all(cls.select().where(func.lower(cls.username) == func.lower(user_identifier)),
1102 qs = union_all(cls.select().where(func.lower(cls.username) == func.lower(user_identifier)),
1103 cls.select().where(func.lower(cls.email) == func.lower(user_identifier)))
1103 cls.select().where(func.lower(cls.email) == func.lower(user_identifier)))
1104 return cls.execute(cls.select(User).from_statement(qs)).scalar_one_or_none()
1104 return cls.execute(cls.select(User).from_statement(qs)).scalar_one_or_none()
1105
1105
1106 @classmethod
1106 @classmethod
1107 def get_by_auth_token(cls, auth_token, cache=False):
1107 def get_by_auth_token(cls, auth_token, cache=False):
1108
1108
1109 q = cls.select(User)\
1109 q = cls.select(User)\
1110 .join(UserApiKeys)\
1110 .join(UserApiKeys)\
1111 .where(UserApiKeys.api_key == auth_token)\
1111 .where(UserApiKeys.api_key == auth_token)\
1112 .where(or_(UserApiKeys.expires == -1,
1112 .where(or_(UserApiKeys.expires == -1,
1113 UserApiKeys.expires >= time.time()))
1113 UserApiKeys.expires >= time.time()))
1114
1114
1115 if cache:
1115 if cache:
1116 q = q.options(
1116 q = q.options(
1117 FromCache("sql_cache_short", f"get_auth_token_{auth_token}"))
1117 FromCache("sql_cache_short", f"get_auth_token_{auth_token}"))
1118
1118
1119 matched_user = cls.execute(q).scalar_one_or_none()
1119 matched_user = cls.execute(q).scalar_one_or_none()
1120
1120
1121 return matched_user
1121 return matched_user
1122
1122
1123 @classmethod
1123 @classmethod
1124 def get_by_email(cls, email, case_insensitive=False, cache=False):
1124 def get_by_email(cls, email, case_insensitive=False, cache=False):
1125
1125
1126 if case_insensitive:
1126 if case_insensitive:
1127 q = cls.select().where(func.lower(cls.email) == func.lower(email))
1127 q = cls.select().where(func.lower(cls.email) == func.lower(email))
1128 else:
1128 else:
1129 q = cls.select().where(cls.email == email)
1129 q = cls.select().where(cls.email == email)
1130
1130
1131 if cache:
1131 if cache:
1132 email_key = _hash_key(email)
1132 email_key = _hash_key(email)
1133 q = q.options(
1133 q = q.options(
1134 FromCache("sql_cache_short", f"get_email_key_{email_key}"))
1134 FromCache("sql_cache_short", f"get_email_key_{email_key}"))
1135
1135
1136 ret = cls.execute(q).scalar_one_or_none()
1136 ret = cls.execute(q).scalar_one_or_none()
1137
1137
1138 if ret is None:
1138 if ret is None:
1139 q = cls.select(UserEmailMap)
1139 q = cls.select(UserEmailMap)
1140 # try fetching in alternate email map
1140 # try fetching in alternate email map
1141 if case_insensitive:
1141 if case_insensitive:
1142 q = q.where(func.lower(UserEmailMap.email) == func.lower(email))
1142 q = q.where(func.lower(UserEmailMap.email) == func.lower(email))
1143 else:
1143 else:
1144 q = q.where(UserEmailMap.email == email)
1144 q = q.where(UserEmailMap.email == email)
1145 q = q.options(joinedload(UserEmailMap.user))
1145 q = q.options(joinedload(UserEmailMap.user))
1146 if cache:
1146 if cache:
1147 q = q.options(
1147 q = q.options(
1148 FromCache("sql_cache_short", f"get_email_map_key_{email_key}"))
1148 FromCache("sql_cache_short", f"get_email_map_key_{email_key}"))
1149
1149
1150 result = cls.execute(q).scalar_one_or_none()
1150 result = cls.execute(q).scalar_one_or_none()
1151 ret = getattr(result, 'user', None)
1151 ret = getattr(result, 'user', None)
1152
1152
1153 return ret
1153 return ret
1154
1154
1155 @classmethod
1155 @classmethod
1156 def get_from_cs_author(cls, author):
1156 def get_from_cs_author(cls, author):
1157 """
1157 """
1158 Tries to get User objects out of commit author string
1158 Tries to get User objects out of commit author string
1159
1159
1160 :param author:
1160 :param author:
1161 """
1161 """
1162 from rhodecode.lib.helpers import email, author_name
1162 from rhodecode.lib.helpers import email, author_name
1163 # Valid email in the attribute passed, see if they're in the system
1163 # Valid email in the attribute passed, see if they're in the system
1164 _email = email(author)
1164 _email = email(author)
1165 if _email:
1165 if _email:
1166 user = cls.get_by_email(_email, case_insensitive=True)
1166 user = cls.get_by_email(_email, case_insensitive=True)
1167 if user:
1167 if user:
1168 return user
1168 return user
1169 # Maybe we can match by username?
1169 # Maybe we can match by username?
1170 _author = author_name(author)
1170 _author = author_name(author)
1171 user = cls.get_by_username(_author, case_insensitive=True)
1171 user = cls.get_by_username(_author, case_insensitive=True)
1172 if user:
1172 if user:
1173 return user
1173 return user
1174
1174
1175 def update_userdata(self, **kwargs):
1175 def update_userdata(self, **kwargs):
1176 usr = self
1176 usr = self
1177 old = usr.user_data
1177 old = usr.user_data
1178 old.update(**kwargs)
1178 old.update(**kwargs)
1179 usr.user_data = old
1179 usr.user_data = old
1180 Session().add(usr)
1180 Session().add(usr)
1181 log.debug('updated userdata with %s', kwargs)
1181 log.debug('updated userdata with %s', kwargs)
1182
1182
1183 def update_lastlogin(self):
1183 def update_lastlogin(self):
1184 """Update user lastlogin"""
1184 """Update user lastlogin"""
1185 self.last_login = datetime.datetime.now()
1185 self.last_login = datetime.datetime.now()
1186 Session().add(self)
1186 Session().add(self)
1187 log.debug('updated user %s lastlogin', self.username)
1187 log.debug('updated user %s lastlogin', self.username)
1188
1188
1189 def update_password(self, new_password):
1189 def update_password(self, new_password):
1190 from rhodecode.lib.auth import get_crypt_password
1190 from rhodecode.lib.auth import get_crypt_password
1191
1191
1192 self.password = get_crypt_password(new_password)
1192 self.password = get_crypt_password(new_password)
1193 Session().add(self)
1193 Session().add(self)
1194
1194
1195 @classmethod
1195 @classmethod
1196 def get_first_super_admin(cls):
1196 def get_first_super_admin(cls):
1197 stmt = cls.select().where(User.admin == true()).order_by(User.user_id.asc())
1197 stmt = cls.select().where(User.admin == true()).order_by(User.user_id.asc())
1198 user = cls.scalars(stmt).first()
1198 user = cls.scalars(stmt).first()
1199
1199
1200 if user is None:
1200 if user is None:
1201 raise Exception('FATAL: Missing administrative account!')
1201 raise Exception('FATAL: Missing administrative account!')
1202 return user
1202 return user
1203
1203
1204 @classmethod
1204 @classmethod
1205 def get_all_super_admins(cls, only_active=False):
1205 def get_all_super_admins(cls, only_active=False):
1206 """
1206 """
1207 Returns all admin accounts sorted by username
1207 Returns all admin accounts sorted by username
1208 """
1208 """
1209 qry = User.query().filter(User.admin == true()).order_by(User.username.asc())
1209 qry = User.query().filter(User.admin == true()).order_by(User.username.asc())
1210 if only_active:
1210 if only_active:
1211 qry = qry.filter(User.active == true())
1211 qry = qry.filter(User.active == true())
1212 return qry.all()
1212 return qry.all()
1213
1213
1214 @classmethod
1214 @classmethod
1215 def get_all_user_ids(cls, only_active=True):
1215 def get_all_user_ids(cls, only_active=True):
1216 """
1216 """
1217 Returns all users IDs
1217 Returns all users IDs
1218 """
1218 """
1219 qry = Session().query(User.user_id)
1219 qry = Session().query(User.user_id)
1220
1220
1221 if only_active:
1221 if only_active:
1222 qry = qry.filter(User.active == true())
1222 qry = qry.filter(User.active == true())
1223 return [x.user_id for x in qry]
1223 return [x.user_id for x in qry]
1224
1224
1225 @classmethod
1225 @classmethod
1226 def get_default_user(cls, cache=False, refresh=False):
1226 def get_default_user(cls, cache=False, refresh=False):
1227 user = User.get_by_username(User.DEFAULT_USER, cache=cache)
1227 user = User.get_by_username(User.DEFAULT_USER, cache=cache)
1228 if user is None:
1228 if user is None:
1229 raise Exception('FATAL: Missing default account!')
1229 raise Exception('FATAL: Missing default account!')
1230 if refresh:
1230 if refresh:
1231 # The default user might be based on outdated state which
1231 # The default user might be based on outdated state which
1232 # has been loaded from the cache.
1232 # has been loaded from the cache.
1233 # A call to refresh() ensures that the
1233 # A call to refresh() ensures that the
1234 # latest state from the database is used.
1234 # latest state from the database is used.
1235 Session().refresh(user)
1235 Session().refresh(user)
1236
1236
1237 return user
1237 return user
1238
1238
1239 @classmethod
1239 @classmethod
1240 def get_default_user_id(cls):
1240 def get_default_user_id(cls):
1241 import rhodecode
1241 import rhodecode
1242 return rhodecode.CONFIG['default_user_id']
1242 return rhodecode.CONFIG['default_user_id']
1243
1243
1244 def _get_default_perms(self, user, suffix=''):
1244 def _get_default_perms(self, user, suffix=''):
1245 from rhodecode.model.permission import PermissionModel
1245 from rhodecode.model.permission import PermissionModel
1246 return PermissionModel().get_default_perms(user.user_perms, suffix)
1246 return PermissionModel().get_default_perms(user.user_perms, suffix)
1247
1247
1248 def get_default_perms(self, suffix=''):
1248 def get_default_perms(self, suffix=''):
1249 return self._get_default_perms(self, suffix)
1249 return self._get_default_perms(self, suffix)
1250
1250
1251 def get_api_data(self, include_secrets=False, details='full'):
1251 def get_api_data(self, include_secrets=False, details='full'):
1252 """
1252 """
1253 Common function for generating user related data for API
1253 Common function for generating user related data for API
1254
1254
1255 :param include_secrets: By default secrets in the API data will be replaced
1255 :param include_secrets: By default secrets in the API data will be replaced
1256 by a placeholder value to prevent exposing this data by accident. In case
1256 by a placeholder value to prevent exposing this data by accident. In case
1257 this data shall be exposed, set this flag to ``True``.
1257 this data shall be exposed, set this flag to ``True``.
1258
1258
1259 :param details: details can be 'basic|full' basic gives only a subset of
1259 :param details: details can be 'basic|full' basic gives only a subset of
1260 the available user information that includes user_id, name and emails.
1260 the available user information that includes user_id, name and emails.
1261 """
1261 """
1262 user = self
1262 user = self
1263 user_data = self.user_data
1263 user_data = self.user_data
1264 data = {
1264 data = {
1265 'user_id': user.user_id,
1265 'user_id': user.user_id,
1266 'username': user.username,
1266 'username': user.username,
1267 'firstname': user.name,
1267 'firstname': user.name,
1268 'lastname': user.lastname,
1268 'lastname': user.lastname,
1269 'description': user.description,
1269 'description': user.description,
1270 'email': user.email,
1270 'email': user.email,
1271 'emails': user.emails,
1271 'emails': user.emails,
1272 }
1272 }
1273 if details == 'basic':
1273 if details == 'basic':
1274 return data
1274 return data
1275
1275
1276 auth_token_length = 40
1276 auth_token_length = 40
1277 auth_token_replacement = '*' * auth_token_length
1277 auth_token_replacement = '*' * auth_token_length
1278
1278
1279 extras = {
1279 extras = {
1280 'auth_tokens': [auth_token_replacement],
1280 'auth_tokens': [auth_token_replacement],
1281 'active': user.active,
1281 'active': user.active,
1282 'admin': user.admin,
1282 'admin': user.admin,
1283 'extern_type': user.extern_type,
1283 'extern_type': user.extern_type,
1284 'extern_name': user.extern_name,
1284 'extern_name': user.extern_name,
1285 'last_login': user.last_login,
1285 'last_login': user.last_login,
1286 'last_activity': user.last_activity,
1286 'last_activity': user.last_activity,
1287 'ip_addresses': user.ip_addresses,
1287 'ip_addresses': user.ip_addresses,
1288 'language': user_data.get('language')
1288 'language': user_data.get('language')
1289 }
1289 }
1290 data.update(extras)
1290 data.update(extras)
1291
1291
1292 if include_secrets:
1292 if include_secrets:
1293 data['auth_tokens'] = user.auth_tokens
1293 data['auth_tokens'] = user.auth_tokens
1294 return data
1294 return data
1295
1295
1296 def __json__(self):
1296 def __json__(self):
1297 data = {
1297 data = {
1298 'full_name': self.full_name,
1298 'full_name': self.full_name,
1299 'full_name_or_username': self.full_name_or_username,
1299 'full_name_or_username': self.full_name_or_username,
1300 'short_contact': self.short_contact,
1300 'short_contact': self.short_contact,
1301 'full_contact': self.full_contact,
1301 'full_contact': self.full_contact,
1302 }
1302 }
1303 data.update(self.get_api_data())
1303 data.update(self.get_api_data())
1304 return data
1304 return data
1305
1305
1306
1306
1307 class UserApiKeys(Base, BaseModel):
1307 class UserApiKeys(Base, BaseModel):
1308 __tablename__ = 'user_api_keys'
1308 __tablename__ = 'user_api_keys'
1309 __table_args__ = (
1309 __table_args__ = (
1310 Index('uak_api_key_idx', 'api_key'),
1310 Index('uak_api_key_idx', 'api_key'),
1311 Index('uak_api_key_expires_idx', 'api_key', 'expires'),
1311 Index('uak_api_key_expires_idx', 'api_key', 'expires'),
1312 base_table_args
1312 base_table_args
1313 )
1313 )
1314
1314
1315 # ApiKey role
1315 # ApiKey role
1316 ROLE_ALL = 'token_role_all'
1316 ROLE_ALL = 'token_role_all'
1317 ROLE_VCS = 'token_role_vcs'
1317 ROLE_VCS = 'token_role_vcs'
1318 ROLE_API = 'token_role_api'
1318 ROLE_API = 'token_role_api'
1319 ROLE_HTTP = 'token_role_http'
1319 ROLE_HTTP = 'token_role_http'
1320 ROLE_FEED = 'token_role_feed'
1320 ROLE_FEED = 'token_role_feed'
1321 ROLE_ARTIFACT_DOWNLOAD = 'role_artifact_download'
1321 ROLE_ARTIFACT_DOWNLOAD = 'role_artifact_download'
1322 # The last one is ignored in the list as we only
1322 # The last one is ignored in the list as we only
1323 # use it for one action, and cannot be created by users
1323 # use it for one action, and cannot be created by users
1324 ROLE_PASSWORD_RESET = 'token_password_reset'
1324 ROLE_PASSWORD_RESET = 'token_password_reset'
1325
1325
1326 ROLES = [ROLE_ALL, ROLE_VCS, ROLE_API, ROLE_HTTP, ROLE_FEED, ROLE_ARTIFACT_DOWNLOAD]
1326 ROLES = [ROLE_ALL, ROLE_VCS, ROLE_API, ROLE_HTTP, ROLE_FEED, ROLE_ARTIFACT_DOWNLOAD]
1327
1327
1328 user_api_key_id = Column("user_api_key_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1328 user_api_key_id = Column("user_api_key_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1329 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1329 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1330 api_key = Column("api_key", String(255), nullable=False, unique=True)
1330 api_key = Column("api_key", String(255), nullable=False, unique=True)
1331 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1331 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1332 expires = Column('expires', Float(53), nullable=False)
1332 expires = Column('expires', Float(53), nullable=False)
1333 role = Column('role', String(255), nullable=True)
1333 role = Column('role', String(255), nullable=True)
1334 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1334 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1335
1335
1336 # scope columns
1336 # scope columns
1337 repo_id = Column(
1337 repo_id = Column(
1338 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
1338 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
1339 nullable=True, unique=None, default=None)
1339 nullable=True, unique=None, default=None)
1340 repo = relationship('Repository', lazy='joined', back_populates='scoped_tokens')
1340 repo = relationship('Repository', lazy='joined', back_populates='scoped_tokens')
1341
1341
1342 repo_group_id = Column(
1342 repo_group_id = Column(
1343 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
1343 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
1344 nullable=True, unique=None, default=None)
1344 nullable=True, unique=None, default=None)
1345 repo_group = relationship('RepoGroup', lazy='joined')
1345 repo_group = relationship('RepoGroup', lazy='joined')
1346
1346
1347 user = relationship('User', lazy='joined', back_populates='user_auth_tokens')
1347 user = relationship('User', lazy='joined', back_populates='user_auth_tokens')
1348
1348
1349 def __repr__(self):
1349 def __repr__(self):
1350 return f"<{self.cls_name}('{self.role}')>"
1350 return f"<{self.cls_name}('{self.role}')>"
1351
1351
1352 def __json__(self):
1352 def __json__(self):
1353 data = {
1353 data = {
1354 'auth_token': self.api_key,
1354 'auth_token': self.api_key,
1355 'role': self.role,
1355 'role': self.role,
1356 'scope': self.scope_humanized,
1356 'scope': self.scope_humanized,
1357 'expired': self.expired
1357 'expired': self.expired
1358 }
1358 }
1359 return data
1359 return data
1360
1360
1361 def get_api_data(self, include_secrets=False):
1361 def get_api_data(self, include_secrets=False):
1362 data = self.__json__()
1362 data = self.__json__()
1363 if include_secrets:
1363 if include_secrets:
1364 return data
1364 return data
1365 else:
1365 else:
1366 data['auth_token'] = self.token_obfuscated
1366 data['auth_token'] = self.token_obfuscated
1367 return data
1367 return data
1368
1368
1369 @hybrid_property
1369 @hybrid_property
1370 def description_safe(self):
1370 def description_safe(self):
1371 from rhodecode.lib import helpers as h
1371 from rhodecode.lib import helpers as h
1372 return h.escape(self.description)
1372 return h.escape(self.description)
1373
1373
1374 @property
1374 @property
1375 def expired(self):
1375 def expired(self):
1376 if self.expires == -1:
1376 if self.expires == -1:
1377 return False
1377 return False
1378 return time.time() > self.expires
1378 return time.time() > self.expires
1379
1379
1380 @classmethod
1380 @classmethod
1381 def _get_role_name(cls, role):
1381 def _get_role_name(cls, role):
1382 return {
1382 return {
1383 cls.ROLE_ALL: _('all'),
1383 cls.ROLE_ALL: _('all'),
1384 cls.ROLE_HTTP: _('http/web interface'),
1384 cls.ROLE_HTTP: _('http/web interface'),
1385 cls.ROLE_VCS: _('vcs (git/hg/svn protocol)'),
1385 cls.ROLE_VCS: _('vcs (git/hg/svn protocol)'),
1386 cls.ROLE_API: _('api calls'),
1386 cls.ROLE_API: _('api calls'),
1387 cls.ROLE_FEED: _('feed access'),
1387 cls.ROLE_FEED: _('feed access'),
1388 cls.ROLE_ARTIFACT_DOWNLOAD: _('artifacts downloads'),
1388 cls.ROLE_ARTIFACT_DOWNLOAD: _('artifacts downloads'),
1389 }.get(role, role)
1389 }.get(role, role)
1390
1390
1391 @classmethod
1391 @classmethod
1392 def _get_role_description(cls, role):
1392 def _get_role_description(cls, role):
1393 return {
1393 return {
1394 cls.ROLE_ALL: _('Token for all actions.'),
1394 cls.ROLE_ALL: _('Token for all actions.'),
1395 cls.ROLE_HTTP: _('Token to access RhodeCode pages via web interface without '
1395 cls.ROLE_HTTP: _('Token to access RhodeCode pages via web interface without '
1396 'login using `api_access_controllers_whitelist` functionality.'),
1396 'login using `api_access_controllers_whitelist` functionality.'),
1397 cls.ROLE_VCS: _('Token to interact over git/hg/svn protocols. '
1397 cls.ROLE_VCS: _('Token to interact over git/hg/svn protocols. '
1398 'Requires auth_token authentication plugin to be active. <br/>'
1398 'Requires auth_token authentication plugin to be active. <br/>'
1399 'Such Token should be used then instead of a password to '
1399 'Such Token should be used then instead of a password to '
1400 'interact with a repository, and additionally can be '
1400 'interact with a repository, and additionally can be '
1401 'limited to single repository using repo scope.'),
1401 'limited to single repository using repo scope.'),
1402 cls.ROLE_API: _('Token limited to api calls.'),
1402 cls.ROLE_API: _('Token limited to api calls.'),
1403 cls.ROLE_FEED: _('Token to read RSS/ATOM feed.'),
1403 cls.ROLE_FEED: _('Token to read RSS/ATOM feed.'),
1404 cls.ROLE_ARTIFACT_DOWNLOAD: _('Token for artifacts downloads.'),
1404 cls.ROLE_ARTIFACT_DOWNLOAD: _('Token for artifacts downloads.'),
1405 }.get(role, role)
1405 }.get(role, role)
1406
1406
1407 @property
1407 @property
1408 def role_humanized(self):
1408 def role_humanized(self):
1409 return self._get_role_name(self.role)
1409 return self._get_role_name(self.role)
1410
1410
1411 def _get_scope(self):
1411 def _get_scope(self):
1412 if self.repo:
1412 if self.repo:
1413 return 'Repository: {}'.format(self.repo.repo_name)
1413 return 'Repository: {}'.format(self.repo.repo_name)
1414 if self.repo_group:
1414 if self.repo_group:
1415 return 'RepositoryGroup: {} (recursive)'.format(self.repo_group.group_name)
1415 return 'RepositoryGroup: {} (recursive)'.format(self.repo_group.group_name)
1416 return 'Global'
1416 return 'Global'
1417
1417
1418 @property
1418 @property
1419 def scope_humanized(self):
1419 def scope_humanized(self):
1420 return self._get_scope()
1420 return self._get_scope()
1421
1421
1422 @property
1422 @property
1423 def token_obfuscated(self):
1423 def token_obfuscated(self):
1424 if self.api_key:
1424 if self.api_key:
1425 return self.api_key[:4] + "****"
1425 return self.api_key[:4] + "****"
1426
1426
1427
1427
1428 class UserEmailMap(Base, BaseModel):
1428 class UserEmailMap(Base, BaseModel):
1429 __tablename__ = 'user_email_map'
1429 __tablename__ = 'user_email_map'
1430 __table_args__ = (
1430 __table_args__ = (
1431 Index('uem_email_idx', 'email'),
1431 Index('uem_email_idx', 'email'),
1432 Index('uem_user_id_idx', 'user_id'),
1432 Index('uem_user_id_idx', 'user_id'),
1433 UniqueConstraint('email'),
1433 UniqueConstraint('email'),
1434 base_table_args
1434 base_table_args
1435 )
1435 )
1436
1436
1437 email_id = Column("email_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1437 email_id = Column("email_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1438 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1438 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1439 _email = Column("email", String(255), nullable=True, unique=False, default=None)
1439 _email = Column("email", String(255), nullable=True, unique=False, default=None)
1440 user = relationship('User', lazy='joined', back_populates='user_emails')
1440 user = relationship('User', lazy='joined', back_populates='user_emails')
1441
1441
1442 @validates('_email')
1442 @validates('_email')
1443 def validate_email(self, key, email):
1443 def validate_email(self, key, email):
1444 # check if this email is not main one
1444 # check if this email is not main one
1445 main_email = Session().query(User).filter(User.email == email).scalar()
1445 main_email = Session().query(User).filter(User.email == email).scalar()
1446 if main_email is not None:
1446 if main_email is not None:
1447 raise AttributeError('email %s is present is user table' % email)
1447 raise AttributeError('email %s is present is user table' % email)
1448 return email
1448 return email
1449
1449
1450 @hybrid_property
1450 @hybrid_property
1451 def email(self):
1451 def email(self):
1452 return self._email
1452 return self._email
1453
1453
1454 @email.setter
1454 @email.setter
1455 def email(self, val):
1455 def email(self, val):
1456 self._email = val.lower() if val else None
1456 self._email = val.lower() if val else None
1457
1457
1458
1458
1459 class UserIpMap(Base, BaseModel):
1459 class UserIpMap(Base, BaseModel):
1460 __tablename__ = 'user_ip_map'
1460 __tablename__ = 'user_ip_map'
1461 __table_args__ = (
1461 __table_args__ = (
1462 UniqueConstraint('user_id', 'ip_addr'),
1462 UniqueConstraint('user_id', 'ip_addr'),
1463 base_table_args
1463 base_table_args
1464 )
1464 )
1465
1465
1466 ip_id = Column("ip_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1466 ip_id = Column("ip_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1467 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1467 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1468 ip_addr = Column("ip_addr", String(255), nullable=True, unique=False, default=None)
1468 ip_addr = Column("ip_addr", String(255), nullable=True, unique=False, default=None)
1469 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
1469 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
1470 description = Column("description", String(10000), nullable=True, unique=None, default=None)
1470 description = Column("description", String(10000), nullable=True, unique=None, default=None)
1471 user = relationship('User', lazy='joined', back_populates='user_ip_map')
1471 user = relationship('User', lazy='joined', back_populates='user_ip_map')
1472
1472
1473 @hybrid_property
1473 @hybrid_property
1474 def description_safe(self):
1474 def description_safe(self):
1475 from rhodecode.lib import helpers as h
1475 from rhodecode.lib import helpers as h
1476 return h.escape(self.description)
1476 return h.escape(self.description)
1477
1477
1478 @classmethod
1478 @classmethod
1479 def _get_ip_range(cls, ip_addr):
1479 def _get_ip_range(cls, ip_addr):
1480 net = ipaddress.ip_network(safe_str(ip_addr), strict=False)
1480 net = ipaddress.ip_network(safe_str(ip_addr), strict=False)
1481 return [str(net.network_address), str(net.broadcast_address)]
1481 return [str(net.network_address), str(net.broadcast_address)]
1482
1482
1483 def __json__(self):
1483 def __json__(self):
1484 return {
1484 return {
1485 'ip_addr': self.ip_addr,
1485 'ip_addr': self.ip_addr,
1486 'ip_range': self._get_ip_range(self.ip_addr),
1486 'ip_range': self._get_ip_range(self.ip_addr),
1487 }
1487 }
1488
1488
1489 def __repr__(self):
1489 def __repr__(self):
1490 return f"<{self.cls_name}('user_id={self.user_id} => ip={self.ip_addr}')>"
1490 return f"<{self.cls_name}('user_id={self.user_id} => ip={self.ip_addr}')>"
1491
1491
1492
1492
1493 class UserSshKeys(Base, BaseModel):
1493 class UserSshKeys(Base, BaseModel):
1494 __tablename__ = 'user_ssh_keys'
1494 __tablename__ = 'user_ssh_keys'
1495 __table_args__ = (
1495 __table_args__ = (
1496 Index('usk_ssh_key_fingerprint_idx', 'ssh_key_fingerprint'),
1496 Index('usk_ssh_key_fingerprint_idx', 'ssh_key_fingerprint'),
1497
1497
1498 UniqueConstraint('ssh_key_fingerprint'),
1498 UniqueConstraint('ssh_key_fingerprint'),
1499
1499
1500 base_table_args
1500 base_table_args
1501 )
1501 )
1502
1502
1503 ssh_key_id = Column('ssh_key_id', Integer(), nullable=False, unique=True, default=None, primary_key=True)
1503 ssh_key_id = Column('ssh_key_id', Integer(), nullable=False, unique=True, default=None, primary_key=True)
1504 ssh_key_data = Column('ssh_key_data', String(10240), nullable=False, unique=None, default=None)
1504 ssh_key_data = Column('ssh_key_data', String(10240), nullable=False, unique=None, default=None)
1505 ssh_key_fingerprint = Column('ssh_key_fingerprint', String(255), nullable=False, unique=None, default=None)
1505 ssh_key_fingerprint = Column('ssh_key_fingerprint', String(255), nullable=False, unique=None, default=None)
1506
1506
1507 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1507 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1508
1508
1509 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1509 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1510 accessed_on = Column('accessed_on', DateTime(timezone=False), nullable=True, default=None)
1510 accessed_on = Column('accessed_on', DateTime(timezone=False), nullable=True, default=None)
1511 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1511 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1512
1512
1513 user = relationship('User', lazy='joined', back_populates='user_ssh_keys')
1513 user = relationship('User', lazy='joined', back_populates='user_ssh_keys')
1514
1514
1515 def __json__(self):
1515 def __json__(self):
1516 data = {
1516 data = {
1517 'ssh_fingerprint': self.ssh_key_fingerprint,
1517 'ssh_fingerprint': self.ssh_key_fingerprint,
1518 'description': self.description,
1518 'description': self.description,
1519 'created_on': self.created_on
1519 'created_on': self.created_on
1520 }
1520 }
1521 return data
1521 return data
1522
1522
1523 def get_api_data(self):
1523 def get_api_data(self):
1524 data = self.__json__()
1524 data = self.__json__()
1525 return data
1525 return data
1526
1526
1527
1527
1528 class UserLog(Base, BaseModel):
1528 class UserLog(Base, BaseModel):
1529 __tablename__ = 'user_logs'
1529 __tablename__ = 'user_logs'
1530 __table_args__ = (
1530 __table_args__ = (
1531 base_table_args,
1531 base_table_args,
1532 )
1532 )
1533
1533
1534 VERSION_1 = 'v1'
1534 VERSION_1 = 'v1'
1535 VERSION_2 = 'v2'
1535 VERSION_2 = 'v2'
1536 VERSIONS = [VERSION_1, VERSION_2]
1536 VERSIONS = [VERSION_1, VERSION_2]
1537
1537
1538 user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1538 user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1539 user_id = Column("user_id", Integer(), ForeignKey('users.user_id',ondelete='SET NULL'), nullable=True, unique=None, default=None)
1539 user_id = Column("user_id", Integer(), ForeignKey('users.user_id',ondelete='SET NULL'), nullable=True, unique=None, default=None)
1540 username = Column("username", String(255), nullable=True, unique=None, default=None)
1540 username = Column("username", String(255), nullable=True, unique=None, default=None)
1541 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id', ondelete='SET NULL'), nullable=True, unique=None, default=None)
1541 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id', ondelete='SET NULL'), nullable=True, unique=None, default=None)
1542 repository_name = Column("repository_name", String(255), nullable=True, unique=None, default=None)
1542 repository_name = Column("repository_name", String(255), nullable=True, unique=None, default=None)
1543 user_ip = Column("user_ip", String(255), nullable=True, unique=None, default=None)
1543 user_ip = Column("user_ip", String(255), nullable=True, unique=None, default=None)
1544 action = Column("action", Text().with_variant(Text(1200000), 'mysql'), nullable=True, unique=None, default=None)
1544 action = Column("action", Text().with_variant(Text(1200000), 'mysql'), nullable=True, unique=None, default=None)
1545 action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
1545 action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
1546
1546
1547 version = Column("version", String(255), nullable=True, default=VERSION_1)
1547 version = Column("version", String(255), nullable=True, default=VERSION_1)
1548 user_data = Column('user_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1548 user_data = Column('user_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1549 action_data = Column('action_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1549 action_data = Column('action_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1550 user = relationship('User', cascade='', back_populates='user_log')
1550 user = relationship('User', cascade='', back_populates='user_log')
1551 repository = relationship('Repository', cascade='', back_populates='logs')
1551 repository = relationship('Repository', cascade='', back_populates='logs')
1552
1552
1553 def __repr__(self):
1553 def __repr__(self):
1554 return f"<{self.cls_name}('id:{self.repository_name}:{self.action}')>"
1554 return f"<{self.cls_name}('id:{self.repository_name}:{self.action}')>"
1555
1555
1556 def __json__(self):
1556 def __json__(self):
1557 return {
1557 return {
1558 'user_id': self.user_id,
1558 'user_id': self.user_id,
1559 'username': self.username,
1559 'username': self.username,
1560 'repository_id': self.repository_id,
1560 'repository_id': self.repository_id,
1561 'repository_name': self.repository_name,
1561 'repository_name': self.repository_name,
1562 'user_ip': self.user_ip,
1562 'user_ip': self.user_ip,
1563 'action_date': self.action_date,
1563 'action_date': self.action_date,
1564 'action': self.action,
1564 'action': self.action,
1565 }
1565 }
1566
1566
1567 @hybrid_property
1567 @hybrid_property
1568 def entry_id(self):
1568 def entry_id(self):
1569 return self.user_log_id
1569 return self.user_log_id
1570
1570
1571 @property
1571 @property
1572 def action_as_day(self):
1572 def action_as_day(self):
1573 return datetime.date(*self.action_date.timetuple()[:3])
1573 return datetime.date(*self.action_date.timetuple()[:3])
1574
1574
1575
1575
1576 class UserGroup(Base, BaseModel):
1576 class UserGroup(Base, BaseModel):
1577 __tablename__ = 'users_groups'
1577 __tablename__ = 'users_groups'
1578 __table_args__ = (
1578 __table_args__ = (
1579 base_table_args,
1579 base_table_args,
1580 )
1580 )
1581
1581
1582 users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1582 users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1583 users_group_name = Column("users_group_name", String(255), nullable=False, unique=True, default=None)
1583 users_group_name = Column("users_group_name", String(255), nullable=False, unique=True, default=None)
1584 user_group_description = Column("user_group_description", String(10000), nullable=True, unique=None, default=None)
1584 user_group_description = Column("user_group_description", String(10000), nullable=True, unique=None, default=None)
1585 users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
1585 users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
1586 inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
1586 inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
1587 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
1587 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
1588 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1588 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1589 _group_data = Column("group_data", LargeBinary(), nullable=True) # JSON data
1589 _group_data = Column("group_data", LargeBinary(), nullable=True) # JSON data
1590
1590
1591 members = relationship('UserGroupMember', cascade="all, delete-orphan", lazy="joined", back_populates='users_group')
1591 members = relationship('UserGroupMember', cascade="all, delete-orphan", lazy="joined", back_populates='users_group')
1592 users_group_to_perm = relationship('UserGroupToPerm', cascade='all', back_populates='users_group')
1592 users_group_to_perm = relationship('UserGroupToPerm', cascade='all', back_populates='users_group')
1593 users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all', back_populates='users_group')
1593 users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all', back_populates='users_group')
1594 users_group_repo_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all', back_populates='users_group')
1594 users_group_repo_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all', back_populates='users_group')
1595 user_user_group_to_perm = relationship('UserUserGroupToPerm', cascade='all', back_populates='user_group')
1595 user_user_group_to_perm = relationship('UserUserGroupToPerm', cascade='all', back_populates='user_group')
1596
1596
1597 user_group_user_group_to_perm = relationship('UserGroupUserGroupToPerm', primaryjoin="UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id", cascade='all', back_populates='target_user_group')
1597 user_group_user_group_to_perm = relationship('UserGroupUserGroupToPerm', primaryjoin="UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id", cascade='all', back_populates='target_user_group')
1598
1598
1599 user_group_review_rules = relationship('RepoReviewRuleUserGroup', cascade='all', back_populates='users_group')
1599 user_group_review_rules = relationship('RepoReviewRuleUserGroup', cascade='all', back_populates='users_group')
1600 user = relationship('User', primaryjoin="User.user_id==UserGroup.user_id", back_populates='user_groups')
1600 user = relationship('User', primaryjoin="User.user_id==UserGroup.user_id", back_populates='user_groups')
1601
1601
1602 @classmethod
1602 @classmethod
1603 def _load_group_data(cls, column):
1603 def _load_group_data(cls, column):
1604 if not column:
1604 if not column:
1605 return {}
1605 return {}
1606
1606
1607 try:
1607 try:
1608 return json.loads(column) or {}
1608 return json.loads(column) or {}
1609 except TypeError:
1609 except TypeError:
1610 return {}
1610 return {}
1611
1611
1612 @hybrid_property
1612 @hybrid_property
1613 def description_safe(self):
1613 def description_safe(self):
1614 from rhodecode.lib import helpers as h
1614 from rhodecode.lib import helpers as h
1615 return h.escape(self.user_group_description)
1615 return h.escape(self.user_group_description)
1616
1616
1617 @hybrid_property
1617 @hybrid_property
1618 def group_data(self):
1618 def group_data(self):
1619 return self._load_group_data(self._group_data)
1619 return self._load_group_data(self._group_data)
1620
1620
1621 @group_data.expression
1621 @group_data.expression
1622 def group_data(self, **kwargs):
1622 def group_data(self, **kwargs):
1623 return self._group_data
1623 return self._group_data
1624
1624
1625 @group_data.setter
1625 @group_data.setter
1626 def group_data(self, val):
1626 def group_data(self, val):
1627 try:
1627 try:
1628 self._group_data = json.dumps(val)
1628 self._group_data = json.dumps(val)
1629 except Exception:
1629 except Exception:
1630 log.error(traceback.format_exc())
1630 log.error(traceback.format_exc())
1631
1631
1632 @classmethod
1632 @classmethod
1633 def _load_sync(cls, group_data):
1633 def _load_sync(cls, group_data):
1634 if group_data:
1634 if group_data:
1635 return group_data.get('extern_type')
1635 return group_data.get('extern_type')
1636
1636
1637 @property
1637 @property
1638 def sync(self):
1638 def sync(self):
1639 return self._load_sync(self.group_data)
1639 return self._load_sync(self.group_data)
1640
1640
1641 def __repr__(self):
1641 def __repr__(self):
1642 return f"<{self.cls_name}('id:{self.users_group_id}:{self.users_group_name}')>"
1642 return f"<{self.cls_name}('id:{self.users_group_id}:{self.users_group_name}')>"
1643
1643
1644 @classmethod
1644 @classmethod
1645 def get_by_group_name(cls, group_name, cache=False,
1645 def get_by_group_name(cls, group_name, cache=False,
1646 case_insensitive=False):
1646 case_insensitive=False):
1647 if case_insensitive:
1647 if case_insensitive:
1648 q = cls.query().filter(func.lower(cls.users_group_name) ==
1648 q = cls.query().filter(func.lower(cls.users_group_name) ==
1649 func.lower(group_name))
1649 func.lower(group_name))
1650
1650
1651 else:
1651 else:
1652 q = cls.query().filter(cls.users_group_name == group_name)
1652 q = cls.query().filter(cls.users_group_name == group_name)
1653 if cache:
1653 if cache:
1654 name_key = _hash_key(group_name)
1654 name_key = _hash_key(group_name)
1655 q = q.options(
1655 q = q.options(
1656 FromCache("sql_cache_short", f"get_group_{name_key}"))
1656 FromCache("sql_cache_short", f"get_group_{name_key}"))
1657 return q.scalar()
1657 return q.scalar()
1658
1658
1659 @classmethod
1659 @classmethod
1660 def get(cls, user_group_id, cache=False):
1660 def get(cls, user_group_id, cache=False):
1661 if not user_group_id:
1661 if not user_group_id:
1662 return
1662 return
1663
1663
1664 user_group = cls.query()
1664 user_group = cls.query()
1665 if cache:
1665 if cache:
1666 user_group = user_group.options(
1666 user_group = user_group.options(
1667 FromCache("sql_cache_short", f"get_users_group_{user_group_id}"))
1667 FromCache("sql_cache_short", f"get_users_group_{user_group_id}"))
1668 return user_group.get(user_group_id)
1668 return user_group.get(user_group_id)
1669
1669
1670 def permissions(self, with_admins=True, with_owner=True,
1670 def permissions(self, with_admins=True, with_owner=True,
1671 expand_from_user_groups=False):
1671 expand_from_user_groups=False):
1672 """
1672 """
1673 Permissions for user groups
1673 Permissions for user groups
1674 """
1674 """
1675 _admin_perm = 'usergroup.admin'
1675 _admin_perm = 'usergroup.admin'
1676
1676
1677 owner_row = []
1677 owner_row = []
1678 if with_owner:
1678 if with_owner:
1679 usr = AttributeDict(self.user.get_dict())
1679 usr = AttributeDict(self.user.get_dict())
1680 usr.owner_row = True
1680 usr.owner_row = True
1681 usr.permission = _admin_perm
1681 usr.permission = _admin_perm
1682 owner_row.append(usr)
1682 owner_row.append(usr)
1683
1683
1684 super_admin_ids = []
1684 super_admin_ids = []
1685 super_admin_rows = []
1685 super_admin_rows = []
1686 if with_admins:
1686 if with_admins:
1687 for usr in User.get_all_super_admins():
1687 for usr in User.get_all_super_admins():
1688 super_admin_ids.append(usr.user_id)
1688 super_admin_ids.append(usr.user_id)
1689 # if this admin is also owner, don't double the record
1689 # if this admin is also owner, don't double the record
1690 if usr.user_id == owner_row[0].user_id:
1690 if usr.user_id == owner_row[0].user_id:
1691 owner_row[0].admin_row = True
1691 owner_row[0].admin_row = True
1692 else:
1692 else:
1693 usr = AttributeDict(usr.get_dict())
1693 usr = AttributeDict(usr.get_dict())
1694 usr.admin_row = True
1694 usr.admin_row = True
1695 usr.permission = _admin_perm
1695 usr.permission = _admin_perm
1696 super_admin_rows.append(usr)
1696 super_admin_rows.append(usr)
1697
1697
1698 q = UserUserGroupToPerm.query().filter(UserUserGroupToPerm.user_group == self)
1698 q = UserUserGroupToPerm.query().filter(UserUserGroupToPerm.user_group == self)
1699 q = q.options(joinedload(UserUserGroupToPerm.user_group),
1699 q = q.options(joinedload(UserUserGroupToPerm.user_group),
1700 joinedload(UserUserGroupToPerm.user),
1700 joinedload(UserUserGroupToPerm.user),
1701 joinedload(UserUserGroupToPerm.permission),)
1701 joinedload(UserUserGroupToPerm.permission),)
1702
1702
1703 # get owners and admins and permissions. We do a trick of re-writing
1703 # get owners and admins and permissions. We do a trick of re-writing
1704 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1704 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1705 # has a global reference and changing one object propagates to all
1705 # has a global reference and changing one object propagates to all
1706 # others. This means if admin is also an owner admin_row that change
1706 # others. This means if admin is also an owner admin_row that change
1707 # would propagate to both objects
1707 # would propagate to both objects
1708 perm_rows = []
1708 perm_rows = []
1709 for _usr in q.all():
1709 for _usr in q.all():
1710 usr = AttributeDict(_usr.user.get_dict())
1710 usr = AttributeDict(_usr.user.get_dict())
1711 # if this user is also owner/admin, mark as duplicate record
1711 # if this user is also owner/admin, mark as duplicate record
1712 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
1712 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
1713 usr.duplicate_perm = True
1713 usr.duplicate_perm = True
1714 usr.permission = _usr.permission.permission_name
1714 usr.permission = _usr.permission.permission_name
1715 perm_rows.append(usr)
1715 perm_rows.append(usr)
1716
1716
1717 # filter the perm rows by 'default' first and then sort them by
1717 # filter the perm rows by 'default' first and then sort them by
1718 # admin,write,read,none permissions sorted again alphabetically in
1718 # admin,write,read,none permissions sorted again alphabetically in
1719 # each group
1719 # each group
1720 perm_rows = sorted(perm_rows, key=display_user_sort)
1720 perm_rows = sorted(perm_rows, key=display_user_sort)
1721
1721
1722 user_groups_rows = []
1722 user_groups_rows = []
1723 if expand_from_user_groups:
1723 if expand_from_user_groups:
1724 for ug in self.permission_user_groups(with_members=True):
1724 for ug in self.permission_user_groups(with_members=True):
1725 for user_data in ug.members:
1725 for user_data in ug.members:
1726 user_groups_rows.append(user_data)
1726 user_groups_rows.append(user_data)
1727
1727
1728 return super_admin_rows + owner_row + perm_rows + user_groups_rows
1728 return super_admin_rows + owner_row + perm_rows + user_groups_rows
1729
1729
1730 def permission_user_groups(self, with_members=False):
1730 def permission_user_groups(self, with_members=False):
1731 q = UserGroupUserGroupToPerm.query()\
1731 q = UserGroupUserGroupToPerm.query()\
1732 .filter(UserGroupUserGroupToPerm.target_user_group == self)
1732 .filter(UserGroupUserGroupToPerm.target_user_group == self)
1733 q = q.options(joinedload(UserGroupUserGroupToPerm.user_group),
1733 q = q.options(joinedload(UserGroupUserGroupToPerm.user_group),
1734 joinedload(UserGroupUserGroupToPerm.target_user_group),
1734 joinedload(UserGroupUserGroupToPerm.target_user_group),
1735 joinedload(UserGroupUserGroupToPerm.permission),)
1735 joinedload(UserGroupUserGroupToPerm.permission),)
1736
1736
1737 perm_rows = []
1737 perm_rows = []
1738 for _user_group in q.all():
1738 for _user_group in q.all():
1739 entry = AttributeDict(_user_group.user_group.get_dict())
1739 entry = AttributeDict(_user_group.user_group.get_dict())
1740 entry.permission = _user_group.permission.permission_name
1740 entry.permission = _user_group.permission.permission_name
1741 if with_members:
1741 if with_members:
1742 entry.members = [x.user.get_dict()
1742 entry.members = [x.user.get_dict()
1743 for x in _user_group.user_group.members]
1743 for x in _user_group.user_group.members]
1744 perm_rows.append(entry)
1744 perm_rows.append(entry)
1745
1745
1746 perm_rows = sorted(perm_rows, key=display_user_group_sort)
1746 perm_rows = sorted(perm_rows, key=display_user_group_sort)
1747 return perm_rows
1747 return perm_rows
1748
1748
1749 def _get_default_perms(self, user_group, suffix=''):
1749 def _get_default_perms(self, user_group, suffix=''):
1750 from rhodecode.model.permission import PermissionModel
1750 from rhodecode.model.permission import PermissionModel
1751 return PermissionModel().get_default_perms(user_group.users_group_to_perm, suffix)
1751 return PermissionModel().get_default_perms(user_group.users_group_to_perm, suffix)
1752
1752
1753 def get_default_perms(self, suffix=''):
1753 def get_default_perms(self, suffix=''):
1754 return self._get_default_perms(self, suffix)
1754 return self._get_default_perms(self, suffix)
1755
1755
1756 def get_api_data(self, with_group_members=True, include_secrets=False):
1756 def get_api_data(self, with_group_members=True, include_secrets=False):
1757 """
1757 """
1758 :param include_secrets: See :meth:`User.get_api_data`, this parameter is
1758 :param include_secrets: See :meth:`User.get_api_data`, this parameter is
1759 basically forwarded.
1759 basically forwarded.
1760
1760
1761 """
1761 """
1762 user_group = self
1762 user_group = self
1763 data = {
1763 data = {
1764 'users_group_id': user_group.users_group_id,
1764 'users_group_id': user_group.users_group_id,
1765 'group_name': user_group.users_group_name,
1765 'group_name': user_group.users_group_name,
1766 'group_description': user_group.user_group_description,
1766 'group_description': user_group.user_group_description,
1767 'active': user_group.users_group_active,
1767 'active': user_group.users_group_active,
1768 'owner': user_group.user.username,
1768 'owner': user_group.user.username,
1769 'sync': user_group.sync,
1769 'sync': user_group.sync,
1770 'owner_email': user_group.user.email,
1770 'owner_email': user_group.user.email,
1771 }
1771 }
1772
1772
1773 if with_group_members:
1773 if with_group_members:
1774 users = []
1774 users = []
1775 for user in user_group.members:
1775 for user in user_group.members:
1776 user = user.user
1776 user = user.user
1777 users.append(user.get_api_data(include_secrets=include_secrets))
1777 users.append(user.get_api_data(include_secrets=include_secrets))
1778 data['users'] = users
1778 data['users'] = users
1779
1779
1780 return data
1780 return data
1781
1781
1782
1782
1783 class UserGroupMember(Base, BaseModel):
1783 class UserGroupMember(Base, BaseModel):
1784 __tablename__ = 'users_groups_members'
1784 __tablename__ = 'users_groups_members'
1785 __table_args__ = (
1785 __table_args__ = (
1786 base_table_args,
1786 base_table_args,
1787 )
1787 )
1788
1788
1789 users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1789 users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1790 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
1790 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
1791 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
1791 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
1792
1792
1793 user = relationship('User', lazy='joined', back_populates='group_member')
1793 user = relationship('User', lazy='joined', back_populates='group_member')
1794 users_group = relationship('UserGroup', back_populates='members')
1794 users_group = relationship('UserGroup', back_populates='members')
1795
1795
1796 def __init__(self, gr_id='', u_id=''):
1796 def __init__(self, gr_id='', u_id=''):
1797 self.users_group_id = gr_id
1797 self.users_group_id = gr_id
1798 self.user_id = u_id
1798 self.user_id = u_id
1799
1799
1800
1800
1801 class RepositoryField(Base, BaseModel):
1801 class RepositoryField(Base, BaseModel):
1802 __tablename__ = 'repositories_fields'
1802 __tablename__ = 'repositories_fields'
1803 __table_args__ = (
1803 __table_args__ = (
1804 UniqueConstraint('repository_id', 'field_key'), # no-multi field
1804 UniqueConstraint('repository_id', 'field_key'), # no-multi field
1805 base_table_args,
1805 base_table_args,
1806 )
1806 )
1807
1807
1808 PREFIX = 'ex_' # prefix used in form to not conflict with already existing fields
1808 PREFIX = 'ex_' # prefix used in form to not conflict with already existing fields
1809
1809
1810 repo_field_id = Column("repo_field_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1810 repo_field_id = Column("repo_field_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1811 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
1811 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
1812 field_key = Column("field_key", String(250))
1812 field_key = Column("field_key", String(250))
1813 field_label = Column("field_label", String(1024), nullable=False)
1813 field_label = Column("field_label", String(1024), nullable=False)
1814 field_value = Column("field_value", String(10000), nullable=False)
1814 field_value = Column("field_value", String(10000), nullable=False)
1815 field_desc = Column("field_desc", String(1024), nullable=False)
1815 field_desc = Column("field_desc", String(1024), nullable=False)
1816 field_type = Column("field_type", String(255), nullable=False, unique=None)
1816 field_type = Column("field_type", String(255), nullable=False, unique=None)
1817 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1817 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1818
1818
1819 repository = relationship('Repository', back_populates='extra_fields')
1819 repository = relationship('Repository', back_populates='extra_fields')
1820
1820
1821 @property
1821 @property
1822 def field_key_prefixed(self):
1822 def field_key_prefixed(self):
1823 return 'ex_%s' % self.field_key
1823 return 'ex_%s' % self.field_key
1824
1824
1825 @classmethod
1825 @classmethod
1826 def un_prefix_key(cls, key):
1826 def un_prefix_key(cls, key):
1827 if key.startswith(cls.PREFIX):
1827 if key.startswith(cls.PREFIX):
1828 return key[len(cls.PREFIX):]
1828 return key[len(cls.PREFIX):]
1829 return key
1829 return key
1830
1830
1831 @classmethod
1831 @classmethod
1832 def get_by_key_name(cls, key, repo):
1832 def get_by_key_name(cls, key, repo):
1833 row = cls.query()\
1833 row = cls.query()\
1834 .filter(cls.repository == repo)\
1834 .filter(cls.repository == repo)\
1835 .filter(cls.field_key == key).scalar()
1835 .filter(cls.field_key == key).scalar()
1836 return row
1836 return row
1837
1837
1838
1838
1839 class Repository(Base, BaseModel):
1839 class Repository(Base, BaseModel):
1840 __tablename__ = 'repositories'
1840 __tablename__ = 'repositories'
1841 __table_args__ = (
1841 __table_args__ = (
1842 Index('r_repo_name_idx', 'repo_name', mysql_length=255),
1842 Index('r_repo_name_idx', 'repo_name', mysql_length=255),
1843 base_table_args,
1843 base_table_args,
1844 )
1844 )
1845 DEFAULT_CLONE_URI = '{scheme}://{user}@{netloc}/{repo}'
1845 DEFAULT_CLONE_URI = '{scheme}://{user}@{netloc}/{repo}'
1846 DEFAULT_CLONE_URI_ID = '{scheme}://{user}@{netloc}/_{repoid}'
1846 DEFAULT_CLONE_URI_ID = '{scheme}://{user}@{netloc}/_{repoid}'
1847 DEFAULT_CLONE_URI_SSH = 'ssh://{sys_user}@{hostname}/{repo}'
1847 DEFAULT_CLONE_URI_SSH = 'ssh://{sys_user}@{hostname}/{repo}'
1848
1848
1849 STATE_CREATED = 'repo_state_created'
1849 STATE_CREATED = 'repo_state_created'
1850 STATE_PENDING = 'repo_state_pending'
1850 STATE_PENDING = 'repo_state_pending'
1851 STATE_ERROR = 'repo_state_error'
1851 STATE_ERROR = 'repo_state_error'
1852
1852
1853 LOCK_AUTOMATIC = 'lock_auto'
1853 LOCK_AUTOMATIC = 'lock_auto'
1854 LOCK_API = 'lock_api'
1854 LOCK_API = 'lock_api'
1855 LOCK_WEB = 'lock_web'
1855 LOCK_WEB = 'lock_web'
1856 LOCK_PULL = 'lock_pull'
1856 LOCK_PULL = 'lock_pull'
1857
1857
1858 NAME_SEP = URL_SEP
1858 NAME_SEP = URL_SEP
1859
1859
1860 repo_id = Column(
1860 repo_id = Column(
1861 "repo_id", Integer(), nullable=False, unique=True, default=None,
1861 "repo_id", Integer(), nullable=False, unique=True, default=None,
1862 primary_key=True)
1862 primary_key=True)
1863 _repo_name = Column(
1863 _repo_name = Column(
1864 "repo_name", Text(), nullable=False, default=None)
1864 "repo_name", Text(), nullable=False, default=None)
1865 repo_name_hash = Column(
1865 repo_name_hash = Column(
1866 "repo_name_hash", String(255), nullable=False, unique=True)
1866 "repo_name_hash", String(255), nullable=False, unique=True)
1867 repo_state = Column("repo_state", String(255), nullable=True)
1867 repo_state = Column("repo_state", String(255), nullable=True)
1868
1868
1869 clone_uri = Column(
1869 clone_uri = Column(
1870 "clone_uri", EncryptedTextValue(), nullable=True, unique=False,
1870 "clone_uri", EncryptedTextValue(), nullable=True, unique=False,
1871 default=None)
1871 default=None)
1872 push_uri = Column(
1872 push_uri = Column(
1873 "push_uri", EncryptedTextValue(), nullable=True, unique=False,
1873 "push_uri", EncryptedTextValue(), nullable=True, unique=False,
1874 default=None)
1874 default=None)
1875 repo_type = Column(
1875 repo_type = Column(
1876 "repo_type", String(255), nullable=False, unique=False, default=None)
1876 "repo_type", String(255), nullable=False, unique=False, default=None)
1877 user_id = Column(
1877 user_id = Column(
1878 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
1878 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
1879 unique=False, default=None)
1879 unique=False, default=None)
1880 private = Column(
1880 private = Column(
1881 "private", Boolean(), nullable=True, unique=None, default=None)
1881 "private", Boolean(), nullable=True, unique=None, default=None)
1882 archived = Column(
1882 archived = Column(
1883 "archived", Boolean(), nullable=True, unique=None, default=None)
1883 "archived", Boolean(), nullable=True, unique=None, default=None)
1884 enable_statistics = Column(
1884 enable_statistics = Column(
1885 "statistics", Boolean(), nullable=True, unique=None, default=True)
1885 "statistics", Boolean(), nullable=True, unique=None, default=True)
1886 enable_downloads = Column(
1886 enable_downloads = Column(
1887 "downloads", Boolean(), nullable=True, unique=None, default=True)
1887 "downloads", Boolean(), nullable=True, unique=None, default=True)
1888 description = Column(
1888 description = Column(
1889 "description", String(10000), nullable=True, unique=None, default=None)
1889 "description", String(10000), nullable=True, unique=None, default=None)
1890 created_on = Column(
1890 created_on = Column(
1891 'created_on', DateTime(timezone=False), nullable=True, unique=None,
1891 'created_on', DateTime(timezone=False), nullable=True, unique=None,
1892 default=datetime.datetime.now)
1892 default=datetime.datetime.now)
1893 updated_on = Column(
1893 updated_on = Column(
1894 'updated_on', DateTime(timezone=False), nullable=True, unique=None,
1894 'updated_on', DateTime(timezone=False), nullable=True, unique=None,
1895 default=datetime.datetime.now)
1895 default=datetime.datetime.now)
1896 _landing_revision = Column(
1896 _landing_revision = Column(
1897 "landing_revision", String(255), nullable=False, unique=False,
1897 "landing_revision", String(255), nullable=False, unique=False,
1898 default=None)
1898 default=None)
1899 enable_locking = Column(
1899 enable_locking = Column(
1900 "enable_locking", Boolean(), nullable=False, unique=None,
1900 "enable_locking", Boolean(), nullable=False, unique=None,
1901 default=False)
1901 default=False)
1902 _locked = Column(
1902 _locked = Column(
1903 "locked", String(255), nullable=True, unique=False, default=None)
1903 "locked", String(255), nullable=True, unique=False, default=None)
1904 _changeset_cache = Column(
1904 _changeset_cache = Column(
1905 "changeset_cache", LargeBinary(), nullable=True) # JSON data
1905 "changeset_cache", LargeBinary(), nullable=True) # JSON data
1906
1906
1907 fork_id = Column(
1907 fork_id = Column(
1908 "fork_id", Integer(), ForeignKey('repositories.repo_id'),
1908 "fork_id", Integer(), ForeignKey('repositories.repo_id'),
1909 nullable=True, unique=False, default=None)
1909 nullable=True, unique=False, default=None)
1910 group_id = Column(
1910 group_id = Column(
1911 "group_id", Integer(), ForeignKey('groups.group_id'), nullable=True,
1911 "group_id", Integer(), ForeignKey('groups.group_id'), nullable=True,
1912 unique=False, default=None)
1912 unique=False, default=None)
1913
1913
1914 user = relationship('User', lazy='joined', back_populates='repositories')
1914 user = relationship('User', lazy='joined', back_populates='repositories')
1915 fork = relationship('Repository', remote_side=repo_id, lazy='joined')
1915 fork = relationship('Repository', remote_side=repo_id, lazy='joined')
1916 group = relationship('RepoGroup', lazy='joined')
1916 group = relationship('RepoGroup', lazy='joined')
1917 repo_to_perm = relationship('UserRepoToPerm', cascade='all', order_by='UserRepoToPerm.repo_to_perm_id')
1917 repo_to_perm = relationship('UserRepoToPerm', cascade='all', order_by='UserRepoToPerm.repo_to_perm_id')
1918 users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all', back_populates='repository')
1918 users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all', back_populates='repository')
1919 stats = relationship('Statistics', cascade='all', uselist=False)
1919 stats = relationship('Statistics', cascade='all', uselist=False)
1920
1920
1921 followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id', cascade='all', back_populates='follows_repository')
1921 followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id', cascade='all', back_populates='follows_repository')
1922 extra_fields = relationship('RepositoryField', cascade="all, delete-orphan", back_populates='repository')
1922 extra_fields = relationship('RepositoryField', cascade="all, delete-orphan", back_populates='repository')
1923
1923
1924 logs = relationship('UserLog', back_populates='repository')
1924 logs = relationship('UserLog', back_populates='repository')
1925
1925
1926 comments = relationship('ChangesetComment', cascade="all, delete-orphan", back_populates='repo')
1926 comments = relationship('ChangesetComment', cascade="all, delete-orphan", back_populates='repo')
1927
1927
1928 pull_requests_source = relationship(
1928 pull_requests_source = relationship(
1929 'PullRequest',
1929 'PullRequest',
1930 primaryjoin='PullRequest.source_repo_id==Repository.repo_id',
1930 primaryjoin='PullRequest.source_repo_id==Repository.repo_id',
1931 cascade="all, delete-orphan",
1931 cascade="all, delete-orphan",
1932 overlaps="source_repo"
1932 overlaps="source_repo"
1933 )
1933 )
1934 pull_requests_target = relationship(
1934 pull_requests_target = relationship(
1935 'PullRequest',
1935 'PullRequest',
1936 primaryjoin='PullRequest.target_repo_id==Repository.repo_id',
1936 primaryjoin='PullRequest.target_repo_id==Repository.repo_id',
1937 cascade="all, delete-orphan",
1937 cascade="all, delete-orphan",
1938 overlaps="target_repo"
1938 overlaps="target_repo"
1939 )
1939 )
1940
1940
1941 ui = relationship('RepoRhodeCodeUi', cascade="all")
1941 ui = relationship('RepoRhodeCodeUi', cascade="all")
1942 settings = relationship('RepoRhodeCodeSetting', cascade="all")
1942 settings = relationship('RepoRhodeCodeSetting', cascade="all")
1943 integrations = relationship('Integration', cascade="all, delete-orphan", back_populates='repo')
1943 integrations = relationship('Integration', cascade="all, delete-orphan", back_populates='repo')
1944
1944
1945 scoped_tokens = relationship('UserApiKeys', cascade="all", back_populates='repo')
1945 scoped_tokens = relationship('UserApiKeys', cascade="all", back_populates='repo')
1946
1946
1947 # no cascade, set NULL
1947 # no cascade, set NULL
1948 artifacts = relationship('FileStore', primaryjoin='FileStore.scope_repo_id==Repository.repo_id', viewonly=True)
1948 artifacts = relationship('FileStore', primaryjoin='FileStore.scope_repo_id==Repository.repo_id', viewonly=True)
1949
1949
1950 review_rules = relationship('RepoReviewRule')
1950 review_rules = relationship('RepoReviewRule')
1951 user_branch_perms = relationship('UserToRepoBranchPermission')
1951 user_branch_perms = relationship('UserToRepoBranchPermission')
1952 user_group_branch_perms = relationship('UserGroupToRepoBranchPermission')
1952 user_group_branch_perms = relationship('UserGroupToRepoBranchPermission')
1953
1953
1954 def __repr__(self):
1954 def __repr__(self):
1955 return "<%s('%s:%s')>" % (self.cls_name, self.repo_id, self.repo_name)
1955 return "<%s('%s:%s')>" % (self.cls_name, self.repo_id, self.repo_name)
1956
1956
1957 @hybrid_property
1957 @hybrid_property
1958 def description_safe(self):
1958 def description_safe(self):
1959 from rhodecode.lib import helpers as h
1959 from rhodecode.lib import helpers as h
1960 return h.escape(self.description)
1960 return h.escape(self.description)
1961
1961
1962 @hybrid_property
1962 @hybrid_property
1963 def landing_rev(self):
1963 def landing_rev(self):
1964 # always should return [rev_type, rev], e.g ['branch', 'master']
1964 # always should return [rev_type, rev], e.g ['branch', 'master']
1965 if self._landing_revision:
1965 if self._landing_revision:
1966 _rev_info = self._landing_revision.split(':')
1966 _rev_info = self._landing_revision.split(':')
1967 if len(_rev_info) < 2:
1967 if len(_rev_info) < 2:
1968 _rev_info.insert(0, 'rev')
1968 _rev_info.insert(0, 'rev')
1969 return [_rev_info[0], _rev_info[1]]
1969 return [_rev_info[0], _rev_info[1]]
1970 return [None, None]
1970 return [None, None]
1971
1971
1972 @property
1972 @property
1973 def landing_ref_type(self):
1973 def landing_ref_type(self):
1974 return self.landing_rev[0]
1974 return self.landing_rev[0]
1975
1975
1976 @property
1976 @property
1977 def landing_ref_name(self):
1977 def landing_ref_name(self):
1978 return self.landing_rev[1]
1978 return self.landing_rev[1]
1979
1979
1980 @landing_rev.setter
1980 @landing_rev.setter
1981 def landing_rev(self, val):
1981 def landing_rev(self, val):
1982 if ':' not in val:
1982 if ':' not in val:
1983 raise ValueError('value must be delimited with `:` and consist '
1983 raise ValueError('value must be delimited with `:` and consist '
1984 'of <rev_type>:<rev>, got %s instead' % val)
1984 'of <rev_type>:<rev>, got %s instead' % val)
1985 self._landing_revision = val
1985 self._landing_revision = val
1986
1986
1987 @hybrid_property
1987 @hybrid_property
1988 def locked(self):
1988 def locked(self):
1989 if self._locked:
1989 if self._locked:
1990 user_id, timelocked, reason = self._locked.split(':')
1990 user_id, timelocked, reason = self._locked.split(':')
1991 lock_values = int(user_id), timelocked, reason
1991 lock_values = int(user_id), timelocked, reason
1992 else:
1992 else:
1993 lock_values = [None, None, None]
1993 lock_values = [None, None, None]
1994 return lock_values
1994 return lock_values
1995
1995
1996 @locked.setter
1996 @locked.setter
1997 def locked(self, val):
1997 def locked(self, val):
1998 if val and isinstance(val, (list, tuple)):
1998 if val and isinstance(val, (list, tuple)):
1999 self._locked = ':'.join(map(str, val))
1999 self._locked = ':'.join(map(str, val))
2000 else:
2000 else:
2001 self._locked = None
2001 self._locked = None
2002
2002
2003 @classmethod
2003 @classmethod
2004 def _load_changeset_cache(cls, repo_id, changeset_cache_raw):
2004 def _load_changeset_cache(cls, repo_id, changeset_cache_raw):
2005 from rhodecode.lib.vcs.backends.base import EmptyCommit
2005 from rhodecode.lib.vcs.backends.base import EmptyCommit
2006 dummy = EmptyCommit().__json__()
2006 dummy = EmptyCommit().__json__()
2007 if not changeset_cache_raw:
2007 if not changeset_cache_raw:
2008 dummy['source_repo_id'] = repo_id
2008 dummy['source_repo_id'] = repo_id
2009 return json.loads(json.dumps(dummy))
2009 return json.loads(json.dumps(dummy))
2010
2010
2011 try:
2011 try:
2012 return json.loads(changeset_cache_raw)
2012 return json.loads(changeset_cache_raw)
2013 except TypeError:
2013 except TypeError:
2014 return dummy
2014 return dummy
2015 except Exception:
2015 except Exception:
2016 log.error(traceback.format_exc())
2016 log.error(traceback.format_exc())
2017 return dummy
2017 return dummy
2018
2018
2019 @hybrid_property
2019 @hybrid_property
2020 def changeset_cache(self):
2020 def changeset_cache(self):
2021 return self._load_changeset_cache(self.repo_id, self._changeset_cache)
2021 return self._load_changeset_cache(self.repo_id, self._changeset_cache)
2022
2022
2023 @changeset_cache.setter
2023 @changeset_cache.setter
2024 def changeset_cache(self, val):
2024 def changeset_cache(self, val):
2025 try:
2025 try:
2026 self._changeset_cache = json.dumps(val)
2026 self._changeset_cache = json.dumps(val)
2027 except Exception:
2027 except Exception:
2028 log.error(traceback.format_exc())
2028 log.error(traceback.format_exc())
2029
2029
2030 @hybrid_property
2030 @hybrid_property
2031 def repo_name(self):
2031 def repo_name(self):
2032 return self._repo_name
2032 return self._repo_name
2033
2033
2034 @repo_name.setter
2034 @repo_name.setter
2035 def repo_name(self, value):
2035 def repo_name(self, value):
2036 self._repo_name = value
2036 self._repo_name = value
2037 self.repo_name_hash = sha1(safe_bytes(value))
2037 self.repo_name_hash = sha1(safe_bytes(value))
2038
2038
2039 @classmethod
2039 @classmethod
2040 def normalize_repo_name(cls, repo_name):
2040 def normalize_repo_name(cls, repo_name):
2041 """
2041 """
2042 Normalizes os specific repo_name to the format internally stored inside
2042 Normalizes os specific repo_name to the format internally stored inside
2043 database using URL_SEP
2043 database using URL_SEP
2044
2044
2045 :param cls:
2045 :param cls:
2046 :param repo_name:
2046 :param repo_name:
2047 """
2047 """
2048 return cls.NAME_SEP.join(repo_name.split(os.sep))
2048 return cls.NAME_SEP.join(repo_name.split(os.sep))
2049
2049
2050 @classmethod
2050 @classmethod
2051 def get_by_repo_name(cls, repo_name, cache=False, identity_cache=False):
2051 def get_by_repo_name(cls, repo_name, cache=False, identity_cache=False):
2052 session = Session()
2052 session = Session()
2053 q = session.query(cls).filter(cls.repo_name == repo_name)
2053 q = session.query(cls).filter(cls.repo_name == repo_name)
2054
2054
2055 if cache:
2055 if cache:
2056 if identity_cache:
2056 if identity_cache:
2057 val = cls.identity_cache(session, 'repo_name', repo_name)
2057 val = cls.identity_cache(session, 'repo_name', repo_name)
2058 if val:
2058 if val:
2059 return val
2059 return val
2060 else:
2060 else:
2061 cache_key = f"get_repo_by_name_{_hash_key(repo_name)}"
2061 cache_key = f"get_repo_by_name_{_hash_key(repo_name)}"
2062 q = q.options(
2062 q = q.options(
2063 FromCache("sql_cache_short", cache_key))
2063 FromCache("sql_cache_short", cache_key))
2064
2064
2065 return q.scalar()
2065 return q.scalar()
2066
2066
2067 @classmethod
2067 @classmethod
2068 def get_by_id_or_repo_name(cls, repoid):
2068 def get_by_id_or_repo_name(cls, repoid):
2069 if isinstance(repoid, int):
2069 if isinstance(repoid, int):
2070 try:
2070 try:
2071 repo = cls.get(repoid)
2071 repo = cls.get(repoid)
2072 except ValueError:
2072 except ValueError:
2073 repo = None
2073 repo = None
2074 else:
2074 else:
2075 repo = cls.get_by_repo_name(repoid)
2075 repo = cls.get_by_repo_name(repoid)
2076 return repo
2076 return repo
2077
2077
2078 @classmethod
2078 @classmethod
2079 def get_by_full_path(cls, repo_full_path):
2079 def get_by_full_path(cls, repo_full_path):
2080 repo_name = repo_full_path.split(cls.base_path(), 1)[-1]
2080 repo_name = repo_full_path.split(cls.base_path(), 1)[-1]
2081 repo_name = cls.normalize_repo_name(repo_name)
2081 repo_name = cls.normalize_repo_name(repo_name)
2082 return cls.get_by_repo_name(repo_name.strip(URL_SEP))
2082 return cls.get_by_repo_name(repo_name.strip(URL_SEP))
2083
2083
2084 @classmethod
2084 @classmethod
2085 def get_repo_forks(cls, repo_id):
2085 def get_repo_forks(cls, repo_id):
2086 return cls.query().filter(Repository.fork_id == repo_id)
2086 return cls.query().filter(Repository.fork_id == repo_id)
2087
2087
2088 @classmethod
2088 @classmethod
2089 def base_path(cls):
2089 def base_path(cls):
2090 """
2090 """
2091 Returns base path when all repos are stored
2091 Returns base path when all repos are stored
2092
2092
2093 :param cls:
2093 :param cls:
2094 """
2094 """
2095 from rhodecode.lib.utils import get_rhodecode_repo_store_path
2095 from rhodecode.lib.utils import get_rhodecode_repo_store_path
2096 return get_rhodecode_repo_store_path()
2096 return get_rhodecode_repo_store_path()
2097
2097
2098 @classmethod
2098 @classmethod
2099 def get_all_repos(cls, user_id=Optional(None), group_id=Optional(None),
2099 def get_all_repos(cls, user_id=Optional(None), group_id=Optional(None),
2100 case_insensitive=True, archived=False):
2100 case_insensitive=True, archived=False):
2101 q = Repository.query()
2101 q = Repository.query()
2102
2102
2103 if not archived:
2103 if not archived:
2104 q = q.filter(Repository.archived.isnot(true()))
2104 q = q.filter(Repository.archived.isnot(true()))
2105
2105
2106 if not isinstance(user_id, Optional):
2106 if not isinstance(user_id, Optional):
2107 q = q.filter(Repository.user_id == user_id)
2107 q = q.filter(Repository.user_id == user_id)
2108
2108
2109 if not isinstance(group_id, Optional):
2109 if not isinstance(group_id, Optional):
2110 q = q.filter(Repository.group_id == group_id)
2110 q = q.filter(Repository.group_id == group_id)
2111
2111
2112 if case_insensitive:
2112 if case_insensitive:
2113 q = q.order_by(func.lower(Repository.repo_name))
2113 q = q.order_by(func.lower(Repository.repo_name))
2114 else:
2114 else:
2115 q = q.order_by(Repository.repo_name)
2115 q = q.order_by(Repository.repo_name)
2116
2116
2117 return q.all()
2117 return q.all()
2118
2118
2119 @property
2119 @property
2120 def repo_uid(self):
2120 def repo_uid(self):
2121 return '_{}'.format(self.repo_id)
2121 return '_{}'.format(self.repo_id)
2122
2122
2123 @property
2123 @property
2124 def forks(self):
2124 def forks(self):
2125 """
2125 """
2126 Return forks of this repo
2126 Return forks of this repo
2127 """
2127 """
2128 return Repository.get_repo_forks(self.repo_id)
2128 return Repository.get_repo_forks(self.repo_id)
2129
2129
2130 @property
2130 @property
2131 def parent(self):
2131 def parent(self):
2132 """
2132 """
2133 Returns fork parent
2133 Returns fork parent
2134 """
2134 """
2135 return self.fork
2135 return self.fork
2136
2136
2137 @property
2137 @property
2138 def just_name(self):
2138 def just_name(self):
2139 return self.repo_name.split(self.NAME_SEP)[-1]
2139 return self.repo_name.split(self.NAME_SEP)[-1]
2140
2140
2141 @property
2141 @property
2142 def groups_with_parents(self):
2142 def groups_with_parents(self):
2143 groups = []
2143 groups = []
2144 if self.group is None:
2144 if self.group is None:
2145 return groups
2145 return groups
2146
2146
2147 cur_gr = self.group
2147 cur_gr = self.group
2148 groups.insert(0, cur_gr)
2148 groups.insert(0, cur_gr)
2149 while 1:
2149 while 1:
2150 gr = getattr(cur_gr, 'parent_group', None)
2150 gr = getattr(cur_gr, 'parent_group', None)
2151 cur_gr = cur_gr.parent_group
2151 cur_gr = cur_gr.parent_group
2152 if gr is None:
2152 if gr is None:
2153 break
2153 break
2154 groups.insert(0, gr)
2154 groups.insert(0, gr)
2155
2155
2156 return groups
2156 return groups
2157
2157
2158 @property
2158 @property
2159 def groups_and_repo(self):
2159 def groups_and_repo(self):
2160 return self.groups_with_parents, self
2160 return self.groups_with_parents, self
2161
2161
2162 @property
2162 @property
2163 def repo_path(self):
2163 def repo_path(self):
2164 """
2164 """
2165 Returns base full path for that repository means where it actually
2165 Returns base full path for that repository means where it actually
2166 exists on a filesystem
2166 exists on a filesystem
2167 """
2167 """
2168 return self.base_path()
2168 return self.base_path()
2169
2169
2170 @property
2170 @property
2171 def repo_full_path(self):
2171 def repo_full_path(self):
2172 p = [self.repo_path]
2172 p = [self.repo_path]
2173 # we need to split the name by / since this is how we store the
2173 # we need to split the name by / since this is how we store the
2174 # names in the database, but that eventually needs to be converted
2174 # names in the database, but that eventually needs to be converted
2175 # into a valid system path
2175 # into a valid system path
2176 p += self.repo_name.split(self.NAME_SEP)
2176 p += self.repo_name.split(self.NAME_SEP)
2177 return os.path.join(*map(safe_str, p))
2177 return os.path.join(*map(safe_str, p))
2178
2178
2179 @property
2179 @property
2180 def cache_keys(self):
2180 def cache_keys(self):
2181 """
2181 """
2182 Returns associated cache keys for that repo
2182 Returns associated cache keys for that repo
2183 """
2183 """
2184 repo_namespace_key = CacheKey.REPO_INVALIDATION_NAMESPACE.format(repo_id=self.repo_id)
2184 repo_namespace_key = CacheKey.REPO_INVALIDATION_NAMESPACE.format(repo_id=self.repo_id)
2185 return CacheKey.query()\
2185 return CacheKey.query()\
2186 .filter(CacheKey.cache_key == repo_namespace_key)\
2186 .filter(CacheKey.cache_key == repo_namespace_key)\
2187 .order_by(CacheKey.cache_key)\
2187 .order_by(CacheKey.cache_key)\
2188 .all()
2188 .all()
2189
2189
2190 @property
2190 @property
2191 def cached_diffs_relative_dir(self):
2191 def cached_diffs_relative_dir(self):
2192 """
2192 """
2193 Return a relative to the repository store path of cached diffs
2193 Return a relative to the repository store path of cached diffs
2194 used for safe display for users, who shouldn't know the absolute store
2194 used for safe display for users, who shouldn't know the absolute store
2195 path
2195 path
2196 """
2196 """
2197 return os.path.join(
2197 return os.path.join(
2198 os.path.dirname(self.repo_name),
2198 os.path.dirname(self.repo_name),
2199 self.cached_diffs_dir.split(os.path.sep)[-1])
2199 self.cached_diffs_dir.split(os.path.sep)[-1])
2200
2200
2201 @property
2201 @property
2202 def cached_diffs_dir(self):
2202 def cached_diffs_dir(self):
2203 path = self.repo_full_path
2203 path = self.repo_full_path
2204 return os.path.join(
2204 return os.path.join(
2205 os.path.dirname(path),
2205 os.path.dirname(path),
2206 f'.__shadow_diff_cache_repo_{self.repo_id}')
2206 f'.__shadow_diff_cache_repo_{self.repo_id}')
2207
2207
2208 def cached_diffs(self):
2208 def cached_diffs(self):
2209 diff_cache_dir = self.cached_diffs_dir
2209 diff_cache_dir = self.cached_diffs_dir
2210 if os.path.isdir(diff_cache_dir):
2210 if os.path.isdir(diff_cache_dir):
2211 return os.listdir(diff_cache_dir)
2211 return os.listdir(diff_cache_dir)
2212 return []
2212 return []
2213
2213
2214 def shadow_repos(self):
2214 def shadow_repos(self):
2215 shadow_repos_pattern = f'.__shadow_repo_{self.repo_id}'
2215 shadow_repos_pattern = f'.__shadow_repo_{self.repo_id}'
2216 return [
2216 return [
2217 x for x in os.listdir(os.path.dirname(self.repo_full_path))
2217 x for x in os.listdir(os.path.dirname(self.repo_full_path))
2218 if x.startswith(shadow_repos_pattern)
2218 if x.startswith(shadow_repos_pattern)
2219 ]
2219 ]
2220
2220
2221 def get_new_name(self, repo_name):
2221 def get_new_name(self, repo_name):
2222 """
2222 """
2223 returns new full repository name based on assigned group and new new
2223 returns new full repository name based on assigned group and new new
2224
2224
2225 :param repo_name:
2225 :param repo_name:
2226 """
2226 """
2227 path_prefix = self.group.full_path_splitted if self.group else []
2227 path_prefix = self.group.full_path_splitted if self.group else []
2228 return self.NAME_SEP.join(path_prefix + [repo_name])
2228 return self.NAME_SEP.join(path_prefix + [repo_name])
2229
2229
2230 @property
2230 @property
2231 def _config(self):
2231 def _config(self):
2232 """
2232 """
2233 Returns db based config object.
2233 Returns db based config object.
2234 """
2234 """
2235 from rhodecode.lib.utils import make_db_config
2235 from rhodecode.lib.utils import make_db_config
2236 return make_db_config(clear_session=False, repo=self)
2236 return make_db_config(clear_session=False, repo=self)
2237
2237
2238 def permissions(self, with_admins=True, with_owner=True,
2238 def permissions(self, with_admins=True, with_owner=True,
2239 expand_from_user_groups=False):
2239 expand_from_user_groups=False):
2240 """
2240 """
2241 Permissions for repositories
2241 Permissions for repositories
2242 """
2242 """
2243 _admin_perm = 'repository.admin'
2243 _admin_perm = 'repository.admin'
2244
2244
2245 owner_row = []
2245 owner_row = []
2246 if with_owner:
2246 if with_owner:
2247 usr = AttributeDict(self.user.get_dict())
2247 usr = AttributeDict(self.user.get_dict())
2248 usr.owner_row = True
2248 usr.owner_row = True
2249 usr.permission = _admin_perm
2249 usr.permission = _admin_perm
2250 usr.permission_id = None
2250 usr.permission_id = None
2251 owner_row.append(usr)
2251 owner_row.append(usr)
2252
2252
2253 super_admin_ids = []
2253 super_admin_ids = []
2254 super_admin_rows = []
2254 super_admin_rows = []
2255 if with_admins:
2255 if with_admins:
2256 for usr in User.get_all_super_admins():
2256 for usr in User.get_all_super_admins():
2257 super_admin_ids.append(usr.user_id)
2257 super_admin_ids.append(usr.user_id)
2258 # if this admin is also owner, don't double the record
2258 # if this admin is also owner, don't double the record
2259 if usr.user_id == owner_row[0].user_id:
2259 if usr.user_id == owner_row[0].user_id:
2260 owner_row[0].admin_row = True
2260 owner_row[0].admin_row = True
2261 else:
2261 else:
2262 usr = AttributeDict(usr.get_dict())
2262 usr = AttributeDict(usr.get_dict())
2263 usr.admin_row = True
2263 usr.admin_row = True
2264 usr.permission = _admin_perm
2264 usr.permission = _admin_perm
2265 usr.permission_id = None
2265 usr.permission_id = None
2266 super_admin_rows.append(usr)
2266 super_admin_rows.append(usr)
2267
2267
2268 q = UserRepoToPerm.query().filter(UserRepoToPerm.repository == self)
2268 q = UserRepoToPerm.query().filter(UserRepoToPerm.repository == self)
2269 q = q.options(joinedload(UserRepoToPerm.repository),
2269 q = q.options(joinedload(UserRepoToPerm.repository),
2270 joinedload(UserRepoToPerm.user),
2270 joinedload(UserRepoToPerm.user),
2271 joinedload(UserRepoToPerm.permission),)
2271 joinedload(UserRepoToPerm.permission),)
2272
2272
2273 # get owners and admins and permissions. We do a trick of re-writing
2273 # get owners and admins and permissions. We do a trick of re-writing
2274 # objects from sqlalchemy to named-tuples due to sqlalchemy session
2274 # objects from sqlalchemy to named-tuples due to sqlalchemy session
2275 # has a global reference and changing one object propagates to all
2275 # has a global reference and changing one object propagates to all
2276 # others. This means if admin is also an owner admin_row that change
2276 # others. This means if admin is also an owner admin_row that change
2277 # would propagate to both objects
2277 # would propagate to both objects
2278 perm_rows = []
2278 perm_rows = []
2279 for _usr in q.all():
2279 for _usr in q.all():
2280 usr = AttributeDict(_usr.user.get_dict())
2280 usr = AttributeDict(_usr.user.get_dict())
2281 # if this user is also owner/admin, mark as duplicate record
2281 # if this user is also owner/admin, mark as duplicate record
2282 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
2282 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
2283 usr.duplicate_perm = True
2283 usr.duplicate_perm = True
2284 # also check if this permission is maybe used by branch_permissions
2284 # also check if this permission is maybe used by branch_permissions
2285 if _usr.branch_perm_entry:
2285 if _usr.branch_perm_entry:
2286 usr.branch_rules = [x.branch_rule_id for x in _usr.branch_perm_entry]
2286 usr.branch_rules = [x.branch_rule_id for x in _usr.branch_perm_entry]
2287
2287
2288 usr.permission = _usr.permission.permission_name
2288 usr.permission = _usr.permission.permission_name
2289 usr.permission_id = _usr.repo_to_perm_id
2289 usr.permission_id = _usr.repo_to_perm_id
2290 perm_rows.append(usr)
2290 perm_rows.append(usr)
2291
2291
2292 # filter the perm rows by 'default' first and then sort them by
2292 # filter the perm rows by 'default' first and then sort them by
2293 # admin,write,read,none permissions sorted again alphabetically in
2293 # admin,write,read,none permissions sorted again alphabetically in
2294 # each group
2294 # each group
2295 perm_rows = sorted(perm_rows, key=display_user_sort)
2295 perm_rows = sorted(perm_rows, key=display_user_sort)
2296
2296
2297 user_groups_rows = []
2297 user_groups_rows = []
2298 if expand_from_user_groups:
2298 if expand_from_user_groups:
2299 for ug in self.permission_user_groups(with_members=True):
2299 for ug in self.permission_user_groups(with_members=True):
2300 for user_data in ug.members:
2300 for user_data in ug.members:
2301 user_groups_rows.append(user_data)
2301 user_groups_rows.append(user_data)
2302
2302
2303 return super_admin_rows + owner_row + perm_rows + user_groups_rows
2303 return super_admin_rows + owner_row + perm_rows + user_groups_rows
2304
2304
2305 def permission_user_groups(self, with_members=True):
2305 def permission_user_groups(self, with_members=True):
2306 q = UserGroupRepoToPerm.query()\
2306 q = UserGroupRepoToPerm.query()\
2307 .filter(UserGroupRepoToPerm.repository == self)
2307 .filter(UserGroupRepoToPerm.repository == self)
2308 q = q.options(joinedload(UserGroupRepoToPerm.repository),
2308 q = q.options(joinedload(UserGroupRepoToPerm.repository),
2309 joinedload(UserGroupRepoToPerm.users_group),
2309 joinedload(UserGroupRepoToPerm.users_group),
2310 joinedload(UserGroupRepoToPerm.permission),)
2310 joinedload(UserGroupRepoToPerm.permission),)
2311
2311
2312 perm_rows = []
2312 perm_rows = []
2313 for _user_group in q.all():
2313 for _user_group in q.all():
2314 entry = AttributeDict(_user_group.users_group.get_dict())
2314 entry = AttributeDict(_user_group.users_group.get_dict())
2315 entry.permission = _user_group.permission.permission_name
2315 entry.permission = _user_group.permission.permission_name
2316 if with_members:
2316 if with_members:
2317 entry.members = [x.user.get_dict()
2317 entry.members = [x.user.get_dict()
2318 for x in _user_group.users_group.members]
2318 for x in _user_group.users_group.members]
2319 perm_rows.append(entry)
2319 perm_rows.append(entry)
2320
2320
2321 perm_rows = sorted(perm_rows, key=display_user_group_sort)
2321 perm_rows = sorted(perm_rows, key=display_user_group_sort)
2322 return perm_rows
2322 return perm_rows
2323
2323
2324 def get_api_data(self, include_secrets=False):
2324 def get_api_data(self, include_secrets=False):
2325 """
2325 """
2326 Common function for generating repo api data
2326 Common function for generating repo api data
2327
2327
2328 :param include_secrets: See :meth:`User.get_api_data`.
2328 :param include_secrets: See :meth:`User.get_api_data`.
2329
2329
2330 """
2330 """
2331 # TODO: mikhail: Here there is an anti-pattern, we probably need to
2331 # TODO: mikhail: Here there is an anti-pattern, we probably need to
2332 # move this methods on models level.
2332 # move this methods on models level.
2333 from rhodecode.model.settings import SettingsModel
2333 from rhodecode.model.settings import SettingsModel
2334 from rhodecode.model.repo import RepoModel
2334 from rhodecode.model.repo import RepoModel
2335
2335
2336 repo = self
2336 repo = self
2337 _user_id, _time, _reason = self.locked
2337 _user_id, _time, _reason = self.locked
2338
2338
2339 data = {
2339 data = {
2340 'repo_id': repo.repo_id,
2340 'repo_id': repo.repo_id,
2341 'repo_name': repo.repo_name,
2341 'repo_name': repo.repo_name,
2342 'repo_type': repo.repo_type,
2342 'repo_type': repo.repo_type,
2343 'clone_uri': repo.clone_uri or '',
2343 'clone_uri': repo.clone_uri or '',
2344 'push_uri': repo.push_uri or '',
2344 'push_uri': repo.push_uri or '',
2345 'url': RepoModel().get_url(self),
2345 'url': RepoModel().get_url(self),
2346 'private': repo.private,
2346 'private': repo.private,
2347 'created_on': repo.created_on,
2347 'created_on': repo.created_on,
2348 'description': repo.description_safe,
2348 'description': repo.description_safe,
2349 'landing_rev': repo.landing_rev,
2349 'landing_rev': repo.landing_rev,
2350 'owner': repo.user.username,
2350 'owner': repo.user.username,
2351 'fork_of': repo.fork.repo_name if repo.fork else None,
2351 'fork_of': repo.fork.repo_name if repo.fork else None,
2352 'fork_of_id': repo.fork.repo_id if repo.fork else None,
2352 'fork_of_id': repo.fork.repo_id if repo.fork else None,
2353 'enable_statistics': repo.enable_statistics,
2353 'enable_statistics': repo.enable_statistics,
2354 'enable_locking': repo.enable_locking,
2354 'enable_locking': repo.enable_locking,
2355 'enable_downloads': repo.enable_downloads,
2355 'enable_downloads': repo.enable_downloads,
2356 'last_changeset': repo.changeset_cache,
2356 'last_changeset': repo.changeset_cache,
2357 'locked_by': User.get(_user_id).get_api_data(
2357 'locked_by': User.get(_user_id).get_api_data(
2358 include_secrets=include_secrets) if _user_id else None,
2358 include_secrets=include_secrets) if _user_id else None,
2359 'locked_date': time_to_datetime(_time) if _time else None,
2359 'locked_date': time_to_datetime(_time) if _time else None,
2360 'lock_reason': _reason if _reason else None,
2360 'lock_reason': _reason if _reason else None,
2361 }
2361 }
2362
2362
2363 # TODO: mikhail: should be per-repo settings here
2363 # TODO: mikhail: should be per-repo settings here
2364 rc_config = SettingsModel().get_all_settings()
2364 rc_config = SettingsModel().get_all_settings()
2365 repository_fields = str2bool(
2365 repository_fields = str2bool(
2366 rc_config.get('rhodecode_repository_fields'))
2366 rc_config.get('rhodecode_repository_fields'))
2367 if repository_fields:
2367 if repository_fields:
2368 for f in self.extra_fields:
2368 for f in self.extra_fields:
2369 data[f.field_key_prefixed] = f.field_value
2369 data[f.field_key_prefixed] = f.field_value
2370
2370
2371 return data
2371 return data
2372
2372
2373 @classmethod
2373 @classmethod
2374 def lock(cls, repo, user_id, lock_time=None, lock_reason=None):
2374 def lock(cls, repo, user_id, lock_time=None, lock_reason=None):
2375 if not lock_time:
2375 if not lock_time:
2376 lock_time = time.time()
2376 lock_time = time.time()
2377 if not lock_reason:
2377 if not lock_reason:
2378 lock_reason = cls.LOCK_AUTOMATIC
2378 lock_reason = cls.LOCK_AUTOMATIC
2379 repo.locked = [user_id, lock_time, lock_reason]
2379 repo.locked = [user_id, lock_time, lock_reason]
2380 Session().add(repo)
2380 Session().add(repo)
2381 Session().commit()
2381 Session().commit()
2382
2382
2383 @classmethod
2383 @classmethod
2384 def unlock(cls, repo):
2384 def unlock(cls, repo):
2385 repo.locked = None
2385 repo.locked = None
2386 Session().add(repo)
2386 Session().add(repo)
2387 Session().commit()
2387 Session().commit()
2388
2388
2389 @classmethod
2389 @classmethod
2390 def getlock(cls, repo):
2390 def getlock(cls, repo):
2391 return repo.locked
2391 return repo.locked
2392
2392
2393 def get_locking_state(self, action, user_id, only_when_enabled=True):
2393 def get_locking_state(self, action, user_id, only_when_enabled=True):
2394 """
2394 """
2395 Checks locking on this repository, if locking is enabled and lock is
2395 Checks locking on this repository, if locking is enabled and lock is
2396 present returns a tuple of make_lock, locked, locked_by.
2396 present returns a tuple of make_lock, locked, locked_by.
2397 make_lock can have 3 states None (do nothing) True, make lock
2397 make_lock can have 3 states None (do nothing) True, make lock
2398 False release lock, This value is later propagated to hooks, which
2398 False release lock, This value is later propagated to hooks, which
2399 do the locking. Think about this as signals passed to hooks what to do.
2399 do the locking. Think about this as signals passed to hooks what to do.
2400
2400
2401 """
2401 """
2402 # TODO: johbo: This is part of the business logic and should be moved
2402 # TODO: johbo: This is part of the business logic and should be moved
2403 # into the RepositoryModel.
2403 # into the RepositoryModel.
2404
2404
2405 if action not in ('push', 'pull'):
2405 if action not in ('push', 'pull'):
2406 raise ValueError("Invalid action value: %s" % repr(action))
2406 raise ValueError("Invalid action value: %s" % repr(action))
2407
2407
2408 # defines if locked error should be thrown to user
2408 # defines if locked error should be thrown to user
2409 currently_locked = False
2409 currently_locked = False
2410 # defines if new lock should be made, tri-state
2410 # defines if new lock should be made, tri-state
2411 make_lock = None
2411 make_lock = None
2412 repo = self
2412 repo = self
2413 user = User.get(user_id)
2413 user = User.get(user_id)
2414
2414
2415 lock_info = repo.locked
2415 lock_info = repo.locked
2416
2416
2417 if repo and (repo.enable_locking or not only_when_enabled):
2417 if repo and (repo.enable_locking or not only_when_enabled):
2418 if action == 'push':
2418 if action == 'push':
2419 # check if it's already locked !, if it is compare users
2419 # check if it's already locked !, if it is compare users
2420 locked_by_user_id = lock_info[0]
2420 locked_by_user_id = lock_info[0]
2421 if user.user_id == locked_by_user_id:
2421 if user.user_id == locked_by_user_id:
2422 log.debug(
2422 log.debug(
2423 'Got `push` action from user %s, now unlocking', user)
2423 'Got `push` action from user %s, now unlocking', user)
2424 # unlock if we have push from user who locked
2424 # unlock if we have push from user who locked
2425 make_lock = False
2425 make_lock = False
2426 else:
2426 else:
2427 # we're not the same user who locked, ban with
2427 # we're not the same user who locked, ban with
2428 # code defined in settings (default is 423 HTTP Locked) !
2428 # code defined in settings (default is 423 HTTP Locked) !
2429 log.debug('Repo %s is currently locked by %s', repo, user)
2429 log.debug('Repo %s is currently locked by %s', repo, user)
2430 currently_locked = True
2430 currently_locked = True
2431 elif action == 'pull':
2431 elif action == 'pull':
2432 # [0] user [1] date
2432 # [0] user [1] date
2433 if lock_info[0] and lock_info[1]:
2433 if lock_info[0] and lock_info[1]:
2434 log.debug('Repo %s is currently locked by %s', repo, user)
2434 log.debug('Repo %s is currently locked by %s', repo, user)
2435 currently_locked = True
2435 currently_locked = True
2436 else:
2436 else:
2437 log.debug('Setting lock on repo %s by %s', repo, user)
2437 log.debug('Setting lock on repo %s by %s', repo, user)
2438 make_lock = True
2438 make_lock = True
2439
2439
2440 else:
2440 else:
2441 log.debug('Repository %s do not have locking enabled', repo)
2441 log.debug('Repository %s do not have locking enabled', repo)
2442
2442
2443 log.debug('FINAL locking values make_lock:%s,locked:%s,locked_by:%s',
2443 log.debug('FINAL locking values make_lock:%s,locked:%s,locked_by:%s',
2444 make_lock, currently_locked, lock_info)
2444 make_lock, currently_locked, lock_info)
2445
2445
2446 from rhodecode.lib.auth import HasRepoPermissionAny
2446 from rhodecode.lib.auth import HasRepoPermissionAny
2447 perm_check = HasRepoPermissionAny('repository.write', 'repository.admin')
2447 perm_check = HasRepoPermissionAny('repository.write', 'repository.admin')
2448 if make_lock and not perm_check(repo_name=repo.repo_name, user=user):
2448 if make_lock and not perm_check(repo_name=repo.repo_name, user=user):
2449 # if we don't have at least write permission we cannot make a lock
2449 # if we don't have at least write permission we cannot make a lock
2450 log.debug('lock state reset back to FALSE due to lack '
2450 log.debug('lock state reset back to FALSE due to lack '
2451 'of at least read permission')
2451 'of at least read permission')
2452 make_lock = False
2452 make_lock = False
2453
2453
2454 return make_lock, currently_locked, lock_info
2454 return make_lock, currently_locked, lock_info
2455
2455
2456 @property
2456 @property
2457 def last_commit_cache_update_diff(self):
2457 def last_commit_cache_update_diff(self):
2458 return time.time() - (safe_int(self.changeset_cache.get('updated_on')) or 0)
2458 return time.time() - (safe_int(self.changeset_cache.get('updated_on')) or 0)
2459
2459
2460 @classmethod
2460 @classmethod
2461 def _load_commit_change(cls, last_commit_cache):
2461 def _load_commit_change(cls, last_commit_cache):
2462 from rhodecode.lib.vcs.utils.helpers import parse_datetime
2462 from rhodecode.lib.vcs.utils.helpers import parse_datetime
2463 empty_date = datetime.datetime.fromtimestamp(0)
2463 empty_date = datetime.datetime.fromtimestamp(0)
2464 date_latest = last_commit_cache.get('date', empty_date)
2464 date_latest = last_commit_cache.get('date', empty_date)
2465 try:
2465 try:
2466 return parse_datetime(date_latest)
2466 return parse_datetime(date_latest)
2467 except Exception:
2467 except Exception:
2468 return empty_date
2468 return empty_date
2469
2469
2470 @property
2470 @property
2471 def last_commit_change(self):
2471 def last_commit_change(self):
2472 return self._load_commit_change(self.changeset_cache)
2472 return self._load_commit_change(self.changeset_cache)
2473
2473
2474 @property
2474 @property
2475 def last_db_change(self):
2475 def last_db_change(self):
2476 return self.updated_on
2476 return self.updated_on
2477
2477
2478 @property
2478 @property
2479 def clone_uri_hidden(self):
2479 def clone_uri_hidden(self):
2480 clone_uri = self.clone_uri
2480 clone_uri = self.clone_uri
2481 if clone_uri:
2481 if clone_uri:
2482 import urlobject
2482 import urlobject
2483 url_obj = urlobject.URLObject(cleaned_uri(clone_uri))
2483 url_obj = urlobject.URLObject(cleaned_uri(clone_uri))
2484 if url_obj.password:
2484 if url_obj.password:
2485 clone_uri = url_obj.with_password('*****')
2485 clone_uri = url_obj.with_password('*****')
2486 return clone_uri
2486 return clone_uri
2487
2487
2488 @property
2488 @property
2489 def push_uri_hidden(self):
2489 def push_uri_hidden(self):
2490 push_uri = self.push_uri
2490 push_uri = self.push_uri
2491 if push_uri:
2491 if push_uri:
2492 import urlobject
2492 import urlobject
2493 url_obj = urlobject.URLObject(cleaned_uri(push_uri))
2493 url_obj = urlobject.URLObject(cleaned_uri(push_uri))
2494 if url_obj.password:
2494 if url_obj.password:
2495 push_uri = url_obj.with_password('*****')
2495 push_uri = url_obj.with_password('*****')
2496 return push_uri
2496 return push_uri
2497
2497
2498 def clone_url(self, **override):
2498 def clone_url(self, **override):
2499 from rhodecode.model.settings import SettingsModel
2499 from rhodecode.model.settings import SettingsModel
2500
2500
2501 uri_tmpl = None
2501 uri_tmpl = None
2502 if 'with_id' in override:
2502 if 'with_id' in override:
2503 uri_tmpl = self.DEFAULT_CLONE_URI_ID
2503 uri_tmpl = self.DEFAULT_CLONE_URI_ID
2504 del override['with_id']
2504 del override['with_id']
2505
2505
2506 if 'uri_tmpl' in override:
2506 if 'uri_tmpl' in override:
2507 uri_tmpl = override['uri_tmpl']
2507 uri_tmpl = override['uri_tmpl']
2508 del override['uri_tmpl']
2508 del override['uri_tmpl']
2509
2509
2510 ssh = False
2510 ssh = False
2511 if 'ssh' in override:
2511 if 'ssh' in override:
2512 ssh = True
2512 ssh = True
2513 del override['ssh']
2513 del override['ssh']
2514
2514
2515 # we didn't override our tmpl from **overrides
2515 # we didn't override our tmpl from **overrides
2516 request = get_current_request()
2516 request = get_current_request()
2517 if not uri_tmpl:
2517 if not uri_tmpl:
2518 if hasattr(request, 'call_context') and hasattr(request.call_context, 'rc_config'):
2518 if hasattr(request, 'call_context') and hasattr(request.call_context, 'rc_config'):
2519 rc_config = request.call_context.rc_config
2519 rc_config = request.call_context.rc_config
2520 else:
2520 else:
2521 rc_config = SettingsModel().get_all_settings(cache=True)
2521 rc_config = SettingsModel().get_all_settings(cache=True)
2522
2522
2523 if ssh:
2523 if ssh:
2524 uri_tmpl = rc_config.get(
2524 uri_tmpl = rc_config.get(
2525 'rhodecode_clone_uri_ssh_tmpl') or self.DEFAULT_CLONE_URI_SSH
2525 'rhodecode_clone_uri_ssh_tmpl') or self.DEFAULT_CLONE_URI_SSH
2526
2526
2527 else:
2527 else:
2528 uri_tmpl = rc_config.get(
2528 uri_tmpl = rc_config.get(
2529 'rhodecode_clone_uri_tmpl') or self.DEFAULT_CLONE_URI
2529 'rhodecode_clone_uri_tmpl') or self.DEFAULT_CLONE_URI
2530
2530
2531 return get_clone_url(request=request,
2531 return get_clone_url(request=request,
2532 uri_tmpl=uri_tmpl,
2532 uri_tmpl=uri_tmpl,
2533 repo_name=self.repo_name,
2533 repo_name=self.repo_name,
2534 repo_id=self.repo_id,
2534 repo_id=self.repo_id,
2535 repo_type=self.repo_type,
2535 repo_type=self.repo_type,
2536 **override)
2536 **override)
2537
2537
2538 def set_state(self, state):
2538 def set_state(self, state):
2539 self.repo_state = state
2539 self.repo_state = state
2540 Session().add(self)
2540 Session().add(self)
2541 #==========================================================================
2541 #==========================================================================
2542 # SCM PROPERTIES
2542 # SCM PROPERTIES
2543 #==========================================================================
2543 #==========================================================================
2544
2544
2545 def get_commit(self, commit_id=None, commit_idx=None, pre_load=None, maybe_unreachable=False, reference_obj=None):
2545 def get_commit(self, commit_id=None, commit_idx=None, pre_load=None, maybe_unreachable=False, reference_obj=None):
2546 return get_commit_safe(
2546 return get_commit_safe(
2547 self.scm_instance(), commit_id, commit_idx, pre_load=pre_load,
2547 self.scm_instance(), commit_id, commit_idx, pre_load=pre_load,
2548 maybe_unreachable=maybe_unreachable, reference_obj=reference_obj)
2548 maybe_unreachable=maybe_unreachable, reference_obj=reference_obj)
2549
2549
2550 def get_changeset(self, rev=None, pre_load=None):
2550 def get_changeset(self, rev=None, pre_load=None):
2551 warnings.warn("Use get_commit", DeprecationWarning)
2551 warnings.warn("Use get_commit", DeprecationWarning)
2552 commit_id = None
2552 commit_id = None
2553 commit_idx = None
2553 commit_idx = None
2554 if isinstance(rev, str):
2554 if isinstance(rev, str):
2555 commit_id = rev
2555 commit_id = rev
2556 else:
2556 else:
2557 commit_idx = rev
2557 commit_idx = rev
2558 return self.get_commit(commit_id=commit_id, commit_idx=commit_idx,
2558 return self.get_commit(commit_id=commit_id, commit_idx=commit_idx,
2559 pre_load=pre_load)
2559 pre_load=pre_load)
2560
2560
2561 def get_landing_commit(self):
2561 def get_landing_commit(self):
2562 """
2562 """
2563 Returns landing commit, or if that doesn't exist returns the tip
2563 Returns landing commit, or if that doesn't exist returns the tip
2564 """
2564 """
2565 _rev_type, _rev = self.landing_rev
2565 _rev_type, _rev = self.landing_rev
2566 commit = self.get_commit(_rev)
2566 commit = self.get_commit(_rev)
2567 if isinstance(commit, EmptyCommit):
2567 if isinstance(commit, EmptyCommit):
2568 return self.get_commit()
2568 return self.get_commit()
2569 return commit
2569 return commit
2570
2570
2571 def flush_commit_cache(self):
2571 def flush_commit_cache(self):
2572 self.update_commit_cache(cs_cache={'raw_id':'0'})
2572 self.update_commit_cache(cs_cache={'raw_id':'0'})
2573 self.update_commit_cache()
2573 self.update_commit_cache()
2574
2574
2575 def update_commit_cache(self, cs_cache=None, config=None):
2575 def update_commit_cache(self, cs_cache=None, config=None):
2576 """
2576 """
2577 Update cache of last commit for repository
2577 Update cache of last commit for repository
2578 cache_keys should be::
2578 cache_keys should be::
2579
2579
2580 source_repo_id
2580 source_repo_id
2581 short_id
2581 short_id
2582 raw_id
2582 raw_id
2583 revision
2583 revision
2584 parents
2584 parents
2585 message
2585 message
2586 date
2586 date
2587 author
2587 author
2588 updated_on
2588 updated_on
2589
2589
2590 """
2590 """
2591 from rhodecode.lib.vcs.backends.base import BaseCommit
2591 from rhodecode.lib.vcs.backends.base import BaseCommit
2592 from rhodecode.lib.vcs.utils.helpers import parse_datetime
2592 from rhodecode.lib.vcs.utils.helpers import parse_datetime
2593 empty_date = datetime.datetime.fromtimestamp(0)
2593 empty_date = datetime.datetime.fromtimestamp(0)
2594 repo_commit_count = 0
2594 repo_commit_count = 0
2595
2595
2596 if cs_cache is None:
2596 if cs_cache is None:
2597 # use no-cache version here
2597 # use no-cache version here
2598 try:
2598 try:
2599 scm_repo = self.scm_instance(cache=False, config=config)
2599 scm_repo = self.scm_instance(cache=False, config=config)
2600 except VCSError:
2600 except VCSError:
2601 scm_repo = None
2601 scm_repo = None
2602 empty = scm_repo is None or scm_repo.is_empty()
2602 empty = scm_repo is None or scm_repo.is_empty()
2603
2603
2604 if not empty:
2604 if not empty:
2605 cs_cache = scm_repo.get_commit(
2605 cs_cache = scm_repo.get_commit(
2606 pre_load=["author", "date", "message", "parents", "branch"])
2606 pre_load=["author", "date", "message", "parents", "branch"])
2607 repo_commit_count = scm_repo.count()
2607 repo_commit_count = scm_repo.count()
2608 else:
2608 else:
2609 cs_cache = EmptyCommit()
2609 cs_cache = EmptyCommit()
2610
2610
2611 if isinstance(cs_cache, BaseCommit):
2611 if isinstance(cs_cache, BaseCommit):
2612 cs_cache = cs_cache.__json__()
2612 cs_cache = cs_cache.__json__()
2613
2613
2614 def is_outdated(new_cs_cache):
2614 def is_outdated(new_cs_cache):
2615 if (new_cs_cache['raw_id'] != self.changeset_cache['raw_id'] or
2615 if (new_cs_cache['raw_id'] != self.changeset_cache['raw_id'] or
2616 new_cs_cache['revision'] != self.changeset_cache['revision']):
2616 new_cs_cache['revision'] != self.changeset_cache['revision']):
2617 return True
2617 return True
2618 return False
2618 return False
2619
2619
2620 # check if we have maybe already latest cached revision
2620 # check if we have maybe already latest cached revision
2621 if is_outdated(cs_cache) or not self.changeset_cache:
2621 if is_outdated(cs_cache) or not self.changeset_cache:
2622 _current_datetime = datetime.datetime.utcnow()
2622 _current_datetime = datetime.datetime.utcnow()
2623 last_change = cs_cache.get('date') or _current_datetime
2623 last_change = cs_cache.get('date') or _current_datetime
2624 # we check if last update is newer than the new value
2624 # we check if last update is newer than the new value
2625 # if yes, we use the current timestamp instead. Imagine you get
2625 # if yes, we use the current timestamp instead. Imagine you get
2626 # old commit pushed 1y ago, we'd set last update 1y to ago.
2626 # old commit pushed 1y ago, we'd set last update 1y to ago.
2627 last_change_timestamp = datetime_to_time(last_change)
2627 last_change_timestamp = datetime_to_time(last_change)
2628 current_timestamp = datetime_to_time(last_change)
2628 current_timestamp = datetime_to_time(last_change)
2629 if last_change_timestamp > current_timestamp and not empty:
2629 if last_change_timestamp > current_timestamp and not empty:
2630 cs_cache['date'] = _current_datetime
2630 cs_cache['date'] = _current_datetime
2631
2631
2632 # also store size of repo
2632 # also store size of repo
2633 cs_cache['repo_commit_count'] = repo_commit_count
2633 cs_cache['repo_commit_count'] = repo_commit_count
2634
2634
2635 _date_latest = parse_datetime(cs_cache.get('date') or empty_date)
2635 _date_latest = parse_datetime(cs_cache.get('date') or empty_date)
2636 cs_cache['updated_on'] = time.time()
2636 cs_cache['updated_on'] = time.time()
2637 self.changeset_cache = cs_cache
2637 self.changeset_cache = cs_cache
2638 self.updated_on = last_change
2638 self.updated_on = last_change
2639 Session().add(self)
2639 Session().add(self)
2640 Session().commit()
2640 Session().commit()
2641
2641
2642 else:
2642 else:
2643 if empty:
2643 if empty:
2644 cs_cache = EmptyCommit().__json__()
2644 cs_cache = EmptyCommit().__json__()
2645 else:
2645 else:
2646 cs_cache = self.changeset_cache
2646 cs_cache = self.changeset_cache
2647
2647
2648 _date_latest = parse_datetime(cs_cache.get('date') or empty_date)
2648 _date_latest = parse_datetime(cs_cache.get('date') or empty_date)
2649
2649
2650 cs_cache['updated_on'] = time.time()
2650 cs_cache['updated_on'] = time.time()
2651 self.changeset_cache = cs_cache
2651 self.changeset_cache = cs_cache
2652 self.updated_on = _date_latest
2652 self.updated_on = _date_latest
2653 Session().add(self)
2653 Session().add(self)
2654 Session().commit()
2654 Session().commit()
2655
2655
2656 log.debug('updated repo `%s` with new commit cache %s, and last update_date: %s',
2656 log.debug('updated repo `%s` with new commit cache %s, and last update_date: %s',
2657 self.repo_name, cs_cache, _date_latest)
2657 self.repo_name, cs_cache, _date_latest)
2658
2658
2659 @property
2659 @property
2660 def tip(self):
2660 def tip(self):
2661 return self.get_commit('tip')
2661 return self.get_commit('tip')
2662
2662
2663 @property
2663 @property
2664 def author(self):
2664 def author(self):
2665 return self.tip.author
2665 return self.tip.author
2666
2666
2667 @property
2667 @property
2668 def last_change(self):
2668 def last_change(self):
2669 return self.scm_instance().last_change
2669 return self.scm_instance().last_change
2670
2670
2671 def get_comments(self, revisions=None):
2671 def get_comments(self, revisions=None):
2672 """
2672 """
2673 Returns comments for this repository grouped by revisions
2673 Returns comments for this repository grouped by revisions
2674
2674
2675 :param revisions: filter query by revisions only
2675 :param revisions: filter query by revisions only
2676 """
2676 """
2677 cmts = ChangesetComment.query()\
2677 cmts = ChangesetComment.query()\
2678 .filter(ChangesetComment.repo == self)
2678 .filter(ChangesetComment.repo == self)
2679 if revisions:
2679 if revisions:
2680 cmts = cmts.filter(ChangesetComment.revision.in_(revisions))
2680 cmts = cmts.filter(ChangesetComment.revision.in_(revisions))
2681 grouped = collections.defaultdict(list)
2681 grouped = collections.defaultdict(list)
2682 for cmt in cmts.all():
2682 for cmt in cmts.all():
2683 grouped[cmt.revision].append(cmt)
2683 grouped[cmt.revision].append(cmt)
2684 return grouped
2684 return grouped
2685
2685
2686 def statuses(self, revisions=None):
2686 def statuses(self, revisions=None):
2687 """
2687 """
2688 Returns statuses for this repository
2688 Returns statuses for this repository
2689
2689
2690 :param revisions: list of revisions to get statuses for
2690 :param revisions: list of revisions to get statuses for
2691 """
2691 """
2692 statuses = ChangesetStatus.query()\
2692 statuses = ChangesetStatus.query()\
2693 .filter(ChangesetStatus.repo == self)\
2693 .filter(ChangesetStatus.repo == self)\
2694 .filter(ChangesetStatus.version == 0)
2694 .filter(ChangesetStatus.version == 0)
2695
2695
2696 if revisions:
2696 if revisions:
2697 # Try doing the filtering in chunks to avoid hitting limits
2697 # Try doing the filtering in chunks to avoid hitting limits
2698 size = 500
2698 size = 500
2699 status_results = []
2699 status_results = []
2700 for chunk in range(0, len(revisions), size):
2700 for chunk in range(0, len(revisions), size):
2701 status_results += statuses.filter(
2701 status_results += statuses.filter(
2702 ChangesetStatus.revision.in_(
2702 ChangesetStatus.revision.in_(
2703 revisions[chunk: chunk+size])
2703 revisions[chunk: chunk+size])
2704 ).all()
2704 ).all()
2705 else:
2705 else:
2706 status_results = statuses.all()
2706 status_results = statuses.all()
2707
2707
2708 grouped = {}
2708 grouped = {}
2709
2709
2710 # maybe we have open new pullrequest without a status?
2710 # maybe we have open new pullrequest without a status?
2711 stat = ChangesetStatus.STATUS_UNDER_REVIEW
2711 stat = ChangesetStatus.STATUS_UNDER_REVIEW
2712 status_lbl = ChangesetStatus.get_status_lbl(stat)
2712 status_lbl = ChangesetStatus.get_status_lbl(stat)
2713 for pr in PullRequest.query().filter(PullRequest.source_repo == self).all():
2713 for pr in PullRequest.query().filter(PullRequest.source_repo == self).all():
2714 for rev in pr.revisions:
2714 for rev in pr.revisions:
2715 pr_id = pr.pull_request_id
2715 pr_id = pr.pull_request_id
2716 pr_repo = pr.target_repo.repo_name
2716 pr_repo = pr.target_repo.repo_name
2717 grouped[rev] = [stat, status_lbl, pr_id, pr_repo]
2717 grouped[rev] = [stat, status_lbl, pr_id, pr_repo]
2718
2718
2719 for stat in status_results:
2719 for stat in status_results:
2720 pr_id = pr_repo = None
2720 pr_id = pr_repo = None
2721 if stat.pull_request:
2721 if stat.pull_request:
2722 pr_id = stat.pull_request.pull_request_id
2722 pr_id = stat.pull_request.pull_request_id
2723 pr_repo = stat.pull_request.target_repo.repo_name
2723 pr_repo = stat.pull_request.target_repo.repo_name
2724 grouped[stat.revision] = [str(stat.status), stat.status_lbl,
2724 grouped[stat.revision] = [str(stat.status), stat.status_lbl,
2725 pr_id, pr_repo]
2725 pr_id, pr_repo]
2726 return grouped
2726 return grouped
2727
2727
2728 # ==========================================================================
2728 # ==========================================================================
2729 # SCM CACHE INSTANCE
2729 # SCM CACHE INSTANCE
2730 # ==========================================================================
2730 # ==========================================================================
2731
2731
2732 def scm_instance(self, **kwargs):
2732 def scm_instance(self, **kwargs):
2733 import rhodecode
2733 import rhodecode
2734
2734
2735 # Passing a config will not hit the cache currently only used
2735 # Passing a config will not hit the cache currently only used
2736 # for repo2dbmapper
2736 # for repo2dbmapper
2737 config = kwargs.pop('config', None)
2737 config = kwargs.pop('config', None)
2738 cache = kwargs.pop('cache', None)
2738 cache = kwargs.pop('cache', None)
2739 vcs_full_cache = kwargs.pop('vcs_full_cache', None)
2739 vcs_full_cache = kwargs.pop('vcs_full_cache', None)
2740 if vcs_full_cache is not None:
2740 if vcs_full_cache is not None:
2741 # allows override global config
2741 # allows override global config
2742 full_cache = vcs_full_cache
2742 full_cache = vcs_full_cache
2743 else:
2743 else:
2744 full_cache = rhodecode.ConfigGet().get_bool('vcs_full_cache')
2744 full_cache = rhodecode.ConfigGet().get_bool('vcs_full_cache')
2745 # if cache is NOT defined use default global, else we have a full
2745 # if cache is NOT defined use default global, else we have a full
2746 # control over cache behaviour
2746 # control over cache behaviour
2747 if cache is None and full_cache and not config:
2747 if cache is None and full_cache and not config:
2748 log.debug('Initializing pure cached instance for %s', self.repo_path)
2748 log.debug('Initializing pure cached instance for %s', self.repo_path)
2749 return self._get_instance_cached()
2749 return self._get_instance_cached()
2750
2750
2751 # cache here is sent to the "vcs server"
2751 # cache here is sent to the "vcs server"
2752 return self._get_instance(cache=bool(cache), config=config)
2752 return self._get_instance(cache=bool(cache), config=config)
2753
2753
2754 def _get_instance_cached(self):
2754 def _get_instance_cached(self):
2755 from rhodecode.lib import rc_cache
2755 from rhodecode.lib import rc_cache
2756
2756
2757 cache_namespace_uid = f'repo_instance.{self.repo_id}'
2757 cache_namespace_uid = f'repo_instance.{self.repo_id}'
2758 region = rc_cache.get_or_create_region('cache_repo_longterm', cache_namespace_uid)
2758 region = rc_cache.get_or_create_region('cache_repo_longterm', cache_namespace_uid)
2759
2759
2760 # we must use thread scoped cache here,
2760 # we must use thread scoped cache here,
2761 # because each thread of gevent needs it's own not shared connection and cache
2761 # because each thread of gevent needs it's own not shared connection and cache
2762 # we also alter `args` so the cache key is individual for every green thread.
2762 # we also alter `args` so the cache key is individual for every green thread.
2763 repo_namespace_key = CacheKey.REPO_INVALIDATION_NAMESPACE.format(repo_id=self.repo_id)
2763 repo_namespace_key = CacheKey.REPO_INVALIDATION_NAMESPACE.format(repo_id=self.repo_id)
2764 inv_context_manager = rc_cache.InvalidationContext(key=repo_namespace_key, thread_scoped=True)
2764 inv_context_manager = rc_cache.InvalidationContext(key=repo_namespace_key, thread_scoped=True)
2765
2765
2766 # our wrapped caching function that takes state_uid to save the previous state in
2766 # our wrapped caching function that takes state_uid to save the previous state in
2767 def cache_generator(_state_uid):
2767 def cache_generator(_state_uid):
2768
2768
2769 @region.conditional_cache_on_arguments(namespace=cache_namespace_uid)
2769 @region.conditional_cache_on_arguments(namespace=cache_namespace_uid)
2770 def get_instance_cached(_repo_id, _process_context_id):
2770 def get_instance_cached(_repo_id, _process_context_id):
2771 # we save in cached func the generation state so we can detect a change and invalidate caches
2771 # we save in cached func the generation state so we can detect a change and invalidate caches
2772 return _state_uid, self._get_instance(repo_state_uid=_state_uid)
2772 return _state_uid, self._get_instance(repo_state_uid=_state_uid)
2773
2773
2774 return get_instance_cached
2774 return get_instance_cached
2775
2775
2776 with inv_context_manager as invalidation_context:
2776 with inv_context_manager as invalidation_context:
2777 cache_state_uid = invalidation_context.state_uid
2777 cache_state_uid = invalidation_context.state_uid
2778 cache_func = cache_generator(cache_state_uid)
2778 cache_func = cache_generator(cache_state_uid)
2779
2779
2780 args = self.repo_id, inv_context_manager.proc_key
2780 args = self.repo_id, inv_context_manager.proc_key
2781
2781
2782 previous_state_uid, instance = cache_func(*args)
2782 previous_state_uid, instance = cache_func(*args)
2783
2783
2784 # now compare keys, the "cache" state vs expected state.
2784 # now compare keys, the "cache" state vs expected state.
2785 if previous_state_uid != cache_state_uid:
2785 if previous_state_uid != cache_state_uid:
2786 log.warning('Cached state uid %s is different than current state uid %s',
2786 log.warning('Cached state uid %s is different than current state uid %s',
2787 previous_state_uid, cache_state_uid)
2787 previous_state_uid, cache_state_uid)
2788 _, instance = cache_func.refresh(*args)
2788 _, instance = cache_func.refresh(*args)
2789
2789
2790 log.debug('Repo instance fetched in %.4fs', inv_context_manager.compute_time)
2790 log.debug('Repo instance fetched in %.4fs', inv_context_manager.compute_time)
2791 return instance
2791 return instance
2792
2792
2793 def _get_instance(self, cache=True, config=None, repo_state_uid=None):
2793 def _get_instance(self, cache=True, config=None, repo_state_uid=None):
2794 log.debug('Initializing %s instance `%s` with cache flag set to: %s',
2794 log.debug('Initializing %s instance `%s` with cache flag set to: %s',
2795 self.repo_type, self.repo_path, cache)
2795 self.repo_type, self.repo_path, cache)
2796 config = config or self._config
2796 config = config or self._config
2797 custom_wire = {
2797 custom_wire = {
2798 'cache': cache, # controls the vcs.remote cache
2798 'cache': cache, # controls the vcs.remote cache
2799 'repo_state_uid': repo_state_uid
2799 'repo_state_uid': repo_state_uid
2800 }
2800 }
2801
2801
2802 repo = get_vcs_instance(
2802 repo = get_vcs_instance(
2803 repo_path=safe_str(self.repo_full_path),
2803 repo_path=safe_str(self.repo_full_path),
2804 config=config,
2804 config=config,
2805 with_wire=custom_wire,
2805 with_wire=custom_wire,
2806 create=False,
2806 create=False,
2807 _vcs_alias=self.repo_type)
2807 _vcs_alias=self.repo_type)
2808 if repo is not None:
2808 if repo is not None:
2809 repo.count() # cache rebuild
2809 repo.count() # cache rebuild
2810
2810
2811 return repo
2811 return repo
2812
2812
2813 def get_shadow_repository_path(self, workspace_id):
2813 def get_shadow_repository_path(self, workspace_id):
2814 from rhodecode.lib.vcs.backends.base import BaseRepository
2814 from rhodecode.lib.vcs.backends.base import BaseRepository
2815 shadow_repo_path = BaseRepository._get_shadow_repository_path(
2815 shadow_repo_path = BaseRepository._get_shadow_repository_path(
2816 self.repo_full_path, self.repo_id, workspace_id)
2816 self.repo_full_path, self.repo_id, workspace_id)
2817 return shadow_repo_path
2817 return shadow_repo_path
2818
2818
2819 def __json__(self):
2819 def __json__(self):
2820 return {'landing_rev': self.landing_rev}
2820 return {'landing_rev': self.landing_rev}
2821
2821
2822 def get_dict(self):
2822 def get_dict(self):
2823
2823
2824 # Since we transformed `repo_name` to a hybrid property, we need to
2824 # Since we transformed `repo_name` to a hybrid property, we need to
2825 # keep compatibility with the code which uses `repo_name` field.
2825 # keep compatibility with the code which uses `repo_name` field.
2826
2826
2827 result = super(Repository, self).get_dict()
2827 result = super(Repository, self).get_dict()
2828 result['repo_name'] = result.pop('_repo_name', None)
2828 result['repo_name'] = result.pop('_repo_name', None)
2829 result.pop('_changeset_cache', '')
2829 result.pop('_changeset_cache', '')
2830 return result
2830 return result
2831
2831
2832
2832
2833 class RepoGroup(Base, BaseModel):
2833 class RepoGroup(Base, BaseModel):
2834 __tablename__ = 'groups'
2834 __tablename__ = 'groups'
2835 __table_args__ = (
2835 __table_args__ = (
2836 UniqueConstraint('group_name', 'group_parent_id'),
2836 UniqueConstraint('group_name', 'group_parent_id'),
2837 base_table_args,
2837 base_table_args,
2838 )
2838 )
2839
2839
2840 CHOICES_SEPARATOR = '/' # used to generate select2 choices for nested groups
2840 CHOICES_SEPARATOR = '/' # used to generate select2 choices for nested groups
2841
2841
2842 group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2842 group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2843 _group_name = Column("group_name", String(255), nullable=False, unique=True, default=None)
2843 _group_name = Column("group_name", String(255), nullable=False, unique=True, default=None)
2844 group_name_hash = Column("repo_group_name_hash", String(1024), nullable=False, unique=False)
2844 group_name_hash = Column("repo_group_name_hash", String(1024), nullable=False, unique=False)
2845 group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
2845 group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
2846 group_description = Column("group_description", String(10000), nullable=True, unique=None, default=None)
2846 group_description = Column("group_description", String(10000), nullable=True, unique=None, default=None)
2847 enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
2847 enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
2848 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
2848 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
2849 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
2849 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
2850 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
2850 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
2851 personal = Column('personal', Boolean(), nullable=True, unique=None, default=None)
2851 personal = Column('personal', Boolean(), nullable=True, unique=None, default=None)
2852 _changeset_cache = Column("changeset_cache", LargeBinary(), nullable=True) # JSON data
2852 _changeset_cache = Column("changeset_cache", LargeBinary(), nullable=True) # JSON data
2853
2853
2854 repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id', back_populates='group')
2854 repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id', back_populates='group')
2855 users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all', back_populates='group')
2855 users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all', back_populates='group')
2856 parent_group = relationship('RepoGroup', remote_side=group_id)
2856 parent_group = relationship('RepoGroup', remote_side=group_id)
2857 user = relationship('User', back_populates='repository_groups')
2857 user = relationship('User', back_populates='repository_groups')
2858 integrations = relationship('Integration', cascade="all, delete-orphan", back_populates='repo_group')
2858 integrations = relationship('Integration', cascade="all, delete-orphan", back_populates='repo_group')
2859
2859
2860 # no cascade, set NULL
2860 # no cascade, set NULL
2861 scope_artifacts = relationship('FileStore', primaryjoin='FileStore.scope_repo_group_id==RepoGroup.group_id', viewonly=True)
2861 scope_artifacts = relationship('FileStore', primaryjoin='FileStore.scope_repo_group_id==RepoGroup.group_id', viewonly=True)
2862
2862
2863 def __init__(self, group_name='', parent_group=None):
2863 def __init__(self, group_name='', parent_group=None):
2864 self.group_name = group_name
2864 self.group_name = group_name
2865 self.parent_group = parent_group
2865 self.parent_group = parent_group
2866
2866
2867 def __repr__(self):
2867 def __repr__(self):
2868 return f"<{self.cls_name}('id:{self.group_id}:{self.group_name}')>"
2868 return f"<{self.cls_name}('id:{self.group_id}:{self.group_name}')>"
2869
2869
2870 @hybrid_property
2870 @hybrid_property
2871 def group_name(self):
2871 def group_name(self):
2872 return self._group_name
2872 return self._group_name
2873
2873
2874 @group_name.setter
2874 @group_name.setter
2875 def group_name(self, value):
2875 def group_name(self, value):
2876 self._group_name = value
2876 self._group_name = value
2877 self.group_name_hash = self.hash_repo_group_name(value)
2877 self.group_name_hash = self.hash_repo_group_name(value)
2878
2878
2879 @classmethod
2879 @classmethod
2880 def _load_changeset_cache(cls, repo_id, changeset_cache_raw):
2880 def _load_changeset_cache(cls, repo_id, changeset_cache_raw):
2881 from rhodecode.lib.vcs.backends.base import EmptyCommit
2881 from rhodecode.lib.vcs.backends.base import EmptyCommit
2882 dummy = EmptyCommit().__json__()
2882 dummy = EmptyCommit().__json__()
2883 if not changeset_cache_raw:
2883 if not changeset_cache_raw:
2884 dummy['source_repo_id'] = repo_id
2884 dummy['source_repo_id'] = repo_id
2885 return json.loads(json.dumps(dummy))
2885 return json.loads(json.dumps(dummy))
2886
2886
2887 try:
2887 try:
2888 return json.loads(changeset_cache_raw)
2888 return json.loads(changeset_cache_raw)
2889 except TypeError:
2889 except TypeError:
2890 return dummy
2890 return dummy
2891 except Exception:
2891 except Exception:
2892 log.error(traceback.format_exc())
2892 log.error(traceback.format_exc())
2893 return dummy
2893 return dummy
2894
2894
2895 @hybrid_property
2895 @hybrid_property
2896 def changeset_cache(self):
2896 def changeset_cache(self):
2897 return self._load_changeset_cache('', self._changeset_cache)
2897 return self._load_changeset_cache('', self._changeset_cache)
2898
2898
2899 @changeset_cache.setter
2899 @changeset_cache.setter
2900 def changeset_cache(self, val):
2900 def changeset_cache(self, val):
2901 try:
2901 try:
2902 self._changeset_cache = json.dumps(val)
2902 self._changeset_cache = json.dumps(val)
2903 except Exception:
2903 except Exception:
2904 log.error(traceback.format_exc())
2904 log.error(traceback.format_exc())
2905
2905
2906 @validates('group_parent_id')
2906 @validates('group_parent_id')
2907 def validate_group_parent_id(self, key, val):
2907 def validate_group_parent_id(self, key, val):
2908 """
2908 """
2909 Check cycle references for a parent group to self
2909 Check cycle references for a parent group to self
2910 """
2910 """
2911 if self.group_id and val:
2911 if self.group_id and val:
2912 assert val != self.group_id
2912 assert val != self.group_id
2913
2913
2914 return val
2914 return val
2915
2915
2916 @hybrid_property
2916 @hybrid_property
2917 def description_safe(self):
2917 def description_safe(self):
2918 from rhodecode.lib import helpers as h
2918 from rhodecode.lib import helpers as h
2919 return h.escape(self.group_description)
2919 return h.escape(self.group_description)
2920
2920
2921 @classmethod
2921 @classmethod
2922 def hash_repo_group_name(cls, repo_group_name):
2922 def hash_repo_group_name(cls, repo_group_name):
2923 val = remove_formatting(repo_group_name)
2923 val = remove_formatting(repo_group_name)
2924 val = safe_str(val).lower()
2924 val = safe_str(val).lower()
2925 chars = []
2925 chars = []
2926 for c in val:
2926 for c in val:
2927 if c not in string.ascii_letters:
2927 if c not in string.ascii_letters:
2928 c = str(ord(c))
2928 c = str(ord(c))
2929 chars.append(c)
2929 chars.append(c)
2930
2930
2931 return ''.join(chars)
2931 return ''.join(chars)
2932
2932
2933 @classmethod
2933 @classmethod
2934 def _generate_choice(cls, repo_group):
2934 def _generate_choice(cls, repo_group):
2935 from webhelpers2.html import literal as _literal
2935 from webhelpers2.html import literal as _literal
2936
2936
2937 def _name(k):
2937 def _name(k):
2938 return _literal(cls.CHOICES_SEPARATOR.join(k))
2938 return _literal(cls.CHOICES_SEPARATOR.join(k))
2939
2939
2940 return repo_group.group_id, _name(repo_group.full_path_splitted)
2940 return repo_group.group_id, _name(repo_group.full_path_splitted)
2941
2941
2942 @classmethod
2942 @classmethod
2943 def groups_choices(cls, groups=None, show_empty_group=True):
2943 def groups_choices(cls, groups=None, show_empty_group=True):
2944 if not groups:
2944 if not groups:
2945 groups = cls.query().all()
2945 groups = cls.query().all()
2946
2946
2947 repo_groups = []
2947 repo_groups = []
2948 if show_empty_group:
2948 if show_empty_group:
2949 repo_groups = [(-1, '-- %s --' % _('No parent'))]
2949 repo_groups = [(-1, '-- %s --' % _('No parent'))]
2950
2950
2951 repo_groups.extend([cls._generate_choice(x) for x in groups])
2951 repo_groups.extend([cls._generate_choice(x) for x in groups])
2952
2952
2953 repo_groups = sorted(
2953 repo_groups = sorted(
2954 repo_groups, key=lambda t: t[1].split(cls.CHOICES_SEPARATOR)[0])
2954 repo_groups, key=lambda t: t[1].split(cls.CHOICES_SEPARATOR)[0])
2955 return repo_groups
2955 return repo_groups
2956
2956
2957 @classmethod
2957 @classmethod
2958 def url_sep(cls):
2958 def url_sep(cls):
2959 return URL_SEP
2959 return URL_SEP
2960
2960
2961 @classmethod
2961 @classmethod
2962 def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
2962 def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
2963 if case_insensitive:
2963 if case_insensitive:
2964 gr = cls.query().filter(func.lower(cls.group_name)
2964 gr = cls.query().filter(func.lower(cls.group_name)
2965 == func.lower(group_name))
2965 == func.lower(group_name))
2966 else:
2966 else:
2967 gr = cls.query().filter(cls.group_name == group_name)
2967 gr = cls.query().filter(cls.group_name == group_name)
2968 if cache:
2968 if cache:
2969 name_key = _hash_key(group_name)
2969 name_key = _hash_key(group_name)
2970 gr = gr.options(
2970 gr = gr.options(
2971 FromCache("sql_cache_short", f"get_group_{name_key}"))
2971 FromCache("sql_cache_short", f"get_group_{name_key}"))
2972 return gr.scalar()
2972 return gr.scalar()
2973
2973
2974 @classmethod
2974 @classmethod
2975 def get_user_personal_repo_group(cls, user_id):
2975 def get_user_personal_repo_group(cls, user_id):
2976 user = User.get(user_id)
2976 user = User.get(user_id)
2977 if user.username == User.DEFAULT_USER:
2977 if user.username == User.DEFAULT_USER:
2978 return None
2978 return None
2979
2979
2980 return cls.query()\
2980 return cls.query()\
2981 .filter(cls.personal == true()) \
2981 .filter(cls.personal == true()) \
2982 .filter(cls.user == user) \
2982 .filter(cls.user == user) \
2983 .order_by(cls.group_id.asc()) \
2983 .order_by(cls.group_id.asc()) \
2984 .first()
2984 .first()
2985
2985
2986 @classmethod
2986 @classmethod
2987 def get_all_repo_groups(cls, user_id=Optional(None), group_id=Optional(None),
2987 def get_all_repo_groups(cls, user_id=Optional(None), group_id=Optional(None),
2988 case_insensitive=True):
2988 case_insensitive=True):
2989 q = RepoGroup.query()
2989 q = RepoGroup.query()
2990
2990
2991 if not isinstance(user_id, Optional):
2991 if not isinstance(user_id, Optional):
2992 q = q.filter(RepoGroup.user_id == user_id)
2992 q = q.filter(RepoGroup.user_id == user_id)
2993
2993
2994 if not isinstance(group_id, Optional):
2994 if not isinstance(group_id, Optional):
2995 q = q.filter(RepoGroup.group_parent_id == group_id)
2995 q = q.filter(RepoGroup.group_parent_id == group_id)
2996
2996
2997 if case_insensitive:
2997 if case_insensitive:
2998 q = q.order_by(func.lower(RepoGroup.group_name))
2998 q = q.order_by(func.lower(RepoGroup.group_name))
2999 else:
2999 else:
3000 q = q.order_by(RepoGroup.group_name)
3000 q = q.order_by(RepoGroup.group_name)
3001 return q.all()
3001 return q.all()
3002
3002
3003 @property
3003 @property
3004 def parents(self, parents_recursion_limit=10):
3004 def parents(self, parents_recursion_limit=10):
3005 groups = []
3005 groups = []
3006 if self.parent_group is None:
3006 if self.parent_group is None:
3007 return groups
3007 return groups
3008 cur_gr = self.parent_group
3008 cur_gr = self.parent_group
3009 groups.insert(0, cur_gr)
3009 groups.insert(0, cur_gr)
3010 cnt = 0
3010 cnt = 0
3011 while 1:
3011 while 1:
3012 cnt += 1
3012 cnt += 1
3013 gr = getattr(cur_gr, 'parent_group', None)
3013 gr = getattr(cur_gr, 'parent_group', None)
3014 cur_gr = cur_gr.parent_group
3014 cur_gr = cur_gr.parent_group
3015 if gr is None:
3015 if gr is None:
3016 break
3016 break
3017 if cnt == parents_recursion_limit:
3017 if cnt == parents_recursion_limit:
3018 # this will prevent accidental infinit loops
3018 # this will prevent accidental infinit loops
3019 log.error('more than %s parents found for group %s, stopping '
3019 log.error('more than %s parents found for group %s, stopping '
3020 'recursive parent fetching', parents_recursion_limit, self)
3020 'recursive parent fetching', parents_recursion_limit, self)
3021 break
3021 break
3022
3022
3023 groups.insert(0, gr)
3023 groups.insert(0, gr)
3024 return groups
3024 return groups
3025
3025
3026 @property
3026 @property
3027 def last_commit_cache_update_diff(self):
3027 def last_commit_cache_update_diff(self):
3028 return time.time() - (safe_int(self.changeset_cache.get('updated_on')) or 0)
3028 return time.time() - (safe_int(self.changeset_cache.get('updated_on')) or 0)
3029
3029
3030 @classmethod
3030 @classmethod
3031 def _load_commit_change(cls, last_commit_cache):
3031 def _load_commit_change(cls, last_commit_cache):
3032 from rhodecode.lib.vcs.utils.helpers import parse_datetime
3032 from rhodecode.lib.vcs.utils.helpers import parse_datetime
3033 empty_date = datetime.datetime.fromtimestamp(0)
3033 empty_date = datetime.datetime.fromtimestamp(0)
3034 date_latest = last_commit_cache.get('date', empty_date)
3034 date_latest = last_commit_cache.get('date', empty_date)
3035 try:
3035 try:
3036 return parse_datetime(date_latest)
3036 return parse_datetime(date_latest)
3037 except Exception:
3037 except Exception:
3038 return empty_date
3038 return empty_date
3039
3039
3040 @property
3040 @property
3041 def last_commit_change(self):
3041 def last_commit_change(self):
3042 return self._load_commit_change(self.changeset_cache)
3042 return self._load_commit_change(self.changeset_cache)
3043
3043
3044 @property
3044 @property
3045 def last_db_change(self):
3045 def last_db_change(self):
3046 return self.updated_on
3046 return self.updated_on
3047
3047
3048 @property
3048 @property
3049 def children(self):
3049 def children(self):
3050 return RepoGroup.query().filter(RepoGroup.parent_group == self)
3050 return RepoGroup.query().filter(RepoGroup.parent_group == self)
3051
3051
3052 @property
3052 @property
3053 def name(self):
3053 def name(self):
3054 return self.group_name.split(RepoGroup.url_sep())[-1]
3054 return self.group_name.split(RepoGroup.url_sep())[-1]
3055
3055
3056 @property
3056 @property
3057 def full_path(self):
3057 def full_path(self):
3058 return self.group_name
3058 return self.group_name
3059
3059
3060 @property
3060 @property
3061 def full_path_splitted(self):
3061 def full_path_splitted(self):
3062 return self.group_name.split(RepoGroup.url_sep())
3062 return self.group_name.split(RepoGroup.url_sep())
3063
3063
3064 @property
3064 @property
3065 def repositories(self):
3065 def repositories(self):
3066 return Repository.query()\
3066 return Repository.query()\
3067 .filter(Repository.group == self)\
3067 .filter(Repository.group == self)\
3068 .order_by(Repository.repo_name)
3068 .order_by(Repository.repo_name)
3069
3069
3070 @property
3070 @property
3071 def repositories_recursive_count(self):
3071 def repositories_recursive_count(self):
3072 cnt = self.repositories.count()
3072 cnt = self.repositories.count()
3073
3073
3074 def children_count(group):
3074 def children_count(group):
3075 cnt = 0
3075 cnt = 0
3076 for child in group.children:
3076 for child in group.children:
3077 cnt += child.repositories.count()
3077 cnt += child.repositories.count()
3078 cnt += children_count(child)
3078 cnt += children_count(child)
3079 return cnt
3079 return cnt
3080
3080
3081 return cnt + children_count(self)
3081 return cnt + children_count(self)
3082
3082
3083 def _recursive_objects(self, include_repos=True, include_groups=True):
3083 def _recursive_objects(self, include_repos=True, include_groups=True):
3084 all_ = []
3084 all_ = []
3085
3085
3086 def _get_members(root_gr):
3086 def _get_members(root_gr):
3087 if include_repos:
3087 if include_repos:
3088 for r in root_gr.repositories:
3088 for r in root_gr.repositories:
3089 all_.append(r)
3089 all_.append(r)
3090 childs = root_gr.children.all()
3090 childs = root_gr.children.all()
3091 if childs:
3091 if childs:
3092 for gr in childs:
3092 for gr in childs:
3093 if include_groups:
3093 if include_groups:
3094 all_.append(gr)
3094 all_.append(gr)
3095 _get_members(gr)
3095 _get_members(gr)
3096
3096
3097 root_group = []
3097 root_group = []
3098 if include_groups:
3098 if include_groups:
3099 root_group = [self]
3099 root_group = [self]
3100
3100
3101 _get_members(self)
3101 _get_members(self)
3102 return root_group + all_
3102 return root_group + all_
3103
3103
3104 def recursive_groups_and_repos(self):
3104 def recursive_groups_and_repos(self):
3105 """
3105 """
3106 Recursive return all groups, with repositories in those groups
3106 Recursive return all groups, with repositories in those groups
3107 """
3107 """
3108 return self._recursive_objects()
3108 return self._recursive_objects()
3109
3109
3110 def recursive_groups(self):
3110 def recursive_groups(self):
3111 """
3111 """
3112 Returns all children groups for this group including children of children
3112 Returns all children groups for this group including children of children
3113 """
3113 """
3114 return self._recursive_objects(include_repos=False)
3114 return self._recursive_objects(include_repos=False)
3115
3115
3116 def recursive_repos(self):
3116 def recursive_repos(self):
3117 """
3117 """
3118 Returns all children repositories for this group
3118 Returns all children repositories for this group
3119 """
3119 """
3120 return self._recursive_objects(include_groups=False)
3120 return self._recursive_objects(include_groups=False)
3121
3121
3122 def get_new_name(self, group_name):
3122 def get_new_name(self, group_name):
3123 """
3123 """
3124 returns new full group name based on parent and new name
3124 returns new full group name based on parent and new name
3125
3125
3126 :param group_name:
3126 :param group_name:
3127 """
3127 """
3128 path_prefix = (self.parent_group.full_path_splitted if
3128 path_prefix = (self.parent_group.full_path_splitted if
3129 self.parent_group else [])
3129 self.parent_group else [])
3130 return RepoGroup.url_sep().join(path_prefix + [group_name])
3130 return RepoGroup.url_sep().join(path_prefix + [group_name])
3131
3131
3132 def update_commit_cache(self, config=None):
3132 def update_commit_cache(self, config=None):
3133 """
3133 """
3134 Update cache of last commit for newest repository inside this repository group.
3134 Update cache of last commit for newest repository inside this repository group.
3135 cache_keys should be::
3135 cache_keys should be::
3136
3136
3137 source_repo_id
3137 source_repo_id
3138 short_id
3138 short_id
3139 raw_id
3139 raw_id
3140 revision
3140 revision
3141 parents
3141 parents
3142 message
3142 message
3143 date
3143 date
3144 author
3144 author
3145
3145
3146 """
3146 """
3147 from rhodecode.lib.vcs.utils.helpers import parse_datetime
3147 from rhodecode.lib.vcs.utils.helpers import parse_datetime
3148 empty_date = datetime.datetime.fromtimestamp(0)
3148 empty_date = datetime.datetime.fromtimestamp(0)
3149
3149
3150 def repo_groups_and_repos(root_gr):
3150 def repo_groups_and_repos(root_gr):
3151 for _repo in root_gr.repositories:
3151 for _repo in root_gr.repositories:
3152 yield _repo
3152 yield _repo
3153 for child_group in root_gr.children.all():
3153 for child_group in root_gr.children.all():
3154 yield child_group
3154 yield child_group
3155
3155
3156 latest_repo_cs_cache = {}
3156 latest_repo_cs_cache = {}
3157 for obj in repo_groups_and_repos(self):
3157 for obj in repo_groups_and_repos(self):
3158 repo_cs_cache = obj.changeset_cache
3158 repo_cs_cache = obj.changeset_cache
3159 date_latest = latest_repo_cs_cache.get('date', empty_date)
3159 date_latest = latest_repo_cs_cache.get('date', empty_date)
3160 date_current = repo_cs_cache.get('date', empty_date)
3160 date_current = repo_cs_cache.get('date', empty_date)
3161 current_timestamp = datetime_to_time(parse_datetime(date_latest))
3161 current_timestamp = datetime_to_time(parse_datetime(date_latest))
3162 if current_timestamp < datetime_to_time(parse_datetime(date_current)):
3162 if current_timestamp < datetime_to_time(parse_datetime(date_current)):
3163 latest_repo_cs_cache = repo_cs_cache
3163 latest_repo_cs_cache = repo_cs_cache
3164 if hasattr(obj, 'repo_id'):
3164 if hasattr(obj, 'repo_id'):
3165 latest_repo_cs_cache['source_repo_id'] = obj.repo_id
3165 latest_repo_cs_cache['source_repo_id'] = obj.repo_id
3166 else:
3166 else:
3167 latest_repo_cs_cache['source_repo_id'] = repo_cs_cache.get('source_repo_id')
3167 latest_repo_cs_cache['source_repo_id'] = repo_cs_cache.get('source_repo_id')
3168
3168
3169 _date_latest = parse_datetime(latest_repo_cs_cache.get('date') or empty_date)
3169 _date_latest = parse_datetime(latest_repo_cs_cache.get('date') or empty_date)
3170
3170
3171 latest_repo_cs_cache['updated_on'] = time.time()
3171 latest_repo_cs_cache['updated_on'] = time.time()
3172 self.changeset_cache = latest_repo_cs_cache
3172 self.changeset_cache = latest_repo_cs_cache
3173 self.updated_on = _date_latest
3173 self.updated_on = _date_latest
3174 Session().add(self)
3174 Session().add(self)
3175 Session().commit()
3175 Session().commit()
3176
3176
3177 log.debug('updated repo group `%s` with new commit cache %s, and last update_date: %s',
3177 log.debug('updated repo group `%s` with new commit cache %s, and last update_date: %s',
3178 self.group_name, latest_repo_cs_cache, _date_latest)
3178 self.group_name, latest_repo_cs_cache, _date_latest)
3179
3179
3180 def permissions(self, with_admins=True, with_owner=True,
3180 def permissions(self, with_admins=True, with_owner=True,
3181 expand_from_user_groups=False):
3181 expand_from_user_groups=False):
3182 """
3182 """
3183 Permissions for repository groups
3183 Permissions for repository groups
3184 """
3184 """
3185 _admin_perm = 'group.admin'
3185 _admin_perm = 'group.admin'
3186
3186
3187 owner_row = []
3187 owner_row = []
3188 if with_owner:
3188 if with_owner:
3189 usr = AttributeDict(self.user.get_dict())
3189 usr = AttributeDict(self.user.get_dict())
3190 usr.owner_row = True
3190 usr.owner_row = True
3191 usr.permission = _admin_perm
3191 usr.permission = _admin_perm
3192 owner_row.append(usr)
3192 owner_row.append(usr)
3193
3193
3194 super_admin_ids = []
3194 super_admin_ids = []
3195 super_admin_rows = []
3195 super_admin_rows = []
3196 if with_admins:
3196 if with_admins:
3197 for usr in User.get_all_super_admins():
3197 for usr in User.get_all_super_admins():
3198 super_admin_ids.append(usr.user_id)
3198 super_admin_ids.append(usr.user_id)
3199 # if this admin is also owner, don't double the record
3199 # if this admin is also owner, don't double the record
3200 if usr.user_id == owner_row[0].user_id:
3200 if usr.user_id == owner_row[0].user_id:
3201 owner_row[0].admin_row = True
3201 owner_row[0].admin_row = True
3202 else:
3202 else:
3203 usr = AttributeDict(usr.get_dict())
3203 usr = AttributeDict(usr.get_dict())
3204 usr.admin_row = True
3204 usr.admin_row = True
3205 usr.permission = _admin_perm
3205 usr.permission = _admin_perm
3206 super_admin_rows.append(usr)
3206 super_admin_rows.append(usr)
3207
3207
3208 q = UserRepoGroupToPerm.query().filter(UserRepoGroupToPerm.group == self)
3208 q = UserRepoGroupToPerm.query().filter(UserRepoGroupToPerm.group == self)
3209 q = q.options(joinedload(UserRepoGroupToPerm.group),
3209 q = q.options(joinedload(UserRepoGroupToPerm.group),
3210 joinedload(UserRepoGroupToPerm.user),
3210 joinedload(UserRepoGroupToPerm.user),
3211 joinedload(UserRepoGroupToPerm.permission),)
3211 joinedload(UserRepoGroupToPerm.permission),)
3212
3212
3213 # get owners and admins and permissions. We do a trick of re-writing
3213 # get owners and admins and permissions. We do a trick of re-writing
3214 # objects from sqlalchemy to named-tuples due to sqlalchemy session
3214 # objects from sqlalchemy to named-tuples due to sqlalchemy session
3215 # has a global reference and changing one object propagates to all
3215 # has a global reference and changing one object propagates to all
3216 # others. This means if admin is also an owner admin_row that change
3216 # others. This means if admin is also an owner admin_row that change
3217 # would propagate to both objects
3217 # would propagate to both objects
3218 perm_rows = []
3218 perm_rows = []
3219 for _usr in q.all():
3219 for _usr in q.all():
3220 usr = AttributeDict(_usr.user.get_dict())
3220 usr = AttributeDict(_usr.user.get_dict())
3221 # if this user is also owner/admin, mark as duplicate record
3221 # if this user is also owner/admin, mark as duplicate record
3222 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
3222 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
3223 usr.duplicate_perm = True
3223 usr.duplicate_perm = True
3224 usr.permission = _usr.permission.permission_name
3224 usr.permission = _usr.permission.permission_name
3225 perm_rows.append(usr)
3225 perm_rows.append(usr)
3226
3226
3227 # filter the perm rows by 'default' first and then sort them by
3227 # filter the perm rows by 'default' first and then sort them by
3228 # admin,write,read,none permissions sorted again alphabetically in
3228 # admin,write,read,none permissions sorted again alphabetically in
3229 # each group
3229 # each group
3230 perm_rows = sorted(perm_rows, key=display_user_sort)
3230 perm_rows = sorted(perm_rows, key=display_user_sort)
3231
3231
3232 user_groups_rows = []
3232 user_groups_rows = []
3233 if expand_from_user_groups:
3233 if expand_from_user_groups:
3234 for ug in self.permission_user_groups(with_members=True):
3234 for ug in self.permission_user_groups(with_members=True):
3235 for user_data in ug.members:
3235 for user_data in ug.members:
3236 user_groups_rows.append(user_data)
3236 user_groups_rows.append(user_data)
3237
3237
3238 return super_admin_rows + owner_row + perm_rows + user_groups_rows
3238 return super_admin_rows + owner_row + perm_rows + user_groups_rows
3239
3239
3240 def permission_user_groups(self, with_members=False):
3240 def permission_user_groups(self, with_members=False):
3241 q = UserGroupRepoGroupToPerm.query()\
3241 q = UserGroupRepoGroupToPerm.query()\
3242 .filter(UserGroupRepoGroupToPerm.group == self)
3242 .filter(UserGroupRepoGroupToPerm.group == self)
3243 q = q.options(joinedload(UserGroupRepoGroupToPerm.group),
3243 q = q.options(joinedload(UserGroupRepoGroupToPerm.group),
3244 joinedload(UserGroupRepoGroupToPerm.users_group),
3244 joinedload(UserGroupRepoGroupToPerm.users_group),
3245 joinedload(UserGroupRepoGroupToPerm.permission),)
3245 joinedload(UserGroupRepoGroupToPerm.permission),)
3246
3246
3247 perm_rows = []
3247 perm_rows = []
3248 for _user_group in q.all():
3248 for _user_group in q.all():
3249 entry = AttributeDict(_user_group.users_group.get_dict())
3249 entry = AttributeDict(_user_group.users_group.get_dict())
3250 entry.permission = _user_group.permission.permission_name
3250 entry.permission = _user_group.permission.permission_name
3251 if with_members:
3251 if with_members:
3252 entry.members = [x.user.get_dict()
3252 entry.members = [x.user.get_dict()
3253 for x in _user_group.users_group.members]
3253 for x in _user_group.users_group.members]
3254 perm_rows.append(entry)
3254 perm_rows.append(entry)
3255
3255
3256 perm_rows = sorted(perm_rows, key=display_user_group_sort)
3256 perm_rows = sorted(perm_rows, key=display_user_group_sort)
3257 return perm_rows
3257 return perm_rows
3258
3258
3259 def get_api_data(self):
3259 def get_api_data(self):
3260 """
3260 """
3261 Common function for generating api data
3261 Common function for generating api data
3262
3262
3263 """
3263 """
3264 group = self
3264 group = self
3265 data = {
3265 data = {
3266 'group_id': group.group_id,
3266 'group_id': group.group_id,
3267 'group_name': group.group_name,
3267 'group_name': group.group_name,
3268 'group_description': group.description_safe,
3268 'group_description': group.description_safe,
3269 'parent_group': group.parent_group.group_name if group.parent_group else None,
3269 'parent_group': group.parent_group.group_name if group.parent_group else None,
3270 'repositories': [x.repo_name for x in group.repositories],
3270 'repositories': [x.repo_name for x in group.repositories],
3271 'owner': group.user.username,
3271 'owner': group.user.username,
3272 }
3272 }
3273 return data
3273 return data
3274
3274
3275 def get_dict(self):
3275 def get_dict(self):
3276 # Since we transformed `group_name` to a hybrid property, we need to
3276 # Since we transformed `group_name` to a hybrid property, we need to
3277 # keep compatibility with the code which uses `group_name` field.
3277 # keep compatibility with the code which uses `group_name` field.
3278 result = super(RepoGroup, self).get_dict()
3278 result = super(RepoGroup, self).get_dict()
3279 result['group_name'] = result.pop('_group_name', None)
3279 result['group_name'] = result.pop('_group_name', None)
3280 result.pop('_changeset_cache', '')
3280 result.pop('_changeset_cache', '')
3281 return result
3281 return result
3282
3282
3283
3283
3284 class Permission(Base, BaseModel):
3284 class Permission(Base, BaseModel):
3285 __tablename__ = 'permissions'
3285 __tablename__ = 'permissions'
3286 __table_args__ = (
3286 __table_args__ = (
3287 Index('p_perm_name_idx', 'permission_name'),
3287 Index('p_perm_name_idx', 'permission_name'),
3288 base_table_args,
3288 base_table_args,
3289 )
3289 )
3290
3290
3291 PERMS = [
3291 PERMS = [
3292 ('hg.admin', _('RhodeCode Super Administrator')),
3292 ('hg.admin', _('RhodeCode Super Administrator')),
3293
3293
3294 ('repository.none', _('Repository no access')),
3294 ('repository.none', _('Repository no access')),
3295 ('repository.read', _('Repository read access')),
3295 ('repository.read', _('Repository read access')),
3296 ('repository.write', _('Repository write access')),
3296 ('repository.write', _('Repository write access')),
3297 ('repository.admin', _('Repository admin access')),
3297 ('repository.admin', _('Repository admin access')),
3298
3298
3299 ('group.none', _('Repository group no access')),
3299 ('group.none', _('Repository group no access')),
3300 ('group.read', _('Repository group read access')),
3300 ('group.read', _('Repository group read access')),
3301 ('group.write', _('Repository group write access')),
3301 ('group.write', _('Repository group write access')),
3302 ('group.admin', _('Repository group admin access')),
3302 ('group.admin', _('Repository group admin access')),
3303
3303
3304 ('usergroup.none', _('User group no access')),
3304 ('usergroup.none', _('User group no access')),
3305 ('usergroup.read', _('User group read access')),
3305 ('usergroup.read', _('User group read access')),
3306 ('usergroup.write', _('User group write access')),
3306 ('usergroup.write', _('User group write access')),
3307 ('usergroup.admin', _('User group admin access')),
3307 ('usergroup.admin', _('User group admin access')),
3308
3308
3309 ('branch.none', _('Branch no permissions')),
3309 ('branch.none', _('Branch no permissions')),
3310 ('branch.merge', _('Branch access by web merge')),
3310 ('branch.merge', _('Branch access by web merge')),
3311 ('branch.push', _('Branch access by push')),
3311 ('branch.push', _('Branch access by push')),
3312 ('branch.push_force', _('Branch access by push with force')),
3312 ('branch.push_force', _('Branch access by push with force')),
3313
3313
3314 ('hg.repogroup.create.false', _('Repository Group creation disabled')),
3314 ('hg.repogroup.create.false', _('Repository Group creation disabled')),
3315 ('hg.repogroup.create.true', _('Repository Group creation enabled')),
3315 ('hg.repogroup.create.true', _('Repository Group creation enabled')),
3316
3316
3317 ('hg.usergroup.create.false', _('User Group creation disabled')),
3317 ('hg.usergroup.create.false', _('User Group creation disabled')),
3318 ('hg.usergroup.create.true', _('User Group creation enabled')),
3318 ('hg.usergroup.create.true', _('User Group creation enabled')),
3319
3319
3320 ('hg.create.none', _('Repository creation disabled')),
3320 ('hg.create.none', _('Repository creation disabled')),
3321 ('hg.create.repository', _('Repository creation enabled')),
3321 ('hg.create.repository', _('Repository creation enabled')),
3322 ('hg.create.write_on_repogroup.true', _('Repository creation enabled with write permission to a repository group')),
3322 ('hg.create.write_on_repogroup.true', _('Repository creation enabled with write permission to a repository group')),
3323 ('hg.create.write_on_repogroup.false', _('Repository creation disabled with write permission to a repository group')),
3323 ('hg.create.write_on_repogroup.false', _('Repository creation disabled with write permission to a repository group')),
3324
3324
3325 ('hg.fork.none', _('Repository forking disabled')),
3325 ('hg.fork.none', _('Repository forking disabled')),
3326 ('hg.fork.repository', _('Repository forking enabled')),
3326 ('hg.fork.repository', _('Repository forking enabled')),
3327
3327
3328 ('hg.register.none', _('Registration disabled')),
3328 ('hg.register.none', _('Registration disabled')),
3329 ('hg.register.manual_activate', _('User Registration with manual account activation')),
3329 ('hg.register.manual_activate', _('User Registration with manual account activation')),
3330 ('hg.register.auto_activate', _('User Registration with automatic account activation')),
3330 ('hg.register.auto_activate', _('User Registration with automatic account activation')),
3331
3331
3332 ('hg.password_reset.enabled', _('Password reset enabled')),
3332 ('hg.password_reset.enabled', _('Password reset enabled')),
3333 ('hg.password_reset.hidden', _('Password reset hidden')),
3333 ('hg.password_reset.hidden', _('Password reset hidden')),
3334 ('hg.password_reset.disabled', _('Password reset disabled')),
3334 ('hg.password_reset.disabled', _('Password reset disabled')),
3335
3335
3336 ('hg.extern_activate.manual', _('Manual activation of external account')),
3336 ('hg.extern_activate.manual', _('Manual activation of external account')),
3337 ('hg.extern_activate.auto', _('Automatic activation of external account')),
3337 ('hg.extern_activate.auto', _('Automatic activation of external account')),
3338
3338
3339 ('hg.inherit_default_perms.false', _('Inherit object permissions from default user disabled')),
3339 ('hg.inherit_default_perms.false', _('Inherit object permissions from default user disabled')),
3340 ('hg.inherit_default_perms.true', _('Inherit object permissions from default user enabled')),
3340 ('hg.inherit_default_perms.true', _('Inherit object permissions from default user enabled')),
3341 ]
3341 ]
3342
3342
3343 # definition of system default permissions for DEFAULT user, created on
3343 # definition of system default permissions for DEFAULT user, created on
3344 # system setup
3344 # system setup
3345 DEFAULT_USER_PERMISSIONS = [
3345 DEFAULT_USER_PERMISSIONS = [
3346 # object perms
3346 # object perms
3347 'repository.read',
3347 'repository.read',
3348 'group.read',
3348 'group.read',
3349 'usergroup.read',
3349 'usergroup.read',
3350 # branch, for backward compat we need same value as before so forced pushed
3350 # branch, for backward compat we need same value as before so forced pushed
3351 'branch.push_force',
3351 'branch.push_force',
3352 # global
3352 # global
3353 'hg.create.repository',
3353 'hg.create.repository',
3354 'hg.repogroup.create.false',
3354 'hg.repogroup.create.false',
3355 'hg.usergroup.create.false',
3355 'hg.usergroup.create.false',
3356 'hg.create.write_on_repogroup.true',
3356 'hg.create.write_on_repogroup.true',
3357 'hg.fork.repository',
3357 'hg.fork.repository',
3358 'hg.register.manual_activate',
3358 'hg.register.manual_activate',
3359 'hg.password_reset.enabled',
3359 'hg.password_reset.enabled',
3360 'hg.extern_activate.auto',
3360 'hg.extern_activate.auto',
3361 'hg.inherit_default_perms.true',
3361 'hg.inherit_default_perms.true',
3362 ]
3362 ]
3363
3363
3364 # defines which permissions are more important higher the more important
3364 # defines which permissions are more important higher the more important
3365 # Weight defines which permissions are more important.
3365 # Weight defines which permissions are more important.
3366 # The higher number the more important.
3366 # The higher number the more important.
3367 PERM_WEIGHTS = {
3367 PERM_WEIGHTS = {
3368 'repository.none': 0,
3368 'repository.none': 0,
3369 'repository.read': 1,
3369 'repository.read': 1,
3370 'repository.write': 3,
3370 'repository.write': 3,
3371 'repository.admin': 4,
3371 'repository.admin': 4,
3372
3372
3373 'group.none': 0,
3373 'group.none': 0,
3374 'group.read': 1,
3374 'group.read': 1,
3375 'group.write': 3,
3375 'group.write': 3,
3376 'group.admin': 4,
3376 'group.admin': 4,
3377
3377
3378 'usergroup.none': 0,
3378 'usergroup.none': 0,
3379 'usergroup.read': 1,
3379 'usergroup.read': 1,
3380 'usergroup.write': 3,
3380 'usergroup.write': 3,
3381 'usergroup.admin': 4,
3381 'usergroup.admin': 4,
3382
3382
3383 'branch.none': 0,
3383 'branch.none': 0,
3384 'branch.merge': 1,
3384 'branch.merge': 1,
3385 'branch.push': 3,
3385 'branch.push': 3,
3386 'branch.push_force': 4,
3386 'branch.push_force': 4,
3387
3387
3388 'hg.repogroup.create.false': 0,
3388 'hg.repogroup.create.false': 0,
3389 'hg.repogroup.create.true': 1,
3389 'hg.repogroup.create.true': 1,
3390
3390
3391 'hg.usergroup.create.false': 0,
3391 'hg.usergroup.create.false': 0,
3392 'hg.usergroup.create.true': 1,
3392 'hg.usergroup.create.true': 1,
3393
3393
3394 'hg.fork.none': 0,
3394 'hg.fork.none': 0,
3395 'hg.fork.repository': 1,
3395 'hg.fork.repository': 1,
3396 'hg.create.none': 0,
3396 'hg.create.none': 0,
3397 'hg.create.repository': 1
3397 'hg.create.repository': 1
3398 }
3398 }
3399
3399
3400 permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3400 permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3401 permission_name = Column("permission_name", String(255), nullable=True, unique=None, default=None)
3401 permission_name = Column("permission_name", String(255), nullable=True, unique=None, default=None)
3402 permission_longname = Column("permission_longname", String(255), nullable=True, unique=None, default=None)
3402 permission_longname = Column("permission_longname", String(255), nullable=True, unique=None, default=None)
3403
3403
3404 def __repr__(self):
3404 def __repr__(self):
3405 return "<%s('%s:%s')>" % (
3405 return "<%s('%s:%s')>" % (
3406 self.cls_name, self.permission_id, self.permission_name
3406 self.cls_name, self.permission_id, self.permission_name
3407 )
3407 )
3408
3408
3409 @classmethod
3409 @classmethod
3410 def get_by_key(cls, key):
3410 def get_by_key(cls, key):
3411 return cls.query().filter(cls.permission_name == key).scalar()
3411 return cls.query().filter(cls.permission_name == key).scalar()
3412
3412
3413 @classmethod
3413 @classmethod
3414 def get_default_repo_perms(cls, user_id, repo_id=None):
3414 def get_default_repo_perms(cls, user_id, repo_id=None):
3415 q = Session().query(UserRepoToPerm, Repository, Permission)\
3415 q = Session().query(UserRepoToPerm, Repository, Permission)\
3416 .join((Permission, UserRepoToPerm.permission_id == Permission.permission_id))\
3416 .join((Permission, UserRepoToPerm.permission_id == Permission.permission_id))\
3417 .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\
3417 .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\
3418 .filter(UserRepoToPerm.user_id == user_id)
3418 .filter(UserRepoToPerm.user_id == user_id)
3419 if repo_id:
3419 if repo_id:
3420 q = q.filter(UserRepoToPerm.repository_id == repo_id)
3420 q = q.filter(UserRepoToPerm.repository_id == repo_id)
3421 return q.all()
3421 return q.all()
3422
3422
3423 @classmethod
3423 @classmethod
3424 def get_default_repo_branch_perms(cls, user_id, repo_id=None):
3424 def get_default_repo_branch_perms(cls, user_id, repo_id=None):
3425 q = Session().query(UserToRepoBranchPermission, UserRepoToPerm, Permission) \
3425 q = Session().query(UserToRepoBranchPermission, UserRepoToPerm, Permission) \
3426 .join(
3426 .join(
3427 Permission,
3427 Permission,
3428 UserToRepoBranchPermission.permission_id == Permission.permission_id) \
3428 UserToRepoBranchPermission.permission_id == Permission.permission_id) \
3429 .join(
3429 .join(
3430 UserRepoToPerm,
3430 UserRepoToPerm,
3431 UserToRepoBranchPermission.rule_to_perm_id == UserRepoToPerm.repo_to_perm_id) \
3431 UserToRepoBranchPermission.rule_to_perm_id == UserRepoToPerm.repo_to_perm_id) \
3432 .filter(UserRepoToPerm.user_id == user_id)
3432 .filter(UserRepoToPerm.user_id == user_id)
3433
3433
3434 if repo_id:
3434 if repo_id:
3435 q = q.filter(UserToRepoBranchPermission.repository_id == repo_id)
3435 q = q.filter(UserToRepoBranchPermission.repository_id == repo_id)
3436 return q.order_by(UserToRepoBranchPermission.rule_order).all()
3436 return q.order_by(UserToRepoBranchPermission.rule_order).all()
3437
3437
3438 @classmethod
3438 @classmethod
3439 def get_default_repo_perms_from_user_group(cls, user_id, repo_id=None):
3439 def get_default_repo_perms_from_user_group(cls, user_id, repo_id=None):
3440 q = Session().query(UserGroupRepoToPerm, Repository, Permission)\
3440 q = Session().query(UserGroupRepoToPerm, Repository, Permission)\
3441 .join(
3441 .join(
3442 Permission,
3442 Permission,
3443 UserGroupRepoToPerm.permission_id == Permission.permission_id)\
3443 UserGroupRepoToPerm.permission_id == Permission.permission_id)\
3444 .join(
3444 .join(
3445 Repository,
3445 Repository,
3446 UserGroupRepoToPerm.repository_id == Repository.repo_id)\
3446 UserGroupRepoToPerm.repository_id == Repository.repo_id)\
3447 .join(
3447 .join(
3448 UserGroup,
3448 UserGroup,
3449 UserGroupRepoToPerm.users_group_id ==
3449 UserGroupRepoToPerm.users_group_id ==
3450 UserGroup.users_group_id)\
3450 UserGroup.users_group_id)\
3451 .join(
3451 .join(
3452 UserGroupMember,
3452 UserGroupMember,
3453 UserGroupRepoToPerm.users_group_id ==
3453 UserGroupRepoToPerm.users_group_id ==
3454 UserGroupMember.users_group_id)\
3454 UserGroupMember.users_group_id)\
3455 .filter(
3455 .filter(
3456 UserGroupMember.user_id == user_id,
3456 UserGroupMember.user_id == user_id,
3457 UserGroup.users_group_active == true())
3457 UserGroup.users_group_active == true())
3458 if repo_id:
3458 if repo_id:
3459 q = q.filter(UserGroupRepoToPerm.repository_id == repo_id)
3459 q = q.filter(UserGroupRepoToPerm.repository_id == repo_id)
3460 return q.all()
3460 return q.all()
3461
3461
3462 @classmethod
3462 @classmethod
3463 def get_default_repo_branch_perms_from_user_group(cls, user_id, repo_id=None):
3463 def get_default_repo_branch_perms_from_user_group(cls, user_id, repo_id=None):
3464 q = Session().query(UserGroupToRepoBranchPermission, UserGroupRepoToPerm, Permission) \
3464 q = Session().query(UserGroupToRepoBranchPermission, UserGroupRepoToPerm, Permission) \
3465 .join(
3465 .join(
3466 Permission,
3466 Permission,
3467 UserGroupToRepoBranchPermission.permission_id == Permission.permission_id) \
3467 UserGroupToRepoBranchPermission.permission_id == Permission.permission_id) \
3468 .join(
3468 .join(
3469 UserGroupRepoToPerm,
3469 UserGroupRepoToPerm,
3470 UserGroupToRepoBranchPermission.rule_to_perm_id == UserGroupRepoToPerm.users_group_to_perm_id) \
3470 UserGroupToRepoBranchPermission.rule_to_perm_id == UserGroupRepoToPerm.users_group_to_perm_id) \
3471 .join(
3471 .join(
3472 UserGroup,
3472 UserGroup,
3473 UserGroupRepoToPerm.users_group_id == UserGroup.users_group_id) \
3473 UserGroupRepoToPerm.users_group_id == UserGroup.users_group_id) \
3474 .join(
3474 .join(
3475 UserGroupMember,
3475 UserGroupMember,
3476 UserGroupRepoToPerm.users_group_id == UserGroupMember.users_group_id) \
3476 UserGroupRepoToPerm.users_group_id == UserGroupMember.users_group_id) \
3477 .filter(
3477 .filter(
3478 UserGroupMember.user_id == user_id,
3478 UserGroupMember.user_id == user_id,
3479 UserGroup.users_group_active == true())
3479 UserGroup.users_group_active == true())
3480
3480
3481 if repo_id:
3481 if repo_id:
3482 q = q.filter(UserGroupToRepoBranchPermission.repository_id == repo_id)
3482 q = q.filter(UserGroupToRepoBranchPermission.repository_id == repo_id)
3483 return q.order_by(UserGroupToRepoBranchPermission.rule_order).all()
3483 return q.order_by(UserGroupToRepoBranchPermission.rule_order).all()
3484
3484
3485 @classmethod
3485 @classmethod
3486 def get_default_group_perms(cls, user_id, repo_group_id=None):
3486 def get_default_group_perms(cls, user_id, repo_group_id=None):
3487 q = Session().query(UserRepoGroupToPerm, RepoGroup, Permission)\
3487 q = Session().query(UserRepoGroupToPerm, RepoGroup, Permission)\
3488 .join(
3488 .join(
3489 Permission,
3489 Permission,
3490 UserRepoGroupToPerm.permission_id == Permission.permission_id)\
3490 UserRepoGroupToPerm.permission_id == Permission.permission_id)\
3491 .join(
3491 .join(
3492 RepoGroup,
3492 RepoGroup,
3493 UserRepoGroupToPerm.group_id == RepoGroup.group_id)\
3493 UserRepoGroupToPerm.group_id == RepoGroup.group_id)\
3494 .filter(UserRepoGroupToPerm.user_id == user_id)
3494 .filter(UserRepoGroupToPerm.user_id == user_id)
3495 if repo_group_id:
3495 if repo_group_id:
3496 q = q.filter(UserRepoGroupToPerm.group_id == repo_group_id)
3496 q = q.filter(UserRepoGroupToPerm.group_id == repo_group_id)
3497 return q.all()
3497 return q.all()
3498
3498
3499 @classmethod
3499 @classmethod
3500 def get_default_group_perms_from_user_group(
3500 def get_default_group_perms_from_user_group(
3501 cls, user_id, repo_group_id=None):
3501 cls, user_id, repo_group_id=None):
3502 q = Session().query(UserGroupRepoGroupToPerm, RepoGroup, Permission)\
3502 q = Session().query(UserGroupRepoGroupToPerm, RepoGroup, Permission)\
3503 .join(
3503 .join(
3504 Permission,
3504 Permission,
3505 UserGroupRepoGroupToPerm.permission_id ==
3505 UserGroupRepoGroupToPerm.permission_id ==
3506 Permission.permission_id)\
3506 Permission.permission_id)\
3507 .join(
3507 .join(
3508 RepoGroup,
3508 RepoGroup,
3509 UserGroupRepoGroupToPerm.group_id == RepoGroup.group_id)\
3509 UserGroupRepoGroupToPerm.group_id == RepoGroup.group_id)\
3510 .join(
3510 .join(
3511 UserGroup,
3511 UserGroup,
3512 UserGroupRepoGroupToPerm.users_group_id ==
3512 UserGroupRepoGroupToPerm.users_group_id ==
3513 UserGroup.users_group_id)\
3513 UserGroup.users_group_id)\
3514 .join(
3514 .join(
3515 UserGroupMember,
3515 UserGroupMember,
3516 UserGroupRepoGroupToPerm.users_group_id ==
3516 UserGroupRepoGroupToPerm.users_group_id ==
3517 UserGroupMember.users_group_id)\
3517 UserGroupMember.users_group_id)\
3518 .filter(
3518 .filter(
3519 UserGroupMember.user_id == user_id,
3519 UserGroupMember.user_id == user_id,
3520 UserGroup.users_group_active == true())
3520 UserGroup.users_group_active == true())
3521 if repo_group_id:
3521 if repo_group_id:
3522 q = q.filter(UserGroupRepoGroupToPerm.group_id == repo_group_id)
3522 q = q.filter(UserGroupRepoGroupToPerm.group_id == repo_group_id)
3523 return q.all()
3523 return q.all()
3524
3524
3525 @classmethod
3525 @classmethod
3526 def get_default_user_group_perms(cls, user_id, user_group_id=None):
3526 def get_default_user_group_perms(cls, user_id, user_group_id=None):
3527 q = Session().query(UserUserGroupToPerm, UserGroup, Permission)\
3527 q = Session().query(UserUserGroupToPerm, UserGroup, Permission)\
3528 .join((Permission, UserUserGroupToPerm.permission_id == Permission.permission_id))\
3528 .join((Permission, UserUserGroupToPerm.permission_id == Permission.permission_id))\
3529 .join((UserGroup, UserUserGroupToPerm.user_group_id == UserGroup.users_group_id))\
3529 .join((UserGroup, UserUserGroupToPerm.user_group_id == UserGroup.users_group_id))\
3530 .filter(UserUserGroupToPerm.user_id == user_id)
3530 .filter(UserUserGroupToPerm.user_id == user_id)
3531 if user_group_id:
3531 if user_group_id:
3532 q = q.filter(UserUserGroupToPerm.user_group_id == user_group_id)
3532 q = q.filter(UserUserGroupToPerm.user_group_id == user_group_id)
3533 return q.all()
3533 return q.all()
3534
3534
3535 @classmethod
3535 @classmethod
3536 def get_default_user_group_perms_from_user_group(
3536 def get_default_user_group_perms_from_user_group(
3537 cls, user_id, user_group_id=None):
3537 cls, user_id, user_group_id=None):
3538 TargetUserGroup = aliased(UserGroup, name='target_user_group')
3538 TargetUserGroup = aliased(UserGroup, name='target_user_group')
3539 q = Session().query(UserGroupUserGroupToPerm, UserGroup, Permission)\
3539 q = Session().query(UserGroupUserGroupToPerm, UserGroup, Permission)\
3540 .join(
3540 .join(
3541 Permission,
3541 Permission,
3542 UserGroupUserGroupToPerm.permission_id ==
3542 UserGroupUserGroupToPerm.permission_id ==
3543 Permission.permission_id)\
3543 Permission.permission_id)\
3544 .join(
3544 .join(
3545 TargetUserGroup,
3545 TargetUserGroup,
3546 UserGroupUserGroupToPerm.target_user_group_id ==
3546 UserGroupUserGroupToPerm.target_user_group_id ==
3547 TargetUserGroup.users_group_id)\
3547 TargetUserGroup.users_group_id)\
3548 .join(
3548 .join(
3549 UserGroup,
3549 UserGroup,
3550 UserGroupUserGroupToPerm.user_group_id ==
3550 UserGroupUserGroupToPerm.user_group_id ==
3551 UserGroup.users_group_id)\
3551 UserGroup.users_group_id)\
3552 .join(
3552 .join(
3553 UserGroupMember,
3553 UserGroupMember,
3554 UserGroupUserGroupToPerm.user_group_id ==
3554 UserGroupUserGroupToPerm.user_group_id ==
3555 UserGroupMember.users_group_id)\
3555 UserGroupMember.users_group_id)\
3556 .filter(
3556 .filter(
3557 UserGroupMember.user_id == user_id,
3557 UserGroupMember.user_id == user_id,
3558 UserGroup.users_group_active == true())
3558 UserGroup.users_group_active == true())
3559 if user_group_id:
3559 if user_group_id:
3560 q = q.filter(
3560 q = q.filter(
3561 UserGroupUserGroupToPerm.user_group_id == user_group_id)
3561 UserGroupUserGroupToPerm.user_group_id == user_group_id)
3562
3562
3563 return q.all()
3563 return q.all()
3564
3564
3565
3565
3566 class UserRepoToPerm(Base, BaseModel):
3566 class UserRepoToPerm(Base, BaseModel):
3567 __tablename__ = 'repo_to_perm'
3567 __tablename__ = 'repo_to_perm'
3568 __table_args__ = (
3568 __table_args__ = (
3569 UniqueConstraint('user_id', 'repository_id', 'permission_id'),
3569 UniqueConstraint('user_id', 'repository_id', 'permission_id'),
3570 base_table_args
3570 base_table_args
3571 )
3571 )
3572
3572
3573 repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3573 repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3574 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3574 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3575 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3575 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3576 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
3576 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
3577
3577
3578 user = relationship('User', back_populates="repo_to_perm")
3578 user = relationship('User', back_populates="repo_to_perm")
3579 repository = relationship('Repository', back_populates="repo_to_perm")
3579 repository = relationship('Repository', back_populates="repo_to_perm")
3580 permission = relationship('Permission')
3580 permission = relationship('Permission')
3581
3581
3582 branch_perm_entry = relationship('UserToRepoBranchPermission', cascade="all, delete-orphan", lazy='joined', back_populates='user_repo_to_perm')
3582 branch_perm_entry = relationship('UserToRepoBranchPermission', cascade="all, delete-orphan", lazy='joined', back_populates='user_repo_to_perm')
3583
3583
3584 @classmethod
3584 @classmethod
3585 def create(cls, user, repository, permission):
3585 def create(cls, user, repository, permission):
3586 n = cls()
3586 n = cls()
3587 n.user = user
3587 n.user = user
3588 n.repository = repository
3588 n.repository = repository
3589 n.permission = permission
3589 n.permission = permission
3590 Session().add(n)
3590 Session().add(n)
3591 return n
3591 return n
3592
3592
3593 def __repr__(self):
3593 def __repr__(self):
3594 return f'<{self.user} => {self.repository} >'
3594 return f'<{self.user} => {self.repository} >'
3595
3595
3596
3596
3597 class UserUserGroupToPerm(Base, BaseModel):
3597 class UserUserGroupToPerm(Base, BaseModel):
3598 __tablename__ = 'user_user_group_to_perm'
3598 __tablename__ = 'user_user_group_to_perm'
3599 __table_args__ = (
3599 __table_args__ = (
3600 UniqueConstraint('user_id', 'user_group_id', 'permission_id'),
3600 UniqueConstraint('user_id', 'user_group_id', 'permission_id'),
3601 base_table_args
3601 base_table_args
3602 )
3602 )
3603
3603
3604 user_user_group_to_perm_id = Column("user_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3604 user_user_group_to_perm_id = Column("user_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3605 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3605 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3606 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3606 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3607 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3607 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3608
3608
3609 user = relationship('User', back_populates='user_group_to_perm')
3609 user = relationship('User', back_populates='user_group_to_perm')
3610 user_group = relationship('UserGroup', back_populates='user_user_group_to_perm')
3610 user_group = relationship('UserGroup', back_populates='user_user_group_to_perm')
3611 permission = relationship('Permission')
3611 permission = relationship('Permission')
3612
3612
3613 @classmethod
3613 @classmethod
3614 def create(cls, user, user_group, permission):
3614 def create(cls, user, user_group, permission):
3615 n = cls()
3615 n = cls()
3616 n.user = user
3616 n.user = user
3617 n.user_group = user_group
3617 n.user_group = user_group
3618 n.permission = permission
3618 n.permission = permission
3619 Session().add(n)
3619 Session().add(n)
3620 return n
3620 return n
3621
3621
3622 def __repr__(self):
3622 def __repr__(self):
3623 return f'<{self.user} => {self.user_group} >'
3623 return f'<{self.user} => {self.user_group} >'
3624
3624
3625
3625
3626 class UserToPerm(Base, BaseModel):
3626 class UserToPerm(Base, BaseModel):
3627 __tablename__ = 'user_to_perm'
3627 __tablename__ = 'user_to_perm'
3628 __table_args__ = (
3628 __table_args__ = (
3629 UniqueConstraint('user_id', 'permission_id'),
3629 UniqueConstraint('user_id', 'permission_id'),
3630 base_table_args
3630 base_table_args
3631 )
3631 )
3632
3632
3633 user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3633 user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3634 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3634 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3635 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3635 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3636
3636
3637 user = relationship('User', back_populates='user_perms')
3637 user = relationship('User', back_populates='user_perms')
3638 permission = relationship('Permission', lazy='joined')
3638 permission = relationship('Permission', lazy='joined')
3639
3639
3640 def __repr__(self):
3640 def __repr__(self):
3641 return f'<{self.user} => {self.permission} >'
3641 return f'<{self.user} => {self.permission} >'
3642
3642
3643
3643
3644 class UserGroupRepoToPerm(Base, BaseModel):
3644 class UserGroupRepoToPerm(Base, BaseModel):
3645 __tablename__ = 'users_group_repo_to_perm'
3645 __tablename__ = 'users_group_repo_to_perm'
3646 __table_args__ = (
3646 __table_args__ = (
3647 UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
3647 UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
3648 base_table_args
3648 base_table_args
3649 )
3649 )
3650
3650
3651 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3651 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3652 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3652 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3653 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3653 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3654 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
3654 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
3655
3655
3656 users_group = relationship('UserGroup', back_populates='users_group_repo_to_perm')
3656 users_group = relationship('UserGroup', back_populates='users_group_repo_to_perm')
3657 permission = relationship('Permission')
3657 permission = relationship('Permission')
3658 repository = relationship('Repository', back_populates='users_group_to_perm')
3658 repository = relationship('Repository', back_populates='users_group_to_perm')
3659 user_group_branch_perms = relationship('UserGroupToRepoBranchPermission', cascade='all', back_populates='user_group_repo_to_perm')
3659 user_group_branch_perms = relationship('UserGroupToRepoBranchPermission', cascade='all', back_populates='user_group_repo_to_perm')
3660
3660
3661 @classmethod
3661 @classmethod
3662 def create(cls, users_group, repository, permission):
3662 def create(cls, users_group, repository, permission):
3663 n = cls()
3663 n = cls()
3664 n.users_group = users_group
3664 n.users_group = users_group
3665 n.repository = repository
3665 n.repository = repository
3666 n.permission = permission
3666 n.permission = permission
3667 Session().add(n)
3667 Session().add(n)
3668 return n
3668 return n
3669
3669
3670 def __repr__(self):
3670 def __repr__(self):
3671 return f'<UserGroupRepoToPerm:{self.users_group} => {self.repository} >'
3671 return f'<UserGroupRepoToPerm:{self.users_group} => {self.repository} >'
3672
3672
3673
3673
3674 class UserGroupUserGroupToPerm(Base, BaseModel):
3674 class UserGroupUserGroupToPerm(Base, BaseModel):
3675 __tablename__ = 'user_group_user_group_to_perm'
3675 __tablename__ = 'user_group_user_group_to_perm'
3676 __table_args__ = (
3676 __table_args__ = (
3677 UniqueConstraint('target_user_group_id', 'user_group_id', 'permission_id'),
3677 UniqueConstraint('target_user_group_id', 'user_group_id', 'permission_id'),
3678 CheckConstraint('target_user_group_id != user_group_id'),
3678 CheckConstraint('target_user_group_id != user_group_id'),
3679 base_table_args
3679 base_table_args
3680 )
3680 )
3681
3681
3682 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)
3682 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)
3683 target_user_group_id = Column("target_user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3683 target_user_group_id = Column("target_user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3684 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3684 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3685 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3685 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3686
3686
3687 target_user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id', back_populates='user_group_user_group_to_perm')
3687 target_user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id', back_populates='user_group_user_group_to_perm')
3688 user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.user_group_id==UserGroup.users_group_id')
3688 user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.user_group_id==UserGroup.users_group_id')
3689 permission = relationship('Permission')
3689 permission = relationship('Permission')
3690
3690
3691 @classmethod
3691 @classmethod
3692 def create(cls, target_user_group, user_group, permission):
3692 def create(cls, target_user_group, user_group, permission):
3693 n = cls()
3693 n = cls()
3694 n.target_user_group = target_user_group
3694 n.target_user_group = target_user_group
3695 n.user_group = user_group
3695 n.user_group = user_group
3696 n.permission = permission
3696 n.permission = permission
3697 Session().add(n)
3697 Session().add(n)
3698 return n
3698 return n
3699
3699
3700 def __repr__(self):
3700 def __repr__(self):
3701 return f'<UserGroupUserGroup:{self.target_user_group} => {self.user_group} >'
3701 return f'<UserGroupUserGroup:{self.target_user_group} => {self.user_group} >'
3702
3702
3703
3703
3704 class UserGroupToPerm(Base, BaseModel):
3704 class UserGroupToPerm(Base, BaseModel):
3705 __tablename__ = 'users_group_to_perm'
3705 __tablename__ = 'users_group_to_perm'
3706 __table_args__ = (
3706 __table_args__ = (
3707 UniqueConstraint('users_group_id', 'permission_id',),
3707 UniqueConstraint('users_group_id', 'permission_id',),
3708 base_table_args
3708 base_table_args
3709 )
3709 )
3710
3710
3711 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3711 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3712 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3712 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3713 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3713 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3714
3714
3715 users_group = relationship('UserGroup', back_populates='users_group_to_perm')
3715 users_group = relationship('UserGroup', back_populates='users_group_to_perm')
3716 permission = relationship('Permission')
3716 permission = relationship('Permission')
3717
3717
3718
3718
3719 class UserRepoGroupToPerm(Base, BaseModel):
3719 class UserRepoGroupToPerm(Base, BaseModel):
3720 __tablename__ = 'user_repo_group_to_perm'
3720 __tablename__ = 'user_repo_group_to_perm'
3721 __table_args__ = (
3721 __table_args__ = (
3722 UniqueConstraint('user_id', 'group_id', 'permission_id'),
3722 UniqueConstraint('user_id', 'group_id', 'permission_id'),
3723 base_table_args
3723 base_table_args
3724 )
3724 )
3725
3725
3726 group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3726 group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3727 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3727 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3728 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
3728 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
3729 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3729 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3730
3730
3731 user = relationship('User', back_populates='repo_group_to_perm')
3731 user = relationship('User', back_populates='repo_group_to_perm')
3732 group = relationship('RepoGroup', back_populates='repo_group_to_perm')
3732 group = relationship('RepoGroup', back_populates='repo_group_to_perm')
3733 permission = relationship('Permission')
3733 permission = relationship('Permission')
3734
3734
3735 @classmethod
3735 @classmethod
3736 def create(cls, user, repository_group, permission):
3736 def create(cls, user, repository_group, permission):
3737 n = cls()
3737 n = cls()
3738 n.user = user
3738 n.user = user
3739 n.group = repository_group
3739 n.group = repository_group
3740 n.permission = permission
3740 n.permission = permission
3741 Session().add(n)
3741 Session().add(n)
3742 return n
3742 return n
3743
3743
3744
3744
3745 class UserGroupRepoGroupToPerm(Base, BaseModel):
3745 class UserGroupRepoGroupToPerm(Base, BaseModel):
3746 __tablename__ = 'users_group_repo_group_to_perm'
3746 __tablename__ = 'users_group_repo_group_to_perm'
3747 __table_args__ = (
3747 __table_args__ = (
3748 UniqueConstraint('users_group_id', 'group_id'),
3748 UniqueConstraint('users_group_id', 'group_id'),
3749 base_table_args
3749 base_table_args
3750 )
3750 )
3751
3751
3752 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)
3752 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)
3753 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3753 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3754 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
3754 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
3755 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3755 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3756
3756
3757 users_group = relationship('UserGroup', back_populates='users_group_repo_group_to_perm')
3757 users_group = relationship('UserGroup', back_populates='users_group_repo_group_to_perm')
3758 permission = relationship('Permission')
3758 permission = relationship('Permission')
3759 group = relationship('RepoGroup', back_populates='users_group_to_perm')
3759 group = relationship('RepoGroup', back_populates='users_group_to_perm')
3760
3760
3761 @classmethod
3761 @classmethod
3762 def create(cls, user_group, repository_group, permission):
3762 def create(cls, user_group, repository_group, permission):
3763 n = cls()
3763 n = cls()
3764 n.users_group = user_group
3764 n.users_group = user_group
3765 n.group = repository_group
3765 n.group = repository_group
3766 n.permission = permission
3766 n.permission = permission
3767 Session().add(n)
3767 Session().add(n)
3768 return n
3768 return n
3769
3769
3770 def __repr__(self):
3770 def __repr__(self):
3771 return '<UserGroupRepoGroupToPerm:%s => %s >' % (self.users_group, self.group)
3771 return '<UserGroupRepoGroupToPerm:%s => %s >' % (self.users_group, self.group)
3772
3772
3773
3773
3774 class Statistics(Base, BaseModel):
3774 class Statistics(Base, BaseModel):
3775 __tablename__ = 'statistics'
3775 __tablename__ = 'statistics'
3776 __table_args__ = (
3776 __table_args__ = (
3777 base_table_args
3777 base_table_args
3778 )
3778 )
3779
3779
3780 stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3780 stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3781 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
3781 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
3782 stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
3782 stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
3783 commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False) #JSON data
3783 commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False) #JSON data
3784 commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False) #JSON data
3784 commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False) #JSON data
3785 languages = Column("languages", LargeBinary(1000000), nullable=False) #JSON data
3785 languages = Column("languages", LargeBinary(1000000), nullable=False) #JSON data
3786
3786
3787 repository = relationship('Repository', single_parent=True, viewonly=True)
3787 repository = relationship('Repository', single_parent=True, viewonly=True)
3788
3788
3789
3789
3790 class UserFollowing(Base, BaseModel):
3790 class UserFollowing(Base, BaseModel):
3791 __tablename__ = 'user_followings'
3791 __tablename__ = 'user_followings'
3792 __table_args__ = (
3792 __table_args__ = (
3793 UniqueConstraint('user_id', 'follows_repository_id'),
3793 UniqueConstraint('user_id', 'follows_repository_id'),
3794 UniqueConstraint('user_id', 'follows_user_id'),
3794 UniqueConstraint('user_id', 'follows_user_id'),
3795 base_table_args
3795 base_table_args
3796 )
3796 )
3797
3797
3798 user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3798 user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3799 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3799 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3800 follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
3800 follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
3801 follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
3801 follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
3802 follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
3802 follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
3803
3803
3804 user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id', back_populates='followings')
3804 user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id', back_populates='followings')
3805
3805
3806 follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
3806 follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
3807 follows_repository = relationship('Repository', order_by='Repository.repo_name', back_populates='followers')
3807 follows_repository = relationship('Repository', order_by='Repository.repo_name', back_populates='followers')
3808
3808
3809 @classmethod
3809 @classmethod
3810 def get_repo_followers(cls, repo_id):
3810 def get_repo_followers(cls, repo_id):
3811 return cls.query().filter(cls.follows_repo_id == repo_id)
3811 return cls.query().filter(cls.follows_repo_id == repo_id)
3812
3812
3813
3813
3814 class CacheKey(Base, BaseModel):
3814 class CacheKey(Base, BaseModel):
3815 __tablename__ = 'cache_invalidation'
3815 __tablename__ = 'cache_invalidation'
3816 __table_args__ = (
3816 __table_args__ = (
3817 UniqueConstraint('cache_key'),
3817 UniqueConstraint('cache_key'),
3818 Index('key_idx', 'cache_key'),
3818 Index('key_idx', 'cache_key'),
3819 Index('cache_args_idx', 'cache_args'),
3819 Index('cache_args_idx', 'cache_args'),
3820 base_table_args,
3820 base_table_args,
3821 )
3821 )
3822
3822
3823 CACHE_TYPE_FEED = 'FEED'
3823 CACHE_TYPE_FEED = 'FEED'
3824
3824
3825 # namespaces used to register process/thread aware caches
3825 # namespaces used to register process/thread aware caches
3826 REPO_INVALIDATION_NAMESPACE = 'repo_cache.v1:{repo_id}'
3826 REPO_INVALIDATION_NAMESPACE = 'repo_cache.v1:{repo_id}'
3827
3827
3828 cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3828 cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3829 cache_key = Column("cache_key", String(255), nullable=True, unique=None, default=None)
3829 cache_key = Column("cache_key", String(255), nullable=True, unique=None, default=None)
3830 cache_args = Column("cache_args", String(255), nullable=True, unique=None, default=None)
3830 cache_args = Column("cache_args", String(255), nullable=True, unique=None, default=None)
3831 cache_state_uid = Column("cache_state_uid", String(255), nullable=True, unique=None, default=None)
3831 cache_state_uid = Column("cache_state_uid", String(255), nullable=True, unique=None, default=None)
3832 cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
3832 cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
3833
3833
3834 def __init__(self, cache_key, cache_args='', cache_state_uid=None, cache_active=False):
3834 def __init__(self, cache_key, cache_args='', cache_state_uid=None, cache_active=False):
3835 self.cache_key = cache_key
3835 self.cache_key = cache_key
3836 self.cache_args = cache_args
3836 self.cache_args = cache_args
3837 self.cache_active = cache_active
3837 self.cache_active = cache_active
3838 # first key should be same for all entries, since all workers should share it
3838 # first key should be same for all entries, since all workers should share it
3839 self.cache_state_uid = cache_state_uid or self.generate_new_state_uid()
3839 self.cache_state_uid = cache_state_uid or self.generate_new_state_uid()
3840
3840
3841 def __repr__(self):
3841 def __repr__(self):
3842 return "<%s('%s:%s[%s]')>" % (
3842 return "<%s('%s:%s[%s]')>" % (
3843 self.cls_name,
3843 self.cls_name,
3844 self.cache_id, self.cache_key, self.cache_active)
3844 self.cache_id, self.cache_key, self.cache_active)
3845
3845
3846 def _cache_key_partition(self):
3846 def _cache_key_partition(self):
3847 prefix, repo_name, suffix = self.cache_key.partition(self.cache_args)
3847 prefix, repo_name, suffix = self.cache_key.partition(self.cache_args)
3848 return prefix, repo_name, suffix
3848 return prefix, repo_name, suffix
3849
3849
3850 def get_prefix(self):
3850 def get_prefix(self):
3851 """
3851 """
3852 Try to extract prefix from existing cache key. The key could consist
3852 Try to extract prefix from existing cache key. The key could consist
3853 of prefix, repo_name, suffix
3853 of prefix, repo_name, suffix
3854 """
3854 """
3855 # this returns prefix, repo_name, suffix
3855 # this returns prefix, repo_name, suffix
3856 return self._cache_key_partition()[0]
3856 return self._cache_key_partition()[0]
3857
3857
3858 def get_suffix(self):
3858 def get_suffix(self):
3859 """
3859 """
3860 get suffix that might have been used in _get_cache_key to
3860 get suffix that might have been used in _get_cache_key to
3861 generate self.cache_key. Only used for informational purposes
3861 generate self.cache_key. Only used for informational purposes
3862 in repo_edit.mako.
3862 in repo_edit.mako.
3863 """
3863 """
3864 # prefix, repo_name, suffix
3864 # prefix, repo_name, suffix
3865 return self._cache_key_partition()[2]
3865 return self._cache_key_partition()[2]
3866
3866
3867 @classmethod
3867 @classmethod
3868 def generate_new_state_uid(cls, based_on=None):
3868 def generate_new_state_uid(cls, based_on=None):
3869 if based_on:
3869 if based_on:
3870 return str(uuid.uuid5(uuid.NAMESPACE_URL, safe_str(based_on)))
3870 return str(uuid.uuid5(uuid.NAMESPACE_URL, safe_str(based_on)))
3871 else:
3871 else:
3872 return str(uuid.uuid4())
3872 return str(uuid.uuid4())
3873
3873
3874 @classmethod
3874 @classmethod
3875 def delete_all_cache(cls):
3875 def delete_all_cache(cls):
3876 """
3876 """
3877 Delete all cache keys from database.
3877 Delete all cache keys from database.
3878 Should only be run when all instances are down and all entries
3878 Should only be run when all instances are down and all entries
3879 thus stale.
3879 thus stale.
3880 """
3880 """
3881 cls.query().delete()
3881 cls.query().delete()
3882 Session().commit()
3882 Session().commit()
3883
3883
3884 @classmethod
3884 @classmethod
3885 def set_invalidate(cls, cache_uid, delete=False):
3885 def set_invalidate(cls, cache_uid, delete=False):
3886 """
3886 """
3887 Mark all caches of a repo as invalid in the database.
3887 Mark all caches of a repo as invalid in the database.
3888 """
3888 """
3889 try:
3889 try:
3890 qry = Session().query(cls).filter(cls.cache_key == cache_uid)
3890 qry = Session().query(cls).filter(cls.cache_key == cache_uid)
3891 if delete:
3891 if delete:
3892 qry.delete()
3892 qry.delete()
3893 log.debug('cache objects deleted for cache args %s',
3893 log.debug('cache objects deleted for cache args %s',
3894 safe_str(cache_uid))
3894 safe_str(cache_uid))
3895 else:
3895 else:
3896 new_uid = cls.generate_new_state_uid()
3896 new_uid = cls.generate_new_state_uid()
3897 qry.update({"cache_state_uid": new_uid,
3897 qry.update({"cache_state_uid": new_uid,
3898 "cache_args": f"repo_state:{time.time()}"})
3898 "cache_args": f"repo_state:{time.time()}"})
3899 log.debug('cache object %s set new UID %s',
3899 log.debug('cache object %s set new UID %s',
3900 safe_str(cache_uid), new_uid)
3900 safe_str(cache_uid), new_uid)
3901
3901
3902 Session().commit()
3902 Session().commit()
3903 except Exception:
3903 except Exception:
3904 log.exception(
3904 log.exception(
3905 'Cache key invalidation failed for cache args %s',
3905 'Cache key invalidation failed for cache args %s',
3906 safe_str(cache_uid))
3906 safe_str(cache_uid))
3907 Session().rollback()
3907 Session().rollback()
3908
3908
3909 @classmethod
3909 @classmethod
3910 def get_active_cache(cls, cache_key):
3910 def get_active_cache(cls, cache_key):
3911 inv_obj = cls.query().filter(cls.cache_key == cache_key).scalar()
3911 inv_obj = cls.query().filter(cls.cache_key == cache_key).scalar()
3912 if inv_obj:
3912 if inv_obj:
3913 return inv_obj
3913 return inv_obj
3914 return None
3914 return None
3915
3915
3916 @classmethod
3916 @classmethod
3917 def get_namespace_map(cls, namespace):
3917 def get_namespace_map(cls, namespace):
3918 return {
3918 return {
3919 x.cache_key: x
3919 x.cache_key: x
3920 for x in cls.query().filter(cls.cache_args == namespace)}
3920 for x in cls.query().filter(cls.cache_args == namespace)}
3921
3921
3922
3922
3923 class ChangesetComment(Base, BaseModel):
3923 class ChangesetComment(Base, BaseModel):
3924 __tablename__ = 'changeset_comments'
3924 __tablename__ = 'changeset_comments'
3925 __table_args__ = (
3925 __table_args__ = (
3926 Index('cc_revision_idx', 'revision'),
3926 Index('cc_revision_idx', 'revision'),
3927 base_table_args,
3927 base_table_args,
3928 )
3928 )
3929
3929
3930 COMMENT_OUTDATED = 'comment_outdated'
3930 COMMENT_OUTDATED = 'comment_outdated'
3931 COMMENT_TYPE_NOTE = 'note'
3931 COMMENT_TYPE_NOTE = 'note'
3932 COMMENT_TYPE_TODO = 'todo'
3932 COMMENT_TYPE_TODO = 'todo'
3933 COMMENT_TYPES = [COMMENT_TYPE_NOTE, COMMENT_TYPE_TODO]
3933 COMMENT_TYPES = [COMMENT_TYPE_NOTE, COMMENT_TYPE_TODO]
3934
3934
3935 OP_IMMUTABLE = 'immutable'
3935 OP_IMMUTABLE = 'immutable'
3936 OP_CHANGEABLE = 'changeable'
3936 OP_CHANGEABLE = 'changeable'
3937
3937
3938 comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True)
3938 comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True)
3939 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3939 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3940 revision = Column('revision', String(40), nullable=True)
3940 revision = Column('revision', String(40), nullable=True)
3941 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3941 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3942 pull_request_version_id = Column("pull_request_version_id", Integer(), ForeignKey('pull_request_versions.pull_request_version_id'), nullable=True)
3942 pull_request_version_id = Column("pull_request_version_id", Integer(), ForeignKey('pull_request_versions.pull_request_version_id'), nullable=True)
3943 line_no = Column('line_no', Unicode(10), nullable=True)
3943 line_no = Column('line_no', Unicode(10), nullable=True)
3944 hl_lines = Column('hl_lines', Unicode(512), nullable=True)
3944 hl_lines = Column('hl_lines', Unicode(512), nullable=True)
3945 f_path = Column('f_path', Unicode(1000), nullable=True)
3945 f_path = Column('f_path', Unicode(1000), nullable=True)
3946 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
3946 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
3947 text = Column('text', UnicodeText().with_variant(UnicodeText(25000), 'mysql'), nullable=False)
3947 text = Column('text', UnicodeText().with_variant(UnicodeText(25000), 'mysql'), nullable=False)
3948 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3948 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3949 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3949 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3950 renderer = Column('renderer', Unicode(64), nullable=True)
3950 renderer = Column('renderer', Unicode(64), nullable=True)
3951 display_state = Column('display_state', Unicode(128), nullable=True)
3951 display_state = Column('display_state', Unicode(128), nullable=True)
3952 immutable_state = Column('immutable_state', Unicode(128), nullable=True, default=OP_CHANGEABLE)
3952 immutable_state = Column('immutable_state', Unicode(128), nullable=True, default=OP_CHANGEABLE)
3953 draft = Column('draft', Boolean(), nullable=True, default=False)
3953 draft = Column('draft', Boolean(), nullable=True, default=False)
3954
3954
3955 comment_type = Column('comment_type', Unicode(128), nullable=True, default=COMMENT_TYPE_NOTE)
3955 comment_type = Column('comment_type', Unicode(128), nullable=True, default=COMMENT_TYPE_NOTE)
3956 resolved_comment_id = Column('resolved_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'), nullable=True)
3956 resolved_comment_id = Column('resolved_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'), nullable=True)
3957
3957
3958 resolved_comment = relationship('ChangesetComment', remote_side=comment_id, back_populates='resolved_by')
3958 resolved_comment = relationship('ChangesetComment', remote_side=comment_id, back_populates='resolved_by')
3959 resolved_by = relationship('ChangesetComment', back_populates='resolved_comment')
3959 resolved_by = relationship('ChangesetComment', back_populates='resolved_comment')
3960
3960
3961 author = relationship('User', lazy='select', back_populates='user_comments')
3961 author = relationship('User', lazy='select', back_populates='user_comments')
3962 repo = relationship('Repository', back_populates='comments')
3962 repo = relationship('Repository', back_populates='comments')
3963 status_change = relationship('ChangesetStatus', cascade="all, delete-orphan", lazy='select', back_populates='comment')
3963 status_change = relationship('ChangesetStatus', cascade="all, delete-orphan", lazy='select', back_populates='comment')
3964 pull_request = relationship('PullRequest', lazy='select', back_populates='comments')
3964 pull_request = relationship('PullRequest', lazy='select', back_populates='comments')
3965 pull_request_version = relationship('PullRequestVersion', lazy='select')
3965 pull_request_version = relationship('PullRequestVersion', lazy='select')
3966 history = relationship('ChangesetCommentHistory', cascade='all, delete-orphan', lazy='select', order_by='ChangesetCommentHistory.version', back_populates="comment")
3966 history = relationship('ChangesetCommentHistory', cascade='all, delete-orphan', lazy='select', order_by='ChangesetCommentHistory.version', back_populates="comment")
3967
3967
3968 @classmethod
3968 @classmethod
3969 def get_users(cls, revision=None, pull_request_id=None):
3969 def get_users(cls, revision=None, pull_request_id=None):
3970 """
3970 """
3971 Returns user associated with this ChangesetComment. ie those
3971 Returns user associated with this ChangesetComment. ie those
3972 who actually commented
3972 who actually commented
3973
3973
3974 :param cls:
3974 :param cls:
3975 :param revision:
3975 :param revision:
3976 """
3976 """
3977 q = Session().query(User).join(ChangesetComment.author)
3977 q = Session().query(User).join(ChangesetComment.author)
3978 if revision:
3978 if revision:
3979 q = q.filter(cls.revision == revision)
3979 q = q.filter(cls.revision == revision)
3980 elif pull_request_id:
3980 elif pull_request_id:
3981 q = q.filter(cls.pull_request_id == pull_request_id)
3981 q = q.filter(cls.pull_request_id == pull_request_id)
3982 return q.all()
3982 return q.all()
3983
3983
3984 @classmethod
3984 @classmethod
3985 def get_index_from_version(cls, pr_version, versions=None, num_versions=None) -> int:
3985 def get_index_from_version(cls, pr_version, versions=None, num_versions=None) -> int:
3986 if pr_version is None:
3986 if pr_version is None:
3987 return 0
3987 return 0
3988
3988
3989 if versions is not None:
3989 if versions is not None:
3990 num_versions = [x.pull_request_version_id for x in versions]
3990 num_versions = [x.pull_request_version_id for x in versions]
3991
3991
3992 num_versions = num_versions or []
3992 num_versions = num_versions or []
3993 try:
3993 try:
3994 return num_versions.index(pr_version) + 1
3994 return num_versions.index(pr_version) + 1
3995 except (IndexError, ValueError):
3995 except (IndexError, ValueError):
3996 return 0
3996 return 0
3997
3997
3998 @property
3998 @property
3999 def outdated(self):
3999 def outdated(self):
4000 return self.display_state == self.COMMENT_OUTDATED
4000 return self.display_state == self.COMMENT_OUTDATED
4001
4001
4002 @property
4002 @property
4003 def outdated_js(self):
4003 def outdated_js(self):
4004 return str_json(self.display_state == self.COMMENT_OUTDATED)
4004 return str_json(self.display_state == self.COMMENT_OUTDATED)
4005
4005
4006 @property
4006 @property
4007 def immutable(self):
4007 def immutable(self):
4008 return self.immutable_state == self.OP_IMMUTABLE
4008 return self.immutable_state == self.OP_IMMUTABLE
4009
4009
4010 def outdated_at_version(self, version: int) -> bool:
4010 def outdated_at_version(self, version: int) -> bool:
4011 """
4011 """
4012 Checks if comment is outdated for given pull request version
4012 Checks if comment is outdated for given pull request version
4013 """
4013 """
4014
4014
4015 def version_check():
4015 def version_check():
4016 return self.pull_request_version_id and self.pull_request_version_id != version
4016 return self.pull_request_version_id and self.pull_request_version_id != version
4017
4017
4018 if self.is_inline:
4018 if self.is_inline:
4019 return self.outdated and version_check()
4019 return self.outdated and version_check()
4020 else:
4020 else:
4021 # general comments don't have .outdated set, also latest don't have a version
4021 # general comments don't have .outdated set, also latest don't have a version
4022 return version_check()
4022 return version_check()
4023
4023
4024 def outdated_at_version_js(self, version):
4024 def outdated_at_version_js(self, version):
4025 """
4025 """
4026 Checks if comment is outdated for given pull request version
4026 Checks if comment is outdated for given pull request version
4027 """
4027 """
4028 return str_json(self.outdated_at_version(version))
4028 return str_json(self.outdated_at_version(version))
4029
4029
4030 def older_than_version(self, version: int) -> bool:
4030 def older_than_version(self, version: int) -> bool:
4031 """
4031 """
4032 Checks if comment is made from a previous version than given.
4032 Checks if comment is made from a previous version than given.
4033 Assumes self.pull_request_version.pull_request_version_id is an integer if not None.
4033 Assumes self.pull_request_version.pull_request_version_id is an integer if not None.
4034 """
4034 """
4035
4035
4036 # If version is None, return False as the current version cannot be less than None
4036 # If version is None, return False as the current version cannot be less than None
4037 if version is None:
4037 if version is None:
4038 return False
4038 return False
4039
4039
4040 # Ensure that the version is an integer to prevent TypeError on comparison
4040 # Ensure that the version is an integer to prevent TypeError on comparison
4041 if not isinstance(version, int):
4041 if not isinstance(version, int):
4042 raise ValueError("The provided version must be an integer.")
4042 raise ValueError("The provided version must be an integer.")
4043
4043
4044 # Initialize current version to 0 or pull_request_version_id if it's available
4044 # Initialize current version to 0 or pull_request_version_id if it's available
4045 cur_ver = 0
4045 cur_ver = 0
4046 if self.pull_request_version and self.pull_request_version.pull_request_version_id is not None:
4046 if self.pull_request_version and self.pull_request_version.pull_request_version_id is not None:
4047 cur_ver = self.pull_request_version.pull_request_version_id
4047 cur_ver = self.pull_request_version.pull_request_version_id
4048
4048
4049 # Return True if the current version is less than the given version
4049 # Return True if the current version is less than the given version
4050 return cur_ver < version
4050 return cur_ver < version
4051
4051
4052 def older_than_version_js(self, version):
4052 def older_than_version_js(self, version):
4053 """
4053 """
4054 Checks if comment is made from previous version than given
4054 Checks if comment is made from previous version than given
4055 """
4055 """
4056 return str_json(self.older_than_version(version))
4056 return str_json(self.older_than_version(version))
4057
4057
4058 @property
4058 @property
4059 def commit_id(self):
4059 def commit_id(self):
4060 """New style naming to stop using .revision"""
4060 """New style naming to stop using .revision"""
4061 return self.revision
4061 return self.revision
4062
4062
4063 @property
4063 @property
4064 def resolved(self):
4064 def resolved(self):
4065 return self.resolved_by[0] if self.resolved_by else None
4065 return self.resolved_by[0] if self.resolved_by else None
4066
4066
4067 @property
4067 @property
4068 def is_todo(self):
4068 def is_todo(self):
4069 return self.comment_type == self.COMMENT_TYPE_TODO
4069 return self.comment_type == self.COMMENT_TYPE_TODO
4070
4070
4071 @property
4071 @property
4072 def is_inline(self):
4072 def is_inline(self):
4073 if self.line_no and self.f_path:
4073 if self.line_no and self.f_path:
4074 return True
4074 return True
4075 return False
4075 return False
4076
4076
4077 @property
4077 @property
4078 def last_version(self):
4078 def last_version(self):
4079 version = 0
4079 version = 0
4080 if self.history:
4080 if self.history:
4081 version = self.history[-1].version
4081 version = self.history[-1].version
4082 return version
4082 return version
4083
4083
4084 def get_index_version(self, versions):
4084 def get_index_version(self, versions):
4085 return self.get_index_from_version(
4085 return self.get_index_from_version(
4086 self.pull_request_version_id, versions)
4086 self.pull_request_version_id, versions)
4087
4087
4088 @property
4088 @property
4089 def review_status(self):
4089 def review_status(self):
4090 if self.status_change:
4090 if self.status_change:
4091 return self.status_change[0].status
4091 return self.status_change[0].status
4092
4092
4093 @property
4093 @property
4094 def review_status_lbl(self):
4094 def review_status_lbl(self):
4095 if self.status_change:
4095 if self.status_change:
4096 return self.status_change[0].status_lbl
4096 return self.status_change[0].status_lbl
4097
4097
4098 def __repr__(self):
4098 def __repr__(self):
4099 if self.comment_id:
4099 if self.comment_id:
4100 return f'<DB:Comment #{self.comment_id}>'
4100 return f'<DB:Comment #{self.comment_id}>'
4101 else:
4101 else:
4102 return f'<DB:Comment at {id(self)!r}>'
4102 return f'<DB:Comment at {id(self)!r}>'
4103
4103
4104 def get_api_data(self):
4104 def get_api_data(self):
4105 comment = self
4105 comment = self
4106
4106
4107 data = {
4107 data = {
4108 'comment_id': comment.comment_id,
4108 'comment_id': comment.comment_id,
4109 'comment_type': comment.comment_type,
4109 'comment_type': comment.comment_type,
4110 'comment_text': comment.text,
4110 'comment_text': comment.text,
4111 'comment_status': comment.status_change,
4111 'comment_status': comment.status_change,
4112 'comment_f_path': comment.f_path,
4112 'comment_f_path': comment.f_path,
4113 'comment_lineno': comment.line_no,
4113 'comment_lineno': comment.line_no,
4114 'comment_author': comment.author,
4114 'comment_author': comment.author,
4115 'comment_created_on': comment.created_on,
4115 'comment_created_on': comment.created_on,
4116 'comment_resolved_by': self.resolved,
4116 'comment_resolved_by': self.resolved,
4117 'comment_commit_id': comment.revision,
4117 'comment_commit_id': comment.revision,
4118 'comment_pull_request_id': comment.pull_request_id,
4118 'comment_pull_request_id': comment.pull_request_id,
4119 'comment_last_version': self.last_version
4119 'comment_last_version': self.last_version
4120 }
4120 }
4121 return data
4121 return data
4122
4122
4123 def __json__(self):
4123 def __json__(self):
4124 data = dict()
4124 data = dict()
4125 data.update(self.get_api_data())
4125 data.update(self.get_api_data())
4126 return data
4126 return data
4127
4127
4128
4128
4129 class ChangesetCommentHistory(Base, BaseModel):
4129 class ChangesetCommentHistory(Base, BaseModel):
4130 __tablename__ = 'changeset_comments_history'
4130 __tablename__ = 'changeset_comments_history'
4131 __table_args__ = (
4131 __table_args__ = (
4132 Index('cch_comment_id_idx', 'comment_id'),
4132 Index('cch_comment_id_idx', 'comment_id'),
4133 base_table_args,
4133 base_table_args,
4134 )
4134 )
4135
4135
4136 comment_history_id = Column('comment_history_id', Integer(), nullable=False, primary_key=True)
4136 comment_history_id = Column('comment_history_id', Integer(), nullable=False, primary_key=True)
4137 comment_id = Column('comment_id', Integer(), ForeignKey('changeset_comments.comment_id'), nullable=False)
4137 comment_id = Column('comment_id', Integer(), ForeignKey('changeset_comments.comment_id'), nullable=False)
4138 version = Column("version", Integer(), nullable=False, default=0)
4138 version = Column("version", Integer(), nullable=False, default=0)
4139 created_by_user_id = Column('created_by_user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
4139 created_by_user_id = Column('created_by_user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
4140 text = Column('text', UnicodeText().with_variant(UnicodeText(25000), 'mysql'), nullable=False)
4140 text = Column('text', UnicodeText().with_variant(UnicodeText(25000), 'mysql'), nullable=False)
4141 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4141 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4142 deleted = Column('deleted', Boolean(), default=False)
4142 deleted = Column('deleted', Boolean(), default=False)
4143
4143
4144 author = relationship('User', lazy='joined')
4144 author = relationship('User', lazy='joined')
4145 comment = relationship('ChangesetComment', cascade="all, delete", back_populates="history")
4145 comment = relationship('ChangesetComment', cascade="all, delete", back_populates="history")
4146
4146
4147 @classmethod
4147 @classmethod
4148 def get_version(cls, comment_id):
4148 def get_version(cls, comment_id):
4149 q = Session().query(ChangesetCommentHistory).filter(
4149 q = Session().query(ChangesetCommentHistory).filter(
4150 ChangesetCommentHistory.comment_id == comment_id).order_by(ChangesetCommentHistory.version.desc())
4150 ChangesetCommentHistory.comment_id == comment_id).order_by(ChangesetCommentHistory.version.desc())
4151 if q.count() == 0:
4151 if q.count() == 0:
4152 return 1
4152 return 1
4153 elif q.count() >= q[0].version:
4153 elif q.count() >= q[0].version:
4154 return q.count() + 1
4154 return q.count() + 1
4155 else:
4155 else:
4156 return q[0].version + 1
4156 return q[0].version + 1
4157
4157
4158
4158
4159 class ChangesetStatus(Base, BaseModel):
4159 class ChangesetStatus(Base, BaseModel):
4160 __tablename__ = 'changeset_statuses'
4160 __tablename__ = 'changeset_statuses'
4161 __table_args__ = (
4161 __table_args__ = (
4162 Index('cs_revision_idx', 'revision'),
4162 Index('cs_revision_idx', 'revision'),
4163 Index('cs_version_idx', 'version'),
4163 Index('cs_version_idx', 'version'),
4164 UniqueConstraint('repo_id', 'revision', 'version'),
4164 UniqueConstraint('repo_id', 'revision', 'version'),
4165 base_table_args
4165 base_table_args
4166 )
4166 )
4167
4167
4168 STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed'
4168 STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed'
4169 STATUS_APPROVED = 'approved'
4169 STATUS_APPROVED = 'approved'
4170 STATUS_REJECTED = 'rejected'
4170 STATUS_REJECTED = 'rejected'
4171 STATUS_UNDER_REVIEW = 'under_review'
4171 STATUS_UNDER_REVIEW = 'under_review'
4172
4172
4173 STATUSES = [
4173 STATUSES = [
4174 (STATUS_NOT_REVIEWED, _("Not Reviewed")), # (no icon) and default
4174 (STATUS_NOT_REVIEWED, _("Not Reviewed")), # (no icon) and default
4175 (STATUS_APPROVED, _("Approved")),
4175 (STATUS_APPROVED, _("Approved")),
4176 (STATUS_REJECTED, _("Rejected")),
4176 (STATUS_REJECTED, _("Rejected")),
4177 (STATUS_UNDER_REVIEW, _("Under Review")),
4177 (STATUS_UNDER_REVIEW, _("Under Review")),
4178 ]
4178 ]
4179
4179
4180 changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True)
4180 changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True)
4181 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
4181 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
4182 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
4182 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
4183 revision = Column('revision', String(40), nullable=False)
4183 revision = Column('revision', String(40), nullable=False)
4184 status = Column('status', String(128), nullable=False, default=DEFAULT)
4184 status = Column('status', String(128), nullable=False, default=DEFAULT)
4185 changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'))
4185 changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'))
4186 modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now)
4186 modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now)
4187 version = Column('version', Integer(), nullable=False, default=0)
4187 version = Column('version', Integer(), nullable=False, default=0)
4188 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
4188 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
4189
4189
4190 author = relationship('User', lazy='select')
4190 author = relationship('User', lazy='select')
4191 repo = relationship('Repository', lazy='select')
4191 repo = relationship('Repository', lazy='select')
4192 comment = relationship('ChangesetComment', lazy='select', back_populates='status_change')
4192 comment = relationship('ChangesetComment', lazy='select', back_populates='status_change')
4193 pull_request = relationship('PullRequest', lazy='select', back_populates='statuses')
4193 pull_request = relationship('PullRequest', lazy='select', back_populates='statuses')
4194
4194
4195 def __repr__(self):
4195 def __repr__(self):
4196 return f"<{self.cls_name}('{self.status}[v{self.version}]:{self.author}')>"
4196 return f"<{self.cls_name}('{self.status}[v{self.version}]:{self.author}')>"
4197
4197
4198 @classmethod
4198 @classmethod
4199 def get_status_lbl(cls, value):
4199 def get_status_lbl(cls, value):
4200 return dict(cls.STATUSES).get(value)
4200 return dict(cls.STATUSES).get(value)
4201
4201
4202 @property
4202 @property
4203 def status_lbl(self):
4203 def status_lbl(self):
4204 return ChangesetStatus.get_status_lbl(self.status)
4204 return ChangesetStatus.get_status_lbl(self.status)
4205
4205
4206 def get_api_data(self):
4206 def get_api_data(self):
4207 status = self
4207 status = self
4208 data = {
4208 data = {
4209 'status_id': status.changeset_status_id,
4209 'status_id': status.changeset_status_id,
4210 'status': status.status,
4210 'status': status.status,
4211 }
4211 }
4212 return data
4212 return data
4213
4213
4214 def __json__(self):
4214 def __json__(self):
4215 data = dict()
4215 data = dict()
4216 data.update(self.get_api_data())
4216 data.update(self.get_api_data())
4217 return data
4217 return data
4218
4218
4219
4219
4220 class _SetState(object):
4220 class _SetState(object):
4221 """
4221 """
4222 Context processor allowing changing state for sensitive operation such as
4222 Context processor allowing changing state for sensitive operation such as
4223 pull request update or merge
4223 pull request update or merge
4224 """
4224 """
4225
4225
4226 def __init__(self, pull_request, pr_state, back_state=None):
4226 def __init__(self, pull_request, pr_state, back_state=None):
4227 self._pr = pull_request
4227 self._pr = pull_request
4228 self._org_state = back_state or pull_request.pull_request_state
4228 self._org_state = back_state or pull_request.pull_request_state
4229 self._pr_state = pr_state
4229 self._pr_state = pr_state
4230 self._current_state = None
4230 self._current_state = None
4231
4231
4232 def __enter__(self):
4232 def __enter__(self):
4233 log.debug('StateLock: entering set state context of pr %s, setting state to: `%s`',
4233 log.debug('StateLock: entering set state context of pr %s, setting state to: `%s`',
4234 self._pr, self._pr_state)
4234 self._pr, self._pr_state)
4235 self.set_pr_state(self._pr_state)
4235 self.set_pr_state(self._pr_state)
4236 return self
4236 return self
4237
4237
4238 def __exit__(self, exc_type, exc_val, exc_tb):
4238 def __exit__(self, exc_type, exc_val, exc_tb):
4239 if exc_val is not None or exc_type is not None:
4239 if exc_val is not None or exc_type is not None:
4240 log.error(traceback.format_tb(exc_tb))
4240 log.error(traceback.format_tb(exc_tb))
4241 return None
4241 return None
4242
4242
4243 self.set_pr_state(self._org_state)
4243 self.set_pr_state(self._org_state)
4244 log.debug('StateLock: exiting set state context of pr %s, setting state to: `%s`',
4244 log.debug('StateLock: exiting set state context of pr %s, setting state to: `%s`',
4245 self._pr, self._org_state)
4245 self._pr, self._org_state)
4246
4246
4247 @property
4247 @property
4248 def state(self):
4248 def state(self):
4249 return self._current_state
4249 return self._current_state
4250
4250
4251 def set_pr_state(self, pr_state):
4251 def set_pr_state(self, pr_state):
4252 try:
4252 try:
4253 self._pr.pull_request_state = pr_state
4253 self._pr.pull_request_state = pr_state
4254 Session().add(self._pr)
4254 Session().add(self._pr)
4255 Session().commit()
4255 Session().commit()
4256 self._current_state = pr_state
4256 self._current_state = pr_state
4257 except Exception:
4257 except Exception:
4258 log.exception('Failed to set PullRequest %s state to %s', self._pr, pr_state)
4258 log.exception('Failed to set PullRequest %s state to %s', self._pr, pr_state)
4259 raise
4259 raise
4260
4260
4261
4261
4262 class _PullRequestBase(BaseModel):
4262 class _PullRequestBase(BaseModel):
4263 """
4263 """
4264 Common attributes of pull request and version entries.
4264 Common attributes of pull request and version entries.
4265 """
4265 """
4266
4266
4267 # .status values
4267 # .status values
4268 STATUS_NEW = 'new'
4268 STATUS_NEW = 'new'
4269 STATUS_OPEN = 'open'
4269 STATUS_OPEN = 'open'
4270 STATUS_CLOSED = 'closed'
4270 STATUS_CLOSED = 'closed'
4271
4271
4272 # available states
4272 # available states
4273 STATE_CREATING = 'creating'
4273 STATE_CREATING = 'creating'
4274 STATE_UPDATING = 'updating'
4274 STATE_UPDATING = 'updating'
4275 STATE_MERGING = 'merging'
4275 STATE_MERGING = 'merging'
4276 STATE_CREATED = 'created'
4276 STATE_CREATED = 'created'
4277
4277
4278 title = Column('title', Unicode(255), nullable=True)
4278 title = Column('title', Unicode(255), nullable=True)
4279 description = Column(
4279 description = Column(
4280 'description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'),
4280 'description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'),
4281 nullable=True)
4281 nullable=True)
4282 description_renderer = Column('description_renderer', Unicode(64), nullable=True)
4282 description_renderer = Column('description_renderer', Unicode(64), nullable=True)
4283
4283
4284 # new/open/closed status of pull request (not approve/reject/etc)
4284 # new/open/closed status of pull request (not approve/reject/etc)
4285 status = Column('status', Unicode(255), nullable=False, default=STATUS_NEW)
4285 status = Column('status', Unicode(255), nullable=False, default=STATUS_NEW)
4286 created_on = Column(
4286 created_on = Column(
4287 'created_on', DateTime(timezone=False), nullable=False,
4287 'created_on', DateTime(timezone=False), nullable=False,
4288 default=datetime.datetime.now)
4288 default=datetime.datetime.now)
4289 updated_on = Column(
4289 updated_on = Column(
4290 'updated_on', DateTime(timezone=False), nullable=False,
4290 'updated_on', DateTime(timezone=False), nullable=False,
4291 default=datetime.datetime.now)
4291 default=datetime.datetime.now)
4292
4292
4293 pull_request_state = Column("pull_request_state", String(255), nullable=True)
4293 pull_request_state = Column("pull_request_state", String(255), nullable=True)
4294
4294
4295 @declared_attr
4295 @declared_attr
4296 def user_id(cls):
4296 def user_id(cls):
4297 return Column(
4297 return Column(
4298 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
4298 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
4299 unique=None)
4299 unique=None)
4300
4300
4301 # 500 revisions max
4301 # 500 revisions max
4302 _revisions = Column(
4302 _revisions = Column(
4303 'revisions', UnicodeText().with_variant(UnicodeText(20500), 'mysql'))
4303 'revisions', UnicodeText().with_variant(UnicodeText(20500), 'mysql'))
4304
4304
4305 common_ancestor_id = Column('common_ancestor_id', Unicode(255), nullable=True)
4305 common_ancestor_id = Column('common_ancestor_id', Unicode(255), nullable=True)
4306
4306
4307 @declared_attr
4307 @declared_attr
4308 def source_repo_id(cls):
4308 def source_repo_id(cls):
4309 # TODO: dan: rename column to source_repo_id
4309 # TODO: dan: rename column to source_repo_id
4310 return Column(
4310 return Column(
4311 'org_repo_id', Integer(), ForeignKey('repositories.repo_id'),
4311 'org_repo_id', Integer(), ForeignKey('repositories.repo_id'),
4312 nullable=False)
4312 nullable=False)
4313
4313
4314 @declared_attr
4314 @declared_attr
4315 def pr_source(cls):
4315 def pr_source(cls):
4316 return relationship(
4316 return relationship(
4317 'Repository',
4317 'Repository',
4318 primaryjoin=f'{cls.__name__}.source_repo_id==Repository.repo_id',
4318 primaryjoin=f'{cls.__name__}.source_repo_id==Repository.repo_id',
4319 overlaps="pull_requests_source"
4319 overlaps="pull_requests_source"
4320 )
4320 )
4321
4321
4322 _source_ref = Column('org_ref', Unicode(255), nullable=False)
4322 _source_ref = Column('org_ref', Unicode(255), nullable=False)
4323
4323
4324 @hybrid_property
4324 @hybrid_property
4325 def source_ref(self):
4325 def source_ref(self):
4326 return self._source_ref
4326 return self._source_ref
4327
4327
4328 @source_ref.setter
4328 @source_ref.setter
4329 def source_ref(self, val):
4329 def source_ref(self, val):
4330 parts = (val or '').split(':')
4330 parts = (val or '').split(':')
4331 if len(parts) != 3:
4331 if len(parts) != 3:
4332 raise ValueError(
4332 raise ValueError(
4333 'Invalid reference format given: {}, expected X:Y:Z'.format(val))
4333 'Invalid reference format given: {}, expected X:Y:Z'.format(val))
4334 self._source_ref = safe_str(val)
4334 self._source_ref = safe_str(val)
4335
4335
4336 _target_ref = Column('other_ref', Unicode(255), nullable=False)
4336 _target_ref = Column('other_ref', Unicode(255), nullable=False)
4337
4337
4338 @hybrid_property
4338 @hybrid_property
4339 def target_ref(self):
4339 def target_ref(self):
4340 return self._target_ref
4340 return self._target_ref
4341
4341
4342 @target_ref.setter
4342 @target_ref.setter
4343 def target_ref(self, val):
4343 def target_ref(self, val):
4344 parts = (val or '').split(':')
4344 parts = (val or '').split(':')
4345 if len(parts) != 3:
4345 if len(parts) != 3:
4346 raise ValueError(
4346 raise ValueError(
4347 'Invalid reference format given: {}, expected X:Y:Z'.format(val))
4347 'Invalid reference format given: {}, expected X:Y:Z'.format(val))
4348 self._target_ref = safe_str(val)
4348 self._target_ref = safe_str(val)
4349
4349
4350 @declared_attr
4350 @declared_attr
4351 def target_repo_id(cls):
4351 def target_repo_id(cls):
4352 # TODO: dan: rename column to target_repo_id
4352 # TODO: dan: rename column to target_repo_id
4353 return Column(
4353 return Column(
4354 'other_repo_id', Integer(), ForeignKey('repositories.repo_id'),
4354 'other_repo_id', Integer(), ForeignKey('repositories.repo_id'),
4355 nullable=False)
4355 nullable=False)
4356
4356
4357 @declared_attr
4357 @declared_attr
4358 def pr_target(cls):
4358 def pr_target(cls):
4359 return relationship(
4359 return relationship(
4360 'Repository',
4360 'Repository',
4361 primaryjoin=f'{cls.__name__}.target_repo_id==Repository.repo_id',
4361 primaryjoin=f'{cls.__name__}.target_repo_id==Repository.repo_id',
4362 overlaps="pull_requests_target"
4362 overlaps="pull_requests_target"
4363 )
4363 )
4364
4364
4365 _shadow_merge_ref = Column('shadow_merge_ref', Unicode(255), nullable=True)
4365 _shadow_merge_ref = Column('shadow_merge_ref', Unicode(255), nullable=True)
4366
4366
4367 # TODO: dan: rename column to last_merge_source_rev
4367 # TODO: dan: rename column to last_merge_source_rev
4368 _last_merge_source_rev = Column(
4368 _last_merge_source_rev = Column(
4369 'last_merge_org_rev', String(40), nullable=True)
4369 'last_merge_org_rev', String(40), nullable=True)
4370 # TODO: dan: rename column to last_merge_target_rev
4370 # TODO: dan: rename column to last_merge_target_rev
4371 _last_merge_target_rev = Column(
4371 _last_merge_target_rev = Column(
4372 'last_merge_other_rev', String(40), nullable=True)
4372 'last_merge_other_rev', String(40), nullable=True)
4373 _last_merge_status = Column('merge_status', Integer(), nullable=True)
4373 _last_merge_status = Column('merge_status', Integer(), nullable=True)
4374 last_merge_metadata = Column(
4374 last_merge_metadata = Column(
4375 'last_merge_metadata', MutationObj.as_mutable(
4375 'last_merge_metadata', MutationObj.as_mutable(
4376 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
4376 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
4377
4377
4378 merge_rev = Column('merge_rev', String(40), nullable=True)
4378 merge_rev = Column('merge_rev', String(40), nullable=True)
4379
4379
4380 reviewer_data = Column(
4380 reviewer_data = Column(
4381 'reviewer_data_json', MutationObj.as_mutable(
4381 'reviewer_data_json', MutationObj.as_mutable(
4382 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
4382 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
4383
4383
4384 @property
4384 @property
4385 def reviewer_data_json(self):
4385 def reviewer_data_json(self):
4386 return str_json(self.reviewer_data)
4386 return str_json(self.reviewer_data)
4387
4387
4388 @property
4388 @property
4389 def last_merge_metadata_parsed(self):
4389 def last_merge_metadata_parsed(self):
4390 metadata = {}
4390 metadata = {}
4391 if not self.last_merge_metadata:
4391 if not self.last_merge_metadata:
4392 return metadata
4392 return metadata
4393
4393
4394 if hasattr(self.last_merge_metadata, 'de_coerce'):
4394 if hasattr(self.last_merge_metadata, 'de_coerce'):
4395 for k, v in self.last_merge_metadata.de_coerce().items():
4395 for k, v in self.last_merge_metadata.de_coerce().items():
4396 if k in ['target_ref', 'source_ref']:
4396 if k in ['target_ref', 'source_ref']:
4397 metadata[k] = Reference(v['type'], v['name'], v['commit_id'])
4397 metadata[k] = Reference(v['type'], v['name'], v['commit_id'])
4398 else:
4398 else:
4399 if hasattr(v, 'de_coerce'):
4399 if hasattr(v, 'de_coerce'):
4400 metadata[k] = v.de_coerce()
4400 metadata[k] = v.de_coerce()
4401 else:
4401 else:
4402 metadata[k] = v
4402 metadata[k] = v
4403 return metadata
4403 return metadata
4404
4404
4405 @property
4405 @property
4406 def work_in_progress(self):
4406 def work_in_progress(self):
4407 """checks if pull request is work in progress by checking the title"""
4407 """checks if pull request is work in progress by checking the title"""
4408 title = self.title.upper()
4408 title = self.title.upper()
4409 if re.match(r'^(\[WIP\]\s*|WIP:\s*|WIP\s+)', title):
4409 if re.match(r'^(\[WIP\]\s*|WIP:\s*|WIP\s+)', title):
4410 return True
4410 return True
4411 return False
4411 return False
4412
4412
4413 @property
4413 @property
4414 def title_safe(self):
4414 def title_safe(self):
4415 return self.title\
4415 return self.title\
4416 .replace('{', '{{')\
4416 .replace('{', '{{')\
4417 .replace('}', '}}')
4417 .replace('}', '}}')
4418
4418
4419 @hybrid_property
4419 @hybrid_property
4420 def description_safe(self):
4420 def description_safe(self):
4421 from rhodecode.lib import helpers as h
4421 from rhodecode.lib import helpers as h
4422 return h.escape(self.description)
4422 return h.escape(self.description)
4423
4423
4424 @hybrid_property
4424 @hybrid_property
4425 def revisions(self):
4425 def revisions(self):
4426 return self._revisions.split(':') if self._revisions else []
4426 return self._revisions.split(':') if self._revisions else []
4427
4427
4428 @revisions.setter
4428 @revisions.setter
4429 def revisions(self, val):
4429 def revisions(self, val):
4430 self._revisions = ':'.join(val)
4430 self._revisions = ':'.join(val)
4431
4431
4432 @hybrid_property
4432 @hybrid_property
4433 def last_merge_status(self):
4433 def last_merge_status(self):
4434 return safe_int(self._last_merge_status)
4434 return safe_int(self._last_merge_status)
4435
4435
4436 @last_merge_status.setter
4436 @last_merge_status.setter
4437 def last_merge_status(self, val):
4437 def last_merge_status(self, val):
4438 self._last_merge_status = val
4438 self._last_merge_status = val
4439
4439
4440 @declared_attr
4440 @declared_attr
4441 def author(cls):
4441 def author(cls):
4442 return relationship(
4442 return relationship(
4443 'User', lazy='joined',
4443 'User', lazy='joined',
4444 #TODO, problem that is somehow :?
4444 #TODO, problem that is somehow :?
4445 #back_populates='user_pull_requests'
4445 #back_populates='user_pull_requests'
4446 )
4446 )
4447
4447
4448 @declared_attr
4448 @declared_attr
4449 def source_repo(cls):
4449 def source_repo(cls):
4450 return relationship(
4450 return relationship(
4451 'Repository',
4451 'Repository',
4452 primaryjoin=f'{cls.__name__}.source_repo_id==Repository.repo_id',
4452 primaryjoin=f'{cls.__name__}.source_repo_id==Repository.repo_id',
4453 overlaps="pr_source"
4453 overlaps="pr_source"
4454 )
4454 )
4455
4455
4456 @property
4456 @property
4457 def source_ref_parts(self):
4457 def source_ref_parts(self):
4458 return self.unicode_to_reference(self.source_ref)
4458 return self.unicode_to_reference(self.source_ref)
4459
4459
4460 @declared_attr
4460 @declared_attr
4461 def target_repo(cls):
4461 def target_repo(cls):
4462 return relationship(
4462 return relationship(
4463 'Repository',
4463 'Repository',
4464 primaryjoin=f'{cls.__name__}.target_repo_id==Repository.repo_id',
4464 primaryjoin=f'{cls.__name__}.target_repo_id==Repository.repo_id',
4465 overlaps="pr_target"
4465 overlaps="pr_target"
4466 )
4466 )
4467
4467
4468 @property
4468 @property
4469 def target_ref_parts(self):
4469 def target_ref_parts(self):
4470 return self.unicode_to_reference(self.target_ref)
4470 return self.unicode_to_reference(self.target_ref)
4471
4471
4472 @property
4472 @property
4473 def shadow_merge_ref(self):
4473 def shadow_merge_ref(self):
4474 return self.unicode_to_reference(self._shadow_merge_ref)
4474 return self.unicode_to_reference(self._shadow_merge_ref)
4475
4475
4476 @shadow_merge_ref.setter
4476 @shadow_merge_ref.setter
4477 def shadow_merge_ref(self, ref):
4477 def shadow_merge_ref(self, ref):
4478 self._shadow_merge_ref = self.reference_to_unicode(ref)
4478 self._shadow_merge_ref = self.reference_to_unicode(ref)
4479
4479
4480 @staticmethod
4480 @staticmethod
4481 def unicode_to_reference(raw):
4481 def unicode_to_reference(raw):
4482 return unicode_to_reference(raw)
4482 return unicode_to_reference(raw)
4483
4483
4484 @staticmethod
4484 @staticmethod
4485 def reference_to_unicode(ref):
4485 def reference_to_unicode(ref):
4486 return reference_to_unicode(ref)
4486 return reference_to_unicode(ref)
4487
4487
4488 def get_api_data(self, with_merge_state=True):
4488 def get_api_data(self, with_merge_state=True):
4489 from rhodecode.model.pull_request import PullRequestModel
4489 from rhodecode.model.pull_request import PullRequestModel
4490
4490
4491 pull_request = self
4491 pull_request = self
4492 if with_merge_state:
4492 if with_merge_state:
4493 merge_response, merge_status, msg = \
4493 merge_response, merge_status, msg = \
4494 PullRequestModel().merge_status(pull_request)
4494 PullRequestModel().merge_status(pull_request)
4495 merge_state = {
4495 merge_state = {
4496 'status': merge_status,
4496 'status': merge_status,
4497 'message': safe_str(msg),
4497 'message': safe_str(msg),
4498 }
4498 }
4499 else:
4499 else:
4500 merge_state = {'status': 'not_available',
4500 merge_state = {'status': 'not_available',
4501 'message': 'not_available'}
4501 'message': 'not_available'}
4502
4502
4503 merge_data = {
4503 merge_data = {
4504 'clone_url': PullRequestModel().get_shadow_clone_url(pull_request),
4504 'clone_url': PullRequestModel().get_shadow_clone_url(pull_request),
4505 'reference': (
4505 'reference': (
4506 pull_request.shadow_merge_ref.asdict()
4506 pull_request.shadow_merge_ref.asdict()
4507 if pull_request.shadow_merge_ref else None),
4507 if pull_request.shadow_merge_ref else None),
4508 }
4508 }
4509
4509
4510 data = {
4510 data = {
4511 'pull_request_id': pull_request.pull_request_id,
4511 'pull_request_id': pull_request.pull_request_id,
4512 'url': PullRequestModel().get_url(pull_request),
4512 'url': PullRequestModel().get_url(pull_request),
4513 'title': pull_request.title,
4513 'title': pull_request.title,
4514 'description': pull_request.description,
4514 'description': pull_request.description,
4515 'status': pull_request.status,
4515 'status': pull_request.status,
4516 'state': pull_request.pull_request_state,
4516 'state': pull_request.pull_request_state,
4517 'created_on': pull_request.created_on,
4517 'created_on': pull_request.created_on,
4518 'updated_on': pull_request.updated_on,
4518 'updated_on': pull_request.updated_on,
4519 'commit_ids': pull_request.revisions,
4519 'commit_ids': pull_request.revisions,
4520 'review_status': pull_request.calculated_review_status(),
4520 'review_status': pull_request.calculated_review_status(),
4521 'mergeable': merge_state,
4521 'mergeable': merge_state,
4522 'source': {
4522 'source': {
4523 'clone_url': pull_request.source_repo.clone_url(),
4523 'clone_url': pull_request.source_repo.clone_url(),
4524 'repository': pull_request.source_repo.repo_name,
4524 'repository': pull_request.source_repo.repo_name,
4525 'reference': {
4525 'reference': {
4526 'name': pull_request.source_ref_parts.name,
4526 'name': pull_request.source_ref_parts.name,
4527 'type': pull_request.source_ref_parts.type,
4527 'type': pull_request.source_ref_parts.type,
4528 'commit_id': pull_request.source_ref_parts.commit_id,
4528 'commit_id': pull_request.source_ref_parts.commit_id,
4529 },
4529 },
4530 },
4530 },
4531 'target': {
4531 'target': {
4532 'clone_url': pull_request.target_repo.clone_url(),
4532 'clone_url': pull_request.target_repo.clone_url(),
4533 'repository': pull_request.target_repo.repo_name,
4533 'repository': pull_request.target_repo.repo_name,
4534 'reference': {
4534 'reference': {
4535 'name': pull_request.target_ref_parts.name,
4535 'name': pull_request.target_ref_parts.name,
4536 'type': pull_request.target_ref_parts.type,
4536 'type': pull_request.target_ref_parts.type,
4537 'commit_id': pull_request.target_ref_parts.commit_id,
4537 'commit_id': pull_request.target_ref_parts.commit_id,
4538 },
4538 },
4539 },
4539 },
4540 'merge': merge_data,
4540 'merge': merge_data,
4541 'author': pull_request.author.get_api_data(include_secrets=False,
4541 'author': pull_request.author.get_api_data(include_secrets=False,
4542 details='basic'),
4542 details='basic'),
4543 'reviewers': [
4543 'reviewers': [
4544 {
4544 {
4545 'user': reviewer.get_api_data(include_secrets=False,
4545 'user': reviewer.get_api_data(include_secrets=False,
4546 details='basic'),
4546 details='basic'),
4547 'reasons': reasons,
4547 'reasons': reasons,
4548 'review_status': st[0][1].status if st else 'not_reviewed',
4548 'review_status': st[0][1].status if st else 'not_reviewed',
4549 }
4549 }
4550 for obj, reviewer, reasons, mandatory, st in
4550 for obj, reviewer, reasons, mandatory, st in
4551 pull_request.reviewers_statuses()
4551 pull_request.reviewers_statuses()
4552 ]
4552 ]
4553 }
4553 }
4554
4554
4555 return data
4555 return data
4556
4556
4557 def set_state(self, pull_request_state, final_state=None):
4557 def set_state(self, pull_request_state, final_state=None):
4558 """
4558 """
4559 # goes from initial state to updating to initial state.
4559 # goes from initial state to updating to initial state.
4560 # initial state can be changed by specifying back_state=
4560 # initial state can be changed by specifying back_state=
4561 with pull_request_obj.set_state(PullRequest.STATE_UPDATING):
4561 with pull_request_obj.set_state(PullRequest.STATE_UPDATING):
4562 pull_request.merge()
4562 pull_request.merge()
4563
4563
4564 :param pull_request_state:
4564 :param pull_request_state:
4565 :param final_state:
4565 :param final_state:
4566
4566
4567 """
4567 """
4568
4568
4569 return _SetState(self, pull_request_state, back_state=final_state)
4569 return _SetState(self, pull_request_state, back_state=final_state)
4570
4570
4571
4571
4572 class PullRequest(Base, _PullRequestBase):
4572 class PullRequest(Base, _PullRequestBase):
4573 __tablename__ = 'pull_requests'
4573 __tablename__ = 'pull_requests'
4574 __table_args__ = (
4574 __table_args__ = (
4575 base_table_args,
4575 base_table_args,
4576 )
4576 )
4577 LATEST_VER = 'latest'
4577 LATEST_VER = 'latest'
4578
4578
4579 pull_request_id = Column(
4579 pull_request_id = Column(
4580 'pull_request_id', Integer(), nullable=False, primary_key=True)
4580 'pull_request_id', Integer(), nullable=False, primary_key=True)
4581
4581
4582 def __repr__(self):
4582 def __repr__(self):
4583 if self.pull_request_id:
4583 if self.pull_request_id:
4584 return f'<DB:PullRequest #{self.pull_request_id}>'
4584 return f'<DB:PullRequest #{self.pull_request_id}>'
4585 else:
4585 else:
4586 return f'<DB:PullRequest at {id(self)!r}>'
4586 return f'<DB:PullRequest at {id(self)!r}>'
4587
4587
4588 reviewers = relationship('PullRequestReviewers', cascade="all, delete-orphan", back_populates='pull_request')
4588 reviewers = relationship('PullRequestReviewers', cascade="all, delete-orphan", back_populates='pull_request')
4589 statuses = relationship('ChangesetStatus', cascade="all, delete-orphan", back_populates='pull_request')
4589 statuses = relationship('ChangesetStatus', cascade="all, delete-orphan", back_populates='pull_request')
4590 comments = relationship('ChangesetComment', cascade="all, delete-orphan", back_populates='pull_request')
4590 comments = relationship('ChangesetComment', cascade="all, delete-orphan", back_populates='pull_request')
4591 versions = relationship('PullRequestVersion', cascade="all, delete-orphan", lazy='dynamic', back_populates='pull_request')
4591 versions = relationship('PullRequestVersion', cascade="all, delete-orphan", lazy='dynamic', back_populates='pull_request')
4592
4592
4593 @classmethod
4593 @classmethod
4594 def get_pr_display_object(cls, pull_request_obj, org_pull_request_obj,
4594 def get_pr_display_object(cls, pull_request_obj, org_pull_request_obj,
4595 internal_methods=None):
4595 internal_methods=None):
4596
4596
4597 class PullRequestDisplay(object):
4597 class PullRequestDisplay(object):
4598 """
4598 """
4599 Special object wrapper for showing PullRequest data via Versions
4599 Special object wrapper for showing PullRequest data via Versions
4600 It mimics PR object as close as possible. This is read only object
4600 It mimics PR object as close as possible. This is read only object
4601 just for display
4601 just for display
4602 """
4602 """
4603
4603
4604 def __init__(self, attrs, internal=None):
4604 def __init__(self, attrs, internal=None):
4605 self.attrs = attrs
4605 self.attrs = attrs
4606 # internal have priority over the given ones via attrs
4606 # internal have priority over the given ones via attrs
4607 self.internal = internal or ['versions']
4607 self.internal = internal or ['versions']
4608
4608
4609 def __getattr__(self, item):
4609 def __getattr__(self, item):
4610 if item in self.internal:
4610 if item in self.internal:
4611 return getattr(self, item)
4611 return getattr(self, item)
4612 try:
4612 try:
4613 return self.attrs[item]
4613 return self.attrs[item]
4614 except KeyError:
4614 except KeyError:
4615 raise AttributeError(
4615 raise AttributeError(
4616 '%s object has no attribute %s' % (self, item))
4616 '%s object has no attribute %s' % (self, item))
4617
4617
4618 def __repr__(self):
4618 def __repr__(self):
4619 pr_id = self.attrs.get('pull_request_id')
4619 pr_id = self.attrs.get('pull_request_id')
4620 return f'<DB:PullRequestDisplay #{pr_id}>'
4620 return f'<DB:PullRequestDisplay #{pr_id}>'
4621
4621
4622 def versions(self):
4622 def versions(self):
4623 return pull_request_obj.versions.order_by(
4623 return pull_request_obj.versions.order_by(
4624 PullRequestVersion.pull_request_version_id).all()
4624 PullRequestVersion.pull_request_version_id).all()
4625
4625
4626 def is_closed(self):
4626 def is_closed(self):
4627 return pull_request_obj.is_closed()
4627 return pull_request_obj.is_closed()
4628
4628
4629 def is_state_changing(self):
4629 def is_state_changing(self):
4630 return pull_request_obj.is_state_changing()
4630 return pull_request_obj.is_state_changing()
4631
4631
4632 @property
4632 @property
4633 def pull_request_version_id(self):
4633 def pull_request_version_id(self):
4634 return getattr(pull_request_obj, 'pull_request_version_id', None)
4634 return getattr(pull_request_obj, 'pull_request_version_id', None)
4635
4635
4636 @property
4636 @property
4637 def pull_request_last_version(self):
4637 def pull_request_last_version(self):
4638 return pull_request_obj.pull_request_last_version
4638 return pull_request_obj.pull_request_last_version
4639
4639
4640 attrs = StrictAttributeDict(pull_request_obj.get_api_data(with_merge_state=False))
4640 attrs = StrictAttributeDict(pull_request_obj.get_api_data(with_merge_state=False))
4641
4641
4642 attrs.author = StrictAttributeDict(
4642 attrs.author = StrictAttributeDict(
4643 pull_request_obj.author.get_api_data())
4643 pull_request_obj.author.get_api_data())
4644 if pull_request_obj.target_repo:
4644 if pull_request_obj.target_repo:
4645 attrs.target_repo = StrictAttributeDict(
4645 attrs.target_repo = StrictAttributeDict(
4646 pull_request_obj.target_repo.get_api_data())
4646 pull_request_obj.target_repo.get_api_data())
4647 attrs.target_repo.clone_url = pull_request_obj.target_repo.clone_url
4647 attrs.target_repo.clone_url = pull_request_obj.target_repo.clone_url
4648
4648
4649 if pull_request_obj.source_repo:
4649 if pull_request_obj.source_repo:
4650 attrs.source_repo = StrictAttributeDict(
4650 attrs.source_repo = StrictAttributeDict(
4651 pull_request_obj.source_repo.get_api_data())
4651 pull_request_obj.source_repo.get_api_data())
4652 attrs.source_repo.clone_url = pull_request_obj.source_repo.clone_url
4652 attrs.source_repo.clone_url = pull_request_obj.source_repo.clone_url
4653
4653
4654 attrs.source_ref_parts = pull_request_obj.source_ref_parts
4654 attrs.source_ref_parts = pull_request_obj.source_ref_parts
4655 attrs.target_ref_parts = pull_request_obj.target_ref_parts
4655 attrs.target_ref_parts = pull_request_obj.target_ref_parts
4656 attrs.revisions = pull_request_obj.revisions
4656 attrs.revisions = pull_request_obj.revisions
4657 attrs.common_ancestor_id = pull_request_obj.common_ancestor_id
4657 attrs.common_ancestor_id = pull_request_obj.common_ancestor_id
4658 attrs.shadow_merge_ref = org_pull_request_obj.shadow_merge_ref
4658 attrs.shadow_merge_ref = org_pull_request_obj.shadow_merge_ref
4659 attrs.reviewer_data = org_pull_request_obj.reviewer_data
4659 attrs.reviewer_data = org_pull_request_obj.reviewer_data
4660 attrs.reviewer_data_json = org_pull_request_obj.reviewer_data_json
4660 attrs.reviewer_data_json = org_pull_request_obj.reviewer_data_json
4661
4661
4662 return PullRequestDisplay(attrs, internal=internal_methods)
4662 return PullRequestDisplay(attrs, internal=internal_methods)
4663
4663
4664 def is_closed(self):
4664 def is_closed(self):
4665 return self.status == self.STATUS_CLOSED
4665 return self.status == self.STATUS_CLOSED
4666
4666
4667 def is_state_changing(self):
4667 def is_state_changing(self):
4668 return self.pull_request_state != PullRequest.STATE_CREATED
4668 return self.pull_request_state != PullRequest.STATE_CREATED
4669
4669
4670 def __json__(self):
4670 def __json__(self):
4671 return {
4671 return {
4672 'revisions': self.revisions,
4672 'revisions': self.revisions,
4673 'versions': self.versions_count
4673 'versions': self.versions_count
4674 }
4674 }
4675
4675
4676 def calculated_review_status(self):
4676 def calculated_review_status(self):
4677 from rhodecode.model.changeset_status import ChangesetStatusModel
4677 from rhodecode.model.changeset_status import ChangesetStatusModel
4678 return ChangesetStatusModel().calculated_review_status(self)
4678 return ChangesetStatusModel().calculated_review_status(self)
4679
4679
4680 def reviewers_statuses(self, user=None):
4680 def reviewers_statuses(self, user=None):
4681 from rhodecode.model.changeset_status import ChangesetStatusModel
4681 from rhodecode.model.changeset_status import ChangesetStatusModel
4682 return ChangesetStatusModel().reviewers_statuses(self, user=user)
4682 return ChangesetStatusModel().reviewers_statuses(self, user=user)
4683
4683
4684 def get_pull_request_reviewers(self, role=None):
4684 def get_pull_request_reviewers(self, role=None):
4685 qry = PullRequestReviewers.query()\
4685 qry = PullRequestReviewers.query()\
4686 .filter(PullRequestReviewers.pull_request_id == self.pull_request_id)
4686 .filter(PullRequestReviewers.pull_request_id == self.pull_request_id)
4687 if role:
4687 if role:
4688 qry = qry.filter(PullRequestReviewers.role == role)
4688 qry = qry.filter(PullRequestReviewers.role == role)
4689
4689
4690 return qry.all()
4690 return qry.all()
4691
4691
4692 @property
4692 @property
4693 def reviewers_count(self):
4693 def reviewers_count(self):
4694 qry = PullRequestReviewers.query()\
4694 qry = PullRequestReviewers.query()\
4695 .filter(PullRequestReviewers.pull_request_id == self.pull_request_id)\
4695 .filter(PullRequestReviewers.pull_request_id == self.pull_request_id)\
4696 .filter(PullRequestReviewers.role == PullRequestReviewers.ROLE_REVIEWER)
4696 .filter(PullRequestReviewers.role == PullRequestReviewers.ROLE_REVIEWER)
4697 return qry.count()
4697 return qry.count()
4698
4698
4699 @property
4699 @property
4700 def observers_count(self):
4700 def observers_count(self):
4701 qry = PullRequestReviewers.query()\
4701 qry = PullRequestReviewers.query()\
4702 .filter(PullRequestReviewers.pull_request_id == self.pull_request_id)\
4702 .filter(PullRequestReviewers.pull_request_id == self.pull_request_id)\
4703 .filter(PullRequestReviewers.role == PullRequestReviewers.ROLE_OBSERVER)
4703 .filter(PullRequestReviewers.role == PullRequestReviewers.ROLE_OBSERVER)
4704 return qry.count()
4704 return qry.count()
4705
4705
4706 def observers(self):
4706 def observers(self):
4707 qry = PullRequestReviewers.query()\
4707 qry = PullRequestReviewers.query()\
4708 .filter(PullRequestReviewers.pull_request_id == self.pull_request_id)\
4708 .filter(PullRequestReviewers.pull_request_id == self.pull_request_id)\
4709 .filter(PullRequestReviewers.role == PullRequestReviewers.ROLE_OBSERVER)\
4709 .filter(PullRequestReviewers.role == PullRequestReviewers.ROLE_OBSERVER)\
4710 .all()
4710 .all()
4711
4711
4712 for entry in qry:
4712 for entry in qry:
4713 yield entry, entry.user
4713 yield entry, entry.user
4714
4714
4715 @property
4715 @property
4716 def workspace_id(self):
4716 def workspace_id(self):
4717 from rhodecode.model.pull_request import PullRequestModel
4717 from rhodecode.model.pull_request import PullRequestModel
4718 return PullRequestModel()._workspace_id(self)
4718 return PullRequestModel()._workspace_id(self)
4719
4719
4720 def get_shadow_repo(self):
4720 def get_shadow_repo(self):
4721 workspace_id = self.workspace_id
4721 workspace_id = self.workspace_id
4722 shadow_repository_path = self.target_repo.get_shadow_repository_path(workspace_id)
4722 shadow_repository_path = self.target_repo.get_shadow_repository_path(workspace_id)
4723 if os.path.isdir(shadow_repository_path):
4723 if os.path.isdir(shadow_repository_path):
4724 vcs_obj = self.target_repo.scm_instance()
4724 vcs_obj = self.target_repo.scm_instance()
4725 return vcs_obj.get_shadow_instance(shadow_repository_path)
4725 return vcs_obj.get_shadow_instance(shadow_repository_path)
4726
4726
4727 @property
4727 @property
4728 def versions_count(self):
4728 def versions_count(self):
4729 """
4729 """
4730 return number of versions this PR have, e.g a PR that once been
4730 return number of versions this PR have, e.g a PR that once been
4731 updated will have 2 versions
4731 updated will have 2 versions
4732 """
4732 """
4733 return self.versions.count() + 1
4733 return self.versions.count() + 1
4734
4734
4735 @property
4735 @property
4736 def pull_request_last_version(self):
4736 def pull_request_last_version(self):
4737 return self.versions_count
4737 return self.versions_count
4738
4738
4739
4739
4740 class PullRequestVersion(Base, _PullRequestBase):
4740 class PullRequestVersion(Base, _PullRequestBase):
4741 __tablename__ = 'pull_request_versions'
4741 __tablename__ = 'pull_request_versions'
4742 __table_args__ = (
4742 __table_args__ = (
4743 base_table_args,
4743 base_table_args,
4744 )
4744 )
4745
4745
4746 pull_request_version_id = Column('pull_request_version_id', Integer(), nullable=False, primary_key=True)
4746 pull_request_version_id = Column('pull_request_version_id', Integer(), nullable=False, primary_key=True)
4747 pull_request_id = Column('pull_request_id', Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=False)
4747 pull_request_id = Column('pull_request_id', Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=False)
4748 pull_request = relationship('PullRequest', back_populates='versions')
4748 pull_request = relationship('PullRequest', back_populates='versions')
4749
4749
4750 def __repr__(self):
4750 def __repr__(self):
4751 if self.pull_request_version_id:
4751 if self.pull_request_version_id:
4752 return f'<DB:PullRequestVersion #{self.pull_request_version_id}>'
4752 return f'<DB:PullRequestVersion #{self.pull_request_version_id}>'
4753 else:
4753 else:
4754 return f'<DB:PullRequestVersion at {id(self)!r}>'
4754 return f'<DB:PullRequestVersion at {id(self)!r}>'
4755
4755
4756 @property
4756 @property
4757 def reviewers(self):
4757 def reviewers(self):
4758 return self.pull_request.reviewers
4758 return self.pull_request.reviewers
4759
4759
4760 @property
4760 @property
4761 def versions(self):
4761 def versions(self):
4762 return self.pull_request.versions
4762 return self.pull_request.versions
4763
4763
4764 def is_closed(self):
4764 def is_closed(self):
4765 # calculate from original
4765 # calculate from original
4766 return self.pull_request.status == self.STATUS_CLOSED
4766 return self.pull_request.status == self.STATUS_CLOSED
4767
4767
4768 def is_state_changing(self):
4768 def is_state_changing(self):
4769 return self.pull_request.pull_request_state != PullRequest.STATE_CREATED
4769 return self.pull_request.pull_request_state != PullRequest.STATE_CREATED
4770
4770
4771 def calculated_review_status(self):
4771 def calculated_review_status(self):
4772 return self.pull_request.calculated_review_status()
4772 return self.pull_request.calculated_review_status()
4773
4773
4774 def reviewers_statuses(self):
4774 def reviewers_statuses(self):
4775 return self.pull_request.reviewers_statuses()
4775 return self.pull_request.reviewers_statuses()
4776
4776
4777 def observers(self):
4777 def observers(self):
4778 return self.pull_request.observers()
4778 return self.pull_request.observers()
4779
4779
4780
4780
4781 class PullRequestReviewers(Base, BaseModel):
4781 class PullRequestReviewers(Base, BaseModel):
4782 __tablename__ = 'pull_request_reviewers'
4782 __tablename__ = 'pull_request_reviewers'
4783 __table_args__ = (
4783 __table_args__ = (
4784 base_table_args,
4784 base_table_args,
4785 )
4785 )
4786 ROLE_REVIEWER = 'reviewer'
4786 ROLE_REVIEWER = 'reviewer'
4787 ROLE_OBSERVER = 'observer'
4787 ROLE_OBSERVER = 'observer'
4788 ROLES = [ROLE_REVIEWER, ROLE_OBSERVER]
4788 ROLES = [ROLE_REVIEWER, ROLE_OBSERVER]
4789
4789
4790 @hybrid_property
4790 @hybrid_property
4791 def reasons(self):
4791 def reasons(self):
4792 if not self._reasons:
4792 if not self._reasons:
4793 return []
4793 return []
4794 return self._reasons
4794 return self._reasons
4795
4795
4796 @reasons.setter
4796 @reasons.setter
4797 def reasons(self, val):
4797 def reasons(self, val):
4798 val = val or []
4798 val = val or []
4799 if any(not isinstance(x, str) for x in val):
4799 if any(not isinstance(x, str) for x in val):
4800 raise Exception('invalid reasons type, must be list of strings')
4800 raise Exception('invalid reasons type, must be list of strings')
4801 self._reasons = val
4801 self._reasons = val
4802
4802
4803 pull_requests_reviewers_id = Column(
4803 pull_requests_reviewers_id = Column(
4804 'pull_requests_reviewers_id', Integer(), nullable=False,
4804 'pull_requests_reviewers_id', Integer(), nullable=False,
4805 primary_key=True)
4805 primary_key=True)
4806 pull_request_id = Column(
4806 pull_request_id = Column(
4807 "pull_request_id", Integer(),
4807 "pull_request_id", Integer(),
4808 ForeignKey('pull_requests.pull_request_id'), nullable=False)
4808 ForeignKey('pull_requests.pull_request_id'), nullable=False)
4809 user_id = Column(
4809 user_id = Column(
4810 "user_id", Integer(), ForeignKey('users.user_id'), nullable=True)
4810 "user_id", Integer(), ForeignKey('users.user_id'), nullable=True)
4811 _reasons = Column(
4811 _reasons = Column(
4812 'reason', MutationList.as_mutable(
4812 'reason', MutationList.as_mutable(
4813 JsonType('list', dialect_map=dict(mysql=UnicodeText(16384)))))
4813 JsonType('list', dialect_map=dict(mysql=UnicodeText(16384)))))
4814
4814
4815 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4815 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4816 role = Column('role', Unicode(255), nullable=True, default=ROLE_REVIEWER)
4816 role = Column('role', Unicode(255), nullable=True, default=ROLE_REVIEWER)
4817
4817
4818 user = relationship('User')
4818 user = relationship('User')
4819 pull_request = relationship('PullRequest', back_populates='reviewers')
4819 pull_request = relationship('PullRequest', back_populates='reviewers')
4820
4820
4821 rule_data = Column(
4821 rule_data = Column(
4822 'rule_data_json',
4822 'rule_data_json',
4823 JsonType(dialect_map=dict(mysql=UnicodeText(16384))))
4823 JsonType(dialect_map=dict(mysql=UnicodeText(16384))))
4824
4824
4825 def rule_user_group_data(self):
4825 def rule_user_group_data(self):
4826 """
4826 """
4827 Returns the voting user group rule data for this reviewer
4827 Returns the voting user group rule data for this reviewer
4828 """
4828 """
4829
4829
4830 if self.rule_data and 'vote_rule' in self.rule_data:
4830 if self.rule_data and 'vote_rule' in self.rule_data:
4831 user_group_data = {}
4831 user_group_data = {}
4832 if 'rule_user_group_entry_id' in self.rule_data:
4832 if 'rule_user_group_entry_id' in self.rule_data:
4833 # means a group with voting rules !
4833 # means a group with voting rules !
4834 user_group_data['id'] = self.rule_data['rule_user_group_entry_id']
4834 user_group_data['id'] = self.rule_data['rule_user_group_entry_id']
4835 user_group_data['name'] = self.rule_data['rule_name']
4835 user_group_data['name'] = self.rule_data['rule_name']
4836 user_group_data['vote_rule'] = self.rule_data['vote_rule']
4836 user_group_data['vote_rule'] = self.rule_data['vote_rule']
4837
4837
4838 return user_group_data
4838 return user_group_data
4839
4839
4840 @classmethod
4840 @classmethod
4841 def get_pull_request_reviewers(cls, pull_request_id, role=None):
4841 def get_pull_request_reviewers(cls, pull_request_id, role=None):
4842 qry = PullRequestReviewers.query()\
4842 qry = PullRequestReviewers.query()\
4843 .filter(PullRequestReviewers.pull_request_id == pull_request_id)
4843 .filter(PullRequestReviewers.pull_request_id == pull_request_id)
4844 if role:
4844 if role:
4845 qry = qry.filter(PullRequestReviewers.role == role)
4845 qry = qry.filter(PullRequestReviewers.role == role)
4846
4846
4847 return qry.all()
4847 return qry.all()
4848
4848
4849 def __repr__(self):
4849 def __repr__(self):
4850 return f"<{self.cls_name}('id:{self.pull_requests_reviewers_id}')>"
4850 return f"<{self.cls_name}('id:{self.pull_requests_reviewers_id}')>"
4851
4851
4852
4852
4853 class Notification(Base, BaseModel):
4853 class Notification(Base, BaseModel):
4854 __tablename__ = 'notifications'
4854 __tablename__ = 'notifications'
4855 __table_args__ = (
4855 __table_args__ = (
4856 Index('notification_type_idx', 'type'),
4856 Index('notification_type_idx', 'type'),
4857 base_table_args,
4857 base_table_args,
4858 )
4858 )
4859
4859
4860 TYPE_CHANGESET_COMMENT = 'cs_comment'
4860 TYPE_CHANGESET_COMMENT = 'cs_comment'
4861 TYPE_MESSAGE = 'message'
4861 TYPE_MESSAGE = 'message'
4862 TYPE_MENTION = 'mention'
4862 TYPE_MENTION = 'mention'
4863 TYPE_REGISTRATION = 'registration'
4863 TYPE_REGISTRATION = 'registration'
4864 TYPE_PULL_REQUEST = 'pull_request'
4864 TYPE_PULL_REQUEST = 'pull_request'
4865 TYPE_PULL_REQUEST_COMMENT = 'pull_request_comment'
4865 TYPE_PULL_REQUEST_COMMENT = 'pull_request_comment'
4866 TYPE_PULL_REQUEST_UPDATE = 'pull_request_update'
4866 TYPE_PULL_REQUEST_UPDATE = 'pull_request_update'
4867
4867
4868 notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True)
4868 notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True)
4869 subject = Column('subject', Unicode(512), nullable=True)
4869 subject = Column('subject', Unicode(512), nullable=True)
4870 body = Column('body', UnicodeText().with_variant(UnicodeText(50000), 'mysql'), nullable=True)
4870 body = Column('body', UnicodeText().with_variant(UnicodeText(50000), 'mysql'), nullable=True)
4871 created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True)
4871 created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True)
4872 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4872 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4873 type_ = Column('type', Unicode(255))
4873 type_ = Column('type', Unicode(255))
4874
4874
4875 created_by_user = relationship('User', back_populates='user_created_notifications')
4875 created_by_user = relationship('User', back_populates='user_created_notifications')
4876 notifications_to_users = relationship('UserNotification', lazy='joined', cascade="all, delete-orphan", back_populates='notification')
4876 notifications_to_users = relationship('UserNotification', lazy='joined', cascade="all, delete-orphan", back_populates='notification')
4877
4877
4878 @property
4878 @property
4879 def recipients(self):
4879 def recipients(self):
4880 return [x.user for x in UserNotification.query()\
4880 return [x.user for x in UserNotification.query()\
4881 .filter(UserNotification.notification == self)\
4881 .filter(UserNotification.notification == self)\
4882 .order_by(UserNotification.user_id.asc()).all()]
4882 .order_by(UserNotification.user_id.asc()).all()]
4883
4883
4884 @classmethod
4884 @classmethod
4885 def create(cls, created_by, subject, body, recipients, type_=None):
4885 def create(cls, created_by, subject, body, recipients, type_=None):
4886 if type_ is None:
4886 if type_ is None:
4887 type_ = Notification.TYPE_MESSAGE
4887 type_ = Notification.TYPE_MESSAGE
4888
4888
4889 notification = cls()
4889 notification = cls()
4890 notification.created_by_user = created_by
4890 notification.created_by_user = created_by
4891 notification.subject = subject
4891 notification.subject = subject
4892 notification.body = body
4892 notification.body = body
4893 notification.type_ = type_
4893 notification.type_ = type_
4894 notification.created_on = datetime.datetime.now()
4894 notification.created_on = datetime.datetime.now()
4895
4895
4896 # For each recipient link the created notification to his account
4896 # For each recipient link the created notification to his account
4897 for u in recipients:
4897 for u in recipients:
4898 assoc = UserNotification()
4898 assoc = UserNotification()
4899 assoc.user_id = u.user_id
4899 assoc.user_id = u.user_id
4900 assoc.notification = notification
4900 assoc.notification = notification
4901
4901
4902 # if created_by is inside recipients mark his notification
4902 # if created_by is inside recipients mark his notification
4903 # as read
4903 # as read
4904 if u.user_id == created_by.user_id:
4904 if u.user_id == created_by.user_id:
4905 assoc.read = True
4905 assoc.read = True
4906 Session().add(assoc)
4906 Session().add(assoc)
4907
4907
4908 Session().add(notification)
4908 Session().add(notification)
4909
4909
4910 return notification
4910 return notification
4911
4911
4912
4912
4913 class UserNotification(Base, BaseModel):
4913 class UserNotification(Base, BaseModel):
4914 __tablename__ = 'user_to_notification'
4914 __tablename__ = 'user_to_notification'
4915 __table_args__ = (
4915 __table_args__ = (
4916 UniqueConstraint('user_id', 'notification_id'),
4916 UniqueConstraint('user_id', 'notification_id'),
4917 base_table_args
4917 base_table_args
4918 )
4918 )
4919
4919
4920 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
4920 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
4921 notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
4921 notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
4922 read = Column('read', Boolean, default=False)
4922 read = Column('read', Boolean, default=False)
4923 sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
4923 sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
4924
4924
4925 user = relationship('User', lazy="joined", back_populates='notifications')
4925 user = relationship('User', lazy="joined", back_populates='notifications')
4926 notification = relationship('Notification', lazy="joined", order_by=lambda: Notification.created_on.desc(), back_populates='notifications_to_users')
4926 notification = relationship('Notification', lazy="joined", order_by=lambda: Notification.created_on.desc(), back_populates='notifications_to_users')
4927
4927
4928 def mark_as_read(self):
4928 def mark_as_read(self):
4929 self.read = True
4929 self.read = True
4930 Session().add(self)
4930 Session().add(self)
4931
4931
4932
4932
4933 class UserNotice(Base, BaseModel):
4933 class UserNotice(Base, BaseModel):
4934 __tablename__ = 'user_notices'
4934 __tablename__ = 'user_notices'
4935 __table_args__ = (
4935 __table_args__ = (
4936 base_table_args
4936 base_table_args
4937 )
4937 )
4938
4938
4939 NOTIFICATION_TYPE_MESSAGE = 'message'
4939 NOTIFICATION_TYPE_MESSAGE = 'message'
4940 NOTIFICATION_TYPE_NOTICE = 'notice'
4940 NOTIFICATION_TYPE_NOTICE = 'notice'
4941
4941
4942 NOTIFICATION_LEVEL_INFO = 'info'
4942 NOTIFICATION_LEVEL_INFO = 'info'
4943 NOTIFICATION_LEVEL_WARNING = 'warning'
4943 NOTIFICATION_LEVEL_WARNING = 'warning'
4944 NOTIFICATION_LEVEL_ERROR = 'error'
4944 NOTIFICATION_LEVEL_ERROR = 'error'
4945
4945
4946 user_notice_id = Column('gist_id', Integer(), primary_key=True)
4946 user_notice_id = Column('gist_id', Integer(), primary_key=True)
4947
4947
4948 notice_subject = Column('notice_subject', Unicode(512), nullable=True)
4948 notice_subject = Column('notice_subject', Unicode(512), nullable=True)
4949 notice_body = Column('notice_body', UnicodeText().with_variant(UnicodeText(50000), 'mysql'), nullable=True)
4949 notice_body = Column('notice_body', UnicodeText().with_variant(UnicodeText(50000), 'mysql'), nullable=True)
4950
4950
4951 notice_read = Column('notice_read', Boolean, default=False)
4951 notice_read = Column('notice_read', Boolean, default=False)
4952
4952
4953 notification_level = Column('notification_level', String(1024), default=NOTIFICATION_LEVEL_INFO)
4953 notification_level = Column('notification_level', String(1024), default=NOTIFICATION_LEVEL_INFO)
4954 notification_type = Column('notification_type', String(1024), default=NOTIFICATION_TYPE_NOTICE)
4954 notification_type = Column('notification_type', String(1024), default=NOTIFICATION_TYPE_NOTICE)
4955
4955
4956 notice_created_by = Column('notice_created_by', Integer(), ForeignKey('users.user_id'), nullable=True)
4956 notice_created_by = Column('notice_created_by', Integer(), ForeignKey('users.user_id'), nullable=True)
4957 notice_created_on = Column('notice_created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4957 notice_created_on = Column('notice_created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4958
4958
4959 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'))
4959 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'))
4960 user = relationship('User', lazy="joined", primaryjoin='User.user_id==UserNotice.user_id')
4960 user = relationship('User', lazy="joined", primaryjoin='User.user_id==UserNotice.user_id')
4961
4961
4962 @classmethod
4962 @classmethod
4963 def create_for_user(cls, user, subject, body, notice_level=NOTIFICATION_LEVEL_INFO, allow_duplicate=False):
4963 def create_for_user(cls, user, subject, body, notice_level=NOTIFICATION_LEVEL_INFO, allow_duplicate=False):
4964
4964
4965 if notice_level not in [cls.NOTIFICATION_LEVEL_ERROR,
4965 if notice_level not in [cls.NOTIFICATION_LEVEL_ERROR,
4966 cls.NOTIFICATION_LEVEL_WARNING,
4966 cls.NOTIFICATION_LEVEL_WARNING,
4967 cls.NOTIFICATION_LEVEL_INFO]:
4967 cls.NOTIFICATION_LEVEL_INFO]:
4968 return
4968 return
4969
4969
4970 from rhodecode.model.user import UserModel
4970 from rhodecode.model.user import UserModel
4971 user = UserModel().get_user(user)
4971 user = UserModel().get_user(user)
4972
4972
4973 new_notice = UserNotice()
4973 new_notice = UserNotice()
4974 if not allow_duplicate:
4974 if not allow_duplicate:
4975 existing_msg = UserNotice().query() \
4975 existing_msg = UserNotice().query() \
4976 .filter(UserNotice.user == user) \
4976 .filter(UserNotice.user == user) \
4977 .filter(UserNotice.notice_body == body) \
4977 .filter(UserNotice.notice_body == body) \
4978 .filter(UserNotice.notice_read == false()) \
4978 .filter(UserNotice.notice_read == false()) \
4979 .scalar()
4979 .scalar()
4980 if existing_msg:
4980 if existing_msg:
4981 log.warning('Ignoring duplicate notice for user %s', user)
4981 log.warning('Ignoring duplicate notice for user %s', user)
4982 return
4982 return
4983
4983
4984 new_notice.user = user
4984 new_notice.user = user
4985 new_notice.notice_subject = subject
4985 new_notice.notice_subject = subject
4986 new_notice.notice_body = body
4986 new_notice.notice_body = body
4987 new_notice.notification_level = notice_level
4987 new_notice.notification_level = notice_level
4988 Session().add(new_notice)
4988 Session().add(new_notice)
4989 Session().commit()
4989 Session().commit()
4990
4990
4991
4991
4992 class Gist(Base, BaseModel):
4992 class Gist(Base, BaseModel):
4993 __tablename__ = 'gists'
4993 __tablename__ = 'gists'
4994 __table_args__ = (
4994 __table_args__ = (
4995 Index('g_gist_access_id_idx', 'gist_access_id'),
4995 Index('g_gist_access_id_idx', 'gist_access_id'),
4996 Index('g_created_on_idx', 'created_on'),
4996 Index('g_created_on_idx', 'created_on'),
4997 base_table_args
4997 base_table_args
4998 )
4998 )
4999
4999
5000 GIST_PUBLIC = 'public'
5000 GIST_PUBLIC = 'public'
5001 GIST_PRIVATE = 'private'
5001 GIST_PRIVATE = 'private'
5002 DEFAULT_FILENAME = 'gistfile1.txt'
5002 DEFAULT_FILENAME = 'gistfile1.txt'
5003
5003
5004 ACL_LEVEL_PUBLIC = 'acl_public'
5004 ACL_LEVEL_PUBLIC = 'acl_public'
5005 ACL_LEVEL_PRIVATE = 'acl_private'
5005 ACL_LEVEL_PRIVATE = 'acl_private'
5006
5006
5007 gist_id = Column('gist_id', Integer(), primary_key=True)
5007 gist_id = Column('gist_id', Integer(), primary_key=True)
5008 gist_access_id = Column('gist_access_id', Unicode(250))
5008 gist_access_id = Column('gist_access_id', Unicode(250))
5009 gist_description = Column('gist_description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
5009 gist_description = Column('gist_description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
5010 gist_owner = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True)
5010 gist_owner = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True)
5011 gist_expires = Column('gist_expires', Float(53), nullable=False)
5011 gist_expires = Column('gist_expires', Float(53), nullable=False)
5012 gist_type = Column('gist_type', Unicode(128), nullable=False)
5012 gist_type = Column('gist_type', Unicode(128), nullable=False)
5013 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
5013 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
5014 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
5014 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
5015 acl_level = Column('acl_level', Unicode(128), nullable=True)
5015 acl_level = Column('acl_level', Unicode(128), nullable=True)
5016
5016
5017 owner = relationship('User', back_populates='user_gists')
5017 owner = relationship('User', back_populates='user_gists')
5018
5018
5019 def __repr__(self):
5019 def __repr__(self):
5020 return f'<Gist:[{self.gist_type}]{self.gist_access_id}>'
5020 return f'<Gist:[{self.gist_type}]{self.gist_access_id}>'
5021
5021
5022 @hybrid_property
5022 @hybrid_property
5023 def description_safe(self):
5023 def description_safe(self):
5024 from rhodecode.lib import helpers as h
5024 from rhodecode.lib import helpers as h
5025 return h.escape(self.gist_description)
5025 return h.escape(self.gist_description)
5026
5026
5027 @classmethod
5027 @classmethod
5028 def get_or_404(cls, id_):
5028 def get_or_404(cls, id_):
5029 from pyramid.httpexceptions import HTTPNotFound
5029 from pyramid.httpexceptions import HTTPNotFound
5030
5030
5031 res = cls.query().filter(cls.gist_access_id == id_).scalar()
5031 res = cls.query().filter(cls.gist_access_id == id_).scalar()
5032 if not res:
5032 if not res:
5033 log.debug('WARN: No DB entry with id %s', id_)
5033 log.debug('WARN: No DB entry with id %s', id_)
5034 raise HTTPNotFound()
5034 raise HTTPNotFound()
5035 return res
5035 return res
5036
5036
5037 @classmethod
5037 @classmethod
5038 def get_by_access_id(cls, gist_access_id):
5038 def get_by_access_id(cls, gist_access_id):
5039 return cls.query().filter(cls.gist_access_id == gist_access_id).scalar()
5039 return cls.query().filter(cls.gist_access_id == gist_access_id).scalar()
5040
5040
5041 def gist_url(self):
5041 def gist_url(self):
5042 from rhodecode.model.gist import GistModel
5042 from rhodecode.model.gist import GistModel
5043 return GistModel().get_url(self)
5043 return GistModel().get_url(self)
5044
5044
5045 @classmethod
5045 @classmethod
5046 def base_path(cls):
5046 def base_path(cls):
5047 """
5047 """
5048 Returns base path when all gists are stored
5048 Returns base path when all gists are stored
5049
5049
5050 :param cls:
5050 :param cls:
5051 """
5051 """
5052 from rhodecode.model.gist import GIST_STORE_LOC
5052 from rhodecode.model.gist import GIST_STORE_LOC
5053 from rhodecode.lib.utils import get_rhodecode_repo_store_path
5053 from rhodecode.lib.utils import get_rhodecode_repo_store_path
5054 repo_store_path = get_rhodecode_repo_store_path()
5054 repo_store_path = get_rhodecode_repo_store_path()
5055 return os.path.join(repo_store_path, GIST_STORE_LOC)
5055 return os.path.join(repo_store_path, GIST_STORE_LOC)
5056
5056
5057 def get_api_data(self):
5057 def get_api_data(self):
5058 """
5058 """
5059 Common function for generating gist related data for API
5059 Common function for generating gist related data for API
5060 """
5060 """
5061 gist = self
5061 gist = self
5062 data = {
5062 data = {
5063 'gist_id': gist.gist_id,
5063 'gist_id': gist.gist_id,
5064 'type': gist.gist_type,
5064 'type': gist.gist_type,
5065 'access_id': gist.gist_access_id,
5065 'access_id': gist.gist_access_id,
5066 'description': gist.gist_description,
5066 'description': gist.gist_description,
5067 'url': gist.gist_url(),
5067 'url': gist.gist_url(),
5068 'expires': gist.gist_expires,
5068 'expires': gist.gist_expires,
5069 'created_on': gist.created_on,
5069 'created_on': gist.created_on,
5070 'modified_at': gist.modified_at,
5070 'modified_at': gist.modified_at,
5071 'content': None,
5071 'content': None,
5072 'acl_level': gist.acl_level,
5072 'acl_level': gist.acl_level,
5073 }
5073 }
5074 return data
5074 return data
5075
5075
5076 def __json__(self):
5076 def __json__(self):
5077 data = dict()
5077 data = dict()
5078 data.update(self.get_api_data())
5078 data.update(self.get_api_data())
5079 return data
5079 return data
5080 # SCM functions
5080 # SCM functions
5081
5081
5082 def scm_instance(self, **kwargs):
5082 def scm_instance(self, **kwargs):
5083 """
5083 """
5084 Get an instance of VCS Repository
5084 Get an instance of VCS Repository
5085
5085
5086 :param kwargs:
5086 :param kwargs:
5087 """
5087 """
5088 from rhodecode.model.gist import GistModel
5088 from rhodecode.model.gist import GistModel
5089 full_repo_path = os.path.join(self.base_path(), self.gist_access_id)
5089 full_repo_path = os.path.join(self.base_path(), self.gist_access_id)
5090 return get_vcs_instance(
5090 return get_vcs_instance(
5091 repo_path=safe_str(full_repo_path), create=False,
5091 repo_path=safe_str(full_repo_path), create=False,
5092 _vcs_alias=GistModel.vcs_backend)
5092 _vcs_alias=GistModel.vcs_backend)
5093
5093
5094
5094
5095 class ExternalIdentity(Base, BaseModel):
5095 class ExternalIdentity(Base, BaseModel):
5096 __tablename__ = 'external_identities'
5096 __tablename__ = 'external_identities'
5097 __table_args__ = (
5097 __table_args__ = (
5098 Index('local_user_id_idx', 'local_user_id'),
5098 Index('local_user_id_idx', 'local_user_id'),
5099 Index('external_id_idx', 'external_id'),
5099 Index('external_id_idx', 'external_id'),
5100 base_table_args
5100 base_table_args
5101 )
5101 )
5102
5102
5103 external_id = Column('external_id', Unicode(255), default='', primary_key=True)
5103 external_id = Column('external_id', Unicode(255), default='', primary_key=True)
5104 external_username = Column('external_username', Unicode(1024), default='')
5104 external_username = Column('external_username', Unicode(1024), default='')
5105 local_user_id = Column('local_user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
5105 local_user_id = Column('local_user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
5106 provider_name = Column('provider_name', Unicode(255), default='', primary_key=True)
5106 provider_name = Column('provider_name', Unicode(255), default='', primary_key=True)
5107 access_token = Column('access_token', String(1024), default='')
5107 access_token = Column('access_token', String(1024), default='')
5108 alt_token = Column('alt_token', String(1024), default='')
5108 alt_token = Column('alt_token', String(1024), default='')
5109 token_secret = Column('token_secret', String(1024), default='')
5109 token_secret = Column('token_secret', String(1024), default='')
5110
5110
5111 @classmethod
5111 @classmethod
5112 def by_external_id_and_provider(cls, external_id, provider_name, local_user_id=None):
5112 def by_external_id_and_provider(cls, external_id, provider_name, local_user_id=None):
5113 """
5113 """
5114 Returns ExternalIdentity instance based on search params
5114 Returns ExternalIdentity instance based on search params
5115
5115
5116 :param external_id:
5116 :param external_id:
5117 :param provider_name:
5117 :param provider_name:
5118 :return: ExternalIdentity
5118 :return: ExternalIdentity
5119 """
5119 """
5120 query = cls.query()
5120 query = cls.query()
5121 query = query.filter(cls.external_id == external_id)
5121 query = query.filter(cls.external_id == external_id)
5122 query = query.filter(cls.provider_name == provider_name)
5122 query = query.filter(cls.provider_name == provider_name)
5123 if local_user_id:
5123 if local_user_id:
5124 query = query.filter(cls.local_user_id == local_user_id)
5124 query = query.filter(cls.local_user_id == local_user_id)
5125 return query.first()
5125 return query.first()
5126
5126
5127 @classmethod
5127 @classmethod
5128 def user_by_external_id_and_provider(cls, external_id, provider_name):
5128 def user_by_external_id_and_provider(cls, external_id, provider_name):
5129 """
5129 """
5130 Returns User instance based on search params
5130 Returns User instance based on search params
5131
5131
5132 :param external_id:
5132 :param external_id:
5133 :param provider_name:
5133 :param provider_name:
5134 :return: User
5134 :return: User
5135 """
5135 """
5136 query = User.query()
5136 query = User.query()
5137 query = query.filter(cls.external_id == external_id)
5137 query = query.filter(cls.external_id == external_id)
5138 query = query.filter(cls.provider_name == provider_name)
5138 query = query.filter(cls.provider_name == provider_name)
5139 query = query.filter(User.user_id == cls.local_user_id)
5139 query = query.filter(User.user_id == cls.local_user_id)
5140 return query.first()
5140 return query.first()
5141
5141
5142 @classmethod
5142 @classmethod
5143 def by_local_user_id(cls, local_user_id):
5143 def by_local_user_id(cls, local_user_id):
5144 """
5144 """
5145 Returns all tokens for user
5145 Returns all tokens for user
5146
5146
5147 :param local_user_id:
5147 :param local_user_id:
5148 :return: ExternalIdentity
5148 :return: ExternalIdentity
5149 """
5149 """
5150 query = cls.query()
5150 query = cls.query()
5151 query = query.filter(cls.local_user_id == local_user_id)
5151 query = query.filter(cls.local_user_id == local_user_id)
5152 return query
5152 return query
5153
5153
5154 @classmethod
5154 @classmethod
5155 def load_provider_plugin(cls, plugin_id):
5155 def load_provider_plugin(cls, plugin_id):
5156 from rhodecode.authentication.base import loadplugin
5156 from rhodecode.authentication.base import loadplugin
5157 _plugin_id = 'egg:rhodecode-enterprise-ee#{}'.format(plugin_id)
5157 _plugin_id = 'egg:rhodecode-enterprise-ee#{}'.format(plugin_id)
5158 auth_plugin = loadplugin(_plugin_id)
5158 auth_plugin = loadplugin(_plugin_id)
5159 return auth_plugin
5159 return auth_plugin
5160
5160
5161
5161
5162 class Integration(Base, BaseModel):
5162 class Integration(Base, BaseModel):
5163 __tablename__ = 'integrations'
5163 __tablename__ = 'integrations'
5164 __table_args__ = (
5164 __table_args__ = (
5165 base_table_args
5165 base_table_args
5166 )
5166 )
5167
5167
5168 integration_id = Column('integration_id', Integer(), primary_key=True)
5168 integration_id = Column('integration_id', Integer(), primary_key=True)
5169 integration_type = Column('integration_type', String(255))
5169 integration_type = Column('integration_type', String(255))
5170 enabled = Column('enabled', Boolean(), nullable=False)
5170 enabled = Column('enabled', Boolean(), nullable=False)
5171 name = Column('name', String(255), nullable=False)
5171 name = Column('name', String(255), nullable=False)
5172 child_repos_only = Column('child_repos_only', Boolean(), nullable=False, default=False)
5172 child_repos_only = Column('child_repos_only', Boolean(), nullable=False, default=False)
5173
5173
5174 settings = Column(
5174 settings = Column(
5175 'settings_json', MutationObj.as_mutable(
5175 'settings_json', MutationObj.as_mutable(
5176 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
5176 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
5177 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
5177 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
5178 repo = relationship('Repository', lazy='joined', back_populates='integrations')
5178 repo = relationship('Repository', lazy='joined', back_populates='integrations')
5179
5179
5180 repo_group_id = Column('repo_group_id', Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
5180 repo_group_id = Column('repo_group_id', Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
5181 repo_group = relationship('RepoGroup', lazy='joined', back_populates='integrations')
5181 repo_group = relationship('RepoGroup', lazy='joined', back_populates='integrations')
5182
5182
5183 @property
5183 @property
5184 def scope(self):
5184 def scope(self):
5185 if self.repo:
5185 if self.repo:
5186 return repr(self.repo)
5186 return repr(self.repo)
5187 if self.repo_group:
5187 if self.repo_group:
5188 if self.child_repos_only:
5188 if self.child_repos_only:
5189 return repr(self.repo_group) + ' (child repos only)'
5189 return repr(self.repo_group) + ' (child repos only)'
5190 else:
5190 else:
5191 return repr(self.repo_group) + ' (recursive)'
5191 return repr(self.repo_group) + ' (recursive)'
5192 if self.child_repos_only:
5192 if self.child_repos_only:
5193 return 'root_repos'
5193 return 'root_repos'
5194 return 'global'
5194 return 'global'
5195
5195
5196 def __repr__(self):
5196 def __repr__(self):
5197 return '<Integration(%r, %r)>' % (self.integration_type, self.scope)
5197 return '<Integration(%r, %r)>' % (self.integration_type, self.scope)
5198
5198
5199
5199
5200 class RepoReviewRuleUser(Base, BaseModel):
5200 class RepoReviewRuleUser(Base, BaseModel):
5201 __tablename__ = 'repo_review_rules_users'
5201 __tablename__ = 'repo_review_rules_users'
5202 __table_args__ = (
5202 __table_args__ = (
5203 base_table_args
5203 base_table_args
5204 )
5204 )
5205 ROLE_REVIEWER = 'reviewer'
5205 ROLE_REVIEWER = 'reviewer'
5206 ROLE_OBSERVER = 'observer'
5206 ROLE_OBSERVER = 'observer'
5207 ROLES = [ROLE_REVIEWER, ROLE_OBSERVER]
5207 ROLES = [ROLE_REVIEWER, ROLE_OBSERVER]
5208
5208
5209 repo_review_rule_user_id = Column('repo_review_rule_user_id', Integer(), primary_key=True)
5209 repo_review_rule_user_id = Column('repo_review_rule_user_id', Integer(), primary_key=True)
5210 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
5210 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
5211 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False)
5211 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False)
5212 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
5212 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
5213 role = Column('role', Unicode(255), nullable=True, default=ROLE_REVIEWER)
5213 role = Column('role', Unicode(255), nullable=True, default=ROLE_REVIEWER)
5214 user = relationship('User', back_populates='user_review_rules')
5214 user = relationship('User', back_populates='user_review_rules')
5215
5215
5216 def rule_data(self):
5216 def rule_data(self):
5217 return {
5217 return {
5218 'mandatory': self.mandatory,
5218 'mandatory': self.mandatory,
5219 'role': self.role,
5219 'role': self.role,
5220 }
5220 }
5221
5221
5222
5222
5223 class RepoReviewRuleUserGroup(Base, BaseModel):
5223 class RepoReviewRuleUserGroup(Base, BaseModel):
5224 __tablename__ = 'repo_review_rules_users_groups'
5224 __tablename__ = 'repo_review_rules_users_groups'
5225 __table_args__ = (
5225 __table_args__ = (
5226 base_table_args
5226 base_table_args
5227 )
5227 )
5228
5228
5229 VOTE_RULE_ALL = -1
5229 VOTE_RULE_ALL = -1
5230 ROLE_REVIEWER = 'reviewer'
5230 ROLE_REVIEWER = 'reviewer'
5231 ROLE_OBSERVER = 'observer'
5231 ROLE_OBSERVER = 'observer'
5232 ROLES = [ROLE_REVIEWER, ROLE_OBSERVER]
5232 ROLES = [ROLE_REVIEWER, ROLE_OBSERVER]
5233
5233
5234 repo_review_rule_users_group_id = Column('repo_review_rule_users_group_id', Integer(), primary_key=True)
5234 repo_review_rule_users_group_id = Column('repo_review_rule_users_group_id', Integer(), primary_key=True)
5235 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
5235 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
5236 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False)
5236 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False)
5237 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
5237 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
5238 role = Column('role', Unicode(255), nullable=True, default=ROLE_REVIEWER)
5238 role = Column('role', Unicode(255), nullable=True, default=ROLE_REVIEWER)
5239 vote_rule = Column("vote_rule", Integer(), nullable=True, default=VOTE_RULE_ALL)
5239 vote_rule = Column("vote_rule", Integer(), nullable=True, default=VOTE_RULE_ALL)
5240 users_group = relationship('UserGroup')
5240 users_group = relationship('UserGroup')
5241
5241
5242 def rule_data(self):
5242 def rule_data(self):
5243 return {
5243 return {
5244 'mandatory': self.mandatory,
5244 'mandatory': self.mandatory,
5245 'role': self.role,
5245 'role': self.role,
5246 'vote_rule': self.vote_rule
5246 'vote_rule': self.vote_rule
5247 }
5247 }
5248
5248
5249 @property
5249 @property
5250 def vote_rule_label(self):
5250 def vote_rule_label(self):
5251 if not self.vote_rule or self.vote_rule == self.VOTE_RULE_ALL:
5251 if not self.vote_rule or self.vote_rule == self.VOTE_RULE_ALL:
5252 return 'all must vote'
5252 return 'all must vote'
5253 else:
5253 else:
5254 return 'min. vote {}'.format(self.vote_rule)
5254 return 'min. vote {}'.format(self.vote_rule)
5255
5255
5256
5256
5257 class RepoReviewRule(Base, BaseModel):
5257 class RepoReviewRule(Base, BaseModel):
5258 __tablename__ = 'repo_review_rules'
5258 __tablename__ = 'repo_review_rules'
5259 __table_args__ = (
5259 __table_args__ = (
5260 base_table_args
5260 base_table_args
5261 )
5261 )
5262
5262
5263 repo_review_rule_id = Column(
5263 repo_review_rule_id = Column(
5264 'repo_review_rule_id', Integer(), primary_key=True)
5264 'repo_review_rule_id', Integer(), primary_key=True)
5265 repo_id = Column(
5265 repo_id = Column(
5266 "repo_id", Integer(), ForeignKey('repositories.repo_id'))
5266 "repo_id", Integer(), ForeignKey('repositories.repo_id'))
5267 repo = relationship('Repository', back_populates='review_rules')
5267 repo = relationship('Repository', back_populates='review_rules')
5268
5268
5269 review_rule_name = Column('review_rule_name', String(255))
5269 review_rule_name = Column('review_rule_name', String(255))
5270 _branch_pattern = Column("branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default='*') # glob
5270 _branch_pattern = Column("branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default='*') # glob
5271 _target_branch_pattern = Column("target_branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default='*') # glob
5271 _target_branch_pattern = Column("target_branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default='*') # glob
5272 _file_pattern = Column("file_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default='*') # glob
5272 _file_pattern = Column("file_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default='*') # glob
5273
5273
5274 use_authors_for_review = Column("use_authors_for_review", Boolean(), nullable=False, default=False)
5274 use_authors_for_review = Column("use_authors_for_review", Boolean(), nullable=False, default=False)
5275
5275
5276 # Legacy fields, just for backward compat
5276 # Legacy fields, just for backward compat
5277 _forbid_author_to_review = Column("forbid_author_to_review", Boolean(), nullable=False, default=False)
5277 _forbid_author_to_review = Column("forbid_author_to_review", Boolean(), nullable=False, default=False)
5278 _forbid_commit_author_to_review = Column("forbid_commit_author_to_review", Boolean(), nullable=False, default=False)
5278 _forbid_commit_author_to_review = Column("forbid_commit_author_to_review", Boolean(), nullable=False, default=False)
5279
5279
5280 pr_author = Column("pr_author", UnicodeText().with_variant(UnicodeText(255), 'mysql'), nullable=True)
5280 pr_author = Column("pr_author", UnicodeText().with_variant(UnicodeText(255), 'mysql'), nullable=True)
5281 commit_author = Column("commit_author", UnicodeText().with_variant(UnicodeText(255), 'mysql'), nullable=True)
5281 commit_author = Column("commit_author", UnicodeText().with_variant(UnicodeText(255), 'mysql'), nullable=True)
5282
5282
5283 forbid_adding_reviewers = Column("forbid_adding_reviewers", Boolean(), nullable=False, default=False)
5283 forbid_adding_reviewers = Column("forbid_adding_reviewers", Boolean(), nullable=False, default=False)
5284
5284
5285 rule_users = relationship('RepoReviewRuleUser')
5285 rule_users = relationship('RepoReviewRuleUser')
5286 rule_user_groups = relationship('RepoReviewRuleUserGroup')
5286 rule_user_groups = relationship('RepoReviewRuleUserGroup')
5287
5287
5288 def _validate_pattern(self, value):
5288 def _validate_pattern(self, value):
5289 re.compile('^' + glob2re(value) + '$')
5289 re.compile('^' + glob2re(value) + '$')
5290
5290
5291 @hybrid_property
5291 @hybrid_property
5292 def source_branch_pattern(self):
5292 def source_branch_pattern(self):
5293 return self._branch_pattern or '*'
5293 return self._branch_pattern or '*'
5294
5294
5295 @source_branch_pattern.setter
5295 @source_branch_pattern.setter
5296 def source_branch_pattern(self, value):
5296 def source_branch_pattern(self, value):
5297 self._validate_pattern(value)
5297 self._validate_pattern(value)
5298 self._branch_pattern = value or '*'
5298 self._branch_pattern = value or '*'
5299
5299
5300 @hybrid_property
5300 @hybrid_property
5301 def target_branch_pattern(self):
5301 def target_branch_pattern(self):
5302 return self._target_branch_pattern or '*'
5302 return self._target_branch_pattern or '*'
5303
5303
5304 @target_branch_pattern.setter
5304 @target_branch_pattern.setter
5305 def target_branch_pattern(self, value):
5305 def target_branch_pattern(self, value):
5306 self._validate_pattern(value)
5306 self._validate_pattern(value)
5307 self._target_branch_pattern = value or '*'
5307 self._target_branch_pattern = value or '*'
5308
5308
5309 @hybrid_property
5309 @hybrid_property
5310 def file_pattern(self):
5310 def file_pattern(self):
5311 return self._file_pattern or '*'
5311 return self._file_pattern or '*'
5312
5312
5313 @file_pattern.setter
5313 @file_pattern.setter
5314 def file_pattern(self, value):
5314 def file_pattern(self, value):
5315 self._validate_pattern(value)
5315 self._validate_pattern(value)
5316 self._file_pattern = value or '*'
5316 self._file_pattern = value or '*'
5317
5317
5318 @hybrid_property
5318 @hybrid_property
5319 def forbid_pr_author_to_review(self):
5319 def forbid_pr_author_to_review(self):
5320 return self.pr_author == 'forbid_pr_author'
5320 return self.pr_author == 'forbid_pr_author'
5321
5321
5322 @hybrid_property
5322 @hybrid_property
5323 def include_pr_author_to_review(self):
5323 def include_pr_author_to_review(self):
5324 return self.pr_author == 'include_pr_author'
5324 return self.pr_author == 'include_pr_author'
5325
5325
5326 @hybrid_property
5326 @hybrid_property
5327 def forbid_commit_author_to_review(self):
5327 def forbid_commit_author_to_review(self):
5328 return self.commit_author == 'forbid_commit_author'
5328 return self.commit_author == 'forbid_commit_author'
5329
5329
5330 @hybrid_property
5330 @hybrid_property
5331 def include_commit_author_to_review(self):
5331 def include_commit_author_to_review(self):
5332 return self.commit_author == 'include_commit_author'
5332 return self.commit_author == 'include_commit_author'
5333
5333
5334 def matches(self, source_branch, target_branch, files_changed):
5334 def matches(self, source_branch, target_branch, files_changed):
5335 """
5335 """
5336 Check if this review rule matches a branch/files in a pull request
5336 Check if this review rule matches a branch/files in a pull request
5337
5337
5338 :param source_branch: source branch name for the commit
5338 :param source_branch: source branch name for the commit
5339 :param target_branch: target branch name for the commit
5339 :param target_branch: target branch name for the commit
5340 :param files_changed: list of file paths changed in the pull request
5340 :param files_changed: list of file paths changed in the pull request
5341 """
5341 """
5342
5342
5343 source_branch = source_branch or ''
5343 source_branch = source_branch or ''
5344 target_branch = target_branch or ''
5344 target_branch = target_branch or ''
5345 files_changed = files_changed or []
5345 files_changed = files_changed or []
5346
5346
5347 branch_matches = True
5347 branch_matches = True
5348 if source_branch or target_branch:
5348 if source_branch or target_branch:
5349 if self.source_branch_pattern == '*':
5349 if self.source_branch_pattern == '*':
5350 source_branch_match = True
5350 source_branch_match = True
5351 else:
5351 else:
5352 if self.source_branch_pattern.startswith('re:'):
5352 if self.source_branch_pattern.startswith('re:'):
5353 source_pattern = self.source_branch_pattern[3:]
5353 source_pattern = self.source_branch_pattern[3:]
5354 else:
5354 else:
5355 source_pattern = '^' + glob2re(self.source_branch_pattern) + '$'
5355 source_pattern = '^' + glob2re(self.source_branch_pattern) + '$'
5356 source_branch_regex = re.compile(source_pattern)
5356 source_branch_regex = re.compile(source_pattern)
5357 source_branch_match = bool(source_branch_regex.search(source_branch))
5357 source_branch_match = bool(source_branch_regex.search(source_branch))
5358 if self.target_branch_pattern == '*':
5358 if self.target_branch_pattern == '*':
5359 target_branch_match = True
5359 target_branch_match = True
5360 else:
5360 else:
5361 if self.target_branch_pattern.startswith('re:'):
5361 if self.target_branch_pattern.startswith('re:'):
5362 target_pattern = self.target_branch_pattern[3:]
5362 target_pattern = self.target_branch_pattern[3:]
5363 else:
5363 else:
5364 target_pattern = '^' + glob2re(self.target_branch_pattern) + '$'
5364 target_pattern = '^' + glob2re(self.target_branch_pattern) + '$'
5365 target_branch_regex = re.compile(target_pattern)
5365 target_branch_regex = re.compile(target_pattern)
5366 target_branch_match = bool(target_branch_regex.search(target_branch))
5366 target_branch_match = bool(target_branch_regex.search(target_branch))
5367
5367
5368 branch_matches = source_branch_match and target_branch_match
5368 branch_matches = source_branch_match and target_branch_match
5369
5369
5370 files_matches = True
5370 files_matches = True
5371 if self.file_pattern != '*':
5371 if self.file_pattern != '*':
5372 files_matches = False
5372 files_matches = False
5373 if self.file_pattern.startswith('re:'):
5373 if self.file_pattern.startswith('re:'):
5374 file_pattern = self.file_pattern[3:]
5374 file_pattern = self.file_pattern[3:]
5375 else:
5375 else:
5376 file_pattern = glob2re(self.file_pattern)
5376 file_pattern = glob2re(self.file_pattern)
5377 file_regex = re.compile(file_pattern)
5377 file_regex = re.compile(file_pattern)
5378 for file_data in files_changed:
5378 for file_data in files_changed:
5379 filename = file_data.get('filename')
5379 filename = file_data.get('filename')
5380
5380
5381 if file_regex.search(filename):
5381 if file_regex.search(filename):
5382 files_matches = True
5382 files_matches = True
5383 break
5383 break
5384
5384
5385 return branch_matches and files_matches
5385 return branch_matches and files_matches
5386
5386
5387 @property
5387 @property
5388 def review_users(self):
5388 def review_users(self):
5389 """ Returns the users which this rule applies to """
5389 """ Returns the users which this rule applies to """
5390
5390
5391 users = collections.OrderedDict()
5391 users = collections.OrderedDict()
5392
5392
5393 for rule_user in self.rule_users:
5393 for rule_user in self.rule_users:
5394 if rule_user.user.active:
5394 if rule_user.user.active:
5395 if rule_user.user not in users:
5395 if rule_user.user not in users:
5396 users[rule_user.user.username] = {
5396 users[rule_user.user.username] = {
5397 'user': rule_user.user,
5397 'user': rule_user.user,
5398 'source': 'user',
5398 'source': 'user',
5399 'source_data': {},
5399 'source_data': {},
5400 'data': rule_user.rule_data()
5400 'data': rule_user.rule_data()
5401 }
5401 }
5402
5402
5403 for rule_user_group in self.rule_user_groups:
5403 for rule_user_group in self.rule_user_groups:
5404 source_data = {
5404 source_data = {
5405 'user_group_id': rule_user_group.users_group.users_group_id,
5405 'user_group_id': rule_user_group.users_group.users_group_id,
5406 'name': rule_user_group.users_group.users_group_name,
5406 'name': rule_user_group.users_group.users_group_name,
5407 'members': len(rule_user_group.users_group.members)
5407 'members': len(rule_user_group.users_group.members)
5408 }
5408 }
5409 for member in rule_user_group.users_group.members:
5409 for member in rule_user_group.users_group.members:
5410 if member.user.active:
5410 if member.user.active:
5411 key = member.user.username
5411 key = member.user.username
5412 if key in users:
5412 if key in users:
5413 # skip this member as we have him already
5413 # skip this member as we have him already
5414 # this prevents from override the "first" matched
5414 # this prevents from override the "first" matched
5415 # users with duplicates in multiple groups
5415 # users with duplicates in multiple groups
5416 continue
5416 continue
5417
5417
5418 users[key] = {
5418 users[key] = {
5419 'user': member.user,
5419 'user': member.user,
5420 'source': 'user_group',
5420 'source': 'user_group',
5421 'source_data': source_data,
5421 'source_data': source_data,
5422 'data': rule_user_group.rule_data()
5422 'data': rule_user_group.rule_data()
5423 }
5423 }
5424
5424
5425 return users
5425 return users
5426
5426
5427 def user_group_vote_rule(self, user_id):
5427 def user_group_vote_rule(self, user_id):
5428
5428
5429 rules = []
5429 rules = []
5430 if not self.rule_user_groups:
5430 if not self.rule_user_groups:
5431 return rules
5431 return rules
5432
5432
5433 for user_group in self.rule_user_groups:
5433 for user_group in self.rule_user_groups:
5434 user_group_members = [x.user_id for x in user_group.users_group.members]
5434 user_group_members = [x.user_id for x in user_group.users_group.members]
5435 if user_id in user_group_members:
5435 if user_id in user_group_members:
5436 rules.append(user_group)
5436 rules.append(user_group)
5437 return rules
5437 return rules
5438
5438
5439 def __repr__(self):
5439 def __repr__(self):
5440 return f'<RepoReviewerRule(id={self.repo_review_rule_id}, repo={self.repo!r})>'
5440 return f'<RepoReviewerRule(id={self.repo_review_rule_id}, repo={self.repo!r})>'
5441
5441
5442
5442
5443 class ScheduleEntry(Base, BaseModel):
5443 class ScheduleEntry(Base, BaseModel):
5444 __tablename__ = 'schedule_entries'
5444 __tablename__ = 'schedule_entries'
5445 __table_args__ = (
5445 __table_args__ = (
5446 UniqueConstraint('schedule_name', name='s_schedule_name_idx'),
5446 UniqueConstraint('schedule_name', name='s_schedule_name_idx'),
5447 UniqueConstraint('task_uid', name='s_task_uid_idx'),
5447 UniqueConstraint('task_uid', name='s_task_uid_idx'),
5448 base_table_args,
5448 base_table_args,
5449 )
5449 )
5450 SCHEDULE_TYPE_INTEGER = "integer"
5450 SCHEDULE_TYPE_INTEGER = "integer"
5451 SCHEDULE_TYPE_CRONTAB = "crontab"
5451 SCHEDULE_TYPE_CRONTAB = "crontab"
5452
5452
5453 schedule_types = [SCHEDULE_TYPE_CRONTAB, SCHEDULE_TYPE_INTEGER]
5453 schedule_types = [SCHEDULE_TYPE_CRONTAB, SCHEDULE_TYPE_INTEGER]
5454 schedule_entry_id = Column('schedule_entry_id', Integer(), primary_key=True)
5454 schedule_entry_id = Column('schedule_entry_id', Integer(), primary_key=True)
5455
5455
5456 schedule_name = Column("schedule_name", String(255), nullable=False, unique=None, default=None)
5456 schedule_name = Column("schedule_name", String(255), nullable=False, unique=None, default=None)
5457 schedule_description = Column("schedule_description", String(10000), nullable=True, unique=None, default=None)
5457 schedule_description = Column("schedule_description", String(10000), nullable=True, unique=None, default=None)
5458 schedule_enabled = Column("schedule_enabled", Boolean(), nullable=False, unique=None, default=True)
5458 schedule_enabled = Column("schedule_enabled", Boolean(), nullable=False, unique=None, default=True)
5459
5459
5460 _schedule_type = Column("schedule_type", String(255), nullable=False, unique=None, default=None)
5460 _schedule_type = Column("schedule_type", String(255), nullable=False, unique=None, default=None)
5461 schedule_definition = Column('schedule_definition_json', MutationObj.as_mutable(JsonType(default=lambda: "", dialect_map=dict(mysql=LONGTEXT()))))
5461 schedule_definition = Column('schedule_definition_json', MutationObj.as_mutable(JsonType(default=lambda: "", dialect_map=dict(mysql=LONGTEXT()))))
5462
5462
5463 schedule_last_run = Column('schedule_last_run', DateTime(timezone=False), nullable=True, unique=None, default=None)
5463 schedule_last_run = Column('schedule_last_run', DateTime(timezone=False), nullable=True, unique=None, default=None)
5464 schedule_total_run_count = Column('schedule_total_run_count', Integer(), nullable=True, unique=None, default=0)
5464 schedule_total_run_count = Column('schedule_total_run_count', Integer(), nullable=True, unique=None, default=0)
5465
5465
5466 # task
5466 # task
5467 task_uid = Column("task_uid", String(255), nullable=False, unique=None, default=None)
5467 task_uid = Column("task_uid", String(255), nullable=False, unique=None, default=None)
5468 task_dot_notation = Column("task_dot_notation", String(4096), nullable=False, unique=None, default=None)
5468 task_dot_notation = Column("task_dot_notation", String(4096), nullable=False, unique=None, default=None)
5469 task_args = Column('task_args_json', MutationObj.as_mutable(JsonType(default=list, dialect_map=dict(mysql=LONGTEXT()))))
5469 task_args = Column('task_args_json', MutationObj.as_mutable(JsonType(default=list, dialect_map=dict(mysql=LONGTEXT()))))
5470 task_kwargs = Column('task_kwargs_json', MutationObj.as_mutable(JsonType(default=dict, dialect_map=dict(mysql=LONGTEXT()))))
5470 task_kwargs = Column('task_kwargs_json', MutationObj.as_mutable(JsonType(default=dict, dialect_map=dict(mysql=LONGTEXT()))))
5471
5471
5472 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
5472 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
5473 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=None)
5473 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=None)
5474
5474
5475 @hybrid_property
5475 @hybrid_property
5476 def schedule_type(self):
5476 def schedule_type(self):
5477 return self._schedule_type
5477 return self._schedule_type
5478
5478
5479 @schedule_type.setter
5479 @schedule_type.setter
5480 def schedule_type(self, val):
5480 def schedule_type(self, val):
5481 if val not in self.schedule_types:
5481 if val not in self.schedule_types:
5482 raise ValueError('Value must be on of `{}` and got `{}`'.format(
5482 raise ValueError('Value must be on of `{}` and got `{}`'.format(
5483 val, self.schedule_type))
5483 val, self.schedule_type))
5484
5484
5485 self._schedule_type = val
5485 self._schedule_type = val
5486
5486
5487 @classmethod
5487 @classmethod
5488 def get_uid(cls, obj):
5488 def get_uid(cls, obj):
5489 args = obj.task_args
5489 args = obj.task_args
5490 kwargs = obj.task_kwargs
5490 kwargs = obj.task_kwargs
5491 if isinstance(args, JsonRaw):
5491 if isinstance(args, JsonRaw):
5492 try:
5492 try:
5493 args = json.loads(args)
5493 args = json.loads(args)
5494 except ValueError:
5494 except ValueError:
5495 args = tuple()
5495 args = tuple()
5496
5496
5497 if isinstance(kwargs, JsonRaw):
5497 if isinstance(kwargs, JsonRaw):
5498 try:
5498 try:
5499 kwargs = json.loads(kwargs)
5499 kwargs = json.loads(kwargs)
5500 except ValueError:
5500 except ValueError:
5501 kwargs = dict()
5501 kwargs = dict()
5502
5502
5503 dot_notation = obj.task_dot_notation
5503 dot_notation = obj.task_dot_notation
5504 val = '.'.join(map(safe_str, [
5504 val = '.'.join(map(safe_str, [
5505 sorted(dot_notation), args, sorted(kwargs.items())]))
5505 sorted(dot_notation), args, sorted(kwargs.items())]))
5506 return sha1(safe_bytes(val))
5506 return sha1(safe_bytes(val))
5507
5507
5508 @classmethod
5508 @classmethod
5509 def get_by_schedule_name(cls, schedule_name):
5509 def get_by_schedule_name(cls, schedule_name):
5510 return cls.query().filter(cls.schedule_name == schedule_name).scalar()
5510 return cls.query().filter(cls.schedule_name == schedule_name).scalar()
5511
5511
5512 @classmethod
5512 @classmethod
5513 def get_by_schedule_id(cls, schedule_id):
5513 def get_by_schedule_id(cls, schedule_id):
5514 return cls.query().filter(cls.schedule_entry_id == schedule_id).scalar()
5514 return cls.query().filter(cls.schedule_entry_id == schedule_id).scalar()
5515
5515
5516 @property
5516 @property
5517 def task(self):
5517 def task(self):
5518 return self.task_dot_notation
5518 return self.task_dot_notation
5519
5519
5520 @property
5520 @property
5521 def schedule(self):
5521 def schedule(self):
5522 from rhodecode.lib.celerylib.utils import raw_2_schedule
5522 from rhodecode.lib.celerylib.utils import raw_2_schedule
5523 schedule = raw_2_schedule(self.schedule_definition, self.schedule_type)
5523 schedule = raw_2_schedule(self.schedule_definition, self.schedule_type)
5524 return schedule
5524 return schedule
5525
5525
5526 @property
5526 @property
5527 def args(self):
5527 def args(self):
5528 try:
5528 try:
5529 return list(self.task_args or [])
5529 return list(self.task_args or [])
5530 except ValueError:
5530 except ValueError:
5531 return list()
5531 return list()
5532
5532
5533 @property
5533 @property
5534 def kwargs(self):
5534 def kwargs(self):
5535 try:
5535 try:
5536 return dict(self.task_kwargs or {})
5536 return dict(self.task_kwargs or {})
5537 except ValueError:
5537 except ValueError:
5538 return dict()
5538 return dict()
5539
5539
5540 def _as_raw(self, val, indent=False):
5540 def _as_raw(self, val, indent=False):
5541 if hasattr(val, 'de_coerce'):
5541 if hasattr(val, 'de_coerce'):
5542 val = val.de_coerce()
5542 val = val.de_coerce()
5543 if val:
5543 if val:
5544 if indent:
5544 if indent:
5545 val = ext_json.formatted_str_json(val)
5545 val = ext_json.formatted_str_json(val)
5546 else:
5546 else:
5547 val = ext_json.str_json(val)
5547 val = ext_json.str_json(val)
5548
5548
5549 return val
5549 return val
5550
5550
5551 @property
5551 @property
5552 def schedule_definition_raw(self):
5552 def schedule_definition_raw(self):
5553 return self._as_raw(self.schedule_definition)
5553 return self._as_raw(self.schedule_definition)
5554
5554
5555 def args_raw(self, indent=False):
5555 def args_raw(self, indent=False):
5556 return self._as_raw(self.task_args, indent)
5556 return self._as_raw(self.task_args, indent)
5557
5557
5558 def kwargs_raw(self, indent=False):
5558 def kwargs_raw(self, indent=False):
5559 return self._as_raw(self.task_kwargs, indent)
5559 return self._as_raw(self.task_kwargs, indent)
5560
5560
5561 def __repr__(self):
5561 def __repr__(self):
5562 return f'<DB:ScheduleEntry({self.schedule_entry_id}:{self.schedule_name})>'
5562 return f'<DB:ScheduleEntry({self.schedule_entry_id}:{self.schedule_name})>'
5563
5563
5564
5564
5565 @event.listens_for(ScheduleEntry, 'before_update')
5565 @event.listens_for(ScheduleEntry, 'before_update')
5566 def update_task_uid(mapper, connection, target):
5566 def update_task_uid(mapper, connection, target):
5567 target.task_uid = ScheduleEntry.get_uid(target)
5567 target.task_uid = ScheduleEntry.get_uid(target)
5568
5568
5569
5569
5570 @event.listens_for(ScheduleEntry, 'before_insert')
5570 @event.listens_for(ScheduleEntry, 'before_insert')
5571 def set_task_uid(mapper, connection, target):
5571 def set_task_uid(mapper, connection, target):
5572 target.task_uid = ScheduleEntry.get_uid(target)
5572 target.task_uid = ScheduleEntry.get_uid(target)
5573
5573
5574
5574
5575 class _BaseBranchPerms(BaseModel):
5575 class _BaseBranchPerms(BaseModel):
5576 @classmethod
5576 @classmethod
5577 def compute_hash(cls, value):
5577 def compute_hash(cls, value):
5578 return sha1_safe(value)
5578 return sha1_safe(value)
5579
5579
5580 @hybrid_property
5580 @hybrid_property
5581 def branch_pattern(self):
5581 def branch_pattern(self):
5582 return self._branch_pattern or '*'
5582 return self._branch_pattern or '*'
5583
5583
5584 @hybrid_property
5584 @hybrid_property
5585 def branch_hash(self):
5585 def branch_hash(self):
5586 return self._branch_hash
5586 return self._branch_hash
5587
5587
5588 def _validate_glob(self, value):
5588 def _validate_glob(self, value):
5589 re.compile('^' + glob2re(value) + '$')
5589 re.compile('^' + glob2re(value) + '$')
5590
5590
5591 @branch_pattern.setter
5591 @branch_pattern.setter
5592 def branch_pattern(self, value):
5592 def branch_pattern(self, value):
5593 self._validate_glob(value)
5593 self._validate_glob(value)
5594 self._branch_pattern = value or '*'
5594 self._branch_pattern = value or '*'
5595 # set the Hash when setting the branch pattern
5595 # set the Hash when setting the branch pattern
5596 self._branch_hash = self.compute_hash(self._branch_pattern)
5596 self._branch_hash = self.compute_hash(self._branch_pattern)
5597
5597
5598 def matches(self, branch):
5598 def matches(self, branch):
5599 """
5599 """
5600 Check if this the branch matches entry
5600 Check if this the branch matches entry
5601
5601
5602 :param branch: branch name for the commit
5602 :param branch: branch name for the commit
5603 """
5603 """
5604
5604
5605 branch = branch or ''
5605 branch = branch or ''
5606
5606
5607 branch_matches = True
5607 branch_matches = True
5608 if branch:
5608 if branch:
5609 branch_regex = re.compile('^' + glob2re(self.branch_pattern) + '$')
5609 branch_regex = re.compile('^' + glob2re(self.branch_pattern) + '$')
5610 branch_matches = bool(branch_regex.search(branch))
5610 branch_matches = bool(branch_regex.search(branch))
5611
5611
5612 return branch_matches
5612 return branch_matches
5613
5613
5614
5614
5615 class UserToRepoBranchPermission(Base, _BaseBranchPerms):
5615 class UserToRepoBranchPermission(Base, _BaseBranchPerms):
5616 __tablename__ = 'user_to_repo_branch_permissions'
5616 __tablename__ = 'user_to_repo_branch_permissions'
5617 __table_args__ = (
5617 __table_args__ = (
5618 base_table_args
5618 base_table_args
5619 )
5619 )
5620
5620
5621 branch_rule_id = Column('branch_rule_id', Integer(), primary_key=True)
5621 branch_rule_id = Column('branch_rule_id', Integer(), primary_key=True)
5622
5622
5623 repository_id = Column('repository_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
5623 repository_id = Column('repository_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
5624 repo = relationship('Repository', back_populates='user_branch_perms')
5624 repo = relationship('Repository', back_populates='user_branch_perms')
5625
5625
5626 permission_id = Column('permission_id', Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
5626 permission_id = Column('permission_id', Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
5627 permission = relationship('Permission')
5627 permission = relationship('Permission')
5628
5628
5629 rule_to_perm_id = Column('rule_to_perm_id', Integer(), ForeignKey('repo_to_perm.repo_to_perm_id'), nullable=False, unique=None, default=None)
5629 rule_to_perm_id = Column('rule_to_perm_id', Integer(), ForeignKey('repo_to_perm.repo_to_perm_id'), nullable=False, unique=None, default=None)
5630 user_repo_to_perm = relationship('UserRepoToPerm', back_populates='branch_perm_entry')
5630 user_repo_to_perm = relationship('UserRepoToPerm', back_populates='branch_perm_entry')
5631
5631
5632 rule_order = Column('rule_order', Integer(), nullable=False)
5632 rule_order = Column('rule_order', Integer(), nullable=False)
5633 _branch_pattern = Column('branch_pattern', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), default='*') # glob
5633 _branch_pattern = Column('branch_pattern', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), default='*') # glob
5634 _branch_hash = Column('branch_hash', UnicodeText().with_variant(UnicodeText(2048), 'mysql'))
5634 _branch_hash = Column('branch_hash', UnicodeText().with_variant(UnicodeText(2048), 'mysql'))
5635
5635
5636 def __repr__(self):
5636 def __repr__(self):
5637 return f'<UserBranchPermission({self.user_repo_to_perm} => {self.branch_pattern!r})>'
5637 return f'<UserBranchPermission({self.user_repo_to_perm} => {self.branch_pattern!r})>'
5638
5638
5639
5639
5640 class UserGroupToRepoBranchPermission(Base, _BaseBranchPerms):
5640 class UserGroupToRepoBranchPermission(Base, _BaseBranchPerms):
5641 __tablename__ = 'user_group_to_repo_branch_permissions'
5641 __tablename__ = 'user_group_to_repo_branch_permissions'
5642 __table_args__ = (
5642 __table_args__ = (
5643 base_table_args
5643 base_table_args
5644 )
5644 )
5645
5645
5646 branch_rule_id = Column('branch_rule_id', Integer(), primary_key=True)
5646 branch_rule_id = Column('branch_rule_id', Integer(), primary_key=True)
5647
5647
5648 repository_id = Column('repository_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
5648 repository_id = Column('repository_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
5649 repo = relationship('Repository', back_populates='user_group_branch_perms')
5649 repo = relationship('Repository', back_populates='user_group_branch_perms')
5650
5650
5651 permission_id = Column('permission_id', Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
5651 permission_id = Column('permission_id', Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
5652 permission = relationship('Permission')
5652 permission = relationship('Permission')
5653
5653
5654 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)
5654 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)
5655 user_group_repo_to_perm = relationship('UserGroupRepoToPerm', back_populates='user_group_branch_perms')
5655 user_group_repo_to_perm = relationship('UserGroupRepoToPerm', back_populates='user_group_branch_perms')
5656
5656
5657 rule_order = Column('rule_order', Integer(), nullable=False)
5657 rule_order = Column('rule_order', Integer(), nullable=False)
5658 _branch_pattern = Column('branch_pattern', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), default='*') # glob
5658 _branch_pattern = Column('branch_pattern', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), default='*') # glob
5659 _branch_hash = Column('branch_hash', UnicodeText().with_variant(UnicodeText(2048), 'mysql'))
5659 _branch_hash = Column('branch_hash', UnicodeText().with_variant(UnicodeText(2048), 'mysql'))
5660
5660
5661 def __repr__(self):
5661 def __repr__(self):
5662 return f'<UserBranchPermission({self.user_group_repo_to_perm} => {self.branch_pattern!r})>'
5662 return f'<UserBranchPermission({self.user_group_repo_to_perm} => {self.branch_pattern!r})>'
5663
5663
5664
5664
5665 class UserBookmark(Base, BaseModel):
5665 class UserBookmark(Base, BaseModel):
5666 __tablename__ = 'user_bookmarks'
5666 __tablename__ = 'user_bookmarks'
5667 __table_args__ = (
5667 __table_args__ = (
5668 UniqueConstraint('user_id', 'bookmark_repo_id'),
5668 UniqueConstraint('user_id', 'bookmark_repo_id'),
5669 UniqueConstraint('user_id', 'bookmark_repo_group_id'),
5669 UniqueConstraint('user_id', 'bookmark_repo_group_id'),
5670 UniqueConstraint('user_id', 'bookmark_position'),
5670 UniqueConstraint('user_id', 'bookmark_position'),
5671 base_table_args
5671 base_table_args
5672 )
5672 )
5673
5673
5674 user_bookmark_id = Column("user_bookmark_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
5674 user_bookmark_id = Column("user_bookmark_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
5675 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
5675 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
5676 position = Column("bookmark_position", Integer(), nullable=False)
5676 position = Column("bookmark_position", Integer(), nullable=False)
5677 title = Column("bookmark_title", String(255), nullable=True, unique=None, default=None)
5677 title = Column("bookmark_title", String(255), nullable=True, unique=None, default=None)
5678 redirect_url = Column("bookmark_redirect_url", String(10240), nullable=True, unique=None, default=None)
5678 redirect_url = Column("bookmark_redirect_url", String(10240), nullable=True, unique=None, default=None)
5679 created_on = Column("created_on", DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
5679 created_on = Column("created_on", DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
5680
5680
5681 bookmark_repo_id = Column("bookmark_repo_id", Integer(), ForeignKey("repositories.repo_id"), nullable=True, unique=None, default=None)
5681 bookmark_repo_id = Column("bookmark_repo_id", Integer(), ForeignKey("repositories.repo_id"), nullable=True, unique=None, default=None)
5682 bookmark_repo_group_id = Column("bookmark_repo_group_id", Integer(), ForeignKey("groups.group_id"), nullable=True, unique=None, default=None)
5682 bookmark_repo_group_id = Column("bookmark_repo_group_id", Integer(), ForeignKey("groups.group_id"), nullable=True, unique=None, default=None)
5683
5683
5684 user = relationship("User")
5684 user = relationship("User")
5685
5685
5686 repository = relationship("Repository")
5686 repository = relationship("Repository")
5687 repository_group = relationship("RepoGroup")
5687 repository_group = relationship("RepoGroup")
5688
5688
5689 @classmethod
5689 @classmethod
5690 def get_by_position_for_user(cls, position, user_id):
5690 def get_by_position_for_user(cls, position, user_id):
5691 return cls.query() \
5691 return cls.query() \
5692 .filter(UserBookmark.user_id == user_id) \
5692 .filter(UserBookmark.user_id == user_id) \
5693 .filter(UserBookmark.position == position).scalar()
5693 .filter(UserBookmark.position == position).scalar()
5694
5694
5695 @classmethod
5695 @classmethod
5696 def get_bookmarks_for_user(cls, user_id, cache=True):
5696 def get_bookmarks_for_user(cls, user_id, cache=True):
5697 bookmarks = select(
5697 bookmarks = select(
5698 UserBookmark.title,
5698 UserBookmark.title,
5699 UserBookmark.position,
5699 UserBookmark.position,
5700 ) \
5700 ) \
5701 .add_columns(Repository.repo_id, Repository.repo_type, Repository.repo_name) \
5701 .add_columns(Repository.repo_id, Repository.repo_type, Repository.repo_name) \
5702 .add_columns(RepoGroup.group_id, RepoGroup.group_name) \
5702 .add_columns(RepoGroup.group_id, RepoGroup.group_name) \
5703 .where(UserBookmark.user_id == user_id) \
5703 .where(UserBookmark.user_id == user_id) \
5704 .outerjoin(Repository, Repository.repo_id == UserBookmark.bookmark_repo_id) \
5704 .outerjoin(Repository, Repository.repo_id == UserBookmark.bookmark_repo_id) \
5705 .outerjoin(RepoGroup, RepoGroup.group_id == UserBookmark.bookmark_repo_group_id) \
5705 .outerjoin(RepoGroup, RepoGroup.group_id == UserBookmark.bookmark_repo_group_id) \
5706 .order_by(UserBookmark.position.asc())
5706 .order_by(UserBookmark.position.asc())
5707
5707
5708 if cache:
5708 if cache:
5709 bookmarks = bookmarks.options(
5709 bookmarks = bookmarks.options(
5710 FromCache("sql_cache_short", f"get_user_{user_id}_bookmarks")
5710 FromCache("sql_cache_short", f"get_user_{user_id}_bookmarks")
5711 )
5711 )
5712
5712
5713 return Session().execute(bookmarks).all()
5713 return Session().execute(bookmarks).all()
5714
5714
5715 def __repr__(self):
5715 def __repr__(self):
5716 return f'<UserBookmark({self.position} @ {self.redirect_url!r})>'
5716 return f'<UserBookmark({self.position} @ {self.redirect_url!r})>'
5717
5717
5718
5718
5719 class FileStore(Base, BaseModel):
5719 class FileStore(Base, BaseModel):
5720 __tablename__ = 'file_store'
5720 __tablename__ = 'file_store'
5721 __table_args__ = (
5721 __table_args__ = (
5722 base_table_args
5722 base_table_args
5723 )
5723 )
5724
5724
5725 file_store_id = Column('file_store_id', Integer(), primary_key=True)
5725 file_store_id = Column('file_store_id', Integer(), primary_key=True)
5726 file_uid = Column('file_uid', String(1024), nullable=False)
5726 file_uid = Column('file_uid', String(1024), nullable=False)
5727 file_display_name = Column('file_display_name', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), nullable=True)
5727 file_display_name = Column('file_display_name', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), nullable=True)
5728 file_description = Column('file_description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'), nullable=True)
5728 file_description = Column('file_description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'), nullable=True)
5729 file_org_name = Column('file_org_name', UnicodeText().with_variant(UnicodeText(10240), 'mysql'), nullable=False)
5729 file_org_name = Column('file_org_name', UnicodeText().with_variant(UnicodeText(10240), 'mysql'), nullable=False)
5730
5730
5731 # sha256 hash
5731 # sha256 hash
5732 file_hash = Column('file_hash', String(512), nullable=False)
5732 file_hash = Column('file_hash', String(512), nullable=False)
5733 file_size = Column('file_size', BigInteger(), nullable=False)
5733 file_size = Column('file_size', BigInteger(), nullable=False)
5734
5734
5735 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
5735 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
5736 accessed_on = Column('accessed_on', DateTime(timezone=False), nullable=True)
5736 accessed_on = Column('accessed_on', DateTime(timezone=False), nullable=True)
5737 accessed_count = Column('accessed_count', Integer(), default=0)
5737 accessed_count = Column('accessed_count', Integer(), default=0)
5738
5738
5739 enabled = Column('enabled', Boolean(), nullable=False, default=True)
5739 enabled = Column('enabled', Boolean(), nullable=False, default=True)
5740
5740
5741 # if repo/repo_group reference is set, check for permissions
5741 # if repo/repo_group reference is set, check for permissions
5742 check_acl = Column('check_acl', Boolean(), nullable=False, default=True)
5742 check_acl = Column('check_acl', Boolean(), nullable=False, default=True)
5743
5743
5744 # hidden defines an attachment that should be hidden from showing in artifact listing
5744 # hidden defines an attachment that should be hidden from showing in artifact listing
5745 hidden = Column('hidden', Boolean(), nullable=False, default=False)
5745 hidden = Column('hidden', Boolean(), nullable=False, default=False)
5746
5746
5747 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
5747 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
5748 upload_user = relationship('User', lazy='joined', primaryjoin='User.user_id==FileStore.user_id', back_populates='artifacts')
5748 upload_user = relationship('User', lazy='joined', primaryjoin='User.user_id==FileStore.user_id', back_populates='artifacts')
5749
5749
5750 file_metadata = relationship('FileStoreMetadata', lazy='joined')
5750 file_metadata = relationship('FileStoreMetadata', lazy='joined')
5751
5751
5752 # scope limited to user, which requester have access to
5752 # scope limited to user, which requester have access to
5753 scope_user_id = Column(
5753 scope_user_id = Column(
5754 'scope_user_id', Integer(), ForeignKey('users.user_id'),
5754 'scope_user_id', Integer(), ForeignKey('users.user_id'),
5755 nullable=True, unique=None, default=None)
5755 nullable=True, unique=None, default=None)
5756 user = relationship('User', lazy='joined', primaryjoin='User.user_id==FileStore.scope_user_id', back_populates='scope_artifacts')
5756 user = relationship('User', lazy='joined', primaryjoin='User.user_id==FileStore.scope_user_id', back_populates='scope_artifacts')
5757
5757
5758 # scope limited to user group, which requester have access to
5758 # scope limited to user group, which requester have access to
5759 scope_user_group_id = Column(
5759 scope_user_group_id = Column(
5760 'scope_user_group_id', Integer(), ForeignKey('users_groups.users_group_id'),
5760 'scope_user_group_id', Integer(), ForeignKey('users_groups.users_group_id'),
5761 nullable=True, unique=None, default=None)
5761 nullable=True, unique=None, default=None)
5762 user_group = relationship('UserGroup', lazy='joined')
5762 user_group = relationship('UserGroup', lazy='joined')
5763
5763
5764 # scope limited to repo, which requester have access to
5764 # scope limited to repo, which requester have access to
5765 scope_repo_id = Column(
5765 scope_repo_id = Column(
5766 'scope_repo_id', Integer(), ForeignKey('repositories.repo_id'),
5766 'scope_repo_id', Integer(), ForeignKey('repositories.repo_id'),
5767 nullable=True, unique=None, default=None)
5767 nullable=True, unique=None, default=None)
5768 repo = relationship('Repository', lazy='joined')
5768 repo = relationship('Repository', lazy='joined')
5769
5769
5770 # scope limited to repo group, which requester have access to
5770 # scope limited to repo group, which requester have access to
5771 scope_repo_group_id = Column(
5771 scope_repo_group_id = Column(
5772 'scope_repo_group_id', Integer(), ForeignKey('groups.group_id'),
5772 'scope_repo_group_id', Integer(), ForeignKey('groups.group_id'),
5773 nullable=True, unique=None, default=None)
5773 nullable=True, unique=None, default=None)
5774 repo_group = relationship('RepoGroup', lazy='joined')
5774 repo_group = relationship('RepoGroup', lazy='joined')
5775
5775
5776 @classmethod
5776 @classmethod
5777 def get_scope(cls, scope_type, scope_id):
5777 def get_scope(cls, scope_type, scope_id):
5778 if scope_type == 'repo':
5778 if scope_type == 'repo':
5779 return f'repo:{scope_id}'
5779 return f'repo:{scope_id}'
5780 elif scope_type == 'repo-group':
5780 elif scope_type == 'repo-group':
5781 return f'repo-group:{scope_id}'
5781 return f'repo-group:{scope_id}'
5782 elif scope_type == 'user':
5782 elif scope_type == 'user':
5783 return f'user:{scope_id}'
5783 return f'user:{scope_id}'
5784 elif scope_type == 'user-group':
5784 elif scope_type == 'user-group':
5785 return f'user-group:{scope_id}'
5785 return f'user-group:{scope_id}'
5786 else:
5786 else:
5787 return scope_type
5787 return scope_type
5788
5788
5789 @classmethod
5789 @classmethod
5790 def get_by_store_uid(cls, file_store_uid, safe=False):
5790 def get_by_store_uid(cls, file_store_uid, safe=False):
5791 if safe:
5791 if safe:
5792 return FileStore.query().filter(FileStore.file_uid == file_store_uid).first()
5792 return FileStore.query().filter(FileStore.file_uid == file_store_uid).first()
5793 else:
5793 else:
5794 return FileStore.query().filter(FileStore.file_uid == file_store_uid).scalar()
5794 return FileStore.query().filter(FileStore.file_uid == file_store_uid).scalar()
5795
5795
5796 @classmethod
5796 @classmethod
5797 def create(cls, file_uid, filename, file_hash, file_size, file_display_name='',
5797 def create(cls, file_uid, filename, file_hash, file_size, file_display_name='',
5798 file_description='', enabled=True, hidden=False, check_acl=True,
5798 file_description='', enabled=True, hidden=False, check_acl=True,
5799 user_id=None, scope_user_id=None, scope_repo_id=None, scope_repo_group_id=None):
5799 user_id=None, scope_user_id=None, scope_repo_id=None, scope_repo_group_id=None):
5800
5800
5801 store_entry = FileStore()
5801 store_entry = FileStore()
5802 store_entry.file_uid = file_uid
5802 store_entry.file_uid = file_uid
5803 store_entry.file_display_name = file_display_name
5803 store_entry.file_display_name = file_display_name
5804 store_entry.file_org_name = filename
5804 store_entry.file_org_name = filename
5805 store_entry.file_size = file_size
5805 store_entry.file_size = file_size
5806 store_entry.file_hash = file_hash
5806 store_entry.file_hash = file_hash
5807 store_entry.file_description = file_description
5807 store_entry.file_description = file_description
5808
5808
5809 store_entry.check_acl = check_acl
5809 store_entry.check_acl = check_acl
5810 store_entry.enabled = enabled
5810 store_entry.enabled = enabled
5811 store_entry.hidden = hidden
5811 store_entry.hidden = hidden
5812
5812
5813 store_entry.user_id = user_id
5813 store_entry.user_id = user_id
5814 store_entry.scope_user_id = scope_user_id
5814 store_entry.scope_user_id = scope_user_id
5815 store_entry.scope_repo_id = scope_repo_id
5815 store_entry.scope_repo_id = scope_repo_id
5816 store_entry.scope_repo_group_id = scope_repo_group_id
5816 store_entry.scope_repo_group_id = scope_repo_group_id
5817
5817
5818 return store_entry
5818 return store_entry
5819
5819
5820 @classmethod
5820 @classmethod
5821 def store_metadata(cls, file_store_id, args, commit=True):
5821 def store_metadata(cls, file_store_id, args, commit=True):
5822 file_store = FileStore.get(file_store_id)
5822 file_store = FileStore.get(file_store_id)
5823 if file_store is None:
5823 if file_store is None:
5824 return
5824 return
5825
5825
5826 for section, key, value, value_type in args:
5826 for section, key, value, value_type in args:
5827 has_key = FileStoreMetadata().query() \
5827 has_key = FileStoreMetadata().query() \
5828 .filter(FileStoreMetadata.file_store_id == file_store.file_store_id) \
5828 .filter(FileStoreMetadata.file_store_id == file_store.file_store_id) \
5829 .filter(FileStoreMetadata.file_store_meta_section == section) \
5829 .filter(FileStoreMetadata.file_store_meta_section == section) \
5830 .filter(FileStoreMetadata.file_store_meta_key == key) \
5830 .filter(FileStoreMetadata.file_store_meta_key == key) \
5831 .scalar()
5831 .scalar()
5832 if has_key:
5832 if has_key:
5833 msg = 'key `{}` already defined under section `{}` for this file.'\
5833 msg = 'key `{}` already defined under section `{}` for this file.'\
5834 .format(key, section)
5834 .format(key, section)
5835 raise ArtifactMetadataDuplicate(msg, err_section=section, err_key=key)
5835 raise ArtifactMetadataDuplicate(msg, err_section=section, err_key=key)
5836
5836
5837 # NOTE(marcink): raises ArtifactMetadataBadValueType
5837 # NOTE(marcink): raises ArtifactMetadataBadValueType
5838 FileStoreMetadata.valid_value_type(value_type)
5838 FileStoreMetadata.valid_value_type(value_type)
5839
5839
5840 meta_entry = FileStoreMetadata()
5840 meta_entry = FileStoreMetadata()
5841 meta_entry.file_store = file_store
5841 meta_entry.file_store = file_store
5842 meta_entry.file_store_meta_section = section
5842 meta_entry.file_store_meta_section = section
5843 meta_entry.file_store_meta_key = key
5843 meta_entry.file_store_meta_key = key
5844 meta_entry.file_store_meta_value_type = value_type
5844 meta_entry.file_store_meta_value_type = value_type
5845 meta_entry.file_store_meta_value = value
5845 meta_entry.file_store_meta_value = value
5846
5846
5847 Session().add(meta_entry)
5847 Session().add(meta_entry)
5848
5848
5849 try:
5849 try:
5850 if commit:
5850 if commit:
5851 Session().commit()
5851 Session().commit()
5852 except IntegrityError:
5852 except IntegrityError:
5853 Session().rollback()
5853 Session().rollback()
5854 raise ArtifactMetadataDuplicate('Duplicate section/key found for this file.')
5854 raise ArtifactMetadataDuplicate('Duplicate section/key found for this file.')
5855
5855
5856 @classmethod
5856 @classmethod
5857 def bump_access_counter(cls, file_uid, commit=True):
5857 def bump_access_counter(cls, file_uid, commit=True):
5858 FileStore().query()\
5858 FileStore().query()\
5859 .filter(FileStore.file_uid == file_uid)\
5859 .filter(FileStore.file_uid == file_uid)\
5860 .update({FileStore.accessed_count: (FileStore.accessed_count + 1),
5860 .update({FileStore.accessed_count: (FileStore.accessed_count + 1),
5861 FileStore.accessed_on: datetime.datetime.now()})
5861 FileStore.accessed_on: datetime.datetime.now()})
5862 if commit:
5862 if commit:
5863 Session().commit()
5863 Session().commit()
5864
5864
5865 def __json__(self):
5865 def __json__(self):
5866 data = {
5866 data = {
5867 'filename': self.file_display_name,
5867 'filename': self.file_display_name,
5868 'filename_org': self.file_org_name,
5868 'filename_org': self.file_org_name,
5869 'file_uid': self.file_uid,
5869 'file_uid': self.file_uid,
5870 'description': self.file_description,
5870 'description': self.file_description,
5871 'hidden': self.hidden,
5871 'hidden': self.hidden,
5872 'size': self.file_size,
5872 'size': self.file_size,
5873 'created_on': self.created_on,
5873 'created_on': self.created_on,
5874 'uploaded_by': self.upload_user.get_api_data(details='basic'),
5874 'uploaded_by': self.upload_user.get_api_data(details='basic'),
5875 'downloaded_times': self.accessed_count,
5875 'downloaded_times': self.accessed_count,
5876 'sha256': self.file_hash,
5876 'sha256': self.file_hash,
5877 'metadata': self.file_metadata,
5877 'metadata': self.file_metadata,
5878 }
5878 }
5879
5879
5880 return data
5880 return data
5881
5881
5882 def __repr__(self):
5882 def __repr__(self):
5883 return f'<FileStore({self.file_store_id})>'
5883 return f'<FileStore({self.file_store_id})>'
5884
5884
5885
5885
5886 class FileStoreMetadata(Base, BaseModel):
5886 class FileStoreMetadata(Base, BaseModel):
5887 __tablename__ = 'file_store_metadata'
5887 __tablename__ = 'file_store_metadata'
5888 __table_args__ = (
5888 __table_args__ = (
5889 UniqueConstraint('file_store_id', 'file_store_meta_section_hash', 'file_store_meta_key_hash'),
5889 UniqueConstraint('file_store_id', 'file_store_meta_section_hash', 'file_store_meta_key_hash'),
5890 Index('file_store_meta_section_idx', 'file_store_meta_section', mysql_length=255),
5890 Index('file_store_meta_section_idx', 'file_store_meta_section', mysql_length=255),
5891 Index('file_store_meta_key_idx', 'file_store_meta_key', mysql_length=255),
5891 Index('file_store_meta_key_idx', 'file_store_meta_key', mysql_length=255),
5892 base_table_args
5892 base_table_args
5893 )
5893 )
5894 SETTINGS_TYPES = {
5894 SETTINGS_TYPES = {
5895 'str': safe_str,
5895 'str': safe_str,
5896 'int': safe_int,
5896 'int': safe_int,
5897 'unicode': safe_str,
5897 'unicode': safe_str,
5898 'bool': str2bool,
5898 'bool': str2bool,
5899 'list': functools.partial(aslist, sep=',')
5899 'list': functools.partial(aslist, sep=',')
5900 }
5900 }
5901
5901
5902 file_store_meta_id = Column(
5902 file_store_meta_id = Column(
5903 "file_store_meta_id", Integer(), nullable=False, unique=True, default=None,
5903 "file_store_meta_id", Integer(), nullable=False, unique=True, default=None,
5904 primary_key=True)
5904 primary_key=True)
5905 _file_store_meta_section = Column(
5905 _file_store_meta_section = Column(
5906 "file_store_meta_section", UnicodeText().with_variant(UnicodeText(1024), 'mysql'),
5906 "file_store_meta_section", UnicodeText().with_variant(UnicodeText(1024), 'mysql'),
5907 nullable=True, unique=None, default=None)
5907 nullable=True, unique=None, default=None)
5908 _file_store_meta_section_hash = Column(
5908 _file_store_meta_section_hash = Column(
5909 "file_store_meta_section_hash", String(255),
5909 "file_store_meta_section_hash", String(255),
5910 nullable=True, unique=None, default=None)
5910 nullable=True, unique=None, default=None)
5911 _file_store_meta_key = Column(
5911 _file_store_meta_key = Column(
5912 "file_store_meta_key", UnicodeText().with_variant(UnicodeText(1024), 'mysql'),
5912 "file_store_meta_key", UnicodeText().with_variant(UnicodeText(1024), 'mysql'),
5913 nullable=True, unique=None, default=None)
5913 nullable=True, unique=None, default=None)
5914 _file_store_meta_key_hash = Column(
5914 _file_store_meta_key_hash = Column(
5915 "file_store_meta_key_hash", String(255), nullable=True, unique=None, default=None)
5915 "file_store_meta_key_hash", String(255), nullable=True, unique=None, default=None)
5916 _file_store_meta_value = Column(
5916 _file_store_meta_value = Column(
5917 "file_store_meta_value", UnicodeText().with_variant(UnicodeText(20480), 'mysql'),
5917 "file_store_meta_value", UnicodeText().with_variant(UnicodeText(20480), 'mysql'),
5918 nullable=True, unique=None, default=None)
5918 nullable=True, unique=None, default=None)
5919 _file_store_meta_value_type = Column(
5919 _file_store_meta_value_type = Column(
5920 "file_store_meta_value_type", String(255), nullable=True, unique=None,
5920 "file_store_meta_value_type", String(255), nullable=True, unique=None,
5921 default='unicode')
5921 default='unicode')
5922
5922
5923 file_store_id = Column(
5923 file_store_id = Column(
5924 'file_store_id', Integer(), ForeignKey('file_store.file_store_id'),
5924 'file_store_id', Integer(), ForeignKey('file_store.file_store_id'),
5925 nullable=True, unique=None, default=None)
5925 nullable=True, unique=None, default=None)
5926
5926
5927 file_store = relationship('FileStore', lazy='joined', viewonly=True)
5927 file_store = relationship('FileStore', lazy='joined', viewonly=True)
5928
5928
5929 @classmethod
5929 @classmethod
5930 def valid_value_type(cls, value):
5930 def valid_value_type(cls, value):
5931 if value.split('.')[0] not in cls.SETTINGS_TYPES:
5931 if value.split('.')[0] not in cls.SETTINGS_TYPES:
5932 raise ArtifactMetadataBadValueType(
5932 raise ArtifactMetadataBadValueType(
5933 'value_type must be one of %s got %s' % (cls.SETTINGS_TYPES.keys(), value))
5933 'value_type must be one of %s got %s' % (cls.SETTINGS_TYPES.keys(), value))
5934
5934
5935 @hybrid_property
5935 @hybrid_property
5936 def file_store_meta_section(self):
5936 def file_store_meta_section(self):
5937 return self._file_store_meta_section
5937 return self._file_store_meta_section
5938
5938
5939 @file_store_meta_section.setter
5939 @file_store_meta_section.setter
5940 def file_store_meta_section(self, value):
5940 def file_store_meta_section(self, value):
5941 self._file_store_meta_section = value
5941 self._file_store_meta_section = value
5942 self._file_store_meta_section_hash = _hash_key(value)
5942 self._file_store_meta_section_hash = _hash_key(value)
5943
5943
5944 @hybrid_property
5944 @hybrid_property
5945 def file_store_meta_key(self):
5945 def file_store_meta_key(self):
5946 return self._file_store_meta_key
5946 return self._file_store_meta_key
5947
5947
5948 @file_store_meta_key.setter
5948 @file_store_meta_key.setter
5949 def file_store_meta_key(self, value):
5949 def file_store_meta_key(self, value):
5950 self._file_store_meta_key = value
5950 self._file_store_meta_key = value
5951 self._file_store_meta_key_hash = _hash_key(value)
5951 self._file_store_meta_key_hash = _hash_key(value)
5952
5952
5953 @hybrid_property
5953 @hybrid_property
5954 def file_store_meta_value(self):
5954 def file_store_meta_value(self):
5955 val = self._file_store_meta_value
5955 val = self._file_store_meta_value
5956
5956
5957 if self._file_store_meta_value_type:
5957 if self._file_store_meta_value_type:
5958 # e.g unicode.encrypted == unicode
5958 # e.g unicode.encrypted == unicode
5959 _type = self._file_store_meta_value_type.split('.')[0]
5959 _type = self._file_store_meta_value_type.split('.')[0]
5960 # decode the encrypted value if it's encrypted field type
5960 # decode the encrypted value if it's encrypted field type
5961 if '.encrypted' in self._file_store_meta_value_type:
5961 if '.encrypted' in self._file_store_meta_value_type:
5962 cipher = EncryptedTextValue()
5962 cipher = EncryptedTextValue()
5963 val = safe_str(cipher.process_result_value(val, None))
5963 val = safe_str(cipher.process_result_value(val, None))
5964 # do final type conversion
5964 # do final type conversion
5965 converter = self.SETTINGS_TYPES.get(_type) or self.SETTINGS_TYPES['unicode']
5965 converter = self.SETTINGS_TYPES.get(_type) or self.SETTINGS_TYPES['unicode']
5966 val = converter(val)
5966 val = converter(val)
5967
5967
5968 return val
5968 return val
5969
5969
5970 @file_store_meta_value.setter
5970 @file_store_meta_value.setter
5971 def file_store_meta_value(self, val):
5971 def file_store_meta_value(self, val):
5972 val = safe_str(val)
5972 val = safe_str(val)
5973 # encode the encrypted value
5973 # encode the encrypted value
5974 if '.encrypted' in self.file_store_meta_value_type:
5974 if '.encrypted' in self.file_store_meta_value_type:
5975 cipher = EncryptedTextValue()
5975 cipher = EncryptedTextValue()
5976 val = safe_str(cipher.process_bind_param(val, None))
5976 val = safe_str(cipher.process_bind_param(val, None))
5977 self._file_store_meta_value = val
5977 self._file_store_meta_value = val
5978
5978
5979 @hybrid_property
5979 @hybrid_property
5980 def file_store_meta_value_type(self):
5980 def file_store_meta_value_type(self):
5981 return self._file_store_meta_value_type
5981 return self._file_store_meta_value_type
5982
5982
5983 @file_store_meta_value_type.setter
5983 @file_store_meta_value_type.setter
5984 def file_store_meta_value_type(self, val):
5984 def file_store_meta_value_type(self, val):
5985 # e.g unicode.encrypted
5985 # e.g unicode.encrypted
5986 self.valid_value_type(val)
5986 self.valid_value_type(val)
5987 self._file_store_meta_value_type = val
5987 self._file_store_meta_value_type = val
5988
5988
5989 def __json__(self):
5989 def __json__(self):
5990 data = {
5990 data = {
5991 'artifact': self.file_store.file_uid,
5991 'artifact': self.file_store.file_uid,
5992 'section': self.file_store_meta_section,
5992 'section': self.file_store_meta_section,
5993 'key': self.file_store_meta_key,
5993 'key': self.file_store_meta_key,
5994 'value': self.file_store_meta_value,
5994 'value': self.file_store_meta_value,
5995 }
5995 }
5996
5996
5997 return data
5997 return data
5998
5998
5999 def __repr__(self):
5999 def __repr__(self):
6000 return '<%s[%s]%s=>%s]>' % (self.cls_name, self.file_store_meta_section,
6000 return '<%s[%s]%s=>%s]>' % (self.cls_name, self.file_store_meta_section,
6001 self.file_store_meta_key, self.file_store_meta_value)
6001 self.file_store_meta_key, self.file_store_meta_value)
6002
6002
6003
6003
6004 class DbMigrateVersion(Base, BaseModel):
6004 class DbMigrateVersion(Base, BaseModel):
6005 __tablename__ = 'db_migrate_version'
6005 __tablename__ = 'db_migrate_version'
6006 __table_args__ = (
6006 __table_args__ = (
6007 base_table_args,
6007 base_table_args,
6008 )
6008 )
6009
6009
6010 repository_id = Column('repository_id', String(250), primary_key=True)
6010 repository_id = Column('repository_id', String(250), primary_key=True)
6011 repository_path = Column('repository_path', Text)
6011 repository_path = Column('repository_path', Text)
6012 version = Column('version', Integer)
6012 version = Column('version', Integer)
6013
6013
6014 @classmethod
6014 @classmethod
6015 def set_version(cls, version):
6015 def set_version(cls, version):
6016 """
6016 """
6017 Helper for forcing a different version, usually for debugging purposes via ishell.
6017 Helper for forcing a different version, usually for debugging purposes via ishell.
6018 """
6018 """
6019 ver = DbMigrateVersion.query().first()
6019 ver = DbMigrateVersion.query().first()
6020 ver.version = version
6020 ver.version = version
6021 Session().commit()
6021 Session().commit()
6022
6022
6023
6023
6024 class DbSession(Base, BaseModel):
6024 class DbSession(Base, BaseModel):
6025 __tablename__ = 'db_session'
6025 __tablename__ = 'db_session'
6026 __table_args__ = (
6026 __table_args__ = (
6027 base_table_args,
6027 base_table_args,
6028 )
6028 )
6029
6029
6030 def __repr__(self):
6030 def __repr__(self):
6031 return f'<DB:DbSession({self.id})>'
6031 return f'<DB:DbSession({self.id})>'
6032
6032
6033 id = Column('id', Integer())
6033 id = Column('id', Integer())
6034 namespace = Column('namespace', String(255), primary_key=True)
6034 namespace = Column('namespace', String(255), primary_key=True)
6035 accessed = Column('accessed', DateTime, nullable=False)
6035 accessed = Column('accessed', DateTime, nullable=False)
6036 created = Column('created', DateTime, nullable=False)
6036 created = Column('created', DateTime, nullable=False)
6037 data = Column('data', PickleType, nullable=False)
6037 data = Column('data', PickleType, nullable=False)
General Comments 0
You need to be logged in to leave comments. Login now